python随机生成运算符_如何使用随机运算符在Python上进行计算

I am making a maths test where each question will be either adding, multiplying or subtracting randomly chosen numbers. My operator will be chosen at random, however I cannot work out how to calculate with the operator. My problem is here:

answer = input()

if answer ==(number1,operator,number2):

print('Correct')

How can I make it so the operator is used in a calculation. For example, if the random numbers were two and five, and the random operator was '+', how would I code my program so that it would end up actually doing the calculation and getting an answer, so in this case it would be:

answer =input()

if answer == 10:

print('Correct')

Basically, how can I do a calculation to check to see if the answer is actually correct?

My full code is below.

import random

score = 0 #score of user

questions = 0 #number of questions asked

operator = ["+","-","*"]

number1 = random.randint(1,20)

number2 = random.randint(1,20)

print("You have now reached the next level!This is a test of your addition and subtraction")

print("You will now be asked ten random questions")

while questions<10: #while I have asked less than ten questions

operator = random.choice(operator)

question = '{} {} {}'.format(number1, operator, number2)

print("What is " + str(number1) +str(operator) +str(number2), "?")

answer = input()

if answer ==(number1,operator,number2):

print("You are correct")

score =score+1

else:

print("incorrect")

Sorry if I have been unclear, thanks in advance

解决方案

Use functions in a dictionary:

operator_functions = {

'+': lambda a, b: a + b,

'-': lambda a, b: a - b,

'*': lambda a, b: a * b,

'/': lambda a, b: a / b,

}

Now you can map an operator in a string to a function:

operator_functions[operator](number1, number2)

There are even ready-made functions for this is the operator module:

import operator

operator_functions = {

'+': operator.add,

'-': operator.sub,

'*': operator.mul,

'/': operator.truediv,

}

Note that you need to be careful about using variable names! You used operator first to create a list of operators, then also use it to store the one operator you picked with random.choice(), replacing the list:

operator = random.choice(operator)

Use separate names here:

operators = ["+","-","*"]

# ...

picked_operator = random.choice(operators)

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值