Python Conditional Statements β€” Making Decisions in Code

Python BasicsConditional StatementsFree Lesson

Advertisement

Python Conditional Statements β€” Making Decisions in Code

Programs need to make decisions. A website decides whether to show a login page or a dashboard. A game decides whether the player has won. A calculator decides whether division by zero is attempted. All of these decisions rely on conditional statements β€” code that evaluates a condition and branches into different paths based on the result.

Python implements conditionals with a clean, readable syntax that enforces clarity through indentation. This tutorial covers every aspect of Python conditionals, from basic if statements to the structural pattern matching introduced in Python 3.10.


Learning Objectives

By the end of this tutorial, you will be able to:

  • Write if, if-else, and if-elif-else statements with correct syntax
  • Use ternary (conditional) expressions for concise assignments
  • Identify truthy and falsy values in Python
  • Apply logical operators (and, or, not) in compound conditions
  • Use match-case for structural pattern matching (Python 3.10+)
  • Recognize and avoid common conditional mistakes
  • Apply practical patterns like guard clauses and dictionary dispatch

The if Statement

The if statement is the most fundamental conditional. It executes a block of code only when a condition evaluates to True.

Basic Syntax

temperature = 95

if temperature > 90:
    print("It's really hot outside.")
    print("Stay hydrated!")

Output:

It's really hot outside.
Stay hydrated!

The condition temperature > 90 evaluates to True, so both indented lines execute. If the condition were False, Python skips the entire indented block.

Indentation Matters

Python uses indentation instead of braces to define code blocks. This is not optional β€” it is a core part of the language syntax. The standard convention is 4 spaces per indentation level.

# Correct β€” 4 spaces
if True:
    print("First level")
    print("Still first level")
        print("Second level")   # Indented further β€” nested block

Contrast with other languages:

// Java β€” braces define blocks
if (true) {
    System.out.println("First level");
    System.out.println("Still first level");
}
// JavaScript β€” braces define blocks
if (true) {
    console.log("First level");
    console.log("Still first level");
}

Python's enforced indentation improves readability. There is never ambiguity about which block a line belongs to.

Blocks Are Defined by Indentation Level

Every increase in indentation starts a new block. Decreasing indentation ends that block and returns to the outer level.

x = 10

if x > 5:
    print("x is greater than 5")    # Block 1
    if x > 8:
        print("x is also > 8")      # Block 2 (nested)
    print("Back to Block 1")        # Still Block 1

print("Outside all blocks")         # No indentation β€” outside

Output:

x is greater than 5
x is also > 8
Back to Block 1
Outside all blocks

Visual Flow of an if Statement

          β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
          β”‚  Condition   β”‚
          β””β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”˜
                 β”‚
          β”Œβ”€β”€β”€β”€β”€β”€β–Όβ”€β”€β”€β”€β”€β”€β”€β”
          β”‚  True or False?β”‚
          β””β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”˜
            β”Œβ”€β”€β”€β”€β”΄β”€β”€β”€β”€β”
            β”‚         β”‚
        β”Œβ”€β”€β”€β–Όβ”€β”€β”  β”Œβ”€β”€β”€β–Όβ”€β”€β”
        β”‚ True  β”‚  β”‚False β”‚
        β”‚ block β”‚  β”‚(skip)β”‚
        β””β”€β”€β”€β”¬β”€β”€β”˜  β””β”€β”€β”€β”¬β”€β”€β”˜
            β”‚         β”‚
            β””β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”˜
                 β”‚
          β”Œβ”€β”€β”€β”€β”€β”€β–Όβ”€β”€β”€β”€β”€β”€β”
          β”‚  Continue    β”‚
          β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜

if-else

The if-else statement provides two-way branching β€” one path for True, another for False.

Two-Way Branching

age = 17

if age >= 18:
    print("You can vote.")
else:
    print("You are too young to vote.")

Output:

You are too young to vote.

The else block runs when the condition is False. You cannot have an else without a preceding if.

Common Patterns

Checking membership:

username = "admin"

if username in ["admin", "root", "superuser"]:
    print("Welcome back, administrator.")
else:
    print("Access denied.")

Validating input:

password = "secret123"

if len(password) >= 8:
    print("Password length is acceptable.")
else:
    print("Password must be at least 8 characters.")

Even/odd check:

number = 7

if number % 2 == 0:
    print(f"{number} is even.")
