Learn Python With Examples
Learn Python With Examples
Ben Good
Copyright
Copyright © 2024 by Ben Good All rights reserved. No part of
this publication may be reproduced, distributed, or transmitted in
any form or by any means, including photocopying, recording, or
other electronic or mechanical methods, without the prior written
permission of the publisher, except in the case of brief quotations
embodied in critical reviews and certain other noncommercial uses
permitted by copyright law.
Table of Contents
Chapter 1: Getting Started with Python
Windows:
2. Run the installer. Ensure to check the box that says “Add Python
3.x to PATH” before clicking “Install Now”.
macOS:
Linux:
print("Hello, World!")
python hello.py
def greet(name):
if name:
print("Hello, " + name + "!")
else:
print("Hello, World!")
x = 10 # An integer assignment
y = 3.14 # A floating-point number
name = "Alice" # A string
# This is a comment
print("Hello, World!") # This prints a message
# Arithmetic Operators
print(5 + 3) # Addition
print(5 - 3) # Subtraction
print(5 * 3) # Multiplication
print(5 / 3) # Division
# Comparison Operators
print(5 > 3) # Greater than
print(5 < 3) # Less than
# Logical Operators
print(True and False) # Logical AND
print(True or False) # Logical OR
Example:
x = 10 # An integer assignment
y = 3.14 # A floating-point number
Example:
s = "Hello, World!"
# Accessing characters
print(s[0]) # Outputs 'H'
# Slicing strings
print(s[1:5]) # Outputs 'ello'
# String methods
print(s.lower()) # Outputs 'hello, world!'
print(s.upper()) # Outputs 'HELLO, WORLD!'
print(s.replace('World', 'Python')) # Outputs 'Hello, Python!'
first_name = "John"
last_name = "Doe"
full_name = first_name + " " + last_name # Concatenation
print(full_name) # Outputs 'John Doe'
# Formatted strings
age = 30
info = f"{full_name} is {age} years old."
print(info) # Outputs 'John Doe is 30 years old.'
Example:
# Access elements
print(my_list[3]) # Outputs 'Python'
# Add elements
my_list.append("new item")
print(my_list) # Outputs [1, 2, 3, 'Python', 3.14, 'new item']
# Slicing
print(my_list[1:4]) # Outputs [2, 3, 'Python']
# List comprehensions
squares = [x**2 for x in range(10)]
print(squares) # Outputs [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
Example:
Example:
my_set = {1, 2, 3, 4, 5, 5}
print(my_set) # Outputs {1, 2, 3, 4, 5} (duplicates are removed)
Example:
age = 20
age = 25
member = True
score = 85
For Loops :For loops are typically used for iterating over a
sequence (like a list, tuple, dictionary, or string).
Example:
Example:
Using loops with :An block after a loop executes after the loop
finishes normally (i.e., without hitting a statement).
numbers = [1, 2, 3, 4, 5]
for num in numbers:
print(num)
else:
print("No more numbers.")
Example:
Example:
Example:
Example:
def greet():
print("Hello, World!")
def greet(name):
print(f"Hello, {name}!")
# Positional arguments
describe_pet('hamster', 'Harry')
# Keyword arguments
describe_pet(pet_name='Willow', animal_type='cat')
Returning Values :
Functions can return values using the statement, which exits the
function and optionally passes back an expression to the caller.
def square(number):
return number ** 2
result = square(4)
print(result) # Outputs 16
# my_module.py
def make_pizza(topping):
print(f"Making a pizza with {topping}")
import my_module
my_module.make_pizza('pepperoni')
make_pizza('mushrooms')
Packages :
pizza/
__init__.py
dough.py
toppings.py
dough.make_dough()
add_topping('tomato')
Understanding how to define and use functions, as well as organize
larger code bases with modules and packages, is crucial for writing
clean, maintainable, and reusable Python code. This organization
helps in managing larger projects efficiently and keeps the code
logically separated based on functionality.
Chapter 5: Exception
Handling
5.1 Understanding Exceptions
Exceptions in Python are errors detected during execution that
disrupt the normal flow of a program. Python provides various built-
in exceptions such as , , , and many others. Understanding these
exceptions is crucial for debugging and for writing robust programs.
numbers = [1, 2, 3]
print(numbers[3]) # IndexError: list index out of range
This example tries to access an element that is not present in the list,
causing an .
Basic usage:
try:
# Code that might cause an exception
print(numbers[3])
except IndexError as e:
# Code that runs if an exception occurs
print("Error:", e)
This block will catch the and print an error message, preventing the
program from crashing.
try:
# Code that might throw different exceptions
x = int(input("Enter a number: "))
result = numbers[x]
except ValueError:
print("Please enter a valid integer.")
except IndexError:
print("That index is out of range.")
except Exception as e:
print("An unexpected error occurred:", e)
try:
check_value(200)
except ValueTooHighError as e:
print(e.message)
# Writing to a file
with open('example.txt', 'w') as file:
file.write("Hello, World!\n")
file.write("This is another line.")
import csv
import json
data = {
"name": "John Doe",
"age": 28,
"city": "New York"
}
Example:
class Dog:
def __init__(self, name, age):
self.name = name
self.age = age
def bark(self):
print(f"{self.name} says woof!")
my_dog = Dog("Rex", 2)
my_dog.bark() # Outputs: Rex says woof!
class Car:
def __init__(self, make, model, year):
self.make = make
self.model = model
self.year = year
self.odometer_reading = 0
def get_descriptive_name(self):
long_name = f"{self.year} {self.make} {self.model}"
return long_name
def read_odometer(self):
print(f"This car has {self.odometer_reading} miles on
it.")
class Book:
def __init__(self, author, title, pages):
self.author = author
self.title = title
self.pages = pages
def __str__(self):
return f"{self.title} by {self.author}"
def __len__(self):
return self.pages
def describe_battery(self):
print(f"This car has a {self.battery_size}-kWh battery.")
numbers = [1, 2, 3, 4]
iter_obj = iter(numbers)
print(next(iter_obj)) # Outputs 1
print(next(iter_obj)) # Outputs 2
Example of a generator:
def countdown(num):
print("Starting countdown")
while num > 0:
yield num
num -= 1
for number in countdown(5):
print(number)
Example of a decorator:
def debug(func):
def wrapper(*args, **kwargs):
result = func(*args, **kwargs)
print(f"Function: {func.__name__}, Arguments: {args}
{kwargs}, Result: {result}")
return result
return wrapper
@debug
def add(x, y):
return x + y
print(add(5, 3))
The decorator enhances any function with debug output about its
arguments and the result.
Context Managers: Context managers allow you to allocate and
release resources precisely when you want. The most common way to
create a context manager is by using the statement.
@contextmanager
def managed_file(name):
try:
file = open(name, 'w')
yield file
finally:
file.close()
with managed_file('hello.txt') as f:
f.write('hello, world!')
multiply = lambda x, y: x * y
print(multiply(2, 3)) # Outputs 6
Functional programming concepts in Python also include functions
like , , and for processing sequences.
Using and :
numbers = [1, 2, 3, 4, 5]
import pandas as pd
data = {
'Country': ['USA', 'Canada', 'Germany', 'UK', 'France'],
'Capital': ['Washington, D.C.', 'Ottawa', 'Berlin', 'London',
'Paris'],
'Population': [328, 37, 83, 66, 67]
}
df = pd.DataFrame(data)
print(df)
# Selecting a column
print(df['Capital'])
Filtering Data:
Installation of Matplotlib:
# Data
x = [1, 2, 3, 4, 5]
y = [2, 3, 5, 7, 11]
# Plot
plt.plot(x, y)
plt.title('Simple Line Plot')
plt.xlabel('X Axis Label')
plt.ylabel('Y Axis Label')
plt.show()
10.2 Plotting with Seaborn
Seaborn is a Python data visualization library based on Matplotlib. It
provides a high-level interface for drawing attractive and informative
statistical graphics.
Installation of Seaborn:
# Data
tips = sns.load_dataset("tips")
# Scatter plot
sns.scatterplot(x="total_bill", y="tip", data=tips)
plt.title('Tip by Total Bill')
plt.show()
ax[0, 0].plot(x, y)
ax[0, 0].set_title('First Plot')
plt.show()
Installation of Plotly:
import plotly.express as px
fig.show()
# Plot
gdf.plot()
plt.show()
Installation of Flask:
Installation of Django:
@app.route('/')
def hello_world():
return 'Hello, World!'
if __name__ == '__main__':
app.run(debug=True)
Run this script, and visit in your browser to see the greeting.
1. Create a project:
cd myproject
3. Start an app:
python manage.py startapp myapp
4. Create a view in :
def hello(request):
return HttpResponse("Hello, World!")
urlpatterns = [
path('', hello),
]
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('myapp.urls')),
]
7. Run the server:
app = Flask(__name__)
@app.route('/api/data')
def data():
return jsonify({'key': 'value', 'name': 'John Doe'})
if __name__ == '__main__':
app.run(debug=True)
Installation:
pip install requests
import requests
response = requests.get('https://api.example.com/data')
data = response.json()
print(data)
This fetches data from an external API and prints the JSON
response.
import socket
def create_server():
server_socket = socket.socket(socket.AF_INET,
socket.SOCK_STREAM)
server_socket.bind(('localhost', 9999))
server_socket.listen(5)
print('Server is listening on port 9999...')
while True:
client_socket, addr = server_socket.accept()
print('Received connection from', addr)
client_socket.send("Hello! You are connected.".encode())
client_socket.close()
if __name__ == '__main__':
create_server()
This server listens on localhost and port 9999, and sends a greeting
message to any client that connects.
import sqlite3
connection.commit()
connection.close()
Security Practices:
import os
import shutil
# Creating a directory
if not os.path.exists('new_folder'):
os.mkdir('new_folder')
# Moving a file
shutil.move('example.txt', 'new_folder/example.txt')
# Copying a file
shutil.copy('new_folder/example.txt',
'new_folder/copy_of_example.txt')
# Deleting a file
os.remove('new_folder/copy_of_example.txt')
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
message = MIMEMultipart("alternative")
message["Subject"] = "Automated Email"
message["From"] = sender_email
message["To"] = receiver_email
# Send email
server = smtplib.SMTP('smtp.example.com', 587)
server.starttls()
server.login(sender_email, password)
server.sendmail(sender_email, receiver_email,
message.as_string())
server.quit()
message = client.messages \
.create(
body="This is an automated message from
Python.",
from_='+15017122661',
to='+15558675310'
)
print(message.sid)
13.3 Scheduling Tasks with Python
For tasks that need to run at specific times or intervals, Python’s
library allows for easy scheduling.
import schedule
import time
def job():
print("I am doing my scheduled task.")
while True:
schedule.run_pending()
time.sleep(60) # wait one minute
Basic Example: Here’s how you might write a simple test case
using :
import unittest
def test_sum_negative(self):
self.assertEqual(sum(-1, 1), 0, "Should be 0")
def test_sum_float(self):
self.assertEqual(sum(1.1, 2.2), 3.3, "Should be
approximately 3.3")
if __name__ == '__main__':
unittest.main()
2. Run the Test: Running the test at this point should naturally
fail since the feature isn’t implemented yet.
class TestMultiply(unittest.TestCase):
def test_multiply_two_numbers(self):
self.assertEqual(multiply(3, 7), 21, "Should be 21")
Run the tests, and if they pass, you can consider the current
requirements met.
import threading
def print_numbers():
for i in range(1, 6):
print(i)
def print_letters():
for letter in 'abcde':
print(letter)
thread1 = threading.Thread(target=print_numbers)
thread2 = threading.Thread(target=print_letters)
thread1.start()
thread2.start()
thread1.join()
thread2.join()
def print_numbers():
for i in range(1, 6):
print(i)
def print_letters():
for letter in 'abcde':
print(letter)
process1 = Process(target=print_numbers)
process2 = Process(target=print_letters)
process1.start()
process2.start()
process1.join()
process2.join()
import asyncio
asyncio.run(main())
asyncio.run(main())
Installation of NumPy:
import numpy as np
# Performing operations
print(arr + 2) # Adds 2 to each element
print(arr * 2) # Multiplies each element by 2
# Multi-dimensional arrays
arr_2d = np.array([[1, 2, 3], [4, 5, 6]])
print(arr_2d)
Installation of SciPy:
Installation of Scikit-Learn:
# Make a prediction
x_new = np.array([60]).reshape((-1, 1))
y_pred = model.predict(x_new)
print("Predicted exam score:", y_pred[0]) # Output the
prediction
Key Concepts:
import sqlite3
# Connect to SQLite database (or create it if it doesn't exist)
conn = sqlite3.connect('example.db')
# Create table
cursor.execute('''
CREATE TABLE IF NOT EXISTS employees (
id INTEGER PRIMARY KEY,
name TEXT,
salary REAL,
department TEXT,
position TEXT,
hireDate TEXT
)
''')
Installation of SQLAlchemy:
Base = declarative_base()
id = Column(Integer, primary_key=True)
name = Column(String)
salary = Column(Float)
department = Column(String)
position = Column(String)
hireDate = Column(Date)
Profiling Python Code: You can use the module, a built-in Python
profiler, to analyze your code’s performance.
import cProfile
import re
def find_numbers():
return re.findall(r'\d+', "Here are some numbers: 1234, 5678,
9012")
cProfile.run('find_numbers()')
Optimization Tips:
#include <Python.h>
PyMODINIT_FUNC PyInit_hello(void) {
return PyModule_Create(&hellomodule);
}
setup(name = 'PackageName',
version = '1.0',
description = 'This is a demo package',
ext_modules = [module])
import hello
hello.say_hello("Programmers")
#cython: boundscheck=False
setup(ext_modules = cythonize('primes.pyx'))
Run:
import primes
print(primes.primes(10))
mypackage/
__init__.py
module1.py
module2.py
setup.py
Example :
setup(
name='mypackage',
version='0.1',
packages=find_packages(),
install_requires=[
# List your project's dependencies here.
# For example:
# 'numpy>=1.14.2',
],
author='Your Name',
author_email='your.email@example.com',
description='A simple example package',
url='https://github.com/yourusername/mypackage', # Optional
)
Example :
package:
name: mypackage
version: 0.1
source:
path: .
build:
number: 0
script: python setup.py install
requirements:
host:
- python
- setuptools
run:
- python
test:
imports:
- mypackage
conda build .
Uploading to Anaconda.org :
anaconda upload /path/to/conda-package.tar.bz2
#cython: language_level=3
app = FastAPI()
@app.get("/")
def read_root():
return {"Hello": "World"}
@app.get("/items/{item_id}")
def read_item(item_id: int, q: str = None):
return {"item_id": item_id, "q": q}