Using a While Loop for 5. factorial


#1



https://www.codecademy.com/en/courses/python-intermediate-en-rCQKw/0/5?curriculum_id=4f89dab3d788890003000096#


I have created a function factorial(x) that aims to use a while loop to calculate and return the factorial of the argument x. However, when I submit this function, I receive the error message "Oops, try again. factorial(3) returned 3 instead of 6."

Here is my explanation of the function/what I expect to happen: At the beginning of the function, two variables are created: "num," which has x as its value, and "empty," which has a value of 1. The while loop is introduced so that, as long as the value of num is greater than 0, the result of the multiplication of num by empty will be stored as the new value of empty, the value of num will be decreased by 1, and the resulting value of num will be returned. When num is no longer greater than 0, the else statement will return empty.

This is not, however, what happens. An explanation of why this function doesn't work would be much appreciated. :slight_smile: Thank you!


def factorial(x):
    num = x
    empty = 1
    while num > 0:
        empty = empty * num
        num - 1
        return num
    else:
       return empty


#2

a function ends the moment a return keyword is reached

If a return keyword is reached in a loop, the function needs to end, so the loop will break

so your while loop breaks in its first iteration, is this what you want?

this:

num - 1

will not decrease one, look:

i = 5
print i # 5
print i - 3 # 2
print i # 5
i = i - 3
print i # 2

see how num - 1 only temporary will decrease num (based on the above example)? it doesn't actually update the variable


#3

Ah! This makes sense. I was operating on the incorrect assumption that the return keyword was needed within the loop in order to sort of finalize one iteration of the loop before moving on to the next. (If that makes sense....)

So, I got rid of that return keyword and changed - to -= to decrement. Thank you for your detailed explanations!


#4

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