UnboundLocalError:局部变量'力量'转让前的参考

时间:2014-03-19 10:53:32

标签: python

我有一个程序可以确定两个字符的结果。有一个错误,我不知道如何解决它。我试过创建全局变量,但它不起作用。

代码:

import random, sys

y_n = ["yes", "Yes", "y", "ye", "yeah", "Ye", "Yeah", "Y"] # list of all possible inputs for Yes.
r = random.randrange # this is to make getting a random number shorter.

class Character(): # class. holds attributes, and methods.
    name = "" #name of the character
    random_attr = "" # do you want the attributes to be randomly generated or inputted manually?
    strength, skill = 0,0 #strength and skill attributes
    dice = 0 # dice score


    def charInputs(self, random_attr): #method
        #holds prompts for input
        prompts = ("Enter Strength Attribute, between 1 and 50: ", "Enter Skill Attribute, between 1 and 50: ") 


        if random_attr in y_n: # if the user has said anything in the y_n list,
            strength, skill = r(1,50), r(1,50) #create random attributes
            #prints out your name, and your attributes
            print(self.name + " - STRENGTH = ", strength, " SKILL = ", skill)
        else: # if no
            try: # 'try' is used for error handling
                answers = [int(input(p)) for p in prompts] 
                # this is a list comprehension. it loops through the prompts and gets inputs from them

                if not all(0 < a <=50 for a in answers): # generator expression - loops through the answers list
                    # and if it is above 50 or below 0, it returns false. else it returns true (because of the
                    # all() function).
                    print("You did not enter an attribute(s) between 1 and 50. Program closing.")
                    #exit here
                else: # if the above expression returns True
                    strength, skill = answers #gets the attributes from the answer lists
                    print(self.name + " - STRENGTH = ", strength, ", SKILL = ", skill) #prints them out

            except ValueError: # if user has not entered a integer
                print("Program exiting. You did not enter a valid data type.") #prints
                #exit here


        return strength, skill; #returns attributes so they can be used outside the function and placed
        # into variables


    def Mods(self, oth_chr, strength, skill, name): # method for creating the modifiers.
        #(you, other character, strength, skill, your name) <---- this is what is inside those brackets
        if c1.strength > oth_chr.strength: # if your strength is greater than the enemies
            str_diff = c1.strength - oth_chr.strength #create strength differences
        elif c1.strength == oth_chr.strength: # if they are both the same
            print("no outcome. both strengths were the same. No modifier could be created.")
            quit()
        else: # if enemies character is greater than yours
            str_diff = oth_chr.strength - c1.strength

        if c1.skill > oth_chr.skill: # if your skill is greater than the enemies
            ski_diff = c1.skill - oth_chr.skill #create skill difference
        elif c1.skill == oth_chr.strength: # if they are the same
            print("No outcome. Both skills were the same, no modifier could be created.")
            quit()
        else: # if the enemies is greater than yours
            ski_diff = oth_chr.skill - c1.skill

        str_mod = str_diff // 5 # creates strength and skill modifiers
        ski_mod = ski_diff // 5

        return str_mod, ski_mod; #returns them so they can be used outside the method and be put into variables

    def diceRollAndOutcome(self, ch2, strength, skill, str_mod, ski_mod, name): # method that is for determining
        # the dice roll and outcome
        c1.dice, ch2.dice = r(1,6), r(1,6) # rolls the dice

        if c1.dice == ch2.dice: # if the dice are the same
            print("No outcome. Both sides are the same.") # no outcome
            #exit here
        elif c1.dice > c2.dice: # if character 1's is greater
            c1.strength += str_mod # adds strength modifier
            c1.skill += ski_mod # adds skill modifier 

            print(self.name + "'s dice is greater than " + ch2.name +  "'s dice!\n")
            ch2.strength -= str_mod # subtract strength mod from character 2 strength
            print("STRENGTH MODIFIER = ", str_mod, " has been subtracted from " + ch2.name + "'s strength attribute. It's strength is now ", ch2.strength, "\n") # prints 
            ch2.skill -= ski_mod # subtract skill modifier from character 2 skill
            print("SKILL MODIFIER = ", ski_mod, " has been subtracted from " + ch2.name + "'s skill attribute. It's skill is now ", ch2.skill, "\n") # prints

            if ch2.strength <= 0: # is character 2's strength less than or = to 0?
                ch2.strength = 0 # make character 2 strength 0
            else: # if not
                print(ch2.name + " has not died! It's remaining strength is ", ch2.strength) # print character 2 has some strength remaining

            if ch2.skill <= 0: # if c2's skill is less than or = to 0
                print(ch2.name + "'s skill has ran out!\n") # skill has ran out
            else:
                print(ch2.name + " has some skill left! It's remaining skill is ", ch2.skill) # print c2 has some skill remaining
        else: # if character 2's dice is greater than c1's
            print(ch2.name + "'s dice is greater than " + name + "'s dice! \n")
            self.strength -= str_mod # strength mod is subtracted from character 1's strength
            print("STRENGTH MODIFIER = ", str_mod, " has been subtracted from " + self.name + "'s strength attribute. It's strength is now ", self.strength, "\n")
            self.skill -= ski_mod # skill mod is subtracted from character 1's skill 
            print("SKILL MODIFIER = ", ski_mod, " has been subtracted from " + self.name + "'s skill attribute. It's skill is now ", self.skill, "\n")

            if self.strength <= 0: # if c1's strength is less than or = to 0
                self.strength = 0 # c1's strength is 0
            else: # if not
                print(self.name + " has not died! It's remaining strength is ", self.strength) # c1 has not died

            if self.skill <= 0: # if c1's skill is less than or = to 0
                print(self.name + "'s skill has ran out!\n") # c1's skill has ran out
            else:
                print(self.name + " has some skill left! It's remaining skill is ", self.skill) # c1's skill has not ran out


