Week 1 - Section 2 - Controlling the flow v1

In this second section we will start to learn how to control the flow of the algorithm using the if statement 

Chapter 2.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?

# Equal
a = 5
b = 5
if a == b: # Remember that comparison is made using ==
     print ("a is equal to b")

# Not Equal
a = "Alice"
b = "Bob"
if a != b: # The exclamation mark ! stand for not
     print ("a is equal to b")