Book Image

Python Essentials

By : Steven F. Lott
Book Image

Python Essentials

By: Steven F. Lott

Overview of this book

Table of Contents (22 chapters)
Python Essentials
Credits
About the Author
About the Reviewers
www.PacktPub.com
Preface
Index

Preface

Python programming should be expressive and elegant. In order for this to be true, the language itself must be easy to learn and easy to use. Any practical language—and its associated libraries—can present a daunting volume of information. In order to help someone learn Python, we've identified and described those features that seem essential.

Learning a language can be a long voyage. We'll pass numerous islands, archipelagos, inlets, and estuaries along the route. Our objective is to point out the key features that will be passed during the initial stages of this journey.

The concepts of data structures and algorithms are ever-present considerations in programming. Our overall approach is to introduce the various Python data structures first. As part of working with a given class of objects, the language statements are introduced later. One of Python's significant advantages over other languages is the rich collection of built-in data types. Selecting an appropriate representation of data can lead to elegant, high-performance applications.

An essential aspect of Python is its overall simplicity. There are very few operators and very few different kinds of statements. Much of the code we write can be generic with respect to the underlying data type. This allows us to easily exchange different data structure implementations as part of making tradeoffs between storage, performance, accuracy, and other considerations.

Some subject areas could take us well beyond the basics. Python's object-oriented programming features are rich enough to easily fill several large volumes. If we're also interested in functional programming features, we can study these in far more depth elsewhere. We'll touch only briefly on these subjects.

What this book covers

Chapter 1, Getting Started, addresses installing or upgrading Python. We explore Python's Read-Evaluate-Print Loop (REPL) as a way to interact with the language. We'll use this interactive Python mode as a way to explore most of the language features.

Chapter 2, Simple Data Types, introduces a few features concerning numbers and some simple collections. We'll look at Python's Unicode strings as well as byte strings, including some of the conversions between strings and numbers.

Chapter 3, Expressions and Output, provides more details on Python expression syntax and how the various numeric types relate to each other. We'll look at the coercion rules and the numeric tower. We'll look at the print() function, which is a common tool for looking at output.

Chapter 4, Variables, Assignment and Scoping Rules, shows how we assign names to objects. We look at a number of different assignment statements available in Python. We also explore the input() function, which parallels the print() function.

Chapter 5, Logic, Comparisons, and Conditions, shows the logical operators and literals that Python uses. We'll look at the comparison operators and how we use them. We'll look closely at the if statement.

Chapter 6, More Complex Data Types, shows the core features of the list, set, and dict built-in types. We use the for statement to work with these collections. We also use functions such as sum(), map(), and filter().

Chapter 7, Basic Function Definitions, introduces the syntax for the def statement as well as the return statement. Python offers a wide variety of ways to provide argument values to functions; we show a few of the alternatives.

Chapter 8, More Advanced Functions, extends the basic function definitions to include the yield statement. This allows us to write generator functions that will iterate over a sequence of data values. We look at a few functional programming features available via built-in functions as well as the modules in the Python Standard Library.

Chapter 9, Exceptions, shows how we handle and raise exceptions. This allows us to write programs which are considerably more flexible. A simple "happy path" can handle the bulk of the processing, and exception clauses can handle rare or unexpected alternative paths.

Chapter 10, Files, Databases, Networks, and Contexts, will introduce a number of features related to persistent storage. We'll look at Python's use of files and file-like objects. We'll also extend the concept of persistence to include some database features available in the Python Standard Library. This chapter will also include a review of the with statement for context management.

Chapter 11, Class Definitions, demonstrates the class statement and the essentials of object-oriented programming. We look at the basics of inheritance and how to define class-level (static) methods.

Chapter 12, Scripts, Modules, Packages, Libraries, and Applications, shows different ways in which we can create Python code files. We'll look at the formal structures of script, module, and package. We'll also look at informal concepts such as application, library, and framework.

Chapter 13, Metaprogramming and Decorators, introduces two concepts that can help us write Python code that manipulates Python code. Python makes metaprogramming relatively simple; we can leverage this to simplify certain types of programming where a common aspect doesn't fit neatly into a class hierarchy or library of functions.

Chapter 14, Fit and Finish – Unit Testing, Packaging, and Documentation, moves beyond the Python language into the idea of creating a complete, polished product. Any well-written program should include test cases and documentation. We show common ways to make sure this is done properly.

