简体   繁体   English

python中的错误-不明白

[英]Error in python - don't understand

I'm creating a game, and am quite new to Python generally. 我正在创建一个游戏,并且对Python来说是相当陌生的。

I created a function 'descriptionGenerator()' which generates a description for characters and objects either randomly or using variables passed to it. 我创建了一个函数'descriptionGenerator()',该函数可以随机或使用传递给它的变量为字符和对象生成描述。

It seemed to be working, but every now and then it wouldn't work correctly. 它似乎工作正常,但有时却无法正常工作。 So i placed it in a loop, and it never seems to be able to complete the loop without one of the iterations having this problem. 因此,我将其放置在一个循环中,如果没有其中一个迭代出现此问题,它似乎永远无法完成循环。

The code is as follows: 代码如下:

#+------------------------------------------+
#| Name: bitsandpieces.py       |
#| A module for the 'Europa I' game         |
#|  created for the Game Making Competition |
#|                                  |
#| Date Created/Modified:                   |
#|          3/4/10 | 3/4/10                 |
#+------------------------------------------+

# Import the required modules
    # Import system modules:
import time
import random
    # Import 3rd party modules:

    # Import game modules:
# Define the 'descriptionGenerator()' function
def descriptionGenerator(descriptionVariables):
    descriptionVariableSize = len(descriptionVariables)
    if descriptionVariables[0] == 'char':
        # If there is only one variable ('char'), create a random description
        if descriptionVariableSize == 1:
            # Define choices for descriptionVariables to be generated from
            gender_choices = ['male', 'female']
            hair_choices = ['black', 'red', 'blonde', 'grey', 'brown', 'blue']
            hair_choices2 = ['long', 'short', 'cropped', 'curly']
            size_choices = ['tubby', 'thin', 'fat', 'almost twig-like']
            demeanour_choices = ['glowering', 'bright', 'smiling', 'sombre', 'intelligent']
            impression_choices = ['likeable', 'unlikeable', 'dangerous', 'annoying', 'afraid']
            # Define description variables
            gender = random.choice(gender_choices)
            height = str(float('0.' + str(random.randint(1, 9))) + float(random.randint(1, 2)))
            if float(height) > 1.8:
                height_string = 'tall'
                if float(height) > 2:
                    height_string = 'very tall'
            elif float(height) < 1.8 and float(height) > 1.5:
                height_string = 'average'
            elif float(height) < 1.5:
                height_string = 'short'
                if float(height) < 1.3:
                    height_string = 'very short'
            hair = random.choice(hair_choices2) + ' ' + random.choice(hair_choices)
            size = random.choice(size_choices)
            demeanour = random.choice(demeanour_choices)
            impression = random.choice(impression_choices)
            # Collect description variables in list 'randomDescriptionVariables'
            randomDescriptionVariables = ['char', gender, height, height_string, hair, size, demeanour, impression]
            # Generate description using the 'descriptionGenerator' function
            descriptionGenerator(randomDescriptionVariables)
        # Generate the description of a character using the variables passed to the function
        elif descriptionVariableSize == 8:
            if descriptionVariables[1] == 'male':
                if descriptionVariables[7] != 'afraid':
                    print """A %s man, about %s m tall. He has %s hair and is %s. He is %s and you get the impression that he is %s.""" %(descriptionVariables[3], descriptionVariables[2], descriptionVariables[4], descriptionVariables[5], descriptionVariables[6], descriptionVariables[7])
                elif descriptionVariables[7] == 'afraid':
                    print """A %s man, about %s m tall. He has %s hair and is %s. He is %s.\nYou feel that you should be %s of him.""" %(descriptionVariables[3], descriptionVariables[2], descriptionVariables[4], descriptionVariables[5], descriptionVariables[6], descriptionVariables[7])
            elif descriptionVariables[1] == 'female':
                if descriptionVariables[7] != 'afraid':
                    print """A %s woman, about %s m tall. She has %s hair and is %s. She is %s and you get the impression that she is %s.""" %(descriptionVariables[3], descriptionVariables[2], descriptionVariables[4], descriptionVariables[5], descriptionVariables[6], descriptionVariables[7])
                elif descriptionVariables[7] == 'afraid':
                    print """A %s woman, about %s m tall. She has %s hair and is %s. She is %s.\nYou feel that you should be %s of her.""" %(descriptionVariables[3], descriptionVariables[2], descriptionVariables[4], descriptionVariables[5], descriptionVariables[6], descriptionVariables[7])
        else:
            pass
    elif descriptionVariables[0] == 'obj':
        # Insert code here 2 deal with object stuff
        pass

print
print
myDescriptionVariables = ['char']
i = 0
while i < 30:
    print
    print
    print
    descriptionGenerator(myDescriptionVariables)
    i = i + 1
time.sleep(10)

When it fails to properly execute it says this: 如果无法正确执行,它会说:

Traceback (most recent call last):
  File "/Users/Jasper/Development/Programming/MyProjects/Game Making Challenge/Europa I/Code/Code 2.0/bitsandpieces.py", line 79, in <module>
    descriptionGenerator(myDescriptionVariables)
  File "/Users/Jasper/Development/Programming/MyProjects/Game Making Challenge/Europa I/Code/Code 2.0/bitsandpieces.py", line 50, in descriptionGenerator
    randomDescriptionVariables = ['char', gender, height, height_string, hair, size, demeanour, impression]
UnboundLocalError: local variable 'height_string' referenced before assignment

Thanks for any help with this 感谢您对此的任何帮助

-----EDIT----- - - -编辑 - - -

Thanks for the help, fixed that problem, but now there is another one! 感谢您的帮助,解决了该问题,但现在又有一个问题!

