3 回答

TA貢獻(xiàn)2065條經(jīng)驗(yàn) 獲得超14個(gè)贊
您如何制作將操作員的字符(例如'+')映射到操作員(例如operator.add)的字典。然后進(jìn)行采樣,設(shè)置字符串格式并執(zhí)行操作。
import random
import operator
生成隨機(jī)數(shù)學(xué)表達(dá)式
def randomCalc():
ops = {'+':operator.add,
'-':operator.sub,
'*':operator.mul,
'/':operator.truediv}
num1 = random.randint(0,12)
num2 = random.randint(1,10) # I don't sample 0's to protect against divide-by-zero
op = random.choice(list(ops.keys()))
answer = ops.get(op)(num1,num2)
print('What is {} {} {}?\n'.format(num1, op, num2))
return answer
詢問用戶
def askQuestion():
answer = randomCalc()
guess = float(input())
return guess == answer
最后進(jìn)行多問題測(cè)驗(yàn)
def quiz():
print('Welcome. This is a 10 question math quiz\n')
score = 0
for i in range(10):
correct = askQuestion()
if correct:
score += 1
print('Correct!\n')
else:
print('Incorrect!\n')
return 'Your score was {}/10'.format(score)
一些測(cè)試
>>> quiz()
Welcome. This is a 10 question math quiz
What is 8 - 6?
2
Correct!
What is 10 + 6?
16
Correct!
What is 12 - 1?
11
Correct!
What is 9 + 4?
13
Correct!
What is 0 - 8?
-8
Correct!
What is 1 * 1?
5
Incorrect!
What is 5 * 8?
40
Correct!
What is 11 / 1?
11
Correct!
What is 1 / 4?
0.25
Correct!
What is 1 * 1?
1
Correct!
'Your score was 9/10'
- 3 回答
- 0 關(guān)注
- 719 瀏覽
添加回答
舉報(bào)