Can't catch ValueError in Python - python

I am starting to learn Python, and I wrote a very simple code to practice try/except.
Here is the code:
a = float(input('num1: '))
b = float(input('num2: '))
try:
result = a / b
except ValueError as e:
print ('error type: ', type (e))
print(result)
Whenever I enter a letter as a number, the print in except is working, but the code crashes.
ZeroDivisionError & TypeError are working, but ValueError is not.
I even put inputs in separate try/except and it is still not working.
How can I handle this error here, and in the real app?

The crash is occurring before you enter the try block. It does not print the error in the except block if you enter a letter with your current code.
Simply putting the input section in a separate try block wouldn't catch it - you need an except block related to the try within which the error is happening, e.g.
try:
a = float(input('num1: '))
b = float(input('num2: '))
except ValueError as e:
print ('Value Error')
try:
result = a / b
except ZeroDivisionError as e:
print ('Zero DivisionError')
print(result)
Alternatively, you could put the input and division all within the try block and catch with your current reporting:
try:
a = float(input('num1: '))
b = float(input('num2: '))
result = a / b
except ValueError as e:
print ('error type: ', type (e))
print(result)
EDIT: Note that if any error does occur in either of these, it will cause further errors later on. You're better off going with the second option, but moving the print(result) into the try block. That's the only time it will be defined.

Related

Python Exceptions difficulty

I am trying to complete a lab soon but I am having difficulty, the prompt is:
A pedometer treats walking 2,000 steps as walking 1 mile. Write a steps_to_miles() function that takes the number of steps as a parameter and returns the miles walked. The steps_to_miles() function throws a ValueError object with the message "Exception: Negative step count entered." when the number of steps is negative. Complete the main() program that reads the number of steps from a user, calls the steps_to_miles() function, and outputs the returned value from the steps_to_miles() function. Use a try-except block to catch any ValueError object thrown by the steps_to_miles() function and output the exception message.
Output each floating-point value with two digits after the decimal point, which can be achieved as follows:
print('{:.2f}'.format(your_value))
I have been working on it for awhile now, my code is:
def steps_to_miles():
steps = int(input())
if steps < 0:
raise ValueError
return steps
if __name__ == '__main__':
try:
steps = steps_to_miles()
miles_walked = float(steps / 2000)
print('{:.2f}'.format(miles_walked))
except ValueError:
print('Exception: Negative step count entered.')
(Sorry for formatting errors...) The code runs but is only giving me 4 out of the 10 points due to Zybooks stating "test_passed function missing" and "Test stepsToMiles(-3850), should throw an exception". What am I missing or how can fix it? Or alternatively is there another way to write the code?
def steps_to_miles(steps):
if steps < 0:
raise ValueError
return float(steps / 2000)
if __name__ == '__main__':
steps = int(input())
try:
miles_walked = steps_to_miles(steps)
except ValueError:
print('Exception: Negative step count entered.')
print('{:.2f}'.format(miles_walked))
in body of try, need use only 'danger' code
your function was unworked becourse: you dont send any parameter, and it dont return value
input moved into main . It was next error: steps was local variable, which dont used in global namespace, and in function main
We can't do a lot to help you with an automatic homework grader, you should probably ask your teacher or TA. Here are a few pointers:
Your steps_to_miles does not take any arguments, according to the assignment it should take a single integer argument.
The ValueError you throw does not have a message attached to it.
steps_to_miles should divide its argument by 2000 but it doesn't do so. Instead you divide by 2000 outside of the function.
You print a specific string in your except block instead of printing the exception's actual message.
You may need to make your error message a variable, in regards to your zyBooks giving you this error: "Test stepsToMiles(-3850).
I would try this in your function: raise ValueError('Exception: Negative step count entered.')
I would also write in this in your final "except" statement.
except ValueError as err:
print(err)
this should work:
def steps_to_miles(num_steps):
if num_steps < 0:
raise ValueError("Exception: Negative step count entered.")
return num_steps / 2000
if __name__ == '__main__':
num_steps = int(input())
try:
num_miles = steps_to_miles(num_steps)
print('{:.2f}'.format(num_miles))
except ValueError as e:
print(e)

