The FizzBuzz problem in Python Core. | Sololearn: Learn to code for FREE!
Neuer Kurs! Jeder Programmierer sollte generative KI lernen!
Kostenlose Lektion ausprobieren
0

The FizzBuzz problem in Python Core.

I'll just copy paste the question below so there's no need to tell what is happening. FizzBuzz is a well known programming assignment, asked during interviews. The given code solves the FizzBuzz problem and uses the words "Solo" and "Learn" instead of "Fizz" and "Buzz". It takes an input n and outputs the numbers from 1 to n. For each multiple of 3, print "Solo" instead of the number. For each multiple of 5, prints "Learn" instead of the number. For numbers which are multiples of both 3 and 5, output "SoloLearn". You need to change the code to skip the even numbers, so that the logic only applies to odd numbers in the range. So, on using the 3, 5 and 15, test case 1 was wrong as there were no signs of multiple of 2. Added the 2 and the test case passed but the second case is still not working. I'll be pasting the code below so can you guys help me? n = int(input()) for i in range(1, n): if i % 2 == 0: continue elif i % 3 == 0: print("Solo") continue elif i % 5 == 0: print('Learn') continue elif i % 15 == 0: print("SoloLearn") continue else: print(i)

15th Mar 2023, 8:01 PM
Abbas Mehdi
Abbas Mehdi - avatar
5 Antworten
+ 6
You need do test first if i is divisible by 5 and 3 BEFORE you test if it is divisible by only one of them.
15th Mar 2023, 9:21 PM
Lisa
Lisa - avatar
+ 5
Suppose i = 15. Then i is divisible by 3 and i % 15 will not be reached.
15th Mar 2023, 8:15 PM
Lisa
Lisa - avatar
0
Well, I removed the i % 15 == 0 part, still the 2nd test case is not solved. Also, if i(15) do gets divided by 3, it will show "Solo" and the 1st test case will also fail.
15th Mar 2023, 9:19 PM
Abbas Mehdi
Abbas Mehdi - avatar
0
Alright, got it! Many Thanks!!!!!
15th Mar 2023, 9:28 PM
Abbas Mehdi
Abbas Mehdi - avatar
0
When using "if-elif-else" the FIRST condition that is True will be and it'll be the ONLY one that's executed even if all of the other conditions are True. So the logic has to be written based on the thought of priority. Place the condition that has the highest priority at the very top. In this case, if a number is divisible by 3 AND 5, then you want that at the top because the conditions that evaluate if a number is divisible by 3 or 5 individually will evaluate to True beforehand.
17th Mar 2023, 6:32 PM
Adrian
Adrian - avatar