[英]My program that uses functions in a while loop does not keep updated values
[英]A program that uses while loop to find average of numbers inputted, and uses a break statement to exit the loop
我想編寫一個程序,該程序使用 while 循環反復提示用戶輸入數字並將數字添加到運行總數中。 當輸入一個空行時,程序應該打印所有輸入數字的平均值。 我也想使用break 語句來退出 while 循環。
我的錯誤工作:
y = "\n"
total = 0
k = 0
while True:
x = input("Enter your number here: ")
x = float(x)
total = total + float(x)
k = k + 1
if type(x) != int:
print(total/k)
break
請記住已經發表的評論,這是執行任務並在遇到空白條目時完成的一種方法。
total = 0.0
k = 0.0
while True:
x = input("Enter your number here: ")
if (x == " "): # Check for a blank line entry here before attempting to convert to float
print("Average is:", (total/k))
break
x = float(x)
total = total + float(x)
k = k + 1
如評論中所述,應在嘗試轉換條目之前檢查空白行條目。
您立即將輸入的 x 值轉換為浮點數。 所以,
if type(x) != int
總是為真,這意味着循環在每次迭代后中斷。
請注意,function input()
將始終輸出字符串,因此type(input()) != int
將始終為真。
嘗試使用try-except
function,當出現 ValueError 時(例如無法將空白/字母轉換為浮點數),將引發異常並中斷循環:
total = 0
k = 0
while True:
x = input("Enter your number here: ")
try:
total += float(x)
k += 1
except ValueError:
if k > 0: #to avoid division by zero
print("Average: ", total/k)
break
Output:
Enter your number here: 3
Enter your number here: 4
Enter your number here: 5
Enter your number here:
Average: 4.0
其他人已經以不同的方式解決了你的問題,但我認為解釋我們的想法也可能有用。
目前,您的程序未正確檢查退出條件(輸入的是空行而不是數字) 。 輸入新行時,您的程序應該執行以下兩種可能的情況之一:
沒有指定第三個選項,所以現在,讓我們假設每一行要么是空行,要么是一個數字。 以后會展開的。
在你決定要做什么之后,動作應該很容易被包裹在一段while True:
塊中——所以它應該是:
initialize_variables_total_and_count
while True:
read_line
decide_what_to_do:
# in case line was a number
convert_line_to_float
add_float_to_total
increment_count
other_case:
# empty line was entered
calculate_and_print
break
只有兩個選項,您只需要決定一次要做什么。 您可以通過決定檢查哪個條件來交換案例(這也導致另一個是其他案例的“默認”行為)。
使用if line_entered == "":
檢查該行是否為空更簡單。 在這種情況下,任何非空行都被視為一個數字,如果不是一個, float()
function 將出錯並且您的程序崩潰。
檢查字符串(輸入的行)是否可以轉換為浮點數有點困難。 python 中沒有內置的,但有一個技巧:您可以嘗試將其轉換為浮點數,如果可行,則它是可轉換的,如果出現錯誤,則不是。 還有其他方法,但這是最簡單的 - 請參閱有關該主題的這個問題。
在這種情況下,每個數字都將被添加到總數中,並且每個非數字(包括空行,還包括“asdf”之類的隨機字符串)都會導致程序計算總數並停止。
您可以通過使用break
或continue
來避免將這兩種情況都放入 if-else 塊中。 (從技術上講,你永遠不需要使用break
或continue
,所有程序都可以在沒有它們的情況下編寫。在這種情況下,你可以有一個 boolean 變量,例如名為run
,寫while run:
而不是break
,做run = False
) . 您可以使用break
和continue
提前結束循環的事實,以避免將第二種情況放在 else 塊中並且仍然具有相同的行為(因為break
和continue
已經導致跳過循環體的 rest)。
所以一個示例實現:(測試== ""
,不使用非結構化控制流)
total = 0
count = 0
run = True
while run:
line = input("Enter your number here: ")
if line == "":
print(total / count)
run = False
else:
total += float(line)
count += 1
我還將k
重命名為count
, x
重命名為line
並使用了就地加法運算符。
另一種帶有中斷的實現,使用try/except
測試float
(並在整個控制流中重新使用它):
total = 0
count = 0
while True:
line = input("Enter your number here: ")
try:
# order matters here. If the first line errors out, the second won't happen so the count will only be inremented if it was indeed a float
total += float(line)
count += 1
except:
print(f"Average is: {total / count}")
break
在這里,我刪除了run
變量,並使用格式字符串打印了一些花哨的東西。
還有一個同時使用continue
和break
的例子:
total = 0
count = 0
while True:
line = input("Enter your number here: ")
if line != "":
total += float(line)
count += 1
continue
print(f"Average is: {total / count}")
break
您可以通過添加更多錯誤處理來稍微幻想一下 - 使用三種情況:
我只為此提供了一個示例實現,但正如您所見,它可以通過多種方式實現。
total = 0
count = 0
# good practice to tell the user what to do
print("Average calcuator. Enter numbers one per line to calulate average of, enter empty line to print result & exit!")
while True:
line = input("Enter your number here: ")
if line == "":
print(f"Average is: {total / count}")
break
else:
try:
total += float(line)
count += 1
except ValueError:
print("You should enter a number or an empty line to calculate & exit!")
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.