2017-03-06 70 views
-2

这是我的代码。当它运行时它总是显示:总是去:全球名称未定义

nameerror: global name "weapon_choice" is not defined.

但是我已经放入了武器选项。为什么?

from sys import exit 

def dead(why): 
    print why,"YOU ARE EATEN BY ZOMBIES!" 
    exit(0) 

def start(): 
    print "You wake up alone in a room.A crowed of corpses around you." 
    print "You find some tools beside maybe helpful." 
    print "What will you get?" 

    weapons = ['axe', 'bat', 'knife', 'pistol'] 
    print weapons 

while True: 
    weapon_choice = raw_input(">") 

    if weapon_choice in weapons: 
     print "Zombies walk towards you, now it's in urgency!" 
     print "You can't deal with them.You must flee!" 
     print "You find door and window.Where you will go?" 

     paths = raw_input(">") 

     if paths == "window": 
      dead("You fall down to the ground.") 
     elif paths == "door": 
      lift() 
     else: 
      dead("oops!") 

    else: 
     print "Can't understand what you say." 

def lift(): 
    print "You can't recognize the number in the lift." 
    print "Get out of the lift or tap a floor whatever. " 

    floor_choice = raw_input(">") 

    if floor_choice == "get out" and weapon_choice != "pistol": 
     dead("Outside full of zombies.You have nowhere to go.") 

    elif floor_choice == "get out" and weapon_choice == "pistol": 
     print "WOW!!!YOU KILL ALL THE ZOMBIES!!" 
     print "you get back to the bed for another sleep." 
     start() 
    elif floor_choice == "tap a floor" and weapon_choice == "axe": 
     street_1() 
    elif floor_choice == "tap a floor" and weapon_choice == "bat": 
     friends_axe() 
    elif floor_choice == "tap a floor" and weapon_choice == "pistol": 
     kill_frinends() 

    else: 
     print "Can't understand what you say." 


start() 

我以为什么时候运行,一开始就已经要求输入器输入weapon_choice。

+1

[Python范围问题]的可能重复(http://stackoverflow.com/questions/1195577/python-scoping-problem) – user3080953

回答

0

首先,它看起来像你有一个缩进错误。一切从

while True: 

else: 
    print "Can't understand what you say." 

应在一个水平上标签,以便它是start函数内。


还有一个范围问题,在您的lift功能:不定义weapon_choice

调用它时你应该通过weapon_choice作为参数传递给lift功能:

def start(): 
    print "You wake up alone in a room.A crowed of corpses around you." 
    print "You find some tools beside maybe helpful." 
    print "What will you get?" 

    weapons = ['axe', 'bat', 'knife', 'pistol'] 
    print weapons 

    while True: 
     # your while loop code here 

     elif paths == "door": 
      lift(weapon_choice) 

     # the rest of your while loop code here 

def lift(weapon_choice): 
    # your lift function code here 

在此之后,你只需要编写功能street_1friends_axekill_frinends --then你”重做!

0

你应该得到:NameError: name 'weapons' is not defined

while True: 
    weapon_choice = raw_input(">") 

start()因此错误之前被调用。尝试将代码块封装在函数中以提高可读性和调试性。

更新:我相信你上面的代码缩进是不正确的。它工作正常,并且如您所期望的没有您提到的错误。