Search icon CANCEL
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: The latest in modern Python recipes for the busy modern programmer

eBook
$28.99 $41.99
Paperback
$35.99 $51.99
Subscription
Free Trial
Renews at $19.99p/m

What do you get with a Packt Subscription?

Free for first 7 days. $19.99 p/m after that. Cancel any time!
Product feature icon Unlimited ad-free access to the largest independent learning library in tech. Access this title and thousands more!
Product feature icon 50+ new titles added per month, including many first-to-market concepts and exclusive early access to books as they are being written.
Product feature icon Innovative learning tools, including AI book assistants, code context explainers, and text-to-speech.
Product feature icon Thousands of reference materials covering every tech concept you need to stay up to date.
Subscribe now
View plans & pricing
Table of content icon View table of contents Preview book icon Preview Book

Modern Python Cookbook

Statements and Syntax

In this chapter we'll look at the following recipes:

  • Writing python script and module files
  • Writing long lines of code
  • Including descriptions and documentation
  • Better RST markup in docstrings
  • Designing complex if...elif chains
  • Designing a while statement which terminates
  • Avoiding a potential problem with break statements
  • Leveraging the exception matching rules
  • Avoiding a potential problem with an except: clause
  • Chaining exceptions with the raise from statement
  • Managing a context using the with statement

Introduction

Python syntax is designed to be very simple. There are a few rules; we'll look at some of the interesting statements in the language as a way to understand those rules. Just looking at the rules without concrete examples can be confusing.

We'll cover some 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 twenty or so different kinds of imperative statements in the language. We've already looked at two kinds of statements in Chapter 1, Numbers, Strings, and Tuples: 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...

Writing Python script and module files – syntax basics

We'll need to write Python script files in order to do anything truly useful. We can experiment with the language at the interaction >>> prompt. For real work, however, we'll need to create files. The whole point of writing software is to create repeatable processing for our data.

How can we avoid syntax errors and be sure our code matches what's in common use? We need to look at some common aspects of style—how we use whitespace to clarify our programming.

We'll also look at a number of more technical considerations. For example, we need to be sure to save our files in the UTF-8 encoding. While ASCII encoding is still supported by Python, it's a poor choice for modern programming. We'll also need to be sure to use spaces instead of tabs. If we use Unix newlines as much...

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 line is easier to read; opinions vary, but 65 characters is often cited as ideal. See http://webtypography.net/2.1.2.

While shorter lines are easier on the eyes, our code can refuse to cooperate with this principle. Long statements are a common problem. How can we break long Python statements into more manageable pieces?

Getting ready

Often, we'll have a statement that's awkwardly long and hard to work with. Let's say we&apos...

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.

Because clarity is important, there are some formatting recipes that can help make the documentation very clear. This recipe also contains a suggested outline so that the documentation will be reasonably complete.

Getting ready

If we've used the Writing python script and module files - syntax basics recipe to build a script file, we'll have put a small documentation string in our script file. We'll expand on this documentation string.

There are other places where documentation strings should...

Introduction


Python syntax is designed to be very simple. There are a few rules; we'll look at some of the interesting statements in the language as a way to understand those rules. Just looking at the rules without concrete examples can be confusing.

We'll cover some 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 twenty or so different kinds of imperative statements in the language. We've already looked at two kinds of statements in Chapter 1, Numbers, Strings, and Tuples: 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've already seen is the assignment statement. Python has many variations on this theme. Most...

Writing Python script and module files – syntax basics


We'll need to write Python script files in order to do anything truly useful. We can experiment with the language at the interaction >>> prompt. For real work, however, we'll need to create files. The whole point of writing software is to create repeatable processing for our data.

How can we avoid syntax errors and be sure our code matches what's in common use? We need to look at some common aspects of style—how we use whitespace to clarify our programming.

We'll also look at a number of more technical considerations. For example, we need to be sure to save our files in the UTF-8 encoding. While ASCII encoding is still supported by Python, it's a poor choice for modern programming. We'll also need to be sure to use spaces instead of tabs. If we use Unix newlines as much as possible, we'll also find things are slightly simpler.

Most text editing tools will work properly with Unix (newline) line endings as well as Windows or DOS...

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 line is easier to read; opinions vary, but 65 characters is often cited as ideal. See http://webtypography.net/2.1.2.

While shorter lines are easier on the eyes, our code can refuse to cooperate with this principle. Long statements are a common problem. How can we break long Python statements into more manageable pieces?

Getting ready

Often, we'll have a statement that's awkwardly long and hard to work with. 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 = 'the internal representation...

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.

Because clarity is important, there are some formatting recipes that can help make the documentation very clear. This recipe also contains a suggested outline so that the documentation will be reasonably complete.

