Use if, elif, else for decision making.
Ternary
x if condition else y
Truthiness
0, "", [], None, False are falsy.
Use if, elif, else for decision making.
x if condition else y
0, "", [], None, False are falsy.
score = 85 if score >= 90: grade = "A" elif score >= 80: grade = "B" else: grade = "F" status = "pass" if score >= 60 else "fail"
score = 85 if score >= 90: grade = "A" elif score >= 80: grade = "B" elif score >= 70: grade = "C" else: grade = "F" print("Grade:", grade) # Ternary status = "Pass" if score >= 60 else "Fail" print("Status:", status) # Multiple conditions age = 22 has_license = True if age >= 18 and has_license: print("Can drive") # In keyword if "a" in ["a", "b"]: print("Found!")
Check if a number is positive, negative, or zero.
num = 10
if num > 0: print("Positive")
elif num < 0: print("Negative")
else: print("Zero")
What is bool("")?
Empty string is falsy.
Early returns at function start that handle edge cases, reducing nesting.