2.1.1 - The if statement

How do we tell if a player has beat the high score? How can we tell if he has run out of lives? How can we tell if she has the key required to open the locked door?

What we need is the if statement. The if statement is also known as a conditional statement. (You can use the term “conditional statement” when you want to impress everyone how smart you are.) The if statement allows a computer to make a decision. Is it hot outside? Has the spaceship reached the edge of the screen? Has too much money been withdrawn from the account? A program can test for these conditions with the if statement.

Lets see an example code:

>>> # Variables used in the example if statements 

>>> a = 4

>>> b = 5

>>> # Basic comparisons

>>> if a < b:

    print("a is less than b") 

>>> if a > b:

    print("a is greater than b") 


What do you believe the code will send to the screen(output)?

Since a is less than b, the first statement will print out if this code is run. If the variables a and b were both equal to 4, then neither of the two if statements above would print anything out. The number 4 is not greater than 4, so the if statement would fail.

What other operators can we use for comparing? Copy the following code and save it as basic_comparisons.py inside your working folder.