繁体   English   中英

为什么这个 python 程序没有给出与未定义变量进行比较的错误

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

我是一名编程新手,在编写代码以回答我正在阅读的初学者书中的练习时,我忘记在字符串quit (第 6 行)上加上引号,该字符串应该测试用户是否想要退出无限循环或不是; 但是它并没有因为没有定义变量而给出错误,而是完全没有任何错误地运行。

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() ,"!")

但是为什么 Python 没有引发错误呢? 相反,它没有抱怨就跑了。

这是输出:

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

我只是好奇,因为每次尝试使用未定义的变量时,Python 都应该给出错误,但为什么这次会出现异常?

我为我糟糕的英语道歉。

实际上quit是一个完全有效的 Python 对象; 类型:

help(quit)

或者

type(quit)

并阅读它。 解释器不应在您的代码中引发任何未定义的对象异常,因为quit是明确定义的。

quit是一个内置函数。 如果您在 ide 中编写,它应该是与其他变量不同的颜色。

您的比较总是错误的,因为您将字符串与函数对象进行比较。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM