Every useful program needs to make decisions. Should this user be granted access? Is one value larger than another? Python’s conditional statements —Documentation Index
Fetch the complete documentation index at: https://mintlify.com/marioaje/Python/llms.txt
Use this file to discover all available pages before exploring further.
if, elif, and else — let your code evaluate a condition and take different paths depending on whether that condition is True or False. Mastering conditionals is the first step toward writing programs that respond intelligently to data.
Basic if / else
The simplest form of a conditional checks a single condition. If it is True, the indented block underneath runs; otherwise the else block runs.
The example below stores two numbers and compares them:
if.py
2000 is not less than 22, Python skips the if block and executes the else block, printing:
F-strings
Notice thef"""...""" syntax used for mensaje. An f-string (formatted string literal) lets you embed any Python expression directly inside curly braces {} within a string. Python evaluates the expression at runtime and inserts the result into the text — no manual concatenation needed.
if / elif / else Chain
When you have more than two possible outcomes, chain as many elif (“else if”) clauses as you need between the opening if and the final else. Python evaluates each condition from top to bottom and runs the first block whose condition is True; all others are skipped.
if.py
| Condition | Meaning | Runs? |
|---|---|---|
a == b | 2000 == 22 → False | No |
a < b | 2000 < 22 → False | No |
else | Everything else | ✅ Yes |
Indentation is mandatory in Python. Unlike many other languages that use
curly braces
{} to group code, Python uses consistent indentation (typically
4 spaces) to define blocks. Every statement inside an if, elif, or else
branch must be indented to the same level. Mixing tabs and spaces — or
inconsistent spacing — will raise an IndentationError at runtime.Login Validation Example
A practical use-case forif/else is credential checking. The snippet below from the course demonstrates a simple login guard:
if.py
"mariosss" and "mario" are not equal, Python prints:
== check that routes execution to the appropriate branch.