Lesson 16/48 ยท ๐ Making Decisions
๐ Making DecisionsLesson 16/48
Phase 2 ยท Making Decisions25 min
If / Else, Making Decisions
Teach your program to choose different paths based on conditions
Programs need to make decisions. "If this is true, do this. Otherwise, do that." That's what
if/else is for.How would you approach this? Think first, then expand.
Basic if/elsepython
age = 18
if age >= 18:
print("You can vote!")
else:
print("Too young to vote.")๐Code TracerStep 1 / 7
trace.py
1score = 85โ
2if score >= 90:
3 grade = "A"
4elif score >= 80:
5 grade = "B"
6else:
7 grade = "C"
8print(grade)
Variables
No variables yet
Step 1 / 7
Indentation matters in Python. The code inside
if and else must be indented (4 spaces or 1 tab). This is how Python knows what's "inside" each branch.Multiple conditions with elifpython
score = 75
if score >= 90:
print("A")
elif score >= 80:
print("B")
elif score >= 70:
print("C")
else:
print("F")
# prints: CComparison operators:
== equal to!= not equal to> greater than< less than>= greater than or equal<= less than or equal= assigns a value (x = 5). == checks equality (x == 5). Mixing these up is the #1 beginner mistake.๐In the Real World...
Every CI/CD pipeline has conditions: if branch == "main", deploy to prod. If tests fail, stop the pipeline. If image size > 500MB, send an alert. You'll write these daily.
Practice Exercises
0/3 solvedExercise 1 of 3easy
โฑ 00:00Grade Calculator
Write a function
get_grade(score) that returns a letter grade:- 90-100 โ "A"- 80-89 โ "B"- 70-79 โ "C"- 60-69 โ "D"- Below 60 โ "F"solution.py
1 / 3
Exercise 2 of 3medium
โฑ 00:00FizzBuzz
Write a function
This is one of the most famous interview questions!
fizzbuzz(n) that returns:- "FizzBuzz" if n is divisible by both 3 and 5- "Fizz" if divisible by 3 only- "Buzz" if divisible by 5 only- The number as a string otherwiseThis is one of the most famous interview questions!
solution.py
2 / 3
Exercise 3 of 3medium
โฑ 00:00Leap Year
Write a function
A year is a leap year if:- It's divisible by 4 AND- Not divisible by 100, UNLESS also divisible by 400
Examples: 2000 โ True, 1900 โ False, 2024 โ True, 2023 โ False
is_leap_year(year) that returns True if it's a leap year.A year is a leap year if:- It's divisible by 4 AND- Not divisible by 100, UNLESS also divisible by 400
Examples: 2000 โ True, 1900 โ False, 2024 โ True, 2023 โ False
solution.py
3 / 3
Solve all 3 exercises to unlock completion