Overview
Teaching: 20 min
Exercises: 25 minQuestions
How do I run Python programs?
What are Python’s basic data types?
Objectives
Launch the Jupyter Notebook, create new notebooks, and exit the Notebook.
Create Markdown cells in a notebook.
Create and run Python cells in a notebook.
Write simple scripts that use atomic data types, variables, and lists.
.py
extension by convention..ipynb
extension.Once you have installed Python and the Jupyter Notebook requirements, open a shell and type:
$ jupyter notebook
FIXME: diagram
How It’s Stored
- The notebook file is stored in a format called JSON.
- Just like a webpage, what’s saved looks different from what you see in your browser.
- But this format allows Jupyter to mix software (in several languages) with documentation and graphics, all in one file.
Code vs. Text
We often use the term “code” to mean “the source code of software written in a language such as Python”. A “code cell” in a Notebook is a cell that contains software; a “text cell” is one that contains ordinary prose written for human beings.
In [ ]:
will disappear to show it is no longer a code cell
and you will be able to write in Markdown.* Use asterisks
* to create
* bullet lists.
1. Use numbers
1. to create
1. numbered lists.
# A Level-1 Heading
## A Level-2 Heading (etc.)
Line breaks
don't matter.
But blank lines
create new paragraphs.
Line breaks don’t matter.
But blank lines create new paragraphs.
[Create links](http://software-carpentry.org) with `[...](...)`.
Or use [named links][data_carpentry].
[data_carpentry]: http://datacarpentry.org
Create links with [...](...)
.
Or use named links.
var = value
to do assignment.age = 42
first_name = 'Ahmed'
__alistairs_real_age
have a special meaning
so we won’t do that until we understand the convention.print
to display values.print
displays things as text.print(first_name, 'is', age, 'years old')
Ahmed is 42 years old
print
automatically puts a single space between items and a newline at the end.print(last_name)
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
<ipython-input-1-c1fbb4e96102> in <module>()
----> 1 print(last_name)
NameError: name 'last_name' is not defined
int
, float
, and str
.+
, -
, *
, /
, ‘%’, and ‘^’ on numbers.
int/int
keeps the fractional part.int//int
is integer division.+
and *
on strings.
\t
and \n
.upper-lower
is the slice’s length.element = 'helium'
print('first character:', element[0])
print('last character:', element[-1])
print('middle:', element[2:5])
first character: h
last character: m
middle: liu
len
to find the length of a string.print(len('helium'))
6
[...]
.len
the same way as strings.pressures = [0.273, 0.275, 0.277, 0.275, 0.276]
print('pressures:', pressures)
print('length:', len(pressures))
print('second value:', pressures[1])
print('middle:', pressures[1:-1])
pressures: [0.273, 0.275, 0.277, 0.275, 0.276]
length: 5
second value: 0.275
middle: [0.275, 0.277, 0.275]
pressures[0] = 0.265
print('pressures is now:', pressures)
pressures is now: [0.265, 0.275, 0.277, 0.275, 0.276]
list.append
to add items to the end of a list.primes = [2, 3, 5]
print('primes is initially:', primes)
primes.append(7)
primes.append(9)
print('primes has become:', primes)
primes is initially: [2, 3, 5]
primes has become: [2, 3, 5, 7, 9]
append
is a method of lists.
object_name.method_name
to call methods.
help(list)
for a preview.del
to remove items from a list entirely.del list_name[index]
removes an item from a list and shortens the list.print('primes before removing last item:', primes)
del primes[4]
print('primes after removing last item:', primes)
primes before removing last item: [2, 3, 5, 7, 9]
primes after removing last item: [2, 3, 5, 7]
[]
is “the zero of lists”.goals = [1, 'Create lists.', 2, 'Extract items from lists.', 3, 'Modify lists.']
element[0] = 'C'
TypeError: 'str' object does not support item assignment
IndexError
if we attempt to access a value that doesn’t exist.print('99th element of element is:', element[99])
IndexError: string index out of range
Creating Lists in Markdown
Create a nested list in a Markdown cell in a notebook that looks like this:
- Get funding.
- Do work.
- Design experiment.
- Collect data.
- Analyze.
- Write up.
- Publish.
More Math
What is displayed when a Python cell in a notebook that contains several calculations is executed? For example, what happens when this cell is executed?
7 * 3 2 + 1
Change an Existing Cell from Code to Markdown
What happens if you write some Python in a code cell and then you switch it to a Markdown cell? For example, put the following in a code cell:
x = 6 * 7 + 12 print(x)
And then run it with shift+return to be sure that it works as a code cell. Now go back to the cell and use escape+M to switch the cell to Markdown and “run” it with shift+return. What happened and how might this be useful?
Equations
Standard Markdown (such as we’re using for these notes) won’t render equations, but the Notebook will. Create a new Markdown cell and enter the following:
$\Sigma_{i=1}^{N} 2^{-i} \approx 1$
(It’s probably easier to copy and paste.) What does it display? What do you think the underscore
_
, circumflex^
, and dollar sign$
do?
Swapping Values
Draw a table showing the values of the variables in this program after each statement is executed. In simple terms, what do the last three lines of this program do?
lowest = 1.0 highest = 3.0 temp = lowest lowest = highest highest = temp
Predicting Values
What is the final value of
position
in the program below? (Try to predict the value without running the program, then check your prediction.)initial = "left" position = initial initial = "right"
Challenge
If you assign
a = 123
, what happens if you try to get the second digit ofa
?Solution
Numbers are not stored in the written representation, so they can’t be treated like strings.
a = 123 print(a[1])
TypeError: 'int' object is not subscriptable
Choosing a Name
Which is a better variable name,
m
,min
, orminutes
? Why? Hint: think about which code you would rather inherit from someone who is leaving the lab:
ts = m * 60 + s
tot_sec = min * 60 + sec
total_seconds = minutes * 60 + seconds
Solution
minutes
is better becausemin
might mean something like “minimum” (and actually does in Python, but we haven’t seen that yet).
Slicing
What does the following program print?
element = 'carbon' print('element[1:3] is:', element[1:3])
element[1:3] is: ar
- What does
thing[low:high]
do?- What does
thing[low:]
(without a value after the colon) do?- What does
thing[:high]
(without a value before the colon) do?- What does
thing[:]
(just a colon) do?
Fill in the Blanks
Fill in the blanks so that the program below produces the output shown.
values = ____ values.____(1) values.____(3) values.____(5) print('first time:', values) values = values[____] print('second time:', values)
first time: [1, 3, 5] second time: [3, 5]
How Large is a Slice?
If ‘low’ and ‘high’ are both non-negative integers, how long is the list
values[low:high]
?
From Strings to Lists and Back
Given this:
print('string to list:', list('tin')) print('list to string:', ''.join(['g', 'o', 'l', 'd']))
['t', 'i', 'n'] 'gold'
- Explain in simple terms what
list('some string')
does.- What does
'-'.join(['x', 'y'])
generate?
Working With the End
What does the following program print?
element = 'helium' print(element[-1])
- How does Python interpret a negative index?
- If a list or string has N elements, what is the most negative index that can safely be used with it, and what location does that index represent?
- If
values
is a list, what doesdel values[-1]
do?- How can you display all elements but the last one without changing
values
? (Hint: you will need to combine slicing and negative indexing.)
Stepping Through a List
What does the following program print?
element = 'fluorine' print(element[::2]) print(element[::-1])
- If we write a slice as
low:high:stride
, what doesstride
do?- What expression would select all of the even-numbered items from a collection?
Slice Bounds
What does the following program print?
element = 'lithium' print(element[0:20]) print(element[-1:3])
Sort and Sorted
What do these two programs print? In simple terms, explain the difference between
sorted(letters)
andletters.sort()
.# Program A letters = list('gold') result = sorted(letters) print('letters is', letters, 'and result is', result)
# Program B letters = list('gold') result = letters.sort() print('letters is', letters, 'and result is', result)
Copying (or Not)
What do these two programs print? In simple terms, explain the difference between
new = old
andnew = old[:]
.# Program A old = list('gold') new = old # simple assignment new[0] = 'D' print('new is', new, 'and old is', old)
# Program B old = list('gold') new = old[:] # assigning a slice new[0] = 'D' print('new is', new, 'and old is', old)
Key Points
Python programs are plain text files.
We can write Python in the Jupyter Notebook as well (which isn’t plain text).
Most common atomic data types are
int
,float
,str
, andbool
.Most common type of collection is
list
.Use variables to store values.
Use
Variables persist between cells.
Variables must be created before they are used.
Use an index to get a single character from a string or list.
Use a slice to get a substring or sub-list.
Use the built-in function
len
to find the length of a string.Python is case-sensitive.