else:
    print(f"{number} is odd.")

Output:

7 is odd.

if-elif-else

When you have more than two possible paths, use if-elif-else. Each elif adds another branch.

Multi-Way Branching

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"Score: {score} β†’ Grade: {grade}")

Output:

Score: 85 β†’ Grade: B

Order Matters β€” First Match Wins

Python evaluates conditions top to bottom and executes the first block whose condition is True. It does not check remaining conditions.

temperature = 75

if temperature > 100:
    print("Extreme heat warning!")
elif temperature > 90:
    print("It's hot.")
elif temperature > 70:
    print("Nice weather.")       # This runs
elif temperature > 50:
    print("Cool outside.")       # This is skipped
else:
    print("Cold!")

Output:

Nice weather.

Even though temperature > 50 is also True, it is never checked because the temperature > 70 branch already matched.

Rearranging changes behavior:

temperature = 75

# Wrong order β€” this gives incorrect results
if temperature > 50:
    print("Cool outside.")       # This runs β€” wrong!
elif temperature > 70:
    print("Nice weather.")       # Never reached

Always order conditions from most restrictive to least restrictive, or from highest to lowest threshold.

Optional Final else

The final else is optional but recommended. Without it, no branch may execute if no condition matches.

day = "Funday"

if day == "Monday":
    print("Start of the work week.")
elif day == "Friday":
    print("Almost weekend!")
# No else β€” if day doesn't match, nothing happens

A final else acts as a safety net:

day = "Funday"

if day == "Monday":
    print("Start of the work week.")
elif day == "Friday":
    print("Almost weekend!")
else:
    print(f"I don't have a special message for {day}.")

Output:

I don't have a special message for Funday.

The Ladder Pattern

When checking a single variable against many values, some developers use "elif ladders":

color = "blue"

if color == "red":
    print("Stop")
elif color == "yellow":
    print("Caution")
elif color == "green":
    print("Go")
elif color == "blue":
    print("Info")
else:
    print("Unknown color")

This works but is often better replaced with a dictionary lookup (covered in Common Patterns later).


Ternary / Conditional Expression

Python supports a one-line conditional expression that returns a value based on a condition.

Syntax

value_if_true if condition else value_if_false

Basic Example

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

Output:

adult

This is equivalent to:

if age >= 18:
    status = "adult"
else:
    status = "minor"

In Function Arguments

Ternaries are especially useful inside function calls:

x = -5
print(f"The absolute value is {x if x >= 0 else -x}")

Output:

The absolute value is 5

Nested Ternaries (and Why to Avoid Them)

You can nest ternaries, but readability suffers quickly:

score = 85
grade = "A" if score >= 90 else "B" if score >= 80 else "C" if score >= 70 else "D" if score >= 60 else "F"
print(grade)

Output:

B

This works but is hard to read. For more than two branches, use an if-elif-else block or a dictionary lookup instead.

When to Use Ternary vs if-else

Use ternary when:

  • Choosing between two simple values
  • The expression is short and readable
  • Assigning a variable inline
parity = "even" if num % 2 == 0 else "odd"

Use if-else when:

  • The logic is complex
  • Multiple statements need to execute
  • You have more than two branches
  • Readability would suffer
if user.is_authenticated:
    redirect_to_dashboard()
    log_access(user)
else:
    redirect_to_login()
    log_attempt(user)

Truthy and Falsy Values

Python has a concept of truthiness: every value can be treated as True or False in a boolean context. You do not always need explicit comparisons.

Comprehensive Table of Falsy Values

ValueWhy it's falsy
FalseThe boolean False
NoneThe null object
0 (int)Zero
0.0 (float)Zero
0j (complex)Zero
"" (string)Empty string
[] (list)Empty list
() (tuple)Empty tuple
{} (dict)Empty dictionary
set()Empty set
range(0)Empty range
b"" (bytes)Empty bytes
Any custom object with __bool__() returning FalseCustom falsy

Everything Else is Truthy

# These are all truthy
if 1:
    print("Non-zero int is truthy")       # Runs

if "hello":
    print("Non-empty string is truthy")   # Runs

if [1, 2, 3]:
    print("Non-empty list is truthy")     # Runs

if {"key": "value"}:
    print("Non-empty dict is truthy")     # Runs

if object():
    print("Any object is truthy")         # Runs

Practical Use: Checking for Empty Collections

names = []

