-1

I started an introduction to Python course in september and I've barely been keeping up. This week the assignment has left me in a fritz. I have gotten help from my teacher and tried my best to use my resources before its overdue so I'm getting a little bit of an understanding but it just isn't clicking for me. I've made a lot of corrections over the week so my code is looking better than it was but I still don't understand what I'm doing wrong.

Instead of creating a factorial for n it is just displaying n as the input value from the user. I have tried entering factorial(n) on various lines and it only gives me an EOF error. Could someone explain what I'm doing wrong? my belief is that i need to call the factorial function, but I can't seem to format it correctly.

def factorial(n):
    if n==0:
        return 1
    else:
        recurse = factorial(n-1)
        result = n * recurse
        return result




done=False
while not done:
    n=input('Enter a Positive Integer \n>>>')
    try:
        n=int(n)
        if n>=0:
            done=True
    except:
        print('try again')

print('n is ', n)
  • You say you "have tried entering factorial(n) on various lines" - can you give us an example of the one attempt you thought most likely to succeed? What result did that give you and what did you expect? – Grismar Oct 11 '20 at 23:37
  • Does this answer your question? [Function for Factorial in Python](https://stackoverflow.com/questions/5136447/function-for-factorial-in-python) – Harshit Oct 12 '20 at 07:39

2 Answers2

1

Simple fix.

def factorial(n):
    if n==0:
        return 1
    else:
        recurse = factorial(n-1)
        result = n * recurse
        return result




done=False
while not done:
    n=input('Enter a Positive Integer \n>>>')
    try:
        n=int(n)
        if n>=0:
            done=True
    except:
        print('try again')

print('n is ', factorial(n))
0

In order to get the factorial of n you need to call the function. For example: res = factorial(n)

Hadar Shavit
  • 107
  • 1
  • 11