An if statement lets you run certain code only if a condition is true.
Example:
age = 21
if age >= 18:
print("You are an adult.")
The code inside the if
block only runs when the condition is true. Note the colon (:
) at the end of the if
line and the indentation (usually 4 spaces) for the code inside the block.
You can combine multiple conditions using logical operators:
and
: Both conditions must be trueif age >= 18 and age < 65:
or
: At least one condition must be trueif age < 18 or age > 65:
not
: Reverses a conditionif not is_logged_in:
Example:
age = 21
has_id = True
if age >= 18 and has_id:
print("Access granted.")
NOTE: Ensure your code is tabbed in like the above examples otherwise Python will return an error!