2017-03-06 45 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()因此錯誤之前被調用。嘗試將代碼塊封裝在函數中以提高可讀性和調試性。

更新:我相信你上面的代碼縮進是不正確的。它工作正常,並且如您所期望的沒有您提到的錯誤。