Just a simple Fizz Buzz example answer that you guys can dissect and point things out.
count = 0
while count <= 100:
if ((count % 5) == 0 and (count % 3) == 0):
print "FizzBuzz"
count = count + 1
elif (count % 3) == 0:
print "Fizz"
count = count + 1
elif (count % 5) == 0:
print "Buzz"
count = count + 1
else:
print count
count = count + 1
By using a for loop you remove the need for the count number. In fact, if this actually were for a job interview, whether or not an applicant used a while or a for would be quite telling of Python knowledge. Also there is no need to have a conditional for both parts being true.
A sane version of fizz buzz could look like this:
for i in range(1,101):
line = ""
if i%3 == 0:
line = "Fizz"
if i%5 == 0:
line += "Buzz"
print(line or i)
That said, I quite like sillier versions like this:
for i in range(1,101):
print("Fizz" * (i%3==0) + "Buzz" * (i%5==0) or i)
There is also a slightly shorter version than that but it isn't as clear.
Rosetta Code is a fun site if you don't know about it:
https://www.rosettacode.org/wiki/FizzBuzz#Python
Wow @
Mekire that is way above my pay grade, I will study this, thank you for the feedback!
(Nov-07-2016, 04:13 PM)Mekire Wrote: [ -> ]In fact, if this actually were for a job interview, whether or not an applicant used a while or a for would be quite telling of Python knowledge.
Almost any programming experience, for that matter. I actually can't think of a language where you'd need to use a while loop for this. Even php has for loop syntax for this sort of thing:
for ($i=0; $i < 101; $i++) { /* fizzbuzz math */ }