0

I am a programming newbie and, while coding to answer an exercise from a beginner's book I am reading, I forgot to put quotes on a string quit (at line 6) which was supposed to test whether the user wants to quit the infinite loop or not; but instead of giving an error for not defining the variable it just ran without any errors at all.

prompt = "\n Please enter the name of a city you have visited:"

prompt+="\n(Enter 'quit' when you are finished.)"
while True:
    city = str(input(prompt))
    if city == quit:
        break;
    else:
        print("I'd love to go to " , city.title() ,"!")

but why didn't Python raised errors? Instead it ran with out complaining.

This was the output:

Please enter the name of a city you have visited:
(Enter 'quit' when you are finished.)Istanbul 
I'd love to go to  Istanbul  !

Please enter the name of a city you have visited:
(Enter 'quit' when you are finished.)Tokoyo
I'd love to go to  Tokoyo !

Please enter the name of a city you have visited:
(Enter 'quit' when you are finished.)quit
I'd love to go to  Quit !

Please enter the name of a city you have visited:
(Enter 'quit' when you are finished.)

I am just curious because Python was supposed to give errors every time you try work with undefined variable but why was this time there was an exception?

I apologize for my bad English.

Thomas Baruchel
  • 7,236
  • 2
  • 27
  • 46
  • Shouldnt that be `if city == "quit"`? Note quotes. Also, you dont really need `else` after `break` – urban Jan 03 '20 at 09:19
  • 1
    Check here https://stackoverflow.com/questions/19747371/python-exit-commands-why-so-many-and-when-should-each-be-used. Pretty much quit is already defined by default as a hint to let people know how to quit python. – André Cascais Jan 03 '20 at 09:19
  • 1
    @urban - Thats what the op's question is about. – Sayse Jan 03 '20 at 09:20
  • `quit` is a reserved word in Python and you can check that by doing `type(quit)`. The output will be ``. – accdias Jan 03 '20 at 09:24
  • quit it a function in python by default – Kevin Omar Jan 03 '20 at 09:25

2 Answers2

0

Actually quit is a perfectly valid Python object; type:

help(quit)

or

type(quit)

and read about it. The interpreter should not raise any undefined object exception in your code since quit is well defined.

Thomas Baruchel
  • 7,236
  • 2
  • 27
  • 46
0

quit is a built-in function. If you are writing in an ide it should be a different color from other variables.

Your comparison will always be wrong, since you are comparing a string with a function object.

Minix
  • 247
  • 4
  • 17