Python Guide - Road to Mastery (Course 3)

Advanced Python Topics

Advanced Python Topics

Let's explore more advanced Python concepts, including Data Structures, File Handling, Error Handling, and more!

16. Data Structures

Python has several built-in data structures like lists, tuples, dictionaries, and sets. Let’s dive deeper into each of these.

Lists

# List example fruits = ["apple", "banana", "cherry"] fruits.append("orange") # Add an item fruits.remove("banana") # Remove an item print(fruits)

Tuples

# Tuple example coordinates = (1, 2) print(coordinates[0]) # Access elements in a tuple

Dictionaries

# Dictionary example person = {"name": "Alice", "age": 25} print(person["name"]) # Access value by key

Sets

# Set example numbers = {1, 2, 3, 4, 5} numbers.add(6) # Add an item numbers.remove(3) # Remove an item print(numbers)

17. File Handling

Learn how to read from and write to files in Python.

# Write to a file with open("example.txt", "w") as file: file.write("Hello, world!") # Read from a file with open("example.txt", "r") as file: print(file.read())

18. Error Handling

Python provides a way to handle errors using try-except blocks.

try: num = int(input("Enter a number: ")) print(f"Your number is: {num}") except ValueError: print("Oops! That's not a valid number.")

19. Advanced Functions

Let’s explore some advanced function concepts like lambda functions and higher-order functions.

Lambda Function

# Lambda function example multiply = lambda x, y: x * y print(multiply(5, 3)) # Output: 15

Map Function

# Map function example numbers = [1, 2, 3, 4] squared_numbers = list(map(lambda x: x ** 2, numbers)) print(squared_numbers) # Output: [1, 4, 9, 16]

20. Python Quiz

Test your knowledge with this quick quiz.

Question 1: What will be the output of the following code? fruits = ["apple", "banana", "cherry"] fruits.remove("banana") print(fruits)

✅ Correct! Well done!

21. Interactive Python Editor

Use the interactive Python editor below to practice your own code:


22. Challenge Task

Write a function that checks if a number is prime:

def is_prime(n): # Your code here pass

Challenge yourself to implement the is_prime function!