Getting ready

If we've used the Writing python script and module files - syntax basics recipe to build a script file, we'll have put a small documentation string in our script file. We'll expand on this documentation string.

There are other places where documentation strings should be used. We'll look that these additional locations in Chapter 3, Function Definitions, and Chapter 6, Basics of Classes and Objects.

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...

Writing better RST markup in docstrings


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. What RST features can we use to make documentation more readable?

Getting ready

In the Including descriptions and documentation recipe, we looked at putting a basic set of documentation into a module. This is the starting point for writing our documentation. There are a large number of RST formatting rules. We'll look at a few which are important for creating readable documentation.

How to do it...

  1. Be sure to write an outline of the key points. This may lead to creating RST section titles to organize the material. A section title is a two-line paragraph with the title followed by an underline using =, -, ^, ~, or one of the other Docutils characters for underlining.

A heading will look like this.

        Topic 
        ===== 

The heading text is on one line,...

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 complex, 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 other is implied in the else.

We'll use pq to mean Python's OR operator in this explanation. We can call these two conditions complete because:

CC = ¬T

We call this complete because no other conditions can exist. There's no third choice. This is the Law of the Excluded Middle. It's also the operating principle behind the else clause. The if statement body is executed or the else statement is executed. There's no third choice.

In practical programming, we...

Designing a while statement which terminates properly


Much of the time, the Python for statement provides all of the iteration controls we need. In many cases, we can use built-in functions like map(), filter(), and reduce() to process collections of data.

There are a few situations, however, where we need to use a while statement. Some of those situations involve data structures where we can't create a proper iterator to step through the items. Other items involve interactions with human users, where we don't have the data until we get input from the person.

Getting ready

Let's say that we're going to be prompting a user for their password. We'll use the getpass module so that there's no echo.

Further, to be sure they've entered it properly, we'll want to prompt them twice and compare the results. This is a situation where a simple for statement isn't going to work out well. It can be pressed into service, but the resulting code looks strange: for statements have an explicit upper bound; prompting...

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, some processing has been done.

This isn't the only meaning for a for statement. When we introduce the break statement inside the body of a for, we change the semantics to there exists. When the break statement leaves the for (or while) statement, we can assert only that there exists at least one item that caused the statement to end.

There's a side issue here. What if the loop ends without executing the break? We are forced to assert that there does not exist even one item that triggered the break. DeMorgan's Law tells us that a not exists condition can be restated as a for all condition: ¬∃xB(x) ≡ ∀x ¬B(x). In this formula, B(x) is the condition on the if statement that includes the break. If we never found B(x), then for all items ¬B(x) was true. This shows some of the symmetry...

Left arrow icon Right arrow icon
Download code icon Download Code

Key benefits

  • Develop succinct, expressive programs in Python
  • Learn the best practices and common idioms through carefully explained and structured recipes
  • Discover new ways to apply Python for the new age of development

Description

Python is the preferred choice of developers, engineers, data scientists, and hobbyists everywhere. It is a great scripting language that can power your applications and provide great speed, safety, and scalability. By exposing Python as a series of simple recipes, you can gain insight into specific language features in a particular context. Having a tangible context helps make the language or standard library feature easier to understand. This book comes with over 100 recipes on the latest version of Python. The recipes will benefit everyone ranging from beginner to an expert. The book is broken down into 13 chapters that build from simple language concepts to more complex applications of the language. The recipes will touch upon all the necessary Python concepts related to data structures, OOP, functional programming, as well as statistical programming. You will get acquainted with the nuances of Python syntax and how to effectively use the advantages that it offers. You will end the book equipped with the knowledge of testing, web services, and configuration and application integration tips and tricks. The recipes take a problem-solution approach to resolve issues commonly faced by Python programmers across the globe. You will be armed with the knowledge of creating applications with flexible logging, powerful configuration, and command-line options, automated unit tests, and good documentation.

Who is this book for?

The book is for web developers, programmers, enterprise programmers, engineers, big data scientist, and so on. If you are a beginner, Python Cookbook will get you started. If you are experienced, it will expand your knowledge base. A basic knowledge of programming would help.

What you will learn

  • See the intricate details of the Python syntax and how to use it to your advantage
  • Improve your code readability through functions in Python
  • Manipulate data effectively using built-in data structures
  • Get acquainted with advanced programming techniques in Python
  • Equip yourself with functional and statistical programming features
  • Write proper tests to be sure a program works as advertised
  • Integrate application software using Python

Product Details

