Python Refresher


  1. Introduction to Python

  2. Basic Data Types and Variables

  3. Control Flow

  4. Data Structures

  5. Functions and Modules

  6. File Handling

  7. Error Handling and Exceptions

  8. Object-Oriented Programming (OOP)

  9. Working with External Libraries

  10. Practical Projects and Next Steps


Chapter 1: Introduction to Python

1.1 What is Python?

Python is a high-level, interpreted programming language known for its simplicity, readability, and versatility. Created by Guido van Rossum and first released in 1991, Python has become one of the most popular programming languages in the world, used in web development, data science, automation, artificial intelligence, robotics, and more.

Key Features:

1.2 Why Use Python?

Python is ideal for both beginners and experienced developers because:

1.3 Installing Python

Check if Python is Installed

Open a terminal (Command Prompt, PowerShell, or Terminal) and type:

python --version

or

python3 --version

If you see a version number (e.g., Python 3.11.0), Python is installed.

Download and Install

1.4 Running Python Code

Interactive Python (REPL)

You can start the Python interactive shell (REPL) by typing:

python

or

python3

You’ll see a prompt like:

>>>

You can type Python code here and see the results immediately.

Example:

>>> print("Hello, world!")
Hello, world!

Running Python Scripts

Save your code in a file with a .py extension, for example hello.py:

print("Hello, world!")

Run the script from the terminal:

python hello.py

1.5 Python IDEs and Editors

You can write Python code in any text editor, but some popular choices include:

Choose the one that best fits your workflow.

1.6 Next Steps

Now that you have Python installed and know how to run code, you’re ready to dive into Python’s basic data types and variables in Chapter 2.


Summary:
This chapter introduced Python’s history, features, setup, and how to run Python code interactively and via scripts. You also learned about different editors to write Python code. In the next chapter, we’ll explore the core building blocks of Python: data types and variables.



Chapter 2: Basic Data Types and Variables

2.1 Introduction

Every programming language has ways to store and manipulate data. In Python, data is represented using various built-in data types. Understanding these types and how to use variables is essential for building any Python program.


2.2 Core Data Types

Integers

Floats

Strings

Booleans


2.3 Variables

Examples:

x = 5
user_name = "Bob"
has_access = False

Naming Conventions:


2.4 Type Conversion

You can convert between data types using built-in functions:

age = "30"
age = int(age)  # Converts string to integer

price = 10
price_str = str(price)  # Converts integer to string

is_valid = bool("non-empty")  # Converts to True

2.5 Basic Input and Output

Output with print()

print("Welcome to Python!")
print("The answer is", 42)

Input with input()

name = input("Enter your name: ")
print("Hello,", name)

Note: input() always returns a string. Convert it to another type if needed.

age = int(input("Enter your age: "))
print("Next year you will be", age + 1)

2.6 Checking Types

Use the type() function to check a variable’s data type:

print(type(42))        # <class 'int'>
print(type(3.14))      # <class 'float'>
print(type("hello"))   # <class 'str'>
print(type(True))      # <class 'bool'>

2.7 Summary

In the next chapter, we’ll see how to use these values in decision-making and loops with control flow statements.



Chapter 3: Control Flow

3.1 Introduction

Control flow statements determine the order in which code is executed in a Python program. In this chapter, you’ll learn how to make decisions with conditional statements and how to repeat actions using loops.


3.2 Conditional Statements

Conditional statements let you execute code blocks only if certain conditions are met.

The if Statement

x = 10
if x > 5:
    print("x is greater than 5")

if-else Statement

age = 17
if age >= 18:
    print("You can vote.")
else:
    print("You cannot vote.")

if-elif-else Statement

score = 85
if score >= 90:
    print("Grade: A")
elif score >= 80:
    print("Grade: B")
elif score >= 70:
    print("Grade: C")
else:
    print("Grade: D or F")

Comparison Operators

Logical Operators

Example:

temperature = 22
is_sunny = True

if temperature > 20 and is_sunny:
    print("Great day for a walk!")