if not names:
    print("No names provided.")   # Runs β€” empty list is falsy
names = ["Alice", "Bob"]

if names:
    print(f"Processing {len(names)} names.")   # Runs

Custom Truthiness with __bool__

You can define custom truthiness for your own classes by implementing the __bool__ method:

class Temperature:
    def __init__(self, degrees):
        self.degrees = degrees

    def __bool__(self):
        # A temperature is "truthy" if above freezing
        return self.degrees > 32

cold = Temperature(20)
warm = Temperature(75)

if cold:
    print("Warm")       # Not printed β€” cold is falsy
else:
    print("Cold")       # Printed

if warm:
    print("Warm")       # Printed β€” warm is truthy
else:
    print("Cold")       # Not printed

Output:

Cold
Warm

Empty Collections Are Falsy

This is a key pattern in Python β€” you can test collections directly:

def process_items(items):
    if items:                           # Truthy if non-empty
        for item in items:
            print(f"Processing {item}")
    else:
        print("Nothing to process.")

process_items([1, 2, 3])
print("---")
process_items([])

Output:

Processing 1
Processing 2
Processing 3
---
Nothing to process.

Logical Operators in Conditions

Python provides three logical operators for combining conditions: and, or, and not.

and, or, not

age = 25
income = 50000

# and β€” both conditions must be True
if age >= 18 and income >= 30000:
    print("Loan approved.")           # Runs

# or β€” at least one condition must be True
if age < 18 or income < 20000:
    print("Loan denied.")             # Skipped

# not β€” inverts the boolean value
is_student = False
if not is_student:
    print("No student discount.")     # Runs

Output:

Loan approved.
No student discount.

Truth Tables

and:

 True  and  True  β†’  True
 True  and  False β†’  False
 False and  True  β†’  False
 False and  False β†’  False

or:

 True  or  True  β†’  True
 True  or  False β†’  True
 False or  True  β†’  True
 False or  False β†’  False

not:

 not True  β†’  False
 not False β†’  True

Short-Circuit Evaluation

Python evaluates logical operators from left to right and stops as soon as the result is determined. This is called short-circuit evaluation.

  • and: If the left side is False, the right side is never evaluated.
  • or: If the left side is True, the right side is never evaluated.
# Short-circuit with and
x = 0
if x != 0 and 10 / x > 2:
    print("Condition met")    # Division never happens β€” x != 0 is False
# Short-circuit with or
name = ""
if name or name.strip():
    print("Has name")         # name.strip() never called if name is truthy

This is useful for avoiding errors:

items = []

# Safe: if items is empty, the loop body is never entered
if items and items[0] == "special":
    print("First item is special")

Combining Conditions

You can chain and group conditions with parentheses:

temperature = 72
humidity = 65
wind_speed = 10

comfortable = (temperature >= 65 and temperature <= 80 and
               humidity < 70 and wind_speed < 20)

if comfortable:
    print("It's a comfortable day.")    # Runs

De Morgan's Laws

De Morgan's Laws describe how to negate compound conditions:

  1. not (A and B) is equivalent to (not A) or (not B)
  2. not (A or B) is equivalent to (not A) and (not B)
# Original condition
if not (age >= 18 and income >= 30000):
    print("Does not meet both requirements.")

# Equivalent using De Morgan's Laws
if age < 18 or income < 30000:
    print("Does not meet both requirements.")

Both produce identical results. Use whichever is more readable for your case.


Match-Case (Python 3.10+)

Python 3.10 introduced structural pattern matching with the match and case keywords. This is similar to switch-case in other languages but far more powerful.

Basic Syntax

match subject:
    case pattern1:
        # Runs if subject matches pattern1
    case pattern2:
        # Runs if subject matches pattern2
    case _:
        # Default case β€” matches anything

Literal Patterns

Match against exact values:

day = "Monday"

match day:
    case "Monday":
        print("Start of the work week.")
    case "Friday":
        print("Almost weekend!")
    case "Saturday" | "Sunday":
        print("It's the weekend!")
    case _:
        print("A regular weekday.")

Output:

Start of the work week.

Capture Patterns

Capture the matched value into a variable:

command = "quit"

match command.split():
    case ["quit"]:
        print("Exiting program.")
    case ["go", direction]:
        print(f"Moving {direction}.")
    case ["get", item]:
        print(f"Picking up {item}.")
    case _:
        print("Unknown command.")

Output:

Exiting program.

