Python Programming
Python Programming
Legal Notice:
This book is copyright protected. It is only for personal use. You
cannot amend, distribute, sell, use, quote or paraphrase any part, or
the content within this book, without the consent of the author or
publisher.
Disclaimer Notice:
Please note the information contained within this document is for
educational and entertainment purposes only. All effort has been
executed to present accurate, up to date, reliable, complete
information. No warranties of any kind are declared or implied.
Readers acknowledge that the author is not engaged in the rendering
of legal, financial, medical or professional advice. The content within
this book has been derived from various sources. Please consult a
licensed professional before attempting any techniques outlined in this
book.
Mac
Although most macOS versions come with an installed Python
version, it's generally outdated.
Windows
The procedure for Python installation on Windows is as follows:
Linux
The majority of Linux distributions have pre-installed Python. On the
off chance that it's not installed, or needs upgrading to the recent
Python version, follow the steps mentioned below.
Some of the key features that are responsible for the popularity of
PyCharm are:
Installation
Anaconda distribution is advised for Jupyter installation, which
includes Python, Jupyter, and other packages for performing scientific
computing and data science.
Program Code:
pip install notebook
Program Code:
jupyter notebook
Program Code:
pip install tensorflow
Program Code:
pip install keras
With Python 3.4 or later, Pip comes embedded in your Python setup.
For Pip to be installed or upgraded, these are the steps:
Program Code:
python get-pip.py
This command triggers the Pip installation or upgrade in your system.
For Linux
You can use the package manager to get Pip installed on many Linux
versions. The below command servers the purpose for Debian-based
versions like Ubuntu:
Program Code:
sudo apt install python3-pip
Program Code:
sudo dnf install python3-pip
Optional Task:
1. Go to the URL—https://code.visualstudio.com/—which is
the official Visual Studio Code website, and download the
OS dedicated installer (Windows, macOS, or Linux).
Program Code:
def greet_english(name):
return f"Hello, {name}!"
def greet_spanish(name):
return f"Hola, {name}!"
def greet_french(name):
1. Save 'greetings.py'.
Program Code:
import greetings
name = "Alice"
print(greetings.greet_english(name))
print(greetings.greet_spanish(name))
print(greetings.greet_french(name))
4. Save and run 'main.py' using your Python interpreter using the
below command.
Command:
python main.py
Output:
Hello, Alice!
Hola, Alice!
Bonjour, Alice!
Program Code:
import math
Program Code:
import numpy as np
Program Code:
from math import sqrt, pi
Import all: You have the option of importing all classes, functions, and
variables via wildcard `*` from a module. This approach is often
discouraged due to the possibility of naming conflicts and making it
obscure to trace the origin of a function, class, or variable.
Program Code:
from math import *
Command:
pip install requests
Program Code:
import requests
feedback = requests.get("https://api.example.com/data")
print(feedback.json())
print(array) # Output: [1 2 3]
Program Code:
import pandas as pd # 'pandas' module is renamed to 'pd'
data = {'A': [1, 2, 3], 'B': [4, 5, 6]}
print(df)
Program Code:
import math
Program Code:
import random
Program Code:
import os
Program Code:
import datetime
today = datetime.date.today()
Program Code:
import json
json_data = json.dumps(data)
pattern = r"\d+"
Program Code:
from collections import Counter
counter = Counter(word_list)
urllib: Includes classes and procedures for cooperating with URLs, for
example, fetching data, parsing URLs, and managing HTTP requests.
Program Code:
from urllib.request import urlopen
response = urlopen("https://www.example.com")
html = response.read()
print(html)
csv: Introduces classes for reading and writing table data in CSV
format.
Program Code:
import csv
reader = csv.reader(csv_file)
print(row)
The modules mentioned above represent just a handful of the many
built-in ones available in Python. You can find a complete list and
detailed documentation in the Python Standard Library documentation
from the URL—https://docs.python.org/3/library/index.html. These
built-in modules can greatly expedite processes and effort, as they
allow for the utilization of powerful, rigorously-tested and reliable
functionalities in your code.
Reloading Modules
Python programming language does not automatically reload a
module if the code in the module is changed during the execution of a
program. Though, the explicit reloading of a module is feasible
through the `importlib.reload()` function.
Program Code:
import importlib
Program Code:
import my_module
Program Code:
importlib.reload(my_module)
Program Code:
# main.py
import my_module
import importlib
my_module.print_hello()
print("\nReloading my_module...")
importlib.reload(my_module)
my_module.print_hello()
Program Code:
# my_module.py
def print_hello():
print("Hello, World!")
Program Code:
Initial output from my_module:
Hello, World!
Reloading my_module...
Splitting Modules
Organizing large files into individual modules is a recommended
approach which boosts code clarity, organization, and usability. Here
is a systematic guide on how to break down a large file into separate
modules:
Program Code:
# Sample: main.py (post-splitting)
6. Verify Your Code: Following the bulky file split and updating
of import instructions, undertake thorough testing of your
code to make sure everything works as it used to. Be
watchful for import errors, circular dependencies, and
discontinued functionality.
Virtual Environments
Python's virtual environments are exclusive platforms that permit
dependency and Python version management for individual projects.
They play a significant role in segregating dependencies from various
projects, preventing clashes, and preserving clean global Python
installations. Thanks to Python 3.3+'s built-in `venv` module, creating
and handling these virtual environments is an effortless task.
Here is a comprehensive guide on creating and utilizing a virtual
environment:
Program Code:
python -m venv my_virtual_env
Program Code:
my_virtual_env\Scripts\activate
- For **macOS/Linux**, execute:
Program Code:
source my_virtual_env/bin/activate
Program Code:
deactivate
Program Code:
pip freeze > requirements.txt
Program Code:
import emoji
print(emoji.emojize("Python is enjoyable :smile:",
language="alias"))
Program Code:
howdoi write a file in python
Program Code:
import wikipedia
overview = wikipedia.summary("Python (programming language)")
print(overview)
sys.exit(): Included in the `sys` module, the `sys.exit()` function
concludes the execution of a Python scheme. It proves useful when
stopping a program during a critical error or when certain conditions
are met.
Program Code:
import sys
if colossal_mistake_encountered:
sys.exit(1)
urllib: The `urllib` module has a set of functions and classes used for
working with URLs, fetching data, and managing HTTP requests.
Program Code:
from urllib.request import urlopen
urlAddress = "https://www.example.com"
responseReceived = urlopen(urlAddress)
html_data = responseReceived.read()
print(html_data)
Program Code:
import turtle
# Creating a turtle object
penObject = turtle.Turtle()
# Scribbling a square
for _ in range(4):
penObject.forward(100)
penObject.right(90)
Functional Programming
Functional programming paradigm emphasizes the utilization of
functions, encourages immutability, and prevents side effects to
formulate tidy, sustainable, and module-based code. Let's understand
more about functional programming through these principles:
Lambda Functions
Anonymous or lambda functions in Python are compact single-
expression functions that are unnamed. They are particularly
beneficial for cases that necessitate brief, straightforward
functionality like in higher-order functions such as `map`, `filter`, and
`sorted`.
Program Code:
lambda arguments: expression
Program Code:
# Defining a lambda function for addition of two digits
add = lambda x, y: x + y
print(result) # Outcome: 8
Program Code:
numbers = [3, 1, 7, 4, 9, 2]
map()
Python's `map()` function qualifies as a higher-order function for its
ability to apply a selected function to all items of one or several
iterables- such as lists, tuples, or sets- and produce an iterable
(precisely, a map object) that incorporates the resulting outcomes. A
typical function, a lambda function, or any callable object can suitably
be used as the first argument the `map()` function will work with.
Program Code:
# Function established to square a given number
def square(x):
return x ** 2
Program Code:
numbers = [1, 2, 3, 4, 5]
Program Code:
# Defined function to sum up two digits
def add(x, y):
return x + y
Program Code:
numbers1 = [1, 2, 3, 4, 5]
filter()
In Python, the `filter()` function is a higher-order function that sifts
through elements from a provided iterable based on a specified
function. This function requires two inputs: a function and an iterable.
The function involved should be designed to accept only one
argument, then output a boolean value. The `filter()` function
implements the provided function upon each iterable element, and if
the function returns `True` for an element, it becomes part of the
result/output of the filter object. This filter object is, in essence, an
iterable which can then be transformed into a list, tuple, or another
form of collection.
Take, for instance, using `filter()` function to skim out even numbers
from a list:
Program Code:
# Establish a function that verifies if a number is even
def is_even(x):
return x % 2 == 0
Program Code:
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Bear in mind that the filtering function needs to yield a boolean value
(`True` or `False`). In circumstances where the function provides a
truthy or falsy value that is not a distinct boolean, the `filter()` function
can still operate, though it's advised to ensure your filtering function
produces a proper boolean for the sake of code readability and
maintainability.
reduce()
The `reduce()` function in Python illustrates a higher-order function
that incrementally implements a provided function to the elements of
an iterable, simplifying the iterable to a single value. `reduce()`
function is now placed in Python's `functools` module, implying its
importation is necessary:
Program Code:
from functools import reduce
Program Code:
from functools import reduce
return x * y
# Result output
print(product) # Output: 120
initial_value = 10
I nability,
the domain of coding, interacting with files constitutes a vital
since it provides programmers the means to accumulate,
extract, and manipulate information across multiple systems and
applications. This section shall assist the reader in comprehending the
numerous tasks executable with files in Python, spanning fundamental
read and write actions to more sophisticated operations like
managing file paths, authorizations, and metadata. By excelling in
these skills, the reader will be capable of constructing applications
that can efficiently operationalize and control data deposited in files,
instituting a sturdy base for their Python progress journey.
With Open()
In Python programming, it's best practice to make use of the `with
open(...) as ...` statement while opening and working with files- a
combination of the `with` statement that sets up a context manager,
and the `open()` function devised to open a file. The benefit of this
method is that it eases file management and ensures automatic
closing of the file when the code block of the `with` statement is
exited (even in exception cases).
Program Code:
file_path = "example.txt"
content = file.read()
In the above example, the file at `file_path` is opened ('r' mode). The
`with` statement creates a context manager safeguarding the file
closure when the block of code is exited. The contents of the file are
read into the `content` variable, and as soon as the `with` block is
exited, the file is auto-closed.
You can also write to a file using `with open(...) as ...` shown below:
Program Code:
file_path = "output.txt"
file.write(data)
In this different case, the file at `file_path` is opened ('w' mode). The
`with` statement sets up a context manager that ensures the file's
closure when exiting the block of code. The data is inscribed to the
file, and upon exiting the `with` statement's block, the file
automatically shuts.
content = os.listdir(directory)
print(content)
import os
newly_created_directory = "fresh_directory"
os.mkdir(newly_created_directory)
Program Code:
import os
directory_to_eliminate = "no_content_directory"
os.rmdir(directory_to_eliminate)
Program Code:
import os
path = "sample_directory"
directory_confirmation = os.path.isdir(path)
print(directory_confirmation)
Program Code:
from pathlib import Path
directory = Path("sample_directory")
print(content)
Program Code:
from pathlib import Path
freshly_created_directory = Path("fresh_directory")
freshly_created_directory.mkdir()
Program Code:
from pathlib import Path
directory_to_erase = Path("no_content_directory")
directory_to_erase.rmdir()
Program Code:
from pathlib import Path
route = Path("sample_directory")
directory_verification = route.is_dir()
print(directory_verification)
Both `pathlib` and `os` modules make for strong tools that manage
directory listings in addition to conducting varieties of file system
operations. The choice between both modules heavily hinges on user
preferences and the version of Python in use. An example of this
distinction is that while `os` is historical and procedural, `pathlib`
works with a more contemporary, object-oriented approach.
File Attributes
File attributes present a kind of metadata concerning a file in a file
system. These attributes may encompass details like the file's size,
the times it was created, modified, or accessed. Python offers the
ability to fetch and modify file attributes with modules such as `os`,
`os.path`, or for Python versions 3.4 and beyond, the `pathlib`
module.
Program Code:
import os
# Defining the file path
file_path = "example.txt"
Program Code:
import os
from datetime import datetime
# Defining the file path
file_path = "example.txt"
Program Code:
import os
from datetime import datetime
# Defining the file path
file_path = "example.txt"
Program Code:
from pathlib import Path
from datetime import datetime
# Defining the file path
file_path = Path("example.txt")
Program Code:
from pathlib import Path
from datetime import datetime
# Defining the file path
file_path = Path("example.txt")
os.mkdir(directory_single)
Program Code:
import os
directories_nested =
"directory_parent/directory_child/directory_grandchild"
os.makedirs(directories_nested)
Program Code:
from pathlib import Path
directory_single = Path("directory_single")
directory_single.mkdir()
Program Code:
from pathlib import Path
directories_nested =
Path("directory_parent/directory_child/directory_grandc
hild")
directories_nested.mkdir(parents=True)
Program Code:
import glob
directory = "example_directory"
pattern = "*.txt"
file_paths = glob.glob(f"{directory}/{pattern}")
print(file_paths)
Program Code:
import glob
directory = "example_directory"
pattern = "file_*.txt"
file_paths = glob.glob(f"{directory}/{pattern}")
print(file_paths)
import fnmatch
directory = "example_directory"
pattern = "*.txt"
filenames = os.listdir(directory)
print(matching_files)
pattern = "file_*.txt"
filenames = os.listdir(directory)
print(matching_files)
Both modules, `glob` and `fnmatch`, serve as useful tools for the
matching of filename patterns in Python. While `glob` stands out due
to its uncomplicated usage, `fnmatch` is preferable for its flexibility
and potential use in advanced pattern-extraction and filtering
operations.
Processing Files
File processing techniques in Python typically involve reading from,
writing to, or manipulating the contents of a file. Here, I shall explicate
some examples of dealing with text files using Python's standard file
handling methods, as well as the `pathlib` module for those using
Python 3.4+.
Utilizing Standard File Handling Methods
Reading a file: This involves employing the `open()` function with `'r'`
mode (read mode) to access and relay the contents of a file.
Program Code:
file_path = "example.txt"
content = file.read()
print(content)
Writing to a file: The `'w'` mode (write mode) is utilized with the
`open()` function to inscribe data on a file. Caution should be taken as
this erases existing file data.
Program Code:
file_path = "example.txt"
file.write(data)
Program Code:
file_path = "example.txt"
file.write(data)
Program Code:
from pathlib import Path
file_path = Path("example.txt")
content = file_path.read_text()
print(content)
Program Code:
from pathlib import Path
file_path = Path("example.txt")
file_path.write_text(data)
Program Code:
from pathlib import Path
file_path = Path("example.txt")
file.write(data)
Traversing Directories
In Python language, the `os` module or the `pathlib` module (for
Python 3.4 and above) can be employed for directory traversal, which
refers to the process of reviewing directory trees involving directories
and their subsequent files and subdirectories.
Illustrative examples on the usage of the `os` and `pathlib` modules
are given below.
Program Code:
import os
init_directory = "sample_directory"
print(f"Directory: {dirpath}")
Program Code:
from pathlib import Path
init_directory = Path("sample_directory")
if pathway.is_dir():
print(f"Directory: {pathway}")
elif pathway.is_file():
print(f"File: {pathway}")
if pathway.is_dir():
print(f"Directory: {pathway}")
navigate_directory(pathway)
elif pathway.is_file():
print(f"File: {pathway}")
init_directory = Path("sample_directory")
navigate_directory(init_directory)
While the `os` module and `pathlib` modules are both valuable for
directory traversing in Python, the choice of module relies on your
comfort level and the Python version used. The former offers a
traditional procedural approach, whereas the latter, which is more
contemporary, takes an object-oriented strategy.
Program Code:
import tempfile
with tempfile.TemporaryFile(mode='w+t') as temp_file:
content = temp_file.read()
print(content)
Establishing a temporary file with a specific prefix and suffix: With the
`tempfile.NamedTemporaryFile()` function, one can create a
temporary file with a given prefix and suffix. The file will be deleted
when it is closed.
Program Code:
import tempfile
with tempfile.NamedTemporaryFile(mode='w+t',
prefix='temp_', suffix='.txt', delete=True) as
temp_file:
content = temp_file.read()
print(content)
Program Code:
import tempfile
import os
with tempfile.TemporaryDirectory() as temp_dir:
temp_file_path = os.path.join(temp_dir,
"temp_file.txt")
File Archiving
The code written in Python enables both the creation and extraction
of archived data sets such as ZIP or TAR files, made possible
through the executable modules, namely `zipfile` and `tarfile`.
Elucidating the functionality embedded within these modules can be
done through specific examples:
Program Code:
#example python code
import zipfile
files_to_archive = ["file1.txt", "file2.txt"]
archive_name = "example.zip"
zip_file.write(filename, arcname=filename)
Extraction of ZIP File: The 'r' or the read mode in the `zipfile.ZipFile`
class executes the extraction of files from an existing ZIP archive to a
designated folder.
Program Code:
#example python code
import zipfile
archive_name = "example.zip"
output_directory = "extracted_files"
zip_file.extractall(output_directory)
archive_name = "example.tar.gz"
tar_file.add(filename, arcname=filename)
output_directory = "extracted_files"
tar_file.extractall(output_directory)
T oneed
maintain the integrity of core object structures, developers often
to extend object functionality in object-oriented programming.
This guide explores an approach to dynamically load new functionality
onto objects without directly modifying their underlying structure. This
technique promotes a modular and adaptable codebase, reducing the
risk of unintended side effects and keeping the original object's
purpose clear.
First-Class Objects
A central concept in programming languages, first-class objects, or
alternatively first-class citizens, signify objects which can acquire
values. Languages recognize entities as first-class and allow their
free use across several programming constructs, letting them be
assigned to variables, passed into functions, or returned as values
from functions. They provide versatility permitting a more powerful
and expressive programming paradigm—a feature that most modern
programming languages attribute to.
Map: The function `map` accepts a function along with a list (or other
iterable units) as parameters. It then applies the given function to
each element of the list and yields a new list with the processed
results. This methodology provides a succinct approach towards
transforming data sets without necessitating explicit loops.
Program Code:
const numbers = [1, 2, 3, 4, 5];
Program Code:
const numbers = [1, 2, 3, 4, 5];
Reduce: This function calls for a function, a list, and an optional initial
value as input. It subsequently applies the input function
systematically to the list's elements, from the left towards the right,
so as to compress the list into a single entity. This proves handy
when data needs to be aggregated or combined in various forms.
Program Code:
const numbers = [1, 2, 3, 4, 5];
Chaining Decorators
Decorator chaining serves as a widely used technique in object-
oriented programming languages, and its purpose is to dynamically
extend an object's functionality without altering its fundamental
structure. The decorator pattern guides this approach, wherein
creating a series of wrapper classes that mimic the original object's
interface allows for the addition or overriding of behavior as needed.
Developers can construct composite behavior in a flexible and
modular manner by chaining multiple decorators.
Program Code:
# Construct the common interface
class FileReader:
pass
return file.read()
self._file_reader = file_reader
return self._file_reader.read(filename)
class CachingFileReader(FileReader):
self._file_reader = file_reader
self._cache = {}
self._cache[filename] =
self._file_reader.read(filename)
return self._cache[filename]
# Chaining the decorators
file_reader =
CachingFileReader(LoggingFileReader(SimpleFileReader()))
Nested Decorators
The term 'Nested Decorators' or 'Stacked Decorators' is commonly
used in programming languages supporting decorators or
annotations, such as Python. It allows programmers to use several
decorators on a single method or function, enhancing readability and
brevity. Nested decorators work by layering decorators atop each
other, with every decorator enveloping the function or method it
precedes.
start_time = time.time()
return result
return wrapper
return result
return wrapper
@log_result
def slow_function(x):
time.sleep(x)
return x * 2
# Call to the decorated function
result = slow_function(2)
Conditional Decorators
Conditional decorators offer a technique through which decorators
can be applied to a function or method, depending on certain
conditions at runtime. This method is especially useful when adding or
modifying the functionality of a function based on specific
configurations, environments, or the state of an application.
In Python, this can be achieved by defining a covering function that
holds a condition, a decorator, and the original function as its
arguments. Depending on the condition, this covering function can
either apply the decorator to the original function or return the function
unmodified.
Program Code:
def conditional_decorator(condition, decorator):
def wrapper(func):
if condition:
return decorator(func)
else:
return func
return wrapper
return wrapper
Debugging Decorators
Debugging decorators in code is advantageous for integrating
diagnostic data or scrutinizing the activity of functions and methods
within the intrinsic framework of your code without alterations.
Decorators simplify the activation or deactivation of debugging
prospects when required.
Program Code:
import functools
def log_call(func):
@functools.wraps(func)
return wrapper
@log_call
return a + b
result = add(3, 4)
Program Code:
import time
def measure_time(func):
@functools.wraps(func)
start = time.perf_counter()
end = time.perf_counter()
return result
return wrapper
@measure_time
def slow_function(x):
time.sleep(x)
return x * 2
result = slow_function(2)
Program Code:
def log_result(func):
@functools.wraps(func)
return result
return wrapper
@log_result
return a * b
result = multiply(3, 4)
Program Code:
@measure_time
@log_call
return a - b
result = subtract(7, 3)
Program Code:
import functools
import traceback
def handle_errors(func):
@functools.wraps(func)
try:
except Exception as e:
print(traceback.format_exc())
return wrapper
@handle_errors
return a / b
result = divide(4, 2)
result = divide(4, 0)
Program Code:
def handle_errors_with_default(default_value):
def decorator(func):
@functools.wraps(func)
try:
except ZeroDivisionError as e:
except Exception as e:
print(f"Error in {func.__name__}: {e}")
print(traceback.format_exc())
return default_value
return wrapper
return decorator
@handle_errors_with_default(default_value=float('inf'))
return a / b
result = safe_divide(4, 2)
result = safe_divide(4, 0)
The scripting process covers minor tasks like file handling to complex
functions like network communications and data computations. By
gaining proficiency in these, you can tap into automation's full
capacity, reducing manual input to the barest minimum. In this
chapter, several practical scripts that can be incorporated effortlessly
into your daily routine as a programmer will be studied.
GUI Scripting
Another integral aspect of scripting languages is Graphical User
Interface (GUI) scripting. This aspect provides an avenue for the
development, management, and interaction with user interfaces via
programming. Scripting languages such as Python, JavaScript, and
AutoHotkey enable programmers to develop tailored scripts for GUI
tasks automation, inclusive of navigating menus, button clicking, and
form filling. The resulting effect is a significantly enhanced user
experience since the scripting allows user-friendly interfaces creation
and simplifying complex software applications interactions.
Glue Language
Scripting languages often perform the 'glue language' function in
software development by seamlessly linking various systems and
components. These languages enhance the communication between
different software modules, enabling these modules to function
together even when they are coded in varying programming
languages. An example is Python, a widely utilized glue language that
integrates C++ or C libraries with web applications. These scripting
languages fill up chasms between various systems, helping
developers come up with more efficient and assembled software
solutions.
Time Conservation
The key advantage automation caters to is the conservation of time-
given that monotonous and time-extensive tasks are automated,
developers save up time for crucial, intricate aspects of the project.
This ensures the quickening of the project life cycle and prompt
delivery of software applications, thereby ensuring a competitive
market stance.
Scalable Operations
Enhanced project size and evolution underlines the necessity of
efficient scalability in operations, crucial for successful outcomes.
Automation effortlessly manages increased workloads, given that
automated processes can be upsized or downsized as per
requirements. This adaptability ensures high performance without
pressurizing human resources, enabling businesses to cater to
shifting needs.
Cost Efficiency
While the initial capital invested in automation technologies and tools
might be on the higher end, the long-term profitability often surpasses
the expenses. Automation minimizes manual intervention, thereby
saving costs on salaries, perks, and training. Furthermore, it
enhances efficiency, precision, and speed of processing which
collectively orchestrates lower operational expenses and greater
revenues.
Augmented Collaboration
Automation fosters enriching team collaborations within organizations,
given that automated operations like continuous integration and
deployment inspire developers to share codes and collaborate more
often. This enhances communication, quick problem-solving, and
boosts productivity collectively. It serves as a catalyst in enhancing
workflows and bridging departments, creating a more harmonious
and partnered work experience.
Functions in Python
Python, like many other programming languages, heavily relies on
functions. These allow a set of instructions to be performed as a
package, thus improving code organization, reusability, and
comprehensibility. This section will discuss particulars like synthetic
properties of Python functions, their use cases as well as how they
can be called into action.
Syntax
The identifier `def` is used to define a function in Python, succeeded
by the function's pivotal name, brackets, and colon. The code block
for any function is a textual unit with a meaningful indentation under its
definition.
def greet():
print("Hello, World!")
Execution of Functions
To run a function, all you need to do is follow it up with an opening
and closing parenthesis like mentioned below.
Program Code:
python
Parameters in Function
Parameters are essentially input values for a function allowing you to
feed data into it.
To set up a function that requires independent parameters, inculcate
such parameter names within the parentheses.
Program Code:
python
def greet(name):
print(f"Hello, {name}!")
Program Code:
python
Return Statements
With the `return` keyword, functions are capable of reverting values.
This enables the use of function end results in other sections of your
code as demonstrated below.
Program Code:
def add(a, b):
return a + b
outcome = add(3, 4)
print(outcome) # Output: 7
In this illustration, the `add` function receives two parameters, `a` and
`b`, and subsequently returns their summation. The computed return
value is then conferred to the `outcome` variable.
Default Parameters
Default values can be designated to function parameters, which
facilitates the calling of the function without having to specifically
provide those parameters. In case a value for a default parameter
isn’t provided, the default one will be used:
Program Code:
def greet(name="World"):
print(f"Hello, {name}!")
Program Code:
import sys
python my_script.py arg1 arg2 arg3
This command creates a `sys.argv` list in `my_script.py` looking like
that:
Program Code:
['my_script.py', 'arg1', 'arg2', 'arg3']
Program Code:
python print_args.py hello world
Argument 1: hello
Argument 2: world
Program Code:
import sys
if len(sys.argv) != 3:
sys.exit(1)
try:
num1 = float(sys.argv[1])
num2 = float(sys.argv[2])
except ValueError:
sys.exit(1)
print("Sum:", result)
Program Code:
for variable in sequence:
# execution command for each sequence item
An example showing how a `for` loop iterates through a sequence of
numbers is:
Program Code:
numbers = [1, 2, 3, 4, 5]
print(num)
Output:
1
Program Code:
for i in range(5):
print(i)
While Loop
The `while` loop in Python is responsible for executing a specific code
block continuously upon satisfaction of a certain condition.
Syntax:
while condition:
Program Code:
i = 0
while i < 5:
print(i)
i += 1
This outputs:
0
1
2
Program Code:
for i in range(10):
if i == 5:
break
if i % 2 == 0:
continue
print(i)
The loop ends when `i` equals 5, with the `continue` statement
overlooking even numbers.
Array Module
To use the array in Python, import the `array` module as shown
below.
Program Code:
python
import array
The `array` module yields the `array` class useful for array creations
and manipulations.
Array Creation
Constructing an array involves the `array()` constructor following the
format:
Syntax Format:
array(typecode, initializer)
Program Code:
import array
Program Code:
int_array = array.array('i', [1, 2, 3, 4, 5])
print(int_array[1]) # Output: 2
int_array[1] = 7
Array Methods
The `array` class offers practical methods for array manipulations
including:
int_array.append(6)
int_array.extend([7, 8, 9])
int_array.pop()
int_array.remove(4)
print(int_array.index(5)) // Output: 3
print(int_array.count(2)) // Output: 1
Program Code:
file_variable = open(file_name, mode)
Program Code:
file = open("example.txt", "r")
Files Reading
• After opening, we can read the file content using several
offered file object methods.
• `read()`: Reads the whole file content as a single string.
• `readline()`: Reads one line from the file, including the newline
character.
• `readlines()`: Reads all lines from the file and returns them in
the form of a string list.
Here's an example on how to use these methods.
Program Code:
file = open("example.txt", "r")
whole_content = file.read()
print("Content:")
print(whole_content)
line = file.readline()
lines = file.readlines()
print("Lines:", lines)
file.close()
To read a file line by line, you can use a `for` loop as shown below.
Program Code:
file = open("example.txt", "r")
print(line.strip())
file.close()
Writing Files
To write in a file, use the `write()` method provided by the file object.
Program Code:
file = open("output.txt", "w")
file.write("Hello, World!")
file.close()
To write at the end of the file, open it in the append mode (`'a'`) and
use the `write()` method.
Program Code:
file = open("output.txt", "a")
file.close()
File Closing
Once your work is done with a file, please make sure to close it using
the `close()` method of the file object.
Program Code:
file.close()
Closing a file makes sure that any changes made but not written
(pending changes) are committed and the system resources are
freed.
Program Code:
with open("example.txt", "r") as file:
whole_content = file.read()
print(whole_content)
# The file automatically closes once the 'with' block code execution
ends
Scripting Exercises
Here are basic instructions for producing Python scripts to mechanize
numerous responsibilities. These directions will inform you regarding
the libraries required and the basic procedure to complete each task.
Make a script that reads from a list of song details (file path, title,
etc.) and rearranges them using `random.shuffle()`.
Image manipulation or adaptation: The `Pillow` collection is used for
basic image editing tasks.
Apart from this, the section will delve into the ethics and legality
surrounding data scraping. Despite its efficiency in collecting
information, data scraping can trigger privacy issues and possibly
infringe on intellectual property rights. We will emphasize the
importance of adhering to the terms of service, respecting copyright
laws, and understanding the ramifications of data scraping. Having a
consciousness of these considerations better equips you to scrape
responsibly and efficiently.
Program Code:
html = '''
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<ul>
<li>Item 1</li>
<li>Item 2</li>
<li>Item 3</li>
</ul>
</body>
</html>
'''
title_end = html_cleaned.find('</title>')
title = html_cleaned[title_start:title_end]
print('Title:', title)
h1_end = html_cleaned.find('</h1>')
h1 = html_cleaned[h1_start:h1_end]
print('Header:', h1)
li_start = 0
while True:
if li_start == -1:
break
li_start += len('<li>')
li = html_cleaned[li_start:li_end]
li_start = li_end
This instance shows text extraction from specified HTML tags using
Python's string methods like `find()` and slicing. However, we cannot
overemphasize that this method is not sturdy and may not be
appropriate for more elaborate HTML structures or when dealing with
attributes, nested tags, or dynamic contents. For these situations, the
use of dedicated web scraping libraries such as Beautiful Soup or
Scrapy is highly encouraged, given they're designed precisely to
navigate the complexities of HTML parsing.
Command:
Program Code:
import requests
Program Code:
url = 'https://example.com/sample-page'
response = requests.get(url)
Program Code:
# Retrieve the page heading
title = soup.title.string
print('Title:', title)
print('Heading:', heading.get_text())
Program Code:
# Retrieve all hyperlinks with the 'external-link' CSS class
links = soup.find_all('a', class_='external-link')
Program Code:
pip install lxml
Program Code:
import requests
response = requests.get(url)
html = etree.HTML(response.content)
Program Code:
# Acquire the page title
title = html.xpath('//title/text()')
print('Title:', title[0])
headings = html.xpath('//h1/text()')
list_items = html.xpath('//li/text()')
Program Code:
pip install Scrapy
Program Code:
import scrapy
class MyProjectItem(scrapy.Item):
title = scrapy.Field()
link = scrapy.Field()
Program Code:
import scrapy
from my_project.items import MyProjectItem
class SampleSpider(scrapy.Spider):
name = 'sample_spider'
start_urls = ['https://example.com/sample-page']
# Title extraction
title = response.css('title::text').get()
print('Title:', title)
headings = response.css('h1::text').getall()
print('Heading:', heading)
links = response.css('a.external-
link::attr(href)').getall()
item = MyProjectItem()
item['title'] = response.css('a.external-
link::text').get()
item['link'] = link
yield item
Program Code:
scrapy crawl sample_spider
Program Code:
scrapy crawl sample_spider -o output.json
Program Code:
pip install MechanicalSoup
Program Code:
import mechanicalsoup
Develop a browsing object and retrieve the webpage with the form:
Program Code:
# Establish a browser object
browser = mechanicalsoup.StatefulBrowser()
url = 'https://example.com/login'
browser.open(url)
Pinpoint the form on the webpage:
Program Code:
# Identify the form on the webpage (first one by default)
form = browser.select_form()
# form = browser.select_form('form#login-form')
Program Code:
# Complete the form (replace 'username' and 'password' as
required)
form.set('username', 'your_username')
form.set('password', 'your_password')
Program Code:
# Lodge the form
response = browser.submit_selected()
Work through the response. Access the response content and parse
the HTML with Beautiful Soup:
Program Code:
# Get the response content
content = response.content
soup = browser.page
When dealing with a lone site, the process may require tracing
various links to other pages such as pagination or related pages.
The following Python snippet is a guide:
Program Code:
import requests
root_url = 'https://example.com'
route = '/page1'
max_pages = 3
def data_scraper(url):
resp = requests.get(url)
print(soup_lib.title.string)
return soup_lib
if subsequent_link:
soup_lib = data_scraper(following_url)
else:
halt
Program Code:
import requests
from bs4 import BeautifulSoup
target_urls = [
'https://example1.com/page1',
'https://example2.com/page2',
'https://example3.com/page3',
def data_scraper(url):
resp = requests.get(url)
print(soup_lib.title.string)
data_scraper(urls)
In this case too, your specific extraction logic should replace the
sample provided above.
Take heed not to violate any website's scraping rules stipulated under
'robots.txt', to alleviate chances of getting blocked over excessive
requests. Delays between requests can be regulated with Python's
`time.sleep()` function.
Program Code:
import requests
url = 'https://example.com'
proxy = 'http://proxy_ip:proxy_port'
proxies = {
'http': proxy,
'https': proxy,
Program Code:
import requests
proxies_list = [
'http://proxy1_ip:proxy1_port',
'http://proxy2_ip:proxy2_port',
def get_random_proxy():
return {
'http': choice(proxies_list),
'https': choice(proxies_list),
I nalternatives
this chapter, we undertake a compelling exploration of Django
that enable the creation of remarkable web applications
leveraging Python. Django is indeed a robust and prevalent web
framework but isn't the sole choice for developers in creating Python-
based websites. In traversing through the varied world of Python web
frameworks, our objective is to enrich our readers with insightful
comprehension to select the most suitable tool aligning with their
distinct requirements and likes.
Bottle
Bottle is an easily-manageable micro web-framework for Python,
designed to provide simplicity and user-friendliness. Its versatility is
best suited for small to mid-level web application development and is
also great for individuals who seek minimalism when coding.
Surprisingly, despite its compact structure, Bottle provides several
distinct benefits and features making it a go-to for web application
development.
Setup Bottle
Setting up Bottle is extremely straightforward due to its existence on
the Python Package Index (PyPI). Use the subsequently mentioned
`pip` command for Bottle installation:
Program Command:
pip install bottle
CherryPy
CherryPy is a Python web framework that stands out for its simplicity,
object-oriented approach, flexibility, and potency. It's one of Python's
pioneering web frameworks, prominently known for enabling
developers to construct web applications devoid of the intricacies and
redundancies inherent in larger frameworks. Although it might not
possess as many features as other options, CherryPy renders itself a
viable contender across various projects due to its key characteristics
and advantages.
Program Code:
pip install cherrypy
Flask
Flask, a widely recognized and used microweb framework designed
for Python, is famed for its simplicity and adaptability in web
development. Projects, ranging from lesser complex varieties to more
sophisticated systems, can be effectively managed using this
framework. A few standout characteristics of Flask help cement its
position as an excellent option for web development.
Program Code:
pip install Flask
Tornado
Tornado denotes a strong, contemporary framework and network
library, Python-centric, specially devised for simultaneous connections
in large numbers. It caters to aspects of real-time communication and
high concurrency, making it perfect for real-time applications such as
chat systems, online gaming, and websockets.
Program Code:
pip install tornado
TurboGears
TurboGears offers a comprehensive solution for web development
built on Python, culminating in its myriad of features drawing from
frameworks like Ruby on Rails and Django. By combining several
components, it offers a feature-packed development experience.
Program Code:
pip install TurboGears2
Pylons Project
The Pylons Project, a compilation of Python's web programming
frameworks and libraries, includes Pyramid—a notable, versatile, and
lightweight web development framework adaptable to projects of any
scale. This discussion will concentrate on the particularities of the
Pyramid framework.
Program Code:
pip install pyramid
web2py
Web2py signifies a widely accepted Python web framework that
incorporates end-to-end features aimed to drive simplicity in web
creation tasks offering a one-stop efficient solution. It thrives well
under rapid application development conditions making it ideal for
project sizes ranging from small to medium ratios. Hence, its key
features set web2py as a compelling and user-friendly choice for web
application development.
By the end of this chapter, readers will shift their viewpoint towards
debugging, seeing it not as a burden but as a path for growth and
learning in Python development. Embracing debug challenges is a
step towards enhancing ourselves as coders, honing our analytical
and technical prowess.
Debugging: Mastering the Art of Problem-
Solving in Coding
Debugging is a complex process of pinpointing, separating, and
solving issues or "bugs" within a software application or computer
program. Bugs manifest as errors, crashes, inadvertent behaviors, or
performance obstacles, disrupting the software's intended
functionality. Being a cornerstone of software development,
debugging assures the end product's quality and undisturbed
functionality for the users.
Pdb
Python's integrated debugger, `pdb`, brings a range of features into a
programmer's arsenal.
Program Code:
(Pdb) until <line_number>
Program Code:
(Pdb) break [<filename>:]<line_number>
Program Code:
(Pdb) print <expression_or_variable>
(Pdb) p <expression_or_variable>
Program Code:
(Pdb) pp <expression_or_variable>
Code Listing: The `list` or `l` command in `pdb` helps display source
code around the current execution line. 11 lines of code are shown by
default, with the current line being central. Specifying a range or a
specific line is also feasible:
Program Code:
(Pdb) list [<first_line>-<last_line>]
(Pdb) l
Pdb Features
Understanding this abundant ' pdb' features aids in making Python
code debugging more productive and controlled. Knowledge of these
features is crucial for effective debugging of Python software.
Program Code:
import pdb
Execution of your script will be halted at this line, hence entering the
interactive `pdb` debugger.
Program Code:
import pdb
def add(a, b):
return a + b
def main():
x = 5
y = 7
result = add(x, y)
print(f"The result of {x} + {y} is {result}")
if __name__ == "__main__":
main()
Upon running this script, the `pdb.set_trace()` line will cause a pause,
and the interactive `pdb` debugger will then commence. You can then
harness various debugger commands to slowly traverse your code
and inspect variable values.
Whatis
In the Python debugger `pdb`, the `whatis` command exists, aiding in
the discovery of a variable or an expression type. This instruction can
offer greater comprehension of variable types during debugging, and
if need be, verification that a variable is a representation of a
particular class or type is easily achieved.
whatis <variable_or_expression>
import pdb
def main():
my_list = [1, 2, 3, 4, 5]
if __name__ == "__main__":
main()
Once it gets to the `pdb.set_trace()` line, the program halts and the
`pdb` interactive debugger is initiated.
So, at the `(Pdb)` prompt, you can now use the `whatis` command to
uncover the types of the variables:
Program Code:
(Pdb) whatis my_list
<class 'list'>
<class 'str'>
<class 'dict'>
Variables
Examining Python's built-in debugger `pdb`, one can monitor variable
values and evaluate expressions whilst in debugging mode.
(Pdb) p <variable_or_expression>
````
For instance:
````
(Pdb) p my_var
For instance:
(Pdb) pp my_nested_dict
Program Code:
(Pdb) display <variable_or_expression>
For example:
Python's inherent clarity and adaptability have led to its swift embrace
across many sectors. Its vast variety of libraries, inclusive of NumPy,
Pandas, and TensorFlow, as well as commanding frameworks such
as Scikit-learn and PyTorch have solidified it as the preferred
language for machine learning practitioners. Utilizing these libraries
allows Python coders to devise, execute, and refine avant-garde
machine-learning algorithms with considerable ease. Hence, the
mastery of these instruments is essential for any Python developer
aiming to maintain a competitive edge in the contemporary job
market.
Supervised Learning
Supervised learning involves training a machine learning model on a
properly labeled dataset inclusive of input attributes and matching
output tags. The aspiration here is to start an association between
the input attributes and the output tags enabling proficient predictions
on new data.
Gervase, P., & Zhang, B. (2022, March 30). How to get started with
scripting in Python. Enable Sysadmin.
https://www.redhat.com/sysadmin/python-scripting-intro