Learn Python Programming - Third Edition

Book description

Get up and running with Python 3.9 through concise tutorials and practical projects in this fully updated third edition

Key Features

  • Extensively revised with richer examples, Python 3.9 syntax, and new chapters on APIs and packaging and distributing Python code
  • Discover how to think like a Python programmer
  • Learn the fundamentals of Python through real-world projects in API development, GUI programming, and data science

Book Description

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, packaging 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-world Python projects based on the concepts you have learned.

What you will learn

  • Get Python up and running on Windows, Mac, and Linux
  • Write elegant, reusable, and efficient code in any situation
  • Avoid common pitfalls like duplication, complicated design, and over-engineering
  • Understand when to use the functional or object-oriented approach to programming
  • Build a simple API with FastAPI and program GUI applications with Tkinter
  • Get an initial overview of more complex topics such as data persistence and cryptography
  • Fetch, clean, and manipulate data, making efficient use of Python's built-in data structures

Who this book is for

This book is for everyone who wants to learn Python from scratch, as well as experienced programmers looking for a reference book. Prior knowledge of basic programming concepts will help you follow along, but it's not a prerequisite.

Table of contents

  1. Preface
    1. Who this book is for
    2. What this book covers
    3. To get the most out of this book
    4. Get in touch
  2. A Gentle Introduction to Python
    1. A proper introduction
    2. Enter the Python
    3. About Python
      1. Portability
      2. Coherence
      3. Developer productivity
      4. An extensive library
      5. Software quality
      6. Software integration
      7. Satisfaction and enjoyment
    4. What are the drawbacks?
    5. Who is using Python today?
    6. Setting up the environment
      1. Python 2 versus Python 3
    7. Installing Python
      1. Setting up the Python interpreter
      2. About virtual environments
      3. Your first virtual environment
      4. Installing third-party libraries
      5. Your friend, the console
    8. How to run a Python program
      1. Running Python scripts
      2. Running the Python interactive shell
      3. Running Python as a service
      4. Running Python as a GUI application
    9. How is Python code organized?
      1. How do we use modules and packages?
    10. Python's execution model
      1. Names and namespaces
      2. Scopes
      3. Objects and classes
    11. Guidelines for writing good code
    12. Python culture
    13. A note on IDEs
    14. Summary
  3. Built-In Data Types
    1. Everything is an object
    2. Mutable or immutable? That is the question
    3. Numbers
      1. Integers
      2. Booleans
      3. Real numbers
      4. Complex numbers
      5. Fractions and decimals
    4. Immutable sequences
      1. Strings and bytes
        1. Encoding and decoding strings
        2. Indexing and slicing strings
        3. String formatting
      2. Tuples
    5. Mutable sequences
      1. Lists
      2. Bytearrays
    6. Set types
    7. Mapping types: dictionaries
    8. Data types
      1. Dates and times
        1. The standard library
        2. Third-party libraries
      2. The collections module
        1. namedtuple
        2. defaultdict
        3. ChainMap
      3. Enums
    9. Final considerations
      1. Small value caching
      2. How to choose data structures
      3. About indexing and slicing
      4. About names
    10. Summary
  4. Conditionals and Iteration
    1. Conditional programming
      1. A specialized else: elif
      2. The ternary operator
    2. Looping
      1. The for loop
        1. Iterating over a range
        2. Iterating over a sequence
      2. Iterators and iterables
      3. Iterating over multiple sequences
      4. The while loop
      5. The break and continue statements
      6. A special else clause
    3. Assignment expressions
      1. Statements and expressions
      2. Using the walrus operator
      3. A word of warning
    4. Putting all this together
      1. A prime generator
      2. Applying discounts
    5. A quick peek at the itertools module
      1. Infinite iterators
      2. Iterators terminating on the shortest input sequence
      3. Combinatoric generators
    6. Summary
  5. Functions, the Building Blocks of Code
    1. Why use functions?
      1. Reducing code duplication
      2. Splitting a complex task
      3. Hiding implementation details
      4. Improving readability
      5. Improving traceability
    2. Scopes and name resolution
      1. The global and nonlocal statements
    3. Input parameters
      1. Argument-passing
      2. Assignment to parameter names
      3. Changing a mutable object
      4. Passing arguments
        1. Positional arguments
        2. Keyword arguments
        3. Iterable unpacking
        4. Dictionary unpacking
        5. Combining argument types
      5. Defining parameters
        1. Optional parameters
        2. Variable positional parameters
        3. Variable keyword parameters
        4. Positional-only parameters
        5. Keyword-only parameters
        6. Combining input parameters
        7. More signature examples
        8. Avoid the trap! Mutable defaults
    4. Return values
      1. Returning multiple values
    5. A few useful tips
    6. Recursive functions
    7. Anonymous functions
    8. Function attributes
    9. Built-in functions
    10. Documenting your code
    11. Importing objects
      1. Relative imports
    12. One final example
    13. Summary
  6. Comprehensions and Generators
    1. The map, zip, and filter functions
      1. map
      2. zip
      3. filter
    2. Comprehensions
      1. Nested comprehensions
      2. Filtering a comprehension
      3. Dictionary comprehensions
      4. Set comprehensions
    3. Generators
      1. Generator functions
      2. Going beyond next
      3. The yield from expression
      4. Generator expressions
    4. Some performance considerations
    5. Don't overdo comprehensions and generators
    6. Name localization
    7. Generation behavior in built-ins
    8. One last example
    9. Summary
  7. OOP, Decorators, and Iterators
    1. Decorators
      1. A decorator factory
    2. Object-oriented programming (OOP)
      1. The simplest Python class
      2. Class and object namespaces
      3. Attribute shadowing
      4. The self argument
      5. Initializing an instance
      6. OOP is about code reuse
        1. Inheritance and composition
      7. Accessing a base class
      8. Multiple inheritance
        1. Method resolution order
      9. Class and static methods
        1. Static methods
        2. Class methods
      10. Private methods and name mangling
      11. The property decorator
      12. The cached_property decorator
      13. Operator overloading
      14. Polymorphism – a brief overview
      15. Data classes
    3. Writing a custom iterator
    4. Summary
  8. Exceptions and Context Managers
    1. Exceptions
      1. Raising exceptions
      2. Defining your own exceptions
      3. Tracebacks
      4. Handling exceptions
      5. Not only for errors
    2. Context managers
      1. Class-based context managers
      2. Generator-based context managers
    3. Summary
  9. Files and Data Persistence
    1. Working with files and directories
      1. Opening files
        1. Using a context manager to open a file
      2. Reading and writing to a file
        1. Reading and writing in binary mode
        2. Protecting against overwriting an existing file
      3. Checking for file and directory existence
      4. Manipulating files and directories
        1. Manipulating pathnames
      5. Temporary files and directories
      6. Directory content
      7. File and directory compression
    2. Data interchange formats
      1. Working with JSON
        1. Custom encoding/decoding with JSON
    3. I/O, streams, and requests
      1. Using an in-memory stream
      2. Making HTTP requests
    4. Persisting data on disk
      1. Serializing data with pickle
      2. Saving data with shelve
      3. Saving data to a database
    5. Summary
  10. Cryptography and Tokens
    1. The need for cryptography
      1. Useful guidelines
    2. Hashlib
    3. HMAC
    4. Secrets
      1. Random numbers
      2. Token generation
      3. Digest comparison
    5. JSON Web Tokens
      1. Registered claims
        1. Time-related claims
        2. Authentication-related claims
      2. Using asymmetric (public key) algorithms
    6. Useful references
    7. Summary
  11. Testing
    1. Testing your application
      1. The anatomy of a test
      2. Testing guidelines
      3. Unit testing 
        1. Writing a unit test
        2. Mock objects and patching
        3. Assertions
      4. Testing a CSV generator
        1. Boundaries and granularity
        2. Testing the export function
        3. Final considerations
    2. Test-driven development
    3. Summary
  12. Debugging and Profiling
    1. Debugging techniques
      1. Debugging with print
      2. Debugging with a custom function
      3. Using the Python debugger
      4. Inspecting logs
      5. Other techniques
        1. Reading tracebacks
        2. Assertions
      6. Where to find information
    2. Troubleshooting guidelines
      1. Where to inspect
      2. Using tests to debug
      3. Monitoring
    3. Profiling Python
      1. When to profile
      2. Measuring execution time
    4. Summary
  13. GUIs and Scripting
    1. First approach: scripting
      1. The imports
      2. Parsing arguments
      3. The business logic
    2. Second approach: a GUI application
      1. The imports
      2. The layout logic
      3. The business logic
        1. Fetching the web page
        2. Saving the images
        3. Alerting the user
      4. How can we improve the application?
    3. Where do we go from here?
      1. The turtle module
      2. wxPython, Kivy, and PyQt
      3. The principle of least astonishment
      4. Threading considerations
    4. Summary
  14. Data Science in Brief
    1. IPython and Jupyter Notebook
      1. Using Anaconda
      2. Starting a Notebook
    2. Dealing with data
      1. Setting up the Notebook
      2. Preparing the data
      3. Cleaning the data
      4. Creating the DataFrame
        1. Unpacking the campaign name
        2. Unpacking the user data
        3. Cleaning everything up
      5. Saving the DataFrame to a file
      6. Visualizing the results
    3. Where do we go from here?
    4. Summary
  15. Introduction to API Development
    1. What is the Web?
      1. How does the Web work?
      2. Response status codes
    2. Type hinting: An overview
      1. Why type hinting?
      2. Type hinting in a nutshell
    3. APIs: An introduction
      1. What is an API?
      2. What is the purpose of an API?
      3. API protocols
      4. API data-exchange formats
    4. The railway API
      1. Modeling the database
      2. Main setup and configuration
        1. Adding settings
      3. Station endpoints
        1. Reading data
        2. Creating data
        3. Updating data
        4. Deleting data
      4. User authentication
      5. Documenting the API
    5. Consuming an API
      1. Calling the API from Django
    6. Where do we go from here?
    7. Summary
  16. Packaging Python Applications
    1. The Python Package Index
    2. The train schedule project
    3. Packaging with setuptools
      1. Required files
        1. pyproject.toml
        2. License
        3. README
        4. Changelog
        5. setup.cfg
        6. setup.py
        7. MANIFEST.in
      2. Package metadata
        1. Accessing metadata in your code
      3. Defining the package contents
        1. Accessing package data files
      4. Specifying dependencies
      5. Entry points
    4. Building and publishing packages
      1. Building
      2. Publishing
    5. Advice for starting new projects
    6. Alternative tools
    7. Further reading
    8. Summary
  17. Other Books You May Enjoy
  18. Index

Product information

  • Title: Learn Python Programming - Third Edition
  • Author(s): Fabrizio Romano, Heinrich Kruger
  • Release date: October 2021
  • Publisher(s): Packt Publishing
  • ISBN: 9781801815093