Python Primitive Data Types: A Comprehensive Tutorial


Python is a popular programming language that is widely used in various fields including data science, web development, and artificial intelligence. In this tutorial, we will be discussing Python primitive data types. These data types are the building blocks of any programming language and they form the basis for more complex data structures.

Python has four primitive data types which include integers, floats, strings, and booleans. Integers represent whole numbers while floats represent decimal numbers. Strings are used to represent text data and booleans represent either true or false values.

In Python, we can assign values to variables using the assignment operator (=). For example, we can assign an integer value to a variable called num as shown below:

num = 10

Similarly, we can assign a float value to a variable called price as shown below:

price = 19.99

We can also assign a string value to a variable called name as shown below:

name = "John"

Finally, we can assign a boolean value to a variable called is_true as shown below:

is_true = True

Python also provides various built-in functions that can be used to perform operations on these primitive data types. For example, we can use the type() function to determine the data type of a particular variable.

print(type(num)) # Output: <class 'int'="">
print(type(price)) # Output: <class 'float'="">
print(type(name)) # Output: <class 'str'="">
print(type(is_true)) # Output: <class 'bool'="">

In conclusion, understanding Python primitive data types is essential for any Python programmer. They provide the foundation for more complex data structures and enable us to perform various operations on our data.

Numeric Data Types

Python has three main numeric data types: integers, floating-point numbers, and complex numbers.

Integers are whole numbers. They can be positive, negative, or zero. In Python, you can declare an integer by assigning a number to a variable:

x = 5
y = -10
z = 0

Floating-point numbers are decimal numbers. They can also be positive, negative, or zero. In Python, you can declare a floating-point number by adding a decimal point to the number:

a = 3.14
b = -2.5
c = 0.0

Complex numbers are numbers that have two parts: a real part and an imaginary part. The imaginary part is denoted with a “j” at the end of the number. In Python, you can declare a complex number by using the “j” notation:

d = 2 + 3j
e = -4j
f = 1.5 - 2.7j

You can perform arithmetic operations on numeric data types in Python using operators such as addition (+), subtraction (-), multiplication (*), and division (/). Here are some examples:

# Integer arithmetic operations
a = 5 + 3     # Result: 8
b = 10 - 4    # Result: 6
c = 2 * 6     # Result: 12
d = 20 / 4    # Result: 5 (division always returns a float)

# Floating-point arithmetic operations
e = 3.14 + 1.86      # Result: 5.0
f = -2.5 * 2         # Result: -5.0
g = 10 / 3           # Result: 3.33333333333 (division always returns a float)

# Complex arithmetic operations
h = (2 + 3j) + (1 - 2j)     # Result: 3 + j
i = (4 + 5j) * (2 - j)      # Result: 13 + 6j
j = (1.5 - 2.7j) / (-0.5j)  # Result: -3 - 3.0j

In addition to these basic arithmetic operations, Python also provides functions for more advanced mathematical operations such as exponentiation, square roots, and trigonometric functions. These functions are part of the built-in math module in Python.

Understanding the different numeric data types in Python is crucial for writing effective code that performs complex calculations and manipulations. By mastering these data types and the operations that can be performed on them, you will be well on your way to becoming a proficient Python programmer.

Text Data Type

Text Data Type:
In Python, text data is represented using the string data type. Strings are used to represent textual data such as names, addresses, sentences, and paragraphs. Strings are enclosed in single quotes (‘ ‘) or double quotes (” “) in Python.

Strings are a sequence of characters that can be accessed by their index values. The first character of the string has an index value of 0. Strings are immutable, which means their values cannot be changed once they are created.

Here’s an example of creating a string variable:

name = 'John'

In the above example, we have assigned the string ‘John’ to the variable name. We can access individual characters of this string using their index values like this:

print(name[0]) # Output: J

We can also concatenate two or more strings using the + operator:

