Kodeclik Logo

Our Programs

Learn More

Schedule

Kodeclik Blog

Control Structures in Python

A control structure is something that affects the flow of control in a Python program. Typically Python programs are executed from the first line to the last line. Consider the following program:

a = 20
b = 10
c = a + b
print("The result of addition is: ", c)

The above program has 4 lines which are executed from line 1 to line 4, in that order. If we run this program, we will get;

The result of addition is:  30

Control structures are basically ways to alter this simple, sequential, flow of execution allowing us to skip statements, return and re-execute statements, or implement more complex constructs. Let us review them one by one next.

Python control structures

Python if-else statements

If-else statements are a basic type of control structure in Python. THey allow you to skip over lines of code and execute specific code segments under specific conditions. For instance, we can update the above program to say:

a = 20
b = 10
c = a + b
print("The result of addition is: ", c)

# If-else construct
if c > 30:
    print("The result is greater than 30.")
else:
    print("The result is less than or equal to 30.")

In this updated program, after the arithmetic operation, an if-else construct is used to check the result and print a message based on the condition. This demonstrates how if-else constructs can be used to control the flow of a program in Python.

If we run this program, we will obtain:

The result of addition is:  30
The result is less than or equal to 30.

Note that the print line “The result is greater than 30” is skipped which is what is meant by altering the flow of the program. Even though this print line appears before the other print line, it is skipped.

Python nested if-else statements

Let us further update the program to have if-else constructs nested inside our if-else statement:

a = 20
b = 10
c = a + b
print("The result of addition is: ", c)

# Nested if-else construct
if c > 30:
    print("The result is greater than 30.")
else:
    if c == 30:
        print("The result is exactly 30.")
    else:
        print("The result is less than 30.")

Note that in the above program, under the “else” part (when we have determined that c is either less than or equal to 30), we further check if the number is equal to 30 and print different messages based on whether that condition is true or false.

The output is:

The result of addition is:  30
The result is exactly 30.

Python nested if-else in both if and else statements

Here's a Python program with an if-else construct nested inside both the if clause and the else clause of a main if-else construct:

x = 50

# Main if-else construct
if x > 0:
    # Nested if-else construct inside the if clause
    if x % 2 == 0:
        print("x is positive and even.")
    else:
        print("x is positive and odd.")
else:
    # Nested if-else construct inside the else clause
    if x < 0:
        print("x is negative.")
    else:
        print("x is zero.")

This program checks the value of x and prints a message based on the following conditions: If x is positive, it checks further whether x is even or odd and prints a corresponding message. If x is not positive, it checks whether x is negative or zero and prints the corresponding message.

If you run this program, you will get:

x is positive and even.

In this manner you can develop very complex webs of conditionals reflecting the logic you would like your program to follow.

Python if-elif-else

A different type of nested conditions is featured in the Python if-elif-else construct. We can view this construct as having additional “if” checks (after the first “if” fails) before the main “else” clause. These checks are called “elifs”, i.e., “else ifs”.

Here is a situation where we will need this:

month = 2  # February
year = 2023

if month == 2:
    if (year % 4 == 0 and year % 100 != 0) or (year % 400 == 0):
        print("Number of days is 29")
    else:
        print("Number of days is 28")
elif month in (4, 6, 9, 11):
    print("Number of days is 30")
elif month in (1, 3, 5, 7, 8, 10, 12):
    print("Number of days is 31")
else:
    print("Invalid month")

In this program, the if-elif-else construct is used to determine the number of days in the given month. The program checks if the month is February, and if so, it further checks if it's a leap year to determine the number of days. The elif clauses check specific other months to decide whether to output a 30 or a 31. Finally, if all conditions fail, this means that we must have given an invalid input and thus the program prints an “invalid month” message.

The output (for the given inputs) is:

Number of days is 28

Thus far we have seen conditional statements, including if, elif, and else, which allow the execution of code blocks based on certain conditions. There are other control structures such as loops and exception handling. Loops enable the repetition of code blocks. Exception handling is also a crucial control structure that allows the graceful handling of errors in a program.

For loops in Python

The simplest type of loop in Python is the for loop that uses the range() function in the for loop to iterate over a range of numbers and perform some operation for each number. Consider:

for number in range(1, 6):
  print(number)

The output is:

1
2
3
4
5

