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
€21.99 €31.99
Paperback
€38.99
Subscription
Free Trial
Renews at €18.99p/m

What do you get with eBook?

Product feature icon Instant access to your Digital eBook purchase
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
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 : 9781786463845
Category :
Languages :

What do you get with eBook?

Product feature icon Instant access to your Digital eBook purchase
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 Details

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

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 117.97
Expert Python Programming
€36.99
Modern Python Cookbook
€38.99
Python GUI Programming Cookbook, Second Edition
€41.99
Total 117.97 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

How do I buy and download an eBook? Chevron down icon Chevron up icon

Where there is an eBook version of a title available, you can buy it from the book details for that title. Add either the standalone eBook or the eBook and print book bundle to your shopping cart. Your eBook will show in your cart as a product on its own. After completing checkout and payment in the normal way, you will receive your receipt on the screen containing a link to a personalised PDF download file. This link will remain active for 30 days. You can download backup copies of the file by logging in to your account at any time.

If you already have Adobe reader installed, then clicking on the link will download and open the PDF file directly. If you don't, then save the PDF file on your machine and download the Reader to view it.

Please Note: Packt eBooks are non-returnable and non-refundable.

Packt eBook and Licensing When you buy an eBook from Packt Publishing, completing your purchase means you accept the terms of our licence agreement. Please read the full text of the agreement. In it we have tried to balance the need for the ebook to be usable for you the reader with our needs to protect the rights of us as Publishers and of our authors. In summary, the agreement says:

  • You may make copies of your eBook for your own use onto any machine
  • You may not pass copies of the eBook on to anyone else
How can I make a purchase on your website? Chevron down icon Chevron up icon

If you want to purchase a video course, eBook or Bundle (Print+eBook) please follow below steps:

  1. Register on our website using your email address and the password.
  2. Search for the title by name or ISBN using the search option.
  3. Select the title you want to purchase.
  4. Choose the format you wish to purchase the title in; if you order the Print Book, you get a free eBook copy of the same title. 
  5. Proceed with the checkout process (payment to be made using Credit Card, Debit Cart, or PayPal)
Where can I access support around an eBook? Chevron down icon Chevron up icon
  • If you experience a problem with using or installing Adobe Reader, the contact Adobe directly.
  • To view the errata for the book, see www.packtpub.com/support and view the pages for the title you have.
  • To view your account details or to download a new copy of the book go to www.packtpub.com/account
  • To contact us directly if a problem is not resolved, use www.packtpub.com/contact-us
What eBook formats do Packt support? Chevron down icon Chevron up icon

Our eBooks are currently available in a variety of formats such as PDF and ePubs. In the future, this may well change with trends and development in technology, but please note that our PDFs are not Adobe eBook Reader format, which has greater restrictions on security.

You will need to use Adobe Reader v9 or later in order to read Packt's PDF eBooks.

What are the benefits of eBooks? Chevron down icon Chevron up icon
  • You can get the information you need immediately
  • You can easily take them with you on a laptop
  • You can download them an unlimited number of times
  • You can print them out
  • They are copy-paste enabled
  • They are searchable
  • There is no password protection
  • They are lower price than print
  • They save resources and space
What is an eBook? Chevron down icon Chevron up icon

Packt eBooks are a complete electronic version of the print edition, available in PDF and ePub formats. Every piece of content down to the page numbering is the same. Because we save the costs of printing and shipping the book to you, we are able to offer eBooks at a lower cost than print editions.

When you have purchased an eBook, simply login to your account and click on the link in Your Download Area. We recommend you saving the file to your hard drive before opening it.

For optimal viewing of our eBooks, we recommend you download and install the free Adobe Reader version 9.