Determining the source of error in try - except - python-3.x

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

Related

using errors in conditions in python

I need help with my quadratic calculating program. I used an expression in an If, the expression will result in a math error obviously. But I don't want the code to break down when the error occurs instead, I want something else to happen.
import math
def quad(a, b, c):
# creating a variable for all the parts that make the expression
first_nu = int(a)
second_nu = int(b)
third_nu = int(c)
four = 4
two = 2
det = second_nu ** 2 - (four * (first_nu * third_nu))
if math.sqrt(det) == 0:
print(' the discriminant is 0 hence the quadratic has no real roots')
else:
# calculating the roots
root_det = math.sqrt(det)
def printing():
option1 = (-third_nu + root_det) / (two * first_nu)
option2 = (-third_nu - root_det) / (two * first_nu)
print(option1, option2)
if det < 0:
printing()
print('The roots are not real roots')
elif det == 0:
print('mathematical error in a situation where there is root of 0')
print('The roots has just one real root')
elif det > 0:
printing()
print('The roots has two real roots')
first_num = input("enter your first number of the quadratic")
second_num = input("enter your second number of the quadratic")
third_num = input("enter your third number of the quadratic")
quad(first_num, second_num, third_num)
Use try: on the code you want to test and put the rest of the code in except. I hope this will solve the issue. For more information about Python error handling here or check from w3schools
The try block lets you test a block of code for errors.
The except block lets you handle the error.

name 'count' is not defined in python

I have this code in python and I am trying to make a counter for the iteration of the binary search (yeah I know it is incomplete...), but I am stuck with the variable inside the function, when i try to print the variable count I get this error
name 'count' is not defined in python
can someone explain why i get this error?
import csv
def binarySearch(arr, l, r, x):
count=0
while l <= r:
mid = int(l + (r - l) / 2)
# Check if x is present at mid
if arr[mid] == x:
return mid
# If x is greater, ignore left half
elif arr[mid] < x:
l = mid + 1
# If x is smaller, ignore right half
else:
r = mid - 1
# If we reach here, then the element
# was not present
return -1
with open('bl_printed_music_500.csv', newline='', encoding="utf-8-sig") as csvfile:
reader = csv.DictReader(csvfile)
arr=[]
for row in reader:
if row ["Publication date (standardised)"] != "":
arr.append(int(row["Publication date (standardised)"])) #create list for searching
list.sort(arr) #list must be sorted to work
#print (arr)
x = 1850 #year to search
# Function call
result = binarySearch(arr, 0, len(arr) - 1, x)
found = False
if result != -1:
found = True
print(found)
print(count)
I think it's because you defined count in binarySearch but try to use it outside of the method. Try using a global variable (define it outside of binarySearch), it should work.
You can return count as well.
For example:
def myFunc():
x = 5
y = 10
return x,y
a, b = myFunc()
print(a)
print(b)
This will be:
5
10
Note that, I could have written x, y = myFunc(). These x and y are not the same as the ones inside myFunc(). The latter are local to the function.
In your code, you can return your local count variable:
return mid, count #(A)
return -1, count #(A)
And get its value by:
result, count = binarySearch(arr, 0, len(arr)-1, x) #(B)
Again, these two count variables, (A) and (B) are different variables with different scopes.
See, for instance:
https://docs.python.org/3/faq/programming.html#why-am-i-getting-an-unboundlocalerror-when-the-variable-has-a-value
Alternatively, if a global variable, as suggested in the other answer, suits you best, you can see an example of its usage in the link.

What is wrong with my function? Giving me a blank output

def get_nearest_multiple(minnum, factor):
"""
function get_nearest_multiple will calculate the nearest multiple that is greater than the min. value,
Parameters are the minimum value and factor,
Will return the ans - the nearest multiple
"""
ans = 0
x = 1
while ans < minnum:
if minnum == 0:
ans = 0
else:
ans = x * factor
x += 1
return ans
get_nearest_multiple(0, 1)
if __name__ == '__main__':
get_nearest_multiple(0, 1)
Can't seem to figure out why my function doesn't print out anything. The output doesn't even show up as an error. Just blank.
Nowhere in your code do you have a print() statement which is required to produce an output in the console

Finding variables in a list

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

Simulating n games of craps in python

I'm pretty new to python and I have been trying to make this simulator that creates a simulator for "games" of craps. My professor wanted it to be made in the most basic form possible which is the reason for having a function for rolling one dice then another. For some reason I can't get my simOneGame function to cooperate and I can't even get it to print a value when I assign a variable to it although it should print a 1 or 0. Here is my code:
def main():
x = eval(input("how many games will be played?: "))
y = simNGames(x)
print(y)
def simOneGame():
win = 0
lose = 0
x = rollDice()
if x == 2 or x == 3 or x == 12:
lose += 1
elif x == 7 or x == 11:
win += 1
y = rollDice()
while y != 7 or y != x :
y = rollDice()
if y == x:
win += 1
elif y == 7 :
lose += 1
if win > lose:
return(1)
else:
return(0)
def simNGames(n):
wins = 0
loses = 0
x = simOneGame()
for i in range(n):
if x > 0:
wins += 1
else:
pass
frac = wins / n
return float(frac)
def rollDice():
return rollDie() + rollDie()
def rollDie():
return randrange(1,7)
I don't get an answer unless input a number greater than 100 and it's always a 1.0
There are several issues I see with your code.
First off, your simNGames only actually simulates one game, but then it adds up that game's results n times. You need to move your x = simOneGame() line inside the loop so that it gets called repeatedly.
There's a separate issue with your simOneGame function's logic. A single craps game is either won or lost, there's no scoring. That means you don't need to be adding up win and loss values. You should change all the places where you do win += 1 to do return 1 instead, and all the places that do lose += 1 should be return 0 (this means you can get rid of the rest of the code dealing with the win and lose variables too).
You also might consider returning True and False rather than 1 and 0, but this might have been decided by your teacher, and it's more a design style point than an error.
Finally, I think the while loop in simOneGame needs an and rather than an or to make the logic work correctly.

Resources