Python:在阶乘程序中使用def

时间:2014-10-22 03:17:24

标签: factorial python-3.4 function

所以我试图制作一个使用def找到阶乘的程序。

改变这个:

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)

使用def的东西。

也许

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

2 个答案:

答案 0 :(得分:1)

不完全确定你在问什么。据我了解你的问题,你想重构你的脚本,以便计算阶乘是一个函数。如果是这样,试试这个:

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

这将定义factorial函数和main函数。底部的if块将执行main函数,但前提是直接解释脚本:

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

或者,您可以将脚本import转换为另一个脚本或交互式会话。这样它就不会执行main函数,但您可以根据需要调用这两个函数。

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

答案 1 :(得分:1)

    def factorial(n):            # Define a function and passing a parameter
        fact = 1                 # Declare a variable fact and set the initial value=1 
        for i in range(1,n+1,1): # Using loop for iteration
            fact = fact*i            
        print(fact)              # Print the value of fact(You can also use "return")

factorial(n) // Calling the function and passing the parameter

您可以将任意数字传递给n以获得阶乘