2017-02-24 43 views
1

我對這個python編碼是新手。所以,請有人找到這個代碼有什麼問題。使用順序程序給定數字的階乘

def factorial(n): 
    sum=1 
    for i in range(1..n+1): 
     sum=sum*i 
    print(sum) 
    return sum 

v=int(input("enter the number:")) 
factorial(v) 

錯誤我得到:

enter the number:4 
Traceback (most recent call last): 
File "C:/Users/Ramakrishnar/AppData/Local/Programs/Python/Python36/fact.py",line 9, in <module> 
factorial(v) 
    File "C:/Users/Ramakrishnar/AppData/Local/Programs/Python/Python36/fact.py", line 3, in factorial 
for i in range(1..n+1): 
AttributeError: 'float' object has no attribute 'n' 
+0

爲我的range(1,N + 1): –

+0

感謝you.It現在的作品! –

+0

好,祝你好運:) –

回答

0

有兩種方法,你可以寫你的程序。要重新格式化您的代碼,使其處於良好的形式,你可以組織你的程序,像這樣:

def main(): 
    variable = int(input('Enter the number: ')) 
    print(factorial(variable)) 


def factorial(number): 
    total = 1 
    for integer in range(1, number + 1): 
     total *= integer 
    return total 


if __name__ == '__main__': 
    main() 

相反,如果你試圖完成用最少的代碼量同樣的事情,下面兩行會做你同樣的事情:

import math 
print(math.factorial(int(input('Enter the number: '))))