Содержание:
- Python Programming: Module 1 – Conditional Statements
Python Programming: Module 1 – Conditional Statements
if, else, elif | Make Decisions in Python
🔷 Boolean Type (bool)
Booleans represent truth values: True or False. They are often produced by comparison operators:
==(equal),!=(not equal)>(greater),<(less)>=(greater or equal),<=(less or equal)
Logical operators: and, or, not.
True is equivalent to 1, False to 0 (can be used in arithmetic).
💡 Open example
print(True + True) # 2 print(True * 10) # 10 print(False + 5) # 5 |
Interesting fact: bool is a subclass of int — True and False are actually 1 and 0.
⚖️ Comparison Operators
Python supports the following comparison operators:
| Operator | Description | Example |
|---|---|---|
== | Equal to | x == 5 |
!= | Not equal to | x != 5 |
> | Greater than | x > 3 |
< | Less than | x < 3 |
>= | Greater than or equal | x >= 5 |
<= | Less than or equal | x <= 5 |
💡 Open example
# ASSIGNMENT – gives a value age = 25 # COMPARISON – checks equality if age == 25: print("You are 25") # WRONG! This assigns, not compares # if age = 25: # SyntaxError! # print("This won't work") |
Key takeaways: = is for assignment, == is for comparison. Mixing them up causes errors.
Interesting fact: In Python, == compares values, while is compares identity (whether two variables point to the same object).
🧠 Logical Operators
📌 Operator and
A and B is True if both A and B are True. In all other cases — False.
| A | B | A and B |
|---|---|---|
| False | False | False |
| False | True | False |
| True | False | False |
| True | True | True |
💡 Open example
age = int(input("age? ")) grade = int(input("grade? ")) print("Access granted: ", age >= 12 and grade >= 7) |
Key takeaway: and = "both must be true". Useful for checking multiple requirements.
📌 Operator or
A or B is False if both A and B are False. In all other cases — True.
| A | B | A or B |
|---|---|---|
| False | False | False |
| False | True | True |
| True | False | True |
| True | True | True |
💡 Open example
city = "Moscow" print("Access granted:", city == "Moscow" or city == "Ufa") |
Key takeaway: or = "at least one must be true". Useful for checking multiple valid options.
📌 Operator not
not A has the opposite value of A.
| A | not A |
|---|---|
| False | True |
| True | False |
💡 Open example
age = 8 print("Access granted:", not (age < 12)) |
Key takeaway: not = "opposite of". Use carefully to avoid confusion.
📌 Combining Logical Operators
Precedence: not (highest), and, or (lowest). Use parentheses for clarity.
💡 Open example
age = int(input()) grade = int(input()) city = input() if age >= 12 and grade >= 7 and (city == "Moscow" or city == "Ufa"): print("Access granted.") else: print("Access denied.") |
📌 Common Mistakes with Logical Operators
💡 Open example
# WRONG – always True if x > 1 or x < 100: print("In range") # CORRECT if x > 1 and x < 100: print("In range") |
💡 Open example
# WRONG if age >= 7 and <= 9: print("Child") # CORRECT if age >= 7 and age <= 9: print("Child") # BETTER – chained comparison if 7 <= age <= 9: print("Child") |
Interesting fact: Chained comparisons like a < b < c are a unique Python feature — many languages don't support this!
🔀 The if Statement
Programs must make decisions based on data — this is called branching. The if statement executes a block of code only if the condition is True.
Syntax:
if condition: # code block – executed if condition is True |
💡 Open example
number = 5 if number > 0: print("The number is positive") |
Key points:
- Colon
:after the condition. - Indented block (4 spaces).
- Block executes only if condition is
True.
💡 Open example
print("What programming language are we learning?") answer = input() if answer == "Python": print("Correct! We are learning Python =)") print("Python is a great language!") |
Example run:
What programming language are we learning? Python Correct! We are learning Python =) Python is a great language!
The indented block executes only when the condition is true.
↔️ The else Statement
else provides an alternative path when the condition is False.
Syntax:
if condition: # code if True else: # code if False |
💡 Open example
number = -3 if number > 0: print("Positive") else: print("Negative or zero") |
Key takeaway: else is the "otherwise" of programming.
💡 Open example
print("What programming language are we learning?") answer = input() if answer == "Python": print("Correct! We are learning Python =)") else: print("Not quite! We are learning Python.") |
Example runs:
What programming language are we learning? Python Correct! We are learning Python =) What programming language are we learning? Java Not quite! We are learning Python.
Key takeaway: if/else handles two cases. Every input leads to one of the two paths.
🔗 The elif Statement
elif (else if) allows checking multiple conditions in sequence. The first True condition wins.
Syntax:
if condition1: # code if condition1 is True elif condition2: # code if condition2 is True elif condition3: # code if condition3 is True else: # code if none are True |
💡 Open example
number = int(input()) if number > 0: print("Positive") elif number < 0: print("Negative") else: print("Zero") |
Key takeaways:
elifhandles multiple specific cases.- Order matters — first
Truewins.
💡 Open example
grade = int(input("Enter score: ")) if grade >= 90: print("5 - Excellent") elif grade >= 80: print("4 - Good") elif grade >= 70: print("3 - Satisfactory") elif grade >= 60: print("2 - Poor") else: print("1 - Fail") |
Example run:
Enter score: 85 4 - Good
Key takeaways:
elifchains are great for grading, categorisation, etc.- Order conditions from most specific to most general.
📌 Cascaded vs Nested Conditionals
Cascaded (better):
if grade >= 90: print("5") elif grade >= 80: print("4") elif grade >= 70: print("3") else: print("1") |
Nested (worse):
if grade >= 90: print("5") else: if grade >= 80: print("4") else: if grade >= 70: print("3") else: print("1") |
Key takeaway: Use elif instead of nested if/else. Keep your code flat and readable.
⛓️ Chained Comparisons
Comparison operators in Python can be chained together.
💡 Open example
age = int(input()) if 3 <= age <= 6: print('You are a child') |
The code checks whether the value of the variable age is within the range of 3 to 6.
if a == b == c: print('equal numbers') else: print('the numbers are not equal') |
The code checks whether all three variables a, b, and c are equal to each other.
❓ Ternary Operator
Python has a conditional expression that is an analogue of the ternary operator.
💡 Open example
student_1 = 5 student_2 = 2 excellent = "first student" if student_1 > student_2 else "second student" print(excellent) # first student |
🔍 The in Operator
The in operator checks if a single character is in a string.
💡 Open example
s = input() if s == 's' or s == 't' or s == 'u' or s == 'd' or s == 'y': print('YES') # With 'in' - clean and concise if len(s) == 1 and s in 'study': print('YES') |
Key takeaway: in is great for checking against multiple values. We'll explore it more with lists.
📊 Minimum and Maximum
Using if/else, you can find the maximum and minimum among variables.
💡 Open example
x, y = int(input()), int(input()) max_ = float('-inf') if x > y: max_ = x else: max_ = y print(max_) |
💡 Open example
x, y = int(input()), int(input()) max_ = float('-inf') min_ = float('inf') if x > y: max_ = x min_ = y else: max_ = y min_ = x print(f"max = {max_} min = {min_}") |
🎯 The match Statement (Python 3.10+)
match is an alternative to long if/elif chains. The underscore _ is the default case.
💡 Open example
command = "start" match command: case "start": print("Starting work") case "stop": print("Stopping") case _: print("Unknown command") |
💡 Open example
match op:
case "ADD":
print("Sum = 2")
case "MUL":
print("Multiplication")
case _:
print("Unknown operation") |
📐 If Statement and Equations
Integers x, y are given. Calculate the value of the function:
f(x,y) = | -2 * x * y |, if (x > 0, y < 0) or (x < 0, y > 0) (x + y)², if (x > 0, y > 0) or (x < 0, y < 0) x, if y = 0 y, if x = 0
💡 Open example
x = int(input("x = ")) y = int(input("y = ")) if (x > 0 and y < 0) or (x < 0 and y > 0): f = abs(-2 * x * y) elif (x > 0 and y > 0) or (x < 0 and y < 0): f = (x + y) ** 2 elif y == 0: f = x elif x == 0: f = y print(f"f({x}, {y}) = {f}") |
Example run:
Input integers x, y: >>> 7 >>> -5 f(7, -5) = 70