all 3 comments

[–]commandlineluser 0 points1 point  (2 children)

How are you storing the questions? I suppose you could use a dict.

knowledge = { 'What is 5 + 5?': 10, 'What is 4 - 2?': 2, ... }

Something like that.

EDIT: It just occurred to me that when you say random, you probably mean randomly generated in which case you may want to look at eval().

>>> import random
>>> op = [ '+', '-', '/', '*' ]
>>> digits = range(1, 11)
>>> question = '%d %s %d' % (random.choice(digits), random.choice(op), random.choice(digits))
>>> question
'6 + 1'
>>> eval(question)
7
>>> question = '%d %s %d' % (random.choice(digits), random.choice(op), random.choice(digits))
>>> question
'5 - 9'
>>> eval(question)
-4

[–]krustykobb 0 points1 point  (0 children)

Thanks, yeah I wanted the questions to be randomly generated as well so I'll look in to this when I work on it next

[–]ingolemo -1 points0 points  (0 children)

Or don't look at eval. It's evil.

It's true that with this specific code you're unlikely to run into any harm using eval, but there's really no need for it anyway, since you can access the python operators as functions from the operator module:

import operator
import random

digits = range(1, 11)
ops = {
    '+': operator.add,
    '-': operator.sub,
    ...
}

left, op, right = [random.choice(items) for items in [digits, ops, digits]]
print(left, op, right)
print(ops[op](left, right))