Branching and Iteration
A computer executes a program line by line from top to bottom. However, there are times when we want to execute a block of code multiple times or skip a block of code. This is where branching and iteration come in.
Strings
Before we go into control flow, let's look at more Python code first. As seen before, strings are a sequence of characters (letters, special characters, spaces, digits) enclosed in either quotation marks or single quotes.
Like with numbers, we can perform operations on strings. Adding strings together is called concatenation and it joins the strings together. We can also multiply strings by a number which repeats the string that many times.
# Creating a string
"Hello World"
'Hello World'
# String operations
print("Hello" + "World") # Prints "HelloWorld"
print("Hello" * 3) # Prints "HelloHelloHello"
# Order of operations still applies
print("Hello")
Input
The second way to interact with the outside world is to take input. In python you can use the input()
command to get an input from the console. You can also provide a string to input()
which will be printed to the console before the user inputs their value.
# Getting input from the user
input() # Waits for the user to input a value
inp = input("Enter a number: ") # Prints "Enter a number: " and waits for the user to input a value
# Printing the input
print(inp)
# Casting the input (Input is always given as a string)
inp = int(input("Enter a number: "))
print(inp + 1)
Branching
The first way to control the flow of a program is with conditionals. They allow you to execute a block of code only if a certain condition is met and so code can be skipped if the condition is not met.
Comparison and Logical Operators
Before we can use conditionals, we need to be able to compare values using comparison operators. These operators compare two values and return a boolean value (True or False). The comparison operators are:
Greater than: >
Less than: <
Greater than or equal to: >=
Less than or equal to: <=
Equal to: == (Note: This is not the same as the assignment operator =)
Not equal to: !=
Logical operators are used to combine multiple comparisons. The logical operators are:
And (both comparisons must be true): and
Or (at least one comparison must be true): or
Not (inverts the boolean value): not
Examples in Python:
# Comparison operators
print(1 > 2) # Prints False
print(1 < 2) # Prints True
print(1 >= 2) # Prints False
print(1 <= 2) # Prints True
print(1 == 2) # Prints False
print(1 != 2) # Prints True
# Logical operators
print(1 > 2 and 1 < 2) # Prints False
print(1 > 2 or 1 < 2) # Prints True
print(not 1 > 2) # Prints True
Conditionals
There are three types of branching in Python: if
, elif
, and else
. if
is used to execute a block of code if a condition is met. elif
is used to execute a block of code if a condition is met and the previous conditions were not met. else
is used to execute a block of code if none of the previous conditions were met.
The if
statement always comes first and is followed by zero or more elif
statements and an optional else
statement at the end. Only one block of code will be executed and it is always the first condition that is met so the order of elif
matters.
# Just an if statement
if 1 > 2:
print("This will not be printed")
# If and else
if 1 > 2:
print("This will not be printed")
else:
print("This will be printed")
# If, elif, and else
if 1 > 2:
print("This will not be printed")
elif 1 < 2:
print("This will be printed")
else:
print("This will not be printed")
# If, elif, and else with multiple conditions
if 1 > 2:
print("This will not be printed")
elif 1 < 2 and 2 > 3:
print("This will not be printed")
elif 1 < 2:
print("This will be printed")
else:
print("This will not be printed")
# You don't have to use else
if 1 > 2:
print("This will not be printed")
elif 1 < 2:
print("This will be printed")
# Body of a conditional must be indented and can be as many lines as you want
if 1 > 2:
print("This will not be printed")
print("This will not be printed")
print("This will not be printed")
The body of a condition must be indented in Python. Anything that is not indented is not part of the conditional.
Iteration
The second way to control the flow of a program is with loops. They allow you to run the same block of code multiple times.
While Loops
While loops execute a block of code repeatedly using a condition like with if statements. The block of code will be executed if the condition is true and once the block of code is executed, the condition is checked again. This process repeats until the condition is false.
# This while loop will run five times
# i will eventually be equal to 5 which makes the condition false
i = 0
while i < 5:
print(i)
i += 1
The output is...
0
1
2
3
4
This also means that if the condition is never false, the loop will run forever. This is called an infinite loop and is usually not what you want.
# This while loop will run forever
# i is never changed so it is always 0 which makes the condition true forever
i = 0
while i < 5:
print(i)
For Loops
For loops are used to iterate if you know how many times you want to iterate. They are similar to while loops but instead of using a condition, they use a counter.
# This for loop will run five times
for i in range(5): # The counter changes from 0 to 4
print(i)
The output is...
0
1
2
3
4
As you can see, the code does the same thing as the while loop earlier but the difference is the while loop does not need a counter but if you want to use one, you have to create it yourself. The for loop immediately gives you a counter that you can use and does not rely on a condition.
The range()
function is what controls the counter. If it is only given one argument, it will start at 0 and go up to but not including the argument.
If the range()
is given two arguments, it will start at the first argument and go up to but not including the second argument.
If the range()
is given three arguments, it will start at the first argument and go up to but not including the second argument and increment by the third argument. It is the step argument.
# The counter changes from 0 to 4
for i in range(5):
print(i) # The output is 0, 1, 2, 3, and 4
# The counter changes from 1 to 5
for i in range(1, 6):
print(i) # The output is 1, 2, 3, 4, and 5
# The counter changes from 1 to 5 and increments by 2
for i in range(1, 6, 2):
print(i) # The output is 1, 3, and 5
Break
The break
keyword can be used to exit a loop early. It can be used in both while and for loops.
# This while loop will run until i is equal to 3
i = 0
while i < 5:
print(i)
if i == 2: # If i is equal to 3, the loop will exit
break
i += 1
The output is...
0
1
2
Even though the loop was supposed to run till i was 5, it ended early because of the break.
What to Use
When deciding whether to use a while loop or a for loop, you should ask yourself if you know how many times you want to iterate. If you do, use a for loop. If you don't, use a while loop.