Wildcard Pattern (_)

The underscore _ is a wildcard that matches anything without capturing:

status_code = 404

match status_code:
    case 200:
        print("OK")
    case 301:
        print("Moved Permanently")
    case 404:
        print("Not Found")
    case _:
        print(f"Unexpected status code: {status_code}")

Output:

Not Found

OR Patterns (|)

Match against multiple patterns in a single case:

month = "Feb"

match month:
    case "Dec" | "Jan" | "Feb":
        print("Winter in the Northern Hemisphere.")
    case "Mar" | "Apr" | "May":
        print("Spring in the Northern Hemisphere.")
    case "Jun" | "Jul" | "Aug":
        print("Summer in the Northern Hemisphere.")
    case "Sep" | "Oct" | "Nov":
        print("Fall in the Northern Hemisphere.")
    case _:
        print("Unknown month.")

Output:

Winter in the Northern Hemisphere.

Guard Clauses (if)

Add conditions to cases with if:

point = (3, -2)

match point:
    case (0, 0):
        print("At the origin.")
    case (x, y) if x == y:
        print(f"On the diagonal at ({x}, {y}).")
    case (x, y) if x > 0 and y > 0:
        print(f"In the first quadrant at ({x}, {y}).")
    case (x, y) if x > 0:
        print(f"Right of the y-axis at ({x}, {y}).")
    case (x, y):
        print(f"Somewhere at ({x}, {y}).")

Output:

Right of the y-axis at (3, -2).

Mapping Patterns (Dict Matching)

Match against dictionary structures:

action = {"type": "login", "user": "alice"}

match action:
    case {"type": "login", "user": username}:
        print(f"User '{username}' logged in.")
    case {"type": "logout", "user": username}:
        print(f"User '{username}' logged out.")
    case {"type": "error", "code": code}:
        print(f"Error code: {code}")
    case _:
        print("Unknown action.")

Output:

User 'alice' logged in.

Sequence Patterns

Match against lists and tuples:

coordinates = [10, 20]

match coordinates:
    case [x]:
        print(f"1D point at {x}.")
    case [x, y]:
        print(f"2D point at ({x}, {y}).")
    case [x, y, z]:
        print(f"3D point at ({x}, {y}, {z}).")
    case _:
        print("Invalid coordinates.")

Output:

2D point at (10, 20).

Class Patterns

Match against class instances:

class Vehicle:
    def __init__(self, make, model, year):
        self.make = make
        self.model = model
        self.year = year

car = Vehicle("Toyota", "Camry", 2024)

match car:
    case Vehicle(make="Tesla", model=model):
        print(f"Electric vehicle: Tesla {model}")
    case Vehicle(make="Toyota", model=model, year=y) if y >= 2023:
        print(f"Recent Toyota: {model} ({y})")
    case Vehicle(make=make, model=model):
        print(f"{make} {model}")

Output:

Recent Toyota: Camry (2024)

Common Patterns

Experienced Python developers use several recurring patterns with conditionals.

Guard Clauses (Early Return)

Instead of nesting logic inside if blocks, use early returns to flatten code:

# Nested style (harder to read)
def process_order(order):
    if order is not None:
        if order.is_valid():
            if order.has_stock():
                # Actual logic buried deep
                order.process()
                order.send_confirmation()
                return "Success"
            else:
                return "Out of stock"
        else:
            return "Invalid order"
    else:
        return "No order provided"

# Guard clause style (clean and readable)
def process_order(order):
    if order is None:
        return "No order provided"

    if not order.is_valid():
        return "Invalid order"

    if not order.has_stock():
        return "Out of stock"

    # Actual logic at the top level
    order.process()
    order.send_confirmation()
    return "Success"

Guard clauses reduce nesting and make the happy path immediately visible.

Dictionary Dispatch (Replacing Long if-elif Chains)

When branching on a known set of values, a dictionary is often cleaner than an if-elif ladder:

# Long if-elif chain
def handle_command(command):
    if command == "start":
        start_system()
    elif command == "stop":
        stop_system()
    elif command == "restart":
        restart_system()
    elif command == "status":
        check_status()
    elif command == "help":
        show_help()
    else:
        print("Unknown command")

# Dictionary dispatch
def start_system():
    print("System started.")

def stop_system():
    print("System stopped.")

def restart_system():
    print("System restarted.")

def check_status():
    print("System is running.")

