簡體   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