I have been given this question to do in Python:
Take in a list of numbers from the user and run FizzBuzz on that list.
When you loop through the list remember the rules:
1) If the number is divisible by both 3 and 5 print FizzBuzz
2) If it's only divisible by 3 print Fizz
3) If it's only divisible by 5 print Buzz
4) Otherwise just print the number
Also remember elif!
I have the following script created, but it gives me an error at if n%3=True
n=input()
if n%3=True:
print("Fizz")
else if n%5=True:
print ("Buzz")
elif print n
Can anyone help? Thank you very much!
A few issues with your code here. The first issue is that, for comparison, you should be using
==
, not=
, which is for assignment.The second issue is that you want to check that the remainder of the divisions (which is what the modulo operator calculates) is zero, not that it's true, which doesn't really make sense.
You should be using
elif
for "otherwise if..." andelse
for "otherwise." And you need to fix the formatting of yourelse
clause.You want:
Finally, your code does not meet the spec:
The above will not do this. This part I'm going to leave to you because I'm not here to solve the assignment for you :)
one of the shortest answers i have found is
61 characters
Based on this
The
.get()
method works wonders here.Operates as follows
For all integers from 1 to 100 (101 is NOT included),
print the value of the dictionary key that we call via get according to these rules.
"Get the first non-False item in the
get
call, or return the integer as a string."When checking for a
True
value, thus a value we can lookup, Python evaluates 0 toFalse
. If i mod 15 = 0, that's False, we would go to the next one.Therefore we
NOT
each of the 'mods' (aka remainder), so that if the mod == 0, which == False, we get a True statement. We multiplyTrue
by the dictionary key which returns the dictionary key (i.e.3*True == 3
)When the integer it not divisible by 3, 5 or 15, then we fall to the default clause of printing the int
'{}'.format(i)
just inserts i into that string - as a string.Some of the output
Fizz
79
Buzz
Fizz
82
83
Fizz
Buzz
86
Fizz
88
89
FizzBuzz
91
92
Fizz
94
Buzz
Fizz
97
98
Fizz
Buzz
Make it universal for any integer, positive or negative. Also make it easily expandable to other keywords for any integer by creating a dictionary of keywords.
n % 3
(orn %
any number) does not evaluate toTrue
orFalse
, it's not a Boolean expression.n % 3 == 0
on the other hand, does.As an aside, what happens when
n % 3 == 0
andn % 5 == 0
both evaluate toTrue
?