Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Save more on your purchases now! discount-offer-chevron-icon
Savings automatically calculated. No voucher code required.
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Conferences
Free Learning
Arrow right icon
Modern Python Cookbook
Modern Python Cookbook

Modern Python Cookbook: 130+ updated recipes for modern Python 3.12 with new techniques and tools , Third Edition

eBook
€22.99 €32.99
Paperback
€41.99
Subscription
Free Trial
Renews at €18.99p/m

What do you get with Print?

Product feature icon Instant access to your digital eBook copy whilst your Print order is Shipped
Product feature icon Paperback book shipped to your preferred address
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
Product feature icon AI Assistant (beta) to help accelerate your learning
OR
Modal Close icon
Payment Processing...
tick Completed

Shipping Address

Billing Address

Shipping Methods
Table of content icon View table of contents Preview book icon Preview Book

Modern Python Cookbook

2
Statements and Syntax

Python syntax is designed to be simple. In this chapter, we’ll look at some of the most commonly used statements in the language as a way to understand the rules. Concrete examples can help clarify the language’s syntax.

We’ll cover some of the basics of creating script files first. Then we’ll move on to looking at some of the more commonly used statements. Python only has about 20 or so different kinds of imperative statements in the language. We’ve already looked at two kinds of statements in Chapter 1, the assignment statement and the expression statement.

When we write something like this:

>>> print("hello world") 
 
hello world

We’re actually executing a statement that contains only the evaluation of a function, print(). This kind of statement—where we evaluate a function or a method of an object—is common.

The other kind of statement we&...

2.1 Writing Python script and module files – syntax basics

The point of Python (and programming in general) is to create automated solutions to problems that involve data and processing. Further, the software we write is a kind of knowledge representation; this means clarity is perhaps the most important quality aspect of software.

In Python, we implement automated solutions by creating script files. These are the top-level, main programs of Python programming. In addition to main scripts, we may also create modules (and packages of modules) to help organize the software into intellectually manageable chunks. A script is a module; however, it has a distinct intent to do useful processing when started by the OS.

A key part of creating clear, readable Python files is making sure our code follows the widely adopted conventions.

For example, we need to be sure to save our files in UTF-8 encoding. While ASCII encoding is still supported by Python,...

2.2 Writing long lines of code

There are many times when we need to write lines of code that are so long that they’re very hard to read. Many people like to limit the length of a line of code to 80 characters or fewer. It’s a well-known principle of graphic design that a narrower area of text is easier to read. See http://webtypography.net/2.1.2 for a deeper discussion of line width and readability.

While fewer characters per line is easier on the eyes, our code can refuse to cooperate with this principle. How can we break long Python statements into more manageable pieces?

2.2.1 Getting ready

Let’s say we’ve got something like this:

>>> import math
>>> example_value = (63/25) * (17+15*math.sqrt(5)) / (7+15*math.sqrt(5))
>>> mantissa_fraction, exponent = math.frexp(example_value)
>>> mantissa_whole = int(mantissa_fraction*2**53)
>>> message_text = f’...

2.3 Including descriptions and documentation

When we have a useful script, we often need to leave notes for ourselves—and others—on what it does, how it solves some particular problem, and when it should be used. This recipe contains a suggested outline to help make the documentation reasonably complete.

2.3.1 Getting ready

If we’ve used the Writing Python script and module files – syntax basics recipe to start a script file, we’ll have a small documentation string in place. We’ll expand on this documentation string in this recipe.

There are other places where documentation strings should be used. We’ll look at these additional locations in Chapter 3 and Chapter 7.

We have two general kinds of modules for which we’ll be writing summary docstrings:

  • Library modules: These files will contain mostly function definitions as well as class definitions...

2.4 Writing better docstrings with RST markup

When we have a useful script, we often need to leave notes on what it does, how it works, and when it should be used. Many tools for producing documentation, including Docutils, work with RST markup. This allows us to write plain text documentation. It can include some special punctuation to pick a bold or italic font variant to call attention to details. In addition, RST permits organizing content via lists and section headings.

