2017-07-19 26 views
1
print("enter your age") 
age = int(input()) 
if age < 21: 
    print("no beer") 
if age > 21: 
    print("what beer do you like?") 
    beer = input() 
if beer is "union": 
    print("this is water") 

鍵入union後回答沒有任何反應。爲什麼?提前致謝!!!==與Python中的運算符的區別

+0

參見:[有沒有在Python'=='和'is'之間的差異?](https://stackoverflow.com/questions/132988/is-there-a-difference- Python中的字符串比較:is vs. ==](https://stackoverflow.com/questions/2988017/string-comparison-in-python-is-vs),[爲什麼使用'=='或'is'來比較Python中的字符串有時會產生不同的結果?](https://stackoverflow.com/questions/1504717/why-does-comparing-strings-in-python-using- –

+1

奇怪的是,如果你設置了'beer =「union」',那麼代碼將按預期工作(可能是因爲Python緩存/重用了不可變對象?)。但是,從'input'獲取字符串會產生不同的對象。 –

回答

0

從文檔中的 「是」 運營商:

The operators is and is not test for object identity: x is y is true if and only if x and y are the same object.

只是你的第二最後一行改爲

if beer == "union": 

的代碼會工作。

0

您的代碼中存在一個明顯的錯誤,測試if beer is "union",應該是if beer == "union",不在age > 21檢查下。

也就是說,如果age < 21beer檢查仍然會發生,並且beer將是未定義的,引發異常。

NameError: name 'beer' is not defined

這是一個比較理智:

if age < 21: 
    print("no beer") 
if age > 21: 
    print("what beer do you like?") 
    beer = input() 
    if beer is "union": 
     print("this is water") 
2

有幾件事錯在這裏:

您檢查age < 21age > 21,但如果我恰好21年會發生什麼舊?您需要將>更改爲>=,以便了解此情況(假設您在美國,飲酒年齡爲21歲及以上)。

我注意到的另一件事。如果我不超過21歲會發生什麼?

Traceback (most recent call last): 
    File "beer.py", line 8, in <module> 
    if beer is "union": 
NameError: name 'beer' is not defined 

糟糕。您已定義beer,但如果您未超過21,則此條件永遠不會達到。因此,當您在最後的if聲明中引用beer時,解釋程序不知道您在說什麼。你會想最後if移動第二個裏面:

if age > 21: 
    print("what beer do you like?") 
    beer = input() 
    if beer is "union": 
     print("this is water") 

最後,它不是使用is作爲==運營商的替代品一個明智的想法,因爲他們是不等價的。在這種情況下,beer is "union"的計算結果爲False,而beer == "union"沒有,但在某些情況下,兩個語句在功能上是等效的。例如:

$ python -i 
>>> x = 3 
>>> if x is 3: 
...  print('x is 3!') 
... 
x is 3! 

因此,您的最終代碼應該是這樣的:

print("enter your age") 
age = int(input()) 
if age < 21: 
    print("no beer") 
if age >= 21: 
    print("what beer do you like?") 
    beer = input() 
    if beer == "union": 
     print("this is water") 

編輯:see this answer爲什麼它們是不等價的。 is檢查它們是否是相同的對象,而==檢查值是否相等(這是您想要的)。

+1

'is'運算符在Python中檢查身份。 「啤酒」變量和字符串「聯合」是內存中的不同對象。因此,'is'將永遠不會返回true。 – Jacobm001

+0

@ Jacobm001實際上,'is'通常會返回'True',看起來不可變的對象在某些情況下被重用(儘管不是用'input')。 –

+0

@JaredGoguen:我的意思是在這種情況下 – Jacobm001

0

我覺得這幅圖會清楚地說明「is」和「==」之間的區別。

enter image description here

相關問題