Python: Type Conversion

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

Check the following example-

bigBoxVal = '100'

print(f"Value of bigBoxVal is {bigBoxVal} and type is {type(bigBoxVal)}")

bigBoxVal = float(bigBoxVal)

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 100 and type is <class 'str'>

Value of bigBoxVal is 100.0 and type is <class 'float'>

Value of bigBoxVal is 100 and type is <class 'int'>
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.