Python unboundLocalError:局部变量';arm&x27;作业前参考?
大家好,我是python的初学者,我正在尝试制作我自己的文本rpg游戏。我已经为英雄制定了一种在商店购物的方法,但由于某些原因,每次我到达商店时都会出现以下错误: nboundLocalError:赋值前引用的局部变量“arm” 有人能给我解释一下这意味着什么以及我如何解决它吗?谢谢Python unboundLocalError:局部变量';arm&x27;作业前参考?,python,Python,大家好,我是python的初学者,我正在尝试制作我自己的文本rpg游戏。我已经为英雄制定了一种在商店购物的方法,但由于某些原因,每次我到达商店时都会出现以下错误: nboundLocalError:赋值前引用的局部变量“arm” 有人能给我解释一下这意味着什么以及我如何解决它吗?谢谢 def shop(): dagger = ('Dagger', 0, 5) sword = ('Sword', 0, 10) leather_hide = ('Le
def shop():
dagger = ('Dagger', 0, 5)
sword = ('Sword', 0, 10)
leather_hide = ('Leather Hide', 5, 0)
if IsShopLocked == True:
print("The shop is locked!\nPlease go back and continue your adventure!")
else:
print()
print("Welcome to the Larkville shop! What would you like to buy?\n1. Weapons\n2. armor\n3. Go back")
selection = int(input("Enter a value: "))
if selection == 1:
print("Weapons shop")
print("1. Bronze Dagger: $7\n2. Bronze Sword: $50 3.Rusty Sword $60")
wpnselection= int(input("Enter a value: "))
elif wpnselection == 1:
if hero.ac<20:
print("You donthave enough gold to buy this yet ")
main()
else:
hero.damage += 10
hero.ac -= 20
print("strength increased to: {}".format(hero.damage))
main()
if wpnselection == 2:
if hero.ac<50:
print("You dont have enough gold to buy this yet...")
main()
else:
hero.damage += 16
hero.ac -= 50
print("strength increased to: {}".format(hero.damage))
main()
elif wpnselection == 3:
if hero.ac<60:
print("You dont have enough gold to buy this yet...")
main()
else:
hero.damage += 28
hero.ac -= 60
print("strength increased to: {}".format(hero.damage))
main()
elif selection == 2:
print ("Armor Shop")
print ("1. Leather hide 20$\n2. warmogs armor 30$")
arm = int(input("enter a value: "))
if arm == 1:
if hero.ac<20:
print("You dont have enough gold!")
main()
else:
hero.hp += 20
hero.ac -= 20
print("Health increased to: {}".format(hero.health))
if arm == 2:
if hero.ac<30:
print("You dont have enough gold!")
main()
if hero.ac>30:
leather_hide = Item('Leather Hide', 5, 0)
IsLeatherHideEquipped = True
hero.hp += 20
hero.ac -= 20
print("Health increased to: {}".format(hero.health))
elif selection == 3:
main()
def shop():
匕首=(‘匕首’,0,5)
剑=(‘剑’,0,10)
皮革=(‘皮革’,5,0)
如果IsShopLocked==True:
打印(“店铺已锁定!\n请返回并继续您的冒险!”)
其他:
打印()
打印(“欢迎来到拉克维尔商店!你想买什么?\n1.武器\n2.盔甲\n3.回去”)
选择=int(输入(“输入值:”)
如果选择==1:
印刷品(“武器店”)
印刷品(“1.青铜匕首:$7\n2.青铜剑:$50 3.生锈的剑:$60”)
wpnselection=int(输入(“输入值:”)
elif wpnselection==1:
如果hero.ac的问题是,当您这样做时:
if arm == 1:
# code
if arm == 2:
# code
您尚未定义arm是什么。。您只能在此行中定义arm
:
arm = int(input("enter a value: "))
这是在elif
的内部范围内-这意味着,如果它没有达到那个点,那么arm
实际上是一个局部变量,在对它进行任何操作之前,它并没有被赋值
也许你想做的是,如果arm==1:…
在上面的elif
的范围内,这些我说不出来,但我认为你应该看看如何更改代码以包含更少的spagetti代码。。分为函数和类。您在elif
(内部作用域)中声明了变量arm
,并试图在该作用域之外使用该变量。在这里,另一个变量selection
也发生了同样的情况
若控件达不到那个条件,那个么变量将是未定义的
您可以首先使用None
def shop():
dagger = ('Dagger', 0, 5)
sword = ('Sword', 0, 10)
leather_hide = ('Leather Hide', 5, 0)
selection=None
arm=None
#rest of the code.