I am trying to write a simple factorial
function in Python, but upon execution, this one merely does nothing and inherently crashes the console for some bizarre reason.
Please bear in mind that I only began coding with Python about a week ago, and am used to using other lower level OOP languages, so please excuse any obvious mistakes.
Here is 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
The function merely prints nothing and refuses any further input.
Try with this function: (works with n >= 0)
def factorial(n):
r = 1
i = 2
while i <= n:
# Use shorter version
r *= i
i += 1
return r
Or (works with n > 0)
def factorial(n):
i = n
while i > 1:
i -= 1
n *= i
return n