I changed this segment of code 2 take the strings as variables, then 'return' them, and then test them: 我更改了这段代码2,将字符串作为变量,然后“返回”它们,然后对其进行测试:

        elif descriptionVariableSize == 8:
            if descriptionVariables[1] == 'male':
                if descriptionVariables[7] != 'afraid':
                    descriptionOutput = """A %s man, about %s m tall. He has %s hair and is %s. He is %s and you get the impression that he is %s.""" %(descriptionVariables[3], descriptionVariables[2], descriptionVariables[4], descriptionVariables[5], descriptionVariables[6], descriptionVariables[7])
                    return descriptionOutput
                elif descriptionVariables[7] == 'afraid':
                    descriptionOutput = """A %s man, about %s m tall. He has %s hair and is %s. He is %s.\nYou feel that you should be %s of him.""" %(descriptionVariables[3], descriptionVariables[2], descriptionVariables[4], descriptionVariables[5], descriptionVariables[6], descriptionVariables[7])
                    return descriptionOutput
            elif descriptionVariables[1] == 'female':
                if descriptionVariables[7] != 'afraid':
                    descriptionOutput = """A %s woman, about %s m tall. She has %s hair and is %s. She is %s and you get the impression that she is %s.""" %(descriptionVariables[3], descriptionVariables[2], descriptionVariables[4], descriptionVariables[5], descriptionVariables[6], descriptionVariables[7])
                    return descriptionOutput
                elif descriptionVariables[7] == 'afraid':
                    descriptionOutput = """A %s woman, about %s m tall. She has %s hair and is %s. She is %s.\nYou feel that you should be %s of her.""" %(descriptionVariables[3], descriptionVariables[2], descriptionVariables[4], descriptionVariables[5], descriptionVariables[6], descriptionVariables[7])
                    return descriptionOutput
        else:
            print 'Incorrect number of variables contained within \'descriptionVariables\''
    elif descriptionVariables[0] == 'obj':
        # Insert code here 2 deal with object stuff
        pass

myDescriptionVariables = ['char']
myOutput = descriptionGenerator(myDescriptionVariables)
print myOutput

However, when I run this, it gives the following output: 但是,当我运行它时,它给出以下输出:

None

What am I doing wrong? 我究竟做错了什么?

You define height_string inside if/else statements: 您在if / else语句中定义height_string:

if float(height) > 1.8:
    height_string = 'tall'
    if float(height) > 2:
        height_string = 'very tall'
elif float(height) < 1.8 and float(height) > 1.5:
    height_string = 'average'
elif float(height) < 1.5:
    height_string = 'short'
    if float(height) < 1.3:
        height_string = 'very short'

However, if height == 1.8 or height == 1.5, all if/elif statements are false, and therefore height_string is never defined. 但是,如果height == 1.8或height == 1.5,则所有if / elif语句均为false,因此从不定义height_string。 Simply change the second statement to have <= and >= signs instead: 只需将第二个语句更改为具有<=和> =符号即可:

elif float(height) <= 1.8 and float(height) >= 1.5:

In response to your edit: 回应您的编辑:

You call the function with 您使用

myOutput = descriptionGenerator(["char"])

Notice that you're passing a list of length one. 请注意,您正在传递长度为1的列表。 Therefore, your function sees descriptionVariableSize == 1 and creates the random description. 因此,您的函数将看到descriptionVariableSize == 1并创建随机描述。

So far, so good. 到现在为止还挺好。

But wait! 可是等等! At the end of that if statement, you have an elif: 在该if语句的结尾,您有一个省略号:

elif descriptionVariableSize == 8:

Now you do have descriptionVariableSize == 8. However, you used elif - so you just spent all that time creating a random set of descriptions, but you never get to use it, because the first statement was true and this statement is only executed if the first statement was false. 现在,您的确有descriptionVariableSize ==8。但是,您使用了elif-因此,您只花了所有时间来创建一个随机的描述集,但从未使用过它,因为第一条语句为true,并且仅在以下情况下才执行该语句第一个陈述是错误的。

The solution - just change that elif to if . 解决方案-只需将elif更改为if Now, whether you pass in a complete statement or generate one in the function, you'll still reach the second section. 现在,无论您传递完整的语句还是在函数中生成一个语句,您仍将到达第二部分。

Edit the ... fifth ? 编辑...第五个?

I didn't notice that you call the function again at the end of the random section. 我没有注意到您在随机部分的末尾再次调用了该函数。 Note that you don't return that call - so anything returned is lost to the void. 请注意,您不会return该呼叫-因此返回的所有内容都会丢失。 Simply change it to 只需将其更改为

 return descriptionGenerator(randomDescriptionVariables)

As an added note - your function is getting a bit unwieldy. 另外请注意-您的功能有些笨拙。 The problem is that you're doing two completely different things in the function - one is generating a random list of qualities, and another is generating a description from those quallities. 问题在于您在函数中执行了两项完全不同的操作-一种正在生成质量的随机列表,另一种正在根据这些质量创建描述。 It may be better to move the stuff in the first if block into its own function, generateRandomDescription() , or something, that only gets called in that first if block. 最好将第一个if块中的内容移动到其自己的函数generateRandomDescription()或仅在第一个if块中被调用的内容中。

While you check to see if height is greater than or less than 1.5 or 1.8, you have nothing in place if it is equal to one of those values. 当您检查height是否大于或小于1.5或1.8时,如果height 等于这些值之一,则没有任何内容。 Change the comparisons around those points to either >= and < , or to > and <= . 将这些点周围的比较更改为>=<><=

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM