Python 当中断不起作用时,如何停止循环?
在这段代码中,我希望用户提供数字,跳过字符串,最后我希望在用户键入“完成”时循环,但它不起作用,我在这里做错了什么?首先将输入值分配给变量,以便您可以使用它进行比较并转换为浮点Python 当中断不起作用时,如何停止循环?,python,list,loops,break,Python,List,Loops,Break,在这段代码中,我希望用户提供数字,跳过字符串,最后我希望在用户键入“完成”时循环,但它不起作用,我在这里做错了什么?首先将输入值分配给变量,以便您可以使用它进行比较并转换为浮点 x=[] while True: try: x.append(float(input('what are your numbers?\n'))) if x.append('done'): break except: print('ba
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))
首先将输入值指定给一个变量,这样您就可以使用它进行比较并将其转换为float
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))
当输入“完成”时,此代码不会中断 这会将字符串“done”追加到列表
x
append
返回None
,因此您的条件总是False
<代码>中断将很好地工作——您必须编写代码才能达到目标。在转换为float之前,请检查输入是否有效。在此过程中,检查“完成”:
当输入“完成”时,此代码不会中断 这会将字符串“done”追加到列表
x
append
返回None
,因此您的条件总是False
<代码>中断将很好地工作——您必须编写代码才能达到目标。在转换为float之前,请检查输入是否有效。在此过程中,检查“完成”:
在插入列表之前,您需要首先检查输入是否为
“完成”
,因为如果列表元素中的任何一个不是数字,则max
将引发TypeError
。另外,continue
在实现中是不必要的,因为它是循环中的最后一条语句:
user_input = input('what are your numbers?\n')
if user_input == "done":
break
# Continue checking the input
在插入列表之前,您需要首先检查输入是否为
“完成”
,因为如果列表元素中的任何一个不是数字,则max
将引发TypeError
。另外,continue
在实现中是不必要的,因为它是循环中的最后一条语句:
user_input = input('what are your numbers?\n')
if user_input == "done":
break
# Continue checking the input
您无法对字符串“done”进行浮点运算,因此代码转到except并继续循环如果x.append('done'):要做什么?`顺便说一句,bare
except:
这样的语句是不好的做法,请参阅。您不能对字符串“done”进行浮点运算,因此代码将转到except并继续循环如果x.append('done'):要做什么顺便说一下,像这样的裸语句是不好的做法,请参阅。
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))