Reputation: 63
I'd like to create a program that generates two random numbers and applies a random arithmetic function to them and then prints the answer. So far I've made the numbers and the calculations but I do not know how to print the sum out or generate an answer.
from random import randint
import random
arithmatic = ['+','-','*','/']
beginning = (randint(1,9))
calculation =(random.choice(arithmatic))
end = (randint(1,9))
print (beginning)
print (calculation)
print (end)
Upvotes: 0
Views: 1867
Reputation: 76965
instead, consider making the operations you choose from true functions:
import operator
arithmetic = [operator.add, operator.sub, operator.mul, operator.div]
# ...
print calculation(beginning, end)
Upvotes: 0
Reputation: 117981
import random
# Generate your first number
>>> first = random.randint(1,9)
>>> first
1
# Generate your second number
>>> second = random.randint(1,9)
>>> second
5
Now map all the operators in your list to the actual operator functions.
import operator
ops = {'+': operator.add, '-': operator.sub, '*': operator.mul, '/': operator.div}
Now you can randomly select an operator
>>> op = random.choice(ops.keys())
>>> op
'+'
Then call the function from your dictionary.
>>> ops[op](first,second)
6
Upvotes: 1