Write a Python program that prints “FizzBuzz” for multiples of both 2 and 3, “Fizz” for multiples of 2 and “Buzz” for multiples of 3; otherwise print the number.
Input
14, 9, 6, 7
Output
14 Fizz
9 Buzz
6 FizzBuzz
7 7
Approach
Test the combined case first, then each single case.
Write a Python program to check whether a year is a leap year.
Input
2000, 1900, 2024
Output
2000 is a leap year
1900 is not a leap year
2024 is a leap year
Approach
Divisible by 400: leap. Else divisible by 100: not leap. Else divisible by 4: leap.
Solution
Python
foryearin[2000,1900,2024]:ifyear%400==0:print(year,"is a leap year")elifyear%100==0:print(year,"is not a leap year")elifyear%4==0:print(year,"is a leap year")else:print(year,"is not a leap year")
Output
2000 is a leap year
1900 is not a leap year
2024 is a leap year
Line by line
Lines 2-7
The rules are checked from the most specific (400) to the most general (4), which is why the order matters.
Learn the concept
New to this topic? Read the lesson, then come back.
Write a Python program to calculate an electricity bill. Units 1-50 cost Rs 0.50, units 51-100 Rs 0.75, units 101-250 Rs 1.25 and units above 250 Rs 1.50 each. Add a 17% surcharge.
Input
350 units
Output
40 units -> 23.4
120 units -> 102.38
350 units -> 468.0
Approach
Charge each slab only for the units that fall in it.
40 units -> 23.4
120 units -> 102.38
350 units -> 468.0
Line by line
Lines 3-5
Units above 250 are charged at 1.50, then units is capped at 250 for the next slab.
Lines 6-11
Each lower slab takes the units between its limits.
Line 12
The first 50 units (or fewer) cost 0.50 each.
Line 13
Multiplying by 1.17 adds the 17% surcharge.
Note
The original sample output (438.75 for 350 units) did not follow these slabs. With slab pricing, 350 units cost 25 + 37.5 + 187.5 + 150 = 400, plus 17% = 468.0.
Learn the concept
New to this topic? Read the lesson, then come back.