2014-10-22 22 views
-1

所以我想製作一個程序,使用def來查找階乘。Python:在析因程序中使用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 intro() 
    blah blah 
def main() 
    blah 
main() 

回答

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 
0
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爲獲得階乘