简体   繁体   中英

largest and smallest number using input while loop python

This is my try to write a program that repeatedly prompts a user for integer numbers until the user enters done . Once done is entered, print out the largest and smallest of the numbers. If the user enters anything other than a valid number catch it with a try/except and put out an appropriate message and ignore the number. Enter 7 , 2 , bob , 10 and 4 and match the output below. But it's false. I need some help can someone explain my fault.

largest = 0
smallest = 0



while True:
    num = input("Enter a number: ")
    if num =="done": break
    try:
           fnum = float(num)
    except:
        print("Invalid input")
        continue

    if largest == 0 or num >= largest: largest = num
    else: largest= largest
    if smallest == 0 or num <= smallest: smallest = num
    else: smallest= smallest

print("Maximum is", largest)
print("Minimum is", smallest)

Instead, why don't you a list to store the values, then you can use the min and max methods:

nums = []

while True:
    num = input("Enter a number: ")
    if num == "done" : break
    try:
        fnum = float(num)

    except:
        print("Invalid input")
        continue

    nums.append(fnum)

largest = max(nums)
smallest = min(nums)

print("Maximum is", largest)
print("Minimum is", smallest)

You should be using fnum in those if statements, not num .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM