The Python programming language is used widely in the sciences, the computational physics, biology, and economics/quantitative finance communities, and in big companies such as Google and Facebook.
For this class we are using Python 3 (e.g. Python 3.8, 3.9, 3.10), which is the current standard. A lot of older code is still only available for Python 2.7 even though Python 2 is no longer officially supported. (There are a number of sometimes subtle incompatibilities between 2 and 3 but once you know Python 3 you will have no problems dealing with Python 2 code if you really have to.)
Resources
There are many books available on Python. The resources below were listed because they are easily accessible.
- Official Beginner’s Guide to Python
- Official Python 3 Tutorial
- A Primer on Scientific Programming with Python, Hans Petter Langtangen. chapters 1-5 PDF, Springer. ISBN-13: 978-3662498866 (written in Python 2.7 but can be easily used with Python 3, too) 1
- PHY432 Wiki: List of Python Tutorials
Keep the Python documentation close by and have a look at Python questions on StackOverflow.
Getting started …
work directory
- Open a terminal.
- Create our “work directory”
~/PHY432/04_python
cd
into~/PHY432/04_python
ipython
For interactive work we will use the ipython interpreter. Start it in a terminal window with
Check that you are in the ~/PHY432/04_python
directory by typing in ipython (note the percentage sign in %pwd
):
You should see
Out[1]: '/Users/YOUR_USERNAME/PHY432/04_python'
or similar.
editor
You will also edit files with your editor (see the lesson on creating text files with a text editor). If you use a point-and-click editor, make sure that you can find the work directory.
python
We will run programs. It is convenient to do this in a second terminal (and keep the one with ipython
open).
- open a second terminal
- go to the work dir
Python Fundamentals
Work interactively in ipython
.
Comments
Comments start with #
Variables and assignment
Variables have names:
(Must start with letters or underscores, cannot contain spaces or other reserved characters (e.g., operators).)
and content
shows 42
Pro Tip
In interactive work, you can also just type the variable name to see its content:
Exercise assignment
Try variable assignments
Make sure that each variable contains what you expect.
Did you get a SyntaxError
? Why?
Variable types
Each variable has a type:
- numeric types:
int
,float
,complex
- text sequence type (string):
str
- boolean values:
True
andFalse
; in python, boolean values are returned from truth value testing - None-data type:
None
(no value or default)
Variables are dynamically typed, i.e., Python figures out by itself what type it should be (different from languages such as C, C++, Fortran, java).
will print something
.
Determine the type of a variable with the type() function:
returns int
.
Exercise types
Determine the type of the variables from the previous activity: half
, h_bar
, h
, label
, one
, symmetrical
, threehalfpi
.
Type conversion
but
raises a ValueError
.
Exercise True or False
Work with your neighbor. Try the following code and figure out why the following expressions return True
or False
:
What rules does Python follow to determine the “truthiness” 2 of an expression?
Expressions
Expressions in Python are formed from numbers, strings, … and variables using operators. The most commonly used operatores are:
- unary:
+x
,-x
,not x
binary
comparison operators, e.g.,
x == y
,x != y
,x > y
,x <= y
, …A comparison has a boolean value (
True
orFalse
).numerical operators, e.g.,
x + y
,x - y
,x * y
,x / y
,x ** y
(power),x // y
(floor division),x % y
(remainder).Also in-place operations, which combine numerical operation with assignment (
x += y
is the same asx = x + y
)
- ternary (
x < y < z
,x if y else z
)
Use parentheses (
and )
for grouping and change of precedence.
Exercise Expressions
Compute the temperature \(T\) in Kelvin from a temperature in Fahrenheit \(\theta = 100\,^\circ\mathrm{F}\) using
\[T = \frac{5}{9} (\theta - 32) + 273.15\]Write a program tempconverter.py
that takes as input the temperature in Fahrenheit \(\theta\) and outputs \(T\).
Container data types
Lists (“arrays”) and tuples are sequences and support a broad set of common operations. Dictionaries (dicts) contain key-value pairs.3
Lists
A list (uses square brackets []
or list()
):
Important list operations:
Indexing
Each element has an index:
temperatures = [60.1, 78.3, 98.8, 97.1, 101.3, 110.0] elements
| | | | | | |
| 0 | 1 | 2 | 3 | 4 | 5 | index
First element
Arbitrary elements
Note
Python indices are 0-based.
For example, the third element is at index 2:
Negative indices count from the last element to the first:
temperatures = [60.1, 78.3, 98.8, 97.1, 101.3, 110.0] elements
| | | | | | |
| 0 | 1 | 2 | 3 | 4 | 5 | index
| -6 | -5 | -4 | -3 | -2 | -1 | negative index
Last element
Third element from the end
Python built-in function to determine the length of a list: len():
gives 6.
Slicing
Slicing produces a new list by extracting a subset of elements as determined by the “slice” start:stop:step. The general slicing syntax for a list a
:
where
- index
start
is included and stop
is excluded;start
,stop
,step
are each optional:- default for
start
: first element (index 0) - default for
stop
: after last element - default for
step
is 1, i.e., include every element.
- default for
Negative values are also allowed for indices and negative step counts backwards.
First 3 elements
(start
defaults to 0 and can be omitted).
Omitting parameters:
Example: slicing
A list with the first 6 letters of the English alphabet:
+---+---+---+---+---+---+
|'A'|'B'|'C'|'D'|'E'|'F'| elements
+---+---+---+---+---+---+
| 0 | 1 | 2 | 3 | 4 | 5 | index
+---+---+---+---+---+---+
|-6 |-5 |-4 |-3 |-2 |-1 | index
+---+---+---+---+---+---+
Refer to the schema above to understand which part of the list the following slices extract:
Exercise extracting from lists
- extract the letter ‘E’ from
letters
- extract the letter ‘E’ from
letters
(in a different way) - extract the letters ‘C’, ‘D’ from letters
- extract the letters ‘A’, ‘D’ from
letters
- extract the letters ‘E’, ‘F’ from
letters
(use negative indices) - extract the letters ‘D’, ‘E’ from
letters
(use negative indices) - extract the second element from
stuff
- extract the first two values from
temperatures
- extract the second-but last value from
temperatures
- extract the last two values from
temperatures
- extract the last element of the last element from
stuff
(should be1
) - What do you get from
stuff[3:4]
? (Should be an animal) - What do you get from
stuff[3:3]
? What is the length of the new list? - BONUS: reverse the order of
temperatures
(note thestep
argument)
List manipulation
Lists are mutable, which means that they can be changed:
gives ['dog', 42, -1.234, 'cat', [3, 2, 1]]
as above.
You can also replace parts of a list (continuing):
gives ['dog', 'python', 'swallow', 'cat', 'Hund', 'Python', 'Schwalbe', 'Katze']
(note that the last list was inserted).
One can also insert into a list without deleting an element by assigning to an empty slice:
gives ['dog', 'python', 'parrot', 'llama', 'swallow', 'cat', 'Hund', 'Python', 'Schwalbe', 'Katze']
.
As a more explicit alternative to stuff[2:2] = ['parrot', 'llama']
one can use
Tuples
A tuple is a list-like container(“sequence”), defined by comma ,
(but often parentheses are added for clarity or when defining a 1-tuple or an empty tuple) or use tuple()
:
Indexing and slicing works the same way as for lists but tuples are immutable:
Often used for compact assignment statements
Dictionaries
A dict is a mutable container with arbitrary (constant) keys (uses curly braces {}
or dict()
):
Access elements by key:
prints 31
.
Create new entries on the fly:
The content of a dict has no defined order (unlike lists and tuples):
Footnotes
An older book by the same author is freely available for ASU students but is written in Python 2. The concepts are still valid but the syntax may differ in some cases:
Python Scripting for Computational Science, Hans Petter Langtangen. Texts in Computational Science and Engineering, Volume 3, 2008. Springer. DOI: 10.1007/978-3-540-73916-6 (free access to the PDF through the ASU Library — requires ASU login) ↩
See, for instance, YouTube:Truthiness (in Python) ↩
There are more container types available in Python (e.g., set and the collections module in the Standard Library) but understanding list, tuple, and dict will already get you a long way. ↩