Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Python by (12.7k points)

I'm attempting to compose a basic factorial function in Python, yet upon execution, this one only sits idle and intrinsically crashes the console for some unusual explanation. 

Kindly remember that I just started coding with Python about seven days prior, and am accustomed to utilizing other lower-level OOP languages, so kindly pardon any undeniable slip-ups.

Look at my current function:

# initialise factorial function:

def factorial(n):

    i = 1 # initialise incrementing variable

    while i < n:

        n = n * i

        i = i + 1

    return n # return result

Here, The function prints nothing.  Kindly help me.

1 Answer

0 votes
by (26.4k points)

Try the below function, which works with n>=0

def factorial(n):

    r = 1

    i = 2

    while i <= n:

        # Use shorter version

        r *= i

        i += 1

    return r

or else, it works with n>0:

def factorial(n):

    i = n

    while i > 1:

        i -= 1

        n *= i

    return n

Are you interested to learn the concepts of Python? Join the python training course fast!

Watch this video tutorial on how to become a professional in python

Related questions

0 votes
1 answer
0 votes
1 answer
0 votes
1 answer
asked Dec 17, 2020 in Python by laddulakshana (12.7k points)

Browse Categories

...