In this program, the range() function is used to generate a sequence of numbers from 1 to 5 (even though the argument to range() is 6, that is considered one more than the upper bound for the loop) and the for loop is used to iterate over this sequence. For each iteration, the current number in the sequence is assigned to the variable "number", and then the "print" function is used to print the number. The loop continues until all the numbers in the range have been printed.

While loops in Python

A while loop is a different way to repeat a certain set of statements. However, instead of repeating statements for a fixed number of times we repeat statements while a condition is met or satisfied. Some programs are natural to write in terms of while loops. To illustrate this idea, let us rewrite the above program to use while loops:

number = 1

# Use a while loop to iterate over a range of numbers
while number < 6:
    print(number)
    number += 1

In this program, a while loop is used to iterate over a range of numbers from 1 to 5. The variable "number" is initialized to 1, and the while loop continues to execute as long as "number" is less than 6. Within the loop, each number is printed, and then the "number" is incremented by 1. The loop continues until "number" is no longer less than 6. Thus after printing 5 (when number=5), number is incremented to 6 and then when it tries to loop again, the while condition is not satisfied, and thus the program execution falls out of the loop.

Exception handling in Python

Exception handling is a complicated subject but we provide one example here to whet your appetite.

try:
  x = int(input("Please enter a number: "))
  inverse = 1 / x
except ValueError:
      print("You did not enter a valid number.")
except ZeroDivisionError:
      print("You cannot divide by zero.")
else:
      print("The inverse of", x, "is", inverse)
finally:
      print("This is always executed, regardless of whether 
      an exception was raised or not.")

Note that there is a “try” block. The try block contains the actual program you desire to execute. Everything outside the try block denote exceptions, i.e., what to do in case something goes wrong. Without these exception blocks, your program will exit with an error condition. However, with these exception blocks, your program will exit gracefully.

Thus exception handling should be used whenever there is a possibility that there might be runtime errors in your program.

In this program, the try block is used to execute the normal part of the code that may raise an exception. The except block is used to catch and handle specific exceptions, altering the control flow based on the type of exception raised. The else block is executed if no exceptions are raised, and the finally block is always executed, regardless of whether an exception was raised or not.

For the things that can go wrong in the above program, our exceptions check for the user entering an invalid input (e.g., a textual string instead of a number) or a valid number but inappropriate to the problem (e.g., zero).

If we run this program with an input of 10, we get:

Please enter a number: 10
The inverse of 10 is 0.1
This is always executed, regardless of 
whether an exception was raised or not.

If we run this program with an input of “0”, we get:

Please enter a number: 0
You cannot divide by zero.
This is always executed, regardless of 
whether an exception was raised or not.

If we run this program as shown below, we get:

Please enter a number: Kodeclik 
You did not enter a valid number.
This is always executed, regardless of 
whether an exception was raised or not.

If we did not have the exception handling code and instead had the program as:

x = int(input("Please enter a number: "))
inverse = 1 / x
print("The inverse of", x, "is", inverse)

and used the same inputs as above, we will experience the below interactions:

Please enter a number: 10
The inverse of 10 is 0.1

Please enter a number: 0
Traceback (most recent call last):
  File "main.py", line 2, in <module>
    inverse = 1 / x
ZeroDivisionError: division by zero

Please enter a number: Kodeclik
Traceback (most recent call last):
  File "main.py", line 1, in <module>
    x = int(input("Please enter a number: "))
ValueError: invalid literal for int() with base 10: 'Kodeclik'

In other words, for the second two cases, the program throws an error which is not caught by exception handling and thus the program executes gracefully.

This might not sound like a big deal but imagine if you had some code after the given segment that you definitely wish to execute. Once an error like the above happens, the program will irrevocably stop. With exception handling, you would have handled the error and gracefully moved on to the remaining piece of code to be executed.

If you liked learning about control structures in Python, learn about Python enumerate!

Interested in more things Python? Checkout our post on Python queues. Also see our blogpost on Python's enumerate() capability. Also if you like Python+math content, see our blogpost on Magic Squares. Finally, master the Python print function!

Want to learn Python with us? Sign up for 1:1 or small group classes.

Kodeclik sidebar newsletter

Join our mailing list

Subscribe to get updates about our classes, camps, coupons, and more.

About

Kodeclik is an online coding academy for kids and teens to learn real world programming. Kids are introduced to coding in a fun and exciting way and are challeged to higher levels with engaging, high quality content.

Copyright @ Kodeclik 2024. All rights reserved.