Search⌘ K
AI Features

Conditional Statements

Explore Python's conditional statements to create dynamic programs that make decisions. Learn to implement if, elif, and else branches, including nested conditionals, to handle multiple scenarios and user input effectively.

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. It 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.")
    ...