简体   繁体   English

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

[英]Python-How to convert function argument into numeric operator/float()/int()?

What I tried to do: 我试图做的:

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. 编写将采用以下格式的两个数字和运算符的代码:N1 OP N2,其中N1和N2是浮点或整数值,OP是以下之一:+, - ,, /,%,* ,表示加法,减法,乘法,除法,模数/余数和取幂,并显示对输入操作数执行该操作的结果。

What I was able to come up with: 我能想到的是:

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)

It works. 有用。 But there might be 2 potential improvements: 但可能有两个潜在的改进:

  1. right now one has to use double quotes( "" ) when entering the operator, for example, calculator(3,"+",3). 现在,当进入运算符时,必须使用双引号( "" ),例如,计算器(3,“+”,3)。 Otherwise the interpreter returns a SyntaxError pop-up. 否则,解释器将返回SyntaxError弹出窗口。 I tried to change if op == "+": into if op == +: , but then the interpreter returns a SyntaxError, highlighting the : after the + . 我试图改变if op == "+": if op == +: :,然后解释器返回一个SyntaxError,突出显示: +

  2. right now the function converts all kinds of number input into float() , even if integer was taken as input. 现在该函数将各种数字输入转换为float() ,即使整数被视为输入。 How to let the function itself determine whether the input is integer or floating point, and convert it accordingly? 如何让函数本身确定输入是整数还是浮点,并相应地转换它?

I read the Documentation on Functions, but it only talked about several types of arguments, and none of them seem to help solving the current problems. 我阅读了关于函数的文档,但它只讨论了几种类型的参数,它们似乎都没有帮助解决当前的问题。 I'm sure this is pretty basic stuff, but as a beginner I tried and wasn't able to figure it out. 我确定这是非常基本的东西,但作为一个初学者,我尝试过并且无法解决这个问题。

You can't use + , * ,etc in your code as they are not valid identifiers, but you can use the operator module and a dictionary here to reduce your code: 您不能在代码中使用+*等,因为它们不是有效的标识符,但您可以使用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"

Demo: 演示:

>>> 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'

Quoting the operator is the only way to pass a symbol. 引用运算符是传递符号的唯一方法。 It's normal for the language. 这种语言很正常。 Python will also figure out the correct type of the result, so no need to convert to float. Python也会找出正确的结果类型,因此无需转换为float。

Here's your program with slight modifications. 这是你的程序稍作修改。 Single quotes are more "normal" for Python, no need for () around return values, and throwing exceptions for bad input is standard practice as well: 单引号对于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')

Output: 输出:

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

Also, building on @Ashwini answer, you can actually just pass the operator name as op instead of the symbol: 此外,在@Ashwini回答的基础上,您实际上只需将运算符名称作为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)

Output: 输出:

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

This converts a string into an integer if possible, otherwise it gives a float or throws an exception if a conversion is not possible: 如果可能,这会将字符串转换为整数,否则如果无法进行转换,则会产生浮点数或抛出异常:

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'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM