运行此代码时:
print("You wake up with a jolt. \"Damn it's dark in here\"")
print("To the north is the cell door, i think")
print("To the west is a cot, maybe")
print("To the east is a toilet")
print("and to the south is a window, it looks like night time")
cellDoor = False
toilet = False
cot = False
window = False
sawClock = False
while(cellDoor == False or toilet == False or cot == False or window == False):
insideCell = raw_input("Where should i go?").lower()
if insideCell == "north" or "go north" or "walk north":
cellDoor = True
print("I can vaugly make out where the walkway ends and drops to the prison floor")
elif insideCell == "east" or "go east" or "walk east":
toilet = True
print("Ugh, this smells used")
elif insideCell == "west" or "go west" or "walk west":
cot = True
print("<sarcasm> Oh boy, that looks comfortable. I cannot wait to sleep on that </sarcasm>")
elif insideCell == "south" or "go south" or "walk south":
window = True
print("It's night time, I wonder when specifically")
print("I remember a clock on the western wall, i should look there")
while(sawClock == False):
findClock = raw_input("Look at the clock").lower()
if findClock == "look west" or "turn west":
print("It's about 23:00, i should get some sleep, after i finsih exploring, of course")
sawClock = True
print("Let's get some sleep now")
什么时候我打字&#34;去南方&#34;或其他任何东西,它打印的内容只有在键入后才会发生&#34; go north&#34;等等。我需要这样才不会发生,我需要在发出适当的命令时才发生每件事。
目前的输出是:
You wake up with a jolt. "Damn it's dark in here"
To the north is the cell door, i think
To the west is a cot, maybe
To the east is a toilet
and to the south is a window, it looks like night time
Where should i go?south
I can vaugly make out where the walkway ends and drops to the prison floor
Where should i go?north
I can vaugly make out where the walkway ends and drops to the prison floor
Where should i go?west
I can vaugly make out where the walkway ends and drops to the prison floor
Where should i go?east
I can vaugly make out where the walkway ends and drops to the prison floor
Where should i go?
答案 0 :(得分:2)
非空字符串的布尔值始终为true
,因此if insideCell == "north" or "go north" or "walk north":
将始终为真,因为"go north"
为true
。你可以解决它:
if insideCell in ["north", "go north", "walk north"]:
对所有其他ifs或elif进行此更改。
答案 1 :(得分:0)
你做不到:
if insideCell == "north" or "go north" or "walk north":
你应该这样做:
if insideCell == "north" or insideCell == "go north" or insideCell == "walk north":
答案 2 :(得分:0)
在表达式中:
if insideCell == "north" or "go north" or "walk north":
你必须检查所有这些的相等性,而不仅仅是第一个(其他两个“或”总是True
,所以这个条件总是True
)。
检查:“/”是否更容易检查“北”是否在用户输入中,而不是检查,检查:
if "north" in insideCell:
这是更加pythonic的方式,而且它对于用户输入更加强大,即使用户进入“向北走”或“向北旅行”也会工作