The Python Apprentice - Robert Smallshire - E-Book

The Python Apprentice E-Book

Robert Smallshire

0,0
37,19 €

-100%
Sammeln Sie Punkte in unserem Gutscheinprogramm und kaufen Sie E-Books und Hörbücher mit bis zu 100% Rabatt.

Mehr erfahren.
Beschreibung

Learn the Python skills and culture you need to become a productive member of any Python project.

About This Book

  • Taking a practical approach to studying Python
  • A clear appreciation of the sequence-oriented parts of Python
  • Emphasis on the way in which Python code is structured
  • Learn how to produce bug-free code by using testing tools

Who This Book Is For

The Python Apprentice is for anyone who wants to start building, creating and contributing towards a Python project. No previous knowledge of Python is required, although at least some familiarity with programming in another language is helpful.

What You Will Learn

  • Learn the language of Python itself
  • Get a start on the Python standard library
  • Learn how to integrate 3rd party libraries
  • Develop libraries on your own
  • Become familiar with the basics of Python testing

In Detail

Experienced programmers want to know how to enhance their craft and we want to help them start as apprentices with Python. We know that before mastering Python you need to learn the culture and the tools to become a productive member of any Python project. Our goal with this book is to give you a practical and thorough introduction to Python programming, providing you with the insight and technical craftsmanship you need to be a productive member of any Python project. Python is a big language, and it's not our intention with this book to cover everything there is to know. We just want to make sure that you, as the developer, know the tools, basic idioms and of course the ins and outs of the language, the standard library and other modules to be able to jump into most projects.

Style and approach

We introduce topics gently and then revisit them on multiple occasions to add the depth required to support your progression as a Python developer. We've worked hard to structure the syllabus to avoid forward references. On only a few occasions do we require you to accept techniques on trust, before explaining them later; where we do, it's to deliberately establish good habits.

Sie lesen das E-Book in den Legimi-Apps auf:

Android
iOS
von Legimi
zertifizierten E-Readern

Seitenzahl: 359

Veröffentlichungsjahr: 2017

Bewertungen
0,0
0
0
0
0
0
Mehr Informationen
Mehr Informationen
Legimi prüft nicht, ob Rezensionen von Nutzern stammen, die den betreffenden Titel tatsächlich gekauft oder gelesen/gehört haben. Wir entfernen aber gefälschte Rezensionen.



 

The Python Apprentice

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

A Practical and Thorough Introduction to the Python Programming Language

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

Robert Smallshire
Austin Bingham

 

       BIRMINGHAM - MUMBAI

The Python Apprentice

 

Copyright © 2017 Robert Smallshire, Austin Bingham 

 

 

All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, without the prior written permission of the publisher, except in the case of brief quotations embedded in critical articles or reviews.

Every effort has been made in the preparation of this book to ensure the accuracy of the information presented. However, the information contained in this book is sold without warranty, either express or implied. Neither the authors, nor Packt Publishing, and its dealers and distributors will be held liable for any damages caused or alleged to be caused directly or indirectly by this book.

Packt Publishing has endeavored to provide trademark information about all of the companies and products mentioned in this book by the appropriate use of capitals. However, Packt Publishing cannot guarantee the accuracy of this information.

 

First published: June 2017

Production reference: 1160617

Published by Packt Publishing Ltd.
Livery Place
35 Livery Street
Birmingham 
B3 2PB, UK.

ISBN 978-1-78829-318-1

www.packtpub.com

Credits

 

 

Authors

Robert Smallshire

Austin Bingham

 

Technical Editor

Joel Wilfred D'souza

Acquisition Editor  

Frank Pohlmann

Indexer  

Rekha Nair 

Project Coordinator  

Suzanne Coutinho

Layout Coordinator

Deepika Naik

 

 

 

  

About the Authors

