Ever wanted to execute a piece of code only if some condition is true? Ever desired of executing a piece of code over and over again, automatically?
What you're willing for, is controlling the flow of execution of a program and this is all what this chapter is about. In this chapter, we'll learn how to execute code based on some condition using the
else statements. Moreover, we'll see how to execute a given piece of code over and over again using the
To execute a piece of code upon the fulfillment of a given condition, we use the
Here's the syntax of the
if condition: # code to execute if condition is True pass
First comes the
if keyword and then the condition that must evaluate to
True in order for the following block of code to be executed.
The first part of an
if statement, i.e. the line containing the
if keyword, is called the header of
if. The block of code following the
if statement is called the body of
if statement is called a conditional statement. Conditional statements are one application of Boolean values.
In the case of
if, when a given value is
if's body executes, however if it's
False, then the body is ignored.
Let's consider a very simple example.
Suppose we want to print
"Don't forget the umbrella" if it's a rainy day today. A variable, specifically a Boolean variable, named
is_rainy_day can be defined to specify whether or not it is a rainy day today.
If it's equal to
True, then it's a rainy day; otherwise it's not a rainy day.
Based on the value of this variable, we can output the given string
"Don't forget the umbrella", using the
if statement, as shown below:
if is_rainy_day: print("Don't forget the umbrella")
This type of execution of a block of code is known as conditional execution, since a condition governs the execution of the code.
Note that this example is not completely fictitious. It can be part of a weather application that informs us when it's a rainy day in our respective city, and suggests us to go out with an umbrella.
if statements are extremely useful in practical level, day-to-day, applications.
Let's consider another example.
As we shall see in the next chapter, we could use comparison operators in Python to compare two values together and output a Boolean value.
One of them is the equality operator, denoted as
== (double equals sign).
It compares two values together for equality. If both the values are equal to one another, it returns
5 == 5
6 == 5
True == True
'Hello' == 'Hello'
'Hello' == 'hello'
Now, let's incorporate this into our example.
Suppose our program asks a user to enter his/her gender.
'M' is for male, and
'F' is for female. To deduce what the user entered, we can use an
if statement, checking whether the value input is equal to
'M' or not, and then act accordingly:
gender = input("What's your gender? M for male, and F for female.") if gender == 'M': print("You're a male programmer!")
Here first we save the input sent by the user in the variable
gender, and then check whether it's equal to
'M'. If it is, a message is printed saying that you're a male programmer.
The use cases of
if are endless — it's not something we would use very rarely — rather it's a highly common statement used in nearly every kind of program. In the chapters following, we'll be using the
if statement a lot, so make sure you understand this really well.
When we want to execute a piece of code upon the fulfillment of a given condition, we use
if. However, what if we want to execute a piece of code when that condition isn't fulfilled?
This is where the
else statement comes in.
Below shown is the syntax of
else in Python:
if condition: # code to execute if condition is True else: # code to execute if condition is False
else statement is not a standalone statement. It's a continuation of a preceding
Explaining the syntax shown above, first comes the
else keyword and then its block of code. Note that the
else keywords here are at the same level of indentation because they are in the same block of code i.e the main script.
This will always be the case for contiguous
if...else statements. It's only anything within their blocks that goes at the next level of indentation. Failing to do so results in syntax errors.
Let's extend our previous program to print another message if the user enters something other than
gender is equal
'M', we print
"You're a male programmer.", as before. However, if
gender is not equal to
'M', in that case we print
"You're not a male programmer.".
Once you start coding practical-level programs, you'll notice that when an
if statement is used, an
else statement is also required, in most of the cases. We'll consider many such cases in the Python Control Flow — Conditional Statements chapter.
Often times, we might want to check for another condition when one fails; and maybe even more conditions when all of the previous ones fail.
This can be achieved using the
if condition1: # code to execute if condition1 is True elif condition2: # code to execute if condition1 is False # and condition2 is True
Let's start by first understanding what does
The word 'elif' comes from the words 'else if'. Here's how we would use it in a sentence:
'If this is true, then do this; else if that is true, then do that'.
The word 'else if' serves to denote another condition to check for when a previous condition fails. However, if the previous condition gets fulfilled, then there is no reason to evaluate the condition denoted by 'else if'.
In Python, the word 'else if' is shortened down to 'elif', which is a reserved keyword.
Now, let's consider a quick example using
Suppose we want to show, to the user, the rating for a particular item they are inspecting in an online store. The rating is represented by the store's application as an integer between 1-3.
1 stands for 'Not Good', 2 stands for 'Average', and 3 stands for 'Good'.
We have to write some Python code such that, given a rating integer, it prints the corresponding rating text, as is described above.
The following code is where to begin. Here we assume that the rating is provided to us in the form of a variable
rating = 2
So, how to solve this problem?
Well, we need to check for just two cases, after which we know we are left with only one case. In other words, we need to use an
elif, and an
rating = 2 if rating == 1: print('Not Good') elif rating == 2: print('Average') else: print('Good')
Here's how the code works:
First it's checked whether
rating is equal to
1. If it is, the text 'Not Good' is printed. Otherwise, it's then checked whether
rating is equal to
2. If it is, the text 'Average' is printed. If none of these conditions are fulfilled, the text 'Good' is printed.
In this case, since
2, we'd get the following output:
Looping, or iteration, is the key to computer automation. It is when a computer executes some piece of code over and over again until some termination point is reached.
In Python, we have two statements that enable iteration:
while. In this section, we shall explore
for on the outskirts, before moving over to
while in the next section.
for loop is meant to iterate over a sequence of values. Recall any sequence types from the Python Data Types chapter? Strings and lists are one of many sequence types in Python.
The for loop can be used to iterate over these types of values.
Here's the general syntax of Python's
for item in sequence: # code to execute repeatedly, # for each item in sequence
It all starts by the
for keyword. Then comes the name of a variable to hold each item of
sequence during each iteration. This is followed by the
in keyword and lastly the sequence to iterate over.
The body of the
for loop represents code that'll be executed for each item in the given sequence.
Now, it's time to understand how all this works together.
Let's suppose that we want to go over the list
[1, 3, 5] and print each number. We would write the following code to accomplish this:
nums = [1, 3, 5] for num in nums: print(num)
Here's how this code works:
- When the
forloop begins, the first item of the list
numsis put inside the variable
num. This variable is just like any other variable in Python, and thereby, is accessible within the loop's body. The loop's body gets executed for the first time, and prints
- The loop's body completes and execution shifts back to the header of the loop. Now, the second item of the list
numsis put inside the variable
num, passing execution back to the body of the loop.
- On this second iteration,
print(num)gets executed and as a result
- The loop's body completes, once more, and so execution shifts back to the header of the loop. Now the variable
numis assigned the third item of
nums, before passing execution to the body of the loop.
- On this third iteration,
print(num)gets executed, and consequently
- Execution comes back to the loop's header, where this time it's noted that the list
numshas been exhausted i.e all its elements have been iterated over. As a result, the
forloop exits and execution shifts out of the loop, to the next statement after the whole loop.
This is how
for works under the hood. It keeps on iterating until the end of the sequence is reached.
We know that a string is also a sequence data type. Specifically, it's a sequence of characters. Let's see how Python dissects a string when used in the
msg = 'Hello' for char in msg: print(char)
As expected, each iteration of the loop deals with each character of the string
for is quite an interesting thing, and in fact, a common concern of many computer algorithms implemented in Python. We'll discover this in detail in the Python Control Flow unit.
Another way to iterate in Python is using the
It behaves a bit differently than
for, with a different syntax; nonetheless, it's still very easy to get the hang of just like
Below shown is the syntax of
while condition: # code to execute while condition is True
while loop's body keeps on executing as long as the given condition remains
True. It only terminates when the given condition becomes
while loop resembles English language particularly well — 'while this condition is true, keep on doing this...'
Once execution enters the
while loop, it can only get out of there if the value of the condition put in the loop's header becomes equal to
False during the execution of the loop.
Let's take a very simple example.
We'll print the first 5 non-negative integers using
while. The idea is that we'll begin at
0 and keep on iterating until the number becomes
6, at which point our loop stops execution.
num = 0 # keep iterating while num is lesser than 5 while num < 5: print(num) num += 1
num is set to
0 — the number at which we wish to start our sequence of numbers.
Then comes the
while loop. The condition here is
num < 5 which merely means that continue execution if
num is lesser than
In the first iteration,
num = 0 is indeed lesser than
5, and so
0 is printed. After this,
num is incremented by
1 which updates it to
The second iteration begins.
num < 5 is evaluated and it returns
num = 1 is lesser than
5. This goes on until we reach
At this point, the condition
num < 5 is evaluated. It returns
False, and likewise execution jumps out of the
What we get altogether is the following output:
Notice line 4 in the code above. It's crucial to the behavior and termination of the
while loop. If we remove it,
num would always remain equal to
0, and therefore
num < 5 would always evaluate to
True, leading to what's known as an infinite loop — a loop that never ends!
Infinite loops are commonly witnessed as beginners construct
while loops in Python — even the pros out there can end up writing infinite loops — since setting them can involve a lot of details, and where there are details, there are errors.
Debugging infinite loops is a painful task especially if the loop works around many values in a complicated manner. We'll learn more about debugging later on in this course.