简体   繁体   English

当中断不起作用时如何停止循环?

[英]How can i stop a loop when break does not work?

x=[]
while True:
    try:
        x.append(float(input('what are your numbers?\n')))
        if x.append('done'):
            break
    except:
        print('bad data')
        continue
print(len(x), sum(x), min(x), max(x))

In this code I want the user to provide numbers, skip strings and finally I want the loop when the user types in 'done' but it does not work, what am I doing wrong here?在这段代码中,我希望用户提供数字,跳过字符串,最后我希望在用户输入“完成”时进行循环,但它不起作用,我在这里做错了什么?

Assign the input value to a variable first, so you can use it for the comparison and cast to float.首先将输入值分配给变量,以便您可以将其用于比较并转换为浮点数。

x=[]

while True:
    inp = input('what are your numbers?\n')
    if inp == 'done':
        break
    try:
        x.append(float(inp))   
    except ValueError:
        print('bad data')

print(len(x), sum(x), min(x), max(x))

This code does not break when the input is `"done"当输入“完成”时,此代码不会中断

    if x.append('done'):
        break

This appends the string "done" to the list x .这会将字符串 "done" 附加到列表x append returns None , so your condition is always False . append返回None ,因此您的条件始终为False break will work just fine -- you have to write your code to get there. break会工作得很好——你必须编写代码才能到达那里。 Check the input for validity before you convert to float.在转换为浮点数之前检查输入的有效性。 During this process, check for "done":在此过程中,检查“完成”:

    user_input = input('what are your numbers?\n')
    if user_input == "done":
        break
    # Continue checking the input

you need to check first if the input is 'done' before inserting to your list, because max will raise TypeError if any of list elements is not a number.在插入列表之前,您需要先检查输入是否'done' ,因为如果任何列表元素不是数字, max将引发TypeError Also continue is unnecessary in your implementation because it is last the statement in your loop:在您的实现中也不需要continue ,因为它是您循环中的最后一条语句:

x=[]
while True:
    try:
        data = input('what are your numbers?\n')
        if data == 'done':
            break
        else:
            num = float(data)
            x.append(num)
    except:
        print('bad data')

print(len(x), sum(x), min(x), max(x))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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