Chapter 02: Basics of Python Programming – Data Types
In programming, data types help to indicate what kind of value each piece of data holds. Python offers a variety of built-in data types, and understanding and using them correctly is essential for writing efficient and error-free code. In this chapter, we will delve deeply into Python’s main data types and their usage.
Main Data Types in Python
Python’s data types can be broadly classified into boolean (bool
), integer (int
), floating-point (float
), complex (complex
), string (str
), list (list
), tuple (tuple
), set (set
), and dictionary (dict
).
Boolean Type (bool
)
The boolean type represents logical true (True
) and false (False
). It is mainly used in conditional statements and is also employed in logical operations.
Example
is_raining = True
is_sunny = False
print(is_raining and is_sunny) # Output: False
print(is_raining or is_sunny) # Output: True
Integer Type (int
)
The integer type represents whole numbers. Python supports arbitrary precision, so there is no limit on the number of digits in an integer as long as memory allows.
Example
large_number = 10000000000000000000
small_number = -42
print(large_number + small_number) # Output: 9999999999999999958
Floating-Point Type (float
)
The floating-point type is used to represent numbers with decimal points (real numbers). The accuracy of floating-point numbers may vary slightly based on the binary representation used by the system.
Example
pi = 3.141592653589793
radius = 5.0
area = pi * (radius ** 2)
print("Area of the circle:", area) # Output: Area of the circle: 78.53981633974483
Complex Type (complex
)
The complex type is used to represent complex numbers composed of a real part and an imaginary part. Complex numbers are primarily used in scientific calculations or engineering mathematics.
Example
z = 3 + 4j
print("Real part:", z.real) # Output: Real part: 3.0
print("Imaginary part:", z.imag) # Output: Imaginary part: 4.0
String Type (str
)
String represents text and is enclosed in single or double quotes. Strings are immutable data types.
Example
greeting = "Hello, World!"
name = 'Alice'
message = greeting + " " + name
print(message) # Output: Hello, World! Alice
List Type (list
)
A list is a data type that can store multiple values in order and is defined with square brackets ([]). Lists are mutable data types, allowing for the addition, deletion, and modification of elements.
Example
fruits = ["apple", "banana", "cherry"]
fruits.append("orange")
print(fruits) # Output: ['apple', 'banana', 'cherry', 'orange']
fruits[1] = "blueberry"
print(fruits) # Output: ['apple', 'blueberry', 'cherry', 'orange']
Tuple Type (tuple
)
A tuple is similar to a list, but it has immutable characteristics. It is useful for managing objects that should not change. Tuples are defined with parentheses ().
Example
coordinates = (10.0, 20.0)
# coordinates[0] = 15.0 # Error: 'tuple' object does not support item assignment
print(coordinates) # Output: (10.0, 20.0)
Set Type (set
)
A set is a collection of unique elements with no defined order. It is useful for performing set-related operations. Sets are defined with curly braces ({}).
Example
fruit_set = {"apple", "banana", "cherry"}
fruit_set.add("orange")
print(fruit_set) # Output's order is random: {'orange', 'banana', 'cherry', 'apple'}
# Example of removing an element
fruit_set.remove("banana")
print(fruit_set) # Output: {'orange', 'cherry', 'apple'}
Dictionary Type (dict
)
A dictionary is a data type for storing key/value pairs. It is defined with curly braces ({}), and keys must be unique.
Example
person = {"name": "John", "age": 30, "job": "developer"}
print(person["name"]) # Output: John
# Adding a new key/value pair
person["city"] = "New York"
print(person) # Output: {'name': 'John', 'age': 30, 'job': 'developer', 'city': 'New York'}
Type Conversion
Converting data types in Python is very useful. It mainly occurs through explicit conversion or implicit conversion.
Explicit Conversion (Type Conversion)
Explicit conversion is done by the developer explicitly stating the conversion in the code. Python provides various functions for type conversion.
Example
# Converting an integer to a string
num = 123
num_str = str(num)
print(type(num_str)) # Output:
# Converting a string to an integer
str_num = "456"
num_int = int(str_num)
print(type(num_int)) # Output:
# Converting an integer to a floating-point number
int_num = 10
float_num = float(int_num)
print(float_num) # Output: 10.0
Implicit Conversion (Automatic Type Conversion)
Implicit conversion refers to type conversion that is automatically carried out by Python. It mainly occurs when there is no risk of data loss.
Example
int_num = 5
float_num = 2.3
result = int_num + float_num
print(result) # Output: 7.3
print(type(result)) # Output:
Conclusion
In this chapter, we learned about the various data types in Python. Understanding the characteristics and proper usage of each data type is very important for gaining a deeper understanding of Python programming. In the next chapter, we will cover more advanced topics such as control statements and functions, which will help you write more complex and powerful programs using Python.