python - 当输入单词 exit 时,如何使用 if 语句来 break 循环?

我想这样做,以便在输入“退出”一词时循环 breaks 并打印一条消息。你怎么做到这一点?

这是我到目前为止的代码:

file=open("C:/Users/wl/Documents/devices.txt","a")
while True:
    newItem = input('Input the new device:')
    
  
if newItem == 'exit':

我试过在最后一行之后放一个 break ,但它不起作用,所以我假设我做错了什么。

回答1

尝试这个:

newItem = str()
while newItem != "exit":
    newItem = input('Input the new device:')

print("'exit' was typed.")

回答2

这就是您如何使用 break 语句实现您想要的效果:

while True:
    newItem = input('Input the new device:')
    if newItem.lower() == 'exit':
         print('your message')
         break

相似文章

随机推荐

最新文章