【发布时间】:2020-07-31 05:39:57
【问题描述】:
我正在尝试为快速的事情创建一个交互式故事代码,而我的布尔值似乎没有在我的代码中从 true 变为 false。 这里是:
age = input ("Type in your age")
print("You're bored during quarantine and decide to go visit a haunted house alone. You visit the house, open the door, and walk in.")
print("You are in front of a creepy door in a hallway.")
print("What do you want to do?")
action = input ("Type: in, left, or right. Then click OK or press enter")
survive = False
def survival():
if age%2 == 0:
survive = False
else:
survive = True
survival()
if action == "in":
print("You choose to go in.")
print("The room is pitch black")
if survive == False:
print("A monster pops out of the corner and eats you!")
else:
print("You turn the light on and realize that this is just an old bathroom. Gross.")
if action == "left":
print("You choose to turn left.")
print("A ghost appears at the end of the hall.")
if survive == False:
print("The ghost chases you down and haunts your soul forever!")
else:
print("Your eyes mistook you, it was a spiderweb.")
if action == "right":
print("You choose to turn right")
print("A greenish light is visible in the distance")
if survive == False:
print("The light gets brighter and brighter, and you realize it was the headlamp of a ghost coal miner!")
else:
print("You go to check out the light, turns out it's some old christmas lighting still plugged in.")
if survive == False:
print("May your soul rest eternally as you join the other ghosts at the haunted house.")
else:
print("You survived your stay at the haunted house and apparently it's just a house.")
您可以看到我正在尝试获取此人的年龄,如果将其除以 2,则将生存设置为 false。但是,无论您输入什么年龄,如果它是偶数或奇数,您仍然会得到生存 = false。有什么可能出错的想法吗?
【问题讨论】:
-
因为您的函数 merel 创建了一个局部变量。您需要使用
global my_variable来进行全局操作。但你不应该。相反,将函数需要的值作为参数传递给函数,并从函数外部返回所需的值。不要使用可变的全局状态 -
@juanpa.arrivillaga 对不起,我是 python 新手,我不太明白。所以我需要在函数中声明生存布尔值?