2

I don't really understand what's wrong with my snippet here, it looks pretty simple but the compiler is returning an error to me.

choice = input("Enter a number: ")

def fact(num):
    if(num == 0):
        return 1
    return num * fact(num-1)

factorial = fact(choice)
print("The factorial of %d is %d." % (choice, factorial))

The function works fine, it's just something about setting the return to a variable, or possibly an issue in my print() statement. I'm just coding some random things to help me understand python syntax better.
Edit: the error

Enter a number: 3
Traceback (most recent call last):
  File "practice.py", line 10, in <module>
    factorial = fact(choice)
  File "practice.py", line 8, in fact
    return num * fact(num-1)
TypeError: unsupported operand type(s) for -: 'str' and 'int'
Unmitigated
  • 76,500
  • 11
  • 62
  • 80
  • 1
    `choice = float(input("Enter a number: "))` or `int` instead of `float` – Trenton McKinney Jul 16 '20 at 02:28
  • Python version matters on this question. Are you using python 2.x or 3.x? And notice that last entry in the traceback - its failing on the return from the function. – tdelaney Jul 16 '20 at 02:33

1 Answers1

4

input returns a string which you need to convert to an int.

choice = int(input("Enter a number: "))

Demo

Your example works in Python 2, as input would try to assume the type of the entered value.

Unmitigated
  • 76,500
  • 11
  • 62
  • 80