How do you break a loop after an exception in python?

I am ready to run this code but before I want to fix the exception handling:

for l in bios:
    OpenThisLink = url + l
    try:
        response = urllib2.urlopen[OpenThisLink]
    except urllib2.HTTPError:
        pass
    bio = response.read[]
    item = re.search['[JD][.*?][\d+]', bio]
    ....

As suggested here, I added the try...except but now if a page doesn't open I get this error:

bio = response.read[]
NameError: name 'response' is not defined

So the program continues to execute. Instead I want it to go back to the for loop and try the next url. I tried break instead of pass but that ends the program. Any suggestions?

asked Dec 3, 2009 at 22:59

Use continue instead of break.

The statement pass is a no-op [meaning that it doesn't do anything]. The program just continues to the next statement, which is why you get an error.

break exits the loops and continues running from the next statement immediately after the loop. In this case, there are no more statements, which is why your program terminates.

continue restarts the loop but with the next item. This is exactly what you want.

answered Dec 3, 2009 at 23:01

Mark ByersMark Byers

781k184 gold badges1551 silver badges1440 bronze badges

2

Try is actually way more powerful than that. You can use the else block here too:

try:
    stuff
except Exception:
    print "oh no a exception"
else:
    print "oh yay no exception"
finally:
    print "leaving the try block"

answered Dec 3, 2009 at 23:34

Jochen RitzelJochen Ritzel

102k29 gold badges195 silver badges190 bronze badges

1

you are getting that error because when the exception is thrown the response variable doesn't exist. If you want to leave the code how you have it you will need to check that response exists before calling read

if response:
    bio = response.read[]
    ...

having said that I agree with Mark that continue is a better suggestion than pass

answered Dec 4, 2009 at 1:27

In this Python tutorial, we will discuss the Python While loop continue. Here we will also cover the below examples:

  • Python while loop continue break
  • Python while loop exception continue
  • Python nested while loop continue
  • Python while true loop continue
  • While loop continue python example
  • Python continue while loop after exception
  • Python try except continue while loop
  • Python while loop break and continue
  • Let us see how to use the continue statement in the While loop in Python.
  • Continue is used to skip the part of the loop. This statement executes the loop to continue the next iteration.
  • In python, the continue statement always returns and moves the control back to the top of the while loop.

Example:

Let’s take an example and check how to use the continue statement in the while loop

new_var = 8
while new_var >0:
    new_var=new_var-1
    if new_var==2:
        continue
    print[new_var]
print["loop end"]

In the above code, we will first initialize a variable with 8 and check whether 8 is greater than 0. Here you can see it is true so I will go for a decrement statement that 8-1 and it will display the variable value as 7. it will check whether a variable is equal to 2. In the above code, you will check that it is not equal to the variable and it will print the value 7.

Here is the output of the following above code

Python while loop continue

Another example is to check how to use the continue statement in the while loop in Python.

Example:

z = 8
while z > 1:
    z -= 2
    if z == 3:
        continue
    print[z]
print['Loop terminate:']

Here is the screenshot of the following given code

Python while loop continue

Read: Python For Loop

Python while loop continue break

  • In python, the break and continue statements are jump statements. The break statement is used to terminate the loop while in the case of the continue statement it is used to continue the next iterative in the loop.
  • In the break statement, the control is transfer outside the loop while in the case of continue statement the control remains in the same loop.

Example:

while True:
    result = input['enter a for the loop: ']
    if result == 'a':
        break
print['exit loop']

a = 0
while a  0:
    l -= 1
    if l == 4:
        continue
    print[l]
print['Loop terminate']

Output

while loop continue python example

Another example to check how to apply the continue statement in the while loop

Example:

t = 8                  
while 8 > 0:              
   print ['New value :', t]
   t = t-1
   if t == 4:
      break

print ["Loop end"]

Here is the output of the program

While loop continue Python example

Read: Python dictionary length

Python try except continue while loop

  • Here we can check how to apply the try-except method in the continue while loop.
  • In this example, I want to convert the input value inside a while loop to an int. In this case, if the value is not an integer it will display an error and continue with the loop.

Example:

m=0
new_var=0
l = input["Enter the value."]
while l!=str["done"]:
     try:
          l=float[l]
     except:
          print ["Not a valid number"]
          continue
     m=m+1
     new_var = l + new_var      
     l= input["Enter the value."]
new_avg=new_var/m
print [new_var, "\g", m, "\g", new_avg]

Here is the implementation of the following given code

Python try-except continue while loop

Python while loop break and continue

  • In Python, there are two statements that can easily handle the situation and control the flow of a loop.
  • The break statement executes the current loop. This statement will execute the innermost loop and can be used in both cases while and for loop.
  • The continue statement always returns the control to the top of the while loop. This statement does not execute but continues on the next iteration item.

Example:

Let’s take an example and check how to use the break and continue statement in while loop

k = 8                    
while k > 0:              
   print ['New value :', k]
   k = k -1
   if k == 4:
      break

print ["loop terminate"]

b = 0
while b 

Chủ Đề