I have the next exercise:
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.
And this is the code i have developed so far but i still can't get it to work properly. I accept any corrections needed. Thank you.
largest = None
smallest = None
while True:
value = input('Enter a Number: ')
if smallest is None:
smallest = value
elif smallest < value:
smallest = value
if largest is None:
largest = value
elif largest > value:
largest = value
if value == 'done':
break
try:
fvalue = float(value)
except:
print('Invalid input')
continue
print(f'Maximun is', max(largest))
print(f'Minimun is', min(smallest))
CodePudding user response:
Your code has several problems and some of those have been addressed in the comments.
The first thing your code should do is to check, if "done" was entered so that we can break the loop. Then you should try to convert the number to an integer (you used float
) and display an error message if there was a ValueError
. You have to convert the value before you do the comparison because otherwise the comparison will be lexicographically. Then you have to change the comparisons. You want to set a new number to smallest
if smallest
is bigger than the current value
, not the other way round. And the last thing: Using max
and min
on a single value doesn't make sense.
This gives us:
largest = None
smallest = None
while True:
value = input('Enter a Number: ')
if value == 'done':
break
try:
value = int(value)
except ValueError:
print('Invalid input')
continue
if smallest is None or smallest > value:
smallest = value
if largest is None or largest < value:
largest = value
print(f'Maximum is', largest)
print(f'Minimum is', smallest)
CodePudding user response:
I think you went in a wrong way when you've chosen to use a contraction like that with if/else
for that task it's better to use something like this
a = set()
while (inp := input('Enter a Number: ')) != 'done':
try:
if str(inp).isnumeric() != True:
raise
a.add(inp)
except Exception as ex:
print(f'your "{inp}" is not appropriate')
print(f'max == {max(a)}', f', min == {min(a)}')
set()
stores unique values only
it's easy to get max an min from set()
by built-in functions max()
and min()
so we just need not to allow to our set anything but numbers - here it's done by while
loop and try/except
inside it
it's easy to read and to change cuz it's without redundancy