Virtual assistance

Python Control Flow

Control flow statements allow you to control the execution path of your program based on conditions and make decisions.

Python Control Flow

What is Control Flow?

Control flow refers to the order in which statements are executed in a program. Python provides several control flow statements that allow you to make decisions, repeat actions, and control program execution.

"Control flow determines the path your program takes through its code."

If Statements

The if statement executes a block of code only if a condition is true:

# Basic if statement
age = 18
if age >= 18:
    print("You are an adult")

# if-else statement
temperature = 25
if temperature > 30:
    print("It's hot outside")
else:
    print("It's not too hot")

# if-elif-else statement
score = 85
if score >= 90:
    grade = "A"
elif score >= 80:
    grade = "B"
elif score >= 70:
    grade = "C"
elif score >= 60:
    grade = "D"
else:
    grade = "F"
print(f"Your grade is: {grade}")

Conditional Expressions

Python supports conditional expressions (ternary operators):

# Conditional expression
age = 20
status = "adult" if age >= 18 else "minor"
print(status)  # "adult"

# Multiple conditions
x = 10
result = "positive" if x > 0 else "zero" if x == 0 else "negative"
print(result)  # "positive"

# In function calls
def get_max(a, b):
    return a if a > b else b

print(get_max(5, 8))  # 8

Truth Values and Boolean Context

In Python, all values have a truth value. Falsy values include: False, None, 0, 0.0, empty strings, empty collections:

# Truthy and falsy values
print(bool(0))        # False
print(bool(1))        # True
print(bool(""))       # False
print(bool("hello"))  # True
print(bool([]))       # False
print(bool([1, 2]))   # True
print(bool(None))     # False

# Using in conditions
name = ""
if name:
    print(f"Hello, {name}")
else:
    print("Name is empty")

# Checking for None
value = None
if value is None:
    print("Value is None")
elif value:
    print("Value is truthy")
else:
    print("Value is falsy but not None")

Short-Circuit Evaluation

Python uses short-circuit evaluation for logical operators:

# and operator - stops at first False
def check_first():
    print("Checking first condition")
    return False

def check_second():
    print("Checking second condition")
    return True

if check_first() and check_second():
    print("Both are true")
# Output: Checking first condition

# or operator - stops at first True
if check_second() or check_first():
    print("At least one is true")
# Output: Checking second condition

Nested If Statements

# Nested conditions
age = 25
has_license = True

if age >= 18:
    if has_license:
        print("You can drive")
    else:
        print("You need a license to drive")
else:
    print("You are too young to drive")

# Better with logical operators
if age >= 18 and has_license:
    print("You can drive")
elif age >= 18 and not has_license:
    print("You need a license to drive")
else:
    print("You are too young to drive")

Comparing Values

Python supports various comparison operators:

# Comparison operators
a, b = 5, 10

print(a == b)   # False - equal
print(a != b)   # True - not equal
print(a < b)    # True - less than
print(a > b)    # False - greater than
print(a <= b)   # True - less than or equal
print(a >= b)   # False - greater than or equal

# Chaining comparisons
x = 5
print(1 < x < 10)  # True - x is between 1 and 10

# String comparisons (lexicographical)
print("apple" < "banana")  # True
print("Apple" < "apple")   # True (ASCII values)

# List comparisons
print([1, 2] < [1, 3])  # True

Membership and Identity Tests

# Membership testing
fruits = ["apple", "banana", "cherry"]
print("apple" in fruits)      # True
print("grape" not in fruits)  # True

# String membership
text = "Hello World"
print("Hello" in text)  # True
print("hello" in text)  # False (case sensitive)

# Dictionary membership (keys)
person = {"name": "Alice", "age": 25}
print("name" in person)   # True
print("Alice" in person)  # False (checks keys, not values)

# Identity testing
a = [1, 2, 3]
b = [1, 2, 3]
c = a

print(a == b)  # True (values are equal)
print(a is b)  # False (different objects)
print(a is c)  # True (same object)

# None checking
value = None
if value is None:
    print("Value is None")

Best Practices

  • Use meaningful conditions: Make conditions clear and readable
  • Avoid deep nesting: Use early returns or logical operators
  • Use parentheses for clarity: Complex conditions benefit from parentheses
  • Prefer elif over nested if: Multiple conditions are clearer with elif
  • Use truthy/falsy appropriately: Understand Python's truth values
  • Consider edge cases: Handle None, empty collections, zero values

Common Patterns

# Guard clauses (early returns)
def process_data(data):
    if data is None:
        return "Error: No data"
    if not data:
        return "Error: Empty data"
    
    # Process data here
    return f"Processed {len(data)} items"

# Checking multiple conditions
def get_discount(age, is_student, is_senior):
    if age < 18 or is_student:
        return 0.2  # 20% discount
    elif age >= 65 or is_senior:
        return 0.15  # 15% discount
    else:
        return 0.0   # No discount

# Range checking
def get_grade(score):
    if not (0 <= score <= 100):
        return "Invalid score"
    
    if score >= 90:
        return "A"
    elif score >= 80:
        return "B"
    elif score >= 70:
        return "C"
    else:
        return "F"

Control flow statements are fundamental to programming. They allow your programs to make decisions and respond differently based on different conditions and inputs.