No history yet

Control Flow Logic

Making Decisions in Code

Your programs often need to make decisions. Just as you might check the weather before deciding what to wear, a program checks conditions to decide which code to run. In Python, this is handled with if, elif, and else statements.

You already know how to store information in variables. Now, let's use that information to control the flow of your script. An if statement tests a condition. If the condition is true, a specific block of code runs. If it's false, the program can either move on, or it can check another condition with elif (short for 'else if'), or run a default block of code with else.

# A simple grading example
score = 85

if score >= 90:
    print("Grade: A")
elif score >= 80:
    print("Grade: B")
elif score >= 70:
    print("Grade: C")
else:
    print("Grade: D or F")

# Output: Grade: B

The program checks each condition in order. As soon as it finds one that is true (score >= 80), it runs the corresponding code and skips the rest of the block. The else block only runs if none of the preceding if or elif conditions are met.

Complex Conditions

Sometimes a simple comparison isn't enough. You might need to check if multiple conditions are true at once, or if at least one of several conditions is met. This is where logical, membership, and identity operators come in.

Logical operators (and, or, not) combine boolean expressions.

  • A and B is true only if both A and B are true.
  • A or B is true if either A or B (or both) are true.
  • not A inverts the boolean value of A.

Membership operators (in, not in) check if a value exists within a sequence, like a list or a string.

Identity operators (is, is not) check if two variables refer to the exact same object in memory. This is different from ==, which checks if the values of two variables are equal.

Use is to check for identity (same object), and == to check for equality (same value). For singletons like None, True, and False, using is is the preferred convention.

user_role = "admin"
user_active = True

# Logical operators
if user_role == "admin" and user_active:
    print("Admin access granted.")

# Membership operator
allowed_roles = ["admin", "editor", "viewer"]
if user_role in allowed_roles:
    print("User has a valid role.")

# Identity operator
user_status = None
if user_status is None:
    print("User status is not set.")

Truthy and Falsy

In Python, every object has an inherent boolean value. This means you don't always need to write an explicit comparison. An object is considered "falsy" if it's an empty collection, a numeric zero, or the special value None. Everything else is "truthy". This allows for concise and readable code.

Falsy values include:

  • None
  • False
  • 0, 0.0, 0j (zero of any numeric type)
  • "", (), [], {} (any empty sequence or collection)

Instead of writing if len(my_list) > 0:, you can simply write if my_list:. This is considered more 'Pythonic'.

user_input = ""
# This block will not run because an empty string is falsy
if user_input:
    print(f"Processing: {user_input}")
else:
    print("No input provided.")

items = []
# This block will not run because an empty list is falsy
if items:
    print("You have items in your cart.")
else:
    print("Your cart is empty.")

# Output:
# No input provided.
# Your cart is empty.

Nested Logic in Practice

Let's combine these concepts to build a simple access control system. This system will check if a user is an admin or a standard user with a valid permission. This requires nesting if statements inside other if statements.

Nested logic allows you to create more complex decision-making paths. The inner if statement is only evaluated if the outer if condition is true.

Lesson image

Our system will check the user's role first. If they are an admin, they get full access. If they are a 'user', we then need to perform a second check to see if they have the 'editor' permission.

# Access control system
user = {
    "username": "testuser",
    "role": "user",
    "permissions": ["viewer", "editor"]
}

if user["role"] == "admin":
    print("Welcome, Admin. Full access granted.")
elif user["role"] == "user":
    print("Welcome, User. Checking permissions...")
    # Nested condition
    if "editor" in user["permissions"]:
        print("You have editor access.")
    else:
        print("You have view-only access.")
else:
    print("Unknown role. Access denied.")

# Output:
# Welcome, User. Checking permissions...
# You have editor access.

This structure is powerful for handling situations where one decision depends on the outcome of another. By building up conditions with logical operators and nesting if statements, you can model complex rules and create robust, intelligent applications.

Quiz Questions 1/6

What is the output of the code below?

score = 85

if score >= 90:
    print("Excellent")
elif score >= 80:
    print("Good")
elif score >= 70:
    print("Average")
else:
    print("Needs Improvement")
Quiz Questions 2/6

Which of the following values is considered "falsy" in Python?