Write a program with a function to find the factorial of n. Requires n to be obtained from system parameters.

The following is a program written in Python to calculate the factorial of n:

import sys

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

if __name__ == '__main__':
    n = int(sys.argv[1])
    result = factorial(n)
    print(result)

The above code first imports the sys module and then defines a function named factorial. This function calculates the factorial recursively and returns 1 when n is equal to 0, otherwise it calculates the factorial of n times (n-1). The recursion ends when n decreases to 0. __name__The property checks if the module was invoked directly, and if the script is executed directly, takes the second argument as n from the command line and prints the result.

It should be noted that before running the program on the command line, you need to install Python and configure its environment variables correctly. Then save the code as a .py format file, and then call the Python interpreter on the command line to run the program. The specific instruction is python file name.py n, where n is the value of the factorial to be calculated.

Guess you like

Origin blog.csdn.net/qq_51447496/article/details/130734219