0

I have a problem with 'if' executed together with 'else' when the value is equal to zero, the indentation seems fine so else is not part of for-else loop:

for i in range(0,5): if i == 0: print("i0 =", i) if i == 2: print("i2 =", i) else: print("else i=", i) i0 = 0 else i= 0 else i= 1 i2 = 2 else i= 3 else i= 4 >>> 
3
  • 4
    if i == 2: to elif i == 2: Commented Feb 5, 2018 at 15:25
  • 0 is not equal to 2 so else branch is being executed Commented Feb 5, 2018 at 15:26
  • You actually have 2 if blocks here. The first one which is alone (without any else) and the second one which does have an else clause. Both of them are ran in every iteration. Commented Feb 5, 2018 at 15:27

2 Answers 2

4

You don't have any problems. If you wanted those two ifs to form a single conditional branching, the second one should have been an elif. Right now, the loop body is comprised of two separate if statements and they are executed as: first, i is compared against zero; next again, i is compared against 2. So, when it is 0, the first if's then-block is triggered, and since it is not 2, the second if's else-block is triggered as well.

Did you actually mean

for i in range(0,5): if i == 0: print("i0 =", i) elif i == 2: print("i2 =", i) else: print("else i=", i) 

?

Sign up to request clarification or add additional context in comments.

1 Comment

that makes sense - I forgot about elif
0

You're probably invalidating the first condition by the second "if" in the statement. I don't know python thus I'm not aware of any other conditional logic but it should be something like this:

for i in range(0,5): if (i == 0 or i == 2): print("if i =", i) else: print("else i=", i) 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.