Today my code works perfectly, but still I am a bit confused about how it worked. I thought that there should be a problem in the code but somehow there isn’t.
Program: Write a program that iterates all the integers between 1-50. If the number is a multiple of 3 then print “fizz”. If the number is a multiple of 5 then “buzz”. If both then “fizzbuzz”. If none of the above then just print the number and move onto next number.
n = 1
fizz = "fizz"
buzz = "buzz"
fizzbuzz = "fizzbuzz"
for n in range (0, 51):
if (n%3==0 and n%5==0):
1st Question: While I was writing the code, I had a gut feeling. One, if I want the exact result then I need to have the (n%3==0 and n%5==0) condition at the beginning. I don’t know where it came from but when I tested actually that was true. Another gut feeling was I should use elif in my statements instead of just if. But my real question is how can the program work perfectly? Because let’s say a number is a multiple of 3 and 5 both. It prints fizzbuzz, then why doesn’t it print fizz and buzz separately again?
Example: For example, 15 is multiple of both. The program sees the first condition, it matches and then it follows orders and prints fizzbuzz. But when it goes to the second condition, (n%3==0) then that should be true as well. Then why doesn’t it print fizz for the same number again? Same for the third condition. Why doesn’t it print buzz again? I am not able to understand the logic of the computer here and the control flow.
2nd Question: Did any of my gut feeling has to do with the fact that this program worked perfectly? If yes, then can you explain how exactly please?
3rd Question: Is it just luck or everyone develops this sort of gut feeling after a certain amount of time?
The reason for this behavior is the order of the if and elif conditions in your code. When the program encounters a number that is a multiple of both 3 and 5 (like 15), it first enters the block of code associated with the (n%3==0 and n%5==0) condition and prints “fizzbuzz”. Once that block is executed, it doesn’t consider the other conditions ((n%3==0) and (n%5==0) ) even if they would evaluate as true for the same number. This is because if and elif conditions are mutually exclusive. Once one of the conditions is satisfied and executed, the program moves on to the next iteration of the loop.