我是编程新手,在编写代码以回答正在阅读的初学者的练习时,我忘记在字符串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)
并阅读。解释器不应在代码中引发任何undefined object异常,因为quit
定义良好。
quit
是内置函数。如果您使用ideide编写,则其颜色应与其他变量不同。
您的比较将永远是错误的,因为您正在将字符串与功能对象进行比较。