Finding variables in a list - python-3.x

I am looking for error checking while searching a list, I ran into an issue with loading an unloading. I am looking for a way to have the script return what variable failed.
thisList = ['tacos', 'beer', 'cheese']
try:
x = thisList.index('beer')
y = thisList.index('eggs')
except ValueError as e:
DO AWESOME
At this point I would like single out y.
Thank you in advance.

As far as I know, this is not possible using a single try/except.
Instead, you could either use one try/except for each of the problematic lines...
try:
x = thisList.index('beer')
except ValueError as e:
print("x not found")
try:
y = thisList.index('eggs')
except ValueError as e:
print("y not found")
... or write yourself a helper function, like find for strings, that instead of raining an exception returns some special sentinel value that you can check afterwards.
def find(l, e):
try:
return l.index(e)
except ValueError:
return -1
x = find(thisList, 'beer') # x is 1
y = find(thisList, 'eggs') # y is -1

Related

Why does having a return statement in my try block make the 'else' statement unreachable?

I'm learning exception handling in Python3 and can't seem to understand why the else statement in my if-else block is unreachable when using return in the try block.
def simple_division() -> float:
"""
:return: the quotient of a / b
"""
a, b = _git_int()
if a == 0:
return 0
else:
try:
return a / b
except ZeroDivisionError:
print("Uh, you can't divide by zero, bud.")
else:
print("This should execute if no exceptions are raised, right? but it doesn't")
finally:
print("This should execute either way.")
I spent some time debugging in order to figure out that the return statement in the try block was at fault... and I now understand that doing something like this circumvents the problem:
def simple_division() -> float:
"""
:return: the quotient of a / b
"""
a, b = _git_int()
if a == 0:
return 0
else:
try:
answer = a / b
except ZeroDivisionError:
print("Uh, you can't divide by zero, bud.")
else:
print("This DOES work")
return answer
finally:
print("This should execute either way.")
But I haven't yet found any documentation explaining why you can't have a return statement in a try block. Could someone explain this to me? What would be the best practice here?

Determining the source of error in try - except

I was wondering if there is way to identify the source of error in a try - except clause. consider the following example:
x = 1
y = 2
z = 0
if I do something like:
result = x / z
I know I would get a zero division error, also I know I can catch this error like this:
try:
result = x / z
except ZeroDivisionError:
print("you divided by zero")
Now my question is if I have something like this
try:
result = x / z
result2 = y / x
except ZeroDivisionError:
print("you divided by zero")
is there a way in python with out if else condition that let me know that the error is in "result" so I can deal with it (for example set this variable to a default value).
try:
result = x / z
result2 = y / x
except ZeroDivisionError:
print("you divided by zero, dealing with the error...")
# a way that python letting me know that the error is due to result variable
# set result to default value
result = 10
You can get it from exception
try:
result = x / z
result2 = y / x
except ZeroDivisionError as ex:
print(ex.__traceback__.tb_lineno)
print("you divided by zero, dealing with the error...")
ex.__traceback__.tb_lineno is line number where exception was raised
Docs: https://docs.python.org/3/library/traceback.html#traceback.TracebackException.lineno
But it is very bad code practice. In your case it is better to check if one of variables is equal 0. It is a lot easier and better in terms of code writing practics
if z == 0:
result = 10
else:
result = x / 10
If there is a case when you can't avoid try-except you can just get two try-excepts to be sure where exception wad raised

Keep getting Infinite loop in try-except block

I'm trying to make a list from user input but only if the input is numbers, and Im using a try except block with ValueError to display an error message and repeat, but I keep getting stuck in an infinite loop after the except block. I'm not familiar with error handling so I don't know how to fix it.
print('Input coords: x y z')
coords = input('Nether coords: ')
while True:
try:
coordslist = [int(i) for i in coords.split()]
except ValueError:
print('Please use numbers and proper format: x y z')
else:
from time import sleep
print('Converting', end='')
sleep(.5)
print('.', end='')
sleep(.5)
print('.', end='')
sleep(.5)
print('.')
convertedcoords = [i * 8 for i in coordslist]
print(convertedcoords)
break
finally:
print('Done')
I tried putting break in the except block but it just stopped entirely. Is it something with the while statement or am I formatting wrong in general?
Thanks

Additional ValueError Exception

I am new with exceptions. Especially multiple exceptions.
I am able to excuse this code with positive numbers and raise the ValueError with negative numbers.
My issue is how to "add" an additional exception for ValueError if I were to use a non-integer.
I maybe making it hard than it is.
def findFirstEvenInteger(number_list):
"""Def even integer. The following rest of the function utilizes a modulo operator
that checks if the number is even."""
for element in number_list:
if element % 2 == 0:
return element
raise ValueError
nn = int(input("Please enter any length of elements: "))
meep = []
for x in range(nn):
x = int(input())
meep.append(x)
try:
print("The first even integer in the list: " + str(findFirstEvenInteger(meep)))
except ValueError:
print("All the number are odd")

How to make the try function only print my message once

I've tried using the try() function, but when i try: and then type print() it just prints the message non-stop. how do i make it only print once?
def inputInt(minv, maxv, message):
res = int(input(message))
while (res > minv) and (res < maxv):
try:
print("Good job.")
except:
print("Invalid input")
Have you tried with break?
Take a look at this and this to get more clarification, but if you want that at the one time the try jumps to the except, it should print it once only, breakis the thing.
I must say this loop will go on forever as you are not changing res. Even if it goes in the try or in the except.
The code that could raise an exception should be in the try. The input should be inside the while. Catch expected exceptions in case an unexpected exception occurs. A naked except is bad practice and can hide errors.
Here's a suggested implementation:
def inputInt(minv, maxv, message):
while True: # Loop until break
try:
res = int(input(message)) # Could raise ValueError if input is not an integer.
if minv <= res <= maxv: # if res is valid,
break # exit while loop
except ValueError: # Ignore ValueError exceptions
pass
print("Invalid input") # if didn't break, input or res was invalid.
return res # Once while exits, res is good
x = inputInt(5,10,"enter number between 5 and 10: ")

Resources