Search code examples
pythonindentation

Input returning string when it needs to be used as an integer


So like I'm trying to teach myself python by doing basic coding challenges. I'm trying to make the program take the user input then do the operations then output the correct result. Instead it just ignores all the operations. I think it had something to do with indents but... I'm like 30 minutes deep into learning python so I really have 0 idea. Could someone please explain why and where this isn't working?

var = input("pick number!= ")


def fizzbuzz(var):
    operand0 = 3
    operand1 = 5
    if var % operand0 == 0 and var % operand1 == 0:
        return "FizzBuzz"
    if var % operand0 == 0:
        return "Fizz"
    if var % operand1 == 0:
        return "Buzz"
    else:
        return var


print(fizzbuzz(var))

Output:

  File "****", line 17, in <module>
    print(fizzbuzz(var))
  File "****", line 7, in fizzbuzz
    if var % operand0 == 0 and var % operand1 == 0:
TypeError: not all arguments converted during string formatting```

Solution

  • When I run your program I get this error:

    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
      File "<stdin>", line 4, in fizzbuzz
    TypeError: not all arguments converted during string formatting
    

    This is because var = input("pick number!= ") makes var a string, not a number. And % doesn't work on strings the same way it does on numbers — see https://pyformat.info/#simple.

    To convert your input to a number, you can use var = int(input("...")) or similar.

    This is a difference between Python 2 and 3 — in Python 2, input() evaluated the argument rather than treating it as a string.