Looping in Factorial function


#1

https://www.codecademy.com/courses/learn-python/lessons/practice-makes-perfect/exercises/factorial?action=resume_content_item&link_content_target=interstitial_undefined

Following is the code given for the factorial:

def factorial(x):
    total = 1
    while x>0:
        total = total* x
        x=x-1
    return total

print(factorial(4))

output:24
At first the code I entered was,

def factorial(x):
    total = 1
    while x > 0:
        total = total * x
        x = x - 1
        total = total * x  #line 6
    return total

print(factorial(4))

output:0
however, the line 6 was not needed which I understand. My problem is, the output for the first code gives the correct answer but the output for second code always gives 0.
I do not understand how the output becomes 0 when while loop explicitly has a condition x>0.
Please someone help me understand why. Thank You!


#2

that there is output is even a mystery, given functions only execute when called and there is no function call, its surprising you have output at all

At a function call, see what happens then


#3

I did not include function call because I thought it was implicitly understood when I mentioned output that it is something displayed when tested.


#4

if you don’t know what the test is, you shouldn’t be to bothered by the output. It could be anything.


#5

Alright, I understand. Kindly refer to my edits.


#6

never mind, i need coffee. Sorry about that. I got it wrong. Please forgive me, i human and make mistakes

for the last iteration of the loop x=1, agree? so then we get:

while 1 > 0:

but then inside the loop you decrease x, so x now becomes zero, which we can verify:

def factorial(x):
    total = 1
    while x > 0:
        total = total * x
        x = x - 1
        if x == 0:
            print("x becomes 0, this a problem!")
        total = total * x  #line 6
    return total

print(factorial(4))

anything multiplied with zero becomes zero, which is why you get zero in the output

this problem only occurs in the faulty code because you do a multiplication after reducing x, while you don’t do this in the correct code


#7

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.