Robert Smallshire is a founding director of Sixty North, a software consulting and training business in Norway providing services throughout Europe, and which uses Python extensively. Robert has worked in senior architecture and technical management roles for several software companies providing tools in the energy sector. He has dealt with understanding, designing, advocating and implementing effective architectures for sophisticated scientific and enterprise software in Python, C++, C# and F# and Javascript. Robert is a regular speaker at conferences, meetups and corporate software events and can be found speaking about topics as diverse as behavioural microeconomics in software development to implementing web services on 8-bit microcontrollers. He is organiser of the Oslo Python group and holds a Ph.D. in a natural science.

 

 

 

 

Austin Bingham is a founding director of Sixty North, a software consulting, training, and application development company. A native of Texas, in 2008 Austin moved to Stavanger, Norway where he helped develop industry-leading oil reservoir modeling software in C++ and Python. Prior to that he worked at National Instruments developing LabVIEW, at Applied Research Labs (Univ. of Texas at Austin) developing sonar systems for the U.S. Navy, and at a number of telecommunications companies. He is an experienced presenter and teacher, having spoken at numerous conferences, software groups, and internal corporate venues. Austin is also an active member of the open source community, contributing regularly to various Python and Emacs projects, and he's the founder of Stavanger Software Developers, one of the largest and most active social software groups in Stavanger. Austin holds a Master of Science in Computer Engineering from the University of Texas at Austin.

www.PacktPub.com

For support files and downloads related to your book, please visit www.PacktPub.com.

Did you know that Packt offers eBook versions of every book published, with PDF and ePub files available? You can upgrade to the eBook version at www.PacktPub.com and as a print book customer, you are entitled to a discount on the eBook copy. Get in touch with us at [email protected] for more details.

At www.PacktPub.com, you can also read a collection of free technical articles, sign up for a range of free newsletters and receive exclusive discounts and offers on Packt books and eBooks.

 

https://www.packtpub.com/mapt

 

Get the most in-demand software skills with Mapt. Mapt gives you full access to all Packt books and video courses, as well as industry-leading tools to help you plan your personal development and advance your career.

Why subscribe?

Fully searchable across every book published by Packt

Copy and paste, print, and bookmark content

On demand and accessible via a web browser

Customer Feedback

Thanks for purchasing this Packt book. At Packt, quality is at the heart of our editorial process. To help us improve, please leave us an honest review on this book's Amazon page at www.amazon.com/dp/1788293185.

If you'd like to join our team of regular reviewers, you can e-mail us at [email protected]. We award our regular reviewers with free eBooks and videos in exchange for their valuable feedback. Help us be relentless in improving our products!

Table of Contents

Preface

Python Promo

Overview

What is Python?

It's a programming language!

Versions of the Python language

It's a standard library!

It's a philosophy

The journey of a thousand miles…

Errata and Suggestions

Conventions Used in This Book

Downloading the example code

Downloading the color images of this book

Getting started

Obtaining and installing Python 3

Windows

macOS

Linux

Starting Python command line REPL

Leaving the REPL

Windows

Unix

Code structure and significant indentation

Python culture

Importing standard library modules

Getting help()

Counting fruit with math.factorial()

Different types of numbers

Scalar data types: integers, floats, None and bool

int

float

Special floating point values

Promotion to float

None

bool

Relational operators

Rich comparison operators

Control flow: if-statements and while-loops

Conditional control flow: The if-statement

if...else

if...elif...else

Conditional repetition: the while-loop

Exiting loops with break

Summary

Strings and Collections

str – an immutable sequence of Unicode code points

String quoting styles

Moment of zen

Concatenation of adjacent strings

Multiline strings and newlines

Raw strings

The str constructor

Strings as sequences

String methods

Strings with Unicode

The bytes type  – an immutable sequence of bytes

Literal bytes

Converting between bytes and str

list – a sequence of objects

The dict type – associating keys with values

The For-loops – iterating over series of items

Putting it all together

Summary

Modularity

Organizing code in a .py file

Running Python programs from the operating system shell

Importing modules into the REPL

Defining functions

Organizing our module into functions

The __name__  type and executing modules from the command line

The Python execution model

The difference between modules, scripts, and programs

