I want to handle ValueError in Python. But whenever I type the below code I get an error and I want the output as I excepted.
a, b = map(int, input().split())
try:
print(a//b)
except ZeroDivisionError as e:
print('Enter code: ', e)
except ValueError as e:
print('Enter code: ', e)
If my inputs for a and b are '1' and '$' than
Expected output for ValueError: 'Enter code: invalid literal for int() with base 10: $
Your problem is before your try, here a, b = map(int, input().split())
The $ is given to int, this fails and raise the invalid literal for int() with base 10: $ which is pretty explicit
try:
a, b = map(int, input().split())
print(a//b)
except ZeroDivisionError as e:
print('Enter code: ', e)
except ValueError as e:
print('Enter code: ', e)
Related
I am practicing with error handling and I have a question. can you make it so the error messages in the assert will be displayed in the except block right now if a error occurs only 'error' is printed and not the actual error message
try:
a = int(input('Please enter the first number it must be >= 200' + '\n' + '(note the sum of both numbers must be <=300)'))
b= int(input('please your second number it must be <= 50'))
c = a + b
assert a >=200 and isinstance(a, int), 'invalid entry for a must be <= 200 and a number'
assert b<=50 and isinstance(b, int), 'invalid entry for b must be <=50 and a number'
assert c <= 300, 'The sum of your numbers is >300'
except ValueError
print('error')
else:
print('All in range')
Add an except that catches the AssertionError and prints it:
except AssertionError as e:
print(e.args[0] if e.args else "error")
I am beginner to python and I have doubt in one program when using try except part
I try to take input from user and add that number by 1 like if you enter 5 then 6 will be printed but if you enter string then except would come in role and print enter only number
I've written code but except is not working there, code is working like if I enter 5 then 6 gets printed but except statement is not working
Here is the code that I've written
def increment(num):
try:
return num + 1
except Exception as e:
print("ufff error occured :", e)
n = int(input("enter your num: "))
a = increment(n)
print(a)
You would have to change to the following:
def increment(num):
try:
return int(num) + 1
except Exception as e:
print("ufff error occured :", e)
n = input("enter your num: ")
a = increment(n)
print(a)
The reason for that is that the exception was raised by the int() functions, because it couldn't convert your input to int. The call to int() was before the increment function. Therefore the exception was unhandled.
You tried converting the input to int before going into the try/except block. If you just put it in the try block it will work.
def increment(num):
try:
num = int(num)
return num + 1
except Exception as e:
print("ufff error occured :", e)
n = input("enter your num: ")
a = increment(n)
print(a)
You have to use the type conversion within the try block so that if num is not a number, the controller would move to expect portion.
The problem here is you are using type conversion outside of try-catch block.
Another point to note, convert e to string as a good practice.
Third point to note,the last line print(a) will itself cause trouble in cases of exception as you have returned nothing from the exception part and directly printed the error. Use a return statement in there else it would return None type and which itself will mess up the flow.
def increment(num):
try:
return int(num) + 1 #Updated Line
except Exception as e:
return "ufff error occurred :" + str(e) #Updated Line
n = input("enter your num: ")
a = increment(n)
print(a)
Might I recommend the following?
def increment(num):
try:
return int(num) + 1
except Exception as e:
print("ufff error occurred:", e)
n = input("enter your num: ")
a = increment(n)
print(a)
The only difference here is that the attempt to convert the user's input to an int occurs within the try-except block, rather than outside. This allows the type conversion error to be caught and your message ("ufff error occurred: ...") to be displayed.
Edit: regarding your comment:
yes it worked out thanks everyone, but can anyone tell what should i have to do if i use int with input line what changes i've to make
Optionally, you could do the following:
def increment(num):
return num + 1
try:
n = int(input("enter your num: "))
a = increment(n)
print(a)
except Exception as e:
print("ufff error occurred:", e)
In this case, I would recommend removing the try-except block in the increment function, because you can safely assume that all values passed to that function will be numeric.
The only code that would raise an exception is the int(...) conversion - and it is not protected under a try/except block. You should put it under the try:
def increment():
try:
return int(input("enter your num: ")) + 1
except ValueError as e:
return f"ufff error occured: {e}"
print(increment())
You should always try to catch the narrowest exception. In this case, a ValueError.
Hi in my assessment i need to raise value errors but my code doesnt work and i dont know why can someone help me please
my code need to ask uurloon and gewerkte_uren if the user doesnt enter int/float he needs to get a error and the program must end when when the program is entered correctly.
can someone please help me :(
def program():
while True:
try:
uurloon = float(input("Hoeveel euro's verdien je per uur: "))
gewerkte_uren = float(input("Hoeveel uur heb je gewerkt: "))
salaris = (gewerkte_uren * uurloon)
print(f"{gewerkte_uren} uren werken levert €{salaris} op.")
except KeyboardInterrupt as a:
print(a)
raise
except OverflowError as b:
print(b)
raise
except ZeroDivisionError as c:
print(c)
raise
except IOError as d:
print(d)
raise
except IndexError as e:
print(e)
raise
except NameError as f:
print(f)
raise
except TypeError as g:
print(g)
raise
except ValueError as h:
print(h)
raise
program()
new code:
while True:
try:
uurloon = float(input("Hoeveel euro's verdien je per uur: "))
gewerkte_uren = float(input("Hoeveel uur heb je gewerkt: "))
salaris = (gewerkte_uren * uurloon)
print(f"{gewerkte_uren} uren werken levert €{salaris} op.")
break
except KeyboardInterrupt as a:
print(a)
except OverflowError as b:
print(b)
except ZeroDivisionError as c:
print(c)
except IOError as d:
print(d)
except IndexError as e:
print(e)
except NameError as f:
print(f)
except TypeError as g:
print(g)
except ValueError as h:
print(h)
i almost got it but when you enter the first input correctly and second wrong it goes back to the first input how can i program it that if you do the second one wrong it asks you to insert the second one again instead of running the program again?
You don't need the raise if you want your program to continue the run. That's how you threw exceptions.
You can catch the exception when Python can't convert the vars uurloon and gewerkte_uren to Float
Like that:
try:
uurloon = float(input("Hoeveel euro's verdien je per uur: "))
gewerkte_uren = float(input("Hoeveel uur heb je gewerkt: "))
salaris = (gewerkte_uren * uurloon)
print(f"{gewerkte_uren} uren werken levert €{salaris} op.")
except ValueError:
print("enter a number")
Task1
Write a script that reads a string from STDIN and raise ValueError
exception if the string has more than 10 characters or else prints the
read string.
I wrote the code like this
a = input("Enter a string")
if(len(a) > 10):
raise ValueError
else:
print(a)
Task2
Use try ... except clauses. Print the error message inside except
block.
I am now confused about how to use try-except here because to print any message in except block the program has to fail at try block.
My input will be PythonIsAmazing
You can just wrap the whole thing in try ... except as follows:
a = input("Enter a string: ")
try:
if(len(a) > 10):
raise ValueError
print(a)
except ValueError:
print("String was longer than 10 characters")
Alternatively, if you had lots of different ValueErrors that might be raised, you could give each a separate error message:
a = input("Enter a string: ")
try:
if(len(a) > 10):
raise ValueError("String was longer than 10 characters")
print(a)
except ValueError as e:
print(e)
Eg:
Enter a string: test
test
Enter a string: PythonIsAmazing
String was longer than 10 characters
I was trying to find a way to do this in python 3.6.5 which is not supported
try:
c=1/0
print (c)
except ZeroDivisionError, args:
print('error dividing by zero', args)
It says this type of syntax is not supported by python 3.6.5
So is there a way to get the arguments of the exception?
How about:
try:
c=1/0
print (c)
except ZeroDivisionError as e:
print('error dividing by zero: ' + str(e.args))
Comma notation is now used to except multiple types of exceptions, and they need to be in parentheses, like:
try:
c = int("hello")
c = 1 / 0
print(c)
except (ZeroDivisionError, ValueError) as e:
print('error: ' + str(e.args))