Understanding Python Data Types
Python has several built-in data types that help us store and manipulate different kinds of data. Let's explore each one in detail:
1. Numbers
Python has several numeric types:
# Integers (whole numbers) age = 25 year = 2024 # Floats (decimal numbers) price = 19.99 pi = 3.14159 # Complex numbers complex_num = 3 + 4j
In this complex number, 3
is the real part and
4j
is the imaginary part. The
imaginary part is multiplied by j or the square root of -1. In
other words,
complex_num = 3 + 4*((-1) ** 0.5)
2. Strings
Strings are sequences of characters:
# String creation name = "Alice" message = 'Hello, World!' # String operations greeting = "Hello" name = "Alice" full_message = greeting + " " + name # Concatenation # String methods upper_text = "hello".upper() # HELLO lower_text = "WORLD".lower() # world length = len("Python") # 6
3. Lists
Lists are ordered, mutable sequences:
# Creating lists numbers = [1, 2, 3, 4, 5] fruits = ["apple", "banana", "orange"] # List operations numbers.append(6) # Add item fruits.remove("apple") # Remove item first_fruit = fruits[0] # Access item fruits[1] = "grape" # Modify item # List methods numbers.sort() # Sort list fruits.reverse() # Reverse list
4. Tuples
Tuples are ordered, immutable sequences:
# Creating tuples coordinates = (10, 20) rgb = (255, 128, 0) # Tuple operations x = coordinates[0] # Access item length = len(rgb) # Get length # Common use cases def get_coordinates(): return (5, 10) # Return multiple values
5. Dictionaries
Dictionaries store key-value pairs:
# Creating dictionaries person = { "name": "John", "age": 30, "city": "New York" } # Dictionary operations name = person["name"] # Access value person["email"] = "john@example.com" # Add item del person["age"] # Remove item # Dictionary methods keys = person.keys() # Get all keys values = person.values() # Get all values
6. Sets
Sets are unordered, mutable sequences of unique items:
# Creating sets inhabitants = { "Human", "Cat", "Dog" } # Set operations inhabitants.add(Antlion) # Add item inhabitants.update([Spider, Pig, Hamster]) # Add multiple items inhabitants.discard["Human"] # Remove item inhabitants2024 = frozenset(inhabitants) # Freeze set; Make immutable
7. Booleans
Booleans represent True or False values:
# Boolean values is_active = True is_finished = False # Boolean operations result = True and False # False result = True or False # True result = not True # False # Comparison operators is_adult = age >= 18 is_valid = name != ""
Conclusion
Understanding these data types is crucial for Python programming. Each type has its own specific use cases and methods. Booleans are often used in conditional statements to make decisions in code.