Using multiple try: except to handle error does not work - python-2.7

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()

Related

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

Finding and returning the value at location index in a list

Could my current code work for this function? Here is the goal of what I am trying to do first and then my current attempt
Look at list of values, xs. Find and return the value at location index. When index is invalid for xs, return response instead.
Current code:
def get(xs, index, response=None):
xs=[]
i=0
for i in xs:
try:
while i<len(xs):
index=xs.index(xs,index)
index = i
return i
except:
return response
Thanks any help is appreciated
You seem to be very confused about what you are trying to do...
So if I understand correctly you want to return xs[index] if it exists otherwise response, a simple way to do that following the EAFP principle is:
def get(xs, index, response=None):
try:
return xs[index]
except IndexError:
return response
Plenty of issues here, let's break them down by segments:
You re-assign the name of the list you pass in thereby effectively losing the list you're searching in:
xs=[]
there's no need to do that, that line can be removed.
You assign a value to i (reminiscent of C) which gets overwritten when the loop begins and you use a for-loop when you don't really need to:
i=0
for i in xs:
again, this too can be removed.
You use a try-except with a bare except; you should specify the exception which could be raised here which is ValueError.
try:
# content
except ValueError:
return response
You're using a while loop getting the index (and specifying start), re-assigning it, and then returning it; it doesn't make much sense. You're really looking for return xs.index(index).
Again, you could really replace all that code with xs.index(index)
All in all, your function could look like this:
def get(xs, index, response=None):
try:
return xs.index(index)
except ValueError:
return response

If statement only iterating over 1st line

When printing row in a csv file, how do you get it to iterate over the entire csv instead of one line at a time when performing an if statement? For example:
import csv
nameid = raw_input("ID please")
with open('cards.csv', 'rb') as csvfile:
reader = csv.reader(csvfile, delimiter=',')
for row in reader:
row = list(row)
if nameid == row[0]:
print row
else:
print "sorry"
with this csv:
101,8
102,10
103,5
104,0
will use only the first line, then the second line, and so on, giving me a false statement 3 out of 4 times. So if I search for "102" in my raw_input, it will print:
"sorry"
['102', '10']
"sorry"
"sorry
You're actually very close to your intended functionality. You don't want to print "sorry" for every line that doesn't match, so you don't want that else block where it is. But you do want to print "sorry" if nothing at all in the file matches. As it turns out, you can just scoot that else block over one level to the left and have it correspond to the for block instead of the if. You'll also need one extra line:
import csv
nameid = raw_input("ID please")
with open('cards.csv', 'rb') as csvfile:
reader = csv.reader(csvfile, delimiter=',')
for row in reader:
row = list(row)
if nameid == row[0]:
print row
break
else:
print "sorry"
Now the else block is only triggered if the for block runs to completion (more info on this syntax here). To make sure it only runs to completion if there are no matches, add the break to immediately exit the loop when you see a match.
It's not giving you a false statement each time. You are iterating through the csv and checking every row's first element against the input. If it doesn't match, you print 'sorry'. If it does, you print the row.
If you want to only print a 'sorry' message if no matches are found, get rid of your else clause. Instead, set a boolean flag that gets initialized as false and only set to true when a match is found. After your iteration is complete, only print the 'sorry' message if the boolean is still false.

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)

Breaking from nested while loop

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.