2.4.1 Getting ready

In the Including descriptions and documentation recipe, we looked at putting some basic documentation into a module. We’ll look at a few of the RST formatting rules for creating readable documentation.

2.4.2 How to do it...

  1. Start with an outline of the key point, creating RST section titles to organize the material. A section title has a one-line title followed by a line of underline characters...

2.5 Designing complex if...elif chains

In most cases, our scripts will involve a number of choices. Sometimes the choices are simple, and we can judge the quality of the design with a glance at the code. In other cases, the choices are more complicated, and it’s not easy to determine whether or not our if statements are designed properly to handle all of the conditions.

In the simplest case, we have one condition, C, and its inverse, ¬C. These are the two conditions for an if...else statement. One condition, C, is stated in the if clause; the inversion condition, ¬C, is implied in the else clause.

This follows the Law of the Excluded Middle: we’re claiming there’s no missing alternative between the two conditions, C and ¬C. For a complex condition, though, this can be difficult to visualize.

If we have something like:


 
 
if weather == Weather.RAIN and plan == Plan.GO_OUT: 
 
    ...

2.6 Saving intermediate results with the := ”walrus” operator

Sometimes we’ll have a complex condition where we want to preserve an expensive intermediate result for later use. Imagine a condition that involves a complex calculation; the cost of computing is high measured in time, input-output operations, memory resources, or all three.

An example includes doing repetitive searches using the Regular Expression (re) package. A match() method can do quite a bit of computation before returning either a Match object or a None object to show the pattern wasn’t found. Once this computation is completed, we may have several uses for the result, and we emphatically do not want to perform the computation again. Often, the initial use is the simple check to see if the result is a Match object or None.

This is an example where it can be helpful to assign a name to the value of an expression and also use the expression in an if statement. We...

2.7 Avoiding a potential problem with break statements

The common way to understand a for statement is that it creates a for all condition. At the end of the statement, we can assert that, for all items in a collection, the processing in the body of the statement has been done.

This isn’t the only meaning a for statement can have. When the break statement is used inside the body of a for statement, it changes the semantics to there exists. When the break statement leaves the for (or while) statement, we can assert there exists at least one item that caused the enclosing statement to end.

There’s a side issue here. What if the for statement ends without executing the break statement? Either way, we’re at the statement after the for statement. The condition that’s true upon leaving a for or while statement with a break statement can be ambiguous. We can’t easily tell; this recipe gives some design guidance.

The problem...

2.8 Leveraging exception matching rules

The try statement lets us capture an exception. When an exception is raised, we have a number of choices for handling it:

  • Ignore it: If we do nothing, the program stops. We can do this in two ways—don’t use a try statement in the first place, or don’t have a matching except clause in the try statement.

  • Log it: We can write a message and use a raise statement to let the exception propagate after writing to a log. The expectation is that this will stop the program.

  • Recover from it: We can write an except clause to do some recovery action to undo any effects of the partially completed try clause.

  • Silence it: If we do nothing (that is, use the pass statement), then processing is resumed after the try statement. This silences the exception, but does not correct the underlying problem, or supply alternative results as a recovery attempt.

  • Rewrite it: We can raise a different...

2.9 Avoiding a potential problem with an except: clause

There are some common mistakes in exception handling. These can cause programs to become unresponsive.

One of the mistakes we can make is to use the except: clause with no named exception class to match. There are a few other mistakes that we can make if we’re not cautious about the exceptions we try to handle.

This recipe will show some common exception handling errors that we can avoid.

2.9.1 Getting ready

When code can raise a variety of exceptions, it’s sometimes tempting to try and match as many as possible. Matching too many exception classes can interfere with stopping a misbehaving Python program. We’ll extend the idea of what not to do in this recipe.

2.9.2 How to do it...

We need to avoid using the bare except: clause. Instead, use except Exception: to match the most general kind of exception that an application...

