I did this example but it does not run with the try and except handling errors in Python.
def my_fun(numCats):
print('How many cats do you have?')
numCats = input()
try:
if int(numCats) >=4:
print('That is a lot of cats')
else:
print('That is not that many cats')
except ValueError:
print("Value error")
I tried:
except Exception:
except (ZeroDivisionError,ValueError) as e:
except (ZeroDivisionError,ValueError) as error:
I did other example and it was able to catch ZeroDivisionError
I am using Jupyter notebook Python 3.
Any help in this matter is highly appreciated.
I am calling
my_fun(int('six'))
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-39-657852cb9525> in <module>()
----> 1 my_fun(int('six'))
ValueError: invalid literal for int() with base 10: 'six'
A few problems:
Please fix the indentation. The indentation levels are mismatched.
There's no need to take in the parameter numCats as it's changed to whatever the user provides anyway.
You're not calling the function my_fun(), meaning that there will never be any output, as functions only run when called.
This should work:
def my_fun():
print('How many cats do you have?\n')
numCats = input()
try:
if int(numCats) > 3:
print('That is a lot of cats.')
else:
print('That is not that many cats.')
except ValueError:
print("Value error")
my_fun() ## As the function is called, it will produce output now
Here is a reworked version of your code:
def my_fun():
numCats = input('How many cats do you have?\n')
try:
if int(numCats) >= 4:
return 'That is a lot of cats'
else:
return 'That is not that many cats'
except ValueError:
return 'Error: you entered a non-numeric value: {0}'.format(numCats)
my_fun()
Explanation
You need to call your function for it to run, as above.
Indentation is important. This has been made consistent with guidelines.
input() takes as a parameter a string which is displayed before the input.
Since the user provides input via input(), your function does not require an argument.
It is good practice to return values and, if necessary, print them afterwards. Rather than having your function print strings and return None.
Your error can be more descriptive, and include the inappropriate input itself.
Related
I am trying to create an error trap using a try-except catch to prevent the user from entering a string, however when I run the code, it does not catch the error.
info=False
count=input("How many orders would you like to place? ")
while info == False:
try:
count*1
break
except TypeError:
print("Please enter a number next time.")
quit()
#code continues
A better way to do this would be to use a try except block
while True:
try:
count=int(input("How many orders would you like to place? "))
break
except:
print("This is not a valid input. Try again\n")
print(count)
str times ìnt works perfectly in python: 'a'*3 = 'aaa'. no exception will be raised in your try block.
if you want to distiguish int from str:
try:
int(count)
except ValueError:
do_something_else()
note: it is ValueError and not TypeError.
The value that input returns is string.
you can try something like this:
try:
val = int(userInput)
except ValueError:
print("That's not an int!")
You can use TypeError in the following way.
while True:
try:
count=input("How many orders would you like to place? ")
count += 1
except TypeError:
print("Please enter a number next time.")
break
Note that, a string can be multiplied by integer in python, so I have used addition operation since we cannot add integer to string in python.
I'm trying to make sure that the user gave a valid floating point number as input.
run='yes'
valid='no'
x=1
while run == 'yes':
while valid == 'no':
x=float(input('Enter the richter scale you wish to convert:'))
check=isinstance(x,float)
if check == False:
print('Invalid value, re-try:')
valid=yes
float(x)`enter code here`
square=1.5*x+4.8
e=10**square
print(e)
tnt=e/4.184*10**9
print(tnt)
You need to use a try, except block. Something like this:
x = input('Enter the richter scale you wish to convert:')
try:
x = float(x)
except ValueError:
print("Sorry, that's not a valid float")
I am deliberately leaving the call to input outside of the try, except so that the value can be used for debugging purposes, and so that in case input some how throws an exception, it's not being caught by this block. Only the conversion to float should be wrapped in this block.
If you do a try in python, and the code doesn't fail, but it's outside of a range you want or something, what is the best way to make it fail so it goes to the except?
A simple example is as follows, to check the input is a number between 0 and 1:
input = 0.2
try:
if 0 < float( input ) < 1:
print "Valid input"
else:
"fail"+0 (to make the code go to except)
except:
print "Invalid input"
Is there a better way to go about this? The between range is just an example, so it should work with other things too (also, in the above example, it should also be able to use a number in string format, so detecting the type wouldn't really work).
Sorry but rchang's answer is not reliable for production code (assert statements are skipped if Python is run with the -O flag). The correct solution is to raise a ValueError, ie:
try:
if 0 < float(input) < 1:
raise ValueError("invalid input value")
print "Valid input"
except (TypeError, ValueError):
print "Invalid input"
You can use the raise statement:
try:
if (some condition):
Exception
except:
...
Note that Exception can be more specific, like for example, a ValueError, or maybe it can be an exception defined by you:
class MyException(Exception):
pass
try:
if (some condition):
raise MyException
except MyException:
...
The other answer is accurate. But to educate you more about exception handling ... you could use raise.
Also consider Bruno's comment where he says:
You also want to catch TypeError in case input is neither a string nor a number.
Thus in this case we may add another except block
input = 1.2
try:
if 0 < float( input ) < 1:
print "Valid input"
else:
raise ValueError #(to make the code go to except)
except ValueError:
print "Input Out of Range"
except TypeError:
print "Input NaN"
TypeError will be raised iff the input is an object ( for e.g)
The built-in assertion mechanism may be a fit here.
input = 0.2
try:
assert 0 < float( input ) < 1
print "Valid input"
except (AssertionError, ValueError):
print "Invalid input"
AssertionError will be raised if the condition you provide to the assert statement does not evaluate to True. Also, upon attempting the float conversion upon an invalid value would raise the ValueError.
I'm trying to assign a new value to a key in a dictionary. But getting "ValueError: invalid literal for int() with base 10:"
Here is what I do.
balance = {'beer':5, 'toast':2}
item = input("what did you eat?: ")
price = input("how much?: ")
if item not in balance:
balance[item] = int(price)
else:
balance[item] = balance[item] + int(price)
I'm puzzled, since I can do balance['beer'] = 5 in python shell, what am I missing?
Read the error message again:
ValueError: invalid literal for int() with base 10
This means, that you are passing an invalid argument to function int(), i.e. a string that does not represent a valid decimal number.
Check what price name holds. As it's taken from the user, your program must be prepared to handle a situation when it's garbage. I usually make a function to handle the boilerplate:
def input_int(prompt):
while True:
data = input(prompt)
try:
return int(data)
except ValueError:
print("That's not a valid number. Try again.")
You can also add some escape condition if it makes sense in your program.
what is the value of price
it is probably a string?
having a value that cannot be converted to an int will cause this
>>> test = 'test'
>>> int(test)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: 'test'
also please make sure to post your complete traceback as python gives it to you in your question, not just the error string
This is a great opportunity to learn about data validation, as you can see your program requires an integer. You can handle this yourself, displaying your own message to the user, or allow the program to just error (assuming the client of your program will understand the error)
There are no shortcuts to data validation
try:
price = int(input("how much?: "))
catch ValueError:
print('Please enter an integer')
or something to that effect
I have little problem with try statement along with multiple conditions. When there is error at 2nd condition, it asks for 1st condition. What I want from it to do is to repeat the same condition, not the whole cycle. I hope you understand me, since my English isn't very good and also I'm newbie to Python so I also don't know how to describe it in my native language.
I hope the following example will help you to better understand my thought.
while True:
try:
zacatek = float(raw_input("Zacatek: "))
konec = float(raw_input("Konec: "))
except Exception:
pass
else:
break
it does following:
Zacatek: 1
Konec: a
Zacatek:
but I want it to do this:
Zacatek: 1
Konec: a
Konec:
Thanks in advance for any help.
Write a function to query for a single float, and call it twice:
def input_float(msg):
while True:
try:
return float(raw_input(msg))
except ValueError:
pass
zacatek = input_float("Zacatek: ")
konec = input_float("Konec: ")
What's happening is that your except clause is catching a ValueError exception on your answer to Konec and returning to the top of the loop.
Your float function is trying to cast a non-numeric response "a" to a float and it throwing the exception.
Alternatively, you could write a different loop for each input:
zacatek = None
while not zacatek:
try:
zacatek = float(raw_input("Zacatek: "))
except Exception:
continue
konec = None
while not konec:
try:
konec = float(raw_input("Konec: "))
except Exception:
continue