2014-10-01 95 views
-1

我需要創建一個將數字中的所有整數相加在一起的程序。爲了enstance,如果我輸入5,程序會看它,就好像它是1 + 2 + 3 + 4 + 5和輸出15.我需要這樣做的任何數字大約爲0.我也必須完成此循環與蟒蛇。這是我到目前爲止。將數字分解爲整數並將它們與python循環一起使用

print("This program calculates the sum of all integers from 1 to the input value.") 
t=0 
x=int(input("Please enter an integer: ")) 
while x>0: 

     print(t) 
x=int(input("Please enter an integer: ")) 
+0

看一看['range'](https://docs.python.org/3.4/library/functions.html#func-range) – inspectorG4dget 2014-10-01 04:48:12

回答

1

python中的range函數在傳遞一個整數時,返回一個從零開始的數字列表。 sum返回列表中所有數字的總和。

所以,從零打印所有號碼的總和x,你可以這樣做:

print(sum(range(x+1)))

0

從1找到總和爲n包括,你可以使用n * (n + 1) // 2公式例如,
n=5: 5 * (5 + 1) // 2 = 15

print("This program calculates the sum of all integers " 
     "from 1 to the input value.") 
while True: 
    x = int(input("Please enter an integer: ")) 
    if x <= 0: 
     break 
    print(x * (x + 1) // 2) # print sum 
相關問題