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:
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;
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 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:
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:
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:
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:

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:
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:
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:
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:
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:
The output is:
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:
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.
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:
If we run this program with an input of “0”, we get:
If we run this program as shown below, we get:
If we did not have the exception handling code and instead had the program as:
and used the same inputs as above, we will experience the below interactions:
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.

Join our mailing list

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

Copyright @ Kodeclik 2023. All rights reserved.