How to do FizzBuzz challange with python?
Question:
We have x number that goes 0 to 100. if x number divisible by 3 write ‘fizz’, if divisible by 5 write ‘buzz’ and if divisible by 3 and 5 write ‘fizzbuzz’.
What is wrong with this code below?
Code for FizzBuzz:
i = 1
while i <= 100:
i = i + 1
if (i % 3 == 0):
print('Fizz')
elif (i % 5 == 0):
print('Buzz')
elif (i % 3 == 0) and (i % 5 == 0):
print('FizzBuzz')
else: print(i)
Answers:
Your last elif will never be reached, because if it is divisible by 3 it will not continue, same with 5. So you need to take your last elif as first.
i = 1
while i <= 100:
i = i + 1
if (i % 3 == 0) and (i % 5 == 0):
print('FizzBuzz')
elif (i % 5 == 0):
print('Buzz')
elif (i % 3 == 0):
print('Fizz')
else: print(i)
Welcome! This might help you out:
i = 1
while i <= 100:
answer = ''
if (i % 15 == 0): print('FizzBuzz')
elif (i % 3 == 0): print('Fizz')
elif (i % 5 == 0): print('Buzz')
else: print(i)
i = i + 1
Basically, after you assigned a
to 1
, you instantly add another 1 in your while loop, so I moved your i = i + 1
to the bottom of the while loop.
Also, your 'FizzBuzz'
wouldn’t be printed out – you skip if it divides both on 3 and 5, it divides by 15, but you skip that making fizzes and buzzes show in the first place and skipping the FizzBuzz. I fixed that too.
I hope it helped!
We have x number that goes 0 to 100. if x number divisible by 3 write ‘fizz’, if divisible by 5 write ‘buzz’ and if divisible by 3 and 5 write ‘fizzbuzz’.
What is wrong with this code below?
Code for FizzBuzz:
i = 1
while i <= 100:
i = i + 1
if (i % 3 == 0):
print('Fizz')
elif (i % 5 == 0):
print('Buzz')
elif (i % 3 == 0) and (i % 5 == 0):
print('FizzBuzz')
else: print(i)
Your last elif will never be reached, because if it is divisible by 3 it will not continue, same with 5. So you need to take your last elif as first.
i = 1
while i <= 100:
i = i + 1
if (i % 3 == 0) and (i % 5 == 0):
print('FizzBuzz')
elif (i % 5 == 0):
print('Buzz')
elif (i % 3 == 0):
print('Fizz')
else: print(i)
Welcome! This might help you out:
i = 1
while i <= 100:
answer = ''
if (i % 15 == 0): print('FizzBuzz')
elif (i % 3 == 0): print('Fizz')
elif (i % 5 == 0): print('Buzz')
else: print(i)
i = i + 1
Basically, after you assigned a
to 1
, you instantly add another 1 in your while loop, so I moved your i = i + 1
to the bottom of the while loop.
Also, your 'FizzBuzz'
wouldn’t be printed out – you skip if it divides both on 3 and 5, it divides by 15, but you skip that making fizzes and buzzes show in the first place and skipping the FizzBuzz. I fixed that too.
I hope it helped!