如何制作运算符变量?

How to make an operator variable?

如何使运算符成为变量?例如,我想将值 1 存储在运算符“+”中,即“+”= 1。但是 python 显示错误,我该怎么办? 我的项目是这样的: while True:

current_number = int(input("Enter the number that you wish to be displayed: "))

 print(f"The current displayed number is: {current_number}")

 print("The value of '+' and '-' is limited to 5")

 n = input()

 if n == "+" or "++" or "+++" or "++++" or "+++++":

    if n == "+":

        print(current_number + 1)

    if n == "++":

        print(current_number + 2)

    if n == "+++":

        print(current_number + 3)

    if n == "++++":
        print(current_number + 4)

    if n == "+++++":
        print(current_number + 5)

 elif n == "-" or "--" or "---" or "----" or "-----":
    if n == "-":

        print(current_number - 1)

    if n == "--":

        print(current_number - 2)

    if n == "---":

        print(current_number - 3)

    if n == "----":

        print(current_number - 4)

    if n == "-----":

        print(current_number - 5)

我想通过使“+”= 1 来简化代码,我该怎么做?

除了 [A-Za-z0-9_] 之外的东西不允许作为变量名称

如果您 100% 需要它,请使用字典 即

specialVars={'+':1, "-":-1}

然后打电话

specialVars['+']

编辑:如果您只需要为每个“+”加 1,为每个“-”加 -1 这样做

print(current_number+n.count('+')-n.count('-'))

len()统计n中的字符数:

while True:
    current_number = int(input("Enter the number that you wish to be displayed: "))
    print(f"The current displayed number is: {current_number}")
    n = input()
    if set(n) == {"+"}:
        print(current_number + len(n))
    elif set(n) == {"-"}:
        print(current_number - len(n))
Enter the number that you wish to be displayed: 37
The current displayed number is: 37
+++++
42

请注意,使用这种方法无需任意限制字符数,尽管您仍然可以通过拒绝 len(n) > 5.

处的输入来明确地做到这一点

检查字符串是否包含所有 "+""-" 的原始版本不起作用:

if n == "+" or "++" or "+++" or "++++" or "+++++":

因为如果 n == "+" 不是 True(n == "+") or ("++") 将简单地 return "++"(这是真的)。写这张支票的“正确”方式是:

if n in ("+", "++", "+++", "++++", "+++++"):

或更简单(因为这些特定字符串都是 "+++++":

的子字符串
if n in "+++++":

我的代码版本是这样做的:

if set(n) == {"+"}:

的工作原理是将 n 转换为 set(将其简化为唯一字符)——如果 n 包含所有 "+",则其 set{"+"}。这适用于任何长度的 n.