2016-03-08 26 views
1

我正在編寫一個應該添加用戶輸入的所有正值的程序,程序應該循環直到他/她輸入負數。程序可以平穩地循環,但是它包含總和中的負數。任何幫助表示讚賞!在Python中創建排除

def main():  
    X=0  
    Y=0 

    print("I can add the sum of all positive numbers") 
    X = int (input ("Please enter a positve number between 0 and infinity: ")) 

    if X > 0: 
     while Y >= 0: 
      print("I can add the sum of all positive numbers") 
      Y = int(input("Please enter a positive number between 0 and infinity: ")) 
      X = X + Y 
     print("The sum of the numbers you entered is: ", X) 

    else: 
     print("Sorry I can only add positive numbers") 

main() 

回答

0

讓你輸入之前加X = X + Y數量(但while內)。您初始化了兩個變量,因此在輸入數字之前「額外」添加僅爲X = 0 + 0,並且沒有負面影響。

否則,它會在while循環退出之前再執行一次添加(即使您輸入負數)。 while循環的條件僅在首次嘗試輸入時才被測試,並且每次代碼完成時程序會檢查是否應該執行另一個「循環」。