Scientific Computing with Python 3 - Claus Führer - E-Book

Scientific Computing with Python 3 E-Book

Claus Führer

0,0
39,59 €

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

Python can be used for more than just general-purpose programming. It is a free, open source language and environment that has tremendous potential for use within the domain of scientific computing. This book presents Python in tight connection with mathematical applications and demonstrates how to use various concepts in Python for computing purposes, including examples with the latest version of Python 3. Python is an effective tool to use when coupling scientific computing and mathematics and this book will teach you how to use it for linear algebra, arrays, plotting, iterating, functions, polynomials, and much more.

Das E-Book können Sie in Legimi-Apps oder einer beliebigen App lesen, die das folgende Format unterstützen:

EPUB
MOBI

Seitenzahl: 311

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.



Table of Contents

Scientific Computing with Python 3
Credits
About the Authors
About the Reviewer
www.PacktPub.com
Why subscribe?
Acknowledgement
Preface
What this book covers
What you need for this book
Who this book is for
Python vs Other Languages
Other Python literature
Conventions
Reader feedback
Customer support
Downloading the example code
Downloading the color images of this book
Errata
Piracy
Questions
1. Getting Started
Installation and configuration instructions
Installation
Anaconda
Configuration
Python Shell
Executing scripts
Getting Help
Jupyter – Python notebook
Program and program flow
Comments
Line joining
Basic types
Numbers
Strings
Variables
Lists
Operations on lists
Boolean expressions
Repeating statements with loops
Repeating a task
Break and else
Conditional statements
Encapsulating code with functions
Scripts and modules
Simple modules - collecting functions
Using modules and namespaces
Interpreter
Summary
2. Variables and Basic Types
Variables
Numeric types
Integers
Plain integers
Floating point numbers
Floating point representation
Infinite and not a number
Underflow - Machine Epsilon
Other float types in NumPy
Complex numbers
Complex Numbers in Mathematics
The j notation
Real and imaginary parts
Booleans
Boolean operators
Boolean casting
Automatic Boolean casting
Return values of and and or
Boolean and integer
Strings
Operations on strings and string methods
String formatting
Summary
Exercises
3. Container Types
Lists
Slicing
Strides
Altering lists
Belonging to a list
List methods
In–place operations
Merging lists – zip
List comprehension
Arrays
Tuples
Dictionaries
Creating and altering dictionaries
Looping over dictionaries
Sets
Container conversions
Type checking
Summary
Exercises
4. Linear Algebra – Arrays
Overview of the array type
Vectors and matrices
Indexing and slices
Linear algebra operations
Solving a linear system
Mathematical preliminaries
Arrays as functions
Operations are elementwise
Shape and number of dimensions
The dot operations
The array type
Array properties
Creating arrays from lists
Accessing array entries
Basic array slicing
Altering an array using slices
Functions to construct arrays
Accessing and changing the shape
The shape function
Number of dimensions
Reshape
Transpose
Stacking
Stacking vectors
Functions acting on arrays
Universal functions
Built-in universal functions
Create universal functions
Array functions
Linear algebra methods in SciPy
Solving several linear equation systems with LU
Solving a least square problem with SVD
More methods
Summary
Exercises
5. Advanced Array Concepts
Array views and copies
Array views
Slices as views
Transpose and reshape as views
Array copy
Comparing arrays
Boolean arrays
Checking for equality
Boolean operations on arrays
Array indexing
Indexing with Boolean arrays
Using where
Performance and Vectorization
Vectorization
Broadcasting
Mathematical view
Constant functions
Functions of several variables
General mechanism
Conventions
Broadcasting arrays
The broadcasting problem
Shape mismatch
Typical examples
Rescale rows
Rescale columns
Functions of two variables
Sparse matrices
Sparse matrix formats
Compressed sparse row
Compressed Sparse Column
Row-based linked list format
Altering and slicing matrices in LIL format
Generating sparse matrices
Sparse matrix methods
Summary
6. Plotting
Basic plotting
Formatting
Meshgrid and contours
Images and contours
Matplotlib objects
The axes object
Modifying line properties
Annotations
Filling areas between curves
Ticks and ticklabels
Making 3D plots
Making movies from plots
Summary
Exercises
7. Functions
Basics
Parameters and arguments
Passing arguments - by position and by keyword
Changing arguments
Access to variables defined outside the local namespace
Default arguments
Beware of mutable default arguments
Variable number of arguments
Return values
Recursive functions
Function documentation
Functions are objects
Partial application
Using Closures
Anonymous functions - the  lambda keyword
The lambda construction is always replaceable
Functions as decorators
Summary
Exercises
8. Classes
Introduction to classes
Class syntax
The __init__ method
Attributes and methods
Special methods
Reverse operations
Attributes that depend on each other
The property function
Bound and unbound methods
Class attributes
Class methods
Subclassing and inheritance
Encapsulation
Classes as decorators
Summary
Exercises
9. Iterating
The for statement
Controlling the flow inside the loop
Iterators
Generators
Iterators are disposable
Iterator tools
Generators of recursive sequences
 Arithmetic geometric mean
