Share E-Book

Learn Python Programming An in-depth introduction to the fundamentals of Python - Third Edition (Heinrich Kruger, Fabrizio Romano) (z-library.sk, 1lib.sk, z-lib.sk)

Author

,

Rating 4.0 AI initial rating

Log in to rate

Programming
Language English

Learn Python Programming, Third Edition is both a theoretical and practical introduction to Python, an extremely flexible and powerful programming language that can be applied to many disciplines. This book will make learning Python easy and give you a thorough understanding of the language. You'll learn how to write programs, build modern APIs, and work with data by using renowned Python data science libraries. This revised edition covers the latest updates on API management, packing applications, and testing. There is also broader coverage of context managers and an updated data science chapter. The book empowers you to take ownership of writing your software and become independent in fetching the resources you need. You will have a clear idea of where to go and how to build on what you have learned from the book. Through examples, the book explores a wide range of applications and concludes by building real-workd Python projects based on the concepts you have learned.

Format PDF
Size 7.2 MB
2
Views
(First 20 pages)

Registered users can read the full content for free

Register as a Gaohf Library member to read the complete e-book online for free and enjoy a better reading experience.

Page 1
(This page has no text content)
Page 2
Learn Python Programming Third Edition An in-depth introduction to the fundamentals of Python Fabrizio Romano Heinrich Kruger BIRMINGHAM—MUMBAI "Python" and the Python Logo are trademarks of the Python Software Foundation.
Page 3
Learn Python Programming Third Edition Copyright © 2021 Packt Publishing All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, without the prior written permission of the publisher, except in the case of brief quotations embedded in critical articles or reviews. Every effort has been made in the preparation of this book to ensure the accuracy of the information presented. However, the information contained in this book is sold without warranty, either express or implied. Neither the authors, nor Packt Publishing or its dealers and distributors, will be held liable for any damages caused or alleged to have been caused directly or indirectly by this book. Packt Publishing has endeavored to provide trademark information about all of the companies and products mentioned in this book by the appropriate use of capitals. However, Packt Publishing cannot guarantee the accuracy of this information. Producer: Tushar Gupta Acquisition Editor – Peer Reviews: Suresh Jain, Saby Dsilva Project Editor: Namrata Katare Development Editor: Lucy Wan Copy Editor: Safis Editing Technical Editor: Aditya Sawant Proofreader: Safis Editing Indexer: Tejal Daruwale Soni Presentation Designer: Pranit Padwal First published: December 2015 Second edition: June 2018 Third edition: October 2021 Production reference: 3160223 Published by Packt Publishing Ltd. Livery Place 35 Livery Street Birmingham B3 2PB, UK. ISBN 978-1-80181-509-3 www.packt.com
Page 4
"To Elisa, the love of my lives, and to all those who gift the world their beautiful smiles." Fabrizio Romano "To my wife, Debi, without whose love, support, and endless patience I would not have been able to do this." Heinrich Kruger
Page 5
Contributors About the authors Fabrizio Romano was born in Italy in 1975. He holds a master's degree in Computer Science Engineering from the University of Padova. He's been working as a professional software developer since 1999. Fabrizio has been part of Sohonet's Product Team since 2016. In 2020, the Television Academy honored them with an Emmy Award in Engineering Development for advancing remote collaboration. I would like to thank everyone at Packt, and the reviewers, who helped us in making this book a success. I also want to thank Heinrich Kruger and Tom Viner for joining me in this adventure. My deepest gratitude goes to my wife-to-be, Elisa, who never made me feel like I was neglecting her, even though I was. Thank you for your love and support. Heinrich Kruger was born in South Africa in 1981. He holds a master's degree in Computer Science from Utrecht University in the Netherlands. He has been working as a professional software developer since 2014 and has worked alongside Fabrizio in the Product Team at Sohonet since 2017. I want to thank Fabrizio for asking me to help him with this book. It's been a great experience working with you, my friend. I would also like to thank Tom Viner and Dong-hee Na for their helpful comments, as well as everyone at Packt who helped us along the way. Most of all, I thank my wife, Debi, for all her love, encouragement, and support.
Page 6
About the reviewers Tom Viner is a principal software developer living in London. He has over 13 years' experience in building web applications and has been using Python and Django for 10 years. He has special interests in open-source software, web security, and test-driven development. I would like to thank Fabrizio Romano and Heinrich Kruger for inviting me to review this book. Dong-hee Na is a software engineer and an open-source enthusiast. He works at Line Corporation as a backend engineer. He has professional experience in machine learning projects based on Python and C++. As for his open-source work, he focuses on the compiler and interpreter area, especially for Python-related projects. He has been a CPython core developer since 2020.
Page 7
(This page has no text content)
Page 8
[ v ] Table of Contents Preface xv Chapter 1: A Gentle Introduction to Python 1 A proper introduction 3 Enter the Python 5 About Python 5 Portability 5 Coherence 5 Developer productivity 6 An extensive library 6 Software quality 6 Software integration 6 Satisfaction and enjoyment 7 What are the drawbacks? 7 Who is using Python today? 8 Setting up the environment 8 Python 2 versus Python 3 8 Installing Python 9 Setting up the Python interpreter 10 About virtual environments 11 Your first virtual environment 13 Installing third-party libraries 15 Your friend, the console 16 How to run a Python program 17 Running Python scripts 17 Running the Python interactive shell 18 Running Python as a service 19
Page 9
Table of Contents [ vi ] Running Python as a GUI application 19 How is Python code organized? 20 How do we use modules and packages? 22 Python's execution model 24 Names and namespaces 24 Scopes 26 Objects and classes 30 Guidelines for writing good code 33 Python culture 34 A note on IDEs 35 Summary 36 Chapter 2: Built-In Data Types 37 Everything is an object 38 Mutable or immutable? That is the question 39 Numbers 40 Integers 40 Booleans 43 Real numbers 44 Complex numbers 46 Fractions and decimals 46 Immutable sequences 48 Strings and bytes 48 Encoding and decoding strings 49 Indexing and slicing strings 50 String formatting 51 Tuples 52 Mutable sequences 54 Lists 54 Bytearrays 57 Set types 59 Mapping types: dictionaries 61 Data types 66 Dates and times 66 The standard library 66 Third-party libraries 71 The collections module 72 namedtuple 72 defaultdict 74 ChainMap 75 Enums 76 Final considerations 77 Small value caching 77
Page 10
Table of Contents [ vii ] How to choose data structures 78 About indexing and slicing 79 About names 81 Summary 81 Chapter 3: Conditionals and Iteration 83 Conditional programming 84 A specialized else: elif 85 The ternary operator 87 Looping 88 The for loop 89 Iterating over a range 89 Iterating over a sequence 90 Iterators and iterables 91 Iterating over multiple sequences 93 The while loop 95 The break and continue statements 98 A special else clause 100 Assignment expressions 102 Statements and expressions 102 Using the walrus operator 103 A word of warning 104 Putting all this together 105 A prime generator 105 Applying discounts 107 A quick peek at the itertools module 111 Infinite iterators 111 Iterators terminating on the shortest input sequence 112 Combinatoric generators 113 Summary 113 Chapter 4: Functions, the Building Blocks of Code 115 Why use functions? 116 Reducing code duplication 117 Splitting a complex task 117 Hiding implementation details 118 Improving readability 119 Improving traceability 120 Scopes and name resolution 121 The global and nonlocal statements 122 Input parameters 124 Argument-passing 125
Page 11
Table of Contents [ viii ] Assignment to parameter names 126 Changing a mutable object 126 Passing arguments 128 Positional arguments 128 Keyword arguments 128 Iterable unpacking 129 Dictionary unpacking 129 Combining argument types 130 Defining parameters 131 Optional parameters 132 Variable positional parameters 132 Variable keyword parameters 133 Positional-only parameters 135 Keyword-only parameters 137 Combining input parameters 137 More signature examples 139 Avoid the trap! Mutable defaults 140 Return values 141 Returning multiple values 143 A few useful tips 144 Recursive functions 145 Anonymous functions 146 Function attributes 148 Built-in functions 149 Documenting your code 149 Importing objects 151 Relative imports 153 One final example 153 Summary 154 Chapter 5: Comprehensions and Generators 157 The map, zip, and filter functions 159 map 159 zip 162 filter 163 Comprehensions 164 Nested comprehensions 166 Filtering a comprehension 167 Dictionary comprehensions 169 Set comprehensions 170 Generators 170 Generator functions 171 Going beyond next 174 The yield from expression 178
Page 12
Table of Contents [ ix ] Generator expressions 178 Some performance considerations 181 Don't overdo comprehensions and generators 184 Name localization 188 Generation behavior in built-ins 190 One last example 190 Summary 192 Chapter 6: OOP, Decorators, and Iterators 195 Decorators 195 A decorator factory 202 Object-oriented programming (OOP) 204 The simplest Python class 205 Class and object namespaces 206 Attribute shadowing 207 The self argument 208 Initializing an instance 209 OOP is about code reuse 210 Inheritance and composition 210 Accessing a base class 215 Multiple inheritance 218 Method resolution order 220 Class and static methods 223 Static methods 223 Class methods 225 Private methods and name mangling 227 The property decorator 229 The cached_property decorator 231 Operator overloading 233 Polymorphism – a brief overview 234 Data classes 235 Writing a custom iterator 236 Summary 237 Chapter 7: Exceptions and Context Managers 239 Exceptions 240 Raising exceptions 242 Defining your own exceptions 242 Tracebacks 242 Handling exceptions 243 Not only for errors 248 Context managers 249 Class-based context managers 251
Page 13
Table of Contents [ x ] Generator-based context managers 253 Summary 255 Chapter 8: Files and Data Persistence 257 Working with files and directories 258 Opening files 258 Using a context manager to open a file 260 Reading and writing to a file 260 Reading and writing in binary mode 261 Protecting against overwriting an existing file 262 Checking for file and directory existence 263 Manipulating files and directories 263 Manipulating pathnames 266 Temporary files and directories 267 Directory content 268 File and directory compression 269 Data interchange formats 270 Working with JSON 271 Custom encoding/decoding with JSON 273 I/O, streams, and requests 278 Using an in-memory stream 278 Making HTTP requests 279 Persisting data on disk 282 Serializing data with pickle 283 Saving data with shelve 285 Saving data to a database 286 Summary 293 Chapter 9: Cryptography and Tokens 295 The need for cryptography 295 Useful guidelines 296 Hashlib 296 HMAC 300 Secrets 301 Random numbers 301 Token generation 302 Digest comparison 304 JSON Web Tokens 304 Registered claims 307 Time-related claims 308 Authentication-related claims 309 Using asymmetric (public key) algorithms 311 Useful references 312 Summary 313
Page 14
Table of Contents [ xi ] Chapter 10: Testing 315 Testing your application 316 The anatomy of a test 318 Testing guidelines 319 Unit testing 320 Writing a unit test 321 Mock objects and patching 323 Assertions 323 Testing a CSV generator 323 Boundaries and granularity 333 Testing the export function 334 Final considerations 337 Test-driven development 339 Summary 341 Chapter 11: Debugging and Profiling 343 Debugging techniques 344 Debugging with print 344 Debugging with a custom function 345 Using the Python debugger 347 Inspecting logs 350 Other techniques 353 Reading tracebacks 354 Assertions 354 Where to find information 355 Troubleshooting guidelines 355 Where to inspect 355 Using tests to debug 356 Monitoring 356 Profiling Python 357 When to profile 360 Measuring execution time 361 Summary 362 Chapter 12: GUIs and Scripting 365 First approach: scripting 368 The imports 368 Parsing arguments 369 The business logic 371 Second approach: a GUI application 375 The imports 378 The layout logic 378 The business logic 382 Fetching the web page 383
Page 15
Table of Contents [ xii ] Saving the images 385 Alerting the user 388 How can we improve the application? 389 Where do we go from here? 390 The turtle module 391 wxPython, Kivy, and PyQt 391 The principle of least astonishment 391 Threading considerations 392 Summary 392 Chapter 13: Data Science in Brief 393 IPython and Jupyter Notebook 394 Using Anaconda 397 Starting a Notebook 397 Dealing with data 398 Setting up the Notebook 398 Preparing the data 399 Cleaning the data 403 Creating the DataFrame 405 Unpacking the campaign name 408 Unpacking the user data 409 Cleaning everything up 413 Saving the DataFrame to a file 414 Visualizing the results 415 Where do we go from here? 422 Summary 423 Chapter 14: Introduction to API Development 425 What is the Web? 426 How does the Web work? 426 Response status codes 428 Type hinting: An overview 428 Why type hinting? 430 Type hinting in a nutshell 431 APIs: An introduction 433 What is an API? 434 What is the purpose of an API? 434 API protocols 435 API data-exchange formats 436 The railway API 436 Modeling the database 438 Main setup and configuration 444 Adding settings 445
Page 16
Table of Contents [ xiii ] Station endpoints 446 Reading data 446 Creating data 453 Updating data 457 Deleting data 460 User authentication 461 Documenting the API 464 Consuming an API 465 Calling the API from Django 466 Where do we go from here? 473 Summary 474 Chapter 15: Packaging Python Applications 477 The Python Package Index 478 The train schedule project 480 Packaging with setuptools 485 Required files 485 pyproject.toml 486 License 487 README 487 Changelog 487 setup.cfg 488 setup.py 488 MANIFEST.in 490 Package metadata 490 Accessing metadata in your code 494 Defining the package contents 497 Accessing package data files 498 Specifying dependencies 499 Entry points 502 Building and publishing packages 503 Building 504 Publishing 505 Advice for starting new projects 508 Alternative tools 508 Further reading 509 Summary 510 Why subscribe? 511 Other Books You May Enjoy 513 Index 517
Page 17
(This page has no text content)
Page 18
[ xv ] Preface The first edition of this book came out on the day of my 40th birthday. It feels like yesterday, but actually it was 6 years ago. In a few weeks, the book became a top seller, and to this day that translates into lovely messages and emails I get from readers all over the world. A couple of years later, I wrote a second edition. That turned out to be a better book, which kept growing in sales and popularity. And now here we are, at the third edition, and this time it won't just be me narrating the story, because for this edition I have been joined by my dear friend and colleague, Heinrich Kruger. Together, we have reworked the book's structure. We removed what we felt didn't fit anymore, and added what we thought would benefit you the most. We have shuffled things around, amended old chapters, and written new ones. We have made sure that both our contributions and our best ideas are on each page you will read. We are both very happy about this. I always wanted to work on a project like this with Heinrich, for whom I have felt enormous respect since I got to know him. He has brought to this book his unique perspective, his incredible talent as a software developer, and he's helped me with my English too! Everything has been updated to Python 3.9, but of course most of the code will still work with any recent version of Python 3. The scary chapter about concurrency is gone, and the one on Web programming has been replaced with another which introduces the concept of APIs. We have also added a whole new chapter about packaging Python applications, which we feel is the perfect way to close the book. We are confident this edition is much better than the previous ones; it's more mature, it tells a better story, and it will take you places.
Page 19
Preface [ xvi ] One thing I am particularly happy about is that the soul of the book is still the same. This is not just a book about Python. This is, first and foremost, a book about programming. A book that aims to convey to you as much information as possible, and sometimes, for practical reasons, it does so by pointing you to the Web to dig deeper, to investigate further. It is designed to last. It expresses concepts and information in a way that should stand the test of time, for as long as possible. We have put in a great amount of thinking to achieve that. And it will require you to work hard. The code is available for you to download, and we do encourage you to play with it, expand it, change it, break it, and see things for yourself. We want you to develop critical thinking. We want you to be independent, empowered. That is the soul of the book, and our hope is that wherever you are in your journey, it will help you go further, become a better programmer, in any way that is possible. When we received the drafts from the second edition to start working on the third one, I was surprised to notice I could not find myself in those pages. Those pages have shown me how my thinking, and therefore my writing, has changed, in the past few years. Change is interwoven in the very fabric of this universe. Everything changes, all the time. So, our wish for you is that you never fixate on opinions, that you never grow stale. Instead, we hope our work, and the way we present it to you, will help you stay flexible, smart, pragmatic, and adaptable. We wish you good luck! And don't forget to enjoy the ride! Who this book is for This book is for people who have some programming experience, but not necessarily with Python. Some knowledge of basic programming concepts will come in handy, although it is not a requirement. Even if you already have some experience with Python, this book can still be useful to you, both as a reference to Python's fundamentals, and for providing a wide range of considerations and suggestions collected over four combined decades of experience.
Page 20
Preface [ xvii ] What this book covers Chapter 1, A Gentle Introduction to Python, introduces you to fundamental programming concepts and constructs of the Python language. It also guides you through getting Python up and running on your computer. Chapter 2, Built-In Data Types, introduces you to Python built-in data types. Python has a very rich set of native data types, and this chapter will give you a description and examples for each of them. Chapter 3, Conditionals and Iteration, teaches you how to control the flow of code by inspecting conditions, applying logic, and performing loops. Chapter 4, Functions, the Building Blocks of Code, teaches you how to write functions. Functions are essential to code reuse, to reducing debugging time, and, in general, to writing higher quality code. Chapter 5, Comprehensions and Generators, introduces you to the functional aspects of Python programming. This chapter teaches you how to write comprehensions and generators, which are powerful tools that you can use to write faster, more concise code, and save memory. Chapter 6, OOP, Decorators, and Iterators, teaches you the basics of object-oriented programming with Python. It shows you the key concepts and all the potentials of this paradigm. It also shows you one of the most useful features of the language: decorators. Chapter 7, Exceptions and Context Managers, introduces the concept of exceptions, which represent errors that occur in applications, and how to handle them. It also covers context managers, which are very useful when dealing with resources. Chapter 8, Files and Data Persistence, teaches you how to deal with files, streams, data interchange formats, and databases. Chapter 9, Cryptography and Tokens, touches upon the concepts of security, hashes, encryption, and tokens, which are essential for writing secure software. Chapter 10, Testing, teaches you the fundamentals of testing, and guides you through a few examples on how to test your code, in order to make it more robust, fast, and reliable. Chapter 11, Debugging and Profiling, shows you the main methods for debugging and profiling code and some examples of how to apply them.
The above is a preview of the first 20 pages. Register to read the complete e-book.

Recommended for You

Loading recommended books...
Failed to load, please try again later

Tip the Site

Scan the WeChat Pay or Alipay code to tip. No login required.

WeChat Pay
Alipay
← Back to List