![](/img/trans.png)
[英]How to find type of user input and print different values depending on the type of input in Python 3.x
[英]How to compare a user input against multiple OR conditions PYTHON 3.x
如果這是一個愚蠢的問題,請道歉。 我已經做了一些搜索,但一直無法找到我需要的信息。 我對python很陌生。 目前在 Learn Python 3 The Hard Way 課程的中間。
我正在嘗試編寫一個 IF 語句,該語句采用用戶生成的字符串,並將其與列表進行比較,如果匹配,則評估為 True。
我已經能夠成功地做到這一點:
if input in list:
print("That was in the list.")
但是我現在要做的是交換它並使用作為 IF 語句一部分的一次性列表。 我正在做一個 ZORK 風格的游戲,其中房間的門在不同的牆壁等處,所以在這種情況下,擁有一堆具有不同配置的“n”、“s”的永久列表對我來說沒有意義, 'e'、'w' 在其中我必須根據哪些牆有門來引用。 但我不想寫出三個獨立的 elif 評估,它們都做完全相同的事情(如果我為每個房間的每個“禁止”方向寫一個)。希望一切都有意義。
我在某處讀到,您可以將列表放入 IF 語句中,例如 {'up', 'down', 'left'} 但是當我嘗試這樣做時,它說我的“in”評估中沒有字符串:
choice = input("> ")
if {'up', 'down', 'left', 'right'} in choice:
print("You wrote a direction!")
else:
print("Oh bummer.")
您需要做的就是使用列表[]
方括號,而不是花括號(那些用於集合),並且您需要將選擇變量向前移動。 (您希望看到choice
在列表中,而不是相反。)
你的代碼應該是:
choice = input("> ")
if choice in ['up', 'down', 'left', 'right']:
print("You wrote a direction!")
else:
print("Oh bummer.")
錯誤的順序
if choice in {'up', 'down', 'left', 'right'}:
print("You wrote a direction!")
else:
print("Oh bummer.")
編輯:使用集合進行存在檢查通常比列表更有效
您可以使用any()
檢查您的choice
變量中是否存在'up'
、 'down'
、 'left'
、 'right'
字符串中的任何一個:
choice = input("> ")
if any(x in choice for x in {'up', 'down', 'left', 'right'}):
print("You wrote a direction!")
else:
print("Oh bummer.")
輸入格式通常是由程序預先確定的,所以你可能會做這樣的事情:
choice = input("> ")
# assuming the input is always in the format of "go <direction>"
direction = choice.split()[1]
if direction in {'up', 'down', 'left', 'right'}:
print("You wrote a direction!")
else:
print("Oh bummer.")
或者也許你可以使用正則表達式(但這更復雜)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.