Type:unicode


#1



Hii everyone!!

So I was trying to understand why does my program always return this "whyy" message, even though I put numbers, and found out that it always gives unicode as a type:

hey 78
type 'unicode'
whyy
None


def distance_from_zero(x):
    if (type(x) == int) or (type(x) == float):
        return abs(x)
    else:
        return 'whyy'
oleg=raw_input('hey')
print type(oleg)
print distance_from_zero(oleg)


So I wonder if this can be overcome somehow...


#2

Hi
This is because the python function raw_input reads a line from input and convert it to a string. You can have a look at
https://docs.python.org/2/library/functions.html#raw_input
If you want to convert a string to an integer or a float, you can consider the functions int(myString) and float(myString)

Another way is to use input() instead of raw_input(). This function will evaluate whatever you enter and no need to convert it afterwards. See

Cheerio


#3

@maxkrasnet,
Using your example in a 'dutch' windows 8.1 IE11 environment

hey 78
<type 'str'>
whyy

The return Value of a raw_input is always a string

http://stackoverflow.com/questions/5563089/raw-input-function-in-python

You could try using the input() method
like

def distance_from_zero(x):
    if (type(x) == int) or (type(x) == float):
        return abs(x)
    else:
        return 'whyy'
oleg=input('hey')
print type(oleg)
print distance_from_zero(oleg)

you will then get

hey 78
<type 'int'>
78

#4

Thank you a lot for replies!! Now it's all clear. Works perfectly with input().