Foundation
Conditional Statements
Use if, elif and else to run code depending on a condition. Python uses indentation to define blocks.
conditionals.py
marks = 72
if marks >= 90:
grade = "A"
elif marks >= 60:
grade = "B"
else:
grade = "C"
print(grade) # B
Conditional expression
ternary.py
status = "adult" if age >= 18 else "minor"
Truthy and falsy values
0, "", [], {}, None and False are falsy. Everything else is truthy.
truthy.py
items = []
if not items:
print("empty")
match statement (Python 3.10+)
match.py
command = "stop"
match command:
case "go":
print("Going")
case "stop":
print("Stopping")
case _:
print("Unknown")
Loading Comments...