# Code clarification

Hi There, Fellow coders!
I need your help with the following problem

Q: 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. DESIRED OUTPUT: Invalid input
Maximum is 10
Minimum is 2

A:`largest = None smallest = None while True: num = input("Enter a number: ") if num == "done" : break try: num1 = int(num) except: print("Invalid input") continue if largest is None or num1 > largest: largest = num1 if smallest is None or num1 < smallest: smallest = num1 print("Maximum is", largest) print("Minimum is", smallest)`

MY OUTPUT: Invalid input
Maximum is None ← Wrong output
Minimum is 2

Please tell me in which part the error lies. Thanks in advance

Reformatted code:

``````largest = None
smallest = None
while True:
num = input("Enter a number: ")
if num == "done" :
break
try:
num1 = int(num)
except:
print("Invalid input")
continue
if largest is None or num1 > largest:
largest = num1
if smallest is None or num1 < smallest:
smallest = num1

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

I run your code and do not have any trouble. Is it possible you are entering the numbers with spaces? Try `strip`ping the result of your input (more details here) to handle this case:

``````num = input("Enter a number: ").strip()
``````

With a space included, calling `int()` on the value in `num` will cause it to error (a space is not able to be cast to type `int`). If this is done repeatedly, it is possible that no value will ever be assigned (and you will end will a `None` value). By using the `strip()` method, we remove any such spaces either before or after the input, effectively sanitizing it.

1 Like

Sure thing. Will try it.

The same is shown. Maybe a problem with the editor?

I ran your code here. Try running your test case and see what happens.

1 Like

Shouldn’t that be underneath the if statements?

1 Like

Thank you very much. I tried and its working. Editor’s the fault.

It seems to be working fine sir. I thought of it but in this case it’s above the statements. Thank you for your kind opinion sir.

I suppose it doesn’t really matter. Your way is certainly more readable, but it looks like the effect is the same. That’s probably how I would’ve written it, too.

1 Like