Setting up a main function with command line argument

Accepting command line arguments

Moment of zen

Docstrings

Comments

Shebang

Executable Python programs on Linux and Mac

Executable Python programs on Windows

Summary

Built-in types and the object model

The nature of Python object references

Reassigning a reference

Assigning one reference to another

Exploring value vs. identity with id()

Testing for equality of identity with is

Mutating without mutating

References to mutable objects

Equality of value (equivalence) versus equality of identity

Argument passing semantics – pass by object-reference

Modifying external objects in a function

Binding new objects in a function

Argument passing is reference binding

Python return semantics

Function arguments in detail

Default parameter values

Keyword arguments

When are default arguments evaluated?

The Python type system

Dynamic typing in Python

Strong typing in Python

Variable declaration and scoping

The LEGB rule

Scopes in action

Identical names in global and local scope

The global keyword

Moment of zen

Everything is an object

Inspecting a function

Summary

Exploring Built-in Collection types

tuple – an immutable sequence of objects

Literal tuples

Tuple element access

The length of a tuple

Iterating over a tuple

Concatenating and repetition of tuples

Nested tuples

Single-element tuples

Empty tuples

Optional parentheses

Returning and unpacking tuples

Swapping variables with tuple unpacking

The tuple constructor

Membership tests

Strings in action

The length of a string

Concatenating strings

Joining strings

Splitting strings

Moment of zen

Partitioning strings

String formatting

Other string methods

range – a collection of evenly spaced integers

Starting value

Step argument

Not using range: enumerate()

list in action

Negative indexing for lists (and other sequences)

Slicing lists

Copying lists

Shallow copies

Repeating lists

Finding list elements with index()

Membership testing with count() and in

Removing list elements by index with del

Removing list elements by value with remove()

Inserting into a list

Concatenating lists

Rearranging list elements

Out-of-place rearrangement

Dictionaries

Copying dictionaries

Updating dictionaries

Iterating over dictionary keys

Iterating over dictionary values

Iterating over key-value pairs

Membership testing for dictionary keys

Removing dictionary items

Mutability of dictionaries

Pretty printing

set – an unordered collection of unique elements

The set constructor

Iterating over sets

Membership testing of sets

Adding elements to sets

Removing elements from sets

Copying sets

Set algebra operations

Union

Intersection

Difference

Symmetric difference

Subset relationships

Collection protocols

Container protocol

Sized protocol

Iterable protocol

Sequence protocol

Other protocols

Summary

Exceptions

Exceptions and control flow

Handling exceptions

Handling multiple exceptions

Programmer errors

Empty blocks – the pass statement

Exception objects

Imprudent return codes

Re-raising exceptions

Exceptions are part of your function's API

Exceptions raised by Python

Catching exceptions

Raising exceptions explicitly

Guard clauses

Exceptions, APIs, and protocols

IndexError

ValueError

KeyError

Choosing not to guard against TypeError

Pythonic style – EAFP versus LBYL

Clean-up actions

Moment of zen

Platform-specific code

Summary

Comprehensions, iterables, and generators

Comprehensions

List comprehensions

List comprehension syntax

Elements of a list comprehension

Set comprehensions

Dictionary comprehensions

Comprehension complexity

Filtering comprehensions

Combining filtering and transformation

Moment of zen

Iteration protocols

An example of the iteration protocols

A more practical example of the iteration protocols

Generator functions

The yield keyword

Generators are iterators

When is generator code executed?

Maintaining explicit state in the generator function

The first stateful generator: take()

The second stateful generator: distinct()

Understand these generators!

Lazy generator pipelines

Laziness and the infinite

Generating the Lucas series

Generator expressions

Batteries included iteration tools

Introducing itertools

Sequences of booleans

Merging sequences with zip

More than two sequences with zip()

Lazily concatenating sequences with chain()

Pulling it all together

Summary

Generators

Iteration tools

Defining new types with classes

Defining classes

Instance methods

Instance initializers

A lack of access modifiers

