Search code examples
pythonpython-3.xrandomarithmetic-expressions

python random arithmetic game


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)

Solution

  • 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