Level I

Play with conditionals

Did you notice that in the “logic expressions” section we were always saying “If this, then that…”. This is exactly what you would do in your everyday life! “If we practice with Code for a Change, we will develop wonderful programming skills”. This can be also translated to a programming language. 

Now you will learn something that is called if, else and elif statements or conditionals.

IF

The If statement has the following structure:

if condition is True:
    do something 

This means that booleans (True or False) are also implicit here.

For example:

The following example gives an indentation error, “IndentationError: expected an indented block”. Indentation is the empty space at the beginning of a line, which can be achieved using spaces or the ‘tab’ key.

From these examples we can learn a couple of things:

  1. When we expect an action to occur given a condition, what we are saying is that this condition exists ( or that it’s True). In real life, if it’s raining, we will use an umbrella, right? We say this under the assumption that the rain is real. Same here. This means that if we explicitly say “If True, do something” the action will be performed. However, we won’t always use the boolean True itself, instead, we will type something that is True, such as “ 2>1”. 
  2. Python requires indentations to indicate a block of code. Until now you’ve learned how to use variables, but this is the first time you see several lines of code forming a “block”. 

ELSE

Following the previous example about the weather forecast from the “IF” section:

if it’s warm outside:
    wear a T-shirt. #plan A
else: 
    wear a jumper. #plan B

Do you see why we need an “else” section now? “else” is equivalent to having a plan B.

This statement will only occur when nothing is happening in the first statement “if” (plan A).

ELIF

This statement is useful when you have several conditions (option A, B, C…). In the previous examples we have introduced only one (e.g. “if warm”). The code works in such a way that, firstly, it tries option A, if True, it works, if not, it jumps to the next option, and so on. 

See the following example in °C (the following values have been extracted from the NSH www.nsh.uk):