'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.



Solution 1:[1]

Try this:

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

print("'exit' was typed.")

Solution 2:[2]

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

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 blunova
Solution 2 Hari Prasad