Conditional Statements and Loops

Learn to make decisions in Python by applying the conditional statements if, elif, and else, and execute a piece of code repeatedly using for and while loops.

Conditional statements

To make decisions in our program, we use conditional statements. Python’s conditional statements are:

  • if

  • if-else

  • if-elif-else

The statement if is used by itself, but elif and else are always accompanied by a corresponding if statement.

The if statement

It’s the simplest conditional statement. Its syntax is:

if(condition):
  statement(s)
Syntax of an if statement

Note that the line following the if(condition): is indented. We can specify more indented statements after statement(s). In Python, statements indented the same amount after the colon (:) are part of the if statement.

Press + to interact
first_var = 10
second_var = -10
if first_var > 0:
print('The first number is greater than 0.')
print('This statement is not part of the if statement.')
# Indented statement is part of the if statement
if second_var > 0:
print('The second number is greater than 0.')
print('This statement is part of the if statement.')

The output demonstrates that line 5 is not part of the if statement. In contrast, line 9 is part of the corresponding if statement because it’s indented. These statements run only when the condition is True. The following is the flowchart of an if statement.

The if-else statement

An else statement is always accompanied by an if statement, i.e., if-else. Its syntax is:

if(condition):
  if_statement(s)
else:
  else_statement(s)
Syntax of an if-else statement

When the condition is True, if_statement(s) are run; otherwise, else_statement(s) are run. The following is the flowchart of an if-else statement:

The if-elif-else statement

The if-elif-else statement uses nested decisions to implement multiple conditions. The following is the flowchart of this statement:

  • If the expression under the if branch is True, statement(s) in the if branch is(are) run.

  • Otherwise, the expression under the elif branch is checked. If True, statement(s) in the elif branch is(are) run.

  • The statement(s) in the else branch is(are) run if both expressions are False.

The following code takes a number as input to illustrate the use of the aforementioned three conditional statements.

Press + to interact
# Converting the string input to a float data type
num_in = float(input())
if num_in > 0:
print('You have entered a positive number.')
elif num_in < 0:
print('You have entered a negative number.')
else:
print("You have entered a 0.")

Enter the input below

The program asks the user to input a number; the output indicates whether the user has entered a 0, positive, or negative number. The if-elif-else statements process the input to display the output.

Loops

Loops or iteration statements allow us to perform a task more than once. Python supports:

  • The for loop: This is used to iterate a statement or a group of statements a fixed number of times.

  • The while loop: This is used to iterate a statement or a group of statements until a condition remains True.

A loop can be part of another loop to form what’s known as a nested loop.

The for loop

A for loop iterates a task a fixed number of times. This loop has a definite beginning and an end. The input to the loop is a sequence or a variable that causes the loop to run a fixed number of times. The following is the syntax of a for loop.

for loop_variable in sequence:
  statement(s) to be executed in the loop
Syntax of a for loop

Note that the statement(s) in the body of the for loop is(are) indented. The length of the sequence determines the number of times the for loop runs. The statement(s) can use the loop_variable inside the body of the for loop. The flowchart of a for loop is given below:

The following code demonstrates the use of a for loop to display multiple items.

Press + to interact
technologies = ["Deep Learning", "Python", "TensorFlow", "Android"]
print(f'"The list: {technologies}',
"\nThe element of the list are:")
# The loop variable k iterates over the list (technologies). Therefore, a for loop is iterated four times.
for k in technologies:
print(" -", k)
# Usage of a for loop with the method range
print('Printing numbers using the method range:')
for x in range(2, 14, 3):
print(" -", x)

Line 11 uses the method range(2, 14, 3) to return a sequence to iterate over the loop.

Note: The number 14 is not part of the output in the code above. This is due to the indexing which excludes the last number in a sequence.

The continue and break statements are sometimes used inside the loops. The former skips all the statements of the loop following it, whereas the latter discontinues the execution of the loop. The following code uses both statements.

Press + to interact
students = ["Adam", "Alice", "Alex", "Julia", "Tom"]
for k in students:
if k == "Alex":
continue
print(k)
if k == "Julia":
break

The output excludes the name Alex because of the continue statement when the value of k equals Alex. Note that the print(k) statement isn’t part of the if statement because it’s not indented with the if statement. The code breaks the loop right after it has printed the name Julia.

The while loop

The while loop runs statements iteratively until its condition remains True. The syntax of the while loop is:

while (condition):
  statement(s) to be executed in the while loop
Syntax of a while loop

The following is the flowchart of the while loop.

The following program uses the while loop to print the sum of the first n natural numbers.

Press + to interact
# This program finds the sum of the first n natural numbers, where the value of n is input by the user
n = int(input()) # Converting string input to int
# Initialize variables sum and j (counter)
sum = 0
j = 1
while j <= n:
sum = sum + j
j = j+1 # Update the counter variable
print("First", n, "natural numbers add up to", sum)

Enter the input below

The program asks us to input a natural number. If we enter the number 4, we get a sum of 10. The while loop allows us to use the break, continue, and the conditional statements inside its body like a for loop.

Nested loops

A nested loop is a loop inside another loop. We use nested loops when, for each iteration of the outer loop, we repeat all iterations of the inner loop. For instance, to read each element of a matrix, we read the rows of this matrix using an outer loop, and for each row, we read all the columns using an inner loop.

A for loop can be nested inside another for loop or a while loop. Similarly, a while loop can be nested inside another while loop or a for loop. The following is a flowchart of a nested loop:

This flowchart shows all the iterations of the inner loop for one iteration of the outer loop. If the outer loop runs nn times, and the inner loop runs for mm times, the total number of iterations of a nested loop would be mnmn. The following code snippet implements nested for loops.

Press + to interact
a = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
for i in range(len(a)):
for j in range(len(a[i])):
# The print() function ends with a newline. To print without a newline,
# we use the parameter 'end' with any character of our choice. Here, we use space.
print(a[i][j], end=' ')
print() # Prints a new line

This code nests a for loop inside another for loop to print the elements of a matrix. Nested loops are computationally expensive; therefore, we should avoid them wherever possible.

Conclusion

In this lesson, we’ve applied the conditional if, elif, and else statements to make decisions in Python. Furthermore, we’ve learned to execute a piece of code repeatedly using for and while loops.