Factorial


#1



Can someone explain what's wrong with my code? It seems to me like it would return the correct answer. I'm guessing it's the formatting and wrong order of commands.

Oops, try again. factorial(2) returned 1 instead of 2


def factorial(x):
    total = []
    answer = 1
    def listing(x):    
        while int(x) > 0:
            total.append(x)
            x -=  1
        return total
    def multiplying(x):  
        for n in total:
            answer *= n
            return answer
    return answer


#2

listing and multiplying are never executed because you never call them


#3

def factorial(x):
    total = []
    answer = 1
    def listing(x):    
        while int(x) > 0:
            total.append(x)
            x -=  1
        return total
    return listing(x)
    def multiplying(x):  
        for n in total:
            answer *= n
            return answer
    return multiplying(x)

I returned both of the functions, but it seems multiplying(x) is omitted, I only get the total list, and not the answer.


#4

a function ends the moment a return keyword is reached, your multiplying reaches a return keyword in the first iteration of the loop, causing the loop to break and the function to end


#5

How can I include both functions and call them without ending the function too soon?


#6

I decide to get rid of the functions, and include everything under factorial(x)
My final code looks like this and it worked!

def factorial(x):
total = []
answer = 1
while int(x) > 0:
total.append(x)
x -= 1
for n in total:
answer *= n
return answer


#7

good choice :slight_smile: good you made it work


#8