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:
>>> 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.
Related Resources
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.
For additional information on related topics, take a look at the following resources:
- Python for Loops: The Pythonic Way (Tutorial)
- Python while Loops: Repeating Tasks Conditionally (Tutorial)
- How Can You Emulate Do-While Loops in Python? (Tutorial)
- Python Exceptions: An Introduction (Tutorial)
- Conditional Statements in Python (if/elif/else) (Course)
- Python Conditional Statements (Quiz)
- For Loops in Python (Definite Iteration) (Course)
- Python "for" Loops: The Pythonic Way (Quiz)
- Mastering While Loops (Course)
- Python while Loops: Repeating Tasks Conditionally (Quiz)
- Introduction to Python Exceptions (Course)
- Raising and Handling Python Exceptions (Course)
- Python Exceptions: An Introduction (Quiz)