Printing the return value of a function in python?

Viewed 80

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'
1 Answers

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.

Related