Are you ready to begin your programming journey? Python has emerged as the perfect starting point for aspiring developers, and there’s a good reason why. In fact, according to Stack Overflow’s 2023 Developer Survey, Python remains one of the most loved and widely used programming languages worldwide. Whether you’re dreaming of creating websites, analyzing data, or building the next revolutionary app, mastering Python basics is your first step toward achieving these goals.
In this comprehensive guide, we’ll explore:
- Essential Python concepts for beginners
- Step-by-step tutorials with practical examples
- Best practices for writing clean, efficient code
- Common challenges and their solutions
- Real-world applications and projects
By the end of this tutorial, you’ll be able to:
- Write basic Python programs confidently
- Understand fundamental programming concepts
- Work with Python’s core data structures
- Handle errors and debug your code
- Create simple yet practical applications
Before we begin, make sure you have Python installed on your computer. We recommend using Visual Studio Code as your code editor for this tutorial.
This guide is designed for complete beginners, requiring no prior programming experience. We’ll start from the absolute basics and progressively build your knowledge with clear explanations and hands-on examples. Whether you’re learning to advance your career, work on personal projects, or simply explore programming, this tutorial will provide the solid foundation you need.
Let’s begin your Python programming journey!
Introduction to Python Programming
Python is a powerful and beginner-friendly programming language. Imagine having a tool that can help you create websites, analyze data, develop games, and even build artificial intelligence applications – that’s Python! Created by Guido van Rossum in 1991, Python has grown to become one of the world’s most popular programming languages because of its simple, readable syntax that feels almost like writing English.
Major companies like Google, Instagram, and Netflix use Python extensively in their operations. Why? Because Python makes complex tasks simpler. Whether you’re a complete beginner or someone switching from another programming language, Python offers a gentle learning curve while providing powerful capabilities.
Let’s look at what makes Python special:
- Easy to Read and Write: Python uses simple, English-like commands
- Versatile: Can be used for web development, data science, AI, and more
- Large Community: Extensive resources and help available online
- Free and Open Source: No cost to start learning and using
Think of Python as your Swiss Army knife in the digital world – it’s versatile, reliable, and gets the job done efficiently. Ready to start your Python journey? Let’s dive into the basics and write your first program.
Here’s a simple example of Python code:
# This is a simple Python program
print("Welcome to Python Programming!")
name = input("What's your name? ")
print(f"Hello, {name}! Let's start coding together!")
Python Fundamental Concepts: Variables and Data Types
Understanding variables and data types is like learning the alphabet before writing sentences. In Python, variables are containers that store data, and they’re essential building blocks for any program you’ll create. Unlike some other programming languages, Python makes working with variables incredibly straightforward – you don’t need to declare what type of data they’ll hold in advance.
Think of variables like labeled boxes where you can store different types of information. Just as you wouldn’t store water in a cardboard box, each type of data in Python has its appropriate “container” type. Let’s explore these fundamental building blocks that make Python so powerful and flexible.
Basic Data Types in Python
1. Strings (str)
Strings are like the words and sentences in Python. They’re pieces of text enclosed in quotes. You can use either single quotes (”) or double quotes (“”) – Python doesn’t mind which you choose.
# Different ways to create strings
name = "Alice"
message = 'Hello, Python!'
long_text = """This is a
multiple line
string"""
# String operations
print(name.upper()) # ALICE
print(message.lower()) # hello, python!
print(len(name)) # 5 (length of string)
print(name + " codes") # Alice codes (concatenation)
2. Numbers (int and float)
Python handles numbers in two main ways: integers (whole numbers) and floating-point numbers (decimals). The beauty of Python is that it manages most mathematical operations just as you’d expect.
# Working with numbers
age = 25 # Integer
height = 1.75 # Float
weight = 68.5 # Float
# Basic math operations
total = age + 5 # Addition
product = age * 2 # Multiplication
power = age ** 2 # Exponentiation (25 squared)
division = weight / 2 # Division (returns float)
# Converting between types
age_text = str(age) # Convert to string: "25"
height_rounded = int(height) # Convert to integer: 1
3. Booleans (bool)
Boolean values are the simplest data type in Python – they can only be True or False. Despite their simplicity, they’re crucial for controlling program flow and making decisions.
# Boolean examples
is_student = True
has_license = False
# Boolean operations
can_drive = is_student and has_license # False
can_learn = is_student or has_license # True
adult = age >= 18 # True (assuming age = 25)
Working with Variables
The real power of variables comes when you start combining them. Python makes this incredibly intuitive:
# Creating a user profile
name = "John Smith"
age = 30
height = 1.85
is_employed = True
# Using f-strings for formatted output
profile = f"""
User Profile:
Name: {name}
Age: {age}
Height: {height}m
Employed: {is_employed}
"""
print(profile)
# Basic calculations with variables
years_to_retirement = 65 - age
daily_coffee_cost = 3.50
weekly_coffee_expense = daily_coffee_cost * 7
print(f"Years until retirement: {years_to_retirement}")
print(f"Weekly coffee expense: ${weekly_coffee_expense}")
Important Tips to Remember
1. Variable Naming Rules:
- Can contain letters, numbers, and underscores
- Must start with a letter or underscore
- Case-sensitive (name and Name are different variables)
- Cannot use Python keywords (like ‘print’ or ‘if’)
2. Type Conversion:
- str() converts to string
- int() converts to integer
- float() converts to floating-point number
- bool() converts to boolean
3. Best Practices:
- Use descriptive variable names
- Follow the snake_case naming convention
- Keep names simple but meaningful
- Comment your code for clarity
Understanding these fundamentals is crucial because they form the foundation for everything else you’ll do in Python. Whether you’re building web applications, analyzing data, or creating games, you’ll always be working with these basic data types and variables.
If you get stuck at any point, you can visit official Python documentation.
Control Flow and Functions in Python
Let’s understand how to control program flow and create reusable functions in Python. This is where your code starts to make decisions and repeat tasks efficiently.
Conditional Statements (if, elif, else)
Python uses conditional statements to make decisions in code. Think of them as the decision-making part of your program:
# Basic if-else structure
age = 18
if age < 13:
print("You're a child")
elif age < 20: print("You're a teenager") else: print("You're an adult") # Multiple conditions score = 85 is_passing = True if score >= 90 and is_passing:
print("Excellent!")
elif score >= 70 or is_passing:
print("Good job!")
else:
print("Need improvement")
Loops (for and while)
Loops help you repeat tasks without writing the same code multiple times:
# For loop examples
fruits = ["apple", "banana", "orange"]
for fruit in fruits:
print(f"I like {fruit}")
# Range in for loops
for number in range(5):
print(f"Count: {number}")
# While loop
counter = 0
while counter < 5:
print(f"Counter is: {counter}")
counter += 1
Functions
Functions are reusable blocks of code. They help organize and simplify your programs:
# Basic function
def greet(name):
return f"Hello, {name}!"
# Function with multiple parameters
def calculate_total(price, tax_rate=0.1):
tax = price * tax_rate
total = price + tax
return total
# Using the functions
message = greet("Alice")
print(message) # Output: Hello, Alice!
bill = calculate_total(100)
print(f"Total bill: ${bill}") # Output: Total bill: $110.0
Practical Example: Combining Everything
Let’s create a simple temperature converter:
def convert_temperature(degrees, to_celsius=True):
if to_celsius:
result = (degrees - 32) * 5/9
unit = "Celsius"
else:
result = (degrees * 9/5) + 32
unit = "Fahrenheit"
return round(result, 2), unit
# Using the converter
temperatures = [32, 68, 100]
for temp in temperatures:
converted_temp, unit = convert_temperature(temp)
print(f"{temp}°F is {converted_temp}°{unit}")
Remember:
- Indentation is crucial in Python
- Functions should do one thing well
- Keep your code clean and readable
- Test your functions with different inputs
Working with Python Data Structures
Now let’s explore how Python handles collections of data. Data structures are essential for organizing and managing multiple pieces of information efficiently.
Lists
Lists are the most versatile data structure in Python. Think of them as ordered collections that can hold any type of data:
# Creating and using lists
fruits = ["apple", "banana", "orange", "grape"]
# Accessing elements
print(fruits[0]) # First item: apple
print(fruits[-1]) # Last item: grape
# Modifying lists
fruits.append("mango") # Add item
fruits.remove("banana") # Remove item
fruits.sort() # Sort list
# List operations
print(len(fruits)) # Number of items
print("apple" in fruits) # Check if item exists
Dictionaries
Dictionaries store key-value pairs, perfect for structured data:
# Creating a dictionary
user = {
"name": "John Doe",
"age": 30,
"email": "[email protected]",
"active": True
}
# Accessing values
print(user["name"]) # John Doe
print(user.get("age")) # 30
# Modifying dictionary
user["phone"] = "123-456-7890" # Add new key-value
user["age"] = 31 # Update value
# Dictionary operations
print(user.keys()) # All keys
print(user.values()) # All values
Practical Example: Student Database
Let’s combine lists and dictionaries to create a simple student database:
# Student database system
students = [
{
"id": 1,
"name": "Alice Smith",
"grades": [85, 90, 88],
"active": True
},
{
"id": 2,
"name": "Bob Johnson",
"grades": [92, 87, 95],
"active": True
}
]
# Function to calculate average grade
def get_average_grade(student):
grades = student["grades"]
return sum(grades) / len(grades)
# Process student data
for student in students:
average = get_average_grade(student)
print(f"Student: {student['name']}")
print(f"Average Grade: {average:.2f}")
print("-" * 20)
Important Tips:
List Operations:
- Lists are ordered and changeable
- Can contain duplicates
- Can mix different data types
- Index starts at 0
Dictionary Features:
- Keys must be unique
- Values can be any data type
- Unordered (in older Python versions)
- Fast lookup by key
Best Practices:
- Choose appropriate data structure
- Keep data organized
- Use meaningful names
- Document complex structures
Practical Python Applications
Now let’s put everything together and create some real-world applications. This section will show you how Python can solve actual problems.
Simple Task Manager Application
class TaskManager:
def __init__(self):
self.tasks = []
def add_task(self, task):
self.tasks.append({"task": task, "completed": False})
print(f"Task added: {task}")
def view_tasks(self):
if not self.tasks:
print("No tasks available!")
return
print("\nYour Tasks:")
for index, task in enumerate(self.tasks, 1):
status = "✓" if task["completed"] else " "
print(f"{index}. [{status}] {task['task']}")
def complete_task(self, task_number):
if 1 <= task_number <= len(self.tasks):
self.tasks[task_number-1]["completed"] = True
print("Task marked as completed!")
else:
print("Invalid task number!")
# Using the Task Manager
todo = TaskManager()
# Adding tasks
todo.add_task("Learn Python basics")
todo.add_task("Create first program")
todo.add_task("Practice coding")
# View all tasks
todo.view_tasks()
# Complete a task
todo.complete_task(1)
# View updated tasks
todo.view_tasks()
Temperature Converter Program
def temperature_converter():
print("Temperature Converter")
print("1. Celsius to Fahrenheit")
print("2. Fahrenheit to Celsius")
choice = input("Select conversion (1/2): ")
temp = float(input("Enter temperature: "))
if choice == '1':
result = (temp * 9/5) + 32
print(f"{temp}°C = {result}°F")
elif choice == '2':
result = (temp - 32) * 5/9
print(f"{temp}°F = {result}°C")
else:
print("Invalid choice!")
# Run the converter
temperature_converter()
Simple Grade Calculator
def calculate_grade(scores):
average = sum(scores) / len(scores)
if average >= 90:
return 'A'
elif average >= 80:
return 'B'
elif average >= 70:
return 'C'
elif average >= 60:
return 'D'
else:
return 'F'
def grade_calculator():
print("Grade Calculator")
scores = []
while True:
score = input("Enter score (or 'done' to finish): ")
if score.lower() == 'done':
break
try:
score = float(score)
if 0 <= score <= 100:
scores.append(score)
else:
print("Score must be between 0 and 100")
except ValueError:
print("Please enter a valid number")
if scores:
average = sum(scores) / len(scores)
grade = calculate_grade(scores)
print(f"\nResults:")
print(f"Scores: {scores}")
print(f"Average: {average:.2f}")
print(f"Grade: {grade}")
else:
print("No scores entered!")
# Run the calculator
grade_calculator()
Key Points to Remember:
1. Program Structure
- Keep functions focused and simple
- Use clear variable names
- Add error handling
- Include user feedback
2. User Interaction
- Clear instructions
- Input validation
- Helpful error messages
- Readable output
3. Best Practices
- Comment your code
- Test different scenarios
- Make code reusable
- Keep it simple
Working with Files and Error Handling in Python
This section will show you how to work with files and handle errors effectively – essential skills for real-world programming.
File Operations
# Reading from a file
def read_file():
try:
with open('example.txt', 'r') as file:
content = file.read()
print("File contents:")
print(content)
except FileNotFoundError:
print("File not found!")
# Writing to a file
def write_file(text):
with open('example.txt', 'w') as file:
file.write(text)
print("Successfully written to file!")
# Appending to a file
def append_to_file(text):
with open('example.txt', 'a') as file:
file.write('\n' + text)
print("Successfully appended to file!")
# Example usage
write_file("Hello, this is first line")
append_to_file("This is second line")
read_file()
Error Handling
# Basic error handling
def divide_numbers():
try:
num1 = float(input("Enter first number: "))
num2 = float(input("Enter second number: "))
result = num1 / num2
print(f"Result: {result}")
except ValueError:
print("Please enter valid numbers!")
except ZeroDivisionError:
print("Cannot divide by zero!")
except Exception as e:
print(f"An error occurred: {e}")
finally:
print("Calculation completed")
# Advanced error handling
class AgeError(Exception):
pass
def verify_age(age):
try:
age = int(age)
if age < 0: raise AgeError("Age cannot be negative") if age > 150:
raise AgeError("Invalid age")
return True
except ValueError:
print("Please enter a valid number")
return False
except AgeError as e:
print(f"Invalid age: {e}")
return False
Practical Example: Simple Note Taking App
class NoteApp:
def __init__(self, filename):
self.filename = filename
def add_note(self, note):
try:
with open(self.filename, 'a') as file:
file.write(f"{note}\n")
print("Note added successfully!")
except Exception as e:
print(f"Error adding note: {e}")
def read_notes(self):
try:
with open(self.filename, 'r') as file:
notes = file.readlines()
if notes:
print("\nYour Notes:")
for i, note in enumerate(notes, 1):
print(f"{i}. {note.strip()}")
else:
print("No notes found!")
except FileNotFoundError:
print("No notes file exists yet!")
except Exception as e:
print(f"Error reading notes: {e}")
def clear_notes(self):
try:
with open(self.filename, 'w') as file:
file.write("")
print("All notes cleared!")
except Exception as e:
print(f"Error clearing notes: {e}")
# Using the Note App
notes = NoteApp("my_notes.txt")
# Add some notes
notes.add_note("Learn Python file handling")
notes.add_note("Practice error handling")
# Read all notes
notes.read_notes()
Key Concepts to Remember:
1. File Operations
- Always close files (use ‘with’ statement)
- Choose correct file mode (r, w, a)
- Handle file-related errors
- Check if file exists before reading
2. Error Handling
- Use specific exceptions first
- Provide helpful error messages
- Include cleanup code in ‘finally’
- Create custom exceptions when needed
3. Best Practices
- Don’t catch exceptions you can’t handle
- Keep error messages user-friendly
- Log errors for debugging
- Clean up resources properly
Python Modules and Libraries
Understanding how to use Python modules and libraries will expand your programming capabilities. Let’s look at some commonly used modules and how to use them.
Built-in Modules
# Working with datetime
import datetime
# Get current date and time
current_time = datetime.datetime.now()
print(f"Current time: {current_time}")
# Format dates
formatted_date = current_time.strftime("%Y-%m-%d")
print(f"Formatted date: {formatted_date}")
# Math module
import math
# Math operations
print(f"Square root of 16: {math.sqrt(16)}")
print(f"Pi value: {math.pi}")
# Random module
import random
# Generate random numbers
random_number = random.randint(1, 10)
print(f"Random number between 1 and 10: {random_number}")
# Choose random item from list
fruits = ['apple', 'banana', 'orange']
random_fruit = random.choice(fruits)
print(f"Random fruit: {random_fruit}")
Third-Party Libraries
# Using requests for HTTP (install with: pip install requests)
import requests
def get_weather(city):
API_KEY = "your_api_key"
url = f"http://api.openweathermap.org/data/2.5/weather?q={city}&appid={API_KEY}"
try:
response = requests.get(url)
data = response.json()
if response.status_code == 200:
temp = data['main']['temp'] - 273.15 # Convert to Celsius
return f"Temperature in {city}: {temp:.2f}°C"
else:
return "City not found!"
except Exception as e:
return f"Error: {e}"
# Using pandas for data analysis (install with: pip install pandas)
import pandas as pd
# Create a simple DataFrame
data = {
'Name': ['John', 'Alice', 'Bob'],
'Age': [25, 30, 35],
'City': ['New York', 'London', 'Paris']
}
df = pd.DataFrame(data)
print("\nDataFrame:")
print(df)
Creating Your Own Module
# File: myutils.py
def celsius_to_fahrenheit(celsius):
return (celsius * 9/5) + 32
def fahrenheit_to_celsius(fahrenheit):
return (fahrenheit - 32) * 5/9
def greet(name):
return f"Hello, {name}!"
# File: main.py
import myutils
# Using our custom module
temp_c = 25
temp_f = myutils.celsius_to_fahrenheit(temp_c)
print(f"{temp_c}°C is {temp_f}°F")
greeting = myutils.greet("Python Learner")
print(greeting)
Key Points to Remember:
1. Module Installation
- Use pip to install packages (pip install package_name)
- Create virtual environments for projects
- Keep requirements.txt updated
- Check module compatibility
2. Module Usage
- Import only what you need
- Use aliases for long module names
- Handle import errors gracefully
- Follow module documentation
3. Best Practices
- Keep modules organized
- Document your custom modules
- Use proper version management
- Test module functionality
Advanced Python Concepts
Let’s dive into some advanced Python features that will make your code more powerful and efficient.
List Comprehensions and Generators
# List Comprehensions
numbers = [1, 2, 3, 4, 5]
# Traditional way
squares_traditional = []
for n in numbers:
squares_traditional.append(n ** 2)
# List comprehension way
squares = [n ** 2 for n in numbers]
print(f"Squares: {squares}")
# With condition
even_squares = [n ** 2 for n in numbers if n % 2 == 0]
print(f"Even squares: {even_squares}")
# Generator Function
def number_generator(n):
for i in range(n):
yield i
# Using generator
gen = number_generator(5)
for num in gen:
print(num)
Lambda Functions and Map/Filter
# Lambda Functions
multiply = lambda x, y: x * y
print(f"3 x 4 = {multiply(3, 4)}")
# Map function
numbers = [1, 2, 3, 4, 5]
doubled = list(map(lambda x: x * 2, numbers))
print(f"Doubled: {doubled}")
# Filter function
evens = list(filter(lambda x: x % 2 == 0, numbers))
print(f"Even numbers: {evens}")
# Combining map and filter
result = list(map(lambda x: x ** 2,
filter(lambda x: x % 2 == 0, numbers)))
print(f"Squares of even numbers: {result}")
Decorators and Context Managers
# Decorator Example
def timer_decorator(func):
import time
def wrapper(*args, **kwargs):
start = time.time()
result = func(*args, **kwargs)
end = time.time()
print(f"Function {func.__name__} took {end-start:.2f} seconds")
return result
return wrapper
@timer_decorator
def slow_function():
import time
time.sleep(1)
print("Function complete")
# Context Manager
class FileManager:
def __init__(self, filename):
self.filename = filename
def __enter__(self):
self.file = open(self.filename, 'w')
return self.file
def __exit__(self, exc_type, exc_value, exc_traceback):
if self.file:
self.file.close()
# Using context manager
with FileManager('test.txt') as file:
file.write('Hello, World!')
Object-Oriented Programming Advanced
class Animal:
def __init__(self, name):
self._name = name
@property
def name(self):
return self._name
@name.setter
def name(self, value):
if not isinstance(value, str):
raise ValueError("Name must be a string")
self._name = value
def speak(self):
pass
class Dog(Animal):
def speak(self):
return f"{self.name} says Woof!"
class Cat(Animal):
def speak(self):
return f"{self.name} says Meow!"
# Using the classes
dog = Dog("Rex")
cat = Cat("Whiskers")
print(dog.speak())
print(cat.speak())
Key Concepts:
1. List Comprehensions
- More readable than traditional loops
- Better performance
- Can include conditions
- Creates new lists efficiently
2. Lambda Functions
- One-line anonymous functions
- Useful with map/filter/reduce
- Simple operations
- Temporary function definitions
3. Decorators
- Modify function behavior
- Code reusability
- Common for logging, timing, authentication
- Can be stacked
4. OOP Advanced Features
- Properties and setters
- Method overriding
- Inheritance
- Encapsulation
Working with APIs in Python
Let’s learn how to interact with APIs using Python. APIs (Application Programming Interfaces) allow your programs to communicate with other services.
Making Basic API Requests
import requests
# Making a simple GET request
def get_user_data(user_id):
url = f"https://jsonplaceholder.typicode.com/users/{user_id}"
response = requests.get(url)
if response.status_code == 200:
return response.json()
else:
return f"Error: {response.status_code}"
# Making a POST request
def create_post(title, body, user_id):
url = "https://jsonplaceholder.typicode.com/posts"
data = {
"title": title,
"body": body,
"userId": user_id
}
response = requests.post(url, json=data)
return response.json()
# Using the functions
user = get_user_data(1)
print("User Data:", user)
new_post = create_post(
"Learning APIs",
"Working with Python requests",
1
)
print("New Post:", new_post)
Working with API Authentication
class APIClient:
def __init__(self, api_key):
self.api_key = api_key
self.base_url = "https://api.example.com"
def get_headers(self):
return {
"Authorization": f"Bearer {self.api_key}",
"Content-Type": "application/json"
}
def get_data(self, endpoint):
url = f"{self.base_url}{endpoint}"
try:
response = requests.get(
url,
headers=self.get_headers()
)
response.raise_for_status()
return response.json()
except requests.exceptions.RequestException as e:
return f"Error: {e}"
# Using the API Client
api = APIClient("your_api_key_here")
data = api.get_data("/users")
Practical Example: Weather App
class WeatherApp:
def __init__(self, api_key):
self.api_key = api_key
self.base_url = "http://api.openweathermap.org/data/2.5"
def get_weather(self, city):
endpoint = f"/weather?q={city}&appid={self.api_key}&units=metric"
url = f"{self.base_url}{endpoint}"
try:
response = requests.get(url)
data = response.json()
if response.status_code == 200:
return {
"city": data["name"],
"temperature": data["main"]["temp"],
"description": data["weather"][0]["description"],
"humidity": data["main"]["humidity"]
}
else:
return f"Error: {data['message']}"
except Exception as e:
return f"Error: {e}"
# Using the Weather App
weather = WeatherApp("your_api_key_here")
result = weather.get_weather("London")
print(result)
Key Points to Remember:
1. API Basics
- Use requests library for HTTP calls
- Handle different HTTP methods (GET, POST, etc.)
- Check response status codes
- Parse JSON responses
2. Best Practices
- Always handle errors
- Use API keys securely
- Follow API rate limits
- Cache responses when appropriate
3. Security Tips
- Never expose API keys in code
- Use environment variables
- Implement proper error handling
- Validate API responses
4. Common API Operations
- Authentication
- Data retrieval
- Creating resources
- Updating data
- Error handling
Database Operations in Python
Let’s learn how to work with databases in Python. We’ll focus on SQLite since it’s built into Python and perfect for learning.
Basic Database Operations (CRUD)
import sqlite3
class DatabaseManager:
def __init__(self, database_name):
self.database_name = database_name
def create_table(self):
try:
with sqlite3.connect(self.database_name) as conn:
cursor = conn.cursor()
cursor.execute('''
CREATE TABLE IF NOT EXISTS users (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT NOT NULL,
email TEXT UNIQUE,
age INTEGER
)
''')
print("Table created successfully!")
except sqlite3.Error as e:
print(f"Error: {e}")
def insert_user(self, name, email, age):
try:
with sqlite3.connect(self.database_name) as conn:
cursor = conn.cursor()
cursor.execute('''
INSERT INTO users (name, email, age)
VALUES (?, ?, ?)
''', (name, email, age))
conn.commit()
return True
except sqlite3.Error as e:
print(f"Error: {e}")
return False
def get_all_users(self):
try:
with sqlite3.connect(self.database_name) as conn:
cursor = conn.cursor()
cursor.execute('SELECT * FROM users')
return cursor.fetchall()
except sqlite3.Error as e:
print(f"Error: {e}")
return []
# Using the Database Manager
db = DatabaseManager('my_database.db')
db.create_table()
db.insert_user('John Doe', '[email protected]', 25)
users = db.get_all_users()
print("Users:", users)
Advanced Queries and Relationships
class AdvancedDatabaseManager:
def __init__(self, database_name):
self.database_name = database_name
def setup_database(self):
with sqlite3.connect(self.database_name) as conn:
cursor = conn.cursor()
# Create Users table
cursor.execute('''
CREATE TABLE IF NOT EXISTS users (
id INTEGER PRIMARY KEY,
username TEXT UNIQUE
)
''')
# Create Posts table with foreign key
cursor.execute('''
CREATE TABLE IF NOT EXISTS posts (
id INTEGER PRIMARY KEY,
user_id INTEGER,
title TEXT,
content TEXT,
FOREIGN KEY (user_id) REFERENCES users (id)
)
''')
def search_posts(self, keyword):
with sqlite3.connect(self.database_name) as conn:
cursor = conn.cursor()
cursor.execute('''
SELECT users.username, posts.title, posts.content
FROM posts
JOIN users ON users.id = posts.user_id
WHERE posts.title LIKE ? OR posts.content LIKE ?
''', (f'%{keyword}%', f'%{keyword}%'))
return cursor.fetchall()
Practical Example: Simple Blog Database
class BlogDatabase:
def __init__(self):
self.conn = sqlite3.connect('blog.db')
self.setup()
def setup(self):
cursor = self.conn.cursor()
# Create tables
cursor.execute('''
CREATE TABLE IF NOT EXISTS posts (
id INTEGER PRIMARY KEY AUTOINCREMENT,
title TEXT NOT NULL,
content TEXT NOT NULL,
created_date TIMESTAMP DEFAULT CURRENT_TIMESTAMP
)
''')
cursor.execute('''
CREATE TABLE IF NOT EXISTS comments (
id INTEGER PRIMARY KEY AUTOINCREMENT,
post_id INTEGER,
comment TEXT NOT NULL,
created_date TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
FOREIGN KEY (post_id) REFERENCES posts (id)
)
''')
self.conn.commit()
def add_post(self, title, content):
cursor = self.conn.cursor()
cursor.execute('''
INSERT INTO posts (title, content)
VALUES (?, ?)
''', (title, content))
self.conn.commit()
return cursor.lastrowid
def add_comment(self, post_id, comment):
cursor = self.conn.cursor()
cursor.execute('''
INSERT INTO comments (post_id, comment)
VALUES (?, ?)
''', (post_id, comment))
self.conn.commit()
def get_post_with_comments(self, post_id):
cursor = self.conn.cursor()
cursor.execute('''
SELECT posts.*, GROUP_CONCAT(comments.comment)
FROM posts
LEFT JOIN comments ON comments.post_id = posts.id
WHERE posts.id = ?
GROUP BY posts.id
''', (post_id,))
return cursor.fetchone()
# Using the Blog Database
blog_db = BlogDatabase()
# Add a new post
post_id = blog_db.add_post(
"First Post",
"This is my first blog post!"
)
# Add comments
blog_db.add_comment(post_id, "Great post!")
blog_db.add_comment(post_id, "Looking forward to more!")
# Get post with comments
post = blog_db.get_post_with_comments(post_id)
print("Post data:", post)
Key Concepts to Remember:
1. Database Basics
- Connection management
- CRUD operations
- SQL queries
- Error handling
2. Best Practices
- Use context managers (with statements)
- Parameterized queries for security
- Proper connection closing
- Transaction management
3. Advanced Features
- Foreign keys
- Joins
- Indexes
- Complex queries