Python: Type Conversion

While using variables in Python, we often need to convert data of one type to some other type. For example when we take input from the user.

Here are some other use cases where you might need type conversion-

  • Input validation
  • Mathematical operations, where we need to use different types like integer and float.
  • File input/output handling.
  • JSON data parsing.
  • API handling.
  • Handling database operations.

Reason for Type Conversion

Check the example below-

age = input("Enter your age: ")

try:
    print("You have entered: ", age)
    
    print("Type of your entered value: ", type(age))
    
    # Try to perform a calculation with the age ValueError
    print("After 10 years, your age will be: ", age + 10)
except ValueError as err:
    print(err)
Python

Output:

Enter your age: 24
You have entered:  24
Type of your entered value:  <class 'str'>

Traceback (most recent call last):
  File "example.py", line 9, in <module>
    print("After 10 years, your age will be: ", age + 10)
TypeError: can only concatenate str (not "int") to str
Plaintext

Here the entered value is taken as a string. So when we try to perform a calculation with the string, Python is unable to perform the calculation, and throws an error.

Now, let’s see what we can do to solve the exception. We can convert the entered string value, to an integer using the “int()” function.

age = input("Enter your age: ")

try:
    print("You have entered: ", age)
    
    print("Type of your entered value: ", type(age))
    
    age = int(age)
    
    print("Type of age after conversion: ", type(age))
    
    # Try to perform a calculation with the age ValueError
    print("After 10 years, your age will be: ", age + 10)
except ValueError as err:
    print(err)
Python

Output:

Enter your age: 24
You have entered:  24

Type of your entered value:  <class 'str'>

Type of age after conversion:  <class 'int'>

After 10 years, your age will be:  34
Plaintext

Similarly, if we try to perform addition on two numbers that are stored as strings, then it will contact instead of performing addition.

# Say we have got these numbers as string
# from some source(like user input, file read, etc.)
first_number = "2"
second_number = "3"

# Adding these two numbers without conversion
result = first_number + second_number # values will concatinate, instead of math operation

print("Result of addition: ", result)

# Result after conversion
result = int(first_number) + int(second_number)

print("Result after conversion: ", result)
Python

Output:

Result of addition:  23
Result after conversion:  5
Plaintext

Not only numbers cause issues. We can also encounter issues with other types. Like, if we try to concatenate a number with strings, we will face issues.

age = 23

# This will throw an error
# as integer can not be concatenated with string
print("You are " + age + " years old")

# The following will work
# print("You are " + str(age) + " years old")
Python

Output:

Traceback (most recent call last):
  File "example.py", line 5, in <module>
    print("You are " + age + " years old")
TypeError: can only concatenate str (not "int") to str
Plaintext

Now let’s see what are the different types of conversions and checking we can perform in Python.

Type Checking

Before the type conversion, let’s see how we can check the variable type (value saved in a variable).

Use the function “type” to check the type of a variable. Here are some examples-

bigBoxNum = 100
bigBoxFloat = 99.99
bigBoxStr = "this is my string"

print("Type of bigBoxNum: ", type(bigBoxNum))
print("Type of bigBoxFloat: ", type(bigBoxFloat))
print("Type of bigBoxStr: ", type(bigBoxStr))
Python

Output:

Type of bigBoxNum:  <class 'int'>
Type of bigBoxFloat:  <class 'float'>
Type of bigBoxStr:  <class 'str'>
Plaintext

Let’s check a few more examples-

bigBoxTpl = ("test", "this", "tuple", 999)
bigBoxList = ["First", "Second", "Big", "Box", "Code"]
bigBoxDict = {"name": "BigBoxCode", "url": "https://bigboxcode.com"}
bigBoxSet = {"Big", "Box", "Code", "Set", 4, 5, 6}

print("Type of bigBoxTpl: ", type(bigBoxTpl))
print("Type of bigBoxList: ", type(bigBoxList))
print("Type of bigBoxDict: ", type(bigBoxDict))
print("Type of bigBoxSet: ", type(bigBoxSet))
Python

