Strings, ints, and operators in Python

前提是你 提交于 2019-12-20 05:45:41

问题


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 clumsy attempt:

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

回答1:


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)


来源:https://stackoverflow.com/questions/15521281/strings-ints-and-operators-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!