Branching using Conditional Statements and Loops in Python
Last updated
Last updated
This tutorial covers the following topics:
Branching with if
, else
and elif
Nested conditions and if
expressions
Iteration with while
loops
Iterating over containers with for
loops
Nested loops, break
and continue
statements
if
, else
and elif
One of the most powerful features of programming languages is branching: the ability to make decisions and execute a different set of statements based on whether one or more conditions are true.
if
statementIn Python, branching is implemented using the if
statement, which is written as follows:
The condition
can be a value, variable or expression. If the condition evaluates to True
, then the statements within the if
block are executed. Notice the four spaces before statement1
, statement2
, etc. The spaces inform Python that these statements are associated with the if
statement above. This technique of structuring code by adding spaces is called indentation.
Indentation: Python relies heavily on indentation (white space before a statement) to define code structure. This makes Python code easy to read and understand. You can run into problems if you don't use indentation properly. Indent your code by placing the cursor at the start of the line and pressing the
Tab
key once to add 4 spaces. PressingTab
again will indent the code further by 4 more spaces, and pressShift+Tab
will reduce the indentation by 4 spaces.
For example, let's write some code to check and print a message if a given number is even.
We use the modulus operator %
to calculate the remainder from the division of a_number
by 2
. Then, we use the comparison operator ==
check if the remainder is 0
, which tells us whether the number is even, i.e., divisible by 2.
Since 34
is divisible by 2
, the expression a_number % 2 == 0
evaluates to True
, so the print
statement under the if
statement is executed. Also, note that we are using the string format
method to include the number within the message.
Let's try the above again with an odd number.
In [3]:
In [4]:
As expected, since the condition another_number % 2 == 0
evaluates to False
, no message is printed.
else
statementWe may want to print a different message if the number is not even in the above example. This can be done by adding the else
statement. It is written as follows:
If condition
evaluates to True
, the statements in the if
block are executed. If it evaluates to False
, the statements in the else
block are executed.
In [5]:
In [6]:
In [7]:
In [8]:
Here's another example, which uses the in
operator to check membership within a tuple.
In [9]:
In [10]:
In [11]:
elif
statementPython also provides an elif
statement (short for "else if") to chain a series of conditional blocks. The conditions are evaluated one by one. For the first condition that evaluates to True
, the block of statements below it is executed. The remaining conditions and statements are not evaluated. So, in an if
, elif
, elif
... chain, at most one block of statements is executed, the one corresponding to the first condition that evaluates to True
.
In [12]:
In [13]:
In the above example, the first 3 conditions evaluate to False
, so none of the first 3 messages are printed. The fourth condition evaluates to True
, so the corresponding message is printed. The remaining conditions are skipped. Try changing the value of today
above and re-executing the cells to print all the different messages.
To verify that the remaining conditions are skipped, let us try another example.
In [14]:
In [15]:
Note that the message 15 is divisible by 5
is not printed because the condition a_number % 5 == 0
isn't evaluated, since the previous condition a_number % 3 == 0
evaluates to True
. This is the key difference between using a chain of if
, elif
, elif
... statements vs. a chain of if
statements, where each condition is evaluated independently.
In [16]:
if
, elif
, and else
togetherYou can also include an else
statement at the end of a chain of if
, elif
... statements. This code within the else
block is evaluated when none of the conditions hold true.
In [17]:
In [19]:
In [20]:
Note that conditions do not necessarily have to be booleans. In fact, a condition can be any value. The value is converted into a boolean automatically using the bool
operator. This means that falsy values like 0
, ''
, {}
, []
, etc. evaluate to False
and all other values evaluate to True
.
In [21]:
In [22]:
In [23]:
In [24]:
The code inside an if
block can also include an if
statement inside it. This pattern is called nesting
and is used to check for another condition after a particular condition holds true.
In [25]:
In [26]:
Notice how the print
statements are indented by 8 spaces to indicate that they are part of the inner if
/else
blocks.
Nested
if
,else
statements are often confusing to read and prone to human error. It's good to avoid nesting whenever possible, or limit the nesting to 1 or 2 levels.
if
conditional expressionA frequent use case of the if
statement involves testing a condition and setting a variable's value based on the condition.
Python provides a shorter syntax, which allows writing such conditions in a single line of code. It is known as a conditional expression, sometimes also referred to as a ternary operator. It has the following syntax:
It has the same behavior as the following if
-else
block:
Let's try it out for the example above.
In [28]:
In [29]:
The conditional expression highlights an essential distinction between statements and expressions in Python.
Statements: A statement is an instruction that can be executed. Every line of code we have written so far is a statement e.g. assigning a variable, calling a function, conditional statements using
if
,else
, andelif
, loops usingfor
andwhile
etc.Expressions: An expression is some code that evaluates to a value. Examples include values of different data types, arithmetic expressions, conditions, variables, function calls, conditional expressions, etc.
Most expressions can be executed as statements, but not all statements are expressions. For example, the regular if
statement is not an expression since it does not evaluate to a value. It merely performs some branching in the code. Similarly, loops and function definitions are not expressions (we'll learn more about these in later sections).
As a rule of thumb, an expression is anything that can appear on the right side of the assignment operator =
. You can use this as a test for checking whether something is an expression or not. You'll get a syntax error if you try to assign something that is not an expression.
In [30]:
In [31]:
pass
statementif
statements cannot be empty, there must be at least one statement in every if
and elif
block. You can use the pass
statement to do nothing and avoid getting an error.
In [33]:
In [34]:
while
loopsAnother powerful feature of programming languages, closely related to branching, is running one or more statements multiple times. This feature is often referred to as iteration on looping, and there are two ways to do this in Python: using while
loops and for
loops.
while
loops have the following syntax:
Statements in the code block under while
are executed repeatedly as long as the condition
evaluates to True
. Generally, one of the statements under while
makes some change to a variable that causes the condition to evaluate to False
after a certain number of iterations.
Let's try to calculate the factorial of 100
using a while
loop. The factorial of a number n
is the product (multiplication) of all the numbers from 1
to n
, i.e., 1*2*3*...*(n-2)*(n-1)*n
.
In [38]:
Here's how the above code works:
We initialize two variables, result
and, i
. result
will contain the final outcome. And i
is used to keep track of the next number to be multiplied with result
. Both are initialized to 1 (can you explain why?)
The condition i <= 100
holds true (since i
is initially 1
), so the while
block is executed.
The result
is updated to result * i
, i
is increased by 1
and it now has the value 2
.
At this point, the condition i <= 100
is evaluated again. Since it continues to hold true, result
is again updated to result * i
, and i
is increased to 3
.
This process is repeated till the condition becomes false, which happens when i
holds the value 101
. Once the condition evaluates to False
, the execution of the loop ends, and the print
statement below it is executed.
Can you see why result
contains the value of the factorial of 100 at the end? If not, try adding print
statements inside the while
block to print result
and i
in each iteration.
Iteration is a powerful technique because it gives computers a massive advantage over human beings in performing thousands or even millions of repetitive operations really fast. With just 4-5 lines of code, we were able to multiply 100 numbers almost instantly. The same code can be used to multiply a thousand numbers (just change the condition to
i <= 1000
) in a few seconds.
You can check how long a cell takes to execute by adding the magic command %%time
at the top of a cell. Try checking how long it takes to compute the factorial of 100
, 1000
, 10000
, 100000
, etc.
Here's another example that uses two while
loops to create an interesting pattern.
Suppose the condition in a while
loop always holds true. In that case, Python repeatedly executes the code within the loop forever, and the execution of the code never completes. This situation is called an infinite loop. It generally indicates that you've made a mistake in your code. For example, you may have provided the wrong condition or forgotten to update a variable within the loop, eventually falsifying the condition.
If your code is stuck in an infinite loop during execution, just press the "Stop" button on the toolbar (next to "Run") or select "Kernel > Interrupt" from the menu bar. This will interrupt the execution of the code. The following two cells both lead to infinite loops and need to be interrupted.
In [41]:
In [42]:
break
and continue
statementsYou can use the break
statement within the loop's body to immediately stop the execution and break out of the loop (even if the condition provided to while
still holds true).
In [43]:
As you can see above, the value of i
at the end of execution is 42. This example also shows how you can use an if
statement within a while
loop.
Sometimes you may not want to end the loop entirely, but simply skip the remaining statements in the loop and continue to the next loop. You can do this using the continue
statement.
In [44]:
In the example above, the statement result = result * i
inside the loop is skipped when i
is even, as indicated by the messages printed during execution.
Logging: The process of adding
for
loopsA for
loop is used for iterating or looping over sequences, i.e., lists, tuples, dictionaries, strings, and ranges. For loops have the following syntax:
The statements within the loop are executed once for each element in sequence
. Here's an example that prints all the element of a list.
In [46]:
Let's try using for
loops with some other data types.
In [47]:
In [48]:
In [49]:
Note that while using a dictionary with a for
loop, the iteration happens over the dictionary's keys. The key can be used within the loop to access the value. You can also iterate directly over the values using the .values
method or over key-value pairs using the .items
method.
In [50]:
In [51]:
Since a key-value pair is a tuple, we can also extract the key & value into separate variables.
In [52]:
range
and enumerate
The range
function is used to create a sequence of numbers that can be iterated over using a for
loop. It can be used in 3 ways:
range(n)
- Creates a sequence of numbers from 0
to n-1
range(a, b)
- Creates a sequence of numbers from a
to b-1
range(a, b, step)
- Creates a sequence of numbers from a
to b-1
with increments of step
Let's try it out.
In [53]:
In [54]:
In [55]:
break
, continue
and pass
statementsSimilar to while
loops, for
loops also support the break
and continue
statements. break
is used for breaking out of the loop and continue
is used for skipping ahead to the next iteration.
In [58]:
In [59]:
In [60]:
Like if
statements, for
loops cannot be empty, so you can use a pass
statement if you don't want to execute any statements inside the loop.
In [61]:
for
and while
loopsSimilar to conditional statements, loops can be nested inside other loops. This is useful for looping lists of lists, dictionaries etc.
In [62]:
With this, we conclude our discussion of branching and loops in Python.
Try answering the following questions to test your understanding of the topics covered in this notebook:
What is branching in programming languages?
What is the purpose of the if
statement in Python?
What is the syntax of the if
statement? Give an example.
What is indentation? Why is it used?
What is an indented block of statements?
How do you perform indentation in Python?
What happens if some code is not indented correctly?
What happens when the condition within the if
statement evaluates to True
? What happens if the condition evaluates for false
?
How do you check if a number is even?
What is the purpose of the else
statement in Python?
What is the syntax of the else
statement? Give an example.
Write a program that prints different messages based on whether a number is positive or negative.
Can the else
statement be used without an if
statement?
What is the purpose of the elif
statement in Python?
What is the syntax of the elif
statement? Give an example.
Write a program that prints different messages for different months of the year.
Write a program that uses if
, elif
, and else
statements together.
Can the elif
statement be used without an if
statement?
Can the elif
statement be used without an else
statement?
What is the difference between a chain of if
, elif
, elif
… statements and a chain of if
, if
, if
… statements? Give an example.
Can non-boolean conditions be used with if
statements? Give some examples.
What are nested conditional statements? How are they useful?
Give an example of nested conditional statements.
Why is it advisable to avoid nested conditional statements?
What is the shorthand if
conditional expression?
What is the syntax of the shorthand if
conditional expression? Give an example.
What is the difference between the shorthand if
expression and the regular if
statement?
What is a statement in Python?
What is an expression in Python?
What is the difference between statements and expressions?
Is every statement an expression? Give an example or counterexample.
Is every expression a statement? Give an example or counterexample.
What is the purpose of the pass statement in if
blocks?
What is iteration or looping in programming languages? Why is it useful?
What are the two ways for performing iteration in Python?
What is the purpose of the while
statement in Python?
What is the syntax of the white
statement in Python? Give an example.
Write a program to compute the sum of the numbers 1 to 100 using a while loop.
Repeat the above program for numbers up to 1000, 10000, and 100000. How long does it take each loop to complete?
What is an infinite loop?
What causes a program to enter an infinite loop?
How do you interrupt an infinite loop within Jupyter?
What is the purpose of the break
statement in Python?
Give an example of using a break
statement within a while loop.
What is the purpose of the continue
statement in Python?
Give an example of using the continue
statement within a while loop.
What is logging? How is it useful?
What is the purpose of the for
statement in Python?
What is the syntax of for
loops? Give an example.
How are for loops and while loops different?
How do you loop over a string? Give an example.
How do you loop over a list? Give an example.
How do you loop over a tuple? Give an example.
How do you loop over a dictionary? Give an example.
What is the purpose of the range
statement? Give an example.
What is the purpose of the enumerate
statement? Give an example.
How are the break
, continue
, and pass
statements used in for loops? Give examples.
Can loops be nested within other loops? How is nesting useful?
Give an example of a for loop nested within another for loop.
Give an example of a while loop nested within another while loop.
Give an example of a for loop nested within a while loop.
Give an example of a while loop nested within a for loop.