How can I get "EOFEroor" in Python while taking multiple inputs from users?

I'm trying to get multiple inputs from users and break the loop by End of File(EOF) error.
while True:
try:
n, l, c = map(int,input().split())
except EOFError:
break
But when the user gives multiple inputs and then press Enter the ValuEroor warning has come.
ValueError: not enough values to unpack (expected 3, got 0)
In this scenario, Is there any way to get EOFEroor to break the loop and avoid ValueEoor?
You will only get EOFError if the user presses CTRL-D. Just add ValueError to the caught exceptions:
except (EOFError, ValueError):
or, if needed to be handled differently:
except EOFError:
...
except ValueError:
...
You will need it anyway in case the user enters a string that can't be converted to int.

Please help. I get this error: "SyntaxError: Unexpected EOF while parsing"

try:
f1=int(input("enter first digit"))
f2=int(input("enter second digit"))
answ=(f1/f2)
print (answ)
except ZeroDivisionError:
You can't have an except line with nothing after it. You have to have some code there, even if it doesn't do anything.
try:
f1=int(input("enter first digit"))
f2=int(input("enter second digit"))
answ=(f1/f2)
print (answ)
except ZeroDivisionError:
pass
In Python, when you write ':', you start a code block. And, as per syntax you can't keep a block empty.
So, you must complete the block.e.g.
try :
f1=int(input("enter first digit"))
f2=int(input("enter second digit"))
answ=(f1/f2)
print (answ)
except ZeroDivisionError::
print ("You can't divide by zero")

How to continue loop after catching exception

The below code produces exception while handling non int values but it doesn't continue the loop but rather comes out from the loop raising error. My intention is to provide the value of 0 for exception cases.
Sample Input:
Common Ruby Errors 45min
Rails for Python Developers lightning
Code:
class TimeNotProvidedError(Exception):
pass
def extract_input():
lines = []
__tracks = {}
try:
lines = [line.strip() for line in open('test.txt')]
except FileNotFoundError as e:
print("File Not Found", e)
for line in lines:
title, minutes = line.rsplit(maxsplit=1)
minutes = int(minutes[:-3])
try:
__tracks[title] = minutes
except TimeNotProvidedError:
__tracks[title] = 0
return __tracks
print(extract_input())
Traceback:
ValueError: invalid literal for int() with base 10: 'lightn'
You're getting the error when converting to int with this line: minutes = int(minutes[:-3]). That line isn't in the try block, so the exception isn't caught. Move that line inside the try block, and you'll get the behavior you wanted.
Furthermore, the exception you're catching is TimeNotProvidedError, which isn't what int throws when a conversion fails. Instead, it throws ValueError, so that's the exception type you need to catch.
The mere act of assigning to __tracks[title] is unlikely to cause an exception, and if it does, re-trying with another assignment probably won't work anyway. What you probably want in your loop is this:
title, minutes = line.rsplit(maxsplit=1)
try:
minutes = int(minutes[:-3])
except ValueError:
minutes = 0
__tracks[title] = minutes

How do you make the program auto restart after value error - Python

So I have this program to convert a binary to hex. I also have a part that returns a value error if you put in a non 0 or 1 or if the string is more or less than 8 digits.
But what I want now with it is if the program does get the value error how do I code it so that it automatically restarts after the value error.
Enclose the code in a while loop.
while True:
try:
#your code
except ValueError:
#reset variables if necesssary
pass #if no other code is needed
else:
break
This should allow your program to repeat until it runs without errors.
Put your code into a loop:
while True:
try:
# your code here
# break out of the loop if a ValueError was not raised
break
except ValueError:
pass # or print some error
Here's a small program to put it in context:
while True:
possible = input("Enter 8-bit binary number:").rstrip()
if possible == 'quit':
break
try:
hex = bin2hex(possible)
except ValueError as e:
print(e)
print("%s is not a valid 8-bit binary number" % possible)
else:
print("\n%s == %x\n" % (possible, hex))
It only stops when you type in quit.

Categories

Resources