How to exit from try block and show exception message? - python

This Python code block generates an error at student [3]. How to immediately show the error message in except rather than printing the previous values?
try:
student = ['bob','rob','mob']
print (student )
print (student [0])
print (student [1])
print (student [2])
print (student [3])
except:
print("error")
Current Output:
['bob','rob','mob']
bob
rob
mob
error
Process finished with exit code 0
How could I avoid the printing before the error is raised?

The code will run until some error happens and the error won't happen until print (student [3]). Therefore previous commands will run and there is now way back.
A simple solution is that you first assign these values to some variables and then print them:
try:
student = ['bob','rob','mob']
a=student [0]
b=student [1]
c=student [2]
d=student [3]
print (a)
print (b)
print (c)
print (d)
except:
print("error")
So the error happens in d=student [3] before the print commands are executed.

You can't do that AFAIK.
Python doesn't know that it is going to encounter an IndexOutOfBounds (IndexError) exception, so it will execute until getting to the exception.
A way to remedy the situation would be to use a for loop and only iterate on that. It should avoid the exception altogether:
try:
student = ['bob','rob','mob']
for stud in student:
print stud
except:
print("error") # less likely to be reached :)

Related

Trying to get my python program to run but I keep getting a variable assignment error. Any ideas as to what I am doing wrong?

def main():
name = ''.join(user_word.lower().split())
name = name.replace('-','') # what?
limit = len(name)
phrase = True
while running:
temp_phrase = phrase.replace(' ', '')
if len(temp_phrase) < limit:
print(f"length of anagram phrase = {len(temp_phrase)}")
find_anagram(name, dict_file)
print("Current anagram phrase =", end = " ")
print(phrase, file=sys.stderr)
choice, name = process_choice(name)
phrase += choice + ' '
elif len(temp_phrase) == limit:
print("\n**FINISHED!!**\n")
print("Anagram of name", end = " ")
print(phrase, file=sys.stderr)
print()
try_again = input("\n\nWant to try again? (Press Enter or else 'n' to quit)\n")
if try_again.lower() == 'n':
running = False
sys.exit()
else:
main()
after running my code I keep getting the error
UnboundLocalError: local variable 'running' referenced before assignment
so I tried making a variable named running in my main function's argument but I got a different error so I just figure I would try to work out this first. Any clue as to how to fix it.
Side note: this problem is from the book impractical python projects (chapter 3 project 5), I copied almost every bit of code so I'm not sure how it isn't working.
The reason you are getting a variable referenced before assignment error is because, as the error describes, you are referencing a variable before assigning any value to it.
The variable running is only referenced inside the while loop, not before. for this to work, you would have to add a line above your while loop assigning a value to running.
Consider this example:
def my_function():
print(my_variable)
my_variable = 'this is a string'
my_function()
In this example, I attempted to print my_variable. However, there was nothing assigned to it before I tried to print it. So the output is the following:
UnboundLocalError: local variable 'my_variable' referenced before assignment
However, if I assign the variable some value before I print it like this, I get the output I am expecting.
def my_function():
my_variable = 'this is a string'
print(my_variable)
my_function()
Output:
this is a string
You may ask why this happens, shouldn't python be able to see that I assigned a value to it and just print that value? The answer to that question is no. To put it simply, Python is executed from top to bottom, so when there is an attempt to print my_variable without assigning anything to it above, the code crashes. Here is some info on how python code works.

check try exception IndexError in python

I have this two pieces of code:
try:
error1=tree.xpath[...]
error2=tree.xpath[...]
except IndexError:
print 'hello' #piece 1
try:
error3=tree.xpath[...]
error4=tree.xpath[...]
except IndexError:
print 'hello' #piece 2
Depends on what xpath pattern is, one of two pieces work well. For example for some sites piece 1 is working fine (so I have to comment piece 2) and for some other sites piece two is working fine (so I have to comment out piece 1).
How can I mix and use both pieces in all conditions for all web sites I am using them?
You can nest exceptions:
try:
error1=tree.xpath[...]
error2=tree.xpath[...]
print "Method 1 succeed"
except IndexError:
print "Method 1 failed, trying method 2"
try:
error3=tree.xpath[...]
error4=tree.xpath[...]
print "Method 2 succeed"
except IndexError:
print 'Both method failed'
You can use the same code by introducing a new variable which keeps a check if the commands were successful.
success = False
try:
error1=tree.xpath[...]
error2=tree.xpath[...]
success = True
except IndexError:
print 'hello' #snippet 1
if not success:
try:
error1=tree.xpath[...]
error2=tree.xpath[...]
except IndexError:
print 'hello' #snippet 2

