control flow

In programming, control flow refers to the order in which individual statements are executed or evaluated within a program.

By default, Python code executes sequentially, or from the top of the script to the bottom, line by line. However, you can alter this flow by using control flow statements, which include conditionals, loops, and branching statements. These statements let you make decisions, repeat tasks, and handle exceptions, making your code more dynamic and powerful.

Control flow statements in Python include if, elif, and else statements for conditional execution, for and while loops for iteration, and control statements like break, continue, and pass to alter loop behavior.

Additionally, exception handling statements like try, except, finally, and raise, allow you to manage errors gracefully while they can also help you contro the flow of your programs.

Example

Here’s an example that demonstrates basic control flow using an if statement:

Python
>>> age = 18
>>> if age >= 18:
...     print("You're an adult!")
... else:
...     print("You're not an adult yet!")
...
You're an adult!

In this example, the if statement checks whether the age is greater than or equal to 18 and prints a corresponding message. In this case, the condition is true, and its associated code block runs. The code under else doesn’t run. This is how you decide what code to run, depending on the condition’s result.

Tutorial

Conditional Statements in Python

In this step-by-step tutorial you'll learn how to work with conditional ("if") statements in Python. Master if-statements and see how to write complex decision making code in your programs.

basics python

For additional information on related topics, take a look at the following resources:


By Leodanis Pozo Ramos • Updated March 6, 2025 • Reviewed by Martin Breuss