03 Introduction to Python I — Variables and Python data types
16 Jan 2018The 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.4 or Python 3.5), which is the current standard. A lot of older code is still only available for Python 2.7 (and 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.
- Resources
- Starting Python
- Today's lesson: Python Fundamentals
Resources
- Official Beginner's Guide to Python
- Official Python 3 Tutorial
- 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)
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"
~/PHY494/03_python
cd
into~/PHY494/03_python
ipython
For interactive work we will use the ipython interpreter. Start it in a terminal window with
Check that you are in the ~/PHY494/03_python
directory by typing in
ipython (note the percentage sign in %pwd
):
You should see
Out[1]: '/Users/YOUR_USERNAME/PHY494/03_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
Note: In interactive work, you can also just type the variable name to see its content:
Activity: 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
.
Activity: types
Determine the type of the variables from the previous activity:
half
, h_bar
, h
, label
, one
, threehalfpi
.
Type conversion
but
raises a ValueError
.
Operators
- unary:
+x
,-x
,not x
-
binary
-
comparison operators, e.g.,
x == y
,x != y
,x > y
,x <= y
, … -
numerical operators, e.g.,
x + y
,x - y
,x * y
,x / y
,x ** y
(power). 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.
Activity: operators
Compute the temperature in Kelvin from a temperature in Fahrenheit using
Container data types
Lists ("arrays") and tuples are sequences and support a broad set of common operations. Dictionaries (dicts) contain key-value pairs.1
Lists
A list (uses
square brackets []
or list()
):
Important list operations:
Indexing
First element
Arbitrary elements
Note: Python indices are 0-based.
Last element
Python built-in function to determine the length of a list: len():
gives 6.
Slicing
General slicing syntac: list_var[start:stop:step]
where index
start
is included and stop
is excluded; the default for step
is 1, i.e., include every element.
First 3 elements
(start
defaults to 0 and can be omitted).
Activity: extracting from lists
- 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 construction
gives ['dog', 42, -1.234, 'cat', [3, 2, 1]]
as above.
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
-
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. ↩