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

4
  • Whats is wrong with it ? Are you getting an error ? no the result you expected ? Commented Jan 9, 2014 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. Commented Jan 9, 2014 at 21:09
  • I am taking 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 Commented Jan 9, 2014 at 21:14
  • 1
    There is a similar Q/A page that should help. stackoverflow.com/questions/354038/… Commented Jan 9, 2014 at 21:17

5 Answers 5

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")
Sign up to request clarification or add additional context in comments.

Comments

3

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.

Comments

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.

Comments

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'>

2 Comments

this is only if you're using Python 2, the above code is valid in Python 3
Thanks, I didn't spot that
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")

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.