π Quick Recap (Dayβ―5)
You mastered writing clean code with proper naming and formatting.
You learned to spot and fix simple syntax errors.
π― What Youβll Learn Today
How to use
ifstatements to run code only when a condition is true.How to chain conditions with
elif.How to provide a fallback with
else.Understanding truthy and falsy values in Python.
π Overview: Making Decisions with if
In everyday life, you make choices: βIf itβs raining, I take an umbrella.β Code can do the same:
if is_raining:
print("Take an umbrella!")ifchecks the condition inside parentheses (or afterif).If the condition is True, the indented block runs.
Chaining with elif and else
Sometimes there are multiple options:
temperature = 15
if temperature > 25:
print("It's hot, wear shorts!")
elif temperature >= 15:
print("Nice weather, wear something comfortable.")
else:
print("It's cold, bundle up!")elifstands for βelse if.β It checks only if all previousiforelifconditions were False.elseruns when none of the above conditions are True.
Truthy and Falsy Values
Python considers certain values as False in conditions:
False,0,0.0,''(empty string),[](empty list),{}(empty dict),None
All others are True. You can write:
items = []
if items:
print("We have items!")
else:
print("No items found.")Since items is empty ([]), itβs falsy, so the else block runs.
π§ββοΈ Take the Wand and Try Yourself
Create a file named
check_number.py.Write code that:
Prompts the user to enter a number (use
input()).Converts the input to an integer.
Uses
if/elif/elseto print:βPositiveβ if the number is greater than 0.
βZeroβ if it equals 0.
βNegativeβ if it is less than 0.
Run your script and test with different numbers.
Solution Example (check_number.py):
# check_number.py
num = int(input("Enter a number: "))
if num > 0:
print("Positive")
elif num == 0:
print("Zero")
else:
print("Negative")Expected interaction:
Enter a number: 5
PositiveEnter a number: 0
ZeroEnter a number: -3
NegativeRun:
python check_number.pyGreat work! Conditional logic opens up many possibilities.
Next up: Day 7: Looping Constructs, where youβll learn how to repeat tasks automatically.