Search code examples
python-3.xfor-loopif-statementincrementdecrement

if-else statement to increment or decrement inside for loop in python


I will take an input n and then print n number of lines.Every line i will input a string if this string is "++X" or "X++" then i will add 1 with 0(The initial value of X is 0). If my string is "--X" or "X--" then i will subtract 1 from 0.(If i already take another string then subtract from this string value).

Here is My code:

n = int(input())
c = 0
for x in range(n):
    a = input()
    if a == "X++" or "++X":
        c = c + 1
    elif a == "--X" or "X--":
        c = c - 1

print(c)

My input:

2
X++
--X

My output:

2

Expected output:

0

Because,value will 1 for "X++" and 0 again for "--X". So,what is wrong in my code and how can i fix this?


Solution

  • Reference: https://docs.python.org/3/reference/expressions.html#operator-precedence

    The order of precedence in the logic expression makes your expression equivalent to if (a == "X++") or "++X": which will always be True because bool("++X") == True. Any non-empty string will be True. So, as other answers suggest, you can use if a == "X++" or a == "++X": since or is evaluated last in the expression, the interp will evaluate the equality operations first, then apply or.

    Another more shorthand way to test if a variable has a value that could be a few alternatives is to use the in operator.

    n = int(input())
    c = 0
    for x in range(n):
        a = input()
        if a in ("X++", "++X"):
            c = c + 1
        elif a in ("--X", "X--"):
            c = c - 1
    
    print(c)
    

    So you had a case where a non-empty string evaluated to True, there are other interesting cases that evaluate to either True or False in expressions. For instance, lists:

    li1 = []
    li2 = [1, 2]
    
    if li1:
        print("li1")
    if li2:
        print("li2")
    

    Will output li2.

    Bonus round - associating values with string input using a dict:

    >>> def foo(n):
    ...     d = {'X++': 1, '++X': 1, '--X': -1, 'X--': -1}
    ...     c = 0
    ...     for _ in range(n):
    ...         a = input()
    ...         c += d.get(a, 0)
    ...     return c
    ...     
    >>> foo(3)
    <-- X++
    <-- ++X
    <-- ++X
    3