3.3 Indentation

Python uses indentation (spaces or tabs) to define code blocks. Consistent indentation is crucial.

if True:
    print("This is indented and part of the if block.")
print("This is outside the if block.")

3.4 Loops

Loops let you repeat actions multiple times.

The while Loop

Repeats as long as a condition is True.

count = 0
while count < 3:
    print("Counting:", count)
    count += 1

The for Loop

Iterates over a sequence (list, string, range, etc.).

for letter in "cat":
    print(letter)

Using range()

for i in range(5):
    print(i)  # Prints 0 to 4

3.5 Loop Control Statements

Example:

for i in range(10):
    if i == 5:
        break  # Stops the loop when i is 5
    if i % 2 == 0:
        continue  # Skips even numbers
    print(i)

3.6 The pass Statement

pass is a placeholder that does nothing; useful when a statement is required syntactically.

if False:
    pass  # Code not yet implemented

3.7 Nested Control Flow

You can nest if statements and loops inside each other.

for i in range(3):
    if i % 2 == 0:
        print(i, "is even")
    else:
        print(i, "is odd")

3.8 Summary

In the next chapter, we’ll explore Python’s core data structures: lists, tuples, sets, and dictionaries.



Chapter 4: Data Structures

4.1 Introduction

Data structures help you organize, store, and manipulate data efficiently. Python provides several built-in data structures, each suited to different types of tasks. This chapter covers lists, tuples, sets, and dictionaries.


4.2 Lists

A list is an ordered, mutable collection of items.

Creating Lists

fruits = ["apple", "banana", "cherry"]
numbers = [1, 2, 3, 4, 5]
mixed = [1, "hello", 3.14, True]

Accessing Elements

print(fruits[0])    # "apple"
print(fruits[-1])   # "cherry"

Slicing

print(numbers[1:4])     # [2, 3, 4]
print(numbers[:3])      # [1, 2, 3]
print(numbers[::2])     # [1, 3, 5]

Modifying Lists

fruits[1] = "blueberry"
fruits.append("date")
fruits.insert(1, "banana")
print(fruits)

Removing Items

fruits.remove("banana")   # Removes first occurrence
popped = fruits.pop()     # Removes and returns last item
del fruits[0]             # Deletes item at index 0

List Methods


4.3 Tuples

A tuple is an ordered, immutable collection.

Creating Tuples

coordinates = (4, 5)
person = ("Alice", 30)
single = (42,)  # Note the comma

Accessing Elements

print(coordinates[1])  # 5

Immutability


4.4 Sets

A set is an unordered collection of unique items.

Creating Sets

colors = {"red", "green", "blue"}
numbers = set([1, 2, 2, 3])
print(numbers)  # {1, 2, 3}

Set Operations

a = {1, 2, 3}
b = {3, 4, 5}
print(a | b)  # Union: {1, 2, 3, 4, 5}
print(a & b)  # Intersection: {3}
print(a - b)  # Difference: {1, 2}

Methods


4.5 Dictionaries

A dictionary is an unordered collection of key-value pairs.

Creating Dictionaries

person = {"name": "Bob", "age": 25}
empty = dict()

Accessing and Modifying

print(person["name"])        # "Bob"
person["age"] = 26
person["city"] = "London"

Removing Keys

del person["city"]
removed = person.pop("age")

Iterating

for key in person:
    print(key, person[key])

for value in person.values():
    print(value)

for key, value in person.items():
    print(key, "->", value)

4.6 Nesting Data Structures

You can combine data structures:

users = [
    {"name": "Alice", "age": 30},
    {"name": "Bob", "age": 25}
]
matrix = [[1, 2], [3, 4]]

4.7 Summary

These structures are core to organizing data in Python. Next, we’ll see how to write reusable code using functions and modules.



Chapter 5: Functions and Modules

5.1 Introduction

Functions and modules are essential for writing organized, reusable, and maintainable code. Functions let you group code into blocks that can be executed repeatedly, while modules allow you to organize code into separate files and use Python’s vast ecosystem of libraries.


