Search icon
Arrow left icon
All Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Newsletters
Free Learning
Arrow right icon
Scientific Computing with Python 3
Scientific Computing with Python 3

Scientific Computing with Python 3: An example-rich, comprehensive guide for all of your Python computational needs

By Claus Führer , Jan Erik Solem , Olivier Verdier
$19.99 per month
Book Dec 2016 332 pages 1st Edition
eBook
AU$60.99 AU$41.99
Print
AU$75.99
Subscription
$19.99 Monthly
eBook
AU$60.99 AU$41.99
Print
AU$75.99
Subscription
$19.99 Monthly

What do you get with a Packt Subscription?

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

Product Details


Publication date : Dec 23, 2016
Length 332 pages
Edition : 1st Edition
Language : English
ISBN-13 : 9781786463517
Category :
Concepts :
Table of content icon View table of contents Preview book icon Preview Book

Scientific Computing with Python 3

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 NumPy
  • The module for graphical representation of mathematical results: matplotlib
  • The shell: IPython
  • A 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:ipython
  • By 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.

Program and program flow


A program is a sequence of statements that are executed in a top-down order. This linear execution order has some important exceptions:

  • There might be a conditional execution of alternative groups of statements (blocks), which we refer to as branching.
  • There are blocks that are executed repetitively, which is called looping (refer to the following Figure 1.2, Program flow).
  • There are function calls that are references to another piece of code, which is executed before the main program flow is resumed. A function call breaks the linear execution and pauses the execution of a program unit while it passes the control to another unit-a function. When this gets completed, its control is returned to the calling unit.

Figure 1.2: Program flow

Python uses a special syntax to mark blocks of statements: a keyword, a colon, and an indented sequence of statements, which belong to the block (refer to the following Figure 1.3 Block command).

Figure 1.3: Block command

Comments

If a line in a program contains the symbol #, everything following on the same line is considered as a comment:

# This is a comment of the following statement
a = 3  # ... which might get a further comment here  

Line joining

A backslash \ at the end of the line marks the next line as a continuation line, that is, explicit line joining. If the line ends before all the parentheses are closed, the following line will automatically be recognized as a continuation line, that is, implicit line joining.

Basic types


Let's go over the basic data types that you will encounter in Python.

Numbers

A number may be an integer, a real number, or a complex number. The usual operations are:

  • addition and subtraction, + and -
  • multiplication and division, * and /
  • power, **

Here is an example:

2 ** (2 + 2) # 16
1j ** 2 # -1
1. + 3.0j

Note

The symbol for complex numbers

j  is a symbol to denote the imaginary part of a complex number. It is a syntactic element and should not be confused with multiplication by a variable. More on complex numbers can be found in section Numeric Types of Chapter 2, Variables and Basic Types.

Strings

Strings are sequences of characters, enclosed by simple or double quotes:

'valid string'
"string with double quotes"
"you shouldn't forget comments"
'these are double quotes: ".." '

You can also use triple quotes for strings that have multiple lines:

"""This is
 a long,
 long string"""

Variables

A variable is a reference to an object. An object may have several references. One uses the assignment operator = to assign a value to a variable:

x = [3, 4] # a list object is created
y = x # this object now has two labels: x and y
del x # we delete one of the labels
del y # both labels are removed: the object is deleted

The value of a variable can be displayed by the print function:

x = [3, 4] # a list object is created
print(x)

Lists

Lists are a very useful construction and one of the basic types in Python. A Python list is an ordered list of objects enclosed by square brackets. One can access the elements of a list using zero-based indexes inside square brackets:

L1 = [5, 6]
L1[0] # 5
L1[1] # 6
L1[2] # raises IndexError
L2 = ['a', 1, [3, 4]]
L2[0] # 'a'
L2[2][0] # 3
L2[-1] # last element: [3,4]
L2[-2] # second to last: 1

Indexing of the elements starts at zero. One can put objects of any type inside a list, even other lists. Some basic list functions are as follows:

  • list(range(n))} creates a list with n elements, starting with zero:
      print(list(range(5))) # returns [0, 1, 2, 3, 4]
  • len gives the length of a list:
      len(['a', 1, 2, 34]) # returns 4
  • append is used to append an element to a list:
      L = ['a', 'b', 'c']
      L[-1] # 'c'
      L.append('d')
      L # L is now ['a', 'b', 'c', 'd']
      L[-1] # 'd'

