0

所以我的变量在 inputnfo() 中明确定义,为什么会出现未定义的错误?尝试和可能除外?我已经添加了删除...交换了它,似乎无法找到解决方案,并且在线答案似乎非常基于情况...在此先感谢:)

超级新和改进的编辑:现在得到 UnboundLocalError

import random

alpha = ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z']

strgen = []

retry = 0

### Defining

def inputnfo():
    global much
    much = input('how long do you want your random word/lucky number to be: ')
    global which
    which = raw_input('would you like letters or numbers?(let,num, or mix?):').lower


def generate():
    while much > 0:
        if which == 'let':
            strgen.append(random.choice(alpha))
            much -= 1
            print '.'

        elif which == 'num':
            strgen.append(random.randint(1,9))
            much -= 1
            print '.'

        elif which == 'mix':
            mixer = random.choice([0,1])
            if mixer == 0:
                strgen.append(random.choice(alpha))
                much -= 1
                print '.'

            elif mixer == 1:
                strgen.append(random.randint(1,9))
                much -= 1
                print '.'

def finish():

    finito = ''.join(strgen)
    print 'Generation Completed!\n'

    if which == 'let':
        print 'Your randomly generated string is:' + finito

    elif which == 'num':
        print 'Your randomly generated number is:' + finito

    elif which == 'mix':
        print 'Your randomly generated Alpha-Numerical string is:' + finito

### Running

inputnfo()

while much != 0:
    generate()

finish()
4

1 回答 1

0

这是因为函数 inputnfo() 中的变量“much”仅对该函数是本地的。这就是为什么您在 while 循环中收到未定义错误的原因。有两个解决方案 1. 通过包含该行使变量“非常”全局化

def inputnfo():
    global much
    try: 

然后删除生成函数的参数

或者2.让函数inputnfo()返回多,在while循环中使用这个返回值生成函数

which = ""对变量“which”做同样的事情并在前面加上一行

which = ""
def inputnfo():
    global much
于 2013-07-11T06:55:40.183 回答