5. Factoral


#1


I am stuck on 5. Factoral

It works and I think it could be written better. It seems sloppy to me. I'm sorry if this gives away the answer to anyone who is currently working on this, I'll delete the post after I get some help.


def factorial(x):
    valuex = int(x)
    iteration = int(x)
    
    while valuex > 1:
        
        iteration *= valuex - 1
        
        valuex -= 1
        
    return iteration
    
   
    
print factorial(2)


#2

believe it or not, your solution is actually quit good. you could consider to do:

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

which is slightly shorter. you rely here on the fact that multiplying by 1 gives the same number.

otherwise you get into complicated solution like recursive function calls:

def factorial(x):
    if x == 1:
        return x
    else:
        return x * factorial(x-1)

this solution is already a lot trickier to understand


#3

Thank you for the input! I didn't know you could put the function inside of the function!

Knowing the rules for python has been my biggest challenge in this course, where I can and can't put certain inputs.

Thanks again! I'm sure I'll have more questions later, I'm very glad there's a large group of people who are so willing to help out!


#4

yea, you can, it is called recursive function call, you can read about it in this topic

Yea, it takes a lot of time to learn programming, you will get there. I also started from scratch.

Sure, you can ask. I will help you, or someone else will :slight_smile:


#5

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