I'm getting points for the ZeroDivisionError exception but not the ValueError exception....not sure what's wrong with my exception statement. It looks correct to my noob eyes. Any help is appreciated.
LAB: Simple integer division - multiple exception handlers
Write a program that reads integers user_num and div_num as input, and
output the quotient (user_num divided by div_num). Use a try block to
perform all the statements. Use an except block to catch any
ZeroDivisionError and output an exception message. Use another except
block to catch any ValueError caused by invalid input and output an
exception message.
Note: ZeroDivisionError is thrown when a division by zero happens.
ValueError is thrown when a user enters a value of different data type
than what is defined in the program. Do not include code to throw any
exception in the program.
Ex: If the input of the program is:
15
3
the output of the program is:
5
Ex: If the input of the program is:
10
0
the output of the program is:
Zero Division Exception: integer division or modulo by zero
Ex: If the input of the program is:
15.5
5
the output of the program is:
Input Exception: invalid literal for int() with base 10: '15.5'
My code:
user_num = int(input())
div_num = int(input())
if isinstance(user_num,int) == False:
problem = user_num
elif isinstance(div_num,int) == False:
problem = div_num
try:
result = user_num/div_num
print(int(result))
except ZeroDivisionError:
print("Zero Division Exception: integer division or modulo by zero")
except ValueError:
print("Input Exception: invalid literal for int() with base 10: '{}'".format(problem))
Enter program input (optional)
15.5
5
Program errors displayed here
Traceback (most recent call last):
File "main.py", line 1, in <module>
user_num = int(input())
ValueError: invalid literal for int() with base 10: '15.5'
1: Compare output 2 / 2
Input
15
3
Your output
5
2: Compare output 2 / 2
Input
15
0
Your output
Zero Division Exception: integer division or modulo by zero
3: Compare output 0 / 2
Traceback (most recent call last):
File "main.py", line 1, in <module>
user_num = int(input())
ValueError: invalid literal for int() with base 10: '15.5'
Input
15.5
5
Your output
Your program produced no output
Expected output
Input Exception: invalid literal for int() with base 10: '15.5'
4: Compare output 0 / 1
Traceback (most recent call last):
File "main.py", line 2, in <module>
div_num = int(input())
ValueError: invalid literal for int() with base 10: '0.5'
Input
25
0.5
Your output
Your program produced no output
Expected output
Input Exception: invalid literal for int() with base 10: '0.5'
5: Compare output 0 / 1
Traceback (most recent call last):
File "main.py", line 1, in <module>
user_num = int(input())
ValueError: invalid literal for int() with base 10: 'twenty'
Input
twenty
5
Your output
Your program produced no output
Expected output
Input Exception: invalid literal for int() with base 10: 'twenty'
6: Compare output 1 / 1
Input
0
4
Your output
0
7: Compare output 1 / 1
Input
15
0
Your output
Zero Division Exception: integer division or modulo by zero
user_num = int(input()) and div_num = int(input()) need to go in a try/except ValueError block because the call to int() is where the error can occur.
You can put the whole thing in try/except and catch multiple exceptions:
try:
user_num = int(input())
div_num = int(input())
result = user_num/div_num
print(int(result))
except ValueError as e1:
print(e1)
except ZeroDivisionError as e2:
print(e2)
Or even:
try:
user_num = int(input())
div_num = int(input())
result = user_num/div_num
print(int(result))
except (ValueError, ZeroDivisionError) as e:
print(e)
Related
What I expect from making this code is, I input some numbers, then when I input strings the output is 'Not Valid', but when I press enter without putting some value to input, the output is the sum of numbers that we input before. But when I run it on VSCode, whenever I press enter, the result always 'Not Valid', and can't get out of the loop.
For example, I input: 1 2 3 a z then the output I expect is: Not valid Not valid 6
I don't know what is wrong, I just learned python 2 months ago.
sum = 0
while True:
try:
sum += int(input())
except ValueError:
print('Not Valid')
except EOFError:
print(sum)
break
When you don't input anything, input() will return the empty string. Converting it to an integer is invalid, so you get the ValueError:
>>> input() # next line is empty because I just pressed Enter
'' # `input()` returned the empty string
>>> int('') # can't convert it to an integer
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: ''
To trigger EOFError, send the EOF signal with Ctrl + D:
>>> input()
^DTraceback (most recent call last):
File "<stdin>", line 1, in <module>
EOFError
Here the ^D represents me pressing Ctrl + D on the keyboard (not literally typing "^D").
I'm getting this error. What am I doing wrong? Thank you.
num = input('Enter positive integer: ')
try:
print(int(num))
except:
print('Error: You did not enter a positive integer')
else: # else is executed if no errors were raised
print('Integer input accepted')
finally: # always executes at the end of the try-except block
print('the try block is completed')
if int(num) > 1:
for i in range(2,int(num)):
# for loop is used, iterate from 2 to n / 2
# nested if statement is used to see it's a prime or not:
if (int(num)% i)== 0:
print('It is a composite')
break
else:
print('It is a prime')
break
elif (int(num) ==0 or int(num) ==1):
print('It is neither prime nor composite')
ValueError Traceback (most recent call last)
<ipython-input-46-049b0b9078db> in <module>
11
12
---> 13 if int(num) > 1:
14 for i in range(2,int(num)):
15
ValueError: invalid literal for int() with base 10: '-2.5'
This is actually an interesting point.
Python can parse the string '-2.5' as a float, but not as an int, despite it knowing what to do with int(-2.5), which simply returns the int -2.
If you want to only consider the int part of a float represented as a string, you'll have to first parse the string as a float, then parse the float as an int, like so:
if int(float(num)) > 1:
for i in range(2,int(num)):
...
However, what you may want to do is actually compare the float number and check whether it's greater than 1. In that case you'd simply have to cast the string as float and compare, like so:
if float(num) > 1:
for i in range(2,int(num)):
...
This is a simple exception handling problem in Python. I have tried taking the inputs a and b using the map() but I don't understand why I'm getting the following error.
My solution:
for i in range(int(input())):
a, b = map(int, input().split())
try:
print(a//b)
except BaseException as e:
print("Error Code: ", e)
Input:
3
1 0
2 $
3 1
Output:
Traceback (most recent call last):
File "Solution.py", line 3, in <module>
a, b = map(int, input().split())
ValueError: invalid literal for int() with base 10: '$'
>>> int('$')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: '$'
a, b = map(int, input().split())
this line here tries to cast input to int and your second line input has $ which is not a valid integer. You should have that part in a try except too, like:
for i in range(int(input())):
try:
a, b = map(int, input().split())
except Exception as e:
print("Error Code: ", e)
continue
try:
print(a//b)
except BaseException as e:
print("Error Code: ", e)
I am trying to make a program where you enter an integer, but if you do not enter an integer, handle it with an exception. However I can not find any exceptions for integers on the internet.
### TECH SUPPORT ###
while True:
try:
i = int(input('Enter an INTEGER: '))
except [INT EXCEPTION HERE]:
print("You must enter an INTEGER, not any other format of data")
-
Does anyone know an exception if you ask for an integer input and do not get an integer?
You can always try it in interpreter to see which error gets raised:
>>> int('a')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: 'a'
Now that you know that it is ValueError, just change your code:
while True:
try:
i = int(input('Enter an INTEGER: '))
except ValueError:
print("You must enter an INTEGER, not any other format of data")
else:
break # to exit the while loop
Yes, use ValueError
More about python try except. Go through the builtin exceptions list, which will help you.
Also, when an builtin exception is raised like so -
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: 'a'
You can see
ValueError: invalid literal for int() with base 10: 'a'
So python raisesValueError and this is the exception you need to use.
You can use "ValueError" exception
while True:
try:
i = int(input('Enter an INTEGER: '))
except ValueError:
print("You must enter an INTEGER, not any other format of data")
I´m getting this error while trying to convert string to integer:
Traceback (most recent call last):
File "main.py", line 9, in <module>
n = int(input())
ValueError: invalid literal for int() with base 10: 'python3 main.py'
This is the code:
n = int(input())
if num>0:
cantPos = cantPos+1
You're probably not realizing that the interpreter is prompting you for input. The input() function takes a string argument which will be the prompt. The common pattern to do here is something like:
n = None
while n is None:
try:
n = int(input('Please enter an integer: '))
except ValueError:
print('That was not an integer!')