Advertisement

Learn Python Intermediate: Level Up Your Skills

You've got the Python basics down. Now it's time to level up. This course covers intermediate concepts that'll make you a more capable Python programmer. We'll cover dictionaries, file handling, error handling, and more.

By the end of this course, you'll be able to build more complex programs and handle real-world programming tasks.

Prerequisites

Before starting, you should know:

  • Variables and data types
  • If statements and loops
  • Functions
  • Lists

If you're not comfortable with these, check out our Python for Beginners course first.

Lesson 1: Dictionaries

Dictionaries store key-value pairs. They're super useful for organizing data:

# Create a dictionary
person = {
    "name": "Alice",
    "age": 25,
    "city": "New York"
}

# Access values
print(person["name"])  # Alice
print(person.get("age"))  # 25

# Add or update
person["email"] = "alice@example.com"
person["age"] = 26

# Loop through
for key, value in person.items():
    print(f"{key}: {value}")

Dictionaries are perfect for storing structured data. Much more flexible than lists when you need to look things up by name.

Lesson 2: Sets

Sets store unique items. Great for removing duplicates or checking membership:

# Create a set
fruits = {"apple", "banana", "orange"}

# Add items
fruits.add("grape")

# Remove duplicates from a list
numbers = [1, 2, 2, 3, 3, 3, 4]
unique = set(numbers)
print(unique)  # {1, 2, 3, 4}

# Check membership (faster than lists)
if "apple" in fruits:
    print("Found!")

Sets are faster than lists for checking if something exists. Use them when you need unique items or fast lookups.

Lesson 3: List Comprehensions

List comprehensions are a concise way to create lists. They're Pythonic and efficient:

# Instead of this:
squares = []
for i in range(10):
    squares.append(i ** 2)

# Do this:
squares = [i ** 2 for i in range(10)]

# With conditions
even_squares = [i ** 2 for i in range(10) if i % 2 == 0]

# Nested
matrix = [[i * j for j in range(3)] for i in range(3)]

List comprehensions are more readable once you get used to them, and they're often faster than loops.

Lesson 4: Working with Files

Reading and writing files is essential for real programs:

# Reading a file
with open("file.txt", "r") as file:
    content = file.read()
    print(content)

# Reading line by line
with open("file.txt", "r") as file:
    for line in file:
        print(line.strip())  # strip() removes newline

# Writing to a file
with open("output.txt", "w") as file:
    file.write("Hello, World!")

# Appending to a file
with open("output.txt", "a") as file:
    file.write("\nNew line")

Always use with statements - they automatically close files, even if there's an error.

Lesson 5: Error Handling

Programs crash when they encounter errors. Handle them gracefully with try/except:

# Basic error handling
try:
    number = int(input("Enter a number: "))
    result = 10 / number
    print(f"Result: {result}")
except ValueError:
    print("That's not a valid number!")
except ZeroDivisionError:
    print("Can't divide by zero!")
except Exception as e:
    print(f"Something went wrong: {e}")

# Multiple exceptions
try:
    # your code
    pass
except (ValueError, TypeError) as e:
    print(f"Error: {e}")

Error handling makes your programs more robust. Users get helpful messages instead of crashes.

Advertisement

Lesson 6: Modules and Packages

Python has tons of built-in modules. Import them to use their features:

# Import entire module
import math
print(math.sqrt(16))  # 4.0

# Import specific function
from math import sqrt, pi
print(sqrt(16))
print(pi)

# Import with alias
import datetime as dt
now = dt.datetime.now()

# Common useful modules
import random
import os
import json
import csv

Don't reinvent the wheel - Python's standard library has modules for almost everything.

Lesson 7: Working with JSON

JSON is a common data format. Python makes it easy to work with:

import json

# Convert Python to JSON
data = {
    "name": "Alice",
    "age": 25,
    "city": "New York"
}
json_string = json.dumps(data)
print(json_string)

# Convert JSON to Python
json_data = '{"name": "Alice", "age": 25}'
python_data = json.loads(json_data)
print(python_data["name"])

# Read from file
with open("data.json", "r") as file:
    data = json.load(file)

# Write to file
with open("data.json", "w") as file:
    json.dump(data, file)

JSON is everywhere - APIs, config files, data storage. Knowing how to work with it is essential.

Lesson 8: Lambda Functions

Lambda functions are small, anonymous functions. Useful for simple operations:

# Regular function
def add(x, y):
    return x + y

# Lambda function (same thing)
add = lambda x, y: x + y

# Common use: sorting
people = [{"name": "Alice", "age": 25}, {"name": "Bob", "age": 30}]
people.sort(key=lambda p: p["age"])

# Common use: filtering
numbers = [1, 2, 3, 4, 5, 6]
evens = list(filter(lambda x: x % 2 == 0, numbers))

Lambdas are handy for simple operations, but don't overuse them - regular functions are clearer for complex logic.

Lesson 9: Generators

Generators are memory-efficient. They yield values one at a time instead of creating entire lists:

# Regular function (creates entire list)
def squares(n):
    result = []
    for i in range(n):
        result.append(i ** 2)
    return result

# Generator (yields one at a time)
def squares_gen(n):
    for i in range(n):
        yield i ** 2

# Use it
for square in squares_gen(10):
    print(square)

# Generator expression
squares = (i ** 2 for i in range(10))

Generators are great for large datasets - they don't store everything in memory at once.

Lesson 10: Decorators

Decorators modify functions. They're advanced but powerful:

# Simple decorator
def my_decorator(func):
    def wrapper():
        print("Before function")
        func()
        print("After function")
    return wrapper

@my_decorator
def say_hello():
    print("Hello!")

say_hello()
# Output:
# Before function
# Hello!
# After function

Decorators are used for logging, timing, authentication, and more. Advanced topic, but useful to know.

Putting It All Together

Let's build a simple program that uses multiple concepts:

import json

def load_data(filename):
    try:
        with open(filename, "r") as file:
            return json.load(file)
    except FileNotFoundError:
        return {}

def save_data(data, filename):
    with open(filename, "w") as file:
        json.dump(data, file)

def add_person(name, age, city):
    data = load_data("people.json")
    data[name] = {"age": age, "city": city}
    save_data(data, "people.json")
    print(f"Added {name}")

def list_people():
    data = load_data("people.json")
    for name, info in data.items():
        print(f"{name}: {info['age']} years old, lives in {info['city']}")

# Use it
add_person("Alice", 25, "New York")
add_person("Bob", 30, "Boston")
list_people()

This program uses dictionaries, file handling, JSON, error handling, and functions. Real programs combine multiple concepts.

What's Next?

Now that you know intermediate Python:

  • Learn about classes and object-oriented programming
  • Explore more modules (requests for web, pandas for data)
  • Build real projects
  • Learn about testing and debugging
  • Move on to advanced Python topics

Practice is key. Build projects that use these concepts. The more you code, the better you'll get.

Common Questions

When should I use dictionaries vs lists?

Use lists when order matters or you need to access items by index. Use dictionaries when you need to look things up by key (like a name or ID). Dictionaries are faster for lookups.

Are list comprehensions always better?

Not always. They're great for simple transformations, but if the logic is complex, a regular loop is clearer. Readability matters more than being clever.

How do I know which module to use?

Google it. "Python how to [what you want to do]" usually leads you to the right module. The Python documentation is also excellent - check docs.python.org.

Keep Learning and Practicing

You've learned intermediate Python concepts. Now practice them. Build projects, solve problems, write code. Try combining multiple concepts - use dictionaries with file handling, or list comprehensions with error handling. The more you practice, the more natural these concepts become.

Advertisement