1. The if
Statement: Your First Decision
The if
statement is the simplest form of conditional logic. It executes a block of code only if a specified condition is `True`.
Syntax:
if condition:
# Code to execute if condition is True
# (This block MUST be indented)
-
The `condition` is an expression that evaluates to either
True
orFalse
(e.g., `age >= 18`, `name == "Alice"`, `is_admin and has_access`). - The code block under the `if` statement **must be indented** (typically 4 spaces) to indicate that it belongs to that `if` block. Python uses indentation to define code blocks, unlike curly braces `{}` in C++ or Java.
Example: Checking Eligibility
user_age = 20
if user_age >= 18:
print("You are eligible to vote!")
print("This message always prints.") # This line is outside the if block
You are eligible to vote! This message always prints.
user_age = 16
if user_age >= 18:
print("You are eligible to vote!")
print("This message always prints.")
This message always prints.