How do I change a value of a variable using an if else statement?
<p>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.</p>

<pre><code>smallest = None
largest = None
while True:
    num = raw_input("Enter a number: ")
    if num == "done":
        break
    try:
        x = int(num)
        if x &lt; smallest:
            smallest = x
        elif x &gt; largest:
            largest = x
    except:
        print"Invalid input"
        continue
print "Maximum is", largest
print "Minimum is", smallest
</code></pre>

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

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

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

<pre><code>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 &lt; smallest:
        smallest = x
    elif x &gt; largest:
        largest = x

print "Maximum is", largest
print "Minimum is", smallest
</code></pre>

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

python python-2.7 python-3.x