'Python Input try and except scenario
I'm required to create an input with a loop and print out the largest and smallest number within the many user inputs which should all be floats. At the same time, there should be a try:/except: error message of "Invalid input" in case the user inputs anything else apart from the float or an ending loop message triggered by an input of "done".
My code below does not print the smallest digit. What could be the problem?
largest = None
smallest = None
while True:
sval = input("Enter a number:")
if num == "done": #Type 'done' to get the output
break
try:
fval = float(sval) #Convert input to float
#Get largest value
if largest is None:
largest = fval
elif fnum > largest:
largest = fval
#Get smallest value
elif smallest is None:
smallest = fval
elif fval < smallest:
smallest = fval
except:
#If the user input is not 'done' or a number
print("Invalid input")
continue
print("Largest value is",largest)
print("Smallest value is",smallest)
Solution 1:[1]
Instead of using elif in the smallest number case, use another set of if - elif.
This is because let's say you gave input of 5 then in the first iteration the value of largest is None, so the command will go into the first if statement and will assign the value of 5 to the largest, after this, it will skip all the elif below it.
Let's say you again provide an input of 6, this time the first elif condition will be executed and the largest variable will be assigned a valued of 6. Again it will skip all the elif below it.
So the smallest value is not getting updated in these cases. Hence, you will get the wrong answer.
Solution 2:[2]
It would help to know what values you are using for input. Also, your code is displaying funcky above so it is difficult to know if I am reading it properly.
With all that said, change "elif smallest is None:" to "if smallest is None:" In other words, change the elif to if when checking for smallest.
I believe your code works unless you start with the smallest value.
Solution 3:[3]
When you try to get the smallest value, then you are using 'elif' instead of 'if'.
#Get largest value
if largest is None:
largest = fval
elif fnum > largest:
largest = fval
#Get smallest value
elif smallest is None:
smallest = fval
elif fval < smallest:
smallest = fval
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | WinterSoldier |
| Solution 2 | Mark Johnson |
| Solution 3 |
