The Python Workshop: A Practical, No-Nonsense Introduction To Python Development

This document was uploaded by one of our users. The uploader already confirmed that they had the permission to publish it. If you are author/publisher or own the copyright of this documents, please report to us by using this DMCA report form.

Simply click on the Download Book button.

Yes, Book downloads on Ebookily are 100% Free.

Sometimes the book is free on Amazon As well, so go ahead and hit "Search on Amazon"

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.

Author(s): Andrew Bird, Lau Cher Han, Mario Corchero Jiménez, Graham Lee, Corey Wade
Publisher: Packt Publishing
Year: 2019

Language: English
Commentary: Code Repository --- https://github.com/TrainingByPackt/The-Python-Workshop
Pages: 606
Tags: Python

Cover......Page 1
FM......Page 2
Copyright......Page 3
Table of Contents......Page 4
Preface......Page 24
Chapter 1: Vital Python – Math, Strings, Conditionals, and Loops......Page 34
Introduction......Page 35
Vital Python......Page 36
Python as a Calculator......Page 37
Basic Math Operations......Page 39
Order of Operations......Page 41
Spacing in Python......Page 42
Exercise 2: Integer and Float Types......Page 43
Variable Assignment......Page 45
Exercise 3: Assigning Variables......Page 46
Activity 1: Assigning Values to Variables......Page 47
Variable Names......Page 48
Exercise 4: Variable Names......Page 49
Exercise 5: Multiple Variables in Python......Page 50
Exercise 6: Comments in Python......Page 51
Activity 2: Finding a Solution Using the Pythagorean Theorem in Python......Page 52
Strings: Concatenation, Methods, and input()......Page 53
Exercise 7: String Error Syntax......Page 54
The print() Function......Page 56
Exercise 8: Displaying Strings......Page 57
Exercise 9: String Concatenation......Page 58
Comma Separators......Page 59
The len() Function......Page 60
Exercise 10: String Methods......Page 61
Casting......Page 62
Exercise 11: Types and Casting......Page 63
Exercise 12: The input() Function......Page 64
Activity 3: Using the input() Function to Rate Your Day......Page 65
Indexing......Page 66
Slicing......Page 68
Booleans and Conditionals......Page 69
Exercise 13: Boolean Variables......Page 70
Logical Operators......Page 71
Exercise 14: Comparison Operators......Page 73
Comparing Strings......Page 75
The if Syntax......Page 76
Exercise 16: Using the if Syntax......Page 77
Exercise 17: Using the if-else Syntax......Page 78
The elif Statement......Page 79
Loops......Page 80
The while Loops......Page 81
break......Page 83
Activity 4: Finding the Least Common Multiple (LCM)......Page 84
Exercise 18: Calculating Perfect Squares......Page 85
Exercise 19: Real Estate Offer......Page 87
Exercise 20: Using for Loops......Page 88
The continue Keyword......Page 91
Activity 5: Building Conversational Bots Using Python......Page 93
Summary......Page 94
Chapter 2: Python Structures......Page 96
Introduction......Page 97
Exercise 21: Working with Python Lists......Page 98
Matrices as Nested Lists......Page 99
Exercise 22: Using a Nested List to Store Data from a Matrix......Page 100
Activity 6: Using a Nested List to Store Employee Data......Page 102
Exercise 23: Implementing Matrix Operations (Addition and Subtraction)......Page 103
Exercise 24: Implementing Matrix Operations (Multiplication)......Page 105
Exercise 25: Basic List Operations......Page 107
Exercise 26: Accessing an Item from Shopping List Data......Page 108
Exercise 27: Adding Items to Our Shopping List......Page 110
Dictionary Keys and Values......Page 111
Exercise 28: Using a Dictionary to Store a Movie Record......Page 113
Activity 7: Storing Company Employee Table Data Using a List and a Dictionary......Page 115
Exercise 29: Using the zip() Method to Manipulate Dictionaries......Page 116
Exercise 30: Accessing a Dictionary Using Dictionary Methods......Page 117
Tuples......Page 118
Exercise 31: Exploring Tuple Properties in Our Shopping List......Page 119
Exercise 32: Using Sets in Python......Page 121
Set Operations......Page 123
Exercise 33: Implementing Set Operations......Page 124
Summary......Page 127
Chapter 3: Executing Python – Programs, Algorithms, and Functions......Page 130
Python Scripts and Modules......Page 131
Exercise 34: Writing and Executing Our First Script......Page 132
Exercise 35: Writing and Importing Our First Module......Page 133
Exercise 36: Adding a Docstring to my_module.py......Page 134
Imports......Page 135
The if __name__ == "__main__" Statement......Page 137
Activity 8: What's the Time?......Page 139
Exercise 38: The Maximum Number......Page 140
Time Complexity......Page 141
Sorting Algorithms......Page 143
Searching Algorithms......Page 145
Exercise 40: Linear Search in Python......Page 146
Exercise 41: Binary Search in Python......Page 148
Exercise 42: Defining and Calling the Function in Shell......Page 149
Exercise 44: Importing and Calling the Function from the Shell......Page 150
Keyword Arguments......Page 151
Exercise 46: Defining the Function with Positional and Keyword Arguments......Page 152
Exercise 47: Using **kwargs......Page 153
Activity 9: Formatting Customer Names......Page 154
Iterative Functions......Page 155
Exercise 49: Exiting the Function During the for Loop......Page 156
Activity 10: The Fibonacci Function with an Iteration......Page 157
Recursive Functions......Page 158
Exercise 50: Recursive Countdown......Page 159
Exercise 51: Factorials with Iteration and Recursion......Page 160
Activity 11: The Fibonacci Function with Recursion......Page 161
Exercise 52: Summing Integers......Page 162
Exercise 53: Timing Your Code......Page 164
Activity 12: The Fibonacci Function with Dynamic Programming......Page 165
Helper Functions......Page 166
Don't Repeat Yourself......Page 167
Exercise 54: Helper Currency Conversion......Page 168
Variables......Page 169
Defining inside versus outside a Function......Page 170
The Nonlocal Keyword......Page 172
Lambda Functions......Page 173
Mapping with Lambda Functions......Page 174
Exercise 56: Mapping with a Logistic Transform......Page 175
Exercise 57: Using the Filter Lambda......Page 176
Summary......Page 177
Chapter 4: Extending Python, Files, Errors, and Graphs......Page 180
Exercise 58: Reading a Text File Using Python......Page 181
Exercise 59: Reading Partial Content from a Text File......Page 184
Writing Files......Page 185
Exercise 60: Creating and Writing Content to Files to Record the Date and Time in a Text File......Page 186
Preparing for Debugging (Defensive Code)......Page 187
Writing Assertions......Page 188
Exercise 61: Working with Incorrect Parameters to Find the Average Using Assert with Functions......Page 189
Plotting Techniques......Page 190
Exercise 62: Drawing a Scatter Plot to Study the Data between Ice Cream Sales versus Temperature......Page 191
Exercise 63: Drawing a Line Chart to Find the Growth in Stock Prices......Page 193
Exercise 64: Plotting Bar Plots to Grade Students......Page 196
Exercise 65: Creating a Pie Chart to Visualize the Number of Votes in a School......Page 199
Exercise 66: Generating a Heatmap to Visualize the Grades of Students......Page 200
Exercise 67: Generating a Density Plot to Visualize the Score of Students......Page 203
Exercise 68: Creating a Contour Plot......Page 205
Extending Graphs......Page 206
Exercise 69: Generating 3D plots to Plot a Sine Wave......Page 208
The Don'ts of Plotting Graphs......Page 209
Cherry Picking Data......Page 210
Wrong Graph, Wrong Context......Page 211
Activity 13: Visualizing the Titanic Dataset Using a Pie Chart and Bar Plots......Page 212
Summary......Page 214
Chapter 5: Constructing Python – Classes and Methods......Page 216
Classes and Objects......Page 217
Exercise 70: Exploring Strings......Page 219
Defining Classes......Page 221
Exercise 71: Creating a Pet Class......Page 222
The __init__ method......Page 223
Exercise 72: Creating a Circle Class......Page 224
Keyword Arguments......Page 225
Exercise 73: The Country Class with Keyword Arguments......Page 226
Instance Methods......Page 227
Exercise 74: Adding an Instance Method to Our Pet Class......Page 228
Adding Arguments to Instance Methods......Page 229
Exercise 75: Computing the Size of Our Country......Page 230
The __str__ method......Page 231
Exercise 76: Adding an __str__ Method to the Country Class......Page 233
Static Methods......Page 234
Exercise 77: Refactoring Instance Methods Using a Static Method......Page 235
Class Methods......Page 237
Exercise 78: Extending Our Pet Class with Class Methods......Page 238
Properties......Page 239
The Property Decorator......Page 240
Exercise 79: The Full Name Property......Page 241
The Setter Method......Page 242
Exercise 80: Writing a Setter Method......Page 243
Validation via the Setter Method......Page 244
The DRY Principle Revisited......Page 245
Single Inheritance......Page 246
Exercise 81: Inheriting from the Person Class......Page 247
Sub-Classing Classes from Python Packages......Page 248
Overriding Methods......Page 249
Calling the Parent Method with super()......Page 252
Exercise 83: Overriding Methods Using super()......Page 253
Exercise 84: Creating a Consultation Appointment System......Page 255
Method Resolution Order......Page 257
Activity 14: Creating Classes and Inheriting from a Parent Class......Page 259
Summary......Page 260
Chapter 6: The Standard Library......Page 262
The Importance of the Standard Library......Page 263
High-Level Modules......Page 264
Knowing How to Navigate in the Standard Library......Page 267
Exercise 85: Using the dataclass Module......Page 268
Exercise 86: Extending the echo.py Example......Page 270
Dates and Times......Page 272
Exercise 87: Comparing datetime across Time Zones......Page 274
Exercise 88: Calculating the Time Delta between Two datetime Objects......Page 276
Exercise 89: Calculating the Unix Epoch Time......Page 278
Activity 15: Calculating the Time Elapsed to Run a Loop......Page 281
Exercise 90: Inspecting the Current Process Information......Page 282
Using pathlib......Page 284
Exercise 91: Using the glob Pattern to List Files within a Directory......Page 286
Using the subprocess Module......Page 288
Exercise 92: Customizing Child Processes with env vars......Page 293
Activity 16: Testing Python Code......Page 295
Using Logging......Page 296
Logger Object......Page 298
Exercise 93: Using a logger Object......Page 299
Logging in warning, error, and fatal Categories......Page 300
Configuring the Logging Stack......Page 303
Exercise 94: Configuring the Logging Stack......Page 304
Exercise 95: Counting Words in a Text Document......Page 308
defaultdict......Page 310
Exercise 96: Refactoring Code with defaultdict......Page 311
ChainMap......Page 314
Caching with functools.lru_cache......Page 317
Exercise 97: Using lru_cache to Speed Up Our Code......Page 318
Partial......Page 322
Exercise 98: Creating a print Function That Writes to stderr......Page 323
Activity 17: Using partial on class Methods......Page 324
Summary......Page 326
Chapter 7: Becoming Pythonic......Page 328
Introduction......Page 329
Exercise 99: Introducing List Comprehensions......Page 330
Exercise 100: Using Multiple Input Lists......Page 333
Activity 18: Building a Chess Tournament......Page 334
Set and Dictionary Comprehensions......Page 335
Exercise 101: Using Set Comprehensions......Page 336
Exercise 102: Using Dictionary Comprehensions......Page 337
Activity 19: Building a Scorecard Using Dictionary Comprehensions and Multiple Lists......Page 338
Exercise 103: Adopting a Default Dict......Page 339
Exercise 104: The Simplest Iterator......Page 342
Exercise 105: A Custom Iterator......Page 344
Exercise 106: Controlling the Iteration......Page 345
Exercise 107: Using Infinite Sequences and takewhile......Page 347
Exercise 108: Turning a Finite Sequence into an Infinite One, and Back Again......Page 350
Exercise 109: Generating a Sieve......Page 351
Activity 20: Using Random Numbers to Find the Value of Pi......Page 352
Regular Expressions......Page 354
Exercise 110: Matching Text with Regular Expressions......Page 356
Activity 21: Regular Expressions......Page 357
Summary......Page 358
Chapter 8: Software Development......Page 360
Debugging......Page 361
Exercise 112: Debugging a Salary Calculator......Page 364
Activity 22: Debugging Sample Python Code for an Application......Page 372
Automated Testing......Page 373
Test Categorization......Page 374
Test Coverage......Page 375
Exercise 113: Checking Sample Code with Unit Testing......Page 376
Writing a Test with pytest......Page 378
Creating a PIP Package......Page 379
Exercise 114: Creating a Distribution That Includes Multiple Files within a Package......Page 381
Adding More Information to Your Package......Page 383
Docstrings......Page 384
Using Sphinx......Page 385
Exercise 115: Documenting a Divisible Code File......Page 386
More Complex Documentation......Page 389
Repository......Page 390
Commit......Page 391
Ignoring Files......Page 392
Exercise 116: Making a Change in CPython Using git......Page 393
Summary......Page 397
Chapter 9: Practical Python – Advanced Topics......Page 400
Developing Collaboratively......Page 401
Exercise 117: Writing Python on GitHub as a Team......Page 402
Dependency Management......Page 407
Exercise 118: Creating and Setting Up a conda Virtual Environment to Install numpy and pandas......Page 409
Exercise 119: Sharing Environments between a conda Server and Your Local System......Page 412
Deploying Code into Production......Page 413
Exercise 120: Dockerizing Your Fizzbuzz Tool......Page 415
Multiprocessing......Page 417
Exercise 121: Working with execnet to Execute a Simple Python Squaring Program......Page 419
Exercise 122: Using the Multiprocessing Package to Execute a Simple Python Program......Page 421
Multiprocessing with the Threading Package......Page 422
Exercise 123: Using the Threading Package......Page 423
Parsing Command-Line Arguments in Scripts......Page 424
Exercise 124: Introducing argparse to Accept Input from the User......Page 425
Exercise 125: Using Positional Arguments to Accept Source and Destination Inputs from a User......Page 427
Performance and Profiling......Page 428
PyPy......Page 429
Exercise 126: Using PyPy to Find the Time to Get a List of Prime Numbers......Page 430
Exercise 127: Adopting Cython to Find the Time Taken to get a List of Prime Numbers......Page 432
Profiling......Page 434
Profiling with cProfile......Page 435
Activity 23: Generating a List of Random Numbers in a Python Virtual Environment......Page 441
Summary......Page 443
Chapter 10: Data Analytics with pandas and NumPy......Page 446
NumPy and Basic Stats......Page 447
Exercise 128: Converting Lists to NumPy Arrays......Page 448
Exercise 129: Calculating the Mean of the Test Score......Page 449
Exercise 130: Finding the Median from a Collection of Income Data......Page 450
Standard Deviation......Page 451
Exercise 131: Finding the Standard Deviation from Income Data......Page 452
Matrices......Page 453
Exercise 132: Matrices......Page 454
Computation Time for Large Matrices......Page 456
Exercise 133: Creating an Array to Implement NumPy Computations......Page 457
Exercise 134: Using DataFrames to Manipulate Stored Student testscore Data......Page 462
Exercise 135: DataFrame Computations with the Student testscore Data......Page 464
Exercise 136: Computing DataFrames within DataFrames......Page 466
New Rows and NaN......Page 469
Exercise 137: Concatenating and Finding the Mean with Null Values for Our testscore Data......Page 470
Cast Column Types......Page 472
Reading Data......Page 473
Exercise 138: Reading and Viewing the Boston Housing Dataset......Page 474
Exercise 139: Gaining Data Insights on the Boston Housing Dataset......Page 476
Exercise 140: Null Value Operations on the Dataset......Page 478
Replacing Null Values......Page 481
The matplotlib Library......Page 482
Exercise 141: Creating a Histogram Using the Boston Housing Dataset......Page 483
Histogram Functions......Page 486
Exercise 142: Creating a Scatter Plot for the Boston Housing Dataset......Page 489
Correlation......Page 490
Exercise 143: Correlation Values from the Dataset......Page 491
Plotting a Regression Line......Page 493
StatsModel Regression Output......Page 495
Exercise 144: Box Plots......Page 496
Violin Plots......Page 497
Activity 24: Data Analysis to Find the Outliers in Pay versus the Salary Report in the UK Statistics Dataset......Page 498
Summary......Page 500
Chapter 11: Machine Learning......Page 502
Introduction......Page 503
Introduction to Linear Regression......Page 504
Simplify the Problem......Page 506
From One to N-Dimensions......Page 507
The Linear Regression Algorithm......Page 508
Exercise 145: Using Linear Regression to Predict the Accuracy of the Median Values of Our Dataset......Page 509
Linear Regression Function......Page 513
Exercise 146: Using the cross_val_score Function to Get Accurate Results on the Dataset......Page 514
Regularization: Ridge and Lasso......Page 516
K-Nearest Neighbors......Page 518
Exercise 147: Using K-Nearest Neighbors to Find the Median Value of the Dataset......Page 519
Exercise 148: K-Nearest Neighbors with GridSearchCV to Find the Optimal Number of Neighbors......Page 521
Decision Trees and Random Forests......Page 522
Exercise 149: Decision Trees and Random Forests......Page 523
Random Forest Hyperparameters......Page 524
Exercise 150: Random Forest Tuned to Improve the Prediction on Our Dataset......Page 525
Classification Models......Page 527
Exercise 151: Preparing the Pulsar Dataset and Checking for Null Values......Page 529
Logistic Regression......Page 531
Exercise 152: Using Logistic Regression to Predict Data Accuracy......Page 532
Naive Bayes......Page 533
Exercise 153: Using GaussianNB, KneighborsClassifier, DecisionTreeClassifier, and RandomForestClassifier to Predict Accuracy in Our Dataset......Page 534
Exercise 154: Finding the Pulsar Percentage from the Dataset......Page 535
Exercise 155: Confusion Matrix and Classification Report for the Pulsar Dataset......Page 539
Exercise 156: Using AdaBoost to Predict the Best Optimal Values......Page 542
Activity 25: Using Machine Learning to Predict Customer Return Rate Accuracy......Page 544
Summary......Page 545
Appendix......Page 548
Index......Page 602