Selection
Ifs allow us to make selections in programming and to decide which direction we go in a program. It’s rather like waking up in the morning and thinking “Mmm, if its sunny today I will go to the beach otherwise I’ll stay at home and polish my shoes.” In this example or are taking an input (the weather) and checking it against something (Sunny) if the two match and therefore your statement is true then you do one thing otherwise you’ll do something else (the false branch). We could write this in pseudo-code like this:
if weather is sunny then (true) Go the beach else (false) Polish Shoes
Basic Python IFs
This example tests the players score to see if it is a win, draw or lose.
Or we can test a number to see if its negative.
x = int(input("Please enter an integer: ")); if x > 0: print ('Negative'); else: print ('Greater than or equal to zero');
Note the first line is using our input function again but this time it is prefixed by a int function – this is important. First, you need to be aware that because you have two open brackets you must have two close brackets in the right places! Secondly, the int function serves to turn the value given by the user into a proper integer number.
A Little Challenge: rewrite this program for yourselves but change it so it tests for positive and add appropriate comments for each line so your teacher can assess your understanding.
Nested IFs
Sometimes we need to ask more than one question in which case we use something call nested IFs. The following example (in pseudo code) tests for positive and negative numbers.
if num is less than zero then print negative else if num more than than zero then print positive else print it's zero !
Now rather than using else if in Python we have to use the reserved keyword elif
.
Another little challenge: try and rewrite the program above in proper Python code with comments.