def show_help():
    print("Available commands: start, stop, restart, status, help")

commands = {
    "start": start_system,
    "stop": stop_system,
    "restart": restart_system,
    "status": check_status,
    "help": show_help,
}

def handle_command(command):
    action = commands.get(command)
    if action:
        action()
    else:
        print("Unknown command")

Dictionary dispatch is faster for large numbers of cases and easier to extend.

Boolean Flags

Use boolean variables to simplify complex conditions:

# Hard to read
if user.is_active and user.has_permission("edit") and not user.is_suspended:
    allow_edit()

# Clearer with a flag
can_edit = user.is_active and user.has_permission("edit") and not user.is_suspended
if can_edit:
    allow_edit()

Chained Comparisons

Python supports chaining comparisons, which is more concise than using and:

temperature = 72

# Chained comparison
if 65 <= temperature <= 80:
    print("Comfortable temperature.")    # Runs

# Equivalent with and
if temperature >= 65 and temperature <= 80:
    print("Comfortable temperature.")    # Runs

# Three-way chain
score = 85
if 0 <= score <= 100:
    print("Valid score range.")          # Runs

Common Mistakes

These are the most frequent errors developers encounter with Python conditionals.

Mistake 1: Assignment = vs Comparison ==

The single equals sign is assignment. The double equals sign is comparison.

# Wrong β€” this is an assignment, not a comparison
if x = 5:          # SyntaxError!
    print("x is 5")

# Correct
if x == 5:
    print("x is 5")

Python 3.8+ introduced the walrus operator := which allows assignment inside expressions, but this is intentional and different from the mistake above:

# Walrus operator β€” intentional assignment
if (n := len(data)) > 10:
    print(f"List is long: {n} items")

Mistake 2: Comparing with None Using is Not ==

None is a singleton. Always use is or is not when comparing to None:

# Wrong β€” works but not idiomatic
if value == None:
    print("Value is None")

# Correct
if value is None:
    print("Value is None")

# Also correct
if value is not None:
    print("Value is not None")

This convention applies specifically to None. For other values, use ==.

Mistake 3: Truthy/Falsy Surprises

Some values behave unexpectedly in boolean context:

# These empty containers are all falsy
if 0:
    print("0 is truthy")           # NOT printed β€” 0 is falsy

if 0.0:
    print("0.0 is truthy")         # NOT printed β€” 0.0 is falsy

if "":
    print("' ' is truthy")         # NOT printed β€” empty string is falsy

if "0":
    print("'0' is truthy")         # PRINTED β€” non-empty string is truthy!

if []:
    print("[] is truthy")          # NOT printed β€” empty list is falsy

The string "0" is truthy because it is a non-empty string. This trips up many beginners.

Mistake 4: elif vs Separate if Statements

Using separate if statements instead of elif means all conditions are checked, even after a match:

# Wrong β€” all conditions checked, potentially multiple blocks execute
score = 85

if score >= 90:
    grade = "A"
if score >= 80:
    grade = "B"       # Overwrites the A!
if score >= 70:
    grade = "C"       # Overwrites the B!

# Correct β€” first match wins
if score >= 90:
    grade = "A"
elif score >= 80:
    grade = "B"
elif score >= 70:
    grade = "C"

Mistake 5: Missing Colons

Every if, elif, else, and match/case statement must end with a colon:

# Wrong β€” SyntaxError
if temperature > 90
    print("Hot!")

# Correct
if temperature > 90:
    print("Hot!")

Practice Exercises

Exercise 1: Temperature Alert System

Write a function that takes a temperature in Fahrenheit and returns an alert message based on the following ranges:

  • Below 32: "Freezing β€” risk of frostbite"
  • 32 to 50: "Cold β€” bundle up"
  • 51 to 75: "Comfortable"
  • 76 to 95: "Warm β€” stay hydrated"
  • 96 to 110: "Hot β€” heat advisory"
  • Above 110: "Extreme heat β€” danger!"

Use if-elif-else and handle invalid temperatures (below -50 or above 150).

def temperature_alert(temp):
    if temp < -50 or temp > 150:
        return "Invalid temperature reading."

    if temp < 32:
        return "Freezing β€” risk of frostbite."
    elif temp < 51:
        return "Cold β€” bundle up."
    elif temp < 76:
        return "Comfortable."
    elif temp < 96:
        return "Warm β€” stay hydrated."
    elif temp < 111:
        return "Hot β€” heat advisory."
    else:
        return "Extreme heat β€” danger!"