5.2 Defining and Calling Functions

A function is a block of code that performs a specific task and can be called by name.

Defining a Function

def greet():
    print("Hello!")

Calling a Function

greet()  # Outputs: Hello!

Function Parameters and Arguments

Functions can take inputs (parameters):

def greet(name):
    print("Hello,", name)

greet("Alice")  # Outputs: Hello, Alice

You can have multiple parameters:

def add(a, b):
    return a + b

result = add(3, 4)  # result is 7

5.3 Return Values

Functions can return values using the return statement.

def square(x):
    return x * x

result = square(5)  # result is 25

If no return is specified, the function returns None.


5.4 Default Parameters and Keyword Arguments

You can provide default values for parameters:

def greet(name="World"):
    print("Hello,", name)

greet()           # Outputs: Hello, World
greet("Bob")      # Outputs: Hello, Bob

Keyword arguments allow you to specify parameters by name:

def power(base, exponent=2):
    return base ** exponent

print(power(3))           # 9
print(power(3, exponent=3))  # 27

5.5 Variable Scope

x = 10  # Global

def foo():
    y = 5  # Local
    print(x, y)

foo()
# print(y)  # Error: y is not defined outside foo()

To modify a global variable inside a function, use the global keyword.


5.6 Docstrings

You can add documentation to functions using docstrings:

def add(a, b):
    """
    Returns the sum of a and b.
    """
    return a + b

print(add.__doc__)

5.7 Modules and Imports

A module is a file containing Python definitions and code. You can use modules to organize your code and to use external libraries.

Importing Modules

import math
print(math.sqrt(16))  # 4.0

You can import specific functions:

from math import sqrt
print(sqrt(25))  # 5.0

You can also give an imported module an alias:

import numpy as np

5.8 Creating Your Own Modules

Any .py file is a module. For example, if you have mymodule.py:

# mymodule.py
def hello():
    print("Hello from mymodule!")

You can import and use it in another file:

import mymodule
mymodule.hello()

5.9 The Python Standard Library

Python comes with many useful modules, such as:

Explore the Python Standard Library documentation for more.


5.10 Summary

In the next chapter, you’ll learn how to handle files for reading and writing data.



Chapter 6: File Handling

6.1 Introduction

File handling is crucial for reading from and writing to files, allowing your Python programs to interact with data stored on disk. This chapter covers opening, reading, writing, and closing files, as well as best practices for working with files.


6.2 Opening Files

Use the built-in open() function to work with files. The basic syntax is:

file_object = open("filename.txt", "mode")

Common modes:

Example:

file = open("example.txt", "r")

6.3 Reading Files

Reading the Entire File

file = open("example.txt", "r")
content = file.read()
print(content)
file.close()

Reading Line by Line

file = open("example.txt", "r")
for line in file:
    print(line.strip())
file.close()

Reading Lines into a List

file = open("example.txt", "r")
lines = file.readlines()
print(lines)
file.close()

6.4 Writing Files

Overwriting Contents

file = open("output.txt", "w")
file.write("Hello, world!\n")
file.write("This is a new file.\n")
file.close()

Appending to Files

file = open("output.txt", "a")
file.write("Adding another line.\n")
file.close()

6.5 Closing Files

Always close files to free up system resources.

file = open("data.txt")
# ... work with file ...
file.close()

6.6 Using with Statements (Context Managers)

A safer and more concise way to handle files is with the with statement, which automatically closes the file:

with open("example.txt", "r") as file:
    content = file.read()
    print(content)
# File is automatically closed here

6.7 File Paths

Example:

import os
print(os.getcwd())  # Get current working directory

from pathlib import Path
p = Path("folder") / "file.txt"
with open(p, "r") as file:
    print(file.read())

6.8 Handling File Exceptions

Use try-except blocks to handle errors like missing files:

try:
    with open("missing.txt") as file:
        data = file.read()
except FileNotFoundError:
    print("File not found!")

