Python control flow: if statements, loops (for, while)
In Python, control flow refers to the order in which statements are executed in a program. Control flow statements allow you to make decisions and repeat actions based on certain conditions. The main control flow statements in Python are if statements and loops (for and while loops). Let's break down each of these:
if Statements:
An if statement is used to execute a block of code only if a certain condition is true. The basic syntax of an if statement is as follows:
Here’s an example:
In this example, since the condition x > 5 is true (10 is indeed greater than 5), the code inside the if block will be executed, and "x is greater than 5" will be printed.
for Loops:
A for loop is used to iterate over a sequence (such as a list, tuple, string, etc.) and execute a block of code for each item in the sequence. The basic syntax of a for loop is as follows:
Here’s an example:
In this example, the loop iterates through the fruits list and prints each fruit name.
while Loops:
A while loop is used to repeatedly execute a block of code as long as a certain condition remains true. The basic syntax of a while loop is as follows:
Here’s an example:
In this example, the loop will continue executing as long as the condition count < 5 remains true. It prints the value of count and increments it by 1 in each iteration.
Get Tharindu Dhananjaya’s stories in your inbox
Join Medium for free to get updates from this writer.
Both for and while loops can also use the break statement to exit the loop prematurely if a certain condition is met, and the continue statement to skip the current iteration and move to the next iteration.
Control flow statements are fundamental for building dynamic and interactive programs in Python. They allow you to control the logic and behavior of your code based on different conditions and sequences of data.









