Control Flow
Control flow is the order in which individual statements, instructions or function calls of an imperative program are executed or evaluated. The control flow of a Python program is regulated by conditional statements, loops, and function calls.
Conditional Statements
Conditional statements are used to perform different actions based on different conditions.
If Statement
An if statement is a conditional statement that runs or skips code based on whether a condition is True or False.
If-Else Statement
An if-else statement is a conditional statement that runs one block of code if the condition is True and another block of code if it is False.
| Python | |
|---|---|
If-Elif-Else Statement
An if-elif-else statement is a conditional statement that runs different code for different conditions.
| Python | |
|---|---|
Match Case Statement
Also known as switch-case in other languages. Python 3.10 introduced the match statement, which is similar to a switch statement in other languages. This is useful when you have multiple conditions to check. Instead of writing a very long if-elif-else statement, you can use the match statement.
| Python | |
|---|---|
Loops
Loops are used to iterate over a sequence or perform a task repeatedly.
For Loop
A for loop is used to iterate over a sequence (list, tuple, dictionary, set, or string).
| Python | |
|---|---|
Tip
When constructing your loops, try and name the variable a sensible name that helps you understand what the loop is doing. For example, if you were looping through a dataframe:
This makes it easy to read and understand.While Loop
A while loop is used to execute a block of code repeatedly as long as a condition is True.
Break and Continue Statements
break and continue are used to alter the flow of a loop.
Break Statement
A break statement is used to exit a loop when a certain condition is met.
| Python | |
|---|---|
Continue Statement
A continue statement is used to skip the current block and move to the next iteration of the loop.
| Python | |
|---|---|
Nested Loops
A nested loop is a loop inside a loop.
| Python | |
|---|---|
List Comprehension
Just to make you aware that list comprehension offers a shorter syntax when you want to create a new list based on the values of an existing list.
Warning
I tend not to recommend this. It is better to be more verbose and explicit in your code, because it is easier for everybody to read and understand. I strongly suggest keeping things as simple as possible. Code is read much more than it is written.