不能完全確定你所要求的。正如我理解你的問題,你想重構你的腳本,以便階乘的計算是一個函數。如果是的話,就試試這個:
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