Search code examples
pythonoperators

How to make an operator variable?


How do I make an operator a variable? for example I want to store the value 1 in operator '+' that is "+" = 1. But python is showing an error, what do I do? my project is this: 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)

I want to simplify the code by making "+" = 1, how do I do it?


Solution

  • Use len() to count the number of characters in 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
    

    Note that with this approach there's no need to arbitrarily limit the number of characters, although you can still do that explicitly by rejecting inputs where len(n) > 5.

    Your original version of the check for if the string contains all "+" or "-" doesn't work:

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

    because (n == "+") or ("++") will simply return "++" (which is true) if n == "+" is not True. A "correct" way to write this check would be:

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

    or more simply (since these specific strings are all substrings of "+++++":

    if n in "+++++":
    

    My version of the code does this instead:

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

    which works by converting n to a set (reducing it to only the unique characters) -- if n contains all "+"s, then its set is {"+"}. This works for any length of n.