Loops Python3陷入了一个循环——使用字典键的简单测试——被循环驱动
我被卡住了,这让我发疯。当for循环结束,函数end被调用时,一切看起来都很好,但我似乎又回到了循环中,问题不断出现——我想我是在走循环吗Loops Python3陷入了一个循环——使用字典键的简单测试——被循环驱动,loops,python-3.x,dictionary,Loops,Python 3.x,Dictionary,我被卡住了,这让我发疯。当for循环结束,函数end被调用时,一切看起来都很好,但我似乎又回到了循环中,问题不断出现——我想我是在走循环吗 import random asked=[] a='' dic = { 'England':'london', 'Ireland' : 'dublin', 'Italy' : 'rome' , 'France' : 'paris', 'Finland' : 'helsinki' , 'Greece': 'ath
import random
asked=[]
a=''
dic = {
'England':'london',
'Ireland' : 'dublin',
'Italy' : 'rome' ,
'France' : 'paris',
'Finland' : 'helsinki' ,
'Greece': 'athens',
'Germany' : 'berlin'
}
def end():
input("Press the enter key to exit.")
def start(a):
if len(asked)==len(dic):
end()
else:
a=random.choice(list(dic.keys()))
if a in asked:
start(a)
else:
asked.append(a)
main(a)
def main(a):
for i in dic:
q=dic[a]
question=input('What is the capital of ' + a + ' ?')
question=question.lower()
if question==q:
print('That is correct ' , q , ' is the capital of ' , a)
start(a)
else:
print( question , 'is not the correct answer ' , q , ' is the capital of ' , a)
start(a)
end()
start(a)
在
main
函数中似乎不需要这一行:
for i in dic:
这一行将导致对同一个城市的a
多次询问问题““+a+”的首都是什么?”
我建议您查看Python调试器,以跟踪像这样的简单流问题
而不是
python3 quiz.py
使用
这将提供一个交互式调试器会话。您可以为主函数和启动函数设置断点:
(Pdb) break main
Breakpoint 1 at c:\users\peter\pytest\quiz.py:29
(Pdb) break start
Breakpoint 2 at c:\users\peter\pytest\quiz.py:17
然后,用c
开始运行继续的代码。当调试器进入其中一个函数时,它将停止,并向您显示它所使用的行
(Pdb) c
> c:\users\peter\pytest\quiz.py(19)start()
-> if len(asked)==len(dic):
(Pdb)
为next
输入n
以单步执行代码,或为continue
输入c
以继续运行,直到下一个断点
(Pdb) n
> c:\users\peter\pytest\quiz.py(22)start()
-> a=random.choice(list(dic.keys()))
(Pdb) n
> c:\users\peter\pytest\quiz.py(23)start()
-> if a in asked:
(Pdb) n
> c:\users\peter\pytest\quiz.py(26)start()
-> asked.append(a)
(Pdb) n
> c:\users\peter\pytest\quiz.py(27)start()
-> main(a)
(Pdb) n
> c:\users\peter\pytest\quiz.py(30)main()
-> for i in dic:
(Pdb) n
> c:\users\peter\pytest\quiz.py(31)main()
-> q=dic[a]
。。。等等非常感谢彼得。我现在明白我错在哪里了。虽然我的输入框在程序结束前被调用了7次,但现在大部分都按预期工作。这意味着我认为我现在能够解决这个问题。
(Pdb) n
> c:\users\peter\pytest\quiz.py(22)start()
-> a=random.choice(list(dic.keys()))
(Pdb) n
> c:\users\peter\pytest\quiz.py(23)start()
-> if a in asked:
(Pdb) n
> c:\users\peter\pytest\quiz.py(26)start()
-> asked.append(a)
(Pdb) n
> c:\users\peter\pytest\quiz.py(27)start()
-> main(a)
(Pdb) n
> c:\users\peter\pytest\quiz.py(30)main()
-> for i in dic:
(Pdb) n
> c:\users\peter\pytest\quiz.py(31)main()
-> q=dic[a]