[英]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.