Skip to main content

7.6) If... It Rains, Use An Umbrella (cont'd)


Another example:

a=3
if a==0:
	print "a is zero"
elif a>0:
	print "a is positive"
else:
	print "a is negative"
print "Done“

Write this in a script and execute it. Now change the value of a to test all the possibilities.

Up to now, you’ve learned that a script is executed line by line, so let’s see what actually happens when you encounter an if statement.

[advanced_iframe src="http://pythontutor.com/iframe-embed.html#code=a%3D3%0Aif+a%3D%3D0%3A%0A%09print+%22a+is+zero%22%0Aelif+a%3E0%3A%0A%09print+%22a+is+positive%22%0Aelse%3A%0A%09print+%22a+is+negative%22%0Aprint+%22Done%22&cumulative=false&heapPrimitives=false&drawParentPointers=false&textReferences=false&showOnlyOutputs=true&py=2&curInstr=0" securitykey="cdcd195854f0661ec0561aa6e33a487eadfbcbcc"]

Notice the red arrow next to the code. At step 2, we’re testing whether a is equal to zero, this is False, so at step 3, we skip line 3 and execute line 4 instead. Because this test returns True, we then execute line 5 at step 4. The else statement is only executed if neither the if or elif statements returned True. At step 5, we therefore skip the else statements (line 6 and 7) and go to line 8 instead.