1

I would like to place operators as a list and then call an element from the list to use as an operator.

If I don't place quotations around the operators, then I get a syntax error for the commas inside of the list:

  File "p22.py", line 24
    cat = [+,-,*]
            ^
SyntaxError: invalid syntax

If I do place the quotations around, then I seem to lost the operator's function, as seen in this instance:

  File "p22.py", line 30
    a = (x which y)
               ^
SyntaxError: invalid syntax

Here is the full code:

import random

def start():
    print('\n________________________________________')
    print('|                                      |')
    print('|         Zach\'s Tutorifier!          |')
    print('|                                      |')
    print('|                                      |')
    print('|     Instructions:                    |')
    print('| Select the type of math you want     |')
    print('| to practice with:                    |')
    print('| 1-Add 2-Subtract 3-Multiply          |')
    print('|--------------------------------------|')
start()
math = int(input('> ')) - 1
cat = ['+','-','*']

def problems():
    which = cat[math]
    x = random.randint(0,9)
    y = random.randint(0,9)
    a = (x which y)
    print('What is %i %s %i?' % (x, which, y) )
    answer = input('> ')
    if answer == a:
        print('Congratulations! Try again? (Y/N)')
        again = input('> ')
        if again == 'Y' or again == 'y':
            problems()
        else:
            start()
    else: 
        print('Try again!')
problems()
Z Monk
  • 37
  • 7

2 Answers2

16

In order to properly translate a string representation of a math operator, you can actually use the builtin operator module to do this for you. Simply, map your string operators to the method call, and work accordingly. Here is an example that you should be able to figure out how to make apply to your code:

from operator import add, sub, mul

operations = {'+': add, '-': sub, '*': mul}

op = input("enter +, - or *")
num1 = int(input("enter a number"))
num2 = int(input("enter another number"))

expected_result = int(input("what do you think the answer should be"))

result = operations[op](num1, num2)

if expected_result == result:
    print('you are right')
else:
    print('no, you are wrong')

To provide an extra bit of information on this line:

operations[op](num1, num2)

operations is a dictionary, and we are accessing the value using the [] on the dictionary, by passing the inputted op as the key to that dictionary. With this, you now have the method in hand, and simply need to call it by passing the parameters (num1, num2).

idjaw
  • 25,487
  • 7
  • 64
  • 83
0

Altough eval can be used, what they say is right: never use it unless it is strictally neccesary and you have no other options and you have maximum security. Well, just don't use it, there are ways to do this things, although they require a little more code.

My proposition is mapping the operators:

import random

# NEW CODE
def sum(a, b):
    return a + b;

def substract(a, b):
    return a - b;

def multiply(a, b):
    return a * b;
# END OF NEW CODE

def start():
    print('\n________________________________________')
    print('|                                      |')
    print('|         Zach\'s Tutorifier!          |')
    print('|                                      |')
    print('|                                      |')
    print('|     Instructions:                    |')
    print('| Select the type of math you want     |')
    print('| to practice with:                    |')
    print('| 1-Add 2-Subtract 3-Multiply          |')
    print('|--------------------------------------|')
start()
math = int(input('> ')) - 1
cat = {
    "+": sum,
    "-": substract,
    "*": multiply
}

def problems():
    # NEW CODE
    operator_char= cat.keys()[math]
    operation = cat[math]
    # END OF NEW CODE
    x = random.randint(0,9)
    y = random.randint(0,9)
    print('What is %i %s %i?' % (x, operator_char, y) )
    answer = input('> ')
    # NEW CODE
    if answer == operation(x, y):
    # END OF NEW CODE
        print('Congratulations! Try again? (Y/N)')
        again = input('> ')
        if again == 'Y' or again == 'y':
            problems()
        else:
            start()
    else: 
        print('Try again!')
problems()
RompePC
  • 815
  • 1
  • 8
  • 17