Skip to content
Advertisement

I’m trying to print the largest number from the inputs that the user gives, but it’s printing the wrong number

Basically, I’m trying to build a code to get the largest number from the user’s inputs. This is my 1st time using a for loop and I’m pretty new to python. This is my code:

session_live = True
numbers = []
a = 0

def largest_num(arr, n):
    #Create a variable to hold the max number
    max = arr[0]

    #Using for loop for 1st time to check for largest number
    for i in range(1, n):
        if arr[i] > max:
            max = arr[i]

        #Returning max's value using return
        return max

while session_live:
    print("Tell us a number")
    num = int(input())

    numbers.insert(a, num)
    a += 1

    print("Continue? (Y/N)")
    confirm = input()


    if confirm == "Y":
        pass

    elif confirm == "N":
        session_live = False
        
        #Now I'm running the function
        arr = numbers
        n = len(arr)
        ans = largest_num(arr, n)
        print("Largest number is", ans)

    else:
        print(":/")
        session_live = False

When I try running my code this is what happens:

Tell us a number
9
Continue? (Y/N)
Y
Tell us a number
8
Continue? (Y/N)
Y
Tell us a number
10
Continue? (Y/N)
N
Largest number is 9

Any fixes?

Advertisement

Answer

So, first things first,

  • the use of max can be avoided, as it is a reserved keyword in python

And coming to your fix, you are comparing it with the value only once in the loop, and you are returning the number, the indentation is the key here. You will have to wait for the loop to complete its job then return the value.

  • There are many inbuilt methods to do the job, Here is your implementation (a bit modified)
session_live = True
numbers = []
a = 0

def largest_num(arr, n):
    #Create a variable to hold the max number

    max_number = arr[0]

    #Using for loop for 1st time to check for largest number
    for i in range(1, n):
        if arr[i] > max_number:
            max_number = arr[i]

    # --- The indentation matters
    #Returning max's value using return
    return max_number

while session_live:
    print("Tell us a number")
    num = int(input())

    numbers.insert(a, num)
    a += 1

    print("Continue? (Y/N)")
    confirm = input()


    if confirm == "Y":
        pass

    elif confirm == "N":
        session_live = False
        
        #Now I'm running the function
        arr = numbers
        n = len(arr)
        ans = largest_num(arr, n)
        print("Largest number is", ans)

    else:
        print(":/")
        session_live = False
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement