如何随机选择一个数学运算符,并用它问重复的数学问题? [英] How can I randomly choose a maths operator and ask recurring maths questions with it?

查看:149
本文介绍了如何随机选择一个数学运算符,并用它问重复的数学问题?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个简单的数学任务,执行困难,涉及随机导入. 这个想法是有10个随机生成的问题的测验.我使用random.randint函数得到的数字范围为(0,12),效果很好.选择随机运算符的下一个步骤我遇到了['+','-','*','/']遇到的问题.

I have a simple maths task I'm having problems executing, involving the random import. The idea is that there is a quiz of 10 randomly generated questions. I've got the numbers ranging from (0,12) using the random.randint function, that works fine. Its the next bit of choosing a random operator I'm having problems with ['+', '-', '*', '/'].

我在学校时有更复杂的编码,但这是我的练习,我所需要的就是能够随机创建一个问题并提出该问题的能力,同时还能自行回答该问题以确定给出的答案是否是正确的. 这是我的代码:

I have my more sophisticated coding back at school, but this is my practise one that all I need is the ability to randomly create a question and ask it, whilst also being able to answer it itself to determine if the answer given is correct. Here's my code:

import random

ops = ['+', '-', '*', '/']
num1 = random.randint(0,12)
num2 = random.randint(0,10)
operation = random.choice(ops)

print(num1)
print(num2)
print(operation)

maths = num1, operation, num2

print(maths)

虽然到现在为止,我的输出还是有些混乱. 例如:

As of right now though, my output is a little messed up. For example:

3
6
*
(3, '*', 6)

显然,它无法从(3,'*',6)确定答案.我将在另一个程序中将此操作转换为子例程,但是它需要首先工作!

Clearly it can't determine the answer from (3, '*', 6). I'll be turning this operation into a subroutine in my other program, but it needs to work first!

如果做得不好,请原谅我,这是对我留在学校的任务的快速恢复,并且我在知识上还很陌生.预先感谢!

And forgive me if its not very well done, this was a quick recreation of the task I left at school, and I'm also fairly new at this with limited knowledge. Thanks in advance!

推荐答案

Python中有一个名为eval()的函数,用于评估包含数学表达式的字符串.

There is a function in Python called eval() that evaluates strings which contain mathematical expressions.

import random

ops = ['+', '-', '*', '/']
num1 = random.randint(0,12)
num2 = random.randint(0,10)
operation = random.choice(ops)

print(num1)
print(num2)
print(operation)

maths = eval(str(num1) + operation + str(num2))

print(maths)

您需要将数字转换为字符串,因为该函数需要字符串'4 * 2','3 + 1'等.

You need to convert your numbers to strings because the function is expecting something like the string '4*2', '3+1' etc. etc.

这篇关于如何随机选择一个数学运算符,并用它问重复的数学问题?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