Type Conversion

code guest
Python Journey
Published in
7 min readAug 18, 2019

We know that each data value has a data type such as string, integer, float, list, dictionary etc. But it might be less intuitive to learn that each data value can be represented in different data types — here are some examples:

  • The characters “a”, “b”, “c” can be represented as a string “abc” or a list [“a”, ”b”, “c”] or a tuple (“a”, “b”, “c”)
  • The numerical information 100 can be represented as an integer 100, string “100” or float 100.0

One of the cool things that most programming languages including Python offer is the ability to work with the same data value in a different data type (like “abc” as [“a”, “b”, “c”])which is called type conversion.

As programmers, type conversion is a must-have tool in our toolkit because firstly, we will frequently encounter situations where we would want to use a data value in a different data type.

For example, one of the most frequent pieces of code we will write is to check the boolean value of a data value:

  • An empty string “” or empty list [] has a boolean value of False
  • Whereas strings with characters like “abc” or lists with items like [“hello”] have a boolean value of True.
  • And because we can use boolean values as a switch to only run some code if the situation we are checking turns out to be True, we can avoid errors due to empty string / list etc

Secondly, it is important to understand type conversion because operators cannot work with operands of different data types. (eg. 5 + “5” would not work in Python)

If you really want to do 5 + “5”, you would have to perform type conversion:

  • turning 5 to a string and add it to “5” to get “55”
  • or converting “5” to an integer and get 10

On the other hand, if we tried to do 5 + 5.0, it would run smoothly and give us 10.0 although 5 is an integer and 5.0 is a float— since operators cannot work with two different data types, has type conversion somehow taken place?

There are many situations in which we would find ourselves needing to use a data value in a different data type — and we have type conversion to do just that! (credits: undraw.co)

Implicit & explicit type conversion

The examples above of 5 + “5” and 5 + 5.0 demonstrate the two ways to do type conversion in Python — implicit and explicit.

The difference being that one happens automatically without us doing anything while the other happens only when we write code that does type conversion.

Explicit type conversion happens when we write code to work with a data value in a different data type — like using the str() function in str(123.1) to obtain a string “123.1” from float 123.1.

Implicit type conversion happens automatically without needing us to code for it. For example, when we add an integer to a float, Python automatically converts the integer to a float first before processing the addition.

Implicit type conversion typically takes place without us noticing it. Here are some examples:

  • when we use if statements to check for boolean value of data values (see the first few paragraphs above)
  • when we print some data value using the print() function, that data value gets implicitly converted to a string
  • when we try to perform arithmetic operations involving data values of bool, integer, float or complex data types, implicit type conversion occurs following the type conversion hierarchy below

Implicit type conversion hierarchy

Have you seen a food chain like the one below:

grass → rabbit → fox

Implicit type conversion also has a “hierarchy” in that the data type lower in hierarchy will be implicitly converted to the data type higher in the hierarchy when necessary (eg. like in 5 + 2.2 — the integer 5 is implicitly converted to float 5.0 first before being added with 2.2):

bool → integer → float → complex

  • bool → integer — True gets converted to 1 while False gets converted to 0
  • integer → float — integers get a decimal point to become floats
  • float → complex — not covered here but you can read it up at this link
# ExamplesTrue + True gives us 2True + True + 2.0 gives us 4.0False + False + True + 2.2 gives us 3.2

The rationale behind the implicit type conversion “hierarchy” is to preserve information:

  • if we implicitly convert floats to integers instead, the fractional part of the float would be lost
  • There is a fascinating discussion on why True is implicitly converted to 1 and False converted to 0.
Implicit type conversion follows a hierarchy and automatically occurs in operations involving data values mixed between bool, integer, float or complex data types. (credits: undraw.co)

Explicit type conversion in detail

There are quite a few ways to do type conversion and many situations where we will want to make use of these type conversion methods.

In this section, we will look at a couple of ways to do type conversion and explain their use-cases.

Conversion function for strings, integers & floats

The str() function can convert any data type to a string:

  • str(123) gives us “123”
  • str([1,2,3]) gives us “[1,2,3]”

The str() function is very useful because of its versatility in working with any data type. So if you have two or more data values of different data types, you could use the str() function to obtain these data values in string format for combination / comparison etc.

The int() function converts boolean values, floats and complex values (not discussed here).

  • False gets converted to 0 and True to 1 — int(True) gives us 1
  • Floats get rounded down to the nearest integer, losing some information in the process — int(10.75) gives us 10

Similar to the int() function, the float() function converts boolean values, integers and complex values (not discussed here) to floats.

  • False gets converted to 0.0 and True to 1.0 —float(True) gives us 1.0
  • Integers gain a .0

Conversion function for boolean values

Any data value can be converted to a boolean value explicitly using the bool(data value) function or implicitly using data values with if statements — and this conversion is probably the most widely used out of all the implicit and explicit conversion methods we have seen because boolean values control application logic.

# As mentioned above, checking boolean value of data values
# can help us avoid errors due to empty string, list, dictionary etc
# Used in an if statement,
# the data value X is implicitly converted to its boolean value
if X:
then do something
else:
do other thing

Almost every data value is converted to True. The only values interpreted as False are

  • The Boolean value False itself
  • Any numerical value equal to 0 like integer 0 or float 0.0
  • The special value None (None is a special value that represents ‘nothingness’ — it even has a data type all to itself — see this post for more info)
  • Any empty sequence like the empty string, empty list and empty tuple
Staring into the void — empty data values like “” or [] can cause our programs to fail! (credits: undraw.co)

ASCII table

The ASCII table is really cool! It maps characters like our alphabets, symbols and digit to ASCII code that in turn can be converted to binary code that our computer can understand:

  • The alphabet character “A” gets mapped to ASCII code (in integer data type) of 65 which gets converted into 8-bit binary code 01000001 which the computer can understand and display on our screen.

In python, we can use the chr(integer) function to obtain the corresponding ascii character value — eg. chr(65) gives us “A”.

We can also run the ord(character) function to obtain the corresponding ascii integer value — eg. ord(“A”) gives us back 65

Fun fact: The ASCII table contains mapping to characters like whitespace and line feed (\n which indicates that the text should continue on a new line)

The ASCII table maps characters (right-most) to ASCII code (left-most) and binary values for our computers to display! (credits: wikipedia)

Further reading

Summary

  • Each data value can be represented in different data types
  • Type conversion can be implicit or explicit
  • Implicit type conversion happens automatically and preserves information
  • Implicit type conversion follows a hierarchy in arithmetic operations: bool → int → float → complex
  • Examples of explicit type conversion include functions like str(), float(), int(), bool(), chr(), ord()

Quiz

Which of the following options are incorrect?
a) Implicit type conversion occurs in → True + 1

b) Explicit type conversion occurs in → int(“are you sure?”)

c) The boolean value of “False” is True

d) bool(“123”) which gives us True is a form of implicit type conversion

Quiz answers

a) True is a boolean value while 1 is an integer — Python automatically converts the boolean value to an integer following the implicit conversion hierarchy so that both operands have the same data type for the arithmetic operation to proceed.

b) The int() function doesn’t work on data values of string data types. It only works on data values of bool, float or complex data types.

c) “False” is a string which contains some characters and so it has a boolean value of True

d)Using the bool() function requires us to write code — it is a form of explicit type conversion

Quiz answers: b & d

--

--