Issue
I want to make a simple math function that takes user input, yet allows the user to not input an integer/float. I quickly learned Python does not identify type by default. Quick Google search shows using literal_eval
, but it returns with ValueError: malformed string
if a string is the input. This is what I have so far:
from ast import literal_eval
def distance_from_zero(x):
if type(x) == int or type(x) == float:
return abs(x)
else:
return "Not possible"
x = literal_eval(raw_input("Please try to enter a number "))
print distance_from_zero(x)
Solution
Like you mentioned you will get malformed string error (ValueError
) if you get input like ast.literal_eval('c1')
. You will also get SyntaxError
if you do something like ast.literal_eval('1c')
. You will want get the input data and then pass it to literal_eval
. You can then catch both of these exceptions, and then return your 'Not Possible'
.
from ast import literal_eval
def distance_from_zero(x):
try:
return abs(literal_eval(x))
except (SyntaxError, ValueError):
return 'Not possible'
x = raw_input("Please try to enter a number ")
print distance_from_zero(x)
Answered By - RJ7
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.