Country selected
Publication date, Length, Edition, Language, ISBN-13
Publication date : Nov 30, 2016
Length: 692 pages
Edition : 1st
Language : English
ISBN-13 : 9781786469250
Category :
Languages :

What do you get with a Packt Subscription?

Free for first 7 days. $19.99 p/m after that. Cancel any time!
Product feature icon Unlimited ad-free access to the largest independent learning library in tech. Access this title and thousands more!
Product feature icon 50+ new titles added per month, including many first-to-market concepts and exclusive early access to books as they are being written.
Product feature icon Innovative learning tools, including AI book assistants, code context explainers, and text-to-speech.
Product feature icon Thousands of reference materials covering every tech concept you need to stay up to date.
Subscribe now
View plans & pricing

Product Details

Publication date : Nov 30, 2016
Length: 692 pages
Edition : 1st
Language : English
ISBN-13 : 9781786469250
Category :
Languages :

Packt Subscriptions

See our plans and pricing
Modal Close icon
$19.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
$199.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
$279.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 $ 139.97 155.97 16.00 saved
Expert Python Programming
$48.99
Modern Python Cookbook
$35.99 $51.99
Python GUI Programming Cookbook, Second Edition
$54.99
Total $ 139.97 155.97 16.00 saved Stars icon

Table of Contents

11 Chapters
Numbers, Strings, and Tuples Chevron down icon Chevron up icon
Statements and Syntax Chevron down icon Chevron up icon
Function Definitions Chevron down icon Chevron up icon
Built-in Data Structures – list, set, dict Chevron down icon Chevron up icon
User Inputs and Outputs Chevron down icon Chevron up icon
Basics of Classes and Objects Chevron down icon Chevron up icon
More Advanced Class Design Chevron down icon Chevron up icon
Input/Output, Physical Format, and Logical Layout Chevron down icon Chevron up icon
Testing Chevron down icon Chevron up icon
Web Services Chevron down icon Chevron up icon
Application Integration Chevron down icon Chevron up icon

Customer reviews

Rating distribution
Full star icon Full star icon Half star icon Empty star icon Empty star icon 2.7
(3 Ratings)
5 star 33.3%
4 star 0%
3 star 0%
2 star 33.3%
1 star 33.3%
Sanjeev Jaiswal Feb 24, 2017
Full star icon Full star icon Full star icon Full star icon Full star icon 5
I got an opportunity before as well to work Review Steven’s book titled “Python for Secret Agents”. He has impressed me with his technical and logical skills. I am writing review for “Modern Python cookbook” as I am one of the reviewer of this book and liked the way book got published with proper title and contents after rigorous technical drafts.As it is a cookbook, so author assumes that the reader is already familiar with Python and can co-relate the cookbook’s recipes with the problem they might have faced for each given topic.Chapter 1 deals with number, tuples, string. Recipes like dealing with large numbers, parsing string with regular expressions, encoding strings are some nice recipes to look upon.Chapter 2 mainly deals with syntax, best code practices etc. You may skim if you are already following Python coding standards, otherwise it nice chapter to read.In fact, all chapters have something to look upon, even you are very experienced programmer. For some of the recipes it was like a revision for me and some of the recipes were a direct solution to the issues I had faced in early stage of Python programming.Chapters which deal with functions, list, class and objects are very impressive and I enjoyed while reviewing these chapters.In gist, it is one of the book that you would want to keep I your bookshelf for quick reference to some recipes whether it’s related to Python concepts or for testing, web services etc.I would suggest this book to intermediate and advanced Python programmers. All the best to the author for this book and hope to read more books from him in Python.
Amazon Verified review Amazon
debashish Aug 15, 2017
Full star icon Full star icon Empty star icon Empty star icon Empty star icon 2
The kindle version has many errors and is inaccurate.For example, it says (for dictionaries): If the key does exist, the setdefault method does nothing. This is wrong. Consider other examples. In chapter 5, the subtopic "Using features of the print() function" has a wrong table layout. The print function defined there has obvious mistakes in it. In chapter 7, "Choosing between inheritance and extension - the is-a question" is an inaccurate title.In general, the text is incoherent in many places and sometimes not relevant to python (for example, referring to the commands on the SunOS operating system). There are also repetitive sections of text. The grammer used is unusual at times - using the word "story" to refer to a scenario. Last but not least, the table of contents lists the chapters without any sections. This makes it difficult to navigate the book.I found it to be a waste of money.
Amazon Verified review Amazon
S. Watkins Oct 14, 2018
Full star icon Empty star icon Empty star icon Empty star icon Empty star icon 1
Right away, I thought it was odd that this book started out discussing naming conventions. The formatting is...shall we say "scattered" may be the best part. The author is all over the place. On page 12 in the middle of naming conventions, he drops "be sure to do this: >>> import thisIf you are not familiar with Python this would be confusing. If you are familiar and have been using it, you understand how incomplete and out of place this comment is at this point. The discussion of importing modules hasn't been touched on in the book yet and no, this comment didn't lead into the discussion of importing modules just yet. So why would you bring up the importing function. It's akin to discussing viable names for your newborn and then out of the blue stating "they should go to college and major in." and then going back to names without finishing your out of place statement. Sadly, this wasn't the last one. The book wastes no time in throwing out random info without details( that doesn't fit the topic that is currently being discussed) while diving into other info that is really not pertinent to a python programmer. I only made it barely half way before throwing this thing in the garbage.
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 included in a Packt subscription? Chevron down icon Chevron up icon

