7 if Statements


The if statement is a conditional statement, it is used to control which parts of a program to run.  Take the simple example

if a==5:
    b = 1
    c = 2

The statement starts with if followed by a==5 which is a test condition, and the line ends with a : character.

In the test condition the == means if the variable a is equal to the value 5 then the test condition is True and it will run the lines of code that follow. However if a is not equal to 5 then then the test condition would be False and it would not run the following lines.

Note here that the lines that follow are indented with 4 spaces, they are both part of the same block and will be run together. As mentioned earlier the spaces are important and they tell the program that these lines are grouped together into the same block.

Test Condition

There are many different  test conditions  expressions which can be used in a conditional statement:

==    if you want to test if a variable is equal to another variable or number, for example a==0
!=      if you want to see if a variable does not equal another variable,  for example   a != -999
>       greater than
>=    greater than or equal
<       less than
<=    less than or equal
and  if the first part is true and the second part is true
or    if the  first part is true or the second part is true
True  means the if statement block will be always run
False means the if statement block will never be run
1      the same as True, means the if statement block will be always run
    the same as False, means the if statement block will never be run

For example

a = 4
b = 3
if a > b:

This will cause the green LED to flash because the a = 4 and is greater than b =3. It will flash only once.

The test condition expressions can be combined , like:

if (a<10 and b>20) or c!=5:
    print( 'the moons must be aligned')

if .. else

There are different forms of the if statement.  You can use an else:  after the if, like

if a==0:
   b= -1
   c= -2

Here if the test condition is true then the commands b=1 and c=2 are run the same as before, but if the test condition is not true then the block of code that follows the else: statement is run instead.

Note that the else: line starts at the same position as the if statement above, and the lines after the else: are indented to form a new block of code.

if .. elif .. else

There is a third type of if statement using elif . The elif is also followed by a test condition expression and is followed by a : character just like the if line

if a==0:
   max = -999 
elif a>0:
   max = a
   max = -a
print(a, max)

Here the statement starts with an if statement followed by an elif  line and then ends with an else line.

There can be one or more elif lines and the final else is optional, but if an else line is used it must come at the end after all the elif lines.