有幾件事錯在這裏:
您檢查age < 21
和age > 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
檢查它們是否是相同的對象,而==
檢查值是否相等(這是您想要的)。
參見:[有沒有在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- –
奇怪的是,如果你設置了'beer =「union」',那麼代碼將按預期工作(可能是因爲Python緩存/重用了不可變對象?)。但是,從'input'獲取字符串會產生不同的對象。 –