2.10 Concealing an exception root cause

Exceptions contain a root cause. The default behavior of internally raised exceptions is to use an implicit __context__ attribute to include the root cause of an exception. In some cases, we may want to deemphasize the root cause because it’s misleading or unhelpful for debugging.

This technique is almost always paired with an application or library that defines a unique exception. The idea is to show the unique exception without the clutter of an irrelevant exception from outside the application or library.

2.10.1 Getting ready

Assume we’re writing some complex string processing. We’d like to treat a number of different kinds of detailed exceptions as a single generic error so that users of our software are insulated from the implementation details. We can attach details to the generic error.

2.10.2 How to do it...

  1. To create...

2.11 Managing a context using the with statement

There are many instances where our scripts will be entangled with external resources. The most common examples are disk files and network connections to external hosts. A common bug is retaining these entanglements forever, tying up these resources uselessly. These are sometimes called a memory leak because the available memory is reduced each time a new file is opened without closing a previously used file.

We’d like to isolate each entanglement so that we can be sure that the resource is acquired and released properly. The idea is to create a context in which our script uses an external resource. At the end of the context, our program is no longer bound to the resource and we want to be guaranteed that the resource is released.

2.11.1 Getting ready

Let’s say we want to write lines of data to a file in CSV format. When we’re done, we want to be sure that the file is closed...

Left arrow icon Right arrow icon
Download code icon Download Code

Key benefits

  • New chapters on type matching, data visualization, dependency management, and more
  • Comprehensive coverage of Python 3.12 with updated recipes and techniques
  • Provides practical examples and detailed explanations to solve real-world problems efficiently

Description

Python is the go-to language for developers, engineers, data scientists, and hobbyists worldwide. Known for its versatility, Python can efficiently power applications, offering remarkable speed, safety, and scalability. This book distills Python into a collection of straightforward recipes, providing insights into specific language features within various contexts, making it an indispensable resource for mastering Python and using it to handle real-world use cases. The third edition of Modern Python Cookbook provides an in-depth look into Python 3.12, offering more than 140 new and updated recipes that cater to both beginners and experienced developers. This edition introduces new chapters on documentation and style, data visualization with Matplotlib and Pyplot, and advanced dependency management techniques using tools like Poetry and Anaconda. With practical examples and detailed explanations, this cookbook helps developers solve real-world problems, optimize their code, and get up to date with the latest Python features.

Who is this book for?

This Python book is for web developers, programmers, enterprise programmers, engineers, and big data scientists. If you are a beginner, this book offers helpful details and design patterns for learning Python. If you are experienced, it will expand your knowledge base. Fundamental knowledge of Python programming and basic programming principles will be helpful

What you will learn

  • Master core Python data structures, algorithms, and design patterns
  • Implement object-oriented designs and functional programming features
  • Use type matching and annotations to make more expressive programs
  • Create useful data visualizations with Matplotlib and Pyplot
  • Manage project dependencies and virtual environments effectively
  • Follow best practices for code style and testing
  • Create clear and trustworthy documentation for your projects
Estimated delivery fee Deliver to Hungary

Premium delivery 7 - 10 business days

€25.95
(Includes tracking information)

Product Details

Country selected
Publication date, Length, Edition, Language, ISBN-13
Publication date : Jul 31, 2024
Length: 818 pages
Edition : 3rd
Language : English
ISBN-13 : 9781835466384
Category :
Languages :
Tools :

What do you get with Print?

Product feature icon Instant access to your digital eBook copy whilst your Print order is Shipped
Product feature icon Paperback book shipped to your preferred address
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
Product feature icon AI Assistant (beta) to help accelerate your learning
OR
Modal Close icon
Payment Processing...
tick Completed

Shipping Address

Billing Address

Shipping Methods
Estimated delivery fee Deliver to Hungary

Premium delivery 7 - 10 business days

€25.95
(Includes tracking information)

