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)