0

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)

2 Answers2

1
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
Cory Kramer
  • 114,268
  • 16
  • 167
  • 218
0

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)
Rafe Kettler
  • 75,757
  • 21
  • 156
  • 151