使用给定元组的算术运算

我想从给定的元组在 python 中使用算术运算。事情是我知道我可以为每个人使用 if 语句,并且根据用户输入它会给出正确的答案。我不知道,但有没有办法在没有 ifs 的情况下做到这一点。正如您在下面看到的那样,我已经尝试过使用 for,但是我无法将字符串作为算术运算符获取。


代码:


__operators = ('+', '-', '/', '//', '*', '**', '%')


def calculator():

    x = input()

    operator = input()

    y = input()

    op = operator


    # print(str(x) + operator + str(y))


    rezultat = 0


    for operator in __operators:

        if operator in __operators:

            operator = op     



    rezultat = x + op + y       

    print(rezultat)

    return rezultat



calculator()


饮歌长啸
浏览 214回答 3
3回答

肥皂起泡泡

您可以使用operator模块和dict!import operatorop = {    "+": operator.add    "-": operator.sub    "/": operator.truediv    "//": operator.floordiv    "*": operator.mul    "**": operator.pow    "%": operator.mod}print(op["+"](2, 3))5

慕娘9325324

它与@Fukiyel的答案基本相同,但没有使用operator模块。您实现了您希望计算器支持的所有操作,然后您创建了一个 dict,其中包含操作符字符的键并对函数进行赋值:def add(n1,n2):    return n1 + n2def subtract(n1,n2):    return n1 - n2def division(n1,n2):    if n2 != 0:        return n1 / n2def integerDivision(n1,n2):    if n2 != 0:        return n1 // n2def multiply(n1,n2):    return n1 * n2def power(n1,n2):    return n1 ** n2def modulo(n1,n2):    return n1 % n2__operators = {'+' : add, '-' : subtract, '/' : division, '//' : integerDivision, '*' : multiply, '**' : power, '%' : modulo}def calculator():    x = int(input())    operator = input()    y = int(input())    for op in __operators:        if operator == op:            result = __operators[operator](x,y)            print(result)            return result calculator()

BIG阳

您可以使用eval但要小心,因为如果处理不当,它允许任意代码执行。if operator in __operators:     rezultat = eval("x" + operator + "y")
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python