python随机生成运算符_我怎样才能随机选择一个数学运算符并用它来问重复出现的数学问题?...

不如做一个字典,把运算符的字符(如“+”)映射到运算符(如operator.add)。然后采样,格式化字符串,并执行该操作。import random

import operator

生成随机数学表达式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

最后做一个多问题测验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)

一些测试>>> 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'

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值