[英]How to accept an answer from two if statements in python
我對python代碼中的嵌套if語句有疑問。 我想知道我是否可以在while循環中有兩個if語句,並且兩個語句都在內部嵌套一個if語句。 這樣,該人員將能夠從嵌套的if語句中進行回復,或者從while循環中的if語句中進行回復。 對我的代碼的任何想法將不勝感激。
這是我嘗試制作的游戲的代碼示例。 我正在嘗試學習並將新技能納入其中,因此這是我的問題。
有沒有一種方法可以確保當我在問題輸入中鍵入“向前看”時,對於第二個輸入,我說“向后看”而不是“去那里”,那么該輸入可能是問題輸入而不是move_on輸入?
def first_room():
print("Your in a room how to get out...")
next_room = True
while next_room:
question = input()
if question == "look forward".lower():
print("You are looking forward")
move_on = input()
if move_on == 'go there'.lower():
next_room = False
second_room()
else:
pass
if question == 'look backward'.lower():
print("You are looking backward")
move_on = input()
if move_on == 'go there'.lower():
next_room = False
third_room()
else:
pass
def second_room():
print("This is the second room")
def third_room():
print("This is the third room")
first_room()
我可以測試,但我認為可能是這樣
我使用帶有True/False
變量來記憶游戲的"state"
順便說一句:如果您在另一個功能中運行一個房間,您將具有隱藏的“遞歸”。 最好返回函數名稱(不帶()
)並在函數外部運行它。
def first_room():
print("Your in a room how to get out...")
looking_forward = False
looking_backward = False
while True:
question = input().lower()
if question == "look forward":
if not looking_forward:
print("You are looking forward")
looking_forward = True
looking_backward = False
else:
print("You are already looking forward, so what next")
elif question == 'look backward':
if not looking_backward:
print("You are looking backward")
looking_forward = False
looking_backward = True
else:
print("You are already looking backward, so what next")
elif question == 'go there':
if looking_forward:
return second_room # return function name to execute outside
if looking_backward:
return third_room # return function name to execute outside
else:
print('Go where ???')
def second_room():
print("This is the second room")
def third_room():
print("This is the third room")
# --------------------------------
next_room = first_room # assign function without ()
while next_room is not None:
next_room = next_room() # get function returned from function
print("Good Bye")
受到furas關於遞歸的評論的啟發,我想知道如何處理具有通用功能的任何房間。 在當前設計中,許多房間需要許多功能,這些功能將一遍又一遍地使用許多相同的代碼。 如果每個房間在某種程度上都是“特殊的”,需要特定的代碼,這可能是不可避免的。 另一方面,如果您有一種通用的方式來瀏覽房間,則可以節省很多工作。
所以我在想,也許您可以以某種常見的形式存儲房間屬性,並具有一個一般功能,要求玩家輸入並建議他們可以做什么。 作為“通用格式”,我在這里選擇了一個詞典列表,確定它是最容易使用的詞典。
每個列表索引(零索引為+1)對應一個房間號,例如roomlist[0]
是第一個房間。 每個字典都存儲了我們需要了解的有關房間的信息,例如,您可以看到哪些方向以及該方向連接到哪個房間。 稍后,您還可以使用有關每個房間的其他信息來擴展字典。 (例如某些房間的特色)
我對此的嘗試:
# Room dictionaries: Each key is a direction and returns the
# room number it connects to. E.g. room1 'forward' goes to room2.
room1 = {'forward': 2,
'backward': 3}
room2 = {'forward': 4,
'backward': 1,
'left': 3}
room3 = {'forward': 5,
'backward': 1,
'right': 2}
roomlist = [room1, room2, room3]
def explore_room(roomindex, room):
# roomindex is the list index (not room number) of the selected room.
# room is the dictionary describing the selected room.
question = None
move_on = None
print("You are in room %s, how to get out..." % (roomindex+1))
# Room number added to help you keep track of where you are.
next_room = True
while next_room:
if question == 'exit' or move_on == 'exit':
break
# If the user replied 'exit' to either question the loop breaks.
# Just to avoid an infinite loop.
question = input().lower()
# Added the .lower here so we don't have to repeat it in each if.
# Pick a direction. The response must be valid AND
# it must be a valid direction for the current room.
if question == "look forward" and 'forward' in room.keys():
print("You are looking forward")
direction = 'forward'
elif question == 'look backward' and 'backward' in room.keys():
print("You are looking backward")
direction = 'backward'
elif question == 'look left' and 'left' in room.keys():
print('You are looking to the left')
direction = 'left'
# ...
else:
print('There is nowhere else to go!')
continue
# Start the loop over again to make the user pick
# a valid direction.
# Choose to move on or stay put.
move_on = input().lower()
if move_on == 'yes':
roomindex = room[direction]-1
# Direction is the dictionary key for the selected direction.
# Room number is roomindex-1 due to zero-indexing of lists.
return roomindex
# Exits explore_room and tells you which room to go to next.
elif move_on == 'no':
continue # Ask for a new direction.
else:
print('Please answer yes or no')
continue # Ask for a new direction.
return None
# No room selected. While return None is implicit I included it here for clarity.
roomindex = 0
while True:
if roomindex is None:
# User exited the function without choosing a new room to go to.
break
roomindex = explore_room(roomindex, roomlist[roomindex])
您在1號房,如何下車...
向前看
你很期待
是
您在2號房,如何下車...
看左邊
您正在向左看
是
您在3號房,如何下車...
向后看
你回頭看
是
您在1號房,如何下車...
退出無處可去!
>
我承認,是/否不是最受啟發的方法。 無論如何,您可能想將實際問題添加到輸入中,以便播放器可以告訴您對它們的期望。 但總的來說,這似乎可行,您可以輕松地添加和互連任意數量的房間。 所有這些都應該僅使用一種功能。
關於if的鏈接和嵌套:嵌套的if通常是可以的,但是正如furas所說的那樣,它們可能會失去控制並膨脹您的代碼。 但是,根據您的情況,您不需要嵌套的ifs。 如我的示例所示,您可以先問路,然后檢查玩家是否想單獨去那里。 兩者是完全獨立的,因此不需要嵌套語句。
一個基本的單問題變體,再次受到furas原始答案的啟發:
def explore_room(roomindex, room):
# roomindex is the list index of the selected room.
# room is the dictionary describing the selected room.
question = None
print("You are in room %s, how to get out..." % (roomindex+1))
# Roomnumber added to help you keep track of where you are.
next_room = True
while next_room:
if question == 'exit':
break
# If the user replied 'exit' to either question the loop breaks.
# Just to avoid an infinite loop.
question = input('Choose an action: ').lower()
# Added the .lower here so we don't have to repeat it each time.
# Pick a direction. The response must be valid AND
# it must be a valid direction in this room.
if question == "look forward" and 'forward' in room.keys():
print("You are looking forward")
direction = 'forward'
elif question == 'look backward' and 'backward' in room.keys():
print("You are looking backward")
direction = 'backward'
elif question == 'look left' and 'left' in room.keys():
print('You are looking to the left')
direction = 'left'
# ...
elif question == 'move':
roomindex = room[direction]-1
return roomindex
# Fails if player selects 'move' before picking a direction.
# It's up to you how you want to handle that scenario.
else:
print('Valid actions are "look forward/backward/left/right" and "move". Enter "exit" to quit.')
continue
# Start the loop over again to make the user pick
# a valid direction.
return None
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.