Todd K. Python & SQL. The Essential Guide For Programmers & Analysts 2024
Todd K. Python & SQL. The Essential Guide For Programmers & Analysts 2024
Table of Contents:
Part 1: Introduction
..................................................................12
Chapter
1:.............................................................................13
Welcome to the World of Data!...........................................13
1.1 The Power of Python .................................................13
1.2 The Magic of SQL .....................................................18
1.3 The Dream Team: Why Learn Python & SQL Together?
.........................................................................................21
Choosing a DBMS...........................................................31
Installing the DBMS ........................................................32
Connecting to the DBMS from Python ...........................32
Part 2: Python Programming Fundamentals
............................36
Chapter
3:.............................................................................37
Building Blocks of Python...................................................37
3.1 Variables and Data Types ..........................................37
Understanding Variables .................................................37
Data Types .......................................................................37
Code Examples ................................................................39
3.2 Operators....................................................................41
Arithmetic Operators .......................................................41
Comparison Operators .....................................................43
Logical Operators ............................................................45
3.3 Taking Input and Displaying Output .........................46
Taking Input.....................................................................46
Displaying Output............................................................47
Code Examples ................................................................47
Chapter
4:.............................................................................51
Control Flow Statements
.....................................................51
4.1 Conditional Statements: if, elif, else..........................51
Theif Statement ............................................................51
Theelse Statement........................................................52
Theelif Statement........................................................52
Code Examples ................................................................53
4.2 Loops: for and while..................................................55
Thefor Loop .................................................................55
Thewhile Loop.............................................................57
Example 3: Using a loop for calculations........................59
4.3 Nested Statements......................................................61
Nesting if Statements.....................................................61
Functions and Modules - Building Blocks of Reusable Code66
Part 3: SQL
Fundamentals.....................................................109
Chapter
8:...........................................................................110
Understanding Relational Databases
.................................110
8.1 Database Concepts: Tables, Columns, and Rows....110
Tables: The Bookshelves ...............................................110
Columns: The Book Sections ........................................111
Rows: The Books Themselves.......................................111
8.2 Data Types in SQL: Choosing the Right Kind of Data114
Understanding Data Types ............................................114
Choosing the Right Data Type ......................................115
Code Examples ..............................................................115
11.1 INNER JOIN, LEFT JOIN, RIGHT JOIN, FULL JOIN Concepts
........................................................................139
Part 1: Introduction
Chapter 1:
Welcome to the World of Data!
Type this code into the interpreter window and press Enter.
You should see the message "Hello, World!" printed on the
screen. This is your first Python program! Congratulations!
Data Types:
Python supports various data types, which specify the kind
of information a variable can hold. In our example, "John" is
a string, which represents text data. Here are some other
common data types:
Understanding Databases
UPDATE Customers
SET email = '[email protected]'
WHERE customer_id = 1001;
These are just the tip of the iceberg. SQL offers a rich set of
commands and functions to manipulate and analyze data
effectively. In the upcoming chapters, we'll explore more
complex SQL concepts, including joining tables, filtering
data, and performing calculations.
Know that, practice is key to mastering SQL. As you learn
new commands, experiment with them and see how they
work. Soon, you'll be querying databases like a pro!
Python and SQL are like two puzzle pieces that fit together
perfectly when it comes to working with data. Let's explore
why:
Data Extraction and Analysis Powerhouse
● SQL's Role: You can use SQL to identify and filter out
incorrect or missing data directly within the database.
● Python's Role: Python provides flexible tools to handle
missing values, outliers, and inconsistencies. Libraries like
pandas offer functions to clean, transform, and standardize
data before analysis.
Career Opportunities
Mastering both Python and SQL opens doors to a wide range
of exciting career paths:
Chapter 2:
Setting Up Your Development
Environment
Popular Options
Factors to Consider
● Your experience level: Beginners might find simpler
editors like VS Code or Atom easier to start with. As you
gain experience, you might explore more feature-rich
options like PyCharm.
Know that, the best way to find the perfect tool is to try
them out. Most code editors and IDEs offer free trials or
community editions, so you can experiment before
committing to one.
Choosing a DBMS
The right DBMS depends on your project's size, complexity,
and specific requirements. Here are some popular choices:
Bash
pip install mysql-connector-python
pip install psycopg2
Python
# Creating a variable
age = 30
Here, we created a variable named age and assigned the
value30 to it.
Data Types
Numeric Types
● int: Represents whole numbers (e.g., -2, 0, 42) ● float:
Represents numbers with decimal points (e.g., 3.14, 0.5) ●
complex: Represents complex numbers (e.g., 2+3j)
Text Type
str: Represents sequences of characters (e.g., "Hello",
'world')
Boolean Type
bool: Represents logical values (True or False)
Sequence Types
● list: An ordered collection of items, mutable (can be
changed) ● tuple: An ordered collection of items, immutable
(cannot be changed)
Mapping Type
● dict: An unordered collection of key-value pairs
Code Examples
Example 1: Basic Data Types
Python
# Numeric types
age = 30 # integer
height = 1.75 # float
complex_number = 2 + 3j # complex
# Text type
name = "Alice" # string
# Boolean type
is_student = True # boolean
Example 2: Sequence Types
Python
# List fruits = ["apple", "banana", "orange"]
print(fruits[0]) # Accessing the first element
# Tuple
colors = ("red", "green", "blue")
print(colors[1]) # Accessing the second element
Example 3: Mapping Type (Dictionary)
Python
# Dictionary
person = {"name": "Bob", "age": 25, "city": "New York"}
print(person["name"]) # Accessing the value with key
"name"
Key Points:
● Variable names should be descriptive and meaningful. ●
Python is case-sensitive. ● You can use underscores _ to
separate words in variable
3.2 Operators
Arithmetic Operators
These are used for basic mathematical calculations:
Addition (+): Adds two values. Python
x=5
y=3
sum = x + y # sum will be 8
Subtraction (-): Subtracts the second value from the first.
Python
difference = x - y # difference will be 2
Multiplication (*): Multiplies two values.
Python
product = x * y # product will be 15
Division (/): Divides the first value by the second.
Python
division = x / y # division will be 1.66666666667
Floor division (//): Divides and rounds down to the nearest
integer.
Python
floor_division = x // y # floor_division will be 1
Modulus (%): Returns the remainder of the division.
Python
remainder = x % y # remainder will be 2
Exponentiation (): Raises the first value to the power of
the second.
Python
power = x ** y # power will be 125
Comparison Operators
These are used to compare values and return a Boolean
result (True or False):
Equal to (==): Checks if two values are equal.
Python
is_equal = x == y # is_equal will be False
Not equal to (!=): Checks if two values are not equal.
Python
is_not_equal = x != y # is_not_equal will be True
Greater than (>): Checks if the first value is greater than
the second.
Python
is_greater_than = x > y # is_greater_than will be True
Less than (<): Checks if the first value is less than the
second.
Python
is_less_than = x < y # is_less_than will be False
Greater than or equal to (>=): Checks if the first value is
greater than or equal to the second.
Python
is_greater_or_equal = x >= y # is_greater_or_equal will be True
Less than or equal to (<=): Checks if the first value is
less than or equal to the second.
Python
is_less_or_equal = x <= y # is_less_or_equal will be False
Logical Operators
These are used to combine Boolean expressions:
and: Returns True if both operands are True.
Python
condition1 = True
condition2 = False
result = condition1 and condition2 # result will be
False
or: Returns True if at least one operand is True.
Python
result = condition1 or condition2 # result will be True
not: Reverses the result of the operand.
Python
result = not condition1 # result will be False
Taking Input
Theinput() function is used to take input from the user. It
reads a line of text from the console and returns it as a
string.
name = input("What is your name? ")
print("Hello,", name, "!")
Displaying Output
Theprint() function is used to display values or messages on
the console. It can take multiple arguments separated by
commas.
Python
age = 30
print("My age is:", age)
This code will print the message "My age is: 30" on the
console.
Code Examples
Example 1: Simple Input and Output
name = input("Enter your name: ")
age = int(input("Enter your age: "))
print("Hello,", name, "! You are", age, "years old.")
Explanation:
1. The first input() function asks for the user's name and
stores it in thename variable.
2. The second input() function asks for the user's age, but
since the input is a string, we convert it to an integer using
int().
3. Theprint() function displays a personalized greeting with
the user's name and age.
1. The program asks the user for two numbers and converts
them to floating-point numbers using float().
2. The numbers are added and stored in thesum variable.
3. Theprint() function displays the calculated sum.
Chapter 4:
Control Flow Statements
Up until now, our Python code has executed line by line from
top to bottom. But what if we want our programs to make
decisions or repeat actions? That's where control flow
statements come in. These statements allow us to alter the
normal flow of program execution.
Theif Statement
The most basic conditional statement is the if statement. It
checks if a condition is true and executes a block of code if
it is.
Python
age = 18
if age >= 18:
print("You are an adult.")
Here, the code inside the if block will only run if the age is
greater than or equal to 18.
Theelse Statement
You can combine an if statement with an else statement to
provide an alternative action if the condition is false.
Python
age = 16
if age >= 18:
print("You are an adult.")
else:
print("You are a minor.")
Theelif Statement
Theelif (short for "else if") statement allows you to check
multiple conditions sequentially.
Python
age = 25
if age < 18:
print("You are a minor.")
elif age >= 18 and age < 65:
print("You are an adult.")
else:
print("You are a senior citizen.")
This code checks if the age is less than 18, then if it's
between 18 and 65, and finally, if it's greater than or equal
to 65.
Code Examples
Example 1: Checking if a number is even or odd
Python
number = 7
if number % 2 == 0:
print("The number is even.")
else:
print("The number is odd.")
Example 2: Grade calculator
Python
score = 85
if score >= 90:
grade = "A"
elif score >= 80:
grade = "B"
elif score >= 70:
grade = "C"
else:
grade = "F"
print("Your grade is:", grade)
Example 3: Leap year checker
Python
year = 2024
if (year % 4 == 0) and (year % 100 != 0) or (year % 400
== 0):
print(year, "is a leap year") else:
print(year, "is not a leap year")
Know that, indentation is crucial in Python. The code block
under each if, elif, or else statement must be indented.
loops.
while
Thefor Loop
fruit.
Key Point: The variable you define within the for loop (in
this case, fruit) only holds the value of the current item
during each iteration.
Thewhile Loop
Syntax:
Python
while condition:
# code to execute while condition is True
Example 2: Guessing game
Python
secret_number = 7
guess_count = 0
while guess_count < 3:
guess = int(input("Guess a number between 1 and 10:
"))
guess_count += 1
if guess == secret_number:
print("Congratulations! You guessed the number.")
break # Exit the loop if the guess is correct
else:
print("Try again!")
if guess_count == 3:
print("Sorry, you ran out of guesses. The number was",
secret_number)
Explanation:
Nesting if Statements
You can nest if statements to create multi-layered decision
making.
Example 1: Discount calculator
Python
price = 100
discount_rate = 0.1 # 10% discount
# Check for bulk discount
if quantity >= 3:
bulk_discount = 0.05 # 5% additional discount for
bulk purchases
total_discount = discount_rate + bulk_discount
discounted_price = price * (1 - total_discount)
print("You qualify for a bulk discount! Discounted
price:", discounted_price)
else:
# Apply regular discount
discounted_price = price * (1 - discount_rate)
print("Discounted price:", discounted_price)
Explanation:
Nesting while Loops You can also nest while loops for more
intricate control flow.
Example 3: Guessing game with hints
Python
secret_number = 25 guess_count = 0
hint_given = False
while guess_count < 5:
guess = int(input("Guess a number between 1 and 100:
"))
guess_count += 1
if guess == secret_number:
print("Congratulations! You guessed the number.")
break
# Provide a hint after two wrong guesses
if guess_count >= 3 and not hint_given:
hint_given = True
if secret_number > guess:
print("Hint: The number is higher.")
else:
print("Hint: The number is lower.")
if guess_count == 5:
print("Sorry, you ran out of guesses. The number was",
secret_number)
Explanation:
Chapter 5:
Functions and Modules - Building
Blocks of Reusable Code
Have you ever felt like you're writing the same lines of code
over and over in your Python programs? That's where
functions come in! They're like mini-programs within your
main program, designed to perform specific tasks and be
reused whenever you need them.
Creating Your First Function: Step-by-Step
Let's build a function that calculates the area of a rectangle.
Here's a step-by-step approach:
1. Define the Function:
Python
def calculate_area(length, width):
"""This function calculates the area of a
rectangle."""
# Code to calculate and return the area
● We use the def keyword to declare a function.
Python
def calculate_area(length, width):
"""This function calculates the area of a rectangle."""
area = length * width
# Code to return the area
Key Points:
● This line tells Python to import the math module and make
its contents available in your program.
2. Using Functions from the Module:
Python
import math
# Use the pi constant from the math module
print("Value of pi:", math.pi)
# Use the sqrt() function from the math module
number = 25
square_root = math.sqrt(number)
print("Square root of", number, ":", square_root)
● Now that the math module is imported, we can access its
elements using the dot notation (math.pi and
Chapter 6:
Data Handling in Python - Taming
the Information Beast
Creating Lists:
Lists are created using square brackets [] and can hold items
of various data types (numbers, strings, even other lists!).
Python
# Grocery list with different items
shopping_list = ["milk", "bread", 3.14, True] #
Numbers, booleans, all allowed!
# List of exam scores
exam_scores = [85, 92, 78, 95]
# Nested list (a list within a list)
weekly_menu = [
["pancakes", "bacon", "eggs"], # Monday's breakfast
["pasta", "tomato sauce", "salad"], # Tuesday's
dinner
]
Accessing Elements:
Items in a list are ordered and have a unique index, starting
from 0. You can access elements using their index within
square brackets.
Python
first_item = shopping_list[0] # Accesses "milk" (index
0)
last_score = exam_scores[1] # Accesses the last score
(index -1)
# Slicing (extracting a portion of the list)
weekend_breakfast = weekly_menu[0] # Gets the entire
list for Monday's breakfast
# Get items from index 1 (inclusive) to 3 (exclusive)
midweek_meals = exam_scores[1:3] # Gets scores for
Tuesday and Wednesday
Modifying Lists:
Since lists are mutable, you can change elements, add new
items, or remove existing ones using various techniques:
shopping_list[0] = "cheese" # Replaces "milk" with
"cheese"
shopping_list.append("bananas") # Adds "bananas" to the
end
shopping_list.remove("bread") # Removes the first
occurrence of "bread"
# Insert an item at a specific position
exam_scores.insert(2, 90) # Inserts 90 between scores
at index 1 and 2
Key Points:
Tuples are like fixed guest lists for a party. Once you create a
tuple, the order and content cannot be changed. They're
similar to lists but enclosed in parentheses ().
Creating Tuples:
Tuples can hold various data types just like lists.
Python
# Guest list for a dinner party
dinner_guests = ("Alice", "Bob", "Charlie")
coordinates = (3, 5) # Can hold multiple data types
Accessing Elements:
Tuples use the same indexing scheme as lists to access
elements.
first_guest = dinner_guests[0] # Accesses "Alice"
y_coordinate = coordinates[1] # Accesses the second
element (y-coordinate)
# Slicing works the same way as with lists
Key Points:
● Tuples are immutable (unchangeable). ● Use tuples when
you need a fixed collection of data that shouldn't be
modified.
Example: Combining Lists and Tuples
Python
# List of student information (tuples can be used for
data integrity)
student_data = [
("Alice", 22, ["Math", "Physics"]),
("Bob", 20, ["English", "History"]),
]
# Accessing Alice's courses
alice_
6.2 Dictionaries and Sets for Unordered Data: Beyond
the Ordered List
Lists and tuples are great for keeping things in order, but
what if you need to store data where the order doesn't
matter? That's where dictionaries and sets come in! They
offer powerful ways to handle unordered data in Python.
Creating Dictionaries:
Python
# Phonebook (key: name, value: phone number)
phonebook = {"Alice": "123-456-7890", "Bob": :
3210"}
# Inventory (key: product name, value: quantity)
inventory = {"apples": 5, "bananas": 3, "oranges": 2}
Explanation:
Accessing Values:
Just like finding a friend's address in your phonebook, you
can retrieve values in a dictionary using their keys within
square brackets.
Python
alice_number = phonebook["Alice"] # Accesses Alice's
phone number
apple_count = inventory["apples"] # Accesses the
quantity of apples
Adding and Modifying Items:
Adding new entries or updating existing information in a
dictionary is straightforward. You simply assign the value to
the desired key.
Python
phonebook["Charlie"] = "555-123-4567" # Add a new entry
for Charlie
inventory["apples"] += 2 # Increase apple count by 2
# Modify an existing value
inventory["bananas"] = 1 # Update banana quantity
Key Points:
Creating Sets:
Python
# Unique fruits in a basket
unique_fruits = {"apple", "banana", "orange"} #
Duplicates are automatically removed
# Set from a list (keeps only unique elements)
numbers_list = [3, 7, 11, 3, 5]
unique_numbers = set(numbers_list)
Explanation:
1. We define sets using curly braces {}.
2. Elements within a set are separated by commas.
3. Sets automatically remove duplicates, ensuring each
element appears only once.
Python
first_name = "Alice"
last_name = "Wonderland"
# Concatenation
full_name = first_name + " " + last_name # Output:
Alice Wonderland
# f-strings
greeting = f"Hello, {first_name}! Welcome to
{last_name}."
print(greeting)
Common String Methods
Python provides a variety of built-in string methods for
various manipulations:
Python
text = " Hello, world! "
# Removing whitespace cleaned_text = text.strip() # Output: "Hello, world!"
# Converting to uppercase
uppercase_text = text.upper() # Output: " HELLO, WORLD!
"
# Finding the index of a substring
index_of_comma = text.find(",") # Output: 5
# Replacing a substring
new_text = text.replace("world", "Python") # Output: "
Hello, Python! "
Splitting and Joining Strings
Python
text = "apple,banana,orange"
# Splitting a string into a list
fruits = text.split(",") # Output: ["apple", "banana",
"orange"] # Joining a list into a string
joined_fruits = "-".join(fruits) # Output: apple
banana-orange
Checking String Content
You can check for specific characters or substrings within a
string using various methods.
Python
text = "Python is fun!"
# Checking if a substring exists
contains_python = "Python" in text # Output: True
# Checking if the string starts or ends with a specific
substring
starts_with_hello = text.startswith("Hello") # Output:
False
ends_with_fun = text.endswith("fun!") # Output: True
Chapter 7:
Introduction to Object-Oriented
Programming (OOP) in Python
(Optional)
Python
class Dog:
def __init__(self, name, breed):
self.name = name
self.breed = breed
def bark(self):
print(f"{self.name} says woof!")
Explanation:
● We use the class keyword to define a new class named Dog.
1. We create two objects, buddy and max, using the Dog class.
2. Each object has its own set of attributes (name and
breed) based on the values provided during creation.
3. We can access the attributes of an object using dot
notation (e.g., buddy.name).
4. We can call methods on an object using dot notation as
well (e.g., buddy.bark()).
Key Points:
Additional Notes:
Chapter 9:
Creating and Managing Databases
with SQL
SQL
CREATE TABLE customers (
customer_id INT PRIMARY KEY, first_name VARCHAR(50),
last_name VARCHAR(50),
email VARCHAR(100)
);
Explanation:
Additional Tips:
Key Points:
Additional Tips:
● You can insert multiple rows at once using the INSERT INTO
... VALUES syntax multiple times.
● TheWHERE clause is essential for specifying which rows to
update or delete.
● Consider using transactions to group multiple changes
together and ensure data integrity. By mastering these
commands, you'll be able to efficiently manage and
maintain the data within your database.
Chapter 10:
The Power of SQL Queries:
Extracting Insights from Your Data
Basic Structure
The core structure of aSELECT statement is simple:
SQL SELECT column1, column2, ... FROM table_name;
Key Points:
● TheSELECT statement is the foundation for querying data.
In the next section, we'll explore how to filter the data you
retrieve using the WHERE clause.
10.2 Using WHERE Clause: Filtering Data
This query retrieves all orders from the orders table for
customer with customer_id 1001 between January 1, 2023, and
December 31, 2023.
Key Points:
Key Points:
system.
Chapter 11:
Joining Tables for Complex Queries
Imagine your database as a collection of puzzle pieces. To
get the complete picture, you need to connect those pieces.
That's where joins come in. They allow you to combine data
from multiple tables based on related information.
This query will return order IDs and customer names for
orders where the customer ID exists in both theorders and
customers tables.
1.
github.com MIT
github.com
A LEFT JOIN returns all rows from the left table, even if there
are no matches in the right table. It's like starting with all
the pieces from the left puzzle and filling in the gaps with
matching pieces from the right.
SQL
SELECT orders.order_id, customers.customer_name
FROM orders
LEFT JOIN customers ON orders.customer_id =
customers.customer_id;
SQL
SELECT orders.order_id, customers.customer_name
FROM orders
FULL OUTER JOIN customers ON orders.customer_id =
customers.customer_id;
This query will return all orders and customers, whether or
not there's a match between the two tables.
Key Points:
This query joins the orders and customers tables based on the
matching customer_id in both tables, retrieving order IDs and
corresponding customer names.
Key Points:
Chapter 12:
Advanced SQL Topics (Optional)
Let's dive deeper into the world of SQL and explore some
powerful techniques to extract valuable insights from your
data.
12.1 Subqueries for Complex Data Retrieval
Basic Structure:
SQL
SELECT column1, aggregate_function(column2)
FROM table_name
GROUP BY column1;
Example 1: Grouping by a Single Column
SQL
SELECT country, COUNT(*) AS customer_count FROM customers
GROUP BY country;
This query counts the number of customers in each country.
Example 2: Grouping by Multiple Columns
SQL
SELECT year(order_date) AS order_year, SUM(order_total)
AS total_sales
FROM orders
GROUP BY year(order_date);
This query calculates the total sales for each year in the
orders table.
Example 3: Using GROUP BY with HAVING
SQL
SELECT country, AVG(age) AS average_age
FROM customers
GROUP BY country
HAVING AVG(age) > 30;
This query calculates the average age of customers for each
country, but only displays countries where the average age
is greater than 30.
Key Points:
● TheGROUP BY clause comes after the WHERE clause (if
used).
Key Points
Chapter 14:
Working with Data in Python & SQL
Now that we've explored both Python and SQL, let's bridge
the gap and see how to effectively move data between
these two worlds.
14.1 Importing Data from Databases into Python for
Analysis
Key Points
Key Points:
● Choose the appropriate library based on your project's
requirements.
Chapter 15:
Data Cleaning and Manipulation in
Python
Chapter 16:
Data Analysis and Visualization with
Python
Chapter 17:
Case Studies: Putting It All Together
representatives.
Example 3: Inventory Management
Problem: Optimize inventory levels to avoid stockouts and
overstocking.
Solution:
1. SQL: Retrieve product information, sales data, and
inventory levels.
SELECT product_id, product_name,
quantity_in_stock, SUM(quantity_sold) AS
total_sold
FROM products
LEFT JOIN sales ON products.product_id =
sales.product_id
GROUP BY product_id, product_name;
2. Python:
Key Points:
Key Points:
Appendix
A: Python Reference Guide
This appendix provides a condensed overview of Python's
core syntax and features. For a comprehensive reference,
always consult the official Python documentation.
Basic Syntax
if condition:
# Code to execute if condition is true
x = 10
name = "Alice"
Data Types: Python supports various data types: ○
Numbers: integers (e.g., 42), floating-point numbers
pairs
Control Flow
Conditional statements: Python
if condition:
# Code to execute if condition is true
else:
# Code to execute if condition is false
Loops: Python
for item in iterable:
# Code to execute for each item
while condition:
# Code to execute while condition is true
Functions
Define functions using def. Python
def greet(name):
print("Hello,", name)
Modules and Packages
● Import modules using import or from ... import. ● Create
packages to organize code into directories.
Common Operators
Built-in Functions
Python offers a rich set of built-in functions:
● print():
Display output ● len(): Get the length of an object ●
type(): Get the data type of an object ● range(): Generate a
sequence of numbers ● list(), tuple(), dict(): Convert to lists,
tuples, or
dictionaries
Additional Notes
LEFT JOIN: Returns all rows from the left table, and the
matched rows from the right table. RIGHT JOIN: Returns all
rows from the right table, and the matched rows from the
left table. FULL OUTER JOIN: Returns all rows when there
is a match in either left or right table or both.
Additional Features
Glossary of Terms
Other Terms
predefined labels.