Welcome to this detailed and comprehensive guide on Python data types. In this tutorial, we will explore numeric data types, booleans, and sets, along with their practical applications. Let's dive in!
I. Numeric Data Types in Python
Python supports several built-in data types. These are the foundation of any data manipulation and analysis. Understanding them is key to becoming proficient in Python.
A. Built-in numeric types
Python's numeric data types are immutable, meaning their values don't change. Here, we will discuss the two most common types: integers and floats.
1. Integers
Integers are whole numbers, positive or negative, without any decimal points. They are great for counting or ranking items. Let's define an integer:
count = 5
print(type(count))
Output:
<class 'int'>
2. Floats
Floats represent real numbers and are written with a decimal point. They allow us to work with fractions and can handle substantial values. Let's define a float:
temperature = 36.7
print(type(temperature))
Output:
<class 'float'>
B. Use of Decimals for exact precision and currency operations
When working with currency or where exact precision is required, decimals come in handy. They offer more precision compared to floats.
1. How to import and use Decimals
Python provides a decimal module to handle decimal numbers. Let's import the Decimal class from the decimal module:
from decimal import Decimal
price = Decimal('19.99')
print(type(price))
Output:
<class 'decimal.Decimal'>
Here, '19.99' is a string which is converted into a decimal object.
C. Printing Floats
Sometimes, when working with very small floats, you might notice that Python
converts them into scientific notation. Let's find out how we can handle such cases.
1. The issue with printing small floats
When you print a small float number, you'll notice it returns in scientific notation. Let's try to print 0.00001:
print(0.00001)
Output:
1e-05
Here, 1e-05 is scientific notation for 0.00001.
2. The use of f-strings to control float outputs
We can use f-strings, a feature of Python, to control the output and avoid scientific notation. Here's how:
print(f"{0.00001:f}")
Output:
0.000010
By using :f in the f-string, we were able to display the float in decimal format instead of scientific notation.
3. Setting the precision in the f-string format specifier
By default, Python's f-string stops at six decimal places. But, we can modify this by adding a .X in the f-string where X is the number of decimal places we want. Let's print a small float with seven decimal places:
print(f"{0.0000001:.7f}")
Output:
0.0000001
D. Types of Python Division
Python supports two types of division: float division and floor division.
1. Float division
Float division returns a float value as the result. The operator used is a single forward slash /.
print(4/2)
Output:
2.0
Even though both numbers are integers, the division operator / returns a float.
2. Floored division
Floored division returns the largest possible integer. The operator used is a double forward slash //.
print(7//3)
Output:
2
Here, 7 divided by 3 is 2.33. However, // returns 2, the largest possible integer that is less than or equal to the actual division result.
II. Boolean Data Type
Boolean is a simple type with two values: True and False. Booleans are primarily used in conditional expressions.
A. Definition and usage of Booleans in Python
A boolean represents the truth values that are associated with the logic branch of mathematics, which informs algorithms in computer science.
is_active = True
print(type(is_active))
Output:
<class 'bool'>
B. Booleans as a data type
As a built-in data type in Python, booleans can play different roles in coding scripts, such as the two roles mentioned below.
1. The two boolean values: true and false
As we have already discussed, boolean has only two possible objects True and False.
is_raining = False
print(is_raining)
Output:
False
2. How to use booleans in conditionals
Booleans are often used in conditional statements to help the program make a decision.
weather = "Rainy"
if weather == "Rainy":
is_raining = True
else:
is_raining = False
print(is_raining)
Output:
True
C. Truthy and Falsey values
In Python, values that evaluate to True are referred to as "truthy", and those that evaluate to False are called "falsey".
1. Definition and examples of truthy and falsey values
Let's examine an example:
print(bool(0)) # Falsey value
print(bool(1)) # Truthy value
Output:
False
True
Here, 0 is considered "falsey" and 1 is considered "truthy". There are other "truthy" and "falsey" values in Python. For example, an empty list [] is a "falsey" value, while a non-empty list like [1, 2] is a "truthy" value.
D. Python operators in a boolean context
Operators can help us compare different values. Let's look at some of the operators and how they can be used in a boolean context.
1. Equality comparison
The double equal sign '==' is used to check if two values are equal.
print(5 == 5) # True because 5 is equal to 5
Output:
True
2. Other comparison operators
Other comparison operators include '>', '<', '!=', '>=', and '<='. Here are some examples:
print(5 > 3) # True because 5 is greater than 3
print(5 != 5) # False because 5 is equal to 5, not different
Output:
True
False
E. Issues with floating point precision in boolean comparisons
Due to how floating point numbers are represented in computer memory, two numbers that should be equal might not be. Here's an example:
num1 = 0.1 + 0.2
num2 = 0.3
print(num1 == num2)
Output:
False
Here, we would expect the two sums to be equal, but they are not due to precision issues. We have to keep this in mind while dealing with float values in boolean comparisons.
III. Sets in Python
A set in Python is a collection of unique elements. Sets are mutable, unordered, and do not allow duplicate elements. This tutorial part will explore the definition and uses of sets, as well as how to create, modify, and perform operations on them.
A. Definition and uses of Sets
In Python, a set is defined with curly braces {} or the set() function. A set only allows unique elements, automatically removing duplicates. Sets are useful when you need to avoid duplicates or when you need to perform operations like union and intersection.
my_set = {1, 2, 3, 4, 4, 4}
print(my_set)
Output:
{1, 2, 3, 4}
In the above example, the set my_set removes the duplicates and only retains a
single instance of the number 4.
B. Creating sets from lists
You can convert a list into a set using the set() function. This can be handy when you need to eliminate duplicate elements.
1. The uniqueness of set elements
my_list = [1, 2, 2, 3, 4, 4, 4]
my_set = set(my_list)
print(my_set)
Output:
{1, 2, 3, 4}
In the above example, all duplicates in the list are removed when it's converted to a set.
C. Modifying sets
You can add items to sets using the add and update methods.
1. How to add elements using the add method
my_set = {1, 2, 3, 4}
my_set.add(5)
print(my_set)
Output:
{1, 2, 3, 4, 5}
2. How to add multiple items using the update method
my_set = {1, 2, 3, 4}
my_set.update([5, 6, 7])
print(my_set)
Output:
{1, 2, 3, 4, 5, 6, 7}
D. Removing data from sets
You can remove elements from a set using methods like discard and pop.
1. Using the discard method
The discard method removes the specified item from the set.
my_set = {1, 2, 3, 4}
my_set.discard(1)
print(my_set)
Output:
{2, 3, 4}
2. Using the pop method
The pop method removes and returns an arbitrary set element.
my_set = {1, 2, 3, 4}
removed_element = my_set.pop()
print(removed_element)
print(my_set)
Output:
1
{2, 3, 4}
E. Set operations
Python supports various operations that can be performed with sets such as union, intersection, and difference.
1. Union operation
The union method returns a set that contains all items from the original set, and all items from the specified sets.
set1 = {1, 2, 3}
set2 = {3, 4, 5}
union_set = set1.union(set2)
print(union_set)
Output:
{1, 2, 3, 4, 5}
2. Intersection operation
The intersection method returns a set that contains the similarity between two or more sets.
set1 = {1, 2, 3}
set2 = {3, 4, 5}
intersection_set = set1.intersection(set2)
print(intersection_set)
Output:
{3}
3. Difference operation
The difference method returns a set that contains the difference between two sets.
set1 = {1, 2, 3}
set2 = {3, 4, 5}
difference_set = set1.difference(set2)
print(difference_set)
Output:
{1, 2}
By mastering these fundamental data types and operations in Python, you will have taken an important step in becoming a proficient programmer. Remember, it's not just about knowing these concepts, but knowing when to use each one that truly marks a skilled developer. Keep practicing, and happy coding!