As we start to want to make more complicated programs we will need to know more about control structures.  They control the flow of the program and determine the order in which things get done, or whether they get done at all.  We have already learned about one control structure - the for loop.

Control structures control a chunk of code called a block.  The first line of the control structure must end with a colon, and then the body of the structure must be indented to show it belongs together.

If you look at the examples below from loops, you can see how the indentation shows which parts of the code belong to which for statement.  The second example has a loop inside another loop.

If, Else, Elif Statements

If statements are one of the most common control structures. 

if I go to the shop:
    I will buy a new dress

I will only get a new dress if I go to the shop.

You can also include an else statement

if I go to the shop:
    I will buy a new dress
else:
    I will wear my old one

Elif is a short form of 'else if'.  So I can say

if I go to the shop:
    I will buy a new dress
elif I go to Marys:
    I will borrow her dress
elif I go to Sallys:
    we will make a dress
else:
    I will wear my old one

Dresses are not all that useful in computer programs, so we will go back to working with numbers and strings!  Here is an example of how we can use an if structure.  Try it out to see how it works.

Add in some elif statements in the code above  so that the following will print out:
  • If the user is less than 20  You are very young
  • If the user is over 20, but less than 40  You are getting older
  • If the user is between 40 and 60  You should think about getting a walking stick soon
  • If the user is over 60  Wow, you are almost an antique!

Logical Expressions in if statements

a == b Is a equal to b?
a != b Is a unequal to b?
a <= b Is a smaller or equal to b?  (For strings refers to alphabetical order)
a >= b Is a larger or equal to b?
a < b Is a smaller than b?
a > b Is a larger than b?
a is b Is a the same object as b?
a is not b Is a the not same object as b?