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

Time:05-15

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.

CodePudding user response:

Try this:

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

print("'exit' was typed.")

CodePudding user response:

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
  • Related