Understanding the ValueError: "Invalid numbers" in python - python

I have the following question:
Define a function called exce_sum where you return the sum of two arguments
But if both arguments are 0, the function should raise an exception saying "Invalid numbers"
The exception needs to have the ValueError() class and the return type of the exception must be a string.
Use try and except.
I wrote the following code:
def exce_sum(x,y):
if x==0 and y==0:
raise ValueError("Invalid numbers")
try:
z=x+y
return(z)
except:
return("the return type of the exception must be a string")
When I write the function exce_sum(0,0)
I receive the error ValueError: Invalid numbers and not ValueError: "Invalid numbers".
However, I do not know how to receive the error ValueError: "Invalid numbers".
Thank you in advance for your help

Change this to
if x==0 and y==0:
raise ValueError("Invalid numbers")
this
if x==0 and y==0:
raise ValueError('"Invalid numbers"')

I don't think you are supposed to print the double quotes anyway :) When exceptions are printed out to console, the message is typically not enclosed in double quotes.
The following should do the trick (you had an unnecessary try-except block):
def exce_sum(x, y):
if x == 0 and y == 0:
raise ValueError("Invalid numbers") # if you still want the quotes use '"Invalid numbers"'
z = x + y
return str(z)

Solution for your questions could be
def exce_sum(num1,num2):
try:
if (num1 == 0 and num2 == 0):
raise ValueError("Invalid Numbers")
else:
return num1 + num2
except ValueError as error:
print(error)
exce_sum(0,0)

Related

May I use True for Python type hintings?

Can I or should I use True or False for Python type hinting?
def can_be_used_as_divider(num) -> True:
if num == 0:
raise ValueError('The number must not be zero!')
return True
I have a function that raises some error in different cases and returns True if it doesn't.
Should I raise errors, return errors or there is any good pattern for this?
You can use typing.Literal.
Example:
from typing import Literal
def can_be_used_as_divider(num) -> Literal[True]:
if num == 0:
raise ValueError('The number must not be zero!')
return True

Exception Handling by validating simple inputs

I am new to Python, after I managed to learn Java at an advanced level.
In Java input validation with exception handling was never a problem to me but somehow in python i get a little confused:
Here an example of a simple FizzBuzz programm which can only read numbers in between 0 and 99, if otherwise, an exception has to be thrown:
if __name__ == '__main__':
def fizzbuzz(n):
try:
if(0<= n <= 99):
for i in range(n):
if i==0:
print("0")
elif (i%3==0 and i%7==0) :
print("fizzbuzz")
elif i%3==0:
print("fizz")
elif i%7==0:
print("buzz")
else:
print(i)
except Exception:
print("/// ATTENTION:The number you entered was not in between 0 and 99///")
try:
enteredNumber = int(input("Please enter a number in between 0 and 99: "))
fizzbuzz(enteredNumber)
except Exception:
print("/// ATTENTION: Something went wrong here. Next time, try to enter a valid Integer ////")
If i run that and enter e.g. 123 the code just terminates and nothing happens.
You need to raise an exception from fizzbuzz() when your condition is not met. Try below:
if __name__ == '__main__':
def fizzbuzz(n):
try:
if(0<= n <= 99):
for i in range(n):
if i==0:
print("0")
elif (i%3==0 and i%7==0) :
print("fizzbuzz")
elif i%3==0:
print("fizz")
elif i%7==0:
print("buzz")
else:
print(i)
else:
raise ValueError("Your exception message")
except Exception:
print("/// ATTENTION:The number you entered was not in between 0 and 99///")
try:
enteredNumber = int(input("Please enter a number in between 0 and 99: "))
fizzbuzz(enteredNumber)
except Exception:
print("/// ATTENTION: Something went wrong here. Next time, try to enter a valid Integer ////")
Also, you must catch specific exceptions instead of catching the generic exception.
If you want to catch an exception you need to make sure it will get raised if the desired scenario occurs.
Since the code block between try and except does not raise an exception by itself, you need to raise one by yourself:
try:
if(0<= n <= 99):
...
else:
raise Exception()
except Exception:
...

Try-Except ErrorCatching

