python - 条件语句在我的 Python 代码中不起作用

标签 python if-statement conditional-statements

这是一次简单的文字冒险尝试。我无法使条件语句按照我希望的方式工作。当给出用户输入时,例如在询问“左”时,它告诉我“左”未定义,即使我在其中列出了它。这是代码。

from time import sleep

name = raw_input("What is your name? ")
live = raw_input("Where do you live? ")

print "%s. You have just come to your senses." % (name)
print "You are in %s, lying in the road." % (live)
sleep (5)

from datetime import datetime
now = datetime.now()

print "You look at your watch. There's a crack in the screen."
sleep (5)
print "Surely it cannot be %s/%s/%s at %s o clock..." % \
(now.day, now.month, now.year, now.hour)
sleep (5)
print "There is light blotting orange onto your closed eyes."
sleep (7)
print "You open your eyes."
sleep (5)
print "you see the road. Scarred, cracked and peppered with dead birds."
sleep (5)
print "Smoke thins out over the horizon."
sleep (5)
print "There is a house you are familiar with, to your right."
sleep (3)
print "There is a road leading uphill to your left."
sleep (3)
print "Where do you turn to?"

answer = raw_input("Type left or right and press Enter.")
if answer == left:
    print "The road winds uphill."
sleep (5)
print "Glass crunches underfoot."
sleep (5)
print "The trees are all bare."
sleep (5)
print "The leaves turned to dust."
print "They are ground into the cracks, between the paving stones."
sleep (5)
if answer == right:
    print "The corridor turns sharply."
sleep (2)
print "You go deeper inside until you can't see anything"
sleep(5)
print "You hear a noise from the floor below."
sleep (5)
print "You can just make out a white doorframe under the staircase."
sleep (5)
answer2 = raw_input("Do you go into the basement? Type yes, or no.")
if answer2 == yes:
    print "The stairs creak. You fumble along the wall for a lightswitch"
sleep (5)
print "Do you press it?"
if answer3 == yes:
    print "Light floods the basement. It leaves you blinded for a few seconds..."
sleep (5)
print "Were you pushed or did you fall?"
sleep (2)
print "No one remembers that day, or any other. The End"
if answer2 == no:
    print "You can't see a thing. You decide to get out back to the street."
sleep (5)
print "Night is falling. You are hopelessly lost."
sleep (20)
sys.exit

最佳答案

if answer == "left":

你需要比较字符串与字符串

if answer == left:

正在尝试将变量 answer 与变量 left 进行比较,python 正确地告诉您没有名为 left 的变量

另一种可能是在顶部定义一个名为 left 的变量

left = "left"

(请记住,这同样适用于您的其他比较)

关于python - 条件语句在我的 Python 代码中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23743299/

相关文章:

PHP If 语句逻辑

Java:if 语句返回的样式问题?

java - 如何从 Condition Autowiring 属性 bean

python 使用函数进行任意切片

python - numpy 的按位运算

python - 断言错误 : array([], dtype=int64) != 数组([], dtype=int64)

javascript - 我们可以在单个三元条件下检查多个值吗?

python - 在 python 中获取 deb 包中的 conffiles 列表

regex - 替换为条件 DTE

file - awk:当文件满足特定条件时 move 文件