简体   繁体   中英

How to use an if statement to break a while loop when the word exit is typed?

I want to make it so that when the word "exit" is typed the loop breaks and it prints a message. How do you do this?

This is the code I have so far:

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

I've tried putting a break after that last line but it won't work so I'm assuming I'm doing something wrong.

Try this:

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

print("'exit' was typed.")

this is how you can achieve what you want with break statement:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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