Search code examples
factorialpython-3.4function

Python: Using def in a factorial program


So i am trying to make a program that finds the factorial using def.

changing this:

print ("Please enter a number greater than or equal to 0: ")
x = int(input())

f = 1
for n in range(2, x + 1):
    f = f * n
print(x,' factorial is ',f)

to

something that uses def.

maybe

def intro()
    blah blah
def main()
    blah
main()

Solution

  • Not entirely sure what you are asking. As I understand your question, you want to refactor your script so that the calculation of the factorial is a function. If so, just try this:

    def factorial(x):             # define factorial as a function
        f = 1
        for n in range(2, x + 1):
            f = f * n
        return f
    
    def main():                   # define another function for user input
        x = int(input("Please enter a number greater than or equal to 0: "))
        f = factorial(x)          # call your factorial function
        print(x,'factorial is',f)
    
    if __name__ == "__main__":    # not executed when imported in another script
        main()                    # call your main function
    

    This will define a factorial function and a main function. The if block at the bottom will execute the main function, but only if the script is interpreted directly:

    ~> python3 test.py 
    Please enter a number greater than or equal to 0: 4
    4 factorial is 24
    

    Alternatively, you can import your script into another script or an interactive session. This way it will not execute the main function, but you can call both functions as you like.

    ~> python3
    >>> import test
    >>> test.factorial(4)
    24