Python if-statement with variable mathematical operator

后端 未结 3 1385

I\'m trying to insert a variable mathematical operator into a if statement, an example of what I\'m trying to achieve in parsing user-supplied mathematical expressions:

3条回答
  •  心在旅途
    2020-12-18 21:06

    I've tried using exec and eval but neither work in an if statement

    For the sake of completeness it should be mentioned that they do work, even if the posted answers provide a better solution. You'll have to eval() the whole comparison, not just the operator:

    maths_operator = "=="
    
    if eval('"test"' + maths_operator '"test"'):
           print "match found"
    

    or exec the line:

    exec 'if "test"' + maths_operator + '"test": print "match found"'
    

提交回复
热议问题