Home > Blockchain >  For-loop doesn't work as intended when replacing a variable with another
For-loop doesn't work as intended when replacing a variable with another

Time:04-29

So I have this program where the first number you input is the amount of times the for-loop will run, and all the other times it checks if the number divides by 3 without a decimal point, and if true, it adds that number to the sum, then prints the final sum at the end.

a=int(input())
sum=0
for i in range (a):
    a=int(input())
    if a % 3 == 0:
        sum=sum a
print(sum)

But if I replace the "a" in for-loop with another variable(Let's say "b"), like this:

a=int(input())
sum=0
for i in range (a):
    b=int(input())
    if b % 3 == 0:
        sum=sum a
print(sum)

The code doesn't work as intended. I understand it like this: you enter the amount of times the for-loop will run (a); then each time you enter another number(b)(even though it's another variable), Python checks if it divides by 3 without a decimal point, and if true, adds it to the sum; then prints the final sum.

I just wanna know what's wrong in my thinking process here and why the code doesn't work with another variable.

CodePudding user response:

welcome! If you want to add 'b' to the sum, change it under the 'if' statement.

If you meant something else, please elaborate on what you want to achieve.

Good luck.

  • Related