Validation and invariants

Adding a second class

Collaborating classes

Moment of zen

Booking seats

Allocating seats to passengers

Naming methods for implementation details

Implementing relocate_passenger()

Counting available seats

Sometimes the only object you need is a function

Making Flight create boarding cards

Polymorphism and duck-typing

Refactoring Aircraft

Inheritance and implementation sharing

A base class for aircraft

Inheriting from Aircraft

Hoisting common functionality into a base class

Summary

Files and Resource Management

Files

Binary and text modes

The important of encoding

Opening a file for writing

Writing to files

Closing files

The file outside of Python

Reading files

Readline line by line

Reading multiple lines at once

Appending to files

File objects as iterators

Context Managers

Managing resources with finally

The with-blocks

Moment of zen

Binary files

The BMP file format

Bitwise operators

Writing a BMP file

Reading binary files

File-like objects

You've already seen file-like objects!

Using file-like objects

Other resources

Summary

Unit testing with the Python standard library

Test cases

Fixtures

Assertions

Unit testing example: text analysis

Running the initial tests

Making the test pass

Using fixtures to create temporary files

Using the new fixtures

Using assertions to test behavior

Counting lines

Counting characters

Testing for exceptions

Testing for file existence

Moment of zen

Summary

Debugging with PDB

Debugging commands

Palindrome debugging

Bug hunting with PDB

Finding infinite loops with sampling

Setting explicit breaks

Stepping through execution

Fixing the bug

Summary

Afterword – Just the Beginning

Virtual Environments

Creating a virtual environment

Activating a virtual environment

Deactivating a virtual environment

Other tools for working with virtual environments

Packaging and Distribution

Configuring a package with distutils

Installing with distutils

Packaging with distutils

Installing Third-Party Packages

Installing pip

The Python Package Index

Installing with pip

Installing Local Packages with pip

Uninstalling Packages

Preface

Welcome to The Python Apprentice! Our goal with this book is to give you a practical and thorough introduction to the Python programming language, providing you with the tools and insight you need to be a productive member of nearly any Python project. Python is a big language, and its not our intention with this book to cover everything there is to know. Rather we want to help you build solid foundations, orient you in the sometimes bewildering universe of Python, and put you in a position to direct your own continued learning.

This book is primarily aimed at people with some experience programming in another language. If you're currently programming in any of the mainstream imperative or object-oriented languages like C++, C#, or Java, then you'll have the background you need to get the most out of this book. If you have experience in other types of languages – for example, functional or actor-based – then you may have a bit steeper learning curve with Python, but you won't encounter any serious difficulties. Most programmers find Python very approachable and intuitive, and with just a little practice they quickly become comfortable with it.

On the other hand, if you don't have any experience with programming this book may be a bit daunting. You'll be learning not just a programming language but many of the topics and issues common to all languages at the same time. And to be fair, we don't spend a lot of time trying to explain these areas of "assumed knowledge". This doesn't mean you can't learn from this book! It just means that you might have to work a bit harder, read sections multiple times, and perhaps get guidance from others. The reward for this effort, though, is that you'll start to develop the knowledge and instincts for approaching other languages, and this is a critical skill for the professional programmer.

