我對 Python 很陌生,所以我在做作業時遇到了麻煩。我需要創建一個程式來添加用戶輸入的未指定數量的正數,如果用戶輸入零或負數,程式將停止。然后它列印出總數。我認為我的代碼的問題在于它沒有回圈。請幫我解決這個問題,謝謝。
def again():
c = 0
a = int(input("a"))
if a >= 1:
b = int(input("b"))
while a and b >= 1:
if b >= 1:
c = (a b)
print("Result",c)
again()
break
if a >= 0 and b >= 0:
break
again()
uj5u.com熱心網友回復:
你的邏輯syntax有一些錯誤,很難理解。希望下面的代碼片段可以幫助您:
def again():
# ask user to input a number:
total = 0 # to sum up all entering numbers...
while True:
x = int(input('Please enter a positive number, or zero/negative to "Exit": '))
if x > 0: total = x
elif x <= 0: # see negative number
print(f' total: {total} ')
break
again()
運行(并輸入數字)
Please enter a positive number, or negative to "Exit": 1
Please enter a positive number, or negative to "Exit": 2
Please enter a positive number, or negative to "Exit": 3
Please enter a positive number, or negative to "Exit": 4
Please enter a positive number, or negative to "Exit": 5
Please enter a positive number, or negative to "Exit": -1
total: 15
uj5u.com熱心網友回復:
以下是一個簡短的解決方案,但您的課程可能不允許此解決方案。它的作業原理是制作一個生成器(基本上是一個由函式而不是記憶體中的資料定義的可迭代物件)并將其求和。
def get_nums():
while True:
x = int(input("Enter a number: "))
if x > 0: yield x
else: break
print(sum(get_nums()))
uj5u.com熱心網友回復:
只需將您的“again()”函式放在一個while回圈中,如下所示:
while True:
again()
希望這能回答你的問題。
編輯:如果我沒有回答你的問題,你至少可以告訴我,而不是拒絕我的回答。
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/484154.html
標籤:Python
上一篇:將一個串列中的每個值分配給具有不同索引數的另一個串列
下一篇:在txt檔案中查找最長的單詞
