Comprehensive Guide to Python
Conditional Statements
This document provides an in-depth explanation of Python's conditional
statements, covering syntax, operators, best practices, and advanced features. It
is designed to be easily understandable by beginners and professionals alike,
with multiple examples, professional formatting, and accurate explanations.
1. Ternary Operator
Meaning:
The word 'ternary' means 'composed of three parts'. A ternary operator in Python
is a short-hand way to write conditional expressions in a single line. It involves
three operands:
1. Condition to evaluate
2. Value if condition is True
3. Value if condition is False
Syntax:
value_if_true if condition else value_if_false
Examples:
Example 1: Age Check
age = 20
status = "Adult" if age >= 18 else "Minor"
print(status)
# Output:
Adult
Example 2: Maximum of Two Numbers
a=5
b = 10
maximum = a if a > b else b
print(f"The maximum is {maximum}")
# Output:
The maximum is 10
2. Multiple Conditions in One Line
Meaning:
Allows checking of multiple comparisons in a single, clean line. This improves
readability and avoids long chained conditions.
Examples:
Example 1: Range Check
x = 12
if 10 <= x <= 20:
print("x is between 10 and 20")
# Output:
x is between 10 and 20
Example 2: Letter in Range
letter = 'c'
if 'a' <= letter <= 'z':
print('Lowercase letter')
# Output:
Lowercase letter
3. Usage of pass
Meaning:
The 'pass' statement in Python is a null operation. It is used when a block of code
is syntactically required but no action is needed. This is helpful when outlining
code or intentionally leaving blocks empty.
Examples:
Example 1: Empty If Block
x=5
if x > 10:
pass
else:
print("x is small")
# Output:
x is small
Example 2: Placeholder for Function Implementation
def future_function():
pass
Example 3: Empty Class Definition
class MyClass:
pass
4. Avoiding Repeating Variables
Instead of repeating variable comparisons, use the 'in' keyword for cleaner code.
Bad Practice Example:
if x == 1 or x == 2 or x == 3:
print("x is 1, 2, or 3")
Better Practice Example:
if x in (1, 2, 3):
print("x is 1, 2, or 3")
5. Boolean Variable in Condition
Meaning:
Boolean variables store either True or False. Instead of comparing them explicitly
with True or False, they can be directly used in conditions, making code cleaner
and more Pythonic.
Examples:
Example 1: Simple Boolean Flag
is_active = True
if is_active:
print("System is active")
else:
print("System is inactive")
# Output:
System is active
Example 2: Using not
is_logged_in = False
if not is_logged_in:
print("Please login")
# Output:
Please login
Example 3: Function Returning Boolean
def is_even(number):
return number % 2 == 0
number = 4
if is_even(number):
print(f"{number} is even")
else:
print(f"{number} is odd")
# Output:
4 is even
6. Using any() and all()
any(): Returns True if any element in the iterable evaluates to True.
all(): Returns True only if all elements in the iterable evaluate to True.
These are useful for validating multiple conditions across lists, sets, or other
iterables.
Examples:
Example 1: Using any()
marks = [45, 78, 88]
if any(mark < 50 for mark in marks):
print("At least one subject failed")
else:
print("All passed")
# Output:
At least one subject failed
Example 2: Using all()
marks = [65, 75, 88]
if all(mark >= 50 for mark in marks):
print("All subjects passed")
else:
print("Some subjects failed")
# Output:
All subjects passed
Example 3: Checking Flags
flags = [True, True, False]
if all(flags):
print("All True")
else:
print("At least one False")
# Output:
At least one False
7. Match-Case (Python 3.10+)
Meaning:
The match-case statement is Python's way of handling pattern matching. It works
as a cleaner alternative to long if-elif-else chains.
Syntax Explanation:
- match variable: Starts the matching block
- case value: Executes block if value matches
- _: Acts as a default or fallback case
Examples:
Example 1: Command Matching
command = "start"
match command:
case "start":
print("System starting...")
case "stop":
print("System stopping...")
case _:
print("Unknown command")
# Output:
System starting...
Example 2: Integer Matching
num = 2
match num:
case 1:
print("One")
case 2:
print("Two")
case 3:
print("Three")
case _:
print("Other Number")
# Output:
Two
Example 3: Tuple Matching
point = (0, 5)
match point:
case (0, y):
print(f"Point lies on Y-axis at {y}")
case (x, 0):
print(f"Point lies on X-axis at {x}")
case (x, y):
print(f"Point at coordinates ({x}, {y})")
# Output:
Point lies on Y-axis at 5