first_name = 'John'
last_name = 'Doe'
full_name = first_name + ' ' + last_name
print(full_name) # Output: John Doe

We can also use various string methods to manipulate strings. Here are a few examples:

sentence = "The quick brown fox jumps over the lazy dog"
print(len(sentence)) # Output: 44 (returns the length of the string)

print(sentence.upper()) # Output: THE QUICK BROWN FOX JUMPS OVER THE LAZY DOG (converts all characters to uppercase)

print(sentence.split()) # Output: ['The', 'quick', 'brown', 'fox', 'jumps', 'over', 'the', 'lazy', 'dog'] (splits the string into a list of words)

In conclusion, strings are an important data type in Python and are used to represent textual data. They have various properties and methods that allow us to manipulate them in different ways.

Boolean Data Type

Python Primitive Data Types: A Comprehensive Tutorial

Boolean Data Type
The Boolean data type is one of the built-in data types in Python. It represents the truth values – True and False. These two values are the only instances of the Boolean data type.

Boolean Values (True and False)
In Python, True and False are predefined keywords that represent the Boolean values. True represents the truth or a positive result, while False represents a false or negative result.

We can create a variable with a Boolean value by assigning either True or False to it. For example:

is_raining = True
is_sunny = False

We can also use comparison operators to get Boolean values as results. For example:

x = 10
y = 5

print(x > y) # Output: True

print(x == y) # Output: False

In the above example, the first print statement will output True because x is greater than y. The second print statement will output False because x is not equal to y.

Boolean values are commonly used in conditional statements and loops to control program flow. For example:

if is_raining:
    print("Remember to bring an umbrella.")

if not is_sunny:
    print("It's not sunny today.")

In the first example, if it’s raining (is_raining is True), then the message “Remember to bring an umbrella.” will be printed. In the second example, if it’s not sunny (not is_sunny), then the message “It’s not sunny today.” will be printed.

Understanding Boolean data type and Boolean values in Python is essential for writing programs that involve decision making and conditional statements.

Sequence Data Types

Python has several built-in sequence data types. These data types allow you to store a collection of items, such as numbers or strings, in a single variable. In this section, we will explore three of the most commonly used sequence data types in Python: list, tuple, and range.

A list is a mutable sequence data type that can store a collection of items. Lists are defined by enclosing a comma-separated sequence of items in square brackets []. The items in a list can be of any data type, including other lists.

Here’s an example of how to define a list in Python:

my_list = [1, 2, 3, 4]

You can access individual elements of the list using index notation. The first element of the list has an index of 0. Here’s an example:

print(my_list[0]) # Output: 1

You can also modify individual elements of the list using index notation. Here’s an example:

my_list[0] = 5
print(my_list) # Output: [5, 2, 3, 4]

A tuple is an immutable sequence data type that can store a collection of items. Tuples are defined by enclosing a comma-separated sequence of items in parentheses (). The items in a tuple can be of any data type, including other tuples.

Here’s an example of how to define a tuple in Python:

my_tuple = (1, 2, 3, 4)

You can access individual elements of the tuple using index notation. Here’s an example:

print(my_tuple[0]) # Output: 1

However, you cannot modify individual elements of the tuple as they are immutable.

The range function is used to generate a sequence of numbers. It is commonly used in for loops to iterate over a sequence of numbers. The range function takes three arguments: start, stop, and step. Here’s an example:

my_range = range(1, 10, 2)
print(list(my_range)) # Output: [1, 3, 5, 7, 9]

In this example, the range function generates a sequence of numbers starting from 1 and ending at 10 (exclusive) with a step of 2. The list function is used to convert the range object into a list.

Mapping Data Type: Dictionary

A dictionary is a built-in data type in Python that allows you to store data in key-value pairs. It is also known as a hash table or associative array in other programming languages. The keys in a dictionary are unique and immutable, while the values can be of any data type.

To create a dictionary, you can enclose a comma-separated list of key-value pairs inside curly braces `{}` or use the built-in `dict()` function. Here is an example:

