简体   繁体   中英

Loops in python need to run the loop only once

j=range(1,6)
for i in j:
     if(i==3):
         print("this is for i=3")
     else:
         print("this is for" + str(i))

the output i am getting is

this is for1
this is for2
this is for i=3
this is for4
this is for5

I need the output

this is for1
this is for i=3

i want the else loop should only execute for once I tried using break also if i use break the if loop is not executing

Try this code, it will give you the result you want:

j=range(1,6)
k=0
for i in j:
     if(i==3):
         print("this is for i=3")
     else:
         if (k==0):
             print("this is for" + str(i))
             k=1

If you only want the else bit done once, you just need to remember that fact and not do it again, something like:

j = range(1,6)
else_not_done = True
for i in j:
     if i == 3:
         print("this is for i=3")
     else:
         if else_not_done:
             print("this is for" + str(i))
             else_not_done = False

You can use elif or use a boolean object to only visit inside the block once as:

With elif :

j=range(1,6)
for i in j:
     if(i==3):
         print("this is for i=3")
     elif i == 1:
         print("this is for" + str(i))
     else:
        pass

With a boolean object:

once = False    # to make sure we only visit once
for i in j:
    if(i==3):
        print("this is for i=3")
    else:
        if not once:
            print("this is for" + str(i))
            once = True   # set it to true to avoid visiting here again
    

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