0

I have a question about python. I have to control type of data. I wrote a code but when I enter a string data, its not working. Whats wrong with about that code?

a=input("enter sth: ")
if type(eval(a))== int :
    print(a, "is a number")
elif type(eval(a))==float:
    print(a," is a number")
elif type(a)== str:
    print(a, "is a str")

When I enter string, it gives this error.

    Traceback (most recent call last):
  File "C:\Users\Alper\Desktop\merve.py", line 2, in <module>
    if type(eval(a))== int :
  File "<string>", line 1, in <module>

NameError: name 'g' is not defined

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Castor
  • 1
  • 1
  • 4
  • Whats is wrong with it ? Are you getting an error ? no the result you expected ? – jramirez Jan 09 '14 at 21:05
  • Is there any chance that you are using Python 2.x and the input could be Unicode? Then `type(a)` might be `unicode`. – steveha Jan 09 '14 at 21:09
  • I am taking this error: Traceback (most recent call last): File "C:\Users\Alper\Desktop\merve.py", line 2, in if type(eval(a))== int : File "", line 1, in NameError: name 'g' is not defined – Castor Jan 09 '14 at 21:14
  • There is a similar Q/A page that should help. http://stackoverflow.com/questions/354038/how-do-i-check-if-a-string-is-a-number-in-python – iiiir.com Jan 09 '14 at 21:17

5 Answers5

3

The problem you encounter is that the eval() function is expecting valid python expression. So 2 is valid, it is an int, 2.0 also, as well as "foo" which is a string. However, foo is not a valid python keyword, so it will fail.

You need to parse your input another way, either matching regular expression, or trying to cast the input to python types.

try:
    b = int(a)
except ValueError:
    try:
        b = float(a)
    except ValueError:
        print("a is a string")
    else:
        print("a is a float")
else:
    print("a is an int")
Cilyan
  • 7,883
  • 1
  • 29
  • 37
2

I tried to not respond but I failed. Sorry if it sounds OT

Please try to avoid use of eval

if you are expecting a literal from input, checkout ast.literal_eval

try:
    a = ast.literal_eval(a)
except:
    pass

Note that this could eval into lists or dicts or other valid literals.

You could also use json or other "evaluators" like

try:
    a = json.loads(a)
except:
    pass

Also, after that:

#rather than
if type(a) == int:
#prefer
if isinstance(a, int):  

Also, for type checking, isinstance(a, basestring) will cover both str and uncode bases.

Phil Cooper
  • 5,747
  • 1
  • 25
  • 41
1

Python's input() treats input as Python code - it is essentially taking raw_input(), sending it to eval() and then returning the result. This means that if you want to treat input as a string, you need to enter it surrounded with quotes. If you enter text surrounded with quotes, input() attempts to treat that text as Python code. Here are some examples (copy-pasted from my Python REPL):

Using input():

>>> a = input("enter something: ")   # treats input as Python code
enter something: 4                   # will evaluate as the integer 4
>>> type(a) 
<type 'int'>                         # type of 4 is an integer

>>> a = input("enter something: ")   # treats input as Python code
enter something: this is a string    # will result in an error
File "<stdin>", line 1, in <module>
File "<string>", line 1
   this is a string
                 ^
SyntaxError: unexpected EOF while parsing

>>> a = input("enter something: ")  # treats input as Python code
enter something: "this is a string" # "this is a string" wrapped in quotes is a string
>>> type(a)
<type 'str'>                        # a is the string "this is a string"

Using raw_input():

>>> a = raw_input("enter something: ") # treats all input as strings
enter something: this is a string         
>>> type(a)
<type 'str'>                           # a is the string "this is a string"
>>> print(a)
this is a string

>>> a = raw_input("enter something: ") # treats all input as strings
enter something: "this is a string"         
>>> type(a)
<type 'str'>                           # a is the string ""this is a string""
>>> print(a)
"this is a string"

>>> a = raw_input("enter something: ") # treats all input as strings
enter something: 4         
>>> type(a)
<type 'str'>                           # a is the string "4"

This also means that the calls to eval() are unnecessary if you use input().

I'd use raw_input() so that the user can enter input without quotation marks, and continue using eval() as you are now.

Eliza Weisman
  • 823
  • 9
  • 17
0

You should provide what your output is. However if you are using python 2.x, you could use

raw_input("Enter sth: ") 

if you want to input a string

s = raw_input("Enter sth: ") 



>>> type(s)

<type 'str'>
Totem
  • 7,189
  • 5
  • 39
  • 66
0

You can also check your input with the string-methods

a = input('enter: ') # if python 2.x raw_input('enter: ')
if a.isalpha():
   print(a, "is a str")
elif a.isdigit():
   if 'float' in str(type(eval(a))):
       print(a, "is a float")
   else:
       print(a, "is a int")
else:
   print("Your input is not allowed")
Oni1
  • 1,445
  • 2
  • 19
  • 39