I'm trying to force the user to input a number using try-except in python however it seems to have no effect.
while count>0:
count=count - 1
while (length != 8):
GTIN=input("Please enter a product code ")
length= len(str(GTIN))
if length!= 8:
print("That is not an eight digit number")
count=count + 1
while valid == False:
try:
GTIN/5
valid = True
except ValueError:
print("That is an invalid number")
count=count + 1
Actually, if the user inputs for example a string, "hello"/5 yields a TypeError, not a ValueError, so catch that instead
You could try to make the input value an int int(value), which raises ValueError if it cannot be converted.
Here's a function that should do what you want with some comments:
def get_product_code():
value = ""
while True: # this will be escaped by the return
# get input from user and strip any extra whitespace: " input "
value = raw_input("Please enter a product code ").strip()
#if not value: # escape from input if nothing is entered
# return None
try:
int(value) # test if value is a number
except ValueError: # raised if cannot convert to an int
print("Input value is not a number")
value = ""
else: # an Exception was not raised
if len(value) == 8: # looks like a valid product code!
return value
else:
print("Input is not an eight digit number")
Once defined, call the function to get input from the user
product_code = get_product_code()
You should also be sure to except and handle KeyboardInterrupt anytime you're expecting user input, because they may put in ^C or something else to crash your program.
product code = None # prevent reference before assignment bugs
try:
product_code = get_product_code() # get code from the user
except KeyboardInterrupt: # catch user attempts to quit
print("^C\nInterrupted by user")
if product_code:
pass # do whatever you want with your product code
else:
print("no product code available!")
# perhaps exit here

ValueError exception not working in python

I'm trying to make a simple program that will calculate the area of a circle when I input the radius. When I input a number it works, but when I input something else I'd like it to say "That's not a number" and let me try again instead of giving me an error.
I can't figure out why this is not working.
from math import pi
def get_area(r):
area = pi * (r**2)
print "A= %d" % area
def is_number(number):
try:
float(number)
return True
except ValueError:
return False
loop = True
while loop == True:
radius = input("Enter circle radius:")
if is_number(radius) == True:
get_area(radius)
loop = False
else:
print "That's not a number!"
When you don't input a number, the error is thrown by input itself which is not in the scope of your try/except. You can simply discard the is_number function altogether which is quite redundant and put the print statement in the except block:
try:
radius = input("Enter circle radius:")
except (ValueError, NameError):
print "That's not a number!"
get_area(radius)
radius is still a string,
replace
get_area(radius)
with
get_area(float(radius))
You also have to replace input with raw_input since you're using Python 2
in= 0
while True:
try:
in= int(input("Enter something: "))
except ValueError:
print("Not an integer!")
continue
else:
print("Yes an integer!")
break

Python, distinguishing custom exceptions

fairly new to Python here. Have this code:
def someFunction( num ):
if num < 0:
raise Exception("Negative Number!")
elif num > 1000:
raise Exception("Big Number!")
else:
print "Tests passed"
try:
someFunction(10000)
except Exception:
print "This was a negative number but we didn't crash"
except Exception:
print "This was a big number but we didn't crash"
else:
print "All tests passed and we didn't crash"
I originally used raise "Negative Number!" etc but quickly discovered that this was the old way of doing things and you have to call the Exception class. Now it's working fine but how do I distinguish between my two exceptions? For the code below it's printing "This was a negative number but we didn't crash". Any pointers on this would be great. Thanks!
you need to create your own exception classes if you want to be able to distinguish the kind of exception that happened. example (i inherited from ValueError as i think this is the closest to what you want - it also allows you to just catch ValueError should the distinction not matter):
class NegativeError(ValueError):
pass
class BigNumberError(ValueError):
pass
def someFunction( num ):
if num < 0:
raise NegativeError("Negative Number!")
elif num > 1000:
raise BigNumberError("Big Number!")
else:
print "Tests passed"
try:
someFunction(10000)
except NegativeError as e:
print "This was a negative number but we didn't crash"
print e
except BigNumberError as e:
print "This was a big number but we didn't crash"
print e
else:
print "All tests passed and we didn't crash"

Categories

Resources