简体   繁体   English

使用 while 循环查找输入数字的平均值并使用 break 语句退出循环的程序

[英]A program that uses while loop to find average of numbers inputted, and uses a break statement to exit the loop

I would like to write a program that uses a while loop to repeatedly prompt the user for numbers and adds the numbers to a running total.我想编写一个程序,该程序使用 while 循环反复提示用户输入数字并将数字添加到运行总数中。 When a blank line is entered, the program should print the average of all the numbers entered.当输入一个空行时,程序应该打印所有输入数字的平均值。 I also would like to use a break statement to exit the while loop.我也想使用break 语句来退出 while 循环。

My Incorrect Work:我的错误工作:

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

Bearing in mind the comments already made, here is one such way to perform your task and finishing up when a blank entry is encountered.请记住已经发表的评论,这是执行任务并在遇到空白条目时完成的一种方法。

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

As noted in the comments, one should check for the blank line entry prior to attempting to convert the entry.如评论中所述,应在尝试转换条目之前检查空白行条目。

You are immediately casting the value of x that is inputted to a float.您立即将输入的 x 值转换为浮点数。 So,所以,

if type(x) != int

always is true, meaning the loop breaks after one iteration every time.总是为真,这意味着循环在每次迭代后中断。

Be aware that the function input() will always outputs a string, so type(input()) != int will always be true.请注意,function input()将始终输出字符串,因此type(input()) != int将始终为真。

Try using try-except function, when there is ValueError (example unable to convert blank/letters to float), the exception will be raised and break the loop:尝试使用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: Output:

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

Others have already solved your problem in different ways, but I think that explaining our thinking might also be useful.其他人已经以不同的方式解决了你的问题,但我认为解释我们的想法也可能有用。

Currently, your program is not checking correclty the exit condition (empty line is entered instead of a number) .目前,您的程序未正确检查退出条件(输入的是空行而不是数字) When a new line is entered, your program should do one of the two possible scenarios:输入新行时,您的程序应该执行以下两种可能的情况之一:

  • when an empty line is entered: print result & exit (break)输入空行时:打印结果并退出(中断)
  • else (assume a number is entered): add number to total否则(假设输入了一个数字):将数字添加到总数中

No third option is specified, so for now, let's assume that every line will either be an empty line or a number.没有指定第三个选项,所以现在,让我们假设每一行要么是空行,要么是一个数字。 Will expand it later.以后会展开的。

After you decided what to do, the actions should just be easily wrapped in a while True: block - so it should be:在你决定要做什么之后,动作应该很容易被包裹在一段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

With only two options, you only need to decide once what to do.只有两个选项,您只需要决定一次要做什么。 You can swap around the cases by deciding which condition to check for (and that also results in the other being the "default" behavior for other cases).您可以通过决定检查哪个条件来交换案例(这也导致另一个是其他案例的“默认”行为)。

It's simpler to check for the line being empty with if line_entered == "": .使用if line_entered == "":检查该行是否为空更简单。 In this case, any non-empty line is treated like a number, and if it were not one, the float() function will error out and your program crashes.在这种情况下,任何非空行都被视为一个数字,如果不是一个, float() function 将出错并且您的程序崩溃。

Checking if a string (the entered line) can be converted to a float is a bit harder.检查字符串(输入的行)是否可以转换为浮点数有点困难。 There is just no built-in for that in python, but there is a trick: you can try to convert it to a float, and if that works, it was convertible, and if that errors, it was not. python 中没有内置的,但有一个技巧:您可以尝试将其转换为浮点数,如果可行,则它是可转换的,如果出现错误,则不是。 There are other ways too, but this is the simplest - see this question on the topic.还有其他方法,但这是最简单的 - 请参阅有关该主题的这个问题
In this case, every number will be added to the total, and every non-number (including the empty line, but also random strings like "asdf") will cause the program to calculate the total and stop.在这种情况下,每个数字都将被添加到总数中,并且每个非数字(包括空行,还包括“asdf”之类的随机字符串)都会导致程序计算总数并停止。

You can avoid putting both cases into an if-else block by using break or continue .您可以通过使用breakcontinue来避免将这两种情况都放入 if-else 块中。 (technicly, you never need to use break or continue , all programs can be written without them. In this case, you could have a boolean variable, named run for example, write while run: and instead of break , do run = False ). (从技术上讲,你永远不需要使用breakcontinue ,所有程序都可以在没有它们的情况下编写。在这种情况下,你可以有一个 boolean 变量,例如名为run ,写while run:而不是break ,做run = False ) . You can use the fact that both break and continue end the loop early to avoid placing the second case inside an else-block and still have the same behavior (as break and continue already causes skipping the rest of the loop body).您可以使用breakcontinue提前结束循环的事实,以避免将第二种情况放在 else 块中并且仍然具有相同的行为(因为breakcontinue已经导致跳过循环体的 rest)。

So an example implementation: (testing for == "" , not using unstructured control flow)所以一个示例实现:(测试== "" ,不使用非结构化控制流)

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

I also renamed k to count , x to line and used in-place addition operators.我还将k重命名为countx重命名为line并使用了就地加法运算符。

Another implementation, with break, testing for float with try/except (and re-using that for the entire control flow):另一种带有中断的实现,使用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

Here I removed the run variable, and used a format string to print a bit fancier.在这里,我删除了run变量,并使用格式字符串打印了一些花哨的东西。

And an example using both continue and break :还有一个同时使用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

You can fancy it a bit with adding more error handling - use three cases:您可以通过添加更多错误处理来稍微幻想一下 - 使用三种情况:

  • user entered empty line: print & exit用户输入空行:打印并退出
  • user entered a number: add to total用户输入了一个数字:加到总数中
  • user entered something else: ignore line, but tell user what to do用户输入了其他内容:忽略行,但告诉用户该怎么做

I only provide one example implementation for this, but as you can see, it can be implemented in many ways.我只为此提供了一个示例实现,但正如您所见,它可以通过多种方式实现。

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM