Search code examples
pythonmathdecrement

Same type of programs giving different output in Python


So ive got two similar programs:

Program-1:

n = int(input())
mylist = []
x=0
for i in range(n):
    t = input()
    if '++' in t:
        x+=1
    else:
        x-=1
print(x)

Program-2:

n = int(input())
mylist = []
for i in range(n):
    mylist.append(input())
x=0
for x in range(n):
    if '++' in mylist[x]:
        x+=1
    elif '--' in mylist[x]:
        x-=1
print(x)

In input:

2
--X
--X

Program-1 is printing "-2" while Program-2 is printing "0".
I cant find the reason for this change in output.

Thanks for your help!
PS: It is my first question in this forum so guide me if i did anything wrong.


Solution

  • In program 2 you're using x as the for loop control variable:

    for x in range(n):
    

    while at the same time using it to store the accumulated sum. Those two uses conflict. Change the name of the variable.