A lot of times, programs need to make  decisions depending on a condition. It’s also often necessary to execute the same code for all items in a list, or until a condition is fulfilled. This means that any good program needs branches and loops in the flow of code (for example, in order to build a delay). It is like real life, right?

This post will show you how to write:

  • conditional statements with the if statement
  •  loops with for and while

The if statement

if statements are used to perform different computations or actions depending on whether a condition evaluates to true or false. The condition can be a comparison or an arithmetic expression.

In Python, the if statement looks like this:

if condition_1:
    statement_1()
elif condition_2:
    statement_2()
else:
    statement_3()

If the condition condition_1 is True, the statements in the block with statement_1() are executed. If not, condition_2 will be checked. If condition_2 evaluates to True, the block with statement_2() are executed. If condition_2 is False, the statements in the block with statement_3() are executed.

Let’s write a program which tells us what to wear depending on the outside temperature – shorts or pants? In order to do this, write a script named script.py with the following content:

#!/usr/bin/python  
temperature = float(raw_input('What is the temperature? '))
if temperature > 70:
    print('Wear shorts.')
else:
    print('Wear long pants.')
    print('Get some exercise outside.')

Now run the script in a console:

python script.py

Of course, you can name the script whatever you want – you just have to change how you call it from the console.

In order to deepen your understanding, try to understand the output and change some things in the if statements, as well as the code that gets executed when the conditions are different.

The for loop

We often need to process all the elements of a list or perform an operation over a series of numbers. The for statement is the right tool to go easily through various types of lists and ranges.

The syntax looks like this:

for variable in sequence:
    statement1()
    statement2()

This takes each item contained in the variable sequence and assigns it to the name variable. Afterwards, statement1() is executed, followed by statement2. Once that’s finished, the next item in sequence is assigned to the name variable and the whole process repeats. This continues until all the items in sequence have been processed.

Of course, this code would only work if sequence, statement1 and statement2 are all defined.

This is a bit easier to understand if we use an example:

>>> animals = ["cat", "dog", "cow"]
>>> for a in animals:
...     print(a)
... 
cat
dog
cow

The range function

The built-in function range iterates over a sequence of numbers. It generates lists of arithmetic progressions:

>>> range(5)
[0, 1, 2, 3, 4]

We can combine both, using range to produce a range of numbers which can let us access the items at those positions within the list. We’ll also make use of the function len, which returns the length of a given sequence. Here we’ll reuse our list from the previous code block, animals.

>>> animals = ["cat", "dog", "cow"]
>>> for i in range(len(animals)):
...     print(i, animals[i])
... 
(0, 'cat')
(1, 'dog')
(2, 'cow')

The while loop

Now to make the confusion complete let me introduce you to the while loop.

A while loop repeatedly executes a block of code as long as a given condition is true. The syntax is:

while expression():
    some_code()

expression() could be replaced by anything you want – a variable which, when converted to a Boolean value, becomes true or false, or a comparison of two things, or a function call that returns a value that can be evaluated as true or false. If the expression evaluates to True, all the indented code after the opening of the while loop is executed, and when the bottom is reached, the expression is evaluated again. This continues until the expression evaluates to False, or until a break statement is reached.

Note that a while loop might not ever run – if the initial expression evaluates to false, the code belonging to it will never be executed at all! On the other hand, be careful of while loops – if the expression – the so-called “guard condition” – doesn’t change within the body of the loop, then the condition will always be true and thus the code will continue to execute indefinitely. This might be what you want (for example in a process that reads the value of a sensor), but it might also not be what you want, so use while wisely 😉

Let’s try this out now. Write a script with the following content:

#!/usr/bin/python
count = 0
while count <= 5:
    print("The count is " + str(count))
    count += 1
print("Done!")

When this script is executed, we get the following output:

The count is 0
The count is 1
The count is 2
The count is 3
The count is 4
The count is 5
Done!

In this example, we used a comparison operator, <=, as well as the in-place addition operator, += and the str function. You can find more information about these in the further reading section below.

Remember: be careful with the while loop. As stated above, it might not stop. If this is what you want, great. If not, you will need your loops to end eventually. My recommendation is to use the while loop sparingly (it is better to use the for loop if you can), and make sure the condition in the while loop will become false at some point.

Now it’s your turn again. Try experimenting with if, for and while on your own and see what you can come up with!

Further resources

Advertisements