# Creating a dictionary
my_dict = {'name': 'Alice', 'age': 25, 'city': 'New York'}
print(my_dict)  # {'name': 'Alice', 'age': 25, 'city': 'New York'}

# Using the dict() function
my_dict2 = dict(name='Bob', age=30, city='San Francisco')
print(my_dict2)  # {'name': 'Bob', 'age': 30, 'city': 'San Francisco'}

You can access the values of a dictionary by using its keys inside square brackets `[]` or using the `get()` method. If the key is not found in the dictionary, `get()` returns `None` by default or a specified default value if provided. Here are some examples:

# Accessing values
print(my_dict['name'])  # Alice
print(my_dict.get('age'))  # 25

# Handling non-existent keys
print(my_dict.get('gender'))  # None
print(my_dict.get('gender', 'N/A'))  # N/A (default value)

You can also update or add new key-value pairs to a dictionary by assigning a value to a key or using the `update()` method. Here are some examples:

# Updating values
my_dict['age'] = 26
print(my_dict)  # {'name': 'Alice', 'age': 26, 'city': 'New York'}

# Adding new values
my_dict['gender'] = 'Female'
print(my_dict)  # {'name': 'Alice', 'age': 26, 'city': 'New York', 'gender': 'Female'}

# Using update()
my_dict.update({'age': 27, 'city': 'Los Angeles'})
print(my_dict)  # {'name': 'Alice', 'age': 27, 'city': 'Los Angeles', 'gender': 'Female'}

You can also remove key-value pairs from a dictionary using the `del` keyword or the `pop()` method. The `pop()` method removes and returns the value of the specified key, or the last key-value pair if no argument is provided. Here are some examples:

# Removing values
del my_dict['gender']
print(my_dict)  # {'name': 'Alice', 'age': 27, 'city': 'Los Angeles'}

# Using pop()
print(my_dict)  # {'name': 'Alice', 'city': 'Los Angeles'}

# Using popitem()
print(my_dict)  # {'name': 'Alice'}

Dictionaries are commonly used in Python for various purposes such as storing configuration settings, counting occurrences of items, and mapping values to functions. They are also used extensively in web development for handling JSON data and HTTP headers.

Sets and Frozensets Data Types

Python has two data types that represent sets: sets and frozensets. A set is an unordered collection of unique elements, while a frozenset is an immutable version of a set.

To create a set, you can use curly braces {} or the built-in function set(). For example:

my_set = {1, 2, 3}
print(my_set) # Output: {1, 2, 3}

my_set = set([1, 2, 3])
print(my_set) # Output: {1, 2, 3}

As you can see from the examples above, you can also create a set from a list by passing it as an argument to the set() function.

To create a frozenset, you can use the built-in function frozenset(). For example:

my_frozenset = frozenset([1, 2, 3])
print(my_frozenset) # Output: frozenset({1, 2, 3})

Once created, sets and frozensets support various operations such as union (|), intersection (&), difference (-), symmetric difference (^), and subset/superset checking (<= and >=).

set1 = {1, 2, 3}
set2 = {3, 4, 5}

# Union
print(set1 | set2) # Output: {1, 2, 3, 4, 5}

# Intersection
print(set1 & set2) # Output: {3}

# Difference
print(set1 - set2) # Output: {1, 2}

# Symmetric Difference
print(set1 ^ set2) # Output: {1, 2, 4 ,5}

# Subset/superset checking
print(set1 <= set2) # Output: False
print(set1 >= set2) # Output: False

Note that the subset/superset checking operators (<= and >=) return True if the left operand is a subset/superset of the right operand.

Frozensets are useful when you need to use sets as keys in dictionaries or as elements of other sets, since they are immutable and therefore hashable.

Type Conversion and Casting in Python Primitive Data Types