Output:

Type of bigBoxTpl:  <class 'tuple'>
Type of bigBoxList:  <class 'list'>
Type of bigBoxDict:  <class 'dict'>
Type of bigBoxSet:  <class 'set'>
Plaintext

Let’s check what the type() returns-

bigBoxNum = 100

print("Type of bigBoxNum: ", type(bigBoxNum))

print("Type of type(bigBoxNum): ", type(type(bigBoxNum)))
Python

Output:

Type of bigBoxNum:  <class 'int'>

Type of type(bigBoxNum):  <class 'type'>
Plaintext

Type Conversion

Now let’s see how can we convert any data type to some specific data type-

Convert to Boolean

Use the function “bool()” to convert any data type to an Integer.

If we convert other data types to Integer, the following things happen-

  • Integer to boolean:
    • 0 converted to False
    • Value greater than(>) Zero(0) converted to True
    • Negative Integer(like -1) converted to True
  • Float to boolean:
    • 0.0 converted to False
    • Value greater than(>) Zero(0) converted to True
    • String to boolean:
      • Empty string converted to False
      • Non-empty string converted to True
    • Tuple to boolean:
      • Empty tuple converted to False
      • Non-empty tuple converted to True
    • List to boolean:
      • Empty list converted to False
      • Non-empty list converted to True
    • Set to boolean:
      • Empty set converted to False
      • Non-empty set converted to True
    • Dictionary to boolean:
      • Empty dictionary converted to False
      • Non-empty dictionary converted to True

    Check the following examples-

    # Integer to Boolean
    bool_val = bool(10)
    print(f"Value of Integer 10 converted to Boolean: {bool_val}")
    
    bool_val = bool(0)
    print(f"Value of Integer 0 converted to Boolean: {bool_val}")
    
    bool_val = bool(-1)
    print(f"Value of negative Integer converted to Boolean: {bool_val}")
    
    # String to Boolean
    bool_val = bool("23")
    print(f'Value of String "23" converted to Boolean: {bool_val}')
    
    bool_val = bool("")
    print(f"Value of empty String converted to Boolean: {bool_val}")
    
    # Float to Boolean
    bool_val = bool(23.55)
    print(f"Value of Float 23.55 converted to Boolean: {bool_val}")
    
    bool_val = bool(0.0)
    print(f"Value of Float 0.0 converted to Boolean: {bool_val}")
    
    # Tuple to Boolean
    bool_val = bool(())
    print(f"Value of empty Tuple converted to Boolean: {bool_val}")
    
    bool_val = bool((1, 2, 3))
    print(f"Value of Tuple converted to Boolean: {bool_val}")
    
    # List to Boolean
    bool_val = bool([])
    print(f"Value of empty List converted to Boolean: {bool_val}")
    
    bool_val = bool([1, 2, 3])
    print(f"Value of List converted to Boolean: {bool_val}")
    
    # Set to Boolean
    bool_val = bool({})
    print(f"Value of empty Set converted to Boolean: {bool_val}")
    
    bool_val = bool({1, 2, 3})
    print(f"Value of Set converted to Boolean: {bool_val}")
    
    # Dictionary to Boolean
    bool_val = bool({})
    print(f"Value of empty Dictionary converted to Boolean: {bool_val}")
    
    bool_val = bool({"one": 1, "two": 2, "three": 3})
    print(f"Value of Dictionary converted to Boolean: {bool_val}")
    
    # None to Boolean
    bool_val = bool(None)
    print(f"Value of None converted to Boolean: {bool_val}")
    Python

    Output:

    Value of Integer 10 converted to Boolean: True
    Value of Integer 0 converted to Boolean: False
    Value of negative Integer converted to Boolean: True
    Value of String "23" converted to Boolean: True
    Value of empty String converted to Boolean: False
    Value of Float 23.55 converted to Boolean: True
    Value of Float 0.0 converted to Boolean: False
    Value of empty Tuple converted to Boolean: False
    Value of Tuple converted to Boolean: True
    Value of empty List converted to Boolean: False
    Value of List converted to Boolean: True
    Value of empty Set converted to Boolean: False
    Value of Set converted to Boolean: True
    Value of empty Dictionary converted to Boolean: False
    Value of Dictionary converted to Boolean: True
    Value of None converted to Boolean: False
    Plaintext

    Convert to Integer

    Use the function “int()” to convert any data type to an Integer. “int()” function accepts a string, byte object, or real number.

    If we convert other data types to Integer, the following things happen-

    • Boolean to Integer:
      • True converted to 1
      • False converted to 0
    • Float to Integer: the integer part is taken, and the decimal part is ignored.
    • String to Integer: parsed to integer if the full string is an integer, else throws an error.
    • Tuple to Integer: throws an error, as the “int()” function does not accept Tuple.
    • List to Integer: throws an error, as the “int()” function does not accept List.
    • Set to Integer: throws an error, as the “int()” function does not accept Set.
    • Dictionary to Integer: throws an error, as the “int()” function does not accept Dictionary.

    Check the following examples-

    # Boolean to Integer
    int_val = int(True)
    print(f"Value of Boolean True converted to Integer: {int_val}")
    
    int_val = int(False)
    print(f"Value of Boolean False converted to Integer: {int_val}")
    
    # String to Integer
    int_val = int("23")
    print(f'Value of String "23" converted to Integer: {int_val}')
    
    try:
        int_val = int("23abc")
        print(f'Value of String "23abc" converted to Integer: {int_val}')
    except ValueError as err:
        print(err)
    
    # Float to Integer
    int_val = int(23.55)
    print(f"Value of Float 23.55 converted to Integer: {int_val}")
    
    int_val = int(0.5)
    print(f"Value of Float .5 converted to Integer: {int_val}")
    
    # Tuple to Integer
    try:
        int_val = int((1, 2, 3))
        print(f"Value of Tuple converted to Integer: {int_val}")
    except TypeError as err:
        print(err)
    
    # List to Integer
    try:
        int_val = int([1, 2, 3])
        print(f"Value of List converted to Integer: {int_val}")
    except TypeError as err:
        print(err)
    
    # Set to Integer
    try:
        int_val = int({1, 2, 3})
        print(f"Value of Set converted to Integer: {int_val}")
    except TypeError as err:
        print(err)
    
    # Dictionary to Integer
    try:
        int_val = int({"one": 1, "two": 2, "three": 3})
        print(f"Value of Dictionary converted to Integer: {int_val}")
    except TypeError as err:
        print(err)
    
    # None to Integer
    try:
        int_val = int(None)
        print(f"Value of None converted to Integer: {int_val}")
    except TypeError as err:
        print(err)
    Python

    Output:

    Value of Boolean True converted to Integer: 1
    Value of Boolean False converted to Integer: 0
    Value of String "23" converted to Integer: 23
    invalid literal for int() with base 10: '23abc'
    Value of Float 23.55 converted to Integer: 23
    Value of Float .5 converted to Integer: 0
    int() argument must be a string, a bytes-like object or a real number, not 'tuple'
    int() argument must be a string, a bytes-like object or a real number, not 'list'
    int() argument must be a string, a bytes-like object or a real number, not 'set'
    int() argument must be a string, a bytes-like object or a real number, not 'dict'
    int() argument must be a string, a bytes-like object or a real number, not 'NoneType'
    Plaintext

    Convert to Float

    Use the function “float()” to convert any data type to a floating number. “float()” function accepts a string, or real number.

    When we convert other data types to float-

    • Boolean to Float:
      • True converted to 1.0
      • False converted to 0.0
    • Integer to Float: converted to float, a decimal part(.0) is added to the integer.
    • String to Float: parsed to float if the full string is a float, else throws an error.
    • Tuple to Float: throws an error, as the “float()” function does not accept Tuple.
    • List to Float: throws an error, as the “float()” function does not accept List.
    • Set to Float: throws an error, as the “float()” function does not accept Set.
    • Dictionary to Float: throws an error, as the “float()” function does not accept Dictionary.

    Check the following examples-

    # Boolean to Float
    float_val = float(True)
    print(f"Value of Boolean True converted to Float: {float_val}")
    
    float_val = float(False)
    print(f"Value of Boolean False converted to Float: {float_val}")
    
    # Integer to Float
    float_val = float(10)
    print(f"Value of Integer 10 converted to Float: {float_val}")
    
    float_val = float(0)
    print(f"Value of Integer 0 converted to Float: {float_val}")
    
    float_val = float(-1)
    print(f"Value of negative Integer converted to Float: {float_val}")
    
    # String to Float
    float_val = float("23")
    print(f'Value of String "23" converted to Float: {float_val}')
    
    try:
        float_val = float("")
        print(f"Value of empty String converted to Float: {float_val}")
    except ValueError as err:
        print(err)
    
    # Tuple to Float
    try:
        float_val = float(())
        print(f"Value of empty Tuple converted to Float: {float_val}")
    except TypeError as err:
        print(err)
    
    try:
        float_val = float((1, 2, 3))
        print(f"Value of Tuple converted to Float: {float_val}")
    except TypeError as err:
        print(err)
    
    # List to Float
    try:
        float_val = float([])
        print(f"Value of empty List converted to Float: {float_val}")
    except TypeError as err:
        print(err)
    
    try:
        float_val = float([1, 2, 3])
        print(f"Value of List converted to Float: {float_val}")
    except TypeError as err:
        print(err)
    
    # Set to Float
    try:
        float_val = float({})
        print(f"Value of empty Set converted to Float: {float_val}")
    except TypeError as err:
        print(err)
    
    try:
        float_val = float({1, 2, 3})
        print(f"Value of Set converted to Float: {float_val}")
    except TypeError as err:
        print(err)
    
    # Dictionary to Float
    try:
        float_val = float({})
        print(f"Value of empty Dictionary converted to Float: {float_val}")
    except TypeError as err:
        print(err)
    
    try:
        float_val = float({"one": 1, "two": 2, "three": 3})
        print(f"Value of Dictionary converted to Float: {float_val}")
    except TypeError as err:
        print(err)
    
    # None to Float
    try:
        float_val = float(None)
        print(f"Value of None converted to Float: {float_val}")
    except TypeError as err:
        print(err)
    
    Python

    Output:

    Value of Boolean True converted to Float: 1.0
    Value of Boolean False converted to Float: 0.0
    Value of Integer 10 converted to Float: 10.0
    Value of Integer 0 converted to Float: 0.0
    Value of negative Integer converted to Float: -1.0
    Value of String "23" converted to Float: 23.0
    could not convert string to float: ''
    float() argument must be a string or a real number, not 'tuple'
    float() argument must be a string or a real number, not 'tuple'
    float() argument must be a string or a real number, not 'list'
    float() argument must be a string or a real number, not 'list'
    float() argument must be a string or a real number, not 'dict'
    float() argument must be a string or a real number, not 'set'
    float() argument must be a string or a real number, not 'dict'
    float() argument must be a string or a real number, not 'dict'
    float() argument must be a string or a real number, not 'NoneType'
    Plaintext

    Convert to String

    Use the function “str()” to convert any data type to a String. “str()” function accepts any type of param.

    When we convert to string-

    • Boolean to String:
      • True converted to “True”
      • False converted to “False”
    • Integer to String: converted to string, as it is in the integer value.
    • Float to String: converted to string, as it is in the float value.
    • Tuple to String: converted to string, as it is in the tuple value.
    • List to String: converted to string, as it is in the list value.
    • Set to String: converted to string, as it is in the set value.
    • Dictionary to String: converted to string, as it is in the dictionary value.

    Check the following examples-

    # Boolean to String
    str_val = str(True)
    print(f"Value of Boolean True converted to String: \"{str_val}\"")
    
    str_val = str(False)
    print(f"Value of Boolean False converted to String: \"{str_val}\"")
    
    # Integer to String
    str_val = str(10)
    print(f"Value of Integer 10 converted to String: \"{str_val}\"")
    
    str_val = str(0)
    print(f"Value of Integer 0 converted to String: \"{str_val}\"")
    
    str_val = str(-1)
    print(f"Value of negative Integer converted to String: \"{str_val}\"")
    
    # Float to String
    str_val = str(23.55)
    print(f"Value of String 23.55 converted to String: \"{str_val}\"")
    
    str_val = str(0.0)
    print(f"Value of String 0.0 converted to String: \"{str_val}\"")
    
    # Tuple to String
    str_val = str(())
    print(f"Value of empty Tuple converted to String: \"{str_val}\"")
    
    str_val = str((1, 2, 3))
    print(f"Value of Tuple converted to String: \"{str_val}\"")
    
    # List to String
    str_val = str([])
    print(f"Value of empty List converted to String: \"{str_val}\"")
    
    str_val = str([1, 2, 3])
    print(f"Value of List converted to String: \"{str_val}\"")
    
    # Set to String
    str_val = str({})
    print(f"Value of empty Set converted to String: \"{str_val}\"")
    
    str_val = str({1, 2, 3})
    print(f"Value of Set converted to String: \"{str_val}\"")
    
    # Dictionary to String
    str_val = str({})
    print(f"Value of empty Dictionary converted to String: \"{str_val}\"")
    
    str_val = str({"one": 1, "two": 2, "three": 3})
    print(f"Value of Dictionary converted to String: \"{str_val}\"")
    
    # None to String
    str_val = str(None)
    print(f"Value of None converted to String: \"{str_val}\"")
    Python

    Output:

    Value of Boolean True converted to String: "True"
    Value of Boolean False converted to String: "False"
    Value of Integer 10 converted to String: "10"
    Value of Integer 0 converted to String: "0"
    Value of negative Integer converted to String: "-1"
    Value of String 23.55 converted to String: "23.55"
    Value of String 0.0 converted to String: "0.0"
    Value of empty Tuple converted to String: "()"
    Value of Tuple converted to String: "(1, 2, 3)"
    Value of empty List converted to String: "[]"
    Value of List converted to String: "[1, 2, 3]"
    Value of empty Set converted to String: "{}"
    Value of Set converted to String: "{1, 2, 3}"
    Value of empty Dictionary converted to String: "{}"
    Value of Dictionary converted to String: "{'one': 1, 'two': 2, 'three': 3}"
    Value of None converted to String: "None"
    Plaintext

    Converting Incompatible Value

    What happens when we try to convert some value that is not compatible-

    Here we try to use the “int()” function to convert some value to an integer, but the value we provided is a string(that has no integer part to it). We will get an error-

    bigBoxVal = 'some random string here'
    
    print(f"Value of bigBoxVal is {bigBoxVal} and type is {type(bigBoxVal)}")
    
    bigBoxVal = int(bigBoxVal)
    
    print(f"Value of bigBoxVal is {bigBoxVal} and type is {type(bigBoxVal)}")
    Python

    Output:

    Value of bigBoxVal is some random string here and type is <class 'str'>
    
    Traceback (most recent call last):
      File "type_conversion.py", line 5, in <module>
        bigBoxVal = int(bigBoxVal)
                    ^^^^^^^^^^^^^^
    ValueError: invalid literal for int() with base 10: 'some random string here'
    Plaintext

    Leave a Comment


    The reCAPTCHA verification period has expired. Please reload the page.