Breaking from nested while loop - python-2.7

I have two nested while loops in my script like in the code below,
while next_page is not None:
while 1:
try:
#Do Something
break
except:
pass
Now when I use the break statement, it breaks both the while loop.
I just want to break from while 1 and keep while next_page is not None: running until the next_page value is not None.
Is this possible? If yes, could someone please advise how to do that.
Thank you.

That break statement only exits that inner loop. A concrete example:
while True:
print "In outer loop"
i = 0
while True:
print "In inner loop"
if i >= 5: break
i += 1
print "Got out of inner loop, still inside outer loop"
break
That outputs the following:
In outer loop
In inner loop
In inner loop
In inner loop
In inner loop
In inner loop
In inner loop
Got out of inner loop, still inside outer loop
This leads me to believe there is something else causing your execution to leave the outer loop - either next_page got assigned to something, or perhaps there is another break floating around.

Related

Using multiple try: except to handle error does not work

I have a list of files I am iterating through:
condition = True
list = ['file1', 'file2', 'file3']
for item in list:
if condition == True
union = <insert process>
....a bunch of other stuff.....
Let's say the code works fine on file1 and file3, but when it gets to file2, an IO error gets thrown. What I want to do is route around file2 when the IOError is thrown a go to back to the next item in the list. I want to use a try: except method to do this but I can't seem to get it right. Note: I have an overall try-catch at the beginning of the code. I am not sure if it may interfere with having a second one on just a specific section of the code.
try:
try:
condition = True
list = ['file1', 'file2', 'file3']
for item in list:
if condition == True
union = <insert process>
....a bunch of other stuff.....
except IOError:
continue
.....a bunch more stuff.....
except Exception as e:
logfile.write(e.message)
logfile.close()
exit()
What is the difference between 'pass' and 'continue' and is why would the above code not work? Do I need to add more specific information to the IOError part?
What's the difference between pass and continue ?
pass is a no-op, it tells python to simply do nothing and go to the next instruction.
continue is a loop operation, it tells python to ignore whatever else code is left in this iteration of the loop and simply go to the next iteration as if it had reached the end of the loop block.
For example:
def foo():
for i in range(10):
if i == 5:
pass
print(i)
def bar():
for i in range(10):
if i == 5:
continue
print(i)
The first will print 0,1,2,3,4,5,6,7,8,9, but the second will print 0,1,2,3,4,6,7,8,9 because the continue statement will cause python to jump back to the start and not go on to the print instruction, whereas pass will continue executing the loop normally.
Why would the above code not work?
The issue with your code is that the try block is outside the loop, once an exception occurs inside the loop, the loop terminates at that point and jumps to the except block outside the loop. To fix that, just move the try and except blocks into your for loop:
try:
condition = True
list = ['file1', 'file2', 'file3']
for item in list:
try:
# open the file 'item' somewhere here
if condition == True
union = <insert process>
....a bunch of other stuff.....
except IOError:
# this will now jump back to for item in list: and go to the next item
continue
.....a bunch more stuff.....
except Exception as e:
logfile.write(e.message)
logfile.close()
exit()

How to fix a loop with boolean variable

I'm doing a project for a class, and I opted to make a text based game in python. I'm trying to set it up so that the question will loop until the player confirms their choice, and I'm having problems with the while loop in this section.
def pc_cls_sc(x):
# code does some stuff
print "You are sure about" + str(x)
exVar = raw_input("Right?")
if exVar == "y":
print "Alright!"
conf_Class = True
else:
print "Ok then."
conf_Class = False
while conf_Class is False:
pc_Class = raw_input(#asks some question)
pc_cls_sc(pc_Class)
The rest of this code functions properly, but the loop continues after the conf_Class variable is supposed to be set to true. I have a similar loop earlier in my code, which works just fine. I've tried moving the variable reassignment outside of the pc_cls_sc function, but all it did was cause double output. Can anyone tell me how to fix this?
You can use break to exit the loop. The code below will keep asking a user for input until they say 'y'.
while True:
x=input("Right? " )
if (x=='y'):
break

Could not exit a for .. in range.. loop by changing the value of the iterator in python [duplicate]

This question already has answers here:
How to change index of a for loop?
(5 answers)
Closed 6 years ago.
I have the following script:
for i in range (10):
print i
i = 11
When i execute this script, I was expecting to print out only 0, but instead, it prints out 0 to 9. Why i=11 did not stop the for loop?
changing i inside the for-loop have no effect how many iterations are performed because that is controlled by how many elements are inside range or in whatever you are looping in, likewise it don't have any effect in which value i will have in the next iteration.
Internally a for loop like this
for elem in iterable:
#stuff
#other stuff
is transformed to something like this (for any stuff and for any iterable)
iterator = iter(iterable)
while True:
try:
elem = next(iterator)
#stuff
except StopIteration:
break
#other stuff
the iterator constructed by iter will trow a StopIteration exception when there are no more elements inside it, and to get the next element you use next. break is used to end a for/while loop and the try-except is used to catch and handled exceptions.
As you can see, any change you do elem (or i in your case) is meaningless to how many iteration you will have or its next value.
To stop a for-loop prematurely you use break, in your case that would be
for i in range(10):
print i
break

Want to skip number while performing for loop

While using for loop in python whatever range we initially define that is fixed.
In any case can we skip at some step like.code give i={0,1,2,3,4,5,6,7,8,9)
I want
i={0,1,2,3,4,8,9}
for i in range(0,10):
print i
if(i==4):
i=i+3
you can use list and in the loop check the list.
listinfo = [0,1,2,3,4,8,9]
for i in range(0,10):
if i in listinfo:
#do your stuff
The reason your code doesn't work is that every iteration of the for-loop begins by setting the value of i to the next item in the range, meaning that it doesn't matter how you set i during the loop's body.
Instead, you can have the loop body only execute for certain values like this:
for i in range(10):
if i not in range(5, 8):
print(i)

returning to a loop when it doesn't meet a certain condition

So I have a while loop that calculates the value of a variable for me.
If that variable does not reach the condition that I want to, is it possible to return to the while loop and insert new variables, and keep returning to the loop until I get the condition that i want.
balance=3329
annualInterestRate=0.2/12
month=0
min_pay=10
while month<12:
new_bal=balance+(balance*annualInterestRate)-min_pay
balance=new_bal
month=month+1
if balance>0:
min_pay+=10
So if by the end of the loop the balance>0 then I want to add 10 to min_pay and go through the loop with the original values. And I want it to keep going until balance<=0
Yes, you can use a nested while loop:
min_pay=10
while True:
balance=3329
annualInterestRate=0.2/12
month=0
while month<12:
new_bal=balance+(balance*annualInterestRate)-min_pay
balance=new_bal
month=month+1
if balance>0:
min_pay+=10
else:
break