使用 while 循环编写一个程序,计算输入数字的平均值,并使用 break 语句退出循环。

3
我想写一个程序,使用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

1
在调用 float() 函数之前,您需要检查输入是否为空。 - John Gordon
欢迎来到 Stack Overflow。请阅读 [导览] 和 [提问]。如果您能描述当前代码中的错误(错误信息是什么?输出结果不正确?),那将会很有帮助。 - Pac0
4个回答

1

请注意,函数input()始终输出一个字符串,因此type(input()) != int永远是真的。

当出现ValueError(例如无法将空白/字母转换为浮点数)时,请尝试使用try-except函数,将会引发异常并中断循环:

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

输出:

Enter your number here:  3
Enter your number here:  4
Enter your number here:  5
Enter your number here:  
Average:  4.0

谢谢您,永久学生。我使用了您的代码并尝试使用相同的值3、4、5,但结果为3。此外,我还尝试了1.5、2和2.5,按Enter键后它给出了1.5作为值。不太确定这是怎么发生的。 - Krys
是的,因为错误发生在步骤k+=1之后,所以会有一个额外的数字(错误地)添加到k中。我已经更新了我的答案,请看一下。 - perpetualstudent
现在这个对你来说工作了吗? - perpetualstudent

0
考虑到已经提出的评论,这里是一种执行任务并在遇到空白条目时完成的方法。
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

如评论中所指出的,我们应该在尝试转换输入之前检查是否存在空行条目。

你好,NoDakker!非常感谢你的帮助。我尝试了你的程序,但它显示“ValueError: could not convert string to float: ''”。我尝试了1.5、2和2.5这些值来计算平均值为2,但都没有成功。 - Krys
你没有检查空行,你正在检查只有一个空格的行。 - Uncle Dino

0
你立即将输入的x值转换为浮点数。因此,
如果 type(x) != int
始终为真,这意味着循环每次迭代后都会中断。

0

其他人已经用不同的方法解决了你的问题,但我认为解释我们的思路也可能有用。

目前,你的程序没有正确检查退出条件(输入空行而不是数字)。当输入新行时,你的程序应该执行以下两种可能的情况之一:

  • 当输入空行时:打印结果并退出(break)
  • 否则(假设输入数字):将数字加入总数

没有指定第三个选项,所以现在让我们假设每一行都是空行或数字。稍后再扩展它。

在你决定要做什么之后,这些操作应该很容易地包含在一个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()函数会出错,使你的程序崩溃。

检查一个字符串(输入的行)是否可以转换为浮点数有点困难。Python中没有内置的转换方法,但有一个技巧:你可以尝试将其转换为浮点数,如果成功,则说明可以转换,如果出错,则无法转换。还有其他方法,但这是最简单的方法-参见此问题上的主题。
在这种情况下,每个数字都会被添加到总数中,每个非数字(包括空行,以及像“asdf”这样的随机字符串)都会导致程序计算总数并停止。

您可以通过使用breakcontinue来避免将两种情况放入if-else块中。(技术上讲,您从不需要使用breakcontinue,所有程序都可以在没有它们的情况下编写。在这种情况下,您可以使用一个布尔变量,例如命名为run,编写while run:,并且在不使用break的情况下,执行run = False)。您可以利用breakcontinue都会提前结束循环的事实,避免将第二种情况放在else块内,仍然具有相同的行为(因为breakcontinue已经导致跳过其余的循环体)。

因此,以下是一个示例实现:(测试== "",不使用非结构化控制流)

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重命名为countx重命名为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变量,并使用格式化字符串打印出更加漂亮的结果。

以下是同时使用continuebreak的示例:

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!")

哇!这真是帮助我更好地理解了一些!谢谢你,Sasszem。 - Krys

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接