Why does try except not work in this case? - python

I have this piece of code here:
money_to_dep = int(input(f"\nHow much money do you want to deposit?(enter amount ONLY):\n>> "))
while True:
try:
print(money_to_dep)
break
except ValueError:
print(f"Wrong INPUT. Try again.")
break
When I type a string instead of an integer, an error still occurs even though I have done except ValueError? Why does this happen? This question really annoys me as I have never been able to have a clear understanding as to how try-except works with handling errors.

You have to put your code like this:
while True:
try:
money_to_dep = int(input(f"\nHow much money do you want to deposit?(enter amount ONLY):\n>> "))
print(money_to_dep)
break
except ValueError:
print(f"Wrong INPUT. Try again.")
The ValueError raise when you use int. So it has to be inside the try statement.

This means that your exception is occuring before your try catch. you need to put your input code inside try, so it can catch exception.
i.e
money_to_dep = int(input(f"\nHow much money do you want to deposit?(enter amount ONLY):\n>> "))
Exveption occurs, but not in try block so not catched. Change it to
while True:
try:
money_to_dep = int(input(f"\nHow much money do you want to deposit?(enter amount ONLY):\n>> "))
print(money_to_dep)
break
except Exception as E:
print(f"Wrong INPUT. Try again.")
break

Related

How to implement "if error occurs do not implement this code"?

I want to write a code in python that basically does something like this:
if error occurs while implementing int(a) print('valid character')
elif no error occurs while implementing int(a) print('invalid character')
a is an input.
I want to make a simple hangman game and if the input is not a letter I want a certain message to be displayed. I tried using if a==int(), but inputs are always a string.
Normally you would use a Try, Except clause to handle errors, but because you're not actually getting an error -- you just want to know if the input is an alphabetical character or not, you would use the string.isalpha function.
guess = input()
if not guess.isalpha():
print('You must supply an alphabetical character')
else:
#the rest of your code would go here
Now to have some fun. This is how you would implement exactly what you where asking, however, please note that this does not catch punctuation characters, emoji characters, and any other random characters that are none-numeric and non-alphabetical.
guess = input()
isOk = False
try:
int(guess)
except ValueError:
isOk = True
if not isOk:
print("you cannot enter a number")
I don't know if it's a good idea to mention this or not, because it's a pretty quirky feature of Python to add the else here, but you can technically condense the above code to
guess = input()
try:
int(guess)
except ValueError:
# All good
pass
else:
# we where able to cast to an integer = bad
print("you cannot enter a number")
but I probably wouldn't ever do that in production code. Also, an important note. As you learn about try except clauses. Even though it's possible to just do except: Make sure you always state whatever you are catching. In this case a ValueError except ValueError: . If you don't do this, you suppress all errors, and you risk getting into a situation down the road were an important error gets suppressed, and you have no idea why your program is behaving incorrectly.
explore try-except designs
try:
# do something here
except (ErrorName):
# error catching
print("invalid character")
Please try and include reproducible code, or a code block of pseudo-code so others can follow along easier!

While(!EOF()) equivalent in Python

I'm working on a school project and it specifically asks for a while not end-of-file loop which I don't know how to do in Python. I'm taking in user input (not from an external file) and computing some math in this infinite loop until they CTRL+C to break the loop. Any thoughts would really help me out. I've added part of the instruction if that helps clarify. Thanks.
Your loop is supposed to stop on two conditions:
An illegal value was entered, ie some value that couldn't be converted to a float. In this case, a ValueError will be raised.
You entered ctrl-Z, which means an EOF. (Sorry, having no Windows here, I just tested it on Linux, where I think that ctrl-D is the equivalent of the Windows ctrl-Z). An EOFError will be raised.
So, you should just create an infinite loop, and break out of it when one of these exceptions occur.
I separated the handling of the exceptions so that you can see what happens and print some meaningful error message:
while True:
try:
amount = float(input())
print(amount) # do your stuff here
except ValueError as err:
print('Terminating because', err)
break
except EOFError:
print('EOF!')
break
If you just want to quit without doing anything more, you can handle both exceptions the same way:
while True:
try:
amount = float(input())
print(amount) # do your stuff here
except (ValueError, EOFError):
break
Use the following:-
while True:
amount = raw_input("Dollar Amount: ")
try:
amount = float(amount)
# do your calculation with amount
# as per your needs here
except ValueError:
print 'Cannot parse'
break

