I'm trying to print out each iteration but instead it's printing out the last value as many times as the input. How do I fix it?
Code 1:
for i in range (1,n+1):
if n % 3 == 0 and n % 5 != 0:
print("Fizz")
if n % 5 == 0 and n % 3 != 0:
print("Buzz")
if n % 3 == 0 and n % 5 == 0:
print("FizzBuzz")
If I input 15, for example, it prints out "FizzBuzz" 15 times. I want it to print out something like this:
Sample Output:
1, 2, Fizz, 4, ..., Fizzbuzz
All you need are a couple minor modifications:
for i in range(1, n + 1):
if i % 3 == 0 and i % 5 != 0:
print("Fizz")
elif i % 5 == 0 and i % 3 != 0:
print("Buzz")
elif i % 3 == 0 and i % 5 == 0:
print("FizzBuzz")
else:
print(i)
You were making the mathematical tests against n
, not i
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.