Python: Conditionals
Python Conditionals
1 Overview
📘 Conditionals in Python
In Python, conditionals are constructs that control the flow of program execution by evaluating Boolean expressions and determining which code blocks should be run based on whether conditions are true or false. Conditionals allow us to control the flow of code execution, enabling the program to choose between different paths depending on some situation and making it more flexible and dynamic.
2 Conditionals
Structure of Conditionals
- The primary decision-making tool is the “if” statement, which checks a given condition.
- Using “if-else”, the program can specify alternative code paths if the condition is false.
- “elif” allows chaining of multiple mutually exclusive branches, where each is tested in order.
2.1 Logical and Relational Operations
- Conditions are built using relational operators (such as <, >, ==) to compare values.
- Compound conditions use logical operators like “and”, “or”, and “not”, enabling more complex decision logic.
2.2 Truthiness and Flow Control
- Python evaluates condition expressions for “truthiness”, meaning any object can be tested for truth value: nonzero numbers, non-empty sequences, or objects evaluate as true, while zeros, empty sequences, or None evaluate as false.
- Indentation (not braces) defines the scope of each conditional block, ensuring only the chosen code sections execute.
2.3 Ternary or Conditional Expressions
- Python provides a compact conditional expression (ternary operator) in the form: `<expr1> if <condition> else <expr2>`, allowing assignment or inline decisions without formal control structures.
- Only the necessary branch of a conditional expression is evaluated, supporting short-circuiting.
2.4 Advanced Conditional Constructs
- In modern Python, the “match-case” statement allows pattern matching against values, similar to a switch statement in other languages.
Conditionals thus enable Python programs to react to dynamic situations by selectively executing code based on logic and conditions, forming the basis for decision-making and branching in software.
3 if statements
if [condition]:
indented code block
This line is also inside the
if block.This line is outside the
if block.
- If the condition is not met, the code inside it is not executed:
if block.
4 if-else statements
- Allow to execute one block of code if the condition is
True, and another block if the condition isFalse. - They never run together, it is just one or the other.
if [condition]:
code block
else:
code block
hi
- If the condition is met:
hi
5 Elif
- Chain multiple conditions.
- Execute the first block of code with a
Truecondition and ignore the rest.
if [condition]:
code block
elif [condition]:
code block
else:
code block
- What does this print?
- There must be an
ifbefore anelif. - Same for
else.
6 Nested conditionals
- We can nest conditions inside conditions for more complexity in decision-making.
- What does this print?
- The same conditions can be expressed in multiple ways:
- We could also write the code without nesting, although it is maybe a bit more difficult to understand:
7 Conditional variable assignation
- Set a value to a variable depending on a condition:
8 Ternary operator
- Shorter way to write if-else statements.
- Use them only if the code is simple.
- Same code as before but in a single line:
9 Best practices
Keep code blocks simple and focused, handling one specific task or condition.
Use parentheses for complex conditions to improve readability.
If needed, you can write multi-line code in Python by using the
\at the end of the line.
10 Example
- Website membership levels and restrictions.
- What does this print?
membership_level = "premium"
account_age_days = 45
num_posts_created = 12
# Check if user is allowed to create a post
if (membership_level == "free" and num_posts_created < 10) or \
(membership_level == "basic" and num_posts_created < 30) or \
(membership_level == "premium" and num_posts_created < 100) or \
(membership_level == "unlimited" or account_age_days >= 365):
print("You are allowed to create more posts.")
else:
print("You have reached your limit on the number of posts.")membership_level = "premium"
account_age_days = 45
num_posts_created = 12
# Check if user is allowed to create a post
if (membership_level == "free" and num_posts_created < 10) or \
(membership_level == "basic" and num_posts_created < 30) or \
(membership_level == "premium" and num_posts_created < 100) or \
(membership_level == "unlimited" or account_age_days >= 365):
print("You are allowed to create more posts.")
else:
print("You have reached your limit on the number of posts.")11 Exercises
11.1 Density calculator (to my ❤️ daughter Emma )
DensityCalculator without functions to calculate the density of a given object and return it. The density is calculated using the formula mass / volume. The user assumes that the density is given in kg/m3 as the mass is in kilogrames and the volume could be selected in different units (ml, m3, cl, mm3, cm3, dm3, l, hl).