我正在撰寫一個代碼來計算用戶在 Python 中輸入的積分平均值。如果用戶連續輸入兩個零并且我已經盡我所能做到這一點,那么回圈應該會中斷,但我很難做到。有人可以幫助我嗎?這是我到目前為止寫的代碼。抱歉英語不好,我是芬蘭的學生:D
months = int(input("Enter the number of months: "))
list = []
loops = 1
for loops in range(1, months 1):
print("Enter the number of credits in month", loops, end="")
credits = int(input(": "))
list.append(credits)
(現在如果學分連續兩次為零)
print("You did have too many study breaks!")
break
loops = 1
average_credits = sum(list) / months
print("Your monthly credit point average is", average_credits, ".")
uj5u.com熱心網友回復:
在將輸入字串轉換為 int 之前,檢查它是否是兩個前導零。
months = int(input("Enter the number of months: "))
list = []
loops = 1
for loops in range(1, months 1):
print("Enter the number of credits in month", loops, end="")
input_str = input(": ")
if input_str == "00":
print("You did have too many study breaks!")
break
credits = int(input_str)
list.append(credits)
loops = 1
uj5u.com熱心網友回復:
我希望這回答了你的問題:
months = int(input("Enter the number of months: "))
count_zeros = 0
list = []
loops = 1
for loops in range(1, months 1):
while count_zeros < 1:
print("Enter the number of credits in month", loops, end="")
if credits == 0:
count_zeros = 1
credits = int(input(": "))
list.append(credits)
loops = 1
else:
print("You did have too many study breaks!")
break
average_credits = sum(list) / months
print("Your monthly credit point average is", average_credits, ".")
uj5u.com熱心網友回復:
這就是我如何解決連續兩個零的問題。
months = int(input("Enter the number of months: "))
list = []
loops = 1
for loops in range(1, months 1):
print("Enter the number of credits in month", loops, end="")
credits = int(input(": "))
# if the length of the list is not 0 (the array is not empty)
# get the last element in the list and check if it is 0
# if it the previous credit was 0, break the loop
if len(list) != 0 and list[-1] == 0:
print("You did have too many study breaks!")
break
list.append(credits)
# loops = 1 - this line is not necessary, the loop will increment automatically in the range
average_credits = sum(list) / months
print("Your monthly credit point average is", average_credits, ".")
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/406298.html
標籤:
下一篇:我需要拆分字串
