我有以下代码:
import random
import operator
operators={"+":operator.add,
"-":operator.sub,
"X":operator.mul}
name = input(" What is Your Name ? :")
score = 0
counter = 1
for question in range(0,10):
num1 = random.randint(1,13)
num2 = random.randint(1,13)
ranop = random.choice(operators)
answer = operators.get(ranop,num1,num2)#operator searches in operators(DICTIONARY) for random operator and then use num1 and num2 to create a question
print("{0} {1} {2}=".format(num1,ranop,num2))
if guess==answer:
print("✔")
else:
print("✘,The answer was {0}".format(answer))
print ("{0}, You Finished! You got {1}/10".format(name.title(),score))
我无法找到发生以下错误的原因:
What is Your Name ? :s
Traceback (most recent call last):
File "substr.py", line 15, in <module>
ranop = random.choice(operators)
File "/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/random.py", line 254, in choice
return seq[i]
KeyError: 0
答案 0 :(得分:2)
random.choice
需要sequence type,例如tuple
或list
。将random.choice(operators)
更改为random.choice(list(operators))
应修复此特定问题,但我仍然不知道您尝试使用此代码执行的操作。
答案 1 :(得分:0)
您有以下错误:
ranop = random.choice(operators) # choice takes a sequence, not a dictionary.
answer = operators.get(ranop,num1,num2)
# In your case, get takes a single argument. It returns a function, which you apply to the numbers.
guess == answer # You never define guess.
它现在应该运行,但您可能希望在某个时刻增加score
。