How to use raise ValueError? - python

I want to see ValueError 4 times but it is showing once, why the program cutting to search the other double numbers?
def isitDoubleorSingle(value):
if(value%2!=0):
raise ValueError("Number isn't double")
print(value)
list=[10,22,79,43,11,80]
for x in list:
isitDoubleorSingle(x)

This will solve your problem. You have to catch your Error in the except block or your script will stop running at your first raise ValueError()
edit: As #Nin17 said, you shouldn't redefine the built-in list, so renaming the list in my_list(or any name you want) should be better.
def isitDoubleorSingle(value):
try:
if(value%2!=0):
raise ValueError()
except ValueError:
print(f"Number {value} isn't double")
my_list=[10,22,79,43,11,80]
for x in my_list:
isitDoubleorSingle(x)

When you raise an exception, the program is already closed automatically, so it is not possible to display the ValueError more than once

Related

Unable to Catch Exception and Raise Error in Python

Suppose that I have a variable initial_cash = 'a'. I want to check if this is convertible to float else I want to raise error for that I've written code below:
initial_cash = 'a'
try:
initial_cash = float(initial_cash)
except TypeError:
raise TypeError("Initial cash amount should be float or int")
I am unable to raise exception instead I get ValueError: could not convert string to float: 'a'. What am I doing wrong due to which the expectation is not caught?
Your answer is in the error message - ValueError. you should expect ValueError instead of TypeError.

Python Try and Except

So recently, I learned something new which is Try and Except, and I still can't really get how it functions. Here is simple code of block. I would like some explanation on how this codes will run. Dish here refers to an item from dictionary. Note : Either ValueError or KeyError can be raised.
try:
return dish["name"].index(cost["$"])
except KeyError:
return None
let's assume you have two dictionaries:
dish = {"name": ["A", "B", "C", "D"]}
cost = {"$": "A"} # It should be any value in A,B,C,D else it will raise Value Error for dish["name"].index(cost["$"])
Now if you want to raise ValueError Then you should search the index of value that does not exist in the list in your case
if I try to do this:
# return dish["name"].index(cost["$"]) $ This will raise ValueError if
# cost['$']= "E" because "E" does not exist in dish["name"] list so it will raise value error
Let me know if it explains your use case.
Quick example but see https://docs.python.org/3/tutorial/errors.html for more info.
Your code will "try" and run the line
return dish["name"].index(cost["$"])
and if there is a ValueError then it will execute the code
return None
A ValueError is a mathematical error such as division by zero. If your code encounters a ValueError, it will run Return None, which does nothing. Try replacing return None with something like print("Exception") and force a value error to see what will happen.

I want to return KeyError not None

I want to return KeyError but instead it returns None. I do not understand why.
if index == self.length or self.slots[index]==None:
raise KeyError
You don't raise a KeyError because you don't enter the if-branch. And you don't enter the if-branch because none of your conditions is true.
You probably need to adjust your condition if the test-case (that you haven't shown!) should really raise the KeyError.
To debug this issue you can insert some print-statements:
print(index, self.length, index==self.length)
print(self.slots[index], self.slots[index]==None)
if index == self.length or self.slots[index]==None:
raise KeyError
or use a debugger of your choice.
However some comments:
Normally you want to check if the index is >= to the length (that includes ==!).
You should compare to None using is. None and NotImplemented are guaranteed singletons.
Use an Exception message in KeyError, for example raise KeyError('index out of bounds or item is None! Try again.')
Functions that don't have hit an explicit return will return None. That's probably why your code returned None instead!

Try Except float but not integer

So, I've approached an obstacle in a programming exercise. I understand the concept of try except but how can I use a try except handler to only accept a float or decimal and if a whole number or integer is entered, it throws an error message. I know in theory it's not possible but is there a way?
Ideally I want to use a try except block of code as that's the current lesson I am on.
Thanks to all in advance!
How about using .is_integer() on float?
>>> float(5).is_integer()
True
>>> float(5.12).is_integer()
False
>>>
so
if float(x).is_integer():
raise ValueError('Non integers please')
There are good answers here, but so far the answers do not use try/except as requested. To use try except, you need try something that will throw an exception if false and then catch the exception.
try:
x / (x - int(x))
except ZeroDivisionError:
raise Exception("No integers allowed.")
if type(variable) is not float:
raise ValueError('Invalid number provided')
OR
if type(variable) is int:
raise ValueError('Invalid number provided')
OR (to check if whole number):
if abs(variable) - floor(abs(variable)) < 1.0e-9:
raise ValueError('Invalid number provided')
you can check the number against types.
# add or remove types from the list
if type(num) in (float, int, Decimal):
do something

How to better write multiple exceptions with redundant code in Python?

How can I better write the following snippet in Python:
try:
statement-1
except Exception1:
codeblock-1
codeblock-2
except Exception2:
codeblock-2
Just to be clear, I want to execute two codeblocks when the first exception occurs, while only the latter of these two codeblocks when the second exception occurs.
You have two options, as I see it; either:
Extract codeblock-2 into a function and just call it (you repeat only one line this way); or
Catch both exceptions in the same except, then handle the two cases appropriately by checking the type of the caught exception.
Note that these aren't mutually exclusive, and the second approach is probably more readable if combined with the first. A snippet of the latter:
try:
statement-1
except (Exception1, Exception2) as exc:
if isinstance(exc, Exception1):
codeblock-1
codeblock-2
In action:
>>> def test(x, y):
try:
return x / y
except (TypeError, ZeroDivisionError) as exc:
if isinstance(exc, TypeError):
print "We got a type error"
print "We got a type or zero division error"
>>> test(1, 2.)
0.5
>>> test(1, 'foo')
We got a type error
We got a type or zero division error
>>> test(1, 0)
We got a type or zero division error
I would just straightforwardly use local function:
def exception_reaction():
codeblock2()
try:
statement1()
except Exception1:
codeblock1()
exception_reaction()
except Exception2:
exception_reaction()

Categories