Intro to CS with Python — Data Types

What is a data type?

“A particular kind of data item, as defined by the values it can take, the programming language used, or the operations that can be performed on it.”

So, data types are simply the form in which information is returned from your Python commands. They are important because they are the key ingredients in any programming languages. As a chef, you will need to know what kind of ingredients are needed for in any dish. If you are using the wrong ingredient, you will end up with something that might taste “bad” — “bug” in programming.

Python Data Types

Built-in Data Types

Python’s built-in data types can be grouped into several classes.

  • boolean: True / False (1 / 0)
  • Numeric Types : int, float, complex
  • Sequences: str, list, tuple, bytes, byte array
  • Sets: set, frozen set (immutable set)
  • Mappings: dict (dictionary)

Mutability

In general, data types can be distinguished by its mutability. The content of immutable data types cannot be changed after they are created.

Immutable Types

  • int, float, complex
  • str
  • bytes
  • tuple
  • frozen set

Mutable Types

  • list
  • set
  • dict
  • byte array

Data Type Conversion

Type conversion in Python is done by the following functions.

type(data)  # returns the type of data
int()  # converts to int
float() # converts to float
str() # converts to str
bool() # converts to bool
list() # converts to list
set() # converts to set
tuple() # converts to tuple

None (null pointer)

None in Python is just a value that commonly used to indicate ‘empty’ or ‘no value’. Comparisons to None are usually done by using is rather than ==.

if var1 is None:
<< do something >>
elif var2 is not None:
<< do something >>