This workshop is licensed under a Creative Commons Attribution 4.0 International License.
For this workshop, I recommend installing Python 3 using Anaconda. The workshop was built using the Spyder IDE, but users can use any python environment they prefer.
General programming language…good at most tasks
We are using Spyder for this workshop. Here’s how to get started with Spyder:
=
symbol assigns the value on the right to the name on the left.age
and a name in quotes to a variable first_name
.age = 42
first_name = 'Ahmed'
_
(typically used to separate words in long variable names)__alistairs_real_age
have a special meaning
so we won’t do that until we understand the convention.print
to display values.print
that prints things as text.print(first_name, 'is', age, 'years old')
Ahmed is 42 years old
print
automatically puts a single space between items to separate them.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
age
a few lines ago.age = age + 3
print('Age in three years:', age)
Age in three years: 45
int
): represents positive or negative whole numbers like 3 or -512.float
): represents real numbers like 3.14159 or -2.5.str
): text.
type
to find the type of a value.type
to find out what type a value has.print(type(52))
<class 'int'>
fitness = 'average'
print(type(fitness))
<class 'str'>
print(5 - 3)
2
print('hello' - 'h')
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-2-67f5626a1e07> in <module>()
----> 1 print('hello' - 'h')
TypeError: unsupported operand type(s) for -: 'str' and 'str'
full_name = 'Ahmed' + ' ' + 'Walsh'
print(full_name)
Ahmed Walsh
separator = '=' * 10
print(separator)
==========
len
counts the number of characters in a string.print(len(full_name))
11
print(len(52))
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-3-f769e8e8097d> in <module>()
----> 1 print(len(52))
TypeError: object of type 'int' has no len()
print(1 + '2')
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-4-fe4f54a023c6> in <module>()
----> 1 print(1 + '2')
TypeError: unsupported operand type(s) for +: 'int' and 'str'
1 + '2'
be 3
or '12'
?print(1 + int('2'))
print(str(1) + '2')
3
12
print('half is', 1 / 2.0)
print('three squared is', 3.0 ** 2)
half is 0.5
three squared is 9.0
first = 1
second = 5 * first
first = 2
print('first is', first, 'and second is', second)
first is 2 and second is 5
first
when doing the multiplication,
creates a new value, and assigns it to second
.second
does not remember where it came from.# This sentence isn't executed by Python.
adjustment = 0.5 # Neither is this - anything after '#' is ignored.
len
takes exactly one.int
, str
, and float
create a new value from an existing one.print
takes zero or more.print
with no arguments prints a blank line.
print('before')
print()
print('after')
before
after
max
, min
, and round
.max
to find the largest value of one or more values.min
to find the smallest.print(max(1, 2, 3))
print(min('a', 'A', '0'))
3
0
max
and min
must be given at least one argument.
print(max(1, 'a'))
TypeError: unorderable types: str() > int()
round
will round off a floating-point number.round(3.712)
4
round(3.712, 1)
3.7
help
to get help for a function.help(round)
Help on built-in function round in module builtins:
round(...)
round(number[, ndigits]) -> number
Round a number to a given precision in decimal digits (default 0 digits).
This returns an int when called with one argument, otherwise the
same type as the number. ndigits may be negative.
import
to load a library module into a program’s memory.module_name.thing_name
.
.
to mean “part of”.math
, one of the modules in the standard library:import math
print('pi is', math.pi)
print('cos(pi) is', math.cos(math.pi))
pi is 3.141592653589793
cos(pi) is -1.0
math.cos(pi)
won’t work: the reference to pi
doesn’t somehow “inherit” the function’s reference to math
.help
to learn about the contents of a library module.help(math)
Help on module math:
NAME
math
MODULE REFERENCE
http://docs.python.org/3.5/library/math
The following documentation is automatically generated from the Python
source files. It may be incomplete, incorrect or include features that
are considered implementation detail and may vary between Python
implementations. When in doubt, consult the module reference at the
location listed above.
DESCRIPTION
This module is always available. It provides access to the
mathematical functions defined by the C standard.
FUNCTIONS
acos(...)
acos(x)
Return the arc cosine (measured in radians) of x.
⋮ ⋮ ⋮
from ... import ...
to load only specific items from a library module.from math import cos, pi
print('cos(pi) is', cos(pi))
cos(pi) is -1.0
import ... as ...
to give a library a short alias while importing it.import math as m
print('cos(pi) is', m.cos(m.pi))
cos(pi) is -1.0
matplotlib
plotting library is often aliased as mpl
.pressure_001
, pressure_002
, etc.,
would be at least as slow as doing them by hand.[...]
.,
.len
to find out how many values are in a list.pressures = [0.273, 0.275, 0.277, 0.275, 0.276]
print('pressures:', pressures)
print('length:', len(pressures))
pressures: [0.273, 0.275, 0.277, 0.275, 0.276]
length: 5
print('zeroth item of pressures:', pressures[0])
print('fourth item of pressures:', pressures[4])
zeroth item of pressures: 0.273
fourth item of pressures: 0.276
pressures[0] = 0.265
print('pressures is now:', pressures)
pressures is now: [0.265, 0.275, 0.277, 0.275, 0.276]
list_name.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.extend
is similar to append
, but it allows you to combine two lists. For example:teen_primes = [11, 13, 17, 19]
middle_aged_primes = [37, 41, 43, 47]
print('primes is currently:', primes)
primes.extend(teen_primes)
print('primes has now become:', primes)
primes.append(middle_aged_primes)
print('primes has finally become:', primes)
primes is currently: [2, 3, 5, 7, 9]
primes has now become: [2, 3, 5, 7, 9, 11, 13, 17, 19]
primes has finally become: [2, 3, 5, 7, 9, 11, 13, 17, 19, [37, 41, 43, 47]]
Note that while extend
maintains the “flat” structure of the list, appending a list to a list makes the result two-dimensional.
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]
[]
on its own to represent a list that doesn’t contain any values.
goals = [1, 'Create lists.', 2, 'Extract items from lists.', 3, 'Modify lists.']
element = 'carbon'
print('zeroth character:', element[0])
print('third character:', element[3])
zeroth character: c
third character: b
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])
pressure_001
, pressure_002
, etc.for number in [2, 3, 5]:
print(number)
for
loop is equivalent to:print(2)
print(3)
print(5)
for
loop’s output is:2
3
5
for
loop must end with a colon, and the body must be indented.{}
or begin
/end
to show nesting.
for number in [2, 3, 5]:
print(number)
IndentationError: expected an indented block
firstName="Jon"
lastName="Smith"
File "<ipython-input-7-f65f2962bf9c>", line 2
lastName="Smith"
^
IndentationError: unexpected indent
for
loop is made up of a collection, a loop variable, and a body.for number in [2, 3, 5]:
print(number)
[2, 3, 5]
, is what the loop is being run on.print(number)
, specifies what to do for each value in the collection.number
, is what changes for each iteration of the loop.
for kitten in [2, 3, 5]:
print(kitten)
primes = [2, 3, 5]
for p in primes:
squared = p ** 2
cubed = p ** 3
print(p, squared, cubed)
2 4 8
3 9 27
5 25 125
range
to iterate over a sequence of numbers.range
produces a sequence of numbers.
range(N)
is the numbers 0..N-1
print('a range is not a list: range(0, 3)')
for number in range(0,3):
print(number)
a range is not a list: range(0, 3)
0
1
2
# Sum the first 10 integers.
total = 0
for number in range(10):
total = total + (number + 1)
print(total)
55
total = total + (number + 1)
as:
number
.total
.total
, replacing the current value.number + 1
because range
produces 0..9, not 1..10.if
statements to control whether or not a block of code is executed.if
statement (more properly called a conditional statement)
controls whether some block of code is executed or not.for
statement:
if
and ends with a colonmass = 3.54
if mass > 3.0:
print(mass, 'is large')
mass = 2.07
if mass > 3.0:
print (mass, 'is large')
3.54 is large
masses = [3.54, 2.07, 9.22, 1.86, 1.71]
for m in masses:
if m > 3.0:
print(m, 'is large')
3.54 is large
9.22 is large
else
to execute a block of code when an if
condition is not true.else
can be used following an if
.if
branch isn’t taken.masses = [3.54, 2.07, 9.22, 1.86, 1.71]
for m in masses:
if m > 3.0:
print(m, 'is large')
else:
print(m, 'is small')
3.54 is large
2.07 is small
9.22 is large
1.86 is small
1.71 is small
elif
to specify additional tests.elif
(short for “else if”) and a condition to specify these.if
.else
(which is the “catch all”).masses = [3.54, 2.07, 9.22, 1.86, 1.71]
for m in masses:
if m > 9.0:
print(m, 'is HUGE')
elif m > 3.0:
print(m, 'is large')
else:
print(m, 'is small')
3.54 is large
2.07 is small
9.22 is HUGE
1.86 is small
1.71 is small
grade = 85
if grade >= 70:
print('grade is C')
elif grade >= 80:
print('grade is B')
elif grade >= 90:
print('grade is A')
grade is C
velocity = 10.0
if velocity > 20.0:
print('moving too fast')
else:
print('adjusting velocity')
velocity = 50.0
adjusting velocity
velocity = 10.0
for i in range(5): # execute the loop 5 times
print(i, ':', velocity)
if velocity > 20.0:
print('moving too fast')
velocity = velocity - 5.0
else:
print('moving too slow')
velocity = velocity + 10.0
print('final velocity:', velocity)
0 : 10.0
moving too slow
1 : 20.0
moving too slow
2 : 30.0
moving too fast
3 : 25.0
moving too fast
4 : 20.0
moving too slow
final velocity: 30.0
Workshop materials are drevied from work that is Copyright ©Software Carpentry.