Lose the useless brackets
This:
while (count < 101):
can just be:
while count < 101:
Increment out of the if
s
Wouldn't be easier to do:
count = 0
while count < 101:
if count % 5 == 0 and count % 3 == 0:
print "FizzBuzz"
elif count % 3 == 0:
print "Fizz"
elif count % 5 == 0:
print "Buzz"
else:
print count
count = count + 1 # this will get executed every loop
A for
loop will be better
for num in xrange(1,101):
if num % 5 == 0 and num % 3 == 0:
print "FizzBuzz"
elif num % 3 == 0:
print "Fizz"
elif num % 5 == 0:
print "Buzz"
else:
print num
I've also renamed count
to num
since it doesn't count much, is just a number between 1 and 100.
Let's use only one print
Why do 4 different print, when what is really changing is the printed message?
for num in xrange(1,101):
if num % 5 == 0 and num % 3 == 0:
msg = "FizzBuzz"
elif num % 3 == 0:
msg = "Fizz"
elif num % 5 == 0:
msg = "Buzz"
else:
msg = str(num)
print msg
Light bulb!
"FizzBuzz"
is the same of "Fizz" + "Buzz"
.
Let's try this one:
for num in xrange(1,101):
msg = ''
if num % 3 == 0:
msg += 'Fizz'
if num % 5 == 0: # no more elif
msg += 'Buzz'
if not msg: # check if msg is an empty string
msg += str(num)
print msg
Copy and paste this last piece of code here to see what it does.
Python is a very flexible and powerful language, so I'm sure there could be other hundred and one different possible solutions to this problem :)
Edit: Improve more
There's still something "quite not right" with these lines:
if not msg:
msg += str(num)
IMHO it would be better to do:
for num in xrange(1,101):
msg = ''
if num % 3 == 0:
msg += 'Fizz'
if num % 5 == 0:
msg += 'Buzz'
print msg or num
There! Now with:
print msg or num
is clear that num
is the default value to be printed.
['Fizz'*(not i%3) + 'Buzz'*(not i%5) or i for i in range(1, 100)]
. \$\endgroup\$print '\n'.join(['Fizz'*(not i%3) + 'Buzz'*(not i%5) or str(i) for i in range(1, 101)])
. Also note the 101 -range(1, 100)
returns 1 to 99. \$\endgroup\$