随机整数无限循环
这个函数在选择一个整数后并不会停止,而是一直在无限循环。有没有人能告诉我为什么会这样,或者我该怎么修复这个问题?
def wGen():
top = len(Repo.words)
randInt = random.randint(0,len(Repo.words))
print randInt, top
它产生了这个输出:(1037是数据库中的元素数量)
...
214 1037
731 1037
46 1037
490 1037
447 1037
103 1037
342 1037
547 1037
565 1037
90 1037
...
我用这个类似菜单的函数来调用这个函数
def gameMenu():
"""Game Menu"""
gameMenuPrint()
def m():
inp = raw_input('enter option: ')
while inp != 'q':
if inp == 'play' or inp =='1': GameC.wGen()
elif inp == 'help' or inp =='2': pass
elif inp == 'back' or inp =='0': mainMenu()
else:
print 'wrong input!'
inp = raw_input('enter valid a option!: ')
m()
2 个回答
0
这个 while 条件会一直为真,除非用户在第一次输入的时候输入 'q'。因为你没有给 inp 变量赋新值,所以它一直保持不变。你需要在 while 循环里再加一个输入,让用户可以不断输入。
4
这部分是问题所在:
def m():
inp = raw_input('enter option: ')
while inp != 'q':
if inp == 'play' or inp =='1': GameC.wGen()
elif inp == 'help' or inp =='2': pass
elif inp == 'back' or inp =='0': mainMenu()
else:
print 'wrong input!'
inp = raw_input('enter valid a option!: ')
你在进入循环之前就请求了 raw_input
,一旦进入循环后,你就再也没有请求输入了。把它改成这样:
def m():
inp = raw_input('enter option: ')
while inp != 'q':
if inp == 'play' or inp =='1': GameC.wGen()
elif inp == 'help' or inp =='2': pass
elif inp == 'back' or inp =='0': mainMenu()
else:
print 'wrong input!'
inp = raw_input('enter option: ')
不过我其实更喜欢这样:
def m():
while True:
inp = raw_input('enter option: ')
if inp == 'q': break
elif inp == 'play' or inp =='1': GameC.wGen()
elif inp == 'help' or inp =='2': pass
elif inp == 'back' or inp =='0': mainMenu()
else:
print 'wrong input!'