Strings, ints, and operators in Python

前端 未结 1 397
逝去的感伤
逝去的感伤 2021-01-28 17:50

How can I use an arithmetic operator (input by the user as a string) in an operation? I can print the operation itself, but I want to print the solution!

Here\'s my clum

相关标签:
1条回答
  • 2021-01-28 18:23

    Use the operator module, which has functions that perform the same operations as your arithmetic operations.

    import operator
    ops = {'*': operator.mul, '/': operator.div, '+': operator.add, '-': operator.sub}
    
    op = input("Please enter  *,  /,  +,  or  - : ")
    result = ops[op](x, y)
    
    0 讨论(0)
提交回复
热议问题