Coding Exercise for Beginners in Python with solution | Exercise 17 |Python for Beginners #lec48
FizzBuzz Coding Challenge Explained
Introduction to FizzBuzz
- The video begins with a recap of previous discussions on Python, specifically mentioning the range function and its application in coding exercises.
- The presenter introduces the FizzBuzz problem, a common coding interview question that requires printing numbers from 1 to n (e.g., 1 to 100).
Problem Requirements
- The task involves printing numbers but with specific conditions:
- If a number is divisible by 3, print "Fizz" instead of the number.
- If a number is divisible by 5, print "Buzz" instead of the number.
- If a number is divisible by both 3 and 5, print "FizzBuzz".
Implementation Steps
- A hint is provided about using a for loop and checking three conditions within it. The order of these conditions matters significantly.
- Viewers are encouraged to pause the video and attempt solving the problem before seeing the solution.
Initial Code Attempt
- The presenter starts writing code in a new file named
fizzbuzz.py, setting up a for loop that iterates from 1 to 100.
- Three conditional checks are implemented:
- Check if the number is divisible by 3 (print "Fizz").
- Check if it's divisible by 5 (print "Buzz").
- Check if it's divisible by both (print "FizzBuzz").
Debugging Issues
- An initial test run shows correct outputs for numbers up to ten but fails at fifteen where it only prints "Fizz".
- This issue arises because once one condition is met (divisible by three), subsequent conditions are not checked.
Adjusting Conditions
- To fix this, the presenter suggests reordering conditions so that checking for divisibility by both three and five occurs first.
- By adjusting the order of checks—first checking for divisibility by five then three—the output correctly displays "FizzBuzz" for fifteen.
Alternative Solutions
- While this solution works, it’s noted that there are multiple ways to approach this problem.
- The presenter mentions using switch statements as an alternative method to streamline condition checks.
Conclusion
- Viewers are encouraged to explore different solutions and approaches as FizzBuzz remains a popular question in coding interviews.