# Test cases
print(temperature_alert(20))     # Freezing β€” risk of frostbite.
print(temperature_alert(45))     # Cold β€” bundle up.
print(temperature_alert(70))     # Comfortable.
print(temperature_alert(85))     # Warm β€” stay hydrated.
print(temperature_alert(105))    # Hot β€” heat advisory.
print(temperature_alert(120))    # Extreme heat β€” danger!
print(temperature_alert(200))    # Invalid temperature reading.

Exercise 2: FizzBuzz with Match-Case

Write a function that prints numbers from 1 to 30, but:

  • For multiples of 3, print "Fizz"
  • For multiples of 5, print "Buzz"
  • For multiples of both 3 and 5, print "FizzBuzz"
  • Otherwise, print the number

Solve it using match-case with guard clauses.

def fizzbuzz_match():
    for i in range(1, 31):
        match (i % 3, i % 5):
            case (0, 0):
                print("FizzBuzz")
            case (0, _):
                print("Fizz")
            case (_, 0):
                print("Buzz")
            case _:
                print(i)

fizzbuzz_match()

Output:

1
2
Fizz
4
Buzz
Fizz
7
8
Fizz
Buzz
11
Fizz
13
14
FizzBuzz
16
17
Fizz
19
Buzz
Fizz
22
23
Fizz
Buzz
26
Fizz
28
29
FizzBuzz

Exercise 3: Login Validator with Guard Clauses

Write a function validate_login(username, password) that returns a tuple of (is_valid, message) using guard clauses. Rules:

  • Username must be at least 3 characters
  • Username must start with a letter
  • Password must be at least 8 characters
  • Password must contain at least one digit
  • Password must contain at least one uppercase letter

Return early with a specific error message on the first failure.

def validate_login(username, password):
    if len(username) < 3:
        return (False, "Username must be at least 3 characters.")

    if not username[0].isalpha():
        return (False, "Username must start with a letter.")

    if len(password) < 8:
        return (False, "Password must be at least 8 characters.")

    if not any(c.isdigit() for c in password):
        return (False, "Password must contain at least one digit.")

    if not any(c.isupper() for c in password):
        return (False, "Password must contain at least one uppercase letter.")

    return (True, "Login successful.")


# Test cases
print(validate_login("ab", "Password1"))        # Too short username
print(validate_login("1user", "Password1"))     # Starts with digit
print(validate_login("user", "pass"))           # Too short password
print(validate_login("user", "password1"))      # No uppercase
print(validate_login("user", "PASSWORD1"))      # No lowercase... wait
print(validate_login("user", "Pass1"))          # Too short
print(validate_login("user", "Password1"))      # Valid

Output:

(False, 'Username must be at least 3 characters.')
(False, 'Username must start with a letter.')
(False, 'Password must be at least 8 characters.')
(False, 'Password must contain at least one uppercase letter.')
(False, 'Password must contain at least one uppercase letter.')
(False, 'Password must be at least 8 characters.')
(True, 'Login successful.')

Key Takeaways

  • if executes a block when a condition is True; if-else provides two branches; if-elif-else handles multiple branches with first-match-wins semantics.
  • Indentation defines blocks in Python. Use 4 spaces consistently. No braces needed.
  • Ternary expressions (x if condition else y) are concise alternatives for simple two-value assignments. Avoid nesting them deeply.
  • Truthy/falsy values: False, None, 0, empty strings, and empty collections are falsy. Everything else is truthy. Use this to write idiomatic checks like if items:.
  • Logical operators (and, or, not) combine conditions with short-circuit evaluation. Use parentheses to group complex expressions.
  • match-case (Python 3.10+) provides powerful structural pattern matching with literal, capture, wildcard, OR, guard, mapping, sequence, and class patterns.
  • Guard clauses flatten nested conditionals by returning early. Dictionary dispatch replaces long elif chains with cleaner lookup tables.
  • Always use == for comparison (not =), is for None checks (not ==), and elif instead of separate if statements when branches are mutually exclusive.

Now that you can make decisions in code, the next step is to repeat actions. In the next tutorial, you will learn about Python loops β€” for and while β€” and how to control iteration with break, continue, and else clauses.

Advertisement

Need Expert Python Help?

Get personalized tutoring, project support, or professional consulting.

Advertisement