I am fairly new to python.
I have been asked to create a calculator using only string commands, conversions between int/string/float etc.(if needed), and using funct
If you're making just a toy calculator, eval() accepts local and global variables, so you could use something like this:
def calculate(x=0, y=0, z=0):
expression = raw_input('Enter an expression: ')
return eval(expression, None, locals())
Here's a sample console session:
>>> calculate()
Enter an expression: x + 5 - y
5
Note that eval() is not secure. If you want to make something serious, you will have to parse the expression.
Also, since your expressions are simple, you could use a regex to validate the input before evaling it:
def validate(expression):
operator = r'\s*[+\-/*]\s*'
return bool(re.match(r'^\s*(?:x{o}y|x{o}y{o}z)$'.format(o=operator), expression))