【发布时间】:2019-08-20 03:06:30
【问题描述】:
我是编程世界的新手,我开始学习 python。
我想制作简单的测验应用程序,但我一开始就卡住了。我想不出打印随机问题并检查答案是否正确的方法。
我编写了这段代码,有时它可以工作,但有时会出错。有人可以向我解释这个错误是什么,我该怎么办?
import random
def topic_ch():
print ("hello you have 3 topics chose your topic by preesing the topic number \n 1-random asking \n 2- quizz")
topc = input()
if topc == "1":
topic_1()
def topic_1():
set1 = {1: "who is the presedint of USA ? :\n -1 D.Trump 2-Emmanuel Macron\n -3 George W. Bush 4-Bill Clinton:",
2:"who is the presedint of France ? :\n -1 D.Trump 2-Emmanuel Macron\n -3 George W. Bush 4-Bill Clinton:"}
print (random.choice(set1))
ans = input()
for set1[1] in set1:
if ans == "1":
print ("correct")
break
else:
print ("opss")
break
for set1[2] in set1:
if ans == "3":
print ("correct")
break
topic_ch()
错误:
python Traceback(最近一次调用最后一次):文件 “C:\Users\Raad\Desktop\oi.py”,第 28 行,在 topic_ch() 文件“C:\Users\Raad\Desktop\oi.py”,第 7 行,在 topic_ch topic_1() 文件“C:\Users\Raad\Desktop\oi.py”,第 13 行,在 topic_1 中 打印 (random.choice(set1)) 文件 "C:\Users\Raad\AppData\Local\Programs\Python\Python37-32\lib\random.py", 第 262 行,可选 返回 seq[i] KeyError: 0
【问题讨论】:
-
随机选择序列中的元素
[0]。然而,由于这是一个字典,[0]被解释为一个键,而不是列表索引,并且字典没有键为0的元素。我不确定random.choice()是否真的打算直接使用dicts。如果您从零开始而不是从一开始对 dict 键进行编号,它可能会起作用。
标签: python python-3.x