python name not defined even though it is

I know this is basic but i actually don't even know what I've done wrong.
while True:
try:
end=int(input("If You Dont Want To Buy Anything Press 1 To Exit\nOr If You Would Like To Try Again Please Press 2"))
except ValueError:
print("\nPlease Enter Only 1 Or 2")
if end==1:
exit()
elif end==2:
continue
I have literally defined end at the start and yet the error is NameError: name 'end' is not defined I've even tried making end a global.
end is only assigned to if there was no ValueError. If int() raises an exception, then the assignment never takes place.
Either test for valid end values inside the try (so that you know no exception was raised), or assign a default value to end first.
For example, the following will not throw your exception and still prompt the user to re-enter the number if anything other than 1 or 2 was entered:
while True:
try:
end=int(input("If You Dont Want To Buy Anything Press 1 To Exit\nOr If You Would Like To Try Again Please Press 2"))
if end==1:
exit()
elif end==2:
break
except ValueError:
pass
print("\nPlease Enter Only 1 Or 2")
Note that I moved the print() to be outside the except block; it'll be printed if an exception was thrown or when no break or exit() was executed. Note that I used break here instead of continue to exit the while True loop; continue would just start the next iteration, prompting the user to enter a number again.
Others have explained the problem; here's a canonical solution. This matches the way many of us regard the process:
- grab a response
- until I get a legal response
- ... tell the user what's wrong
- ... get a new response
input_prompt = "If You Don't Want To Buy Anything Press 1 To Exit\nOr If You Would Like To Try Again Please Press 2"
response = input(input_prompt)
while response != '1' and response != '2':
print("\nPlease Enter Only 1 Or 2")
response = input(input_prompt)
end = int(reponse)
This has no unnatural loop exits (harder to follow and maintain), and no exception processing (slow).
It tries to assign a value to end, but catches a ValueError and after the except it tries to see what 'end' is however it was never assigned a value due to the Exception.
If int(input(...)) fails, a ValueError is raised. That happens before end is assigned. Add another control statement in the error handling, for instance
while True:
try:
end=int(input("If You Dont Want To Buy Anything Press 1 To Exit\nOr If You Would Like To Try Again Please Press 2"))
except ValueError:
print("\nPlease Enter Only 1 Or 2")
continue # ask again
if end==1:
exit()
elif end==2:
continue

Stop Python from trowing KeyError exceptions

I get an error while running my script and I know it is there, But I don't want Python to print the error. The error (it is a KeyError) is in a if statement. Is there a way to stop the if statement from printing error messages?
Try this.
while True:
try:
x = int(raw_input("Please enter a number: "))
break
except ValueError:
print "Oops! That was no valid number. Try again..."

Why exception is not properly caught?

I have a piece of code.
import sys
while(True):
print "Enter a number: "
try:
number = int(sys.stdin.readline())
except ValueError:
print "Error! Enter again an integer value"
continue
finally:
print number
break
Here I expect when I enter a non-integer number, the output should be
Error! Enter again an integer value
and then it should ask for input. But it is printing the message but asking for further inputs. Please explain it or if am thinking it wrong.
If I handle with NameError, then error message is not even being printed and the program is exiting with a traceback call.
The finally clause always runs, whether an exception was caught or not. You want else, which runs when there was no exception.
Also: you don't need parentheses for a while, and you probably want the raw_input function which is a little nicer to use than messing with sys.stdin directly.
So I would do:
while True:
try:
number = int(raw_input("Enter a number: "))
except ValueError:
print "Error! Enter again an integer value"
continue
else:
print number
break
Your finally should be else, otherwise it will execute regardless of whether or not there was an exception.

Categories