Python creating a calculator

后端 未结 4 1207
傲寒
傲寒 2020-12-22 12:50

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

4条回答
  •  半阙折子戏
    2020-12-22 13:31

    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))
    

提交回复
热议问题