我试图找出如何在分配之前使用if语句来进行更改。这个脚本的目的是检查是否在提示之前将刀从表中取出。这样做是为了让你可以走回桌面并获得另一个回应,如果你已经采取它。我做错了什么?
def table ():
if knife_taken == False:
print "it's an old, brown wooden table, and atop it you find a knife"
print "Will you take the knife or go back?"
knife = raw_input ("> ")
if knife.strip().lower() in ["back", "b", "no"]:
basement2()
elif knife.strip().lower() in ["take knife", "knife", "yes", "k"]:
knife_taken = True
print "You now have the knife, good, you are going to need it"
raw_input()
basement2()
else:
print "I did not understand that."
raw_input()
table()
else:
print "There's nothing on the table"
raw_input()
basement2()
答案 0 :(得分:5)
基本上,当您在函数中更改变量knife_taken时,将其更改为local
级别,这意味着当函数结束时,更改将丢失。有两种方法可以解决这个问题:使用global
(但那是坏方法)
global knife_taken
knife_taken = True
或者你可以从函数
返回刀的状态return knife_taken
# later on
kitchen(knife_taken)
并将其存储在变量中,稍后将其作为争论传递回厨房
或者作为额外的小奖励,您可以将游戏状态存储在字典中。然后,您可以在游戏状态发生变化时更新字典,例如。
game_state = {}
game_state['knife_taken'] = False
def kitchen():
if not game_state['knife_taken']:
print "Take the knife!"
game_state['knife_taken'] = True
else:
print "Nothing to see here."
kitchen()
kitchen()