SomeDict = {'Sarah':20, 'Mark': 'hello', 'Jackie': 'bye'}
try:
result = ""
theKey = raw_input("Enter some key: ")
val = someDict[theKey]
except keyErrorr:
result "hello"
else:
result = result + "" + "done"
print result
I understand the try block you can insert and code to try and see what error comes up, and the error then can be caught by the except block. I am trying to figure out the best way to insert a if / else in the try and except block for the same key error that is present in this code. I was thinking that i could just replace the try and except with If/else or is it possible to just add a if/else in the try and except. Any help on how to insert a if/else into this code for key error would be greatly appreciated. So basically i want to add a if/else code into the try and except block for the same key error.
SomeDict = {'Sarah':20, 'Mark': 'hello', 'Jackie': 'bye'}
try:
result = "" #could i insert something like if result == "" : #for this line?
theKey = raw_input("Enter some key: ")
val = someDict[theKey]
except keyErrorr:
result "hello"
else:
result = result + "" + "done"
print result
One reasonable option is to initialize result = None, then test if result is None:.
It's better to use None than the empty string, since someday you might want a dictionary value to be the empty string, plus None is probably clearer to the casual reader of your code.
You could also just skip the try-except, and use if theKey in someDict:.
you can add another except without a specification what exception it should handle.
try:
# do something
except KeyError:
# do something because of the Keyerror
except:
# do what you need to do if the exception is not a KeyError
someDict = {'Sarah':20, 'Mark': 'hello', 'Jackie': 'bye'} # corrected dict name
result = ""
theKey = raw_input("Enter some key: ")
try: # just try the code where the error could be
val = someDict[theKey]
except KeyError: # corrected exception name and indent level
result = "hello" # corrected syntax
else: # corrected indent level
result = result + "" + "done" # why add "" ?
print result
does this work for you?
Related
I am trying to use try and except for some code. I have been able to get the try portion of the code to work appropriatly, but not the except portion. I am using the ValueError, but have tried the NameError and IndexError.
What am I missing?
string1 = input("Enter a string:")
d = dict(enumerate(string1))
try:
enter_value = input("Enter a value(should be in the initial string1):")
if enter_value in d.values():
print("Value found.")
except ValueError:
print("Value not found.")
The code I have written produces the correct response when the enter_value is in the dict(). But displays:
"Enter a value(should be in the initial string1):d"
When it is not in the dict()
Use the code:
string1 = input("Enter a string:")
d = dict(enumerate(string1))
enter_value = input("Enter a value(should be in the initial string1):")
if enter_value in d.values():
print("Value found.")
else:
print("value not found.")
What that error does is it produces an error if the value is incorrect but you want to see if the value is in the string or not so just check it and then put out a response.
Your code is performing correctly. You are asking if enter_value is in the list d.values(), but if it is not it wouldn't throw an error, but instead just break out of your if statement because you are not indexing or anything too tricky. You can catch this logic with an else: block like this:
string1 = input("Enter a string:")
d = dict(enumerate(string1))
try:
enter_value = input("Enter a value(should be in the initial string1):")
if enter_value in d.values():
print("Value found.")
else:
print("Value not found.")
except:
print("There was an error!!")
Although with this specific code I don't suspect there will be any errors to catch (that I can think of at least, I'm sure if you tried hard enough you could break it though XD)
As mentionned if enter_value in d.values(): will return true or false but it won't raise an exception so don t use a try here because it's unecessary.
Also instead of using a dict you can simply check if the value is present in the string
string1 = input("Enter a string:")
enter_value = input("Enter a value(should be in the initial string1):")
if enter_value in string1:
print("Value found.")
else:
print("Value not found.")
If you want to understand try/except, check this quick exemple
try:
1 / 0
except ZeroDivisionError:
print('error, unable to divide by 0')
You can do what you're trying to do, like this:
string1 = input("Enter a string:")
d = dict(enumerate(string1))
try:
enter_value = input("Enter a value(should be in the initial string1):")
if enter_value not in d.values():
raise KeyError('Value not found.')
print(f"Value found.")
except KeyError as e:
print(e)
I noticed the other answers are pointing out other ways of doing it, but if you want to use exceptions, this is how.
Typically, you don't raise an exception when looking for a value in a dict though, it's typically more when a key is missed. Like this:
d = {'a': 1, 'b': 2, 'c': 3}
try:
_ = d['d']
except KeyError:
print('Key not found.')
So I have a code for my dictionary:
def get_rooms_for(dict1, num):
try:
for x in dict1:
if x == num:
print(dict1[x])
except KeyError:
print (num,"is not available.")
And my test is
get_rooms_for({'CS101':3004, 'CS102':4501, 'CS103':6755,'NT110':1244, 'CM241':1411}, 'CS999')
And I expect my result is to print out 'num' parameter with string saying
CS999 is not available.
But when I put it this it returns empty
What should i have to do if I want to pick an KeyError in dictionary, using exception code??
When you enter the try loop you're then looping over all the keys in the dictionary. CS999 isn't a key in the dictionary, so you never try to access it. Thus you never hit a KeyError, and the except clause is never reached.
What you want to do is more like this:
def get_rooms_for(dict1, num):
if num in dict1:
print(dict1[num])
else:
print("{} is not available".format(num))
But Python already has a method for that: get
dict1.get(num, "{} is not available".format(num))
Which will return the value mapped to num if it's in the dictionary, and "{} is not available".format(num) if it's not.
try this one :
def get_rooms_for(dict1, num):
try:
print(dict1[num])
except KeyError:
print (num,"is not available.")
Try this :
def get_rooms_for(dict1, num):
try:
for x in dict1:
if dict1[num] == x:
print "It will print particular key's {0} value if its exists or It will generate keyerror".format(dict1[num])
print(dict1[x])
except KeyError:
print (num,"is not available.")
Output :
('CS999', 'is not available.')
You also can try without try and exception :
def get_rooms_for(dict1, num):
if dict1.has_key(str(num)): # or str(num) in dict1
print "Key available"
else:
print num,"is not available."
get_rooms_for({'CS101':3004, 'CS102':4501, 'CS103':6755,'NT110':1244, 'CM241':1411}, 'CS999')
output:
CS999 is not available.
Is there any pythonic way to deal with wrong user input? I'm creating a module to help people work with files, and I have functions like rename, move, basepath, etc. Example:
def move(file_path):
# do something and return
I would like to know how to handle exceptions (i.e. if I should wrap my code in a try-except block);
def move(file_path):
try:
# do something and return
except Exception as error:
# return error
If I should use the try-except, I would like to know how I should return from it. I have a background in functional programming, so I was thinking like this:
def move(file_path):
try:
# do something
return (True, something...)
except Exception as error:
return (False, error)
Other example:
def execute_query(database_cursor, query, fetch):
if type(database_cursor) != "":
return (1, "database_cursor isn't a valid database cursor")
cursor.execute(query)
if fetch == "*":
return self.cursor.fetchall()
yield self.cursor.fetchone()
In this case, I'm worried about the user sending input that is not a database.
Is there any convention for this functionality?
Thanks!
Update
How i'm doing:
from sys import exit
def testing_something(a, b, c):
try:
return 0, a + b + c
except Exception, error:
return 1, error
error, result = testing_something(1, 2, 3)
if error:
print error # raise error or treat.
sys.exit(error)
I think is very clever to do like this, now i can decide to raise it or to treat it.
In the past, I've used something like the following to ensure that a certain user input was "valid" in the sense that it was contained within a list or something. This was useful for validating manual file input for loading data into memory.
def validate_choice(selection, choices):
while selection not in choices:
selection = input("'%s' is not a valid entry. Try again: " % selection)
print("'%s' works! Returning..." % selection)
return selection
result1 = validate_choice('foo', ['foo', 'bar', 'baz'])
result2 = validate_choice('boogers', ['foo', 'bar', 'baz'])
If you're trying to coerce something of one type to another type, here's another example which coerces the user to enter either A) an integer or B) a number that can be coerced to an integer:
def str_to_int_validation(num):
parsed = False
while not parsed:
try:
num = input("Enter an integer: ")
num = int(num)
parsed = True
except ValueError:
print("'%s' is not an integer. Try again.")
return num
Hope that helps!
This you may consider Pythonic if you want, but it is nothing really but a hacky bit of code:
import os
import shutil
class MoveError(Exception): pass
def move (patha, pathb):
# Some checks
if not os.path.exists(patha):
return MoveError("'%s' does not exist!" % patha)
if os.path.exists(pathb):
return MoveError("'%s' already exists! I will not overwrite it!" % pathb)
print "Moving '%s' to '%s'..." % (patha, pathb)
try: shutil.move(patha, pathb)
except Exception, e:
return MoveError("Whoops, something nasty happened! Error is:\n%s" % str(e))
return "%i bytes moved" % os.path.getsize(pathb)
def help ():
print "This is some help!"
def quit ():
global running
print "Quitting!"
running = 0
commands = {"mv": move, "move": move, "help": help, "?": help, "q": quit, "quit": quit}
running = 1
while running:
inp = raw_input("--> ").split()
if not inp: continue
try: cmd = commands[inp[0]]
except:
print "Invalid command '%s'" % inp[0]
continue
result = cmd(*inp[1:])
if isinstance(result, Exception):
print "Error occurred!"
else: print "Done!"
if result is not None:
print result
Getting the command from commands dictionary could have also been:
cmd = commands.get(inp[0], None)
if not cmd: print "Command doesn't exist!"
or unefficient way:
if inp[0]not in commands:
print "No such command"
else: cmd = commands[inp[0]]
Now, we can start arguing over which of the three is more Pythonic. And that's just for this part of code.
But, it is dead true that returning exceptions, although it may be tempting is something to be done rarely. Usually only when you have to push something into some library's object to force it to catch the exception. (depends on design of the lib - and is very rarely needed). Your original design, starts well, with flag indicating error, but the second thing should be the error message then. Or go on like this, if you feel that you really need it for some reason. But you can always do:
def move (pa, pb):
raise MoveError, "I will not move anything!"
and then:
try:
commands["move"]("somefile", "somewhereelse") # To simulate call from user input
print "Done!"
except Exception, e:
print "An error occurred.\n%s" % str(e)
#!/usr/bin/python
try:
f = open("/home/masi/r.raw", "r+")
aBuf = f.seek(4)
except:
print "Error at position : ", position
events = []
for i in range(100):
aBuf = f.seek(4);
try:
if aBuf[:4] == b'\xFA\xFA\xFA\xFA':
print("E")
except:
# print "\0"
f.close()
when I commented out the print of except, I get the error
f.close()
^
IndentationError: expected an indented block
I think I need to have try-except because the if-clause is false often.
Why do I get this unexpected indendation?
except is expecting one or more statements.
You could write:
try:
if aBuf[:4] == b'\xFA\xFA\xFA\xFA':
print("E")
except:
pass
Warning
As stated in the comments, it is not a good practice to use except: pass.
See Why is “except: pass” a bad programming practice?.
Your code from events = [] and down needs to be inside of the first try..except block. The f.close() is out of scope.
I have 2 generator and using the next method & while loop to process thru it as below,
code
while end_of_loop = 'n':
try:
table1_row = next(table1_generator)
table2_row = next(table2_generator)
except StopIteration:
end_of_loop = 'y'
How do I identify which iterator object has no rows?
Im trying to compare 2 tables and each table rows are in generator objects.
def _compare(self):
end_of_table = 'N'
try:
while end_of_table =='N':
try:
if self.table1_key == self.table2_key:
print 'same key'
self.table1_row = next(self.table1_generator)
self._convert_table1_key_fields()
self.table2_row = next(self.table2_generator)
self._convert_table2_key_fields()
elif self.table1_key > self.table2_key:
self.table2_row = next(self.table1_generator)
self._convert_table2_key_fields()
elif self.table1_key < self.table2_key:
self.table1_row = next(self.table2_generator)
self._convert_table1_key_fields()
except StopIteration as e:
print e.args
print 'IterError'
end_of_table = 'y'
except StopIteration:
print 'Next Iteration'
You can provide a second "sentinel" value to next:
sentinel = object()
while end_of_loop = 'n':
table1_row = next(table1_generator,sentinel)
table2_row = next(table2_generator,sentinel)
#I don't account for the case where they could be exhausted at
#the same time. It's easy to add that if it matters though.
if table1_row is sentinel:
print "table1_generator gave up first"
#"break" might be more appropriate ...
#(Unless there more to the loop than this.)
end_of_loop = 'y'
elif table2_row is sentinel:
print "table2_generator gave up first"
end_of_loop = 'y'
You didn't provide details about the context or what you're actually trying to do, but it sounds like itertools.izip_longest might be useful in your case (and more pythonic). You can fill with Nones or another value which is suitable.
I can't think of a use case for this (care to share?), but I'd try wrapping next into my own function:
def mynext(it):
try:
return next(it)
except StopIteration:
raise StopIteration(it)
and then, for example,
a = iter([1,2,3,4,5])
b = iter([4,5,6,7])
try:
while True:
print mynext(a)
print mynext(b)
except StopIteration as e:
if e.args[0] == a: print 'a ended'
if e.args[0] == b: print 'b ended'