Basic Exception Handling

I'm trying to just execute this simple exceptiion handler and it won't work for some reason. I want it to throw the exception and write the error to a file.
fileo = "C:/Users/bgbesase/Documents/Brent/ParsePractice/out.txt"
g = 4
h = 6
try:
if g > h:
print 'Hey'
except Exception as e:
f = open(fileo, 'w')
f.truncate()
f.write(e)
f.close()
print e
Any ideas what I am doing wrong?
Your snippet is not supposed to raise any exceptions. Maybe you want to do something like
try:
if g > h:
print 'Hey'
else:
raise NotImplementedError('This condition is not handled here!')
except Exception as e:
# ...
Another possibility is that you meant to say:
try:
assert g > h
print 'Hey!'
except AssertionError as e:
# ...
The assert keyword basically behaves like a "fail-safe." If the condition is false, it will raise an AssertionError exception. It is often used to check preconditions for arguments to functions. (Say a value needs to be greater than zero for the function to make sense.)
Edit:
An exception is a sort of "signal" in your code that halts whatever your program was doing and finds it way to the nearest "exception handler." Whenever an exception occurs in your program, all execution immediately halts, and it tries to go to the nearest except: section of the code. If none exists, the program crashes. Try executing the following program:
print 'Hello. I will try doing a sum now.'
sum = 3 + 5
print 'This is the sum: ' + str(sum)
print 'Now I will do a division!'
quotient = 5/0
print 'This is the result of that: ' + str(quotient)
If you run it, you will see that your program crashes. My Python tells me:
ZeroDivisionError: integer division or modulo by zero
This is an exception! Something exceptional happened! You can't divide by zero, of course. As you now know, this exception is a sort of signal that finds its way to the closest exception: block, or the exception handler. We can rewrite this program so it is safer.
try:
print 'Hello. I will try doing a sum now.'
sum = 3 + 5
print 'This is the sum: ' + str(sum)
print 'Now I will do a division!'
quotient = 5/0
print 'This is the result of that: ' + str(quotient)
except Exception as e:
print 'Something exceptional occurred!'
print e
Now we catch the exception, the signal that something exceptional happened. We put the signal in the variable e and we print it. Now your program will result in
Something exceptional occurred!
integer division or modulo by zero
When the ZeroDivisionError exception occurred, it stopped the execution at that spot, and went straight to the exception handler. We can also manually raise exceptions if we want to.
try:
print 'This you will see'
raise Exception('i broke your code')
print 'This you will not'
except Exception as e:
print 'But this you will. And this is the exception that occurred:'
print e
The raise keyword manually sends an exception signal. There are different kinds of exceptions, like the ZeroDivisionError exception, the AssertionError exception, the NotImplementedError exception and tons more, but I leave those for further studies.
In your original code, there was nothing exceptional happening, so that's why you never saw an exception getting triggered. If you want to trigger an exception based on a condition (like g > h) you can use the assert keyword, which behaves a little like raise, but it only raises an exception when the condition is false. So if you write
try:
print 'Is all going well?'
assert 3 > 5
print 'Apparently so!'
except AssertionError as e:
print 'Nope, it does not!'
You will never see the "Apparently so!" message, since the assertion is false and it triggers an exception. Assertion are useful for making sure values make sense in your program and you want to abort the current operation if they don't.
(Note that I caught explicitly the AssertionError in my exception handling code. This will not catch other exceptions, only AssertionErrors. You'll get to this in no time if you continue reading about exceptions. Don't worry too much about them now.)
You're not actually ever raising an exception. To raise an exception, you need to use the raise keyword with an Exception class or instance of an Exception class. In this case, I would recommend a ValueError as you've gotten a bad value.
fileo = "C:/Users/bgbesase/Documents/Brent/ParsePractice/out.txt"
g = 4
h = 6
try:
if g > h:
raise ValueError('Hey')
except Exception as e:
f = open(fileo, 'w')
f.truncate()
f.write(str(e))
f.close()
print e