Chapter 15, Next Steps, will demonstrate four simple kinds of applications. We'll look at the command-line interface (CLI), graphic user interface (GUI), simple Web frameworks, as well as MapReduce applications.

What you need for this book

We're going to focus on Python 3, exclusively. Many computers will have Python 2 already installed, which means an upgrade is required. Some computers don't have Python installed at all, which means that a fresh installation of Python 3 will be necessary. The details are the subject of Chapter 1, Getting Started.

It's important to note that Python 2 can't easily be used to run all of the examples. Python 2 may work for many of the examples, but it's not our focus.

In order to install software, you'll generally need administrative rights on the computer you intend to use. For a home computer, this is generally true. For computers supplied through work or school, administrative passwords may be required.

You may also want to have a proper programmer's text editor. Default text editing applications such as Windows Notepad or Mac OS X TextEdit can be used, but aren't ideal. There are numerous free text editors available: feel free to download several to locate the one that feels most comfortable for you.

Who this book is for

This book is for programmers who want to learn Python quickly. It shows key features of Python, assuming a background in programming. The focus is on essential features: the approach is broad but relatively shallow. We'll provide pointers and direction for additional study and research, assuming that the reader is willing and able to follow those pointers.

In many data-intensive industries, a great deal of big data analysis is done with Python and toolsets such as Apache Hadoop. In this case, the users of Python will be statisticians, data scientists, or analysts. Their interest isn't in Python itself, but in using Python to process collections of data. This book is designed to provide language fundamentals for data scientists.

This book can be used by students who are learning Python. Since this book doesn't cover the computer science foundations of programming, an additional text would be helpful.

Conventions

In this book, you will find a number of text styles that distinguish between different kinds of information. Here are some examples of these styles and an explanation of their meaning.

Code words in text, database table names, folder names, filenames, file extensions, pathnames, dummy URLs, user input, and Twitter handles are shown as follows: "We've built an ArgumentParser method using all of the default parameters."

A block of code is set as follows:

def prod(sequence):
    p= 1
    for item in sequence:
        p *= item
    return p

When we wish to draw your attention to a particular part of a code block, the relevant lines or items are set in bold:

def prod(sequence):
    p= 1
    for item in sequence:
        p *= item
    return

Any command-line input or output is written as follows:

MacBookPro-SLott:Code slott$ python3 -m test_all

New terms and important words are shown in bold. Words that you see on the screen, for example, in menus or dialog boxes, appear in the text like this: "Clicking on Continue will step through the Read Me, License, Destination Select, and Installation Type windows."

Note

Warnings or important notes appear in a box like this.

Tip

Tips and tricks appear like this.

Reader feedback

Feedback from our readers is always welcome. Let us know what you think about this book—what you liked or disliked. Reader feedback is important for us as it helps us develop titles that you will really get the most out of.

To send us general feedback, simply e-mail , and mention the book's title in the subject of your message.

If there is a topic that you have expertise in and you are interested in either writing or contributing to a book, see our author guide at www.packtpub.com/authors.

Customer support

Now that you are the proud owner of a Packt book, we have a number of things to help you to get the most from your purchase.

Downloading the example code

You can download the example code files from your account at http://www.packtpub.com for all the Packt Publishing books you have purchased. If you purchased this book elsewhere, you can visit http://www.packtpub.com/support and register to have the files e-mailed directly to you.

Errata

Although we have taken every care to ensure the accuracy of our content, mistakes do happen. If you find a mistake in one of our books—maybe a mistake in the text or the code—we would be grateful if you could report this to us. By doing so, you can save other readers from frustration and help us improve subsequent versions of this book. If you find any errata, please report them by visiting http://www.packtpub.com/submit-errata, selecting your book, clicking on the Errata Submission Form link, and entering the details of your errata. Once your errata are verified, your submission will be accepted and the errata will be uploaded to our website or added to any list of existing errata under the Errata section of that title.

To view the previously submitted errata, go to https://www.packtpub.com/books/content/support and enter the name of the book in the search field. The required information will appear under the Errata section.

Piracy

Piracy of copyrighted material on the Internet is an ongoing problem across all media. At Packt, we take the protection of our copyright and licenses very seriously. If you come across any illegal copies of our works in any form on the Internet, please provide us with the location address or website name immediately so that we can pursue a remedy.

Please contact us at with a link to the suspected pirated material.

We appreciate your help in protecting our authors and our ability to bring you valuable content.

Questions

If you have a problem with any aspect of this book, you can contact us at , and we will do our best to address the problem.