Product Details

Publication date : Jul 31, 2024
Length: 818 pages
Edition : 3rd
Language : English
ISBN-13 : 9781835466384
Category :
Languages :
Tools :

Packt Subscriptions

See our plans and pricing
Modal Close icon
€18.99 billed monthly
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Simple pricing, no contract
€189.99 billed annually
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just €5 each
Feature tick icon Exclusive print discounts
€264.99 billed in 18 months
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just €5 each
Feature tick icon Exclusive print discounts

Frequently bought together


Stars icon
Total 106.97
Modern Python Cookbook
€41.99
Python Real-World Projects
€34.99
Mastering Python Design Patterns
€29.99
Total 106.97 Stars icon

Table of Contents

19 Chapters
Chapter 1 Numbers, Strings, and Tuples Chevron down icon Chevron up icon
Chapter 2 Statements and Syntax Chevron down icon Chevron up icon
Chapter 3 Function Definitions Chevron down icon Chevron up icon
Chapter 4 Built-In Data Structures Part 1: Lists and Sets Chevron down icon Chevron up icon
Chapter 5 Built-In Data Structures Part 2: Dictionaries Chevron down icon Chevron up icon
Chapter 6 User Inputs and Outputs Chevron down icon Chevron up icon
Chapter 7 Basics of Classes and Objects Chevron down icon Chevron up icon
Chapter 8 More Advanced Class Design Chevron down icon Chevron up icon
Chapter 9 Functional Programming Features Chevron down icon Chevron up icon
Chapter 10 Working with Type Matching and Annotations Chevron down icon Chevron up icon
Chapter 11 Input/Output, Physical Format, and Logical Layout Chevron down icon Chevron up icon
Chapter 12 Graphics and Visualization with Jupyter Lab Chevron down icon Chevron up icon
Chapter 13 Application Integration: Configuration Chevron down icon Chevron up icon
Chapter 14 Application Integration: Combination Chevron down icon Chevron up icon
Chapter 15 Testing Chevron down icon Chevron up icon
Chapter 16 Dependencies and Virtual Environments Chevron down icon Chevron up icon
Chapter 17 Documentation and Style Chevron down icon Chevron up icon
Other Books You May Enjoy Chevron down icon Chevron up icon
Index Chevron down icon Chevron up icon

Customer reviews

Top Reviews
Rating distribution
Full star icon Full star icon Full star icon Full star icon Half star icon 4.9
(18 Ratings)
5 star 88.9%
4 star 11.1%
3 star 0%
2 star 0%
1 star 0%
Filter icon Filter
Top Reviews

Filter reviews by




N/A Nov 05, 2024
Full star icon Full star icon Full star icon Full star icon Full star icon 5
Feefo Verified review Feefo
Samuel de Zoete Oct 01, 2024
Full star icon Full star icon Full star icon Full star icon Full star icon 5
There are many good books to learn how to code in Python. However, most books and courses show you how it's done and move on to the next topic. This book is different. It not only shows you how it's done, it will explain why it's done this way and how it works. This additional inside is going to make a difference in you being an average programmer or being a really good one!
Amazon Verified review Amazon
Stephan Miller Aug 03, 2024
Full star icon Full star icon Full star icon Full star icon Full star icon 5
Many coding books lose much of their usefulness after you learn the concepts they have to teach you. But recipe books are great because they become permanent references. When you want to do something specific, you can go right to it. Sometimes I just browse them to see if there is any code that triggers an idea or to run into something I never thought of doing. And this book has more than 130 recipes in my favorite programming language.
Amazon Verified review Amazon
Robert Aug 04, 2024
Full star icon Full star icon Full star icon Full star icon Full star icon 5
The review covers the third edition of Modern Python Cookbook. This book is not necessarily for the first-time Python user, but if you have some previous experience, this book is the one you want in your collection. It starts with simple Python lessons about numbers, strings, and tuples then progresses into functions, lists, dictionaries, and how to create classes. The chapter about graphics and visualization using the Jupyter notebook was a nice touch. The book is easy to follow and the examples are extremely helpful. I highly recommend this book.
Amazon Verified review Amazon
Paul Gerber Aug 05, 2024
Full star icon Full star icon Full star icon Full star icon Full star icon 5
I've recently finished reading "Modern Python Cookbook 3rd Edition" by Steve Lott, and I must say it was an absolutely delightful read. This book is packed with practical recipes and examples that cater to both intermediate and advanced Python developers.One of the standout features of this book is its clear and concise explanations, which made it easy to grasp even the more complex concepts.Another highlight was the section on testing and debugging. The recipes on using pytest and mocking were extremely useful.Steve Lott's emphasis on writing clean and maintainable code resonated with me deeply. His approach to leveraging Python's powerful features like decorators, context managers, and metaclasses has not only improved the quality of my code but also boosted my productivity.Overall, "Modern Python Cookbook 3rd Edition" is a treasure trove of Python wisdom. Whether you're looking to refine your skills or seeking new techniques to tackle challenging problems, this book is an invaluable resource. Highly recommended for anyone serious about mastering Python!
Amazon Verified review Amazon
Get free access to Packt library with over 7500+ books and video courses for 7 days!
Start Free Trial

