0

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?

2
  • fact is supposed to take an argument, 'x'. You call fact(x) but x is not defined. Also, you probably don't want to take input and redefine x inside of the fact function. Commented Oct 12, 2018 at 16:41
  • 3
    Take the input outside of the function, or else each recurive function call will ask for the input again. Commented Oct 12, 2018 at 16:41

2 Answers 2

1

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))
Sign up to request clarification or add additional context in comments.

5 Comments

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))' >>>
Works fine for me
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?
@marklarbecause the python console takes a line of code, not a whole program.
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.
0

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: "))))

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.