简体   繁体   中英

Why doesn't this python program give errors for comparing with an undefined variable

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.

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.

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.

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