我想做的是:
Create a calculator application. Write code that will take two numbers and an operator in the format: N1 OP N2, where N1 and N2 are floating point or integer values, and OP is one of the following: +, -, , /, %, *, representing addition, subtraction, multiplication, division, modulus/remainder, and exponentiation, respectively, and displays the result of carrying out that operation on the input operands.
我能想到的是:
def calculator(n1,op,n2):
n1 = float(n1)
n2 = float(n2)
if op == "+":
return (n1 + n2)
elif op == "-":
return (n1 - n2)
elif op == "*":
return (n1 * n2)
elif op == "/":
return (n1 / n2)
elif op == "%":
return (n1 % n2)
elif op == "**":
return (n1 ** n2)
它起作用了。但可能有两个潜在的改进:
现在,在输入运算符(例如calculator(3,“+”,3))时,必须使用双引号(""
)。否则,解释器返回一个SyntaxError
弹出窗口。我试图将if op == "+":
改为if op == +:
,但随后解释器返回一个SyntaxError,突出显示:
之后的+
。
现在,该函数将所有类型的数字输入转换为float()
,即使整数作为输入。如何让函数本身确定输入是整数还是浮点,并进行相应的转换?
我阅读了有关函数的文档,但它只讨论了几种类型的参数,而且它们似乎都无助于解决当前的问题。我相信这是很基本的东西,但作为一个初学者,我尝试了,但没能搞清楚。
如果可能的话,这会将字符串转换为整数,否则它会给出一个浮点数,如果无法转换,则抛出异常:
不能在代码中使用
+
、*
等,因为它们不是有效的标识符,但是可以使用operator
模块和此处的字典来减少代码:演示:
引用运算符是传递符号的唯一方法。这是正常的语言。Python还将计算出正确的结果类型,因此不需要转换为float。
这是你的程序,稍加修改。对于Python,单引号更为“正常”,不需要在返回值周围加上(),对于错误的输入抛出异常也是标准做法:
输出:
另外,在@Ashwini answer的基础上,您实际上可以将运算符名称作为op而不是符号传递:
输出:
相关问题 更多 >
编程相关推荐