Search code examples
pythonfizzbuzz

Fizz buzz extended


I know how to make a basic fizzbuzz, but now that I am asked to extend it and make it so that the user inputs the number, I cant seem to make it work how the sample code does.

{Game Requirements: Provide a welcome message, Ask the user to enter a value, Check it is correct against the stored value in the sequence, If the value is correct, it should move on to the next number If the value is incorrect, then the game should be over}

print("Welcome to FizzBuzz.")
print("Enter a number, Fizz, Buzz or FizzBuzz:")
for x in range (1,16):
  answer = input()
  fizz = (x%3 == 0)
  buzz = (x%5 == 0) 
  fizzbuzz = (x%3 and x%5 == 0)
  if answer == x:
    print ("next")
  elif answer == "fizz": 
    print("Next")
  elif answer == "buzz":
    print("Next")
  elif answer == "Fizzbuzz":
    print("next")

  else:
      print("incorrect, game over")

It results in incorrect if in put any number, and fizz and buzz when I just write them in. Im new to coding so I might have some things very wrong.


Solution

  • This code here assigns the input it receives from the console to a variable called 'answer'. Since the input it got from the console is a string, the 'answer' variable's type becomes a string.

    answer = input()
    

    And when you try to compare a string to and integer it will always return false. This is what is happening here.

    if answer == x:
    

    In order to fix this, you need to make sure while comparing two types for equality they are the same type. You can fix this by using str(argument) built-in function which takes an argument and returns it as a string. You can implement this in your code as shown below.

    if answer == str(x):
    

    There is also a lot of logic errors on your code. I've made a quick example using two variables which should be easier to understand.

    print("Welcome to FizzBuzz.")
    print("Enter a number, Fizz, Buzz or FizzBuzz:")
    for currentInteger in range (1,16):
      enteredInput = input() #enteredInput is now a string.
      desiredInput = ""
    
      fizz = (currentInteger % 3 == 0)
      buzz = (currentInteger % 5 == 0)
    
      if fizz:
        desiredInput += "fizz"
      if buzz:
        desiredInput += "buzz"
      if not buzz and not fizz:
        desiredInput = str(currentInteger) #Since our desiredInput is a string we need to convert our iteration integer to a string in order to assign it to desiredInput variable.
    
      if desiredInput == enteredInput:
        print("Next: ")
      else:
        print("Wrong input game over.")
        break