Search⌘ K
AI Features

Conditional Statements

Explore how Python's conditional statements enable your code to make decisions and execute dynamically. Learn the syntax and use of if, elif, and else blocks, including nested conditionals, to handle multiple logical paths. Gain practical skills to create interactive programs that respond to user input and real-world scenarios through controlled branching logic.

Up until this point, every program we have written has executed sequentially, starting at the top line and running straight to the bottom without deviation. However, real-world software needs to make decisions. An app might ask, "Has the user logged in?" or a game might check, "Did the player's health drop to zero?" To handle these scenarios, we use control flow statements. These tools allow our code to branch, executing specific blocks only when certain conditions are met, making our scripts dynamic and responsive rather than static lists of instructions.

The if statement

The foundation of decision-making in Python is the if statement. If you are learning how to write an if else statement in Python, the first step is understanding how Python evaluates a condition (an expression) that results in True or False. If the condition is true, Python executes the indented block of code immediately following the statement. If the condition is false, Python skips that block entirely.

Syntactically, an if statement ends with a colon (:). The lines following the colon must be indented, usually by four spaces. This indentation is not just for readability; it is how Python identifies which lines belong to that specific branch.

Python 3.14.0
temperature = 35
print("Checking safety...")
if temperature > 30:
print("Warning: High temperature detected!") # To be executed, if True
print("Engaging cooling system.") # To be executed, if True
print("System check complete.")
  • Line 1: We establish our state variable, temperature. This value serves as the input that determines which path the program takes at a decision point.

  • Line 3: This execution is unconditional. Because it sits at the start of the line (no indentation), Python treats it as part of the main sequential flow that must occur every time the script runs.

  • Line 5: The if keyword initiates a logical gate. Python evaluates the expression temperature > 30 to a boolean. If the result is True, the "gate" opens, allowing the program to enter the specialized branch of code immediately following it.

  • Lines 6–7: These lines define the indented block. In Python, indentation isn't just for style; it defines the scope. These instructions are "owned" by the if statement and will only be executed if the safety threshold is exceeded.

  • Line 9: We outdent to return to the main program flow. By moving back to the left margin, we signal to Python that the conditional branch has ended. This line executes regardless of whether the warning was triggered or not.

Try changing temperature to a value less than 30 and notice the output.

Flowchart of if and else statements
Flowchart of if and else statements

The fallback: else

Often, we need to perform one action if a condition is true and a different action if it is false. To do this, we structure a Python if else statement using the else keyword. The else block guarantees that exactly one of the two paths will be taken.

The else keyword acts as a catch-all. It does not accept a condition; it simply runs whenever the associated if condition evaluates to False.

Python 3.14.0
password = "secret_code"
input_attempt = "password123"
if input_attempt == password:
print("Access Granted.")
else:
print("Access Denied.")
  • Line 4: We compare the user's attempt against the correct password. The result is False.

  • Line 5: This line is skipped because the condition failed.

  • Line 6: The else keyword catches the flow because the if condition was False.

  • Line 7: Python executes the else block, printing "Access Denied".

Multiple options: elif

Real-world logic rarely fits into a simple "yes or no" binary. We often have three or more mutually exclusive possibilities. For this, we use the elif keyword (short for "else if").

We can chain as many elif blocks as needed. Python evaluates them from top to bottom. As soon as one condition evaluates to True, Python executes that block and immediately exits the entire conditional structure, ignoring any remaining elif or else blocks.

Python 3.14.0
traffic_light = "Yellow"
if traffic_light == "Red":
print("Stop immediately.")
elif traffic_light == "Yellow":
print("Slow down and prepare to stop.")
elif traffic_light == "Green":
print("Proceed with caution.")
else:
print("Error: Unknown signal status.")
  • Line 3: We evaluate the if condition, i.e., whether the light is "Red". It is not, so we skip to the elif block.

  • Line 5: We check if the light is "Yellow". This evaluates to True.

  • Line 6: We execute this print() statement.

  • Lines 7–10: Because we found a match at line 5, Python ignores the last elif ("Green") check and else.

Nested conditionals

We can place conditional statements inside other conditional statements to create hierarchical logic. This is called nesting. While powerful, deep nesting can make code harder to read, so we generally aim to keep our logic as flat as possible. However, nesting is essential when a decision depends on a prerequisite check.

Python 3.14.0
has_ticket = True
is_vip = False
if has_ticket:
print("Welcome to the event.")
if is_vip:
print("Please proceed to the VIP lounge.")
else:
print("Your seat is in the general admission area.")
else:
print("You must purchase a ticket to enter.")
  • Line 4: We first check if the person has a ticket. Since has_ticket is True, we enter the first block.

  • Line 5: This message prints for everyone with a ticket.

  • Line 6: Inside the first block, we perform a second check for is_vip.

  • Lines 8–9: Since is_vip is False, the inner else block executes, directing the user to general admission.

Flowchart of nested conditional statements
Flowchart of nested conditional statements

Practical application: Interactive decision maker

By combining conditional logic with the input() function we learned previously, we can build programs that adapt dynamically to user data. In this example, we calculate shipping costs based on the weight of a package.

# Shipping Calculator
weight_input = input("Enter package weight (kg): ")
weight = float(weight_input)  # Convert string input to float

if weight <= 0:
    print("Error: Weight must be positive.")
elif weight <= 2:
    cost = 5.00
    print(f"Standard shipping: ${cost}")
elif weight <= 10:
    cost = 10.00
    print(f"Medium shipping: ${cost}")
else:
    cost = 20.00
    print(f"Heavy shipping: ${cost}")
A script that determines cost based on numerical ranges
  • Line 2: We capture the weight as a string from the user.

  • Line 3: We cast the string to a float to perform numerical comparisons. Before running logic, it is often useful to know how to check data type in Python to ensure your input is actually a number and not a string.

  • Line 5: We validate the input first. If the user enters 0 or a negative number, we handle the error immediately.

  • Line 7: If the weight is valid (e.g., 1.5 kg), this condition matches, setting the cost to $5.00.

  • Line 10: If the weight is 5 kg, the previous check fails (5 <= 2 is False), so this elif catches it.

  • Line 13: Any weight over 10 kg falls into this final category.

We have now unlocked the ability to write non-linear programs. By mastering if, elif, and else, we can direct our code to handle errors, process different data types distinctively, and react to user choices. This branching logic is the backbone of algorithms, enabling a single script to behave intelligently across hundreds of scenarios. In the next lesson, we will refine this further by combining multiple conditions into complex logical tests.