Sahil Babbar
Sahil Babbar

Reputation: 599

Checking whether the user input is a str in Python

I checked various questions on Stack Overflow but one thing every logic lacks. Let me demonstrate using Python:

while True:
    user_input = raw_input()
    if type(user_input) == str:
        print 'ERROR'
    else:
        print 'BINGO'

Also, we cannot use input() in place of raw_input() as it gives the error:Traceback (most recent call last):

File ".\test.py", line 3, in <module>
    user_input = int(input())
  File "<string>", line 1, in <module>
NameError: name 'asdf' is not defined

The problem here is that raw_input converts the user input into string so it always prints 'ERROR' and if I change the second line to

user_input = int(raw_input)

then, it gives an error:

Traceback (most recent call last):
  File ".\test.py", line 3, in <module>
    user_input = int(raw_input())
ValueError: invalid literal for int() with base 10: 'asdf'

I tried this with try and except but it shall work fine to check integer but not a string.

Upvotes: 0

Views: 218

Answers (2)

Ciasto piekarz
Ciasto piekarz

Reputation: 8277

# first store the value to a variable
user_input = raw_input('>')
try:
    if int(user_input):
        print "User entered %d is integer" % int(user_input)
except ValueError: 
    # check whether the user entered string or not
    print "User entered %s is a string" % user_input

The raw_input always stores string whether you enter an integer.

Upvotes: -1

Idan Arye
Idan Arye

Reputation: 12633

You got it all backwards - raw_input does not "convert the user input into string" - the user input was a string to begin with! It's input that converts it to other things.

If you want to use raw_input, you can assume you'll get a string and you need to convert it to int yourself. As you have seen, this fails if the string does not represent an integer, but you can easily catch that error:

while True:
    user_input = raw_input()
    try:
        user_input_as_integer = int(user_input)
        print 'BINGO'
    except ValueError:
        print 'ERROR'

Upvotes: 3

Related Questions