-2

I’m trying to make a fizzbuzz program: count up to n; for each i up to n, print “fizz” if a multiple of 3, and “buzz” if a multiple of 5 — if a multiple of both, print “fizzbuzz”.

I’m using modular arithmetic, but for some reason my syntax is wrong.

Here is my code (without the “fizzbuzz” bit yet):

def fizzbuzz(n):
   for i in range(n):
      if i % 3 = 0
         return fizz
      if i % 5 = 0
         return buzz
      else
         return i
      
print(fizzbuzz(100))

Error Code:

Python3IDE(Python 3.7) running!
  File "/var/mobile/Containers/Data/Application/FD2AF249-3788-42B7-90B2-929E9D35A2E1/Documents/FizzBuzz.py", line 5
    if i % 3 = 0
             ^
SyntaxError: invalid syntax
Pytho3IDE run end!

Any help is much appreciated.

tkausl
  • 13,686
  • 2
  • 33
  • 50
Grant
  • 1

3 Answers3

1

The problem is in the if i % 3 = 0 and the if i % 5 = 0. The comparison operator, in this case, would be ==, so you would have to rewrite both statements with the comparison operator. Currently, you are using the assignment operator, which Python doesn't understand.

Alex K
  • 111
  • 2
0

Your code is correct, you just missed out on some of the syntax.

def fizzbuzz(n):
   for i in range(n):

Note the double equal signs instead of single equal sign. A single equal sign is an assignment operator, while a double is a comparison operator.

      if i % 3 == 0:
         return fizz
      if i % 5 == 0:
         return buzz
      else:
         return i
  
print(fizzbuzz(100))
0

your syntax is wrong because you are using = instead of == to check is equal:

      if i % 3 = 0
         return fizz
      if i % 5 = 0
         return buzz

should be:

      if i % 3 == 0:
         return "fizz"
      if i % 5 == 0:
         return "buzz"

= is an assignment operator while == is equality operator.

Also, you forgot to add colon : at the end of each if statement.

And, you forgot to use " " on fizz and buzz. Python will search for variables with that name and won't find them. you want to return a string with fizz or buzz.

You should consider taking one of the hundred tutorials for beginners in python, that there is on YouTube...

Eladtopaz
  • 1,036
  • 1
  • 6
  • 21
  • Thank you for your response! When I do this, another error pops up: if i % 3 == 0 ^ It is pointing out the zero as incorrect syntax – Grant Aug 19 '21 at 04:45
  • You also need to add `:` at the end of each `if statement` like I did. – Eladtopaz Aug 19 '21 at 04:49
  • This isn't the only problem. fizz and buzz don't exist as variables – OneCricketeer Aug 19 '21 at 04:50
  • Oh wow, you are right, I didn't notice that. I edited the answer. Thank you. – Eladtopaz Aug 19 '21 at 05:08
  • It's a Good Idea to test answer code before posting it, just in case you missed something important. ;) But it's not a good idea to answer typo questions. They're rarely useful to future readers, so they get deleted. – PM 2Ring Aug 20 '21 at 02:54