Expressions¶
2019
2000 + 19
2000  19
*
1 * 2 * (3 * 4)
/
. This operation will always return a float
10 / 2
//
, which returns the division rounded down to the lowest integer, and the modulo
operator %
, which returns the remainder of a division after substracting the next lowest integer. These are easier to understand by example: 10 // 6
10 % 6
6 // 2
6 % 3
**
(NOT ^
) 2 ** 3
Variables¶
type
that describes what sort of data it contains. Some of the most common types are int
(integer), float
(floating point number), and string
(text) * Unlike many other languages, in Python you do not have to specify the type when you create a variable. Python infers the data type based on the context. This is called 'duck typing'. int
variables are simply numbers. Let's assign 27 to a variable 'age'. If the variable age
does not already exist, this assignment expression will create it age = 27
type()
function. Let's examine the type of age
. type(age)
float
variables are created by adding a decimal point to a number. Let's redefine age
as 27.0 and check the type age = 27.0
type(age)
string
variables contain text and are created using quotation marks. Both single and double quotation marks are OK. Let's try making age
a string first_name = "Ryan"
type(first_name)
string
that contains only numbers age = "27"
type(age)
age = 42
age
age = 29
age
Builtin functions¶
type
, which we've already used. Functions are called using the function name and parentheses, which enclose the function arguments. In the example below, print
is the function, and the string "Hello world!"
is the argument.
print("Hello world!")
print
can accept multiple arguments, separate by commas, and will combine them together to generate its output, like this: print("Age is", age, "years")
 Place your cursor inside the name of any function, and press SHIFT+TAB. This will open a small box with function information, which can be expanded by pressing tab again.
 Use the builtin
help
function, where the argument tohelp
is the name of the function you want to know more about.  Type the name of the function followed by
?
, which will show the functions documentation or 'docstring'
Finding help¶
## click your cursor inside 'print' and press SHIFT+TAB
print("this is cool")
help(print)
print?
Importing other modules and functions¶
import
statement. In this example, we're going to import a module called math
that contains a number of functions that can be accessed by using math.FUNCTION_NAME_HERE
. import math
math.exp(2)
print("Exponent of 2:", math.exp(2))
print("Sine of 3.1415:", math.sin(3.1415))
 numpy  for efficient numerical array manipulation and operation
 scipy  for a number of tools related to scientific computing
 matplotlib  for plotting data and creating figures
import numpy as np
from matplotlib import pyplot
inflammation = np.loadtxt("inflammation01.csv", delimiter=',')
%matplotlib inline
average = np.average(inflammation, axis=0)
pyplot.plot(average)
Lesson 2: Lists and Strings¶
A list stores many values in a single structure.¶
 A
list
stores many values together.  Contained within square brackets
[...]
.  Values separated by commas
,
.  Use
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)
Use the builtin function len
to find the length of a list¶
goals = [1, 'Create lists.', 2, 'Extract items from lists.',
3, 'Modify lists.']
Index and slice to get information out of a string/list¶
 Locations are numbered from 0 rather than 1
 Negative indices count backward from the end of the string
 Slices include the lower bound but exclude the upper bound, so
(upper  lower)
is the slice's length
numbers = ["one", "two", "three", "four", "five"]
print('first element:', numbers[0])
print('last element:', numbers[1])
print('middle elemnets:', numbers[2:5])
# NBVAL_RAISES_EXCEPTION
## This code will fail
print('99th element of numbers is:', numbers[99])
List values can be replaced by assigning to them¶
 Use an index expression on the left of assignment to replace a value.
 We say that lists are mutable because their contents can be changed after they are created
pressures[0] = 0.265
print('pressures is now:', pressures)
Appending items to a list lengthens it¶
 use
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)
append
is a method of lists * like a function, but tied to a particular object  Use
object_name.method_name
to call methods 
deliberately resembles the way we refer to things in a library

We will meet other methods of lists as we go along
 Use
help(list)
for a preview
Extending a list adds another list to it¶
extend
is similar to append
, but it allows you to combine two lists. teen_primes = [11, 13, 17, 19]
older_primes = [23, 31, 47, 59]
print('primes is currently:', primes)
primes.extend(teen_primes)
print('primes has now become:', primes)
primes.append(older_primes)
print('primes has finally become:', primes)
extend
maintains the "flat" structure of the list, appending a list to a list makes the result twodimensional. Use del
to remove items from a list entirely¶
del list_name[index]
removes an item from a list and shortens the list. Not a function or method, but a statement in the language.
print('primes before removing item:', primes)
del primes[4]
print('primes after removing item:', primes)
The empty list contains no values¶
[]
is "the zero of lists" Helpful as a starting point for collecting values
 NEVER use an empty list as a default argument in a function!
Strings can be sliced and indexed just like lists¶
 You can think of strings as lists of characters
greeting = "My name is Ryan"
print('first character:', greeting[0])
print('last character:', greeting[1])
print('middle character:', greeting[2:5])
Unlike lists, strings are immutable¶
 Cannot change the characters in a string after it has been created.
 Python considers the string to be a single value with parts, not a collection of values.
# NBVAL_RAISES_EXCEPTION
element = 'helium'
## This code will fail
element[0] = 'C'
Lesson 3: For loops¶
letter
and the iterable I've used is the list name
, which was defined as '['J', 'i', 'm', 'm', 'y']'
. Other iterables include strings and dictionary keys, among others. For example, we could make name
a string and iterate through it in the same way we iterated through the list: name = 'Jimmy'
for letter in name:
print(letter)
name = 'Jimmy'
for letter in name[0:3]:
print(letter)
len
function. enumerate
function assigns an index (or counter) to each value of an iterable. It returns a tuple of (counter, value) that can be useful in for loops. For example, here we assign the index to the variable n
and the value of the iterable to letter
: for n, letter in enumerate(name):
print("Letter", n, "", letter)
Use zip()
to loop over two iterables simultaneously¶
zip
function can be used to loop through two iterables simultaneously (like two sides of a zipper). Here, we use zip
to iterate through two strings that have the same length for letter1, letter2 in zip("Jimmy", "Heath"):
print(letter1, letter2)
Use range()
to iterate ranges of numbers¶
range
function is used to construct an iterable corresponding to a set of numbers beginning at 0 and ending at a certain number: range
can take multiple arguments, where the first argument is interpreted as the beginning of the range. In the example below, we combine a for
loop with an if
statement to print only the even numbers. This makes use of the modulo %
operator we covered in the Variables lesson.
break
statement is used to stop iterating through an iterable if some condition is met. Here, we will end our loop as soon as we encouter the number 6: for number in range(2, 10):
if number == 6:
break
else:
print(number)
for
loops is to keep track of a running total of numbers. In this pattern, it's important to declare the variable that you're adding to outside the scope of the for loop. The example below makes use of the "in place addition" +=
operator, which says "add the value on the right of the operator to the value of the variable on the left". So x += 5
means "add 5 to the current value of variable x
. Python has similar "in place" operators for several other operations, including =
, *=
, and /=
for subtraction, multiplication, and division, respectively.
my_sum = 0
for number in range(6):
my_sum += number
print("Sum of numbers from 0 to 5 is", my_sum)