Abdullah Bilal
Abdullah Bilal

Reputation: 393

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":
        break
    try:
        x = int(num)
        if x < smallest:
            smallest = x
        elif x > largest:
            largest = x
    except:
        print"Invalid input"
        continue
print "Maximum is", largest
print "Minimum is", smallest

Upvotes: 0

Views: 4030

Answers (2)

chepner
chepner

Reputation: 531055

First, (almost) never use a bare except statement. You will catch exceptions you can't or don't want to handle (like SystemExit). At the very least, use except Exception.

Second, your except block implies you only want to handle the ValueError that int(num) might raise. Catch that, and nothing else.

Third, the code that compares x to smallest and largest is independent of the ValueError handling, so move that out of the try block to after the try/except statement.

smallest = None
largest = None
num = "not done"    # Initialize num to avoid an explicit break
while num != "done":
    num = raw_input("Enter a number: ")
    try:
        x = int(num)
    except:
        print "Invalid input"
        continue

    if smallest is None:
        smallest = x
    if largest is None:
        largest = x

    if x < smallest:
        smallest = x
    elif x > largest:
        largest = x

print "Maximum is", largest
print "Minimum is", smallest

Note that you can't fold the None checks into the if/elif statement, because if the user only enters one number, you need to make sure that both smallest and largest are set to that number. After the first number is entered, there is no case where a single number will update both smallest and largest, so if/elif is valid.

Upvotes: 1

tobias_k
tobias_k

Reputation: 82899

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:

Upvotes: 4

Related Questions