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.
Related
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
I am required to write a function that takes a simple mathematical formula as a string as an argument. The function should then return the result of that formula. For example, for the input "2 + 3" the function should return 5.
A string is considered a valid formula if it has the format . Note that operator and integer are separated by whitespace.
A valid operator is either +, -, * or /
If a string doesn't consist of three parts (integer operator integer), the function should raise a ValueError with the message "Formula must be of the following format: ."
If the first part or the last part of the input string can't be converted to integers, the function should raise a ValueError with the message "Expected two integers."
If the second part of the string is not one of the valid operators, the function should raise a ValueError with the message "Invalid operator ''. Expected one of these operators: +, -, *, /."
If the second integer is zero and the operator is /, the function should raise a ZeroDivisionError with the message "Division by zero not possible."
So far I've managed to split the string by whitespace and convert the [0] and [2] indexes to integers to be used in solving the respective mathematical equations, and I've also written a try: except: block that successfully catches invalid operators and returns the desired error message. My problem is going on to accommodate the other exceptions as outlined in the conditions, although I've written code that attempts to catch the exceptions and print the relevant error messages, it isn't working and I'm still getting the default internal python error messages. I'm assuming something in my approach is off, maybe the order that the try: except blocks are written in? something with the indenting? I'm new to this so any pointers or advice would be much appreciated.
def formula_from_string(formula):
valid_operators = '+-*/'
chopped=formula.split()
equa=int(chopped[0]),chopped[1],int(chopped[2])
subtraction=equa[0]-equa[2]
addition=equa[0]+equa[2]
division=equa[0]/equa[2]
multiplication=equa[0]*equa[2]
if chopped[1]=='+':
return(addition)
elif chopped[1]=='-':
return(subtraction)
elif chopped[1]=='*':
return(multiplication)
elif chopped[1]=='/':
return(division)
try:
if chopped[1] not in valid_operators:
invalid=chopped[1]
raise ValueError
except ValueError:
print('Value Error:')
return("Invalid operator '"+invalid+"'. Expected one of these operators: +, -, *, /.")
try:
if chopped[0] or chopped[2] != int:
raise ValueError
except ValueError:
print('Value Error:')
return('Expected two integers.')
try:
if equa[1]=='/' and equa[2]==0:
raise ZeroDivisionError
except ZeroDivisionError:
print('ZeroDivisionError:')
return('Division by zero not possible.')
try:
if chopped <=1 or chopped >=2:
raise ValueError
except ValueError:
print('ValueError:')
return('Formula must be of the following format: <integer> <operator> <integer>.')
This code should helps you.
learn about Regex (Regular Expressions)
See Regular expression operations
import re
def formula_from_string(formula):
valid_operators = '+-*/'
pattern = re.compile(r'^(\d+)(?:\s+)?([*/+\-^])(?:\s+)?(\d+)$')
try:
if match := pattern.search(formula):
operator = match.group(2)
if operator not in valid_operators:
raise ValueError(f"Invalid operator {repr(operator)}. Expected one of these operators: +, -, *, /.")
else:
raise ValueError('Formula must be of the following format: <integer> <operator> <integer>.')
return eval(formula) # Safe call
except (ValueError, ZeroDivisionError) as e:
print(e)
# Uncomment to see output
# formula_from_string('3 / 2') # 1.5
# formula_from_string('3 ^ 2') # ValueError Invalid operator
# formula_from_string('a / 2') # ValueError Formula must be...
# formula_from_string('3 / 0') # ZeroDivisionError
I still get a:
ValueError: invalid literal for float(): 002Q
when I try to:
df.column_name.astype(np.float64)
even after doing this on my column:
def convert_float(x):
try:
return np.float64(x)
except ValueError:
return np.NaN
df.column_name.apply(convert_float).astype(np.float64)
I also looked in the data manually, but could not find any value 002Q
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 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()