In this first chapter we'll take a quick tour of the Python language. We'll cover what Python is (hint: it's more than just a language!), take a look at how it was – and still is – developed, and get a sense of what makes it so appealing to so many programmers. We'll also give a brief preview of how the rest of the book is structured.

Python Promo

To start with, what's so great about Python? Why do you want to learn it? There are lots of good answers to those questions. One is that Python is powerful. The Python language is expressive and productive, it comes with a great standard library, and it's the center of a huge universe of wonderful third-party libraries. With Python you can build everything from simple scripts to complex applications, you can do it quickly, you can do it safely, and you can do it with fewer lines of code than you might think possible.

But that's just one part of what makes Python great. Another is that Python is wonderfully open. Its open-source, so you can get to know every aspect of it if you want. At the same time, Python is hugely popular and has a great community to support you when you run into trouble. This combination of openness and large userbase means that almost anyone – from casual programmers to professional software developers – can engage with the language at the level they need.

Another benefit of a large user base is that Python is showing up in more and more places. You may be wanting learn Python simply because it's the language of some technology you want to use, and this is not surprising – many of the most popular web and scientific packages in the world are written in Python.

But for many people those reasons take back-seat to something more important: Python is fun! Python's expressive, readable style, quick edit-and-run development cycle, and "batteries included" philosophy mean that you can sit down and enjoy writing code rather than fighting compilers and thorny syntax. And Python will grow with you. As your experiments become prototypes and your prototypes become products, Python makes the experience of writing software not just easier but truly enjoyable.

In the words of Randall Munroe, "Come join us! Programming is fun again!"

Overview

This book comprises 10 chapters (not including this one). The chapters build on one another, so unless you've already had some exposure to Python you'll need to follow them in order. We'll start with getting Python installed into your system and orienting you a bit.

We'll then cover language elements, features, idioms, and libraries, all driven by working examples that you'll be able to build along with the text. We're firm believers that you'll learn more by doing than by just reading, so we encourage you to run the examples yourself.

By the end of the book you'll know the fundamentals of the Python language. You'll also know how to use third-party libraries, and you'll know the basics of developing them yourself. We'll even cover the basics of testing so that you can ensure and maintain the quality of the code you develop.

The chapters are:

Getting started: We go through installing Python, look at some of the basic Python tools, and cover the core elements of the language and syntax.

Strings and Collections: We look at some of the fundamental complex data types: strings, byte sequences, lists, and dictionaries.

Modularity: We look at the tools Python has for structuring your code, such as functions and modules.

Built-in types and the object model: We examine Python's type system and object system in detail, and we develop a strong sense of Python’s reference semantics.

Exploring Built-in Collection Types: We go into more depth on some of the Python collection types, as well as introduce a few more.

Exceptions: We learn about Python's exception-handling system and the central role that exceptions play in the language.

Comprehensions, iterables, and generators: We explore the elegant, pervasive, and powerful sequence-oriented parts of Python such as comprehensions and generator functions.

Defining new types with classes: We cover developing your own complex data types in Python using classes to support object-oriented programming.

Files and Resource Management: We look at how to work with files in Python, and we cover the tools Python has for Resource Management.

Unit testing with the Python standard library: We show you how to use Python's unittest package to produce defect-free code that works as expected.

What is Python?

It's a programming language!

So what is Python? Simply put, Python is a programming language. It was initially developed by Guido van Rossum in the late 1980's in the Netherlands. Guido continues to be actively involved in guiding the development and evolution of the language, so much so that he's been given the title "Benevolent Dictator for Life", or, more commonly, BDFL. Python is developed as an open-source project and is free to download and use as you wish. The non-profit Python Software Foundation manages Python's intellectual property, plays a strong role in promoting the language, and in some cases funds its development.

On a technical level, Python is a strongly typed language. This means that every object in the language has a definite type, and there's generally no way to circumvent that type. At the same time, Python is dynamically typed, meaning that there's no type-checking of your code prior to running it. This is in contrast to statically typed languages like C++ or Java where a compiler does a lot of type-checking for you, rejecting programs which misuse objects. Ultimately, the best description of the Python type system is that it uses duck-typing where an object's suitability for a context is only determined at runtime. We'll cover this in more detail in Chapter 8, Defining new types with classes.

Python is a general-purpose programming language. It's not intended for use in any particular domain or environment, but instead can be fruitfully used for a wide variety of tasks. There are, of course, some areas where it's less suitable than others – for example in extremely time-sensitive or memory-constrained environments – but for the most part Python is as flexible and adaptable as many modern programming language, and more so than most.

Python is an interpreted language. This is a bit of a misstatement, technically, because Python is normally compiled into a form of byte-code before it's executed. However, this compilation happens invisibly, and the experience of using Python is normally one of immediately executing code without a noticeable compilation phase. This lack of an interruption between editing and running is one of the great joys of working with Python.

The syntax of Python is designed to be clear, readable, and expressive. Unlike many popular languages, Python uses white-space to delimit code blocks, and in the process does away with reams of unnecessary parentheses while enforcing a universal layout. This means that all Python code looks alike in important ways, and you can learn to read Python very quickly. At the same time, Python's expressive syntax means that you can get a lot of meaning into a single line of code. This expressive, highly-readable code means that Python maintenance is relatively easy.

There are multiple implementations of the Python language. The original – and still by far the most common – implementation is written in C. This version is commonly referred to as CPython. When someone talks about "running Python", it's normally safe to assume that they are talking about CPython, and this is the implementation that we'll be using for this book.

Other implementations of Python include:

Jython, written to target the Java Virtual Machine

IronPython, written to target the .NET platform

PyPy, written (somewhat circularly) in a language called RPython which is designed for developing dynamic languages like Python

These implementations generally trail behind CPython, which is considered to be the "standard" for the language. Much of what you will learn in this book will apply to all of these implementations.

Versions of the Python language

There are two important versions of the Python language in common use right now: Python 2 and Python 3. These two versions represent changes in some key elements of the language, and code written for one will not generally work for the other unless you take special precautions. Python 2 is older and more well-established than Python 3, but Python 3 addresses some known shortcomings in the older version. Python 3 is the definite future of Python, and you should use it if at all possible.

While there are some critical differences between Python 2 and 3, most of the fundamentals of the two version are the same. If you learn one, most of what you know transfers cleanly to the other. In this book we'll be teaching Python 3, but we'll point out important differences between the versions when necessary.

It's a standard library!

Beyond being a programming language, Python comes with a powerful and broad standard library. Part of the Python philosophy is "batteries included", meaning that you can use Python for many complex, real-world tasks out-of-the box, with no need to install third-party packages. This is not only extremely convenient, but it means that it's easier to get started learning Python by using interesting, engaging examples – something we aim for in this book!

Another great effect of the "batteries included" approach is that it means that many scripts – even non-trivial ones – can be run immediately on any Python installation. This removes a common, annoying barrier to installing software that you can face with other languages.

The standard library has a generally high level of good documentation. The APIs are well documented, and the modules often have good narrative descriptions with quick start guides, best practice information, and so forth. The standard library documentation is always available online, and you can also install it locally if you want to.

Since the standard library is such an important part of Python, we'll be covering parts of it throughout this book. Even so, we won't be covering more than a small fraction of it, so you're encouraged to explore it on your own.

It's a philosophy

Finally, no description of Python would be complete with mentioning that, to many people, Python represents a philosophy for writing code. Principles of clarity and readability are part of what it means to write correct or pythonic code. It's not always clear what pythonic means in all circumstances, and sometimes there may be no single correct way to write something. But the fact that the Python community is concerned about issues like simplicity, readability, and explicitness means that Python code tends to be more…well…beautiful!

Many of Python's principles are embodied in the so-called Zen of Python. The "zen" isn't a hard-and-fast set of rules, but rather a set of guidelines or touchstones to keep in mind when coding. When you find yourself trying to decide between several courses of action, these principles can often give you a nudge in the right direction. We'll be highlighting elements from the "Zen of Python" throughout this book.

The journey of a thousand miles…

We think Python is a great language, and we're excited to help you get started with it. By the time you get through this book, you will be able to write substantial Python programs, and you'll be able to read even more complex ones. More importantly, you'll have the foundation you need to go out and discover all of the more advanced topics in the language, and hopefully we'll get you excited enough about Python to actually do so. Python is a big language with a huge eco-system of software built in and around it, and it can be a real adventure to discover everything it has to offer.

Welcome to Python!

Though more and more projects are starting to be "primarily Python 3" or even "Python 3 only".

This book came about by circuitous means. In 2013, when we incorporated our Norway-based sofware consultancy and training business Sixty North, we were courted by Pluralsight, a publisher of online video training material, to produce Python training videos for the rapidly growing MOOC market. At the time, we had no experience of producing video training material, but we were sure we wanted to carefully structure our introductory Python content to respect certain constraints. For example, we wanted an absolute minimum of forward references since those would be very inconvenient for our viewers. We're both men of words who live by Turing Award winner Leslie Lamport's maxim "If you're thinking without writing you only think you're thinking", so it was natural for us to attack video course production by first writing a script.

In short order our online video course was written, recorded, and published by Pluralsight as Python Fundamentals, to a hugely positive reception which has sustained for several years now. From the earliest days we had in mind that the script could form the basis of a book, although it's fair to say we underestimated the effort required to transform the content from a good script into a better book.

The Python Apprentice is the result of that transformation. It can be used either as a standalone Python tutorial, or as the companion volume to our video course, depending on which style of learning suits you best. The Python Apprentice is the first in a trilogy of three books, comprising in addition The Python Journeyman and The Python Master. The two later books correspond to our subsequent Pluralsight courses Python – Beyond the Basics and Advanced Python (coming soon!).

Errata and Suggestions

All the material in this book has been thoroughly reviewed and tested; nevertheless, it's inevitable that some mistakes have crept in. If you do spot a mistake, we'd really appreciate it if you'd let us know via the Leanpub Python Apprentice Discussion page so we can make amends and deploy a new version.

Downloading the example code

You can download the example code files for this book from your account at http://www.packtpub.com. 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.

You can download the code files by following these steps:

Log in or register to our website using your e-mail address and password.

Hover the mouse pointer on the

SUPPORT

tab at the top.

Click on

Code Downloads & Errata

.

Enter the name of the book in the

Search

box.

Select the book for which you're looking to download the code files.

Choose from the drop-down menu where you purchased this book from.

Click on

Code Download

.

Once the file is downloaded, please make sure that you unzip or extract the folder using the latest version of:

WinRAR / 7-Zip for Windows

Zipeg / iZip / UnRarX for Mac

7-Zip / PeaZip for Linux

The code bundle for the book is also hosted on GitHub at https://github.com/PacktPublishing/The-Python-Apprentice. We also have other code bundles from our rich catalog of books and videos available at https://github.com/PacktPublishing/. Check them out!

Downloading the color images of this book

We also provide you with a PDF file that has color images of the screenshots/diagrams used in this book. The color images will help you better understand the changes in the output. You can download this file from https://www.packtpub.com/sites/default/files/downloads/ThePythonApprentice_ColorImages.pdf.

Getting started

In this chapter we'll cover obtaining and installing Python on your system for Windows, Ubuntu Linux, and macOS. We'll also write our first basic Python code and become a acquainted with the essentials Python programming culture, such as the Zen of Python, while never forgetting the comical origins of the name of the language.

Obtaining and installing Python 3

There are two major versions of the Python language, Python 2 which is the widely deployed legacy language and Python 3 which is the present and future of the language. Much Python code will work without modification between the last version of Python 2 (which is Python 2.7 (https://www.python.org/download/releases/2.7/)) and recent versions of Python 3, such as Python 3.5 (https://www.python.org/download/releases/3.5.1/). However, there are some key differences between the major versions, and in a strict sense the languages are incompatible. We'll be using Python 3.5 for this book, but we'll point out key differences with Python 2 as we go. It's also very likely that, this being a book on Python fundamentals, everything we present will apply to future versions of Python 3, so don't be afraid to try those as they become available.

Before we can start programming in Python we need to get hold of a Python environment. Python is a highly portable language and is available on all major operating systems. You will be able to work through this book on Windows, Mac or Linux, and the only major section where we diverge into platform specifics is coming right up — as we install Python 3. As we cover the three platforms, feel free to skip over the sections which aren’t relevant for you.

Windows

The following are the steps to be performed for Windows platform:

For Windows you need to visit the official Python website, and then head to the Downloads page by clicking the link on the left. For Windows you should choose one of the MSI installers depending on whether you're running on a 32- or 64-bit platform.

Download and run the installer.

In the installer, decide whether you only want to install Python for yourself, or for all users of your machine.

Choose a location for the Python distribution. The default will be inC:\Python35 in the root of the C: drive. We don't recommended installing Python into Program Files because the virtualized file store used to isolate applications from each other in Windows Vista and later can interfere with easily installing third-party Python packages.

On the Customize Python page of the wizard we recommend keeping the defaults, which use less than 40 MB of space.

In addition to installing the Python runtime and standard library, the installer will register various file types, such as *.py files, with the Python interpreter.

Once Python has been installed, you'll need to add Python to your system PATH environment variable. To do this, from the Control Panel choose System and Security, then System. Another way to get here easily is to hold down your Windows key and press the Break key on your keyboard. Using the task pane on the left choose Advanced System Settings to open the Advanced tab of the System Properties dialog. Click Environment variables to open the child dialog.

If you have Administrator privileges you should be able to add the pathsC:\Python35 and C:\Python35\Scripts to the semicolon separated list of entries associated with the PATH system variable. If not, you should be able to create, or append to, a PATH variable specific to your user containing the same value.

Now open a new console window — either Powershell or cmd will work fine — and verify that you can run python from the command line:

> python

Python 3.5.0 (v3.5.0:374f501f4567, Sep 13 2015, 02:27:37) [MSC v.1900 64 bit (AMD64)] on win32

Type "help", "copyright", "credits" or "license" for more information.

>>>

Welcome to Python!

The triple arrow prompt shows you that Python is waiting for your input.

At this point you might want to skip forward whilst we show how to install Python on Mac and Linux.

macOS

For macOS you need to visit the official Python website at http://python.org. Head to the Download page by clicking the link on the left. On the Download page, find the macOS installer matching your version of macOS and click the link to download it.

A DMG Disk Image file downloads, which you open from your Downloads stack or from the Finder.

In the Finder window that opens you will see the file Python.mpkg multipackage installer file. Use the "secondary" click action to open the context menu for that file. From that menu, select Open.

On some versions of macOS you will now be told that the file is from an unidentified developer. Press the Open button on this dialog to continue with the installation.

You are now in the Python installer program. Follow the directions, clicking through the wizard.

There is no need to customize the install, and you should keep the standard settings. When it's available, click the Install button to install Python. You may be asked for your password to authorize the installation. Once the installation completes click Close to close the installer.

Now that Python 3 is installed, open a terminal window and verify that you can run Python 3 from the command line:

> python

Python 3.5.0 (default, Nov 3 2015, 13:17:02)

[GCC 4.2.1 Compatible Apple LLVM 6.1.0 (clang-602.0.53)] on darwin

Type "help", "copyright", "credits" or "license" for more information.

>>>

Welcome to Python!

The triple arrow prompt shows that Python is waiting for your input.

Linux

To install Python on Linux you will want to use your system's package manager. We'll show how to install Python on a recent version of Ubuntu, but the process is very similar on most other modern Linux distributions.

On Ubuntu, first start the Ubuntu Software Center. This can usually be run by clicking on it's icon in the launcher. Alternatively, you can run it from the dashboard by searching on Ubuntu Software Center and clicking the selection.

Once you're in the software center, enter the search term python 3.5 in the search bar in the upper right-hand corner and press return.

One of the results you'll get will say Python (v3.5) with Python Interpreter (v3.5) in smaller type beneath it. Select this entry and click the Install button that appears.

You may need to enter your password to install the software at this point.

You should now see a progress indicator appear, which will disappear when installation is complete.

Open a terminal (using Ctrl+Alt+T) and verify that you can run Python 3.5 from the command line:

$ python3.5

Python 3.5.0+ (default, Oct 11 2015, 09:05:38)

[GCC 5.2.1 20151010] on linux

Type "help", "copyright", "credits" or "license" for more information.

>>>

Welcome to Python!

The triple arrow prompt shows you that Python is waiting for your input.