Operations on lists

  • The operator + concatenates two lists:

          L1 = [1, 2]
          L2 = [3, 4]
          L = L1 + L2 # [1, 2, 3, 4]
  • As one might expect, multiplying a list with an integer concatenates the list with itself several times:

    n*L is equivalent to making n additions.

          L = [1, 2]
          3 * L # [1, 2, 1, 2, 1, 2]

Boolean expressions

A Boolean expression is an expression that may have the value True or False. Some common operators that yield conditional expressions are as follow:

  •  Equal, ==
  •  Not equal, !=
  •  Less than, Less than or equal to, < , <=
  •  Greater than, Greater than or equal to, > , >=

One combines different Boolean values with or and and. The keyword not , gives the logical negation of the expression that follows. Comparisons can be chained so that, for example, x < y < z is equivalent to x < y and y < z. The difference is that y is only evaluated once in the first example. In both cases, z is not evaluated at all when the first condition, x < y, evaluates to False:

2 >= 4  # False
2 < 3 < 4 # True
2 < 3 and 3 < 2 # False
2 != 3 < 4 or False # True
2 <= 2 and 2 >= 2 # True
not 2 == 3 # True
not False or True and False # True!

Note

Precedence rules

The <, >, <=, >=, !=, and == operators have higher precedence than not.  The operators and, or have the lowest precedence. Operators with higher precedence rules are evaluated before those with lower.

Repeating statements with loops


Loops are used to repetitively execute a sequence of statements while changing a variable from iteration to iteration. This variable is called the index variable. It is successively assigned to the elements of a list, (refer to Chapter 9, Iterating) :

L = [1, 2, 10]
for s in L:
    print(s * 2) # output: 2 4 20

The part to be repeated in the for loop has to be properly indented:

for elt in my_list:
    do_something
    something_else
print("loop finished") # outside the for block

Repeating a task

One typical use of a for loop is to repeat a certain task a fixed number of times:

n = 30
for iteration in range(n):
    do_something # this gets executed n times

Break and else

The for statement has two important keywords: break and else. break quits the for loop even if the list we are iterating is not exhausted:

for x in x_values:
   if x > threshold:
     break
   print(x)

The finalizing else checks whether the for loop was broken with the break keyword. If it was not broken, the block following the else keyword is executed:

for x in x_values:
    if x > threshold:
       break
else:
    print("all the x are below the threshold")

Conditional statements


This section covers how to use conditions for branching, breaking, or otherwise controlling your code. A conditional statement delimits a block that will be executed if the condition is true. An optional block, started with the keyword else  will be executed if the condition is not fulfilled (refer to Figure 1.3, Block command diagram). We demonstrate this by printing |x|, the absolute value of x:

The Python equivalent is as follows:

x = ...
if x >= 0:
    print(x)
else:
    print(-x)

Any object can be tested for the truth value, for use in an if or while statement. The rules for how the truth values are obtained are explained in section Boolean of Chapter 2, Variables and Basic Types.

Encapsulating code with functions


Functions are useful for gathering similar pieces of code in one place. Consider the following mathematical function:

The Python equivalent is as follows:

def f(x):
    return 2*x + 1

In Figure 1.4 Anatomy of a function the  elements of a function block are explained. 

  • The keyword def   tells Python we are defining a function.
  • f is the name of the function.
  • x is the argument, or input of the function.
  • What is after return is called the output of the function.

Figure 1.4: Anatomy of a function

Once the function is defined, it can be called using the following code:

f(2) # 5
f(1) # 3

Scripts and modules


A collection of statements in a file (which usually has a py extension), is called a script. Suppose we put the contents of the following code into a file named smartscript.py:

def f(x):
    return 2*x + 1
z = []
for x in range(10):
    if f(x) > pi:
        z.append(x)
    else:
        z.append(-1)
print(z)

In a Python or IPython shell, such a script can then be executed with the exec command after opening and reading the file. Written as a one-liner it reads:

exec(open('smartscript.py').read())

The IPython shell provides the magic command %run as a handy alternative way to execute a script:

%run smartscript

Simple modules - collecting functions

Often one collects functions in a script. This creates a module with additional Python functionality. To demonstrate this, we create a module by collecting functions in a single file, for example smartfunctions.py:

def f(x):
    return 2*x + 1
def g(x):
    return x**2 + 4*x - 5
