Abdullah Bilal Abdullah Bilal - 11 months ago 53
Python Question

How do I change a value of a variable using an if else statement?

I've been on it for days but nothing is helping. The value of smallest does not change no matter what i do. it does not happen with the value of largest although it uses almost the same line of code.

smallest = None
largest = None
while True:
num = raw_input("Enter a number: ")
if num == "done":
x = int(num)
if x < smallest:
smallest = x
elif x > largest:
largest = x
print"Invalid input"
print "Maximum is", largest
print "Minimum is", smallest


The problem is that you are, in both cases, comparing numbers to None in the first iteration. In Python 2, every number will come out as "greater" when compared to None, thus the code works for finding the maximum, but fails for finding the minimum.

BTW, in Python 3, the same would give you a TypeError.

To fix it, you can change your comparison to something like this, taking the None case into account:

if smallest is None or x < smallest: