所以我的变量在inputnfo()中明确定义,为什么我得到一个未定义的错误?尝试&除了呢?我添加了删除...交换了所有周围,似乎无法找到解决方案,并在线答案似乎非常基于情况...提前感谢:)
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()
答案 0 :(得分:0)
因为函数inputnfo()中的变量“很多”本身就是该函数的本地变量。这就是为什么你在while循环中得到一个未定义的错误。有两个解决方案 1.通过包含行
使变量“更加”全局def inputnfo():
global much
try:
然后删除generate function
的参数或者 2.让函数inputnfo()返回很多并在while循环中使用此返回值并生成函数
为变量“which”做同样的事情
并添加一行which = ""
befor
which = ""
def inputnfo():
global much