FAQs

What is the delivery time and cost of print book? Chevron down icon Chevron up icon

Shipping Details

USA:

'

Economy: Delivery to most addresses in the US within 10-15 business days

Premium: Trackable Delivery to most addresses in the US within 3-8 business days

UK:

Economy: Delivery to most addresses in the U.K. within 7-9 business days.
Shipments are not trackable

Premium: Trackable delivery to most addresses in the U.K. within 3-4 business days!
Add one extra business day for deliveries to Northern Ireland and Scottish Highlands and islands

EU:

Premium: Trackable delivery to most EU destinations within 4-9 business days.

Australia:

Economy: Can deliver to P. O. Boxes and private residences.
Trackable service with delivery to addresses in Australia only.
Delivery time ranges from 7-9 business days for VIC and 8-10 business days for Interstate metro
Delivery time is up to 15 business days for remote areas of WA, NT & QLD.

Premium: Delivery to addresses in Australia only
Trackable delivery to most P. O. Boxes and private residences in Australia within 4-5 days based on the distance to a destination following dispatch.

India:

Premium: Delivery to most Indian addresses within 5-6 business days

Rest of the World:

Premium: Countries in the American continent: Trackable delivery to most countries within 4-7 business days

Asia:

Premium: Delivery to most Asian addresses within 5-9 business days

Disclaimer:
All orders received before 5 PM U.K time would start printing from the next business day. So the estimated delivery times start from the next day as well. Orders received after 5 PM U.K time (in our internal systems) on a business day or anytime on the weekend will begin printing the second to next business day. For example, an order placed at 11 AM today will begin printing tomorrow, whereas an order placed at 9 PM tonight will begin printing the day after tomorrow.


Unfortunately, due to several restrictions, we are unable to ship to the following countries:

  1. Afghanistan
  2. American Samoa
  3. Belarus
  4. Brunei Darussalam
  5. Central African Republic
  6. The Democratic Republic of Congo
  7. Eritrea
  8. Guinea-bissau
  9. Iran
  10. Lebanon
  11. Libiya Arab Jamahriya
  12. Somalia
  13. Sudan
  14. Russian Federation
  15. Syrian Arab Republic
  16. Ukraine
  17. Venezuela
What is custom duty/charge? Chevron down icon Chevron up icon

Customs duty are charges levied on goods when they cross international borders. It is a tax that is imposed on imported goods. These duties are charged by special authorities and bodies created by local governments and are meant to protect local industries, economies, and businesses.

Do I have to pay customs charges for the print book order? Chevron down icon Chevron up icon

The orders shipped to the countries that are listed under EU27 will not bear custom charges. They are paid by Pack