largest = None
smallest = None
while True:
pick = input("Please Enter a number: ")
try:
#first look for user to click done then test to make sure input
#is an int
if pick == "done":
break
x = int(pick)
#test print statement
print("try: success")
except ValueError:
#test print statements
print("Invalid Input")
print("Except: Success")
print("largest:", largest)
print("smallest:", smallest)
continue
if largest == None:
largest = pick
#test print statement
print("1: success")
if smallest == None:
smallest = pick
#test print statement
print("2: success")
if pick > largest:
largest = pick
#test print statement
print("3: success")
if pick < smallest:
smallest = pick
#test print statement
print("4: success")
print("largest:", largest)
print("smallest:", smallest)
print("Maximum is", largest)
print("Minimum is", smallest)
I'm trying to repeatedly ask the user to enter numbers until they type done. While they enter numbers I have several if statements that will run to keep changing the smallest and largest variable. I also have entered a try/ except to only accept numbers.
I entered the numbers 7,2,bob,10, and 4. Everything was fine until I got to 10. When I entered 10 the smallest variable changed from 2 to 10. The variable smallest was at 2 but changed to 10 off of the fourth if statement (if pick < smallest). I know it only hit that statement because that is the only success print statement that printed. Please let me know where my fault in logic is. Thanks in advance!
You created an integer from the value
pickrefers to, but never used the converted value again, nor reassignedpick, sopickremained a string, not a number. Lexicographically,'10'is less than'2'.Your code will work as expected if you change:
to:
so all the values used after that point are
ints, and useintcomparison rules.As a side-note: When comparing to
None, useisandis not, rather than==and!=. It's part of the PEP 8 programming recommendations; in this case, and most cases, code will work just fine if you ignore it, but the code is slower, and risks misbehavior with types that claim to be equal to anything, even though nothing should be equal toNone.