Welcome! This notebook is appropriate for people who have never programmed before. A few tips:
[shift] + [enter]
In [126]:
1 + 1
Out[126]:
In [127]:
3 / 4 # caution: in Python 2 the result will be an integer
Out[127]:
In [128]:
7 ** 3
Out[128]:
The arithmetic operators in Python are:
+ - * / ** % //
Use the Python interpreter to calculate:
(psst...) If you're stuck, try
help()
and then in the interactive box, type symbols
In [129]:
import math
print("The square root of 3 is:", math.sqrt(3))
print("pi is:", math.pi)
print("The sin of 90 degrees is:", math.sin(math.radians(90)))
import statement imports the module into the namespace<module>.<function>
help(<module>)
In [130]:
from math import acos, degrees # use 'from' sparingly
int(degrees(acos(0.743144))) # 'int' to make an integer
Out[130]:
Use help(str) to see available functions for string objects. For help on a particular function from the class, type the class name and the function name: help(str.join)
String operations are easy:
s = "foobar"
"bar" in s
s.find("bar")
index = s.find("bar")
s[:index]
s[index:] + " this is intuitive! Hooray!"
s[-1] # The last element in the list or string
Strings are immutable, meaning they cannot be modified, only copied or replaced. (This is related to memory use, and interesting for experienced programmers ... don't worry if you don't get what this means.)
In [131]:
# Here's to start.
s = "foobar"
"bar" in s
Out[131]:
In [132]:
# You try out the other ones!
s.find("bar")
Out[132]:
Using only string addition (concatenation) and the function str.join, combine declaration and sayings :
declaration = "We are the knights who say:\n"
sayings = ['"icky"'] * 3 + ['"p\'tang"']
# the (\') escapes the quote
to a variable, sentence, that when printed does this:
>>> print(sentence)
We are the knights who say:
"icky", "icky", "icky", "p'tang"!
In [133]:
help(str.join)
In [134]:
declaration = "We are now the knights who say:\n"
sayings = ['"icky"'] * 3 + ['"p\'tang"']
# You do the rest -- fix the below :-)
print(sayings)
In [135]:
sentence = declaration + ", ".join(sayings) + "!"
print(sentence)
print() # empty 'print' makes a newline
In [136]:
# By the way, you use 'split' to split a string...
# (note what happens to the commas):
print(" - ".join(['ni'] * 12))
print("\n".join("icky, icky, icky, p'tang!".split(", ")))
There are a bunch of ways to do string formatting:
"%s is: %.3f (or %d in Indiana)" % \
("Pi", math.pi, math.pi)
# %s = string
# %0.3f = floating point number, 3 places to the left of the decimal
# %d = decimal number
#
# Style notes:
# Line continuation with '\' works but
# is frowned upon. Indent twice
# (8 spaces) so it doesn't look
# like a control statement
In [137]:
print("%s is: %.3f (well, %d in Indiana)" % ("Pi", math.pi, math.pi))
str.format doesn't require types:"{0} is: {1} ({1:3.2} truncated)".format(
"Pi", math.pi)
# More style notes:
# Line continuation in square or curly
# braces or parenthesis is better.
In [138]:
# Use a colon and then decimals to control the
# number of decimals that print out.
#
# Also note the number {1} appears twice, so that
# the argument `math.pi` is reused.
print("{0} is: {1} ({1:.3} truncated)".format("Pi", math.pi))
"{pi} is {pie:05.3}".format(
pi="Pi", pie=math.pi)
# 05.3 = zero-padded number, with
# 5 total characters, and
# 3 significant digits.
In [139]:
# Go to town -- change the decimal places!
print("{pi} is: {pie:05.2}".format(pi="Pi", pie=math.pi))
In [140]:
# Boolean
x = True
type(x)
Out[140]:
Lists, dictionaries, sets. We will talk about them later.
There is also a library collections with additional specialized container types.
In [141]:
# Lists can contain multiple types
x = [True, 1, 1.2, 'hi', [1], (1,2,3), {}, None]
type(x)
# (the underscores are for special internal variables)
Out[141]:
In [142]:
# List access. Try other numbers!
x[1]
Out[142]:
In [143]:
print("x[0] is:", x[0], "... and x[1] is:", x[1]) # Python is zero-indexed
In [144]:
x.append(set(["a", "b", "c"]))
for item in x:
print(item, "... type =", type(item))
If you need to check an object's type, do this:
isinstance(x, list)
isinstance(x[1], bool)
In [145]:
# You do it!
isinstance(x, tuple)
Out[145]:
Lists, when copied, are copied by pointer. What that means is every symbol that points to a list, points to that same list.
Same with dictionaries and sets.
fifth_element = x[4]
fifth_element.append("Both!")
print(fifth_element)
print(x)
Why? The assignment (=) operator copies the pointer to the place on the computer where the list (or dictionary or set) is: it does not copy the actual contents of the whole object, just the address where the data is in the computer. This is efficent because the object could be megabytes big.
In [146]:
# You do it!
fifth_element = x[4]
print(fifth_element)
fifth_element.append("Both!")
print(fifth_element)
# and see, the original list is changed too!
print(x)
Example:
import copy
# -------------------- A shallow copy
x[4] = ["list"]
shallow_copy_of_x = copy.copy(x)
shallow_copy_of_x[0] = "Shallow copy"
fifth_element = x[4]
fifth_element.append("Both?")
def print_list(l):
print("-" * 10)
for elem in l:
print(elem)
print()
# look at them
print_list(shallow_copy_of_x)
print_list(x)
fifth_element
In [147]:
import copy
# -------------------- A shallow copy
x[4] = ["list"]
shallow_copy_of_x = copy.copy(x)
shallow_copy_of_x[0] = "Shallow copy"
fifth_element = x[4]
fifth_element.append("Both?")
In [148]:
# look at them
def print_list(l):
print("-" * 8, "the list, element-by-element", "-" * 8)
for elem in l:
print(elem)
print()
print_list(shallow_copy_of_x)
print_list(x)
In [149]:
# -------------------- A deep copy
x[4] = ["list"]
deep_copy_of_x = copy.deepcopy(x)
deep_copy_of_x[0] = "Deep copy"
fifth_element = deep_copy_of_x[4]
fifth_element.append("Both? -- no, just this one got it!")
# look at them
print(fifth_element)
print("\nand...the fifth element in the original list:")
print(x[4])
| boolean | integer | float | string | None |
| True | 42 | 42.0 | "hello" | None |
| list | tuple | set | dictionary |
|
|
|
|
In [150]:
l = ["a", 0, [1, 2] ]
l[1] = "second element"
type(l)
Out[150]:
In [151]:
print(l)
In [152]:
indices = range(len(l))
print(indices)
In [153]:
# Iterate over the indices using i=0, i=1, i=2
for i in indices:
print(l[i])
In [154]:
# Or iterate over the items in `x` directly
for x in l:
print(x)
In [155]:
t = ("a", 0, "tuple")
type(t)
Out[155]:
In [156]:
for x in t:
print x
In [157]:
s = set(['a', 0])
if 'b' in s:
print("has b")
In [158]:
s.add("b")
s.remove("a")
if 'b' in s:
print("has b")
In [159]:
l = [1,2,3]
try:
s.add(l)
except TypeError:
print("Could not add the list")
#raise # uncomment this to raise an error
In [160]:
# two ways to do the same thing
d = {"mother":"hamster",
"father":"elderberries"}
d = dict(mother="hamster",
father="elderberries")
In [161]:
d['mother']
Out[161]:
In [162]:
print("the dictionary keys:", d.keys())
print()
print("the dictionary values:", d.values())
In [163]:
# When iterating over a dictionary, use items() and two variables:
for k, v in d.items():
print("key: ", k, end=" ... ")
print("val: ", v)
In [164]:
# If you don't you will just get the keys:
for k in d:
print(k)
The syntax for creating a function is:
def function_name(arg1, arg2, kwarg1=default1):
"""Docstring goes here -- triple quoted."""
pass # the 'pass' keyword means 'do nothing'
# The next thing unindented statement is outside
# of the function. Leave a blank line between the
# end of the function and the next statement.
:) finishes the signature.Also, at the end of a function, leave at least one blank line to separate the thought from the next thing in the script.
In [165]:
def function_name(arg1, arg2, kwarg1="my_default_value"):
"""Docstring goes here -- triple quoted."""
pass # the 'pass' keyword means 'do nothing'
In [166]:
# See the docstring appear when using `help`
help(function_name)
The 'tab' character '\t' counts as one single character even if it looks like multiple characters in your editor.
But indentation is how you denote nesting!
So, this can seriously mess up your coding. The Python style guide recommends configuring your editor to make the tab keypress type four spaces automatically.
To set the spacing for Python code in Sublime, go to Sublime Text → Preferences → Settings - More → Syntax Specific - User
It will open up the file Python.sublime-settings. Please put this inside, then save and close.
{
"tab_size": 4,
"translate_tabs_to_spaces": true
}
In [167]:
# Paste the function definition below:
In [168]:
# Here's the help statement
help(greet_person)
In [169]:
# And here's the function in action!
greet_person("world")
Python's philosophy for handling data types is called duck typing (If it walks like a duck, and quacks like a duck, it's a duck). Functions do no type checking — they happily process an argument until something breaks. This is great for fast coding but can sometimes make for odd errors. (If you care to specify types, there is a standard way to do it, but don't worry about this if you're a beginner.)
In [170]:
# your function
def greet_people(list_of_people)
"""Documentation string goes here."""
# You do it here!
pass
In [171]:
def greet_people(list_of_people):
for person in list_of_people:
greet_person(person)
In [172]:
greet_people(["world", "awesome python user!", "rockstar!!!"])
In [173]:
# Try it!
The if statement checks whether the condition after if is true.
Note the placement of colons (:) and the indentation. These are not optional.
elif or else statements if you only
want to do something if your test condition is true.Advanced users, there is no switch statement in Python.
In [174]:
# Standard if / then / else statement.
#
# Go ahead and change `i`
i = 1
if i is None:
print("None!")
elif i % 2 == 0:
print("`i` is an even number!")
else:
print("`i` is neither None nor even")
In [175]:
# This format is for very short one-line if / then / else.
# It is called a `ternary` statement.
#
"Y" if i==1 else "N"
Out[175]:
The while loop requires you to set up something first. Then it
tests whether the statement after the while is true.
Again note the colon (:) and the indentation.
while loop will executewhile block
In [176]:
i = 0
while i < 3:
print("i is:", i)
i += 1
print("We exited the loop, and now i is:", i)
In [177]:
for i in range(3):
print("in the for loop. `i` is:", i)
print()
print("outside the for loop. `i` is:", i)
In [178]:
# or loop directly over a list or tuple
for element in ("one", 2, "three"):
print("in the for loop. `element` is:", element)
print()
print("outside the for loop. `element` is:", element)
Please look at this code and think of what will happen, then copy it and run it. We introduce break and continue...can you tell what they do?
i be at the end?for i in range(20):
if i == 15:
break
elif i % 2 == 0:
continue
for j in range(5):
print(i + j, end="...")
print() # newline
In [179]:
# Paste it here, and run!