Home Page Icon
Home Page
Table of Contents for
cover
Close
cover
by Corey Wade, Graham Lee, Mario Corchero Jimenez, Dr. Lau Cher Han, Andrew Bird
The Python Workshop
Preface
About the Book
About the Chapters
Conventions
Before You Begin
To Install Jupyter on Windows
To Install the Python Terminal on Windows
A Few Important Packages
To install Docker
Installing the Code Bundle
1. Vital Python – Math, Strings, Conditionals, and Loops
Introduction
Vital Python
Numbers: Operations, Types, and Variables
To Open a Jupyter Notebook
Python as a Calculator
Standard Math Operations
Basic Math Operations
Order of Operations
Exercise 1: Getting to Know the Order of Operations
Spacing in Python
Number Types: Integers and Floats
Exercise 2: Integer and Float Types
Complex Number Types
Errors in Python
Variables
Variable Assignment
Exercise 3: Assigning Variables
Changing Types
Reassigning Variables in Terms of Themselves
Activity 1: Assigning Values to Variables
Variable Names
Exercise 4: Variable Names
Multiple Variables
Exercise 5: Multiple Variables in Python
Comments
Exercise 6: Comments in Python
Docstrings
Activity 2: Finding a Solution Using the Pythagorean Theorem in Python
Strings: Concatenation, Methods, and input()
String Syntax
Exercise 7: String Error Syntax
Escape Sequences with Quotes
Multi-Line Strings
The print() Function
Exercise 8: Displaying Strings
String Operations and Concatenation
Exercise 9: String Concatenation
String Interpolation
Comma Separators
Format
The len() Function
String Methods
Exercise 10: String Methods
Casting
Exercise 11: Types and Casting
The input() Function
Exercise 12: The input() Function
Activity 3: Using the input() Function to Rate Your Day
String Indexing and Slicing
Indexing
Slicing
Strings and Their Methods
Booleans and Conditionals
Booleans
Exercise 13: Boolean Variables
Logical Operators
Comparison Operators
Exercise 14: Comparison Operators
Comparing Strings
Exercise 15: Comparing Strings
Conditionals
The if Syntax
Indentation
Exercise 16: Using the if Syntax
if else
Exercise 17: Using the if-else Syntax
The elif Statement
Loops
The while Loops
An Infinite Loop
break
Activity 4: Finding the Least Common Multiple (LCM)
Programs
Exercise 18: Calculating Perfect Squares
Exercise 19: Real Estate Offer
The for Loop
Exercise 20: Using for Loops
The continue Keyword
Activity 5: Building Conversational Bots Using Python
Summary
2. Python Structures
Introduction
The Power of Lists
Exercise 21: Working with Python Lists
Matrices as Nested Lists
Exercise 22: Using a Nested List to Store Data from a Matrix
Activity 6: Using a Nested List to Store Employee Data
Matrix Operations
Exercise 23: Implementing Matrix Operations (Addition and Subtraction)
Matrix Multiplication Operations
Exercise 24: Implementing Matrix Operations (Multiplication)
List Methods
Exercise 25: Basic List Operations
Accessing an Item from a List
Exercise 26: Accessing an Item from Shopping List Data
Adding an Item to a List
Exercise 27: Adding Items to Our Shopping List
Dictionary Keys and Values
Exercise 28: Using a Dictionary to Store a Movie Record
Activity 7: Storing Company Employee Table Data Using a List and a Dictionary
Zipping and Unzipping Dictionaries Using zip()
Exercise 29: Using the zip() Method to Manipulate Dictionaries
Dictionary Methods
Exercise 30: Accessing a Dictionary Using Dictionary Methods
Tuples
Exercise 31: Exploring Tuple Properties in Our Shopping List
A Survey of Sets
Exercise 32: Using Sets in Python
Set Operations
Exercise 33: Implementing Set Operations
Choosing Types
Summary
3. Executing Python – Programs, Algorithms, and Functions
Introduction
Python Scripts and Modules
Exercise 34: Writing and Executing Our First Script
Exercise 35: Writing and Importing Our First Module
Shebangs in Ubuntu
Docstrings
Exercise 36: Adding a Docstring to my_module.py
Imports
Exercise 37: Finding the System Date
The if __name__ == "__main__" Statement
Activity 8: What's the Time?
Python Algorithms
Exercise 38: The Maximum Number
Time Complexity
Time Complexity for the Maximum Number Algorithm
Sorting Algorithms
Exercise 39: Using Bubble Sort in Python
Searching Algorithms
Exercise 40: Linear Search in Python
Exercise 41: Binary Search in Python
Basic Functions
Exercise 42: Defining and Calling the Function in Shell
Exercise 43: Defining and Calling the Function in Python Script
Exercise 44: Importing and Calling the Function from the Shell
Positional Arguments
Keyword Arguments
Exercise 45: Defining the Function with Keyword Arguments
Exercise 46: Defining the Function with Positional and Keyword Arguments
Exercise 47: Using **kwargs
Activity 9: Formatting Customer Names
Iterative Functions
Exercise 48: A Simple Function with a for Loop
Exiting Early
Exercise 49: Exiting the Function During the for Loop
Activity 10: The Fibonacci Function with an Iteration
Recursive Functions
A Terminating Case
Exercise 50: Recursive Countdown
Exercise 51: Factorials with Iteration and Recursion
Activity 11: The Fibonacci Function with Recursion
Dynamic Programming
Exercise 52: Summing Integers
Timing Your Code
Exercise 53: Timing Your Code
Activity 12: The Fibonacci Function with Dynamic Programming
Helper Functions
Don't Repeat Yourself
Exercise 54: Helper Currency Conversion
Variable Scope
Variables
Defining inside versus outside a Function
The Global Keyword
The Nonlocal Keyword
Lambda Functions
Exercise 55: The First Item in a List
Mapping with Lambda Functions
Exercise 56: Mapping with a Logistic Transform
Filtering with Lambda Functions
Exercise 57: Using the Filter Lambda
Sorting with Lambda Functions
Summary
4. Extending Python, Files, Errors, and Graphs
Introduction
Reading Files
Exercise 58: Reading a Text File Using Python
Exercise 59: Reading Partial Content from a Text File
Writing Files
Exercise 60: Creating and Writing Content to Files to Record the Date and Time in a Text File
Preparing for Debugging (Defensive Code)
Writing Assertions
Exercise 61: Working with Incorrect Parameters to Find the Average Using Assert with Functions
Plotting Techniques
Exercise 62: Drawing a Scatter Plot to Study the Data between Ice Cream Sales versus Temperature
Exercise 63: Drawing a Line Chart to Find the Growth in Stock Prices
Exercise 64: Plotting Bar Plots to Grade Students
Exercise 65: Creating a Pie Chart to Visualize the Number of Votes in a School
Exercise 66: Generating a Heatmap to Visualize the Grades of Students
Exercise 67: Generating a Density Plot to Visualize the Score of Students
Exercise 68: Creating a Contour Plot
Extending Graphs
Exercise 69: Generating 3D plots to Plot a Sine Wave
The Don'ts of Plotting Graphs
Manipulating the Axis
Cherry Picking Data
Wrong Graph, Wrong Context
Activity 13: Visualizing the Titanic Dataset Using a Pie Chart and Bar Plots
Summary
5. Constructing Python – Classes and Methods
Introduction
Classes and Objects
Exercise 70: Exploring Strings
Defining Classes
Exercise 71: Creating a Pet Class
The __init__ method
Exercise 72: Creating a Circle Class
Keyword Arguments
Exercise 73: The Country Class with Keyword Arguments
Methods
Instance Methods
Exercise 74: Adding an Instance Method to Our Pet Class
Adding Arguments to Instance Methods
Exercise 75: Computing the Size of Our Country
The __str__ method
Exercise 76: Adding an __str__ Method to the Country Class
Static Methods
Exercise 77: Refactoring Instance Methods Using a Static Method
Class Methods
Exercise 78: Extending Our Pet Class with Class Methods
Properties
The Property Decorator
Exercise 79: The Full Name Property
The Setter Method
Exercise 80: Writing a Setter Method
Validation via the Setter Method
Inheritance
The DRY Principle Revisited
Single Inheritance
Exercise 81: Inheriting from the Person Class
Sub-Classing Classes from Python Packages
Exercise 82: Sub-Classing the datetime.date Class
Overriding Methods
Calling the Parent Method with super()
Exercise 83: Overriding Methods Using super()
Multiple Inheritance
Exercise 84: Creating a Consultation Appointment System
Method Resolution Order
Activity 14: Creating Classes and Inheriting from a Parent Class
Summary
6. The Standard Library
Introduction
The Importance of the Standard Library
High-Level Modules
Lower-Level Modules
Knowing How to Navigate in the Standard Library
Exercise 85: Using the dataclass Module
Exercise 86: Extending the echo.py Example
Dates and Times
Exercise 87: Comparing datetime across Time Zones
Exercise 88: Calculating the Time Delta between Two datetime Objects
Exercise 89: Calculating the Unix Epoch Time
Activity 15: Calculating the Time Elapsed to Run a Loop
Interacting with the OS
OS Information
Exercise 90: Inspecting the Current Process Information
Using pathlib
Exercise 91: Using the glob Pattern to List Files within a Directory
Listing All Hidden Files in Your Home Directory
Using the subprocess Module
Exercise 92: Customizing Child Processes with env vars
Activity 16: Testing Python Code
Logging
Using Logging
Logger Object
Exercise 93: Using a logger Object
Logging in warning, error, and fatal Categories
Configuring the Logging Stack
Exercise 94: Configuring the Logging Stack
Collections
Counters
Exercise 95: Counting Words in a Text Document
defaultdict
Exercise 96: Refactoring Code with defaultdict
ChainMap
Functools
Caching with functools.lru_cache
Exercise 97: Using lru_cache to Speed Up Our Code
Partial
Exercise 98: Creating a print Function That Writes to stderr
Activity 17: Using partial on class Methods
Summary
7. Becoming Pythonic
Introduction
Using List Comprehensions
Exercise 99: Introducing List Comprehensions
Exercise 100: Using Multiple Input Lists
Activity 18: Building a Chess Tournament
Set and Dictionary Comprehensions
Exercise 101: Using Set Comprehensions
Exercise 102: Using Dictionary Comprehensions
Activity 19: Building a Scorecard Using Dictionary Comprehensions and Multiple Lists
Default Dictionary
Exercise 103: Adopting a Default Dict
Iterators
Exercise 104: The Simplest Iterator
Exercise 105: A Custom Iterator
Exercise 106: Controlling the Iteration
Itertools
Exercise 107: Using Infinite Sequences and takewhile
Exercise 108: Turning a Finite Sequence into an Infinite One, and Back Again
Generators
Exercise 109: Generating a Sieve
Activity 20: Using Random Numbers to Find the Value of Pi
Regular Expressions
Exercise 110: Matching Text with Regular Expressions
Exercise 111: Using Regular Expressions to Replace Text
Activity 21: Regular Expressions
Summary
8. Software Development
Introduction
Debugging
Exercise 112: Debugging a Salary Calculator
Activity 22: Debugging Sample Python Code for an Application
Automated Testing
Test Categorization
Test Coverage
Writing Tests in Python with Unit Testing
Exercise 113: Checking Sample Code with Unit Testing
Writing a Test with pytest
Creating a PIP Package
Exercise 114: Creating a Distribution That Includes Multiple Files within a Package
Adding More Information to Your Package
Creating Documentation the Easy Way
Docstrings
Using Sphinx
Exercise 115: Documenting a Divisible Code File
More Complex Documentation
Source Management
Repository
Commit
Staging Area
Undoing Local Changes
History
Ignoring Files
Exercise 116: Making a Change in CPython Using git
Summary
9. Practical Python – Advanced Topics
Introduction
Developing Collaboratively
Exercise 117: Writing Python on GitHub as a Team
Dependency Management
Virtual Environments
Exercise 118: Creating and Setting Up a conda Virtual Environment to Install numpy and pandas
Saving and Sharing Virtual Environments
Exercise 119: Sharing Environments between a conda Server and Your Local System
Deploying Code into Production
Exercise 120: Dockerizing Your Fizzbuzz Tool
Multiprocessing
Multiprocessing with execnet
Exercise 121: Working with execnet to Execute a Simple Python Squaring Program
Multiprocessing with the Multiprocessing Package
Exercise 122: Using the Multiprocessing Package to Execute a Simple Python Program
Multiprocessing with the Threading Package
Exercise 123: Using the Threading Package
Parsing Command-Line Arguments in Scripts
Exercise 124: Introducing argparse to Accept Input from the User
Positional Arguments
Exercise 125: Using Positional Arguments to Accept Source and Destination Inputs from a User
Performance and Profiling
Changing Your Python
PyPy
Exercise 126: Using PyPy to Find the Time to Get a List of Prime Numbers
Cython
Exercise 127: Adopting Cython to Find the Time Taken to get a List of Prime Numbers
Profiling
Profiling with cProfile
Activity 23: Generating a List of Random Numbers in a Python Virtual Environment
Summary
10. Data Analytics with pandas and NumPy
Introduction
NumPy and Basic Stats
Exercise 128: Converting Lists to NumPy Arrays
Exercise 129: Calculating the Mean of the Test Score
Exercise 130: Finding the Median from a Collection of Income Data
Skewed Data and Outliers
Standard Deviation
Exercise 131: Finding the Standard Deviation from Income Data
Matrices
Exercise 132: Matrices
Computation Time for Large Matrices
Exercise 133: Creating an Array to Implement NumPy Computations
The pandas Library
Exercise 134: Using DataFrames to Manipulate Stored Student testscore Data
Exercise 135: DataFrame Computations with the Student testscore Data
Exercise 136: Computing DataFrames within DataFrames
New Rows and NaN
Exercise 137: Concatenating and Finding the Mean with Null Values for Our testscore Data
Cast Column Types
Data
Downloading Data
Downloading the Boston Housing Data from GitHub
Reading Data
Exercise 138: Reading and Viewing the Boston Housing Dataset
Exercise 139: Gaining Data Insights on the Boston Housing Dataset
Null Values
Exercise 140: Null Value Operations on the Dataset
Replacing Null Values
Visual Analysis
The matplotlib Library
Histograms
Exercise 141: Creating a Histogram Using the Boston Housing Dataset
Histogram Functions
Scatter Plots
Exercise 142: Creating a Scatter Plot for the Boston Housing Dataset
Correlation
Exercise 143: Correlation Values from the Dataset
Regression
Plotting a Regression Line
StatsModel Regression Output
Additional Models
Exercise 144: Box Plots
Violin Plots
Activity 24: Data Analysis to Find the Outliers in Pay versus the Salary Report in the UK Statistics Dataset
Summary
11. Machine Learning
Introduction
Introduction to Linear Regression
Simplify the Problem
From One to N-Dimensions
The Linear Regression Algorithm
Exercise 145: Using Linear Regression to Predict the Accuracy of the Median Values of Our Dataset
Linear Regression Function
Cross-Validation
Exercise 146: Using the cross_val_score Function to Get Accurate Results on the Dataset
Regularization: Ridge and Lasso
K-Nearest Neighbors, Decision Trees, and Random Forests
K-Nearest Neighbors
Exercise 147: Using K-Nearest Neighbors to Find the Median Value of the Dataset
Exercise 148: K-Nearest Neighbors with GridSearchCV to Find the Optimal Number of Neighbors
Decision Trees and Random Forests
Exercise 149: Decision Trees and Random Forests
Random Forest Hyperparameters
Exercise 150: Random Forest Tuned to Improve the Prediction on Our Dataset
Classification Models
Exercise 151: Preparing the Pulsar Dataset and Checking for Null Values
Logistic Regression
Exercise 152: Using Logistic Regression to Predict Data Accuracy
Other Classifiers
Naive Bayes
Exercise 153: Using GaussianNB, KneighborsClassifier, DecisionTreeClassifier, and RandomForestClassifier to Predict Accuracy in Our Dataset
Confusion Matrix
Exercise 154: Finding the Pulsar Percentage from the Dataset
Exercise 155: Confusion Matrix and Classification Report for the Pulsar Dataset
Boosting Methods
Exercise 156: Using AdaBoost to Predict the Best Optimal Values
Activity 25: Using Machine Learning to Predict Customer Return Rate Accuracy
Summary
Appendix
1. Vital Python – Math, Strings, Conditionals, and Loops
Activity 1: Assigning Values to Variables
Activity 2: Finding a Solution Using Pythagorean Theorem in Python
Activity 3: Using the input() Function to Rate Your Day
Activity 4: Finding the Least Common Multiple (LCM)
Activity 5: Building Conversational Bots Using Python
2. Python Structures
Activity 6: Using a Nested List to Store Employee Data
Activity 7: Storing Company Employee Table Data Using a List and a Dictionary
3. Executing Python – Programs, Algorithms, Functions
Activity 8: What's the Time?
Activity 9: Formatting Customer Names
Activity 10: The Fibonacci Function with an Iteration
Activity 11: The Fibonacci Function with Recursion
Activity 12: The Fibonacci Function with Dynamic Programming
4. Extending Python, Files, Errors, and Graphs
Activity 13: Visualizing the Titanic Dataset Using a Pie Chart and Bar Plots
5. Constructing Python – Classes and Methods
Activity 14: Creating Classes and Inheriting from a Parent Class
Solution:
6. The Standard Library
Activity 15: Calculating the Time Elapsed to Run a Loop
Activity 16: Testing Python Code
Activity 17: Using partial on class Methods
Wrong Assumptions with Date and Time
7. Becoming Pythonic
Activity 18: Building a Chess Tournament
Activity 19: Building a Scorecard Using Dictionary Comprehensions and Multiple Lists
Activity 20: Using Random Numbers to Find the Value of Pi
Activity 21: Regular Expressions
8. Software Development
Activity 22: Debugging Sample Python Code for an Application
9. Practical Python – Advanced Topics
Activity 23: Generating a List of Random Numbers in a Python Virtual Environment
10. Data Analytics with pandas and NumPy
Activity 24: Data Analysis to Find the Outliers in Pay versus the Salary Report in the UK Statistics Dataset
11. Machine Learning
Activity 25: Using Machine Learning to Predict Customer Return Rate Accuracy
Search in book...
Toggle Font Controls
Playlists
Add To
Create new playlist
Name your new playlist
Playlist description (optional)
Cancel
Create playlist
Sign In
Email address
Password
Forgot Password?
Create account
Login
or
Continue with Facebook
Continue with Google
Sign Up
Full Name
Email address
Confirm Email Address
Password
Login
Create account
or
Continue with Facebook
Continue with Google
Next
Next Chapter
C13963_FM_Final_SZ_ePub
Add Highlight
No Comment
..................Content has been hidden....................
You can't read the all page of ebook, please click
here
login for view all page.
Day Mode
Cloud Mode
Night Mode
Reset