Python如何将函数参数转换为数值运算符/float()/int()?

2024-05-23 17:42:25 发布

您现在位置:Python中文网/ 问答频道 /正文

我想做的是:

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)

它起作用了。但可能有两个潜在的改进:

  1. 现在,在输入运算符(例如calculator(3,“+”,3))时,必须使用双引号("")。否则,解释器返回一个SyntaxError弹出窗口。我试图将if op == "+":改为if op == +:,但随后解释器返回一个SyntaxError,突出显示:之后的+

  2. 现在,该函数将所有类型的数字输入转换为float(),即使整数作为输入。如何让函数本身确定输入是整数还是浮点,并进行相应的转换?

我阅读了有关函数的文档,但它只讨论了几种类型的参数,而且它们似乎都无助于解决当前的问题。我相信这是很基本的东西,但作为一个初学者,我尝试了,但没能搞清楚。


Tags: andthe函数returnifthatfloatcalculator
3条回答

如果可能的话,这会将字符串转换为整数,否则它会给出一个浮点数,如果无法转换,则抛出异常:

In [573]: def make_number(number_string):
   .....:     try:
   .....:         return int(number_string)
   .....:     except ValueError:
   .....:         return float(number_string)
   .....:     


In [574]: make_number('1')
Out[574]: 1

In [575]: make_number('1.0')
Out[575]: 1.0

In [576]: make_number('a')
ValueError: could not convert string to float: 'a'

不能在代码中使用+*等,因为它们不是有效的标识符,但是可以使用operator模块和此处的字典来减少代码:

from operator import mul,add,div,sub,pow,mod
dic = {'+':add, '-':sub, '*':mul, '**':pow, '%':mod, '/':div}
def calculator(n1,op,n2):
    n1 = n1
    n2 = n2
    try:
        return dic[op](n1,n2)
    except KeyError:
        return "Invalid Operator"

演示:

>>> calculator(3,"**",3)
27
>>> calculator(3,"*",3)
9
>>> calculator(3,"+",3)
6
>>> calculator(3,"/",3)
1
>>> calculator(3,"&",3)  # & is not defined in your dict
'Invalid Operator'

引用运算符是传递符号的唯一方法。这是正常的语言。Python还将计算出正确的结果类型,因此不需要转换为float。

这是你的程序,稍加修改。对于Python,单引号更为“正常”,不需要在返回值周围加上(),对于错误的输入抛出异常也是标准做法:

def calculator(n1,op,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
    else:
        raise ValueError('invalid operator')

输出:

>>> calculator(1,'+',2)     # note result is int
3
>>> calculator(1,'/',2)     # Python 3.x returns float result for division
0.5
>>> calculator(2,'*',2.5)   # float result when mixed.
5.0
>>> calculator(2,'x',2.5)
Traceback (most recent call last):
  File "<interactive input>", line 1, in <module>
  File "C:\Users\metolone\Desktop\x.py", line 15, in calculator
    raise ValueError('invalid operator')
ValueError: invalid operator

另外,在@Ashwini answer的基础上,您实际上可以将运算符名称作为op而不是符号传递:

from operator import mul,add as plus,truediv as div,sub as minus,pow,mod

def calculator(n1,op,n2):
    return op(n1,n2)

输出:

>>> calculator(2,plus,4)
6
>>> calculator(2,div,4)
0.5

相关问题 更多 >