I'm trying to learn Python, but it's not going well. I wrote this, but it doesn't work. I've found examples that do work, but when I compare them I don't get what I'm doing different.
def fact(x):
x = int(input("enter number: "))
if x == 0:
return 1
return x * fact(x - 1)
print(fact(x))
I want it to ask for the user's input and then find the factorial of it. What am I doing wrong?
Picachieu
3,82010 gold badges29 silver badges47 bronze badges
2 Answers 2
Asking the user for the input should occur outside the factorial function.
I renamed the user input to y here, to make it clear x and y are different variables.
def fact(x):
if x == 0:
return 1
return x * fact(x - 1)
y = int(input("enter number: "))
print(fact(y))
answered Oct 12, 2018 at 16:42
AKX
171k17 gold badges148 silver badges230 bronze badges
Sign up to request clarification or add additional context in comments.
5 Comments
marklar
I dont get it, I just copy pasted your code into python3 console and it doesnt work iI get this when I try to run it. Type "help", "copyright", "credits" or "license" for more information. >>> def fact(x): ... if x == 0: ... return 1 ... return x * fact(x - 1) ... >>> y = int(input("enter number: ")) enter number: print(fact(y)) Traceback (most recent call last): File "<stdin>", line 1, in <module> ValueError: invalid literal for int() with base 10: 'print(fact(y))' >>>
Sheldore
Works fine for me
marklar
if I save it and run it as a file it works if I try to write it in the python console it doesnt, why?
javajav
@marklarbecause the python console takes a line of code, not a whole program.
AKX
According to the lines above, @marklar, you are pasting the last line ("print(fact(y))") at the "enter number: " prompt that appears once you've pasted the "input" line.
if you are executing in console then try in below format, it should work:
def fact(x):
if x == 0:
return 1
return x * fact(x - 1)
print(fact(int(input("enter number: "))))
answered Oct 12, 2018 at 16:57
Raj Naik
871 gold badge2 silver badges9 bronze badges
Comments
lang-py
factis supposed to take an argument, 'x'. You callfact(x)butxis not defined. Also, you probably don't want to take input and redefinexinside of thefactfunction.