Python 无法从函数更改全局变量
我试图将我学到的一些东西实现到一个简单的文本游戏中,但是我在尝试更改一个函数中的全局变量以使其在另一个函数中保持不变时遇到了困难Python 无法从函数更改全局变量,python,variables,global,local,Python,Variables,Global,Local,我试图将我学到的一些东西实现到一个简单的文本游戏中,但是我在尝试更改一个函数中的全局变量以使其在另一个函数中保持不变时遇到了困难 keynumb = 0 这是全局变量。我试图在一个函数中将其更改为1,然后在另一个函数中调用它(,如果1打开门,如果0不打开门),等等 我已经试了大约一个小时,直到我的大脑死掉,希望有人能指出我做错了什么 我在代码中的行处添加了星号 干杯 from sys import exit keynumb = 0 def start(): print "You
keynumb = 0
这是全局变量。我试图在一个函数中将其更改为1,然后在另一个函数中调用它(,如果1打开门,如果0不打开门),等等
我已经试了大约一个小时,直到我的大脑死掉,希望有人能指出我做错了什么
我在代码中的行处添加了星号
干杯
from sys import exit
keynumb = 0
def start():
print "You are in a room with two doors in front of you. One on the left, and one on the right."
while True:
door_choice = raw_input("Do you take the left or right door? Your choice: ")
if "left" in door_choice or "Left" in door_choice:
dark_room()
elif "right" in door_choice:
monster_room()
else:
print "I don't understand."
def dark_room():
print "You find yourself in a dark room, unable to see anything."
while True:
dr_choice = raw_input("What do you do?")
if "light" and "switch" in dr_choice or "turn" and "light" in dr_choice:
print "You've turn on the light and the room is illuminated."
print "On the floor is a small silver key."
dr_choice_light = raw_input("What do you do?")
if "pick" in dr_choice_light:
print "You pick up the key and exit back the way you came."
keynumber() *************
start()
elif "nothing" in dr_choice_light:
print "You do nothing. Nothing happens."
elif "back" in dr_choice_light or "exit" in dr_choice_light:
start()
else:
print "That didn't do anything."
def monster_room():
print "It seems this door is locked and requires a key."
while True:
mons = raw_input("What do you do?")
if "key" in mons and keynumb == 0: **************
print "You don't have a key, dummy. Might as well turn back.."
elif "key" in mons and keynumb == 1:
print "You open it using the small silver key."
print "You enter the room and a huge monster looks up from his iPhone. \"You want to get past me?\" he says. Well, if you know what 4 + 4 is then I'll let you pass."
answer = raw_input("What is 4+4?")
if answer == "8":
print "\"Well done!\" says the monster. He smiles as you pass to the door behind him."
else:
print "Stupid. You die."
exit
elif "back" in mons:
print "You turn back."
start()
else:
print "I don't understand."
def keynumber(): **********
global keynumb += 1
return keynumb
start()
keynumber
你想要什么
def keynumber():
global keynumb
keynumb += 1
我省略了返回声明,因为您似乎没有在那里使用它啊,太棒了,干杯,效果很好。我想我把它复杂化了。exit
是一个函数。当他死的时候,在你的怪物房间函数中将它称为exit()
:这行有什么问题:如果dr_choice中的“light”和“switch”或者dr_choice中的“turn”和“light”:
?dr_choice中的“in dr_choice”应该在light之后,并且也应该在turn之后,否则我只是问“if”light“?(这是一个很大的猜测..就像一个布尔值?如果它只是一个if语句,则返回True/False?@isherwood或,添加到该语句中^(太晚了,无法编辑)。。我的另一个猜测是,这整个方法,甚至是修改后的方法,是否因为太多和/或太多而没有意义?有没有一种方法,可能是用逗号来分隔两个字符串,所以可能是这样的:Dr_choice中的if“light”、“switch”或Dr_choice中的“turn”、“light”。。。。?