. #To convert a numeriacal string into integer/float we use the syntax:. if we add a float value with an integer we get back an answer in #two strings can be concatenated using + operator. #for example, the integer value in the above example 123 can be converted into a string '123' and then added to concatenate both the strings.">

Finding the Type of Variable in Python and Their Conversions

05 min read

In order to find out about the type of 'variable', we use the "type" function.

 Consider the following example:

variable1= 'hello' 
variable2 = 'world'
variable3= 34
variable4=43.50

print(type(variable1)) print(type(variable2)) print(type(variable3)) print(type(variable4))
Output
<class 'str'>
<class 'str'>
<class 'int'>
<class 'float'>

 

# if we add a float value with an integer we get back an answer in <class 'float'>
#two strings can be concatenated using + operator.
#for example,

print('hello'+'world')

Output:
helloworld #It is to be noted that there is no space produced between the two strings

 

#a string and an integer/float cannot be operated together.

print('hello' + 123)
Output 

ERROR: class mismatch

 

# the integer value in the above example 123 can be converted into a string '123' and then added to concatenate both the strings.

print('hello' + ' ' + '123') # a space can also be added as a string in between.
Output:
hello 123

 

#To convert a numeriacal string into integer/float we use the syntax:

variable1= '12345' # its declared as a string.
variable2 = int(variable1) #The string is converted into a integer of value 12345.
variable3 = str(variable2) # the integer of value 12345 is now converted into a string '12345'

variable4 = 'hello123' # alphanumeric string is declared
print(int(variable4)) # a string which is not completly numeric cannot be numeric cannot be converted into integer/float.
Output:
ERROR: Traceback (most recent call last):
File "C:/Users/*****/Documents/Python/PycharmProjects/Practice1/***/testing", line 2, in <module>
print(int(ee))
ValueError: invalid literal for int() with base 10: 'hello123'
POST A NEW COMMENT
     
  • Input (stdin)

    Output (stdout)


    Input (stdin)

    Your Output (stdout)

    Expected Output

    Compiler Message

    Input (stdin)

    2    3

    Your Output (stdout)

    5

    Expected Output

    5

    Compiler Message

    5

    Error