c1 = Character() # creates instance of Character class inside "c1"
c2 = Character() # creates instance of Character class inside "c2"
c1.name = str(input("PLAYER 1 - Enter your characters name: ")) # input character name
c2.name = str(input("PLAYER 2 - Enter your characters name: ")) # input character name

c1.random_attr = str(input("PLAYER 1 - Would you like your attributes to be randomly generated? Yes or No: ").lower()) # would the character like their attributes randomly generated or not
c1.strength, c1.skill = c1.charInputs(c1.random_attr) # returned strength and skill attributes are put into variables

c2.random_attr = str(input("PLAYER 2 - Would you like your attributes to be randomly generated? Yes or No: ").lower()) # would the character like their attributes randomly generated or not
c2.strength, c2.skill = c2.charInputs(c2.random_attr) # returned strength and skill attributes are put into variables

str_mod, ski_mod = c1.Mods(c2, c1.strength, c1.skill, c1.name) # returned strength and skill modifiers are put into variables

c1.diceRollAndOutcome(c2,c1.strength, c1.skill, str_mod, ski_mod, c1.name) # calls diceRollAndOutcome method

错误:

Traceback (most recent call last):
  File "N:\CA\task 3\task 3.py", line 118, in <module>
    c1.strength, c1.skill = c1.charInputs(c1.random_attr) # returned strength and skill attributes are put into variables
  File "N:\CA\task 3\task 3.py", line 41, in charInputs
    return strength, skill; #returns attributes so they can be used outside the function and placed
UnboundLocalError: local variable 'strength' referenced before assignment

我该如何解决这个问题?有什么问题 - 我怎么能阻止将来这样做呢?

错误指向第118行和第41行,我查看了其他问题,但它们没有意义,因为它不是我们正在处理的代码。

3 个答案:

答案 0 :(得分:2)

charInputs函数中,有一个流路径不会将任何值分配给strengthskill

您在课程中定义的类变量在您的函数中不可见,除非您在self.strength中使用self.skillcharInputs

但是,仔细看看你的课程,我宁愿在__init__函数中定义一些默认值。

答案 1 :(得分:1)

charInputs函数中,有一条路径可以在不指定strengthskill的情况下结束。

如果random_attr in y_n为False,则会执行else分支。在该分支中,如果strength未引发异常 skill为True,则您不会分配answers = [int(input(p)) for p in prompts]all(0 < a <=50 for a in answers)。如果这些都不是真的(所以用户输入一个字符串,或者输入有效范围之外的值),你最终会在函数的末尾,而不会为这两个名称赋值。

您的代码对那些表明您需要退出的案例有评论,但您实际上并没有这样做。

答案 2 :(得分:0)

else函数中的第二个returncharInputs语句不知道strength是谁。此变量不存在于charInputs函数

的范围内