【问题标题】:Strings, ints, and operators in PythonPython 中的字符串、整数和运算符
【发布时间】:2013-03-20 10:43:29
【问题描述】:

如何在运算中使用算术运算符(由用户作为字符串输入)?我可以打印操作本身,但我想打印解决方案!

这是我笨拙的尝试:

# Initialise variables

x = 2
y = 3

# Prompt the user for an arithmetic operator

operator = input("Please enter  *,  /,  +,  or  - : ")

# Calculate the operation

result = (str(x) + operator + str(y))

# Display the result

print(result)

【问题讨论】:

    标签: python string operators int


    【解决方案1】:

    使用operator module,它具有执行与算术运算相同的运算的功能。

    import operator
    ops = {'*': operator.mul, '/': operator.div, '+': operator.add, '-': operator.sub}
    
    op = input("Please enter  *,  /,  +,  or  - : ")
    result = ops[op](x, y)
    

    【讨论】:

    • 感谢马丁!我不得不将 'operator.div' 更改为 'operator.truediv',然后它就完美运行了。我会赞成你的回答,但我没有足够的“声誉”!
    • @felixinutero:你接受我的回答就足够了。 :-) 很高兴能帮上忙!
    猜你喜欢
    • 2013-08-30
    • 2020-08-18
    • 1970-01-01
    • 1970-01-01
    • 2016-08-13
    • 2013-09-16
    • 2012-10-08
    • 1970-01-01
    • 2013-04-09
    相关资源
    最近更新 更多