Convergence acceleration
List filling patterns
List filling with the append method
List from iterators
Storing generated values
When iterators behave as lists
Generator expression
Zipping iterators
Iterator objects
Infinite iterations
The while loop
Recursion
Summary
Exercises
10. Error Handling
What are exceptions?
Basic principles
Raising exceptions
Catching exceptions
User-defined exceptions
Context managers - the with statement
Finding Errors: Debugging
Bugs
The stack
The Python debugger
Overview - debug commands
Debugging in IPython
Summary
11. Namespaces, Scopes, and Modules
Namespace
Scope of a variable
Modules
Introduction
Modules in IPython
The IPython magic command
The variable __name__
Some useful modules
Summary
12. Input and Output
File handling
Interacting with files
Files are iterable
File modes
NumPy methods
savetxt
 loadtxt
Pickling
Shelves
Reading and writing Matlab data files
Reading and writing images
Summary
13. Testing
Manual testing
Automatic testing
Testing the bisection algorithm
Using unittest package
Test setUp and tearDown methods
Parameterizing tests
Assertion tools
Float comparisons
Unit and functional tests
Debugging
Test discovery
Measuring execution time
Timing with a magic function
Timing with the Python module timeit
Timing with a context manager
Summary
Exercises
14. Comprehensive Examples
Polynomials
Theoretical background
Tasks
The polynomial class
Newton polynomial
Spectral clustering
Solving initial value problems
Summary
Exercises
15. Symbolic Computations - SymPy
What are symbolic computations?
Elaborating an example in SymPy
Basic elements of SymPy
Symbols - the basis of all formulas
Numbers
Functions
Undefined functions
Elementary Functions
Lambda - functions
Symbolic Linear Algebra
Symbolic matrices
Examples for Linear Algebra Methods in SymPy
Substitutions
Evaluating symbolic expressions
Example: A study on the convergence order of Newton's Method
Converting a symbolic expression into a numeric function
A study on the parameter dependency of polynomial coefficients
Summary
References

Scientific Computing with Python 3

Scientific Computing with Python 3

Copyright © 2016 Packt Publishing

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: December 2016

Production reference: 1141216

Published by Packt Publishing Ltd.

Livery Place

35 Livery Street

Birmingham 

B3 2PB, UK.

ISBN 978-1-78646-351-7

www.packtpub.com

Credits

Authors

Claus Führer

Jan Erik Solem

Olivier Verdier

Copy Editor

Vikrant Phadkay

Sneha Singh

Reviewers

 Helmut Podhaisky

Project Coordinator

Nidhi Joshi 

Commissioning Editor

Veena Pagare

Proofreader

Safis Editing

Acquisition Editor

Sonali Vernekar

Indexer

Mariammal Chettiyar

Content Development Editor

Aishwarya Pandere

Graphics

Disha Haria

Technical Editor

Karan Thakkar

Production Coordinator

Arvindkumar Gupta

About the Authors

Claus Führer is a professor of scientific computations at Lund University, Sweden. He has an extensive teaching record that includes intensive programming courses in numerical analysis and engineering mathematics across various levels in many different countries and teaching environments. Claus also develops numerical software in research collaboration with industry and received Lund University’s Faculty of Engineering Best Teacher Award in 2016.

