The Python Workshop

Book description

Cut through the noise and get real results with a step-by-step approach to learning Python 3.X programming

Key Features

  • Ideal for the Python beginner who is getting started for the first time
  • A step-by-step Python tutorial with exercises and activities that help build key skills
  • Structured to let you progress at your own pace, on your own terms
  • Use your physical copy to redeem free access to the online interactive edition

Book Description

You already know you want to learn Python, and a smarter way to learn Python 3 is to learn by doing. The Python Workshop focuses on building up your practical skills so that you can work towards building up your machine learning skills as a data scientist, write scripts that help automate your life and save you time, or even create your own games and desktop applications. You'll learn from real examples that lead to real results.

Throughout The Python Workshop, you'll take an engaging step-by-step approach to understanding Python. You won't have to sit through any unnecessary theory. If you're short on time you can jump into a single exercise each day or spend an entire weekend learning about Python scripting. It's your choice. Learning on your terms, you'll build up and reinforce key skills in a way that feels rewarding.

Every physical copy of The Python Workshop unlocks access to the interactive edition. With videos detailing all exercises and activities, you'll always have a guided solution. You can also benchmark yourself against assessments, track progress, and receive free content updates. You'll even earn a secure credential that you can share and verify online upon completion. It's a premium learning experience that's included with your printed copy. To redeem, follow the instructions located at the start of your Python book.

Fast-paced and direct, The Python Workshop is the ideal companion for Python beginners. You'll build and iterate on your code like a software developer, learning along the way. This process means that you'll find that your new skills stick, embedded as best practice. A solid foundation for the years ahead.

What you will learn

  • Learn how to write clean and concise code with Python 3
  • Understand classes and object-oriented programming
  • Tackle entry-level data science and create engaging visualizations
  • Use Python to create responsive, modern web applications
  • Automate essential day-to-day tasks with Python scripts
  • Get started with predictive Python machine learning

Who this book is for

This book is designed for professionals, students, and hobbyists who want to learn Python and apply it to solve challenging real-world problems. Although this is a beginner's book, it will help if you already know standard programming topics, such as variables, if-else statements, and functions. Experience with another object-oriented program is beneficial, but not mandatory.

Table of contents

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

Product information

  • Title: The Python Workshop
  • Author(s): Andrew Bird, Dr. Lau Cher Han, Mario Corchero Jimenez, Graham Lee, Corey Wade
  • Release date: November 2019
  • Publisher(s): Packt Publishing
  • ISBN: 9781839218859