简体   繁体   中英

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM