find the largest of n numbers using a user defined functions largest() in python

def largest(n, nums):
    # Initialize max_num variable to store the largest number found
    max_num = nums[0]
    # Iterate through the list of numbers
    for i in range(1,n):
        # Compare the current number with current max_num
        if nums[i] > max_num:
            # Update max_num if current number is greater than current max_num
            max_num = nums[i]
    # Return the largest number
    return max_num

# Prompt user to enter the number of elements
n = int(input("Enter the number of elements: "))
nums = []

# Iterate through n number of inputs
for i in range(n):
    # Prompt user to enter number
    num = int(input("Enter number: "))
    nums.append(num)

# call function largest 
print("Largest number is:", largest(n, nums))

In the above python program to find the largest of n numbers using a user defined functions largest() we have defined a user defined function largest(n, nums) which takes two arguments, first one is the number of elements n and second is a list nums of numbers. Inside the function, I have initialized a variable max_num to store the largest number found, which is the first element of the list of numbers nums[0]. Then I have used a for loop to iterate through the list of numbers, comparing each one with the current maximum number, if a larger number is found, it becomes the new maximum number. Finally, the function largest() returns the largest number that was found. I have used this function to find the largest number in the main program, where I have prompted the user to enter the number of elements and the numbers.

Leave a Comment