A subscription provides you with full access to view all Packt and licnesed content online, this includes exclusive access to Early Access titles. Depending on the tier chosen you can also earn credits and discounts to use for owning content

How can I cancel my subscription? Chevron down icon Chevron up icon

To cancel your subscription with us simply go to the account page - found in the top right of the page or at https://subscription.packtpub.com/my-account/subscription - From here you will see the ‘cancel subscription’ button in the grey box with your subscription information in.

What are credits? Chevron down icon Chevron up icon

Credits can be earned from reading 40 section of any title within the payment cycle - a month starting from the day of subscription payment. You also earn a Credit every month if you subscribe to our annual or 18 month plans. Credits can be used to buy books DRM free, the same way that you would pay for a book. Your credits can be found in the subscription homepage - subscription.packtpub.com - clicking on ‘the my’ library dropdown and selecting ‘credits’.

What happens if an Early Access Course is cancelled? Chevron down icon Chevron up icon

Projects are rarely cancelled, but sometimes it's unavoidable. If an Early Access course is cancelled or excessively delayed, you can exchange your purchase for another course. For further details, please contact us here.

Where can I send feedback about an Early Access title? Chevron down icon Chevron up icon

If you have any feedback about the product you're reading, or Early Access in general, then please fill out a contact form here and we'll make sure the feedback gets to the right team. 

Can I download the code files for Early Access titles? Chevron down icon Chevron up icon

We try to ensure that all books in Early Access have code available to use, download, and fork on GitHub. This helps us be more agile in the development of the book, and helps keep the often changing code base of new versions and new technologies as up to date as possible. Unfortunately, however, there will be rare cases when it is not possible for us to have downloadable code samples available until publication.

When we publish the book, the code files will also be available to download from the Packt website.

How accurate is the publication date? Chevron down icon Chevron up icon

The publication date is as accurate as we can be at any point in the project. Unfortunately, delays can happen. Often those delays are out of our control, such as changes to the technology code base or delays in the tech release. We do our best to give you an accurate estimate of the publication date at any given time, and as more chapters are delivered, the more accurate the delivery date will become.

How will I know when new chapters are ready? Chevron down icon Chevron up icon

We'll let you know every time there has been an update to a course that you've bought in Early Access. You'll get an email to let you know there has been a new chapter, or a change to a previous chapter. The new chapters are automatically added to your account, so you can also check back there any time you're ready and download or read them online.

I am a Packt subscriber, do I get Early Access? Chevron down icon Chevron up icon

Yes, all Early Access content is fully available through your subscription. You will need to have a paid for or active trial subscription in order to access all titles.

How is Early Access delivered? Chevron down icon Chevron up icon

Early Access is currently only available as a PDF or through our online reader. As we make changes or add new chapters, the files in your Packt account will be updated so you can download them again or view them online immediately.

How do I buy Early Access content? Chevron down icon Chevron up icon

Early Access is a way of us getting our content to you quicker, but the method of buying the Early Access course is still the same. Just find the course you want to buy, go through the check-out steps, and you’ll get a confirmation email from us with information and a link to the relevant Early Access courses.

What is Early Access? Chevron down icon Chevron up icon

Keeping up to date with the latest technology is difficult; new versions, new frameworks, new techniques. This feature gives you a head-start to our content, as it's being created. With Early Access you'll receive each chapter as it's written, and get regular updates throughout the product's development, as well as the final course as soon as it's ready.We created Early Access as a means of giving you the information you need, as soon as it's available. As we go through the process of developing a course, 99% of it can be ready but we can't publish until that last 1% falls in to place. Early Access helps to unlock the potential of our content early, to help you start your learning when you need it most. You not only get access to every chapter as it's delivered, edited, and updated, but you'll also get the finalized, DRM-free product to download in any format you want when it's published. As a member of Packt, you'll also be eligible for our exclusive offers, including a free course every day, and discounts on new and popular titles.