LebGeeks

A community for technology geeks in Lebanon.

You are not logged in.

#1 January 6 2016

anonymous
Member

Python code

Every time I try to run this code it gives me errors. I'm trying to make a function that returns the factorial of a number. I need some help:
def factorial(x):
    x>0
    if x == 1 or x==0:
        return 1
    n = x-1
    while n>0:
        n = x-1
        m=0
        m = x*n
        return m
        x-=1
        if n ==1:
            break
print factorial(4)

Offline

#2 January 6 2016

scorz
Member

Re: Python code

I don't know python but this code looks a bit messy.
It should be something like hmm

  def factorial(x):
          if x == 0:
             return 1

          else:
             return x*factorial(x-1)

Offline

#3 January 6 2016

themike10452
Member

Re: Python code

scorz wrote:

I don't know python but this code looks a bit messy.
It should be something like hmm

  def factorial(x):
          if x == 0:
             return 1

          else:
             return x*factorial(x-1)

Yep, that looks more like it. His code was nowhere near functional, I guess he doesn't know python yet either.

Offline

#4 January 6 2016

anonymous
Member

Re: Python code

well yeah I'm still new to python and currently studying it and this should be my homework!
Thanks a lot guys

Offline

#5 January 7 2016

scorz
Member

Re: Python code

@themike
Yeah it's obvious, my guess would be he's new into programming in general.

@anony
No problem. I am not sure if you know that, but what I did is called "recursion".
What you were trying to do is "iteration".

Offline

Board footer