首页 > 解决方案 > While 循环停止,输入为空白

问题描述

当 x 输入为空白时,如何使 while 循环停止,而不是在出现“停止”一词时停止?

这就是我所做的,但使用“停止”。但是,如果我将条件更改为 x!=' ',当我尝试将 x 转换为 int 时,它会中断。

x=''
y=''
list=[]
while x!='stop':
    x=input('x input: ')
    y=int(input('y input: '))
    if x!='stop':
        list.append((int(x),y))
    
print('Stop')
print(list)

标签: pythonpython-3.xwhile-loop

解决方案


试试这个

x=''
y=''
list=[]
while x!='stop':
    x=input('x input: ')
    y=int(input('y input: '))
    # break loop when x is empty string
    if x == '':
        break;
    if x!='stop':
        list.append((int(x),y))
    
    
print('Stop')
print(list)

break如果关键字为空字符串,则中断循环。x在将变量x转换为int.


推荐阅读