6.9 Working with Other File Types

For binary files, add "b" to the mode:

with open("image.png", "rb") as file:
    data = file.read()

For reading and writing CSV, JSON, and other formats, use modules like csv and json:

import json
with open("data.json") as f:
    data = json.load(f)

6.10 Summary

Next, you’ll learn how to handle errors and exceptions in Python programs.



Chapter 7: Error Handling and Exceptions

7.1 Introduction

Errors are inevitable in programming. Python provides a robust system for handling errors and exceptions, allowing you to write more reliable and user-friendly programs. In this chapter, you’ll learn how to anticipate, catch, and respond to exceptions.


7.2 What Are Exceptions?

An exception is an error detected during execution. When an exception occurs, normal program flow is interrupted. If not handled, the program will terminate and display a traceback.

Example:

print(10 / 0)  # Raises ZeroDivisionError
numbers = [1, 2, 3]
print(numbers[5])  # Raises IndexError

7.3 The try-except Block

Use try-except blocks to handle exceptions gracefully.

Syntax:

try:
    # Code that might raise an exception
    risky_code()
except SomeException:
    # Code to handle the exception
    handle_the_problem()

Example:

try:
    x = int(input("Enter a number: "))
    print(100 / x)
except ValueError:
    print("Please enter a valid number!")
except ZeroDivisionError:
    print("Cannot divide by zero!")

7.4 Catching All Exceptions

You can catch any exception by omitting the exception type, but use this sparingly.

try:
    # risky code
except:
    print("Something went wrong.")

It’s better to catch specific exceptions when possible.


7.5 The else and finally Blocks

try:
    file = open("data.txt")
except FileNotFoundError:
    print("File not found.")
else:
    data = file.read()
    file.close()
finally:
    print("Attempted to open file.")

7.6 Raising Exceptions

You can raise exceptions intentionally using the raise statement.

def set_age(age):
    if age < 0:
        raise ValueError("Age cannot be negative!")
    print("Age set to:", age)

set_age(-5)  # Raises ValueError

7.7 Creating Custom Exceptions

Define your own exception classes by inheriting from Exception.

class NegativeNumberError(Exception):
    pass

def check_positive(number):
    if number < 0:
        raise NegativeNumberError("Negative numbers are not allowed.")

try:
    check_positive(-2)
except NegativeNumberError as e:
    print(e)

7.8 Common Built-in Exceptions


7.9 Best Practices


7.10 Summary

Next, you’ll learn about object-oriented programming and how to use classes and objects in Python.



Chapter 8: Object-Oriented Programming (OOP)

8.1 Introduction

Object-Oriented Programming (OOP) is a paradigm that organizes code using objects and classes. OOP makes it easier to manage complex programs by grouping data and behavior together, encouraging code reuse and modularity.


8.2 Classes and Objects

A class is a blueprint for creating objects, which are instances of that class.

Defining a Class

class Dog:
    pass

Creating Objects

my_dog = Dog()
print(type(my_dog))  # <class '__main__.Dog'>

8.3 Instance Attributes and Methods

Attributes are variables that belong to an object. Methods are functions defined within a class.

The __init__ Method

The __init__ method initializes the object’s attributes.

class Dog:
    def __init__(self, name, age):
        self.name = name
        self.age = age

my_dog = Dog("Buddy", 5)
print(my_dog.name)  # Buddy

Instance Methods

Instance methods operate on the object’s data.

class Dog:
    def __init__(self, name):
        self.name = name
    def bark(self):
        print(self.name, "says woof!")

my_dog = Dog("Fido")
my_dog.bark()  # Fido says woof!

8.4 Class Attributes and Methods

class Cat:
    species = "Felis catus"  # Class attribute
    def __init__(self, name):
        self.name = name  # Instance attribute

cat1 = Cat("Whiskers")
cat2 = Cat("Luna")
print(cat1.species, cat2.species)  # Felis catus Felis catus

8.5 Inheritance

Inheritance lets you create a new class based on an existing one.

