Control Flow in Python

In Python, lines of code are executed sequentially, in the order you create them. However, you can change this flow of execution by using conditional statements and loops. We introduce both of these in this lesson.

If Statements

The if statement tests whether a condition is True and if so, executes the indented block of code that follows.

a = 4
b = 5

if a < b:
	print('a is less than b')

If statements can be paired with an optional elif statement to test whether another condition is True.

a = 6
b = 5

if a < b:
	print('a is less than b')
elif a < b:
	print('a is not less than b')

The else statement executes if all the preceding if-statements are False. This is also optional, although using an if-else combination is a frequent practice.

a = 5
b = 5

if a < b:
	print('a is less than b')
elif a < b:
	print('a is not less than b')
else:
	print('a must be equal to b')

Multiple Conditional Statements

Multiple condition statements can be strung together by using the boolean operators and and or.

Parentheses can be used to create even more intricate conditional testing. The conditionals inside parentheses are evaluated first.

a = 2
b = 3

if a > 0 and a < 10:
	print('a is a positive number that\'s less than 10')
	
if (a > b or a > 0) and b * 4 > 10:
	print('success')

Nesting Conditional Statements

Condition statements can be nested inside other condition statements. These are useful when you need to test additional condition statements if the first condition is true.

age = 123

if age > 18:
	if age > 60:
		print('This is an old adult')
	elif age > 40:
		print('This is a middle-age adult')
	else:
		print('This is a young adult')
else:
	print('This is not an adult')

The Pass Instruction

The pass statement is used as a placeholder for code that has not yet been implemented.

Python requires the inner block of code for if-statements, loops, and etc. have instructions in order for the script to run without an error.

However, there may be times when you haven’t written all of your program’s code but still want to run the script. The pass statement will allow you to do that.

if 1 < 88:
	pass

def connect_to_db():
	pass

for n in range(1,11):
	pass

Building Loops

The while loop keeps repeating a block of code until a condition is no longer true.

Add an else-statement at the end of a while loop to execute a block of code once the the loop finishes. The else-statement will always execute.

i = 4
while i >= 1:
	print(i)
	i -= 1

i = 4
while i >= 1:
	print(i)
	i -= 1
else:
	print('i is now less than 1')

Be careful when creating while loops. Python will generate an infinite loop error if the condition never becomes false.

A for loop is used to iterate over each element in a sequence of values such as a range of numbers, elements in a list, or the characters in a string.

names = ['Toad', 'Badger', 'Ratty', 'Mole']
for name in names:
	print(name)

for n in names[0]:     
	print(n)	 # prints the letters for Toad on new lines

The range() function creates a sequence of numbers that can be iterated over with a for loop. The sequence starts at 0 and iterates by 1 as the default behavior.

The function requires an integer as input. Passing a 6 into the function will create the numbers 0-5.

for n in range(6):
	print(n)

range() also accepts start and end parameters to give you more control over the sequencing. When using range() this way, the syntax is: range(start, stop, step)

for n in range(10, 21, 2):
	print(n)

Sometimes you may wish to stop a loop before it completes all its iterations. The break statement allows you to do just that.

names = ['Toad', 'Badger', 'Ratty', 'Mole']
for name in names:
	if name == 'Badger':
		print(name)
		break

If you have loops inside of loops, the break statement only breaks out of its parent loop.

A continue statement is similar to a break statement but instead of stopping the loop, continue stops the current iteration and continues with the next iteration in the loop.

names = ['Toad', 'Badger', 'Ratty', 'Mole']
for name in names:
	if name == 'Badger':
		continue
	print(name)

As with while loops, the else statement can be used at the end of for loops to execute a block of code once the loop is finished.

names = ['Toad', 'Badger', 'Ratty', 'Mole']
for name in names:
	if name == 'Badger':
		continue
	print(name)
else:
	print('Done with looping')

Summary

In this post we looked at the flow of operations in Python by using conditional statements and by creating loops. In future lessons we investigate lists and dictionaries.

Check out the Python reading list to learn more.