Hi all, Can someone have a look at my code?

Thanks in advance!

The hint seems to be suggesting the use of a recursive function. Such a function returns calls to itself while progressively reducing the input until the base case is reached, that being when it reaches `1`

.

```
>>> def factorial(n):
if n == 0 or n == 1: return 1
while n > 0:
return n * factorial(n - 1)
>>> factorial(7)
5040
>>>
```

We’ve done as the hint suggested and got the result we want to see. The only case we have not tested is less than zero. By definition negative numbers cannot be factorialized. It hasn’t come up yet but if a negative number is passed in our function should raise a fatal error (RangeError). For this practice exercise that level of scrutiny is not asked for so we can trust the lesson checker not to pass in any negative numbers.

Given that we have a recursive solution above, can you solve this problem with an iterative approach, instead for the extra practice? Give it a try.

1 Like

Thanks mtf for the hint. I cheked my code and corrected it to have a correct output.

In my previous code I misplaced the position of factoral.

1 Like

(2) Using our input as the starting point for our factorial ‘result’ seemed like a good way to start.

(3) After that its a check to see if ‘x > 1’. This avoids us multiplying by 0 and ignores the final multiplication by 1 which has no impact.

(4) Then the code iterates over our ‘result’ multiplying the next smaller number in the series

(5) Reduces our value of x by -1

(6) And returns the ‘result’:

```
def factorial(x):
result = x
while x > 1:
result = result * (x-1)
x = x -1
return result
```

2 Likes

def factorial(x):

output = 1

for i in range(1, x+1):

output *= i

return output

Just posting my code because I like it!

I wrote this code: can it be made even shorter?

def factorial(x):
fact_cal = 1
while x > 1:
y = x - 1
fact_cal = fact_cal * x * y
x = x - 2
print (fact_cal)
return fact_cal
factorial(4)

this works:

def factorial(x):

if x == 1:

result = 1

else:

result = x * factorial(x - 1)

return result

This worked for me. Probably one of the first of these exercises where I didn’t reference anything for the solution, so I’d like to ask – is there anything “less elegant” about my solution compared to others in the thread? A response to this might help me with figuring out problems in the future. Thanks!