Python supports basically TWO types of conditional statements to control the flow of a program based on whether a condition is true or false.
No 1 : IF-ELSE
if statement: This is the simplest form. A block of code is executed only if the specified condition is True.
python
age = 20
if age >= 18:
print("Eligible to vote.") # Indented block is executedMultiple if-- if-elif-else statement:
known as a chained conditional or ladder, it is used for checking multiple conditions. The code block associated with the first ‘if’ or ‘elif’ condition that evaluates to True is executed.
python
score = 70
if score >= 90:
print("Grade: A")
elif score >= 80:
print("Grade: B")
else:
print("Grade: C") # This block is executedNested if(s) statement:
This is done by nesting one if or if-else statement inside another. Nesting allows more complex decision logic to be used, where one condition is tested only after the other condition is satisfied.
python
age = 70
is_member = True
if age >= 60:
if is_member:
print("30% senior discount!") # This is executed
else:
print("20% senior discount.")
else:
print("Not eligible for a senior discount.")No 2: MATCH-CASE
The match and case statements, added to the 3.10 version of the Python interpreter, offer a powerful way of using structural pattern matching, similar to the switch-case statements of other languages but more flexible.
The basic syntax of the match statement consists of the keyword match followed by an expression, and then a series of case blocks.
python
match expression:
case pattern1:
# code block for pattern1
case pattern2:
# code block for pattern2
# ...
case _:
# code block for the default case (wildcard)
No Comments Yet