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.')
Related
I am trying to get the type of data user inputs, but I am getting some issues with code. I tried with the below code:
def user_input_type():
try:
user_input = int(raw_input("Enter set of characters or digit"))
except:
try:
user_input = str(user_input)
except Exception as e:
print e
return type(user_input)
return type(user_input)
print user_input_type()
but it gives me 2 warnings before running the code.
Local variable user_input might be referenced before assignment.
Too broad exception clause such as no exception class specified, or specified as Exception.
After running the code when I enter digits it gives me proper value but when I enter character it gives me an error:
UnboundLocalError: local variable 'user_input' referenced before assignment
Please help.
You need to set the 'user_input' outside of the try-catch.
Ex:
def user_input_type():
user_input = raw_input("Enter set of characters or digit") #---->Outside try-except
try:
user_input = int(user_input)
except:
try:
user_input = str(user_input)
except Exception as e:
print e
return type(user_input)
print user_input_type()
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.
I have this code as shown below and I would like to make a function which has a try and except error which makes it so when you input anything other than 1, 2 or 3 it will make you re input it. Below is the line which asks you for your age.
Age = input("What is your age? 1, 2 or 3: ")
Below this is what I have so far to try and achieve what I want.
def Age_inputter(prompt=' '):
while True:
try:
return int(input(prompt))
except ValueError:
print("Not a valid input (an integer is expected)")
any ideas?
add a check before return then raise if check fails:
def Age_inputter(prompt=' '):
while True:
try:
age = int(input(prompt))
if age not in [1,2,3]: raise ValueError
return age
except ValueError:
print("Not a valid input (an integer is expected)")
This may work:
def Age_inputter(prompt=' '):
while True:
try:
input_age = int(input(prompt))
if input_age not in [1, 2, 3]:
# ask the user to input his age again...
print 'Not a valid input (1, 2 or 3 is expected)'
continue
return input_age
except (ValueError, NameError):
print 'Not a valid input (an integer is expected)'
Here is my code:
string = input("Enter a sting")
pos = int(input("Enter the position to be modified"))
try:
b = string.split()
b[pos] = 'k'
b = "".join(b)
print(b)
except:
if string == "":
print("Enter a valid string")
quit()
if pos not in range(len(string)):
print("Enter a valid position to be modified")
quit()
If you try out the code with either a wrong index or an empty string, you will see that the program will run with an IndexError. You can catch that in your except clause. Judging by your question, you said you wanted to quit the program when the exception is caught so the below code will work. I modified the error message in order to not confuse the user as to what they should do next.
string = input("Enter a sting: ")
pos = int(input("Enter the position to be modified: "))
try:
b = string.split()
b[pos] = 'k'
b = "".join(b)
print(b)
except IndexError as e:
if string == "":
print("Error: Need to enter a valid string.")
if pos not in range(len(string)):
print("Error: Need to enter a valid position to be modified.")
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?