2015-10-20 19 views
1

編寫一個Python程序,讀入一系列正整數並寫出所有小於25的整數乘積和所有整數整數大於或等於25.使用0作爲標記值。Python:分離少於25個int和大於25個int輸入,然後使用這些數字

def main(): 
    user_input = 1 
    while user_input != 0: 
     user_input = int(input("Enter positive integers, then type 0 when finnished. ")) 
     if (user_input) < 25: 
      product = 1 
      product = (user_input) * product 
     else: 
      (user_input) >= 25 
      sum = 0 
      sum = (user_input) + sum 

    print('The product off all the integers less than 25 is ', product, "and the sum of all the integers greater than 25 is ", sum, ".") 
main() 

這是我到目前爲止。這是我在計算機科學課上的第一個Python代碼。

我的主要障礙是前哨值必須爲零,並且我的user_input乘以產品,它只是將所有東西都歸零。

+0

你使用numpy的? – EL3PHANTEN

+0

爲什麼不測試零*以前*檢查它是高於還是低於25? – jonrsharpe

+0

您需要在while循環之外初始化您的標記值 – AChampion

回答

0

對您的代碼進行了一些小的更正。

  • 初始化循環外的標記或每次都重置。
  • Else子句語法錯誤和改變爲elif
  • 更名sum不與蟒內置sum
  • 保護product總共乘以零退出衝突。

代碼:

def main(): 
    sum_total, product = 0, 1 
    user_input = 1 
    while user_input != 0: 
     user_input = int(input("Enter positive integers, then type 0 when finnished. ")) 
     if 0 < user_input < 25: 
      product *= user_input 
     elif user_input >= 25: 
      sum_total += user_input 
    print("The product off all the integers less than 25 is ", product) 
    print("The sum of all the integers greater than 25 is ", sum_total) 
+0

非常感謝您,由於顯示器間距的原因,我實際上已將我的輸出窗口縮短,並一直認爲您的代碼已被某些內容忽略。 「所有小於25的整數的乘積是6,並且所有整數的和大於25 ......」 這就是我正在閱讀的所有內容,並且我查閱了大量的教程和示例,爲了我的生活找不到一個錯誤。 elif是我真的不知道,那將是非常有用的。再次感謝。 –

0

您可以隨時檢查標記值是否爲0,如果是這樣,只需將值添加到它。

相關問題