Type conversion and casting are important concepts in Python programming, especially when dealing with primitive data types. Type conversion refers to the process of changing the data type of a variable to another data type, while casting is the process of explicitly changing the data type of a variable.

Python provides built-in functions that can be used for type conversion and casting. Some common built-in functions for type conversion include int(), float(), str(), bool(), etc. These functions take an argument and return a value of the specified data type.

For example, if we have a string variable that contains a number, we can convert it to an integer using the int() function:

num_str = "10"
num_int = int(num_str)
print(num_int)   # Output: 10

Similarly, we can convert an integer to a float using the float() function:

num_int = 10
num_float = float(num_int)
print(num_float)   # Output: 10.0

Casting is useful when we need to change the data type of a variable temporarily without modifying its original value. For instance, we may need to perform arithmetic operations on variables with different data types. In such cases, we can cast one or more variables to a common data type.

Here’s an example of casting in Python:

num_int = 10
num_str = "20"
sum_numbers = num_int + int(num_str)   # Casting num_str to int
print(sum_numbers)   # Output: 30

In this example, we casted the `num_str` variable to an integer using the `int()` function before adding it to `num_int`. The result is stored in `sum_numbers`.

In conclusion, understanding type conversion and casting in Python is crucial for working with primitive data types effectively. By using built-in functions for type conversion and casting, we can easily change the data type of variables and perform operations on them.


In conclusion, understanding Python’s primitive data types is crucial for any beginner in programming. We have covered the fundamental concepts of Python’s primitive data types, including integers, floats, booleans, strings, and None.

Integers are whole numbers that can be positive or negative. They are used to represent values in mathematical operations and counting.

Floats are decimal numbers that can also be positive or negative. They are used to represent values that require more precision than integers, such as scientific calculations.

Booleans express a truth value and can only take two possible values: True or False. They are commonly used in conditional statements and loops.

Strings are sequences of characters enclosed in quotation marks. They are used to represent text-based data and can be manipulated using various string methods.

Finally, None is a special data type in Python that represents the absence of a value. It is commonly used as a placeholder or default value.

It is important to note that these data types can interact with each other through operators and functions. Understanding how they work together is essential for building complex programs.

By mastering these fundamental concepts, you will have a solid foundation to build upon as you continue your journey into the world of Python programming.
Interested in learning more? Check out our Introduction to Python course!

How to Become a Data Scientist PDF

Your FREE Guide to Become a Data Scientist

Discover the path to becoming a data scientist with our comprehensive FREE guide! Unlock your potential in this in-demand field and access valuable resources to kickstart your journey.

Don’t wait, download now and transform your career!

Pierian Training
Pierian Training
Pierian Training is a leading provider of high-quality technology training, with a focus on data science and cloud computing. Pierian Training offers live instructor-led training, self-paced online video courses, and private group and cohort training programs to support enterprises looking to upskill their employees.

You May Also Like

Data Science, Tutorials

Guide to NLTK – Natural Language Toolkit for Python

Introduction Natural Language Processing (NLP) lies at the heart of countless applications we use every day, from voice assistants to spam filters and machine translation. It allows machines to understand, interpret, and generate human language, bridging the gap between humans and computers. Within the vast landscape of NLP tools and techniques, the Natural Language Toolkit […]

Machine Learning, Tutorials

GridSearchCV with Scikit-Learn and Python

Introduction In the world of machine learning, finding the optimal set of hyperparameters for a model can significantly impact its performance and accuracy. However, searching through all possible combinations manually can be an incredibly time-consuming and error-prone process. This is where GridSearchCV, a powerful tool provided by Scikit-Learn library in Python, comes to the rescue. […]

Python Basics, Tutorials

Plotting Time Series in Python: A Complete Guide

Introduction Time series data is a type of data that is collected over time at regular intervals. It can be used to analyze trends, patterns, and behaviors over time. In order to effectively analyze time series data, it is important to visualize it in a way that is easy to understand. This is where plotting […]