This workshop is licensed under a Creative Commons Attribution 4.0 International License.
General programming language...good at most tasks
CTRL + Enter
will run a cell; Shift + Enter
will run a cell and highlight the next cell.
In [1]:
5 - 2
Out[1]:
=
symbol assigns the value on the right to the name on the left.age
and a name in quotes to a variable first_name
.
In [2]:
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.
In [3]:
print(first_name, 'is', age, 'years old')
print
automatically puts a single space between items to separate them.
In [4]:
print(last_name)
In [5]:
age = age + 3
print('Age in three years:', age)
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.
In [6]:
print(type(52))
In [7]:
height = 'average'
print(type(height))
In [8]:
print(5 - 3)
In [9]:
print('hello' - 'h')
In [10]:
full_name = 'Ahmed' + ' ' + 'Walsh'
print(full_name)
In [11]:
separator = '=' * 10
print(separator)
In [12]:
print(len(full_name))
In [13]:
print(len(52))
In [14]:
print(1 + '2')
1 + '2'
be 3
or '12'
?
In [15]:
print(1 + int('2'))
print(str(1) + '2')
In [16]:
print('half is', 1 / 2.0)
print('three squared is', 3.0 ** 2)
In [17]:
first = 1
second = 5 * first
first = 2
print('first is', first, 'and second is', second)
first
when doing the multiplication,
creates a new value, and assigns it to second
.second
does not remember where it came from.
In [18]:
# This sentence isn't executed by Python.
adjustment = 0.5 # Neither is this - anything after '#' is ignored.
print(adjustment)
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.
In [19]:
print('before')
print()
print('after')
In [20]:
print(max(1,2,3))
print(min('a', 'A', '0'))
In [21]:
print(max(1, 'a'))
In [22]:
round(3.712)
Out[22]:
In [23]:
round(3.712, 1)
Out[23]:
In [24]:
help(round)
In [25]:
text = 'Hello there, nice to meet you!'
print(text)
print(text.startswith('hell'))
print(text.replace('Hello','Goodbye'))
print(text.title().replace('!','?'))
import
to load a library module into a program's memory.module_name.thing_name
..
to mean "part of".datetime
, one of the modules in the standard library:
In [26]:
import datetime
today = datetime.datetime.now()
nextYear = today + datetime.timedelta(days=365)
print(today)
print(nextYear)
In [27]:
help(datetime)
In [28]:
from datetime import datetime, timedelta
today = datetime.now()
nextYear = today + timedelta(days=365)
print(today)
print(nextYear)
In [29]:
import datetime as dt
today = dt.datetime.now()
nextYear = today + dt.timedelta(days=365)
print(today)
print(nextYear)
matplotlib
plotting library is often aliased as plt
.name_001
, name_002
, etc.,
would be at least as slow as doing them by hand.[...]
.,
.len
to find out how many values are in a list.
In [30]:
names = ['Cathy','Doug','Monica','Jake','Peter']
print(type(names))
print('names:', names)
print('length:', len(names))
In [31]:
print('zeroth item of names:', names[0])
print('fourth item of names:', names[4])
In [32]:
names[0] = 'Catherine'
print('names is now:', names)
In [33]:
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.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:
In [34]:
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)
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.
In [35]:
print('primes before removing last item:', primes)
del primes[4]
print('primes after removing last item:', primes)
In [36]:
goals = []
goals.extend([1, 'Create lists.', 2, 'Extract items from lists.', 3, 'Modify lists.'])
print(goals)
In [37]:
values = [1,3,4,7,9,13]
print(values[0:2])
print(values[:2])
print(values[2:])
print(values[:-1])
IndexError
if we attempt to access a value that doesn't exist.
In [38]:
print('99th element of element is:', element[99])
{...}
."key":"value"
.,
.
In [39]:
students = {"firstName":"John","lastName":"Smith"}
print(type(students))
print(students)
In [40]:
students["age"] = 19
print(students)
students["major"] = ["Art History","French"]
print(students)
In [41]:
print(students["firstName"])
print(students['age'])
print(students['major'][1])
In [42]:
courses = {"courses":[
{
"Title":"Intro to Economics",
"Instructor": {
"firstName": "Robert",
"lastName":"Schiller",
},
"Number": "ECON 101",
"Size": 65,
"isFull": True,
},
{
"Title":"Intro to French",
"Instructor": {
"firstName": "Marie",
"lastName": "Gribouille",
},
"Number":"FREN 101",
"Size": 15,
"isFull": False,
}
]}
print(courses)
In [43]:
print(courses.keys())
print(courses.values())
'courses'
is the top level or root elementcourses['courses']
is a list; it's items are accessed using the index.keys()
& .values()
lists the dictionary keys and values respectively at the current dictionary level
In [44]:
print(courses['courses'][0].keys())
print(courses['courses'][0].values())
In [45]:
print(courses['courses'][1]['Instructor']['lastName'])