Jan Erik Solem is a Python enthusiast, former associate professor, and currently the CEO of Mapillary, a street imagery computer vision company. He has previously worked as a face recognition expert, founder and CTO of Polar Rose, and computer vision team leader at Apple. Jan is a World Economic Forum technology pioneer and won the Best Nordic Thesis Award 2005-2006 for his dissertation on image analysis and pattern recognition. He is also the author of "Programming Computer Vision with Python" (O'Reilly 2012).

Olivier Verdier began using Python for scientific computing back in 2007 and received a PhD in mathematics from Lund University in 2009. He has held post-doctoral positions in Cologne, Trondheim, Bergen, and Umeå and is now an associate professor of mathematics at Bergen University College, Norway.

About the Reviewer

Helmut Podhaisky works in the Institute of Mathematics at the Martin Luther University in Halle-Wittenberg, where he teaches mathematics and scientific computing. He has co-authored a book on numerical methods for ordinary differential equations as well as several research papers on numerical methods. For work and fun, he uses Python, Fortran, Octave, Mathematica, and Haskell.

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 PacktCopy and paste, print, and bookmark contentOn demand and accessible via a web browser

Acknowledgement

We want to acknowledge the competent and helpful comments and suggestions by Helmut Podhaisky, Halle University, Germany. To have such a partner in the process of writing a book is a big luck and chance for the authors.

We would also like to express our gratitude towards the reviewers of the first edition of this book, [7], Linda Kann, KTH Stockholm, Hans Petter Langtangen, Simula Research Laboratory, and Alf Inge Wang, NTNU Trondheim.

A book has to be tested in teaching. And here we had fantastic partners: the teaching assistants from the course "Beräkningsprogramering med Python" during the years and the colleagues involved in teaching: Najmeh Abiri, Christian Andersson, Dara Maghdid, Peter Meisrimel, Fatemeh Mohammadi, Azahar Monge, Anna-Maria Persson, Alexandros Sopasakis, Tony Stillfjord, Lund University. Najmeh Abiri also tested most of the Jupyter notebook material which you find on the book's webpage.

A book has not only to be written, it has to be published, and in this process Aishwarya Pandere and Karan Thakkar, PACKT Publishing, were always constructive, friendly and helpful partners bridging different time zones and different text processing tools. Thanks.

Claus Führer, Jan-Erik Solem, Olivier Verdier  Lund, Bergen 2016

Preface

Python can be used for more than just general-purpose programming. It is a free, open source language and environment that has tremendous potential for use within the domain of scientific computing. This book presents Python in tight connection with mathematical applications and demonstrates how to use various concepts in Python for computing purposes, including examples with the latest version of Python 3. Python is an effective tool to use when coupling scientific computing and mathematics and this book will teach you how to use it for linear algebra, arrays, plotting, iterating, functions, polynomials, and much more.

What this book covers

Chapter 1, Getting Started, addresses the main language elements of Python without going into detail. Here we make a brief tour through all. It is a good starting point for those who want to start directly. It is a quick reference for those readers who want in a later chapter understand an example which uses might use constructs like functions before functions were explained in deep .

Chapter 2, Variables and Basic Types, presents the most important and basic types in Python. Float is the more important datatype in scientific computing together with the special numbers nan and inf. Booleans, integers, complex, and strings are other basic datatypes, which will be used throughout this book.

Chapter 3, Container Types, explains how to work with container types, mainly lists. Dictionaries and tuples will be explained as well as indexing and looping, through container objects. Occasionally, one uses even sets as a special container type.

Chapter 4, Linear Algebra, works with the most important objects in linear algebra--vectors and matrices. This book chooses NumPy array as the central tool for describing matrices and even higher order tensors. Arrays have many advanced features and allows also for universal functions acting on matrices or vectors elementwise. The book emphasizes on array indexing, slices, and the dot product as the basic operation in most computing tasks. Some linear algebra examples are worked out to demonstrate the use of SciPy's submodule linalg.

Chapter 5, Advanced Array Concepts, explains some more advanced aspects of arrays. The difference between array copies and views is explained extensively as views make programs using arrays very fast but are often a source for errors, which are hard to debug. The use of Boolean arrays to write effective, compact, and readable code is shown and demonstrated. Finally, the technique of array broadcasting-- a unique feature of NumPy arrays -- is explained by its analogy to operations performed on functions.

Chapter 6, Plotting, shows how to make plots, mainly classical x/yplots but also 3D plots and histograms. Scientific computing requires good tools for visualizing the results. Python's module matplotlib is introduced starting from the handy plotting commands in its submodule pyplot. Finetuning and modifying plots becomes possible by creating graphical objects such as axes. We show how attributes of these objects can be changed and annotations can be made.

Chapter 7, Functions, form the fundamental building block in programming, which is probably nearest to underlying mathematical concepts. Function definition and function calls are explained as the different ways to set function arguments. Anonymous lambda functions are introduced and used in various examples throughout the book.

Chapter 8, Classes, defines objects as instances of classes, which we provide with methods and attributes. In mathematics, class attributes often depend on each other, which requires special programming techniques for setter and getter functions. Basic mathematical operations such as + can be defined for special mathematic datatypes. Inheritance and abstraction are mathematical concepts which are reflected by object oriented programming. We demonstrate the use of inheritance by a simple solver class for ordinary differential equations.

Chapter 9, Iterating, presents iteration using loops and iterators. There is now a chapter in this book without loops and iterations, but here we come to principles of iterators and create own generator objects. In this chapter, you learn why a generator can be exhausted and how infinite loops can be programmed. Python's module itertools is a useful companion for this chapter.

Chapter 10, Error Handling, covers errors and exceptions and how to find and fix them. An error or an exception is an event, which breaks the execution of a program unit. This chapter shows what to do then, that is, how an exception can be handled. You learn to define your own exception classes and how to provide valuable information, which can be used for catching these exceptions. Error handling is more than printing an error message.

Chapter 11, Namespaces, Scopes and Modules, covers Python modules. What are local and global variables? When is a variable known and when is it unknown to a program unit? This is discussed in this chapter. A variable can be passed to a function by a parameter list or tacitly injected by making use of its scope. When should this technique be applied and when not? This chapter tries to give an answer to this central question.

Chapter 12, Input and Output, covers some options for handling data files. Data files are used for storing and providing data for a given problem, often large scale measurements. This chapter describes how this data can be accessed and modified using different formats.

Chapter 13, Testing, focuses on testing for scientific programming. The key tool is unittest, which allows for automatic testing and parametrized tests. By considering the classical bisection algorithm in numerical mathematics, we exemplify different steps to design meaningful tests, which as a side effect also deliver a documentation of the use of a piece of code. Careful testing provides test protocols which can be later helpful when debugging a complex code often written by many different programmers.

Chapter 14, Comprehensive Examples, presents some comprehensive and longer examples together with a brief introduction to the theoretical background and their complete implementation. These examples make use of all constructs shown in the book so far and put them in a larger and more complex context. They are open for extensions by the reader.

Chapter 15, Symbolic Computations - SymPy, speaks about symbolic computations. Scientific computing is mainly numeric computations with inexact data and approximative results. This is contrasted by symbolic computations often formal manipulation, which aims for exact solutions in a closed form expression. In this last chapter of the book, we introduce this technique in Python, which is often used for deriving and verifying theoretically mathematical models and numerical results. We emphasize on high precision floating point evaluation of symbolic expressions.

What you need for this book

You would need Pyhon3.5 or higher, SciPy, NumPy, Matplotlib, IPython shell (we recommend strongly to install Python and its packages through Anaconda). The examples of the book do not have any special hardware requirements on memory and graphics.

Who this book is for

This book is the outcome of a course on Python for scientific computing which is taught at Lund University since 2008. The course expanded over the years, and condensed versions of the material were taught at universities in Cologne, Trondheim, Stavanger, Soran, Lappeenranta and also in computation oriented companies.

Our belief is that Python and its surrounding scientific computing ecosystem — SciPy, NumPY and matplotlib — represent a tremendous progress in scientific computing environment. Python and the aforementioned libraries are free and open source. What’s more, is a modern language featuring all the bells and whistles that this adjective entails: object oriented programming, testing, advanced shell with IPython, etc. When writing this book we had two groups of readers in mind:

The reader who chooses Python as his or her first programming language will use this book in a teacher-led course. The book guides into the different topics and offers background reading and experimenting. A teacher typically selects and orders the material from this book in such a way, that it fits to the specific learning outcomes of an introductory course.The reader who already has some experience in programming, and some taste for scientific computing or mathematics will use this book as a companion when diving into the world of Scipy and Numpy. Programming in Python can be quite different from programming in MATLAB, say. The book wants to point out the "pythonic" way of programming, which makes programming a pleasure.

Our goal is to explain the steps to get started with Python in the context of scientific computing. The book may be read either from the first page to the last, or by picking the bits that seem most interesting. Needless to say, as improving one’s programming skills requires considerable practice, it is highly advisable to experiment and play with the examples and the exercises in the book.

We hope that the readers will enjoy programming with Python, SciPy, NumPY and matplotlib as much as we do.

Python vs Other Languages

When it comes to deciding what language to use for a book on scientific computing many factors come in to play. The learning threshold of the language itself is important for newcomers, here scripting languages usually provide the best options. A wide range of modules for numerical computing is necessary, preferably with a strong developer community. If these core modules are built on a well-tested, optimized foundation of fast libraries like e.g. LAPACK, even better. Finally, if the language is also usable in a wider setting and a wider range of applications, the chance of the reader using the skills learned from this book outside an academic setting is greater. Therefore the choice of Python was a natural one.

In short, Python is

free and open sourcea scripting language, meaning that it is interpreteda modern language (object oriented, exception handling, dynamic typing etc.)concise, easy to read and quick to learnfull of freely available libraries, in particular scientific ones (linear algebra, visualization tools, plotting, image analysis, differential equations solving, symbolic computations, statistics etc.)useful in a wider setting: scientific computing, scripting, web sites, text parsing, etc.widely used in industrial applications

There are other alternatives to Python. Some of them and the differences to Python are listed here.

Java, C++ : Object oriented, compiled languages. More verbose and low level compared to Python. Few scientific libraries.

C, FORTRAN : Low level compiled languages. Both languages are extensively used in scientific computing, where computational time matters. Nowadays these languages are often combined with Python wrappers.

PHP, Ruby, other interpreted languages. PHP is web oriented. Ruby is as flexible as Python but has few scientific libraries.

MATLAB, Scilab, Octave : MATLAB is a tool for matrix computation that evolved for scientific computing. The scientific library is huge. The language features are not as developed as those of Python. Neither free nor open source. SciLab and Octave are open source tools which are syntactically similar to MATLAB.

Haskell : Haskell is a modern functional language and follows different programming paradigms than Python. There are some common constructions like list comprehension. Haskell is rarely used in scientific computing. See also [12].

Other Python literature

Here we give some hints to literature on Python which can serve as complementary sources or as texts for parallel reading. Most introductory books on Python are devoted to teach this language as a general purpose tool. One excellent example which we want to mention here explicitly is [19]. It explains the language by simple examples, e.g. object oriented programming is explained by organizing a pizza bakery.

There are very few books dedicated to Python directed towards scientific computing and engineering. Among these few books we would like to mention the two books by Langtangen which combine scientific computing with the modern "pythonic" view on programming, [16,17].

This "pythonic" view is also the guiding line of our way of teaching programming of numerical algorithms. We try to show how many well-established concepts and constructions in computer science can be applied to problems within scientific computing. The pizza-bakery example is replaced by Lagrange polynomials, generators become time stepping methods for ODEs, and so on.

Finally we have to mention the nearly infinite amount of literature on the web. The web was also a big source of knowledge when preparing this book. Literature from the web often covers things that are new, but can also be totally outdated. The web also presents solutions and interpretations which might contradict each other. We strongly recommend to use the web as additional source, but we consider a "traditional" textbook with the web resources "edited" as the better entry point to a rich new world.

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, and user input are shown as follows: "install additional packages with conda install within your virtual environment"

A block of code is set as follows:

from scipy import * from matplotlib.pyplot import *

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

jupyter notebook

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: "The Jupyter notebook is a fantastic tool for demonstrating your work."

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 [email protected], 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 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 WindowsZipeg / iZip / UnRarX for Mac7-Zip / PeaZip for Linux

The code bundle for the book is also hosted on GitHub at https://github.com/PacktPublishing/Scientific-Computing-with-Python-3. 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/ScientificComputingwithPython3_ColorImages.pdf.

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 [email protected] 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 [email protected], and we will do our best to address the problem.

Chapter 1. Getting Started

In this chapter, we will give a brief overview of the principal syntactical elements of Python. Readers who have just started learning programming are guided through the book in this chapter. Every topic is presented here in a how-to way and will be explained later in the book in a deeper conceptual manner and will also be enriched with many applications and extensions.

Readers who are already familiar with another programming language will come across, in this chapter, the Python way of doing classical language constructs. It offers them a quick start to Python programming.

Both types of readers are encouraged to take this chapter as a brief guideline when zigzagging through the book. However, before we start we have to make sure that everything is in place and you have the correct version of Python installed together with the main modules for Scientific Computing and tools, such as a good editor and a shell, which helps in code developing and testing.

Read the following section, even if you already have access to a computer with Python installed. You might want to adjust things to have a working environment conforming to the presentation in this book.

Installation and configuration instructions

Before diving into the subject of the book you should have all the relevant tools installed on your computer. We will give you some advice and recommend tools that you might want to use. We only describe public domain and free tools.

Installation

There are currently two major versions of Python; the 2.x branch and the new 3.x branch. There are language incompatibilities between these branches and one has to be aware of which one to use. This book is based on the 3.x branch, considering the language up to release 3.5.

For this book you need to install the following:

The interpreter: Python 3.5 (or later)The modules for scientific computing: SciPy with NumPyThe module for graphical representation of mathematical results: matplotlibThe shell: IPythonA Python related editor: Spyder (refer to the following Figure 1.1, Spyder), Geany

The installation of these is eased by the so-called distribution packages. We recommend that you use Anaconda. The default screen of Spyder consists of an editor window on left, a console window in the lower right corner which gives access to an IPython shell and a help window in the upper right corner as shown in the following figure:

Figure 1.1: The default screen of Spyder consists of an editor window on left, a console window in the lower right corner which gives access to an IPython shell and a help window in the upper right corner.

Anaconda

Even if you have Python pre-installed on your computer, we recommend that you create your personal Python environment that allows you to work without the risk of accidentally affecting the software on which your computer's functionality might depend. With a virtual environment, such as Anaconda, you are free to change language versions and install packages without the unintended side-effects.

If the worst happens and you screw things up totally, just delete the Anaconda directory and start again. Running the Anaconda installer will install Python, a Python development environment and editor (Spyder), the shell IPython, and the most important packages for numerical computations, for example SciPy, NumPy, and matplotlib.

You can install additional packages with conda install within your virtual environment created by Anaconda (refer for official documentation from[2]).

Configuration

Most Python codes will be collected in files. We recommend that you use the following header in all your Python files:

from scipy import * from matplotlib.pyplot import *

With this, you make sure that all standard modules and functions used in this book, such as SciPy, are imported. Without this step, most of the examples in the book would raise errors. Many editors, such as Spyder, provide the possibility to create a template for your files. Look for this feature and put the preceding header into a template.

Python Shell

The Python shell is good but not optimal for interactive scripting. We therefore recommend using IPython instead (refer to [26] for the official documentation). IPython can be started in different ways:

In a terminal shell by running the following command:ipythonBy directly clicking on an icon called Jupyter QT Console
When working with Spyder you should use an IPython console (refer to Figure 1.1, Spyder).

Executing scripts

You often want to execute the contents of a file. Depending on the location of the file on your computer, it is necessary to navigate to the correct location before executing the contents of a file.

Use the command cd in IPython in order to move to the directory where your file is located.To execute the contents of a file named myfile.py, just run the following command in the IPython shell
run myfile

Getting Help

Here are some tips on how to use IPython:

To get help on an object, just type ? after the object's name and then return.Use the arrow keys to reuse the last executed commands.You may use the Tab key for completion (that is, you write the first letter of a variable or method and IPython shows you a menu with all the possible completions).Use Ctrl+D to quit.Use IPython's magic functions. You can find a list and explanations by applying  %magic  on the command prompt.

Tip

You can find out more about IPython in its online documentation, [15].

Jupyter – Python notebook

The Jupyter notebook is a fantastic tool for demonstrating your work. Students might want to use it to make and document homework and exercises and teachers can prepare lectures with it, even slides and web pages.

If you have installed Python via Anaconda, you already have everything for Jupyter in place. You can invoke the notebook by running the following command in the terminal window:

jupyter notebook

A browser window will open and you can interact with Python through your web browser.