1

I'm using python and I'm trying to detect if someone types quit, then stop the program.

Here is my code:

print('')

while True:
    inpt = input('>>> ')
    if inpt is 'quit':
        print(':(')
        break

I run it and it doesn't work. I proceeded to try this code:

print('')

while True:
    inpt = input('>>> ')
    if inpt is 'test':
        print(':(')
        break

To see if it has something to do with the word quit, but it didn't work either. Then I tried this code:

print('')

while True:
    inpt = input('>>> ')
    if inpt is 't':
        print(':(')
        break

And it worked, but I don't know why. Does anyone know how to get quit to work?

OneCricketeer
  • 179,855
  • 19
  • 132
  • 245
Zoe
  • 85
  • 9
  • 3
    You need to use `==` not `is`. `is` checks for identity, `==` checks for equality. It happens to work for `'t'` because Python interns small string literals. – juanpa.arrivillaga Apr 15 '17 at 18:14
  • See [here](http://stackoverflow.com/questions/132988/is-there-a-difference-between-and-is-in-python) and [here](http://stackoverflow.com/questions/15541404/python-string-interning) – juanpa.arrivillaga Apr 15 '17 at 18:17
  • If your question is solved, please choose the answer that solved it instead of editing the subject. – Klaus D. Apr 15 '17 at 18:22
  • Side note: to implement a Python interactive console, use the [`code` module](https://docs.python.org/3/library/code.html). – ivan_pozdeev Apr 15 '17 at 18:54
  • cricket_007 I did it so other people didn't click on this, then realise it was my stupid mistake, having nothing to do with 1 Character Long Strings – Zoe Apr 17 '17 at 06:21

1 Answers1

3

is is an identity operator. It is used to check if two values (or variables) are located on the same part of the memory. Two variables that are equal does not imply that they are identical. To check if inpt contains '>>>' string use either in or == (if you want to be more specific) operator.

'quit' == inpt
mic4ael
  • 7,974
  • 3
  • 29
  • 42