Reputation: 35
I am making a maths quiz in python and am using 3 operators: add, subtract and multiply. I want to use arithmetic operators but I am finding it difficult because python just reads it as a symbol if i just print it. I use the following code:
import random
import operator
opslist = [ # This is the bit that I want to change, i also want
operator.add, # the operators all on one line
operator.sub,
operator.mul
]
num1 = random.randint(1,10) # These are two random numbers for my quiz
num2 = random.randint(1,10)
ops = random.choice(opslist) #Random operator for my quiz
total = (ops(num1,num2)) # Answer for my quiz
print (num1,ops,num2) # Random question for my quiz
Here is the ouput:
6 <built-in function add> 5
1.) how do I make the output "6+5"
2.) Also, how do I make the numbers only do small calculations that result in positive answers so the question can never be something like "5-8"
Upvotes: 3
Views: 170
Reputation: 3651
I would use a dictionary also in your code. This is what I did.
import random
import operator
opslist= {
operator.add: "+", # the operators all on one line
operator.sub: "-",
operator.mul: "x"
}
num1 = random.randint(1,10) # These are two random numbers for my quiz
num2 = random.randint(1,10)
ops = random.choice(list(opslist.keys())) #Random operator from opslist keys
total = (ops(num1,num2)) # Answer for my quiz
print(num1,opslist[ops],num2)
When printing the question, the program prints out the sign for the operator. To make it sure that you don't get negative numbers add this under total:
while total < 0:
num1 = random.randint(1,10)
num2 = random.randint(1,10)
ops = random.choice(opslist)
total = (ops(num1,num2))
Upvotes: 1
Reputation: 20025
You can use a dictionary to map an operation to its symbolic representation. Also you can add some logic for subtraction, to ensure num2
is lower than num1
:
import random
import operator
ops = {
operator.add: '+',
operator.sub: '-',
operator.mul: '*'
}
num1, num2 = random.randint(1, 10), random.randint(1, 10)
op = random.choice(ops.keys())
if op != operator.sub or num2 <= num1:
print "%d %s %d = %d" % (num1, ops[op], num2, op(num1, num2))
Possible result:
3 - 2 = 1
Upvotes: 1