NameError: global name 'PIN' is not defined

I am getting the following Error Message :
Traceback (most recent call last):
File "/Volumes/KINGSTON/Programming/Assignment.py", line 17, in <module>
Assignment()
File "/Volumes/KINGSTON/Programming/Assignment.py", line 3, in Assignment
My code is:
def Assignment():
prompt = 'What is your PIN?'
result = PIN
error = 'Incorrect, please try again'
retries = 2
while result == PIN:
ok = raw_input(Prompt)
if ok == 1234:
result = menu
else:
print error
retries = retries - 1
if retries < 0:
print 'You have used your maximum number of attempts. Goodbye.'
Assignment():
would really appreciate a little help if anyone knows where i am going wrong and can explain
That particular error is raised because when you say result = PIN, PIN doesn't actually exist. Since it isn't in quotes, Python assumes it is a variable name, but when it goes to check what that variable is equal to, it doesn't find anything and raises the NameError. When you fix that, it will also happen with prompt since you later refer to it as Prompt.
I'm not sure if this is your full code or not, so I'm not sure what the other issues could be, but it looks like you are using result and PIN to control your while loop. Remember that a while loop runs until the condition it is checking is False (or if you manually break out of it), so instead of declaring the extra variables, you could start with something like this:
def Assignment():
# No need to declare the other variables as they are only used once
tries = 2
# Go until tries == 0
while tries > 0:
ok = raw_input('What is your PIN?')
# Remember that the output of `raw_input` is a string, so either make your
# comparison value a string or your raw_input an int (here, 1234 is a string)
if ok == '1234':
# Here is another spot where you may hit an error if menu doesn't exist
result = menu
# Assuming that you can exit now, you use break
break
else:
print 'Incorrect, please try again'
# Little shortcut - you can rewrite tries = tries - 1 like this
tries -= 1
# I'll leave this for you to sort out, but do you want to show them both
# the 'Please try again' and the 'Maximum attempts' messages?
if tries == 0:
print 'You have used your maximum number of attempts. Goodbye.'

Python Program beeps when run?

I am running into a problem. The following program beeps when it runs, which I did not program into it. I am running Windows 7 on a laptop and was wondering why this happens.
My code is basically a simple little encryptor. It is not yet capable of handling things outside of the ASCII range but that is outside the scope of this question.
Ultimately, I would like to know, why does it beep?
(Note: this is from a class which is why self is included.)
def encrypt(self,message,private_key):
import random
self.message=str(message)
self.private_key=int(private_key)
self.public_key=""
self.final_message=""
self.errors=[]
for letter in str(self.message):
y=random.randrange(0,ord(letter))
a=y+self.private_key
x=ord(str(letter))^a
if x in range(0,256):
z=chr(x)
self.final_message=self.final_message+str(z)
self.public_key=self.public_key+str(chr(y))
else:
char="Letter: "+str(letter)+", ASCII value unabled to be processed: "+str(x)+" using keys: "+"Private key: "+str(self.private_key)+" Random Key: "+str(y)
self.errors.append(char)
print "Message: "+str(self.message)
print
print "Length of Message: "+"["+str(len(str(self.message)))+"]"
print
print "Final Message: "+"["+str(self.final_message)+"] "+"length of message: "+str(len(str(self.final_message)))
print
print "Public Key: "+"["+str(self.public_key)+"] "+"length of key: "+str(len(str(self.public_key)))
print
print "Private Key:"+"["+str(self.private_key)+"]"
if len(self.errors)!=0:
print "errors: "
print
for error in self.errors:
print error
print
http://en.wikipedia.org/wiki/Bell_character
ascii 7 is your culprit. consider encoding into base64 or some other printable subset.
If you are printing ASCII code 7 at any time, you may make your console/terminal beep.
Try it:
>>> print chr(7)

Categories