Reputation: 1
I have the following code:
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))
I can't find why the following error occurs:
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
Upvotes: 0
Views: 81
Reputation: 4508
You have the following errors:
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.
It should now run, but you probably want to increment score
at some point.
Upvotes: 0
Reputation: 34438
random.choice
requires a sequence type, like tuple
or list
. Changing random.choice(operators)
to random.choice(list(operators))
should fix this specific issue, but I still have no idea what you're attempting to do with this code.
Upvotes: 2