lundi 6 janvier 2020

Python for loops with if-elif-else conditions [duplicate]

I have a conceptual doubt regarding Python for loops with if/elif/else statements. So, I have written this code to explain my question further:

print("Start***********")
for i in range(10):
  print("Iterating for loop:")
  print("I at the start of loop")
  print(i)
  if i==5:
    print("Entering if")
    print("I before")
    print(i)
    i+=2
    print("I due to if condition")
    print(i)
  elif i<8:
    print("Entering elif")
    print("I before")
    print(i)
    i+=1
    print("I due to elif condition")
    print(i)
  else:
    print("Entering else")
    print(i)
    print("I due to else condition")

I have two conceptual doubts in this:

1) Why is my i not being incremented at the start of for loop? Especially when if and elif statements are executed?

2) When my i equals to 5 it executes the if statement and changes it's value to 7, but again in the for loop i changes back to 6. I don't understand why does that happen.

Any clarification regarding this doubts would be highly appreciated. So any links or resources to read or search on the Internet would be valuable enough.

The output of my code above is as follows:

Start***********
Iterating for loop:
I at the start of loop
0
Entering elif
I before
0
I due to elif condition
1
Iterating for loop:
I at the start of loop
1
Entering elif
I before
1
I due to elif condition
2
Iterating for loop:
I at the start of loop
2
Entering elif
I before
2
I due to elif condition
3
Iterating for loop:
I at the start of loop
3
Entering elif
I before
3
I due to elif condition
4
Iterating for loop:
I at the start of loop
4
Entering elif
I before
4
I due to elif condition
5
Iterating for loop:
I at the start of loop
5
Entering if
I before
5
I due to if condition
7
Iterating for loop:
I at the start of loop
6
Entering elif
I before
6
I due to elif condition
7
Iterating for loop:
I at the start of loop
7
Entering elif
I before
7
I due to elif condition
8
Iterating for loop:
I at the start of loop
8
Entering else
8
I due to else condition
Iterating for loop:
I at the start of loop
9
Entering else
9
I due to else condition

Aucun commentaire:

Enregistrer un commentaire