DrBgyan
DrBgyan

Reputation: 3

if statement not working within for loop

I am a beginner. I am doing an iterative calculation in python like

for i in range(30):
    if i<10:
       p = 1
    if 10<=i<20:
       p = 2
    else:
       p = 3

however, when I run the code, for the if i<10 case, I am getting p=3 which is the else case. I get correct p = 2 in second case. What is wrong with this code?

Upvotes: 0

Views: 52

Answers (1)

Jason
Jason

Reputation: 726

For you code, the first if and the else statement will both run when i < 10. Maybe you should change your second if to elif:

for i in range(30):
   if i<10:
      p = 1
   elif 10<=i<20:
      p = 2
   else:
      p = 3

Upvotes: 2

Related Questions