Python Primer — Statements

Marius Safta
5 min readMay 2, 2019

--

Hello World,

The first part of this primer series dealt with Python data types. This post covers the if, for and while statements.

If/Else/Elif statement

If statements allow the execution of a block of code if a condition is met. Another block of code can be specified to be executed if the same condition is not met.

Remember that Python doesn’t use curly braces to delimit blocks of code, but code indentation. Code is much easier to read through, but a bit of extra caution is required when writing it.

a = 2if a % 2 == 0:    print(‘a is even’)else:    print(‘a is odd’)>> a is even

In the above example, the a % 2 condition is evaluated inside the if statement.

Setting a with the value 2 will make the condition True, which will execute the print(‘a is even’) branch.

Otherwise, the print(‘a is odd’) branch is executed, the condition evaluation being false.

There can be multiple evaluation branches, with the elif statement.

age = 33if age < 10:    print(“You are a child”)elif age < 18:    print(“You are a teenager”)elif age < 65:    print(“You are an adult”)else:    print(“You are retired”)>> You are an adult

The condition age < 10 is evaluated first. If that is true, “You are a child” is displayed.

If this first condition is false, the condition in the first elif statement, age < 18, is evaluated. If true, “You are a teenager” is displayed.

If the condition in the first elif is false, the next elif condition is evaluated. If age < 65 is true, “You are an adult” is displayed.

Finally, if none of the conditions are true, the code in the else block is executed and “You are retired” is displayed.

In the Jupyter notebook you can execute the code for different values of the age variable and test each branch.

For loop

The for loop iterates over a sequence. With it we can go through all the characters of a string, or the items of a list, or the first n integer numbers.

Iterating over a string

s = “Hello World”for letter in s:    print(letter)>>HelloWorld

With the for loop, we go through every character in the s string. On each iteration, the character value is put inside the letter variable, which we print to the screen. When the for loop is completed, every letter will have been printed to the screen.

Iterating over a list, set or tuple

l = [1,4,7,9,11,45,879,34435]for item in l:    print(item)>> 1479114587934435

Just like with strings, we go through every element in the list, keep its value in the item variable and print that every iteration.

We can do much more than just printing the value every iteration. For instance, let’s check the value first with an if statement and only print the even values in the list.

for item in l:    if item % 2 == 0:        print(item)>> 4

There is a single even value in the list.

Using for with sets is the same, the list is just converted to a set first in the below example:

s = set(l)for item in s:    if item % 2 == 0:        print(item)>> 4

And the same if a tuple is defined:

t = (‘Monday’, ‘Tuesday’, ‘Wednesday’, ‘Thursday’, ‘Friday’)for work_day in t:    print(work_day)>> MondayTuesdayWednesdayThursdayFriday

Iterating over integer sequences

Sometimes iteration is required over a sequence of integer numbers. For example, let’s iterate over and display the 10 digits. Iteration over a sequence of integer is done using range().

for x in range(10):    print(x)>>0123456789

Range yields a sequence of integer starting from 0 (remember Python is 0 indexed) up until, but not including the integer parameter inside range().

Iterating through a string with range is also possible, using the integers as the character indexes. Let’s print all vowels of a string.

s = “Hello World”for i in range(0,len(s)):    if s[i] in (“a”, “e”, “i”, “o”, “u”):        print(s[i])>>eoo

First we move through the range between 0 and the length of the string. For each character position, we check if that character is in a vowel tuple we constructed. If it is, the condition is true and we print the letter.

While loop

The While statement executes a block of code as long as the condition it holds remains true. To get a better understanding, let’s print the 10 digits like in the for example above.

x = 0while x < 10:    print(x)    x = x + 1>> 0123456789

Since we want to stop after printing 9, the condition is x < 10. Each iteration we increment x by 1 so we can print the next digit. Once x is 10, the condition is false and the loop stops.

An else statement can be added at the end. Its block will execute when the while loop stops.

x = 0while x < 10:    print(x)    x = x + 1else:    print(“All done”)>> 0123456789All done

To interrupt the current iteration of the loop and continue straight with the next one, the continue keyword is used. In the above example, let’s say we want to skip printing 5.

x = 0while x < 10:    if x == 5:        x = x + 1        continue    print(x)    x = x + 1else:    print(“All done”)>>012346789All done

The loop can be entirely stopped, by using the break keyword. If we replace continue with break in the above example, the loop stop when reaching break.

x = 0while x < 10:    if x == 5:        x = x + 1        break    print(x)    x = x + 1else:    print(“All done”)>> 01234

One thing to keep in mind about while loops is the danger of infinite loops. It is imperative the condition inside the while statement must be false at some point, otherwise the code will execute forever.

Below is an example of an infinite loop.

if True:    print(“Forever”)

Conclusion

This post was a quick rundown of Python statement. The repository containing accompanying Jupyter notebooks is: https://github.com/clujsoai/python

Next we’ll tackle functions, methods and objects. We’ll be using a lot of libraries in the future, so it’s important to have a basic understanding of how these work.

Your opinions, feedback or (constructive) criticism are welcomed in discussions below or at @mariussafta

Join our Facebook and Meetup groups and keep an eye out for discussions and future meetups.

--

--