Let's move on to some more advanced concepts and features in Python. This session will cover topics like dictionaries, list comprehensions, and basic file handling.
Dictionaries
Dictionaries are used to store data values in key-value pairs.
# Creating a dictionary
person = {
"name": "Alice",
"age": 25,
"city": "New York"
}
# Accessing values
print(person["name"]) # Output: Alice
# Adding a new key-value pair
person["email"] = "alice@example.com"
List Comprehensions
List comprehensions provide a concise way to create lists.
# Without list comprehension
squares = []
for x in range(10):
squares.append(x**2)
# With list comprehension
squares = [x**2 for x in range(10)]
File Handling
Python allows you to read from and write to files.
Reading a File
with open('example.txt', 'r') as file:
content = file.read()
print(content)
Writing to a File
with open('example.txt', 'w') as file:
file.write("Hello, World!")
Exception Handling
Exceptions are errors that occur during execution. You can handle them using try-except blocks.
try:
result = 10 / 0
except ZeroDivisionError:
print("Cannot divide by zero!")
Classes and Objects
Python is an object-oriented programming language, which means it allows you to define classes and create objects.
class Dog:
def __init__(self, name, age):
self.name = name
self.age = age
def bark(self):
return "Woof!"
# Creating an object
my_dog = Dog("Buddy", 3)
print(my_dog.name) # Output: Buddy
print(my_dog.bark()) # Output: Woof!
These concepts will help you write more complex and efficient Python programs.