def h(x):
    return 1/f(x)
  • These functions can now be used by any external script or directly in the IPython environment.
  • Functions within the module can depend on each other.
  • Grouping functions with a common theme or purpose gives modules that can be shared and used by others.

Again, the command exec(open('smartfunctions.py').read()) makes these functions available to your IPython shell (note that there is also the IPython magic function run). In Python terminology, one says that they are put into the actual namespace.

Using modules and namespaces

Alternatively, the modules  can be imported by the command import. It creates a named namespace. The command from puts the functions into the general namespace:

import smartfunctions
print(smartfunctions.f(2))      # 5

from smartfunctions import g    #import just this function
print(g(1)) # 0
  
from smartfunctions import *    #import all
print(h(2)*f(2))                # 1.0

Tip

Import

The commands import and from  import the functions only once into the respective namespace. Changing the functions after the import has no effect for the current Python session. More on modules can be found in section Modules of Chapter 11, Namespaces, Scopes and Modules.

Interpreter


The Python interpreter executes the following steps:

  • First, run the syntax.
  • Then execute the code line by line.
  • Code inside a function or class declaration is not executed (but checked for syntax).
      def f(x):
          return y**2  
      a = 3   # here both a and f are defined

You can run the preceding program because there are no syntactical errors. You get an error only when you call the function f.

f(2) # error, y is not defined

Summary


In this chapter, we briefly addressed the main language elements of Python without going into detail. You should now be able to start playing with small pieces of code and to test different program constructs. All this is intended as an appetizer for the following chapters in which we will give you the details, examples, exercises, and more background information.

Left arrow icon Right arrow icon
Download code icon Download Code

Key benefits

  • Your ultimate resource for getting up and running with Python numerical computations
  • Explore numerical computing and mathematical libraries using Python 3.x code with SciPy and NumPy modules
  • A hands-on guide to implementing mathematics with Python, with complete coverage of all the key concepts

Description

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 you will learn

[*] The principal syntactical elements of Python [*] The most important and basic types in Python [*] The essential building blocks of computational mathematics, linear algebra, and related Python objects [*] Plot in Python using matplotlib to create high quality figures and graphics to draw and visualize your results [*] Define and use functions and learn to treat them as objects [*] How and when to correctly apply object-oriented programming for scientific computing in Python [*] Handle exceptions, which are an important part of writing reliable and usable code [*] Two aspects of testing for scientific programming: Manual and Automatic

What do you get with a Packt Subscription?

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

Product Details


Publication date : Dec 23, 2016
Length 332 pages
Edition : 1st Edition
Language : English
ISBN-13 : 9781786463517
Category :
Concepts :

Table of Contents

23 Chapters
Scientific Computing with Python 3 Chevron down icon Chevron up icon
Credits Chevron down icon Chevron up icon
About the Authors Chevron down icon Chevron up icon
About the Reviewer Chevron down icon Chevron up icon
www.PacktPub.com Chevron down icon Chevron up icon
Acknowledgement Chevron down icon Chevron up icon
Preface Chevron down icon Chevron up icon
Getting Started Chevron down icon Chevron up icon
Variables and Basic Types Chevron down icon Chevron up icon
Container Types Chevron down icon Chevron up icon
Linear Algebra – Arrays Chevron down icon Chevron up icon
Advanced Array Concepts Chevron down icon Chevron up icon
Plotting Chevron down icon Chevron up icon
Functions Chevron down icon Chevron up icon
Classes Chevron down icon Chevron up icon
Iterating Chevron down icon Chevron up icon
Error Handling Chevron down icon Chevron up icon
Namespaces, Scopes, and Modules Chevron down icon Chevron up icon
Input and Output Chevron down icon Chevron up icon
Testing Chevron down icon Chevron up icon
Comprehensive Examples Chevron down icon Chevron up icon
Symbolic Computations - SymPy Chevron down icon Chevron up icon
References Chevron down icon Chevron up icon

Customer reviews

Filter icon Filter
Top Reviews
Rating distribution
Empty star icon Empty star icon Empty star icon Empty star icon Empty star icon 0
(0 Ratings)
5 star 0%
4 star 0%
3 star 0%
2 star 0%
1 star 0%

Filter reviews by


No reviews found
Get free access to Packt library with over 7500+ books and video courses for 7 days!
Start Free Trial

FAQs

What is included in a Packt subscription? Chevron down icon Chevron up icon

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

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

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

What are credits? Chevron down icon Chevron up icon

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

What is Early Access? Chevron down icon Chevron up icon

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