How to convert input to float with exception handling - 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.

Related

Try and Except Python

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.

Error Trapping Strings and Integers

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.

Better way to fail a try in python if result is valid but not wanted

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.

Having trouble requesting input in python

i have troubling handling input in python. I have a program that request from the user the number of recommendations to be calculated.He can enter any positive integer and blank(""). I tried using the "try: , except: " commands,but then i leave out the possibility of blank input. By the way blank means that the recommendations are going to be 10.
I tried using the ascii module,but my program ends up being completely confusing. I would be glad if anyone could get me on the idea or give me an example of how to handle this matter.
My program for this input is :
while input_ok==False:
try:
print "Enter the number of the recommendations you want to be displayed.\
You can leave blank for the default number of recommendations(10)",
number_of_recs=input()
input_ok=True
except:
input_ok=False
P.S. Just to make sure thenumber_of_recs , can either be positive integer or blank. Letters and negative numbers should be ignored cause they create errors or infinite loops in the rest of the program.
while True:
print ("Enter the number of the recommendations you want to " +
"be displayed. You can leave blank for the " +
"default number of recommendations(10)"),
number_of_recs = 10 # we set the default value
user_input = raw_input()
if user_input.strip() == '':
break # we leave default value as it is
try:
# we try to convert string from user to int
# if it fails, ValueError occurs:
number_of_recs = int(user_input)
# *we* raise error 'manually' if we don't like value:
if number_of_recs < 0:
raise ValueError
else:
break # if value was OK, we break out of the loop
except ValueError:
print "You must enter a positive integer"
continue
print number_of_recs

Try statement - multiple conditions - Python 2

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

Categories