for i in range(1,101) :
result = ""
if i % 3==0 : result+="Fizz"
if i % 5==0 : result+="Buzz"
if result == "" : print(i)
else : print(result)
Output
1
2
Fizz
4
Buzz
Fizz
7
8
Fizz
Buzz
11
Fizz
13
14
FizzBuzz
16
17
Fizz
19
Buzz
Fizz
22
23
Fizz
Buzz
...
97
98
Fizz
Buzz
The above code iterates through the numbers 1 to 100. If the number is divisible by 3, it adds "Fizz" to the result string. If the number is divisible by 5, it adds "Buzz" to the result string. If the number is divisible by 3 and 5, it adds "FizzBuzz" to the result string. If the result string is empty, it prints the number. Otherwise, it prints the result string.
This is a better approach to solving the FizzBuzz problem using Python. We are not using the modulo operator here, hence the efficiency of our program will be higher than the previous solution.
count_3 = 0
count_5 = 0
for i in range(1,101) :
count_3 += 1
count_5 += 1
result=""
if count_3 == 3:
result+="Fizz"
count_3 = 0
if count_5 == 5:
result+="Buzz"
count_5 = 0
if result == "":
print(i)
else:
print(result)
As we know that Python provides different methods that can be helpful to write the program in one line. We will use the same approach here.
for i in range(1, 101) :
print("Fizz"*(i%3<1)+(i%5<1)*"Buzz" or i)
0 Comments