How to print the value only which is creating exception in python? - python-3.x

try:
a,b = map(int,input().split())
print(a//b)
except ZeroDivisionError:
print("invalid")
except ValueError:
print("this value _ is not allowed for division")
I need to print the value here _ which is caused for exceptions as "#" or "%"

It looks like you're trying to get something similar to the code showed below. This is possible by using regular expressions (through the search() function of the re module) to find the invalid argument that comes in the exception's (e) arguments (args).
e.args is a tuple that looks like the following when the ValueError is raised because of an invalid input entered:
("invalid literal for int() with base 10: '%'",)
Therefore, we could do something as follows:
import re
try:
a, b = map(int, input().split())
print(a // b)
except ZeroDivisionError:
print("Can't divide by zero")
except ValueError as e:
regex_groups = re.search('\'(.+)\'|\"(.+)\"', e.args[0]).groups()
invalid_arg = regex_groups[0] if regex_groups[0] else regex_groups[1]
print(f"This value: {invalid_arg} is not allowed for division")
Testing:
1 $
This value: $ is not allowed for division
Q 2
This value: Q is not allowed for division
% '
This value: % is not allowed for division
20 ?
This value: ? is not allowed for division
50 2
25

Related

Additional ValueError Exception

I am new with exceptions. Especially multiple exceptions.
I am able to excuse this code with positive numbers and raise the ValueError with negative numbers.
My issue is how to "add" an additional exception for ValueError if I were to use a non-integer.
I maybe making it hard than it is.
def findFirstEvenInteger(number_list):
"""Def even integer. The following rest of the function utilizes a modulo operator
that checks if the number is even."""
for element in number_list:
if element % 2 == 0:
return element
raise ValueError
nn = int(input("Please enter any length of elements: "))
meep = []
for x in range(nn):
x = int(input())
meep.append(x)
try:
print("The first even integer in the list: " + str(findFirstEvenInteger(meep)))
except ValueError:
print("All the number are odd")

Why am I getting a syntax error for "except ValueError"

I keep on getting a syntax error for the line "except ValueError"
I tried many things including using 'pass' but it still didn't work.
y=0
while y==0:
x= input ('Enter the time(hour) ')
val = int(x)
if val <0 or val >= 24:
raise ValueError
break
except ValueError:
pass
print("Invalid integer. The number must be in the range of 0-24.")
if val>=12:
print (x + "pm")
else:
print (x + "am")
I wanted the program to return an error and print invalid integer if the 'val' was above or equal to 24 or lower than 0.
The reason you are getting a syntax error is that there is no valid standalone except statement. The correct usage of the except keyword is in a try...except statement.
y=0
while y==0:
x= input ('Enter the time(hour) ')
try:
val = int(x)
if val < 0 or val >= 24:
raise ValueError
break
except ValueError:
print("Invalid integer. The number must be in the range of 0-24.")
if val>=12:
print (x + "pm")
else:
print (x + "am")
Above is your example altered to show the proper use of the except keyword.

How do you code an error message for the wrong user input?

I need to Write a program, that takes input (from STDIN) of a number N, then prints N lines containing "Hello".
0< Max number in Input <=100
I am using Python 3.
User Input = abc
I've tried using if/elif/else to produce an "Error" message if the user inputs anything other than an integer. However, I think my last elif statement opposes the fact that I'm calling the "line" input an integer.
When I use a string as my test case I get a coding error:
Traceback (most recent call last):
File "/temp/file.py", line 3, in <module>
line = int(sys.stdin.readline())
ValueError: invalid literal for int() with base 10: 'abc'
Code:
import sys
line = int(sys.stdin.readline())
if line<1:
print("Error")
elif line>100:
print("Error")
elif line != int:
print("Error")
else:
print("Hello\n" * line)
You want to use a try/except statement:
>>> try:
l = int(input())
except ValueError:
print("Invalid Input")
abc
Invalid Input
If you want it to keep prompting the user until they enter valid input, use a while loop:
while True:
try:
l = int(input())
break
except ValueError:
print("Invalid Input")

python3: how to enable strong typing?

Is there a way to get real strong typing in python3, such that one gets a runtime error, when the wrong type is used?
See following example:
def pick(k:int = None):
if k: print("value: ", k)
else: print("no value")
pick()
pick(1000)
pick("error")
this gives the following output:
no value <- can be accepted, and for this example it would be useful
value: 1000
value: error <- here should come a runtime error
Check this, hope will help. This is one of the way to force type checking.
def pick(k:int = None):
assert isinstance(k, int), 'Value Must be of Interger Type'
print("value: ", k) if k else print("no value") # Single Line Statement
In case of None or string it will raise AssertionError
AssertionError: Value Must be of Interger Type
However if you really need ValueError to be raise then
def pick(k:int = None):
if not isinstance(k, int):
raise ValueError('Value Must be of Interger Type')
print("value: ", k) if k else print("no value") # Single line statement
Exception
ValueError: Value Must be of Interger Type

Getting a syntax error for except in python 3.5.2

I have a function to ask the user to input an integer and I am trying to put in a try function that will replace ValueError with "Input must be an integer." but I keep getting a syntax error for my except! I am using Python 3.5.2
def get_int ():
s = int(input("Give me an integer: "))
return(s)
while s is float:
try:
s = int(input("Give me an integer: "))
except(ValueError) as "Input must be an integer."
print("Input must be an integer.")
except ValueError as:
^
SyntaxError: invalid syntax
except should be at the same indentation level as try, needs a colon before the body, and the as clause is used to hold the error in a variable; something like this:
try:
s = int(input("Give me an integer: "))
except ValueError:
print("Input must be an integer.")

Resources