class Animal:
    def speak(self):
        print("Some sound")

class Dog(Animal):
    def speak(self):
        print("Woof!")

d = Dog()
d.speak()  # Woof!

8.6 The super() Function

Use super() to call methods from the parent class.

class Animal:
    def __init__(self, name):
        self.name = name

class Dog(Animal):
    def __init__(self, name, breed):
        super().__init__(name)
        self.breed = breed

8.7 Encapsulation and Private Members

class Person:
    def __init__(self, name):
        self._name = name  # Protected
        self.__secret = "hidden"  # Private

p = Person("Alice")
print(p._name)  # Allowed, but discouraged
# print(p.__secret)  # AttributeError

8.8 Polymorphism

Polymorphism allows different classes to provide different implementations of the same method.

class Bird:
    def speak(self):
        print("Chirp")

class Duck(Bird):
    def speak(self):
        print("Quack")

animals = [Bird(), Duck()]
for a in animals:
    a.speak()  # Output: Chirp Quack

8.9 Special Methods

Special methods (dunder methods) define behavior for built-in operations.

class Book:
    def __init__(self, title):
        self.title = title
    def __str__(self):
        return f"Book: {self.title}"

b = Book("1984")
print(b)  # Book: 1984

8.10 Summary

In the next chapter, you’ll learn how to work with external libraries and manage dependencies in Python.



Chapter 9: Working with External Libraries

9.1 Introduction

Python’s true power comes from its vast ecosystem of external libraries (also called packages or modules). These libraries expand Python’s capabilities for web development, data science, networking, automation, and much more. This chapter shows you how to find, install, and use external libraries, as well as manage dependencies with virtual environments.


9.2 Finding Libraries


9.3 Installing Libraries with pip

pip install package_name
pip install --upgrade package_name
pip uninstall package_name

Example:

pip install requests

9.4 Importing and Using Libraries

After installation, import the library in your Python code:

import requests

response = requests.get("https://api.github.com")
print(response.status_code)
print(response.json())

Many libraries have their own documentation and usage guides online. Refer to the official docs for best practices.


9.5 Managing Project Dependencies

As your projects grow, you’ll likely need multiple libraries. It’s important to manage dependencies carefully to avoid version conflicts and ensure reproducibility.

Listing Installed Packages

pip list

Freezing Requirements

Save a list of installed packages for your project:

pip freeze > requirements.txt

Install all dependencies in another environment:

pip install -r requirements.txt

9.6 Virtual Environments

Virtual environments isolate your project’s dependencies from your system Python and other projects.

Creating a Virtual Environment

python -m venv venv

Activating the Virtual Environment

Deactivating

deactivate


9.8 Using External Libraries: Example

Install and use numpy:

pip install numpy
import numpy as np

a = np.array([1, 2, 3])
print(a * 2)  # [2 4 6]

9.9 Troubleshooting and Best Practices


9.10 Summary

In the next chapter, you’ll apply what you’ve learned by building small projects and get tips for further learning.



Chapter 10: Practical Projects and Next Steps

10.1 Introduction

Now that you’ve refreshed your Python skills, it’s time to put your knowledge into practice. In this chapter, you’ll find ideas for small projects, learn basic testing and debugging techniques, and get resources for further learning.


10.2 Small Project Ideas

Try building simple projects to reinforce what you’ve learned:

1. Calculator

2. To-Do List

3. Number Guessing Game

4. Simple Web Scraper

5. Data Analysis with Pandas


10.3 Basic Testing and Debugging

Testing Functions

Use Python’s built-in unittest or pytest frameworks to test your code.

def add(a, b):
    return a + b

def test_add():
    assert add(2, 3) == 5
    assert add(-1, 1) == 0

test_add()
print("All tests passed!")

Debugging Techniques

import pdb; pdb.set_trace()

10.4 Version Control with Git


10.5 Next Steps in Python

Explore More Advanced Topics

Learn from the Community


10.6 Summary

Congratulations on completing your Python refresher! Keep coding and exploring.