10:00 - 11:00: Work
11:00 - 11:10: Break
11:10 - 12:30: Work
12:30 - 13:30: Lunch
13:30 - 17:00: Work & Project
Slides available online at:
Or a shorter link (it takes you to the same place):
a = "kitty"
b = a[2:4]
print(b)
tt
c = a + " " + "kat"
print(c)
kitty kat
d = c[:4]
e = c[4:]
print(d)
print(e)
kitt y kat
print(c)
kitty kat
f = c[-1]
print(f)
t
g = c[-5:-2]
print(g)
y k
input()
does two thing at once:
answer_1 = input("What's the capital city of Canada?")
answer_2 = input("When did the Cold War end?")
What's the capital city of Canada?Ottawa
names = ["Alan", "Irish", "Ryan", "Sajed", "Stacy"]
counter = 0
for mentor in names:
print("High five " + mentor)
counter = counter + 1
print("High-fived " + str(counter) + " mentors!")
High five Alan High five Irish High five Ryan High five Sajed High five Stacy High-fived 5 mentors!
names = ["Alan", "Irish", "Ryan", "Sajed", "Stacy"]
counter = 0
for mentor in names:
print("High five " + mentor)
counter = counter + 1
print("High-fived " + str(counter) + " mentors!")
High five Alan High five Irish High five Ryan High five Sajed High five Stacy High-fived 5 mentors!
names = ["Mariah", "Sajed", "Sean"]
counter = 0
for mentor in names:
print("High five " + mentor)
counter = counter + 1
print("High-fived " + str(counter) + " mentors!")
High five Mariah High five Sajed High five Sean High-fived 3 mentors!
Project: Analyze historical temperature values Canada
input(q)
: display message in q and store whatever user types into a variabletype(x)
: ask Python about the data type of xlen(x)
: ask Python to tell us the length of a variable xprint(x)
: printing x to screenThis goes into your script
def say_hello():
print("Hello, world!")
In ipython, run the script first
say_hello()
Hello, world!
Doubt thou the stars are fire;
Doubt that the sun doth move;
Doubt truth to be a liar;
But never doubt I love.
O dear Ophelia, I am ill at these numbers.
What is the output of the following code?
def increase_by_one(number):
new = number + 1
print(new)
increase_by_one(6)
a) Nothing
b) 6
c) 7
def kg_to_lb(weight_kg):
weight_lb = weight_kg * 2.2
return weight_lb
answer = kg_to_lb(2)
print(answer)
4.4
We can use the output of one function as the input of another function.
answer = kg_to_lb(2)
print(answer)
4.4
print(kg_to_lb(2))
4.4
Write a function that converts pounds to kilograms. 1 lb = 0.454 kg, or 1 kg = 2.2 lb.
def lb_to_kg(weight_lb):
weight_kg = weight_lb / 2.2
return weight_kg
OR
def lb_to_kg(weight_lb):
weight_kg = weight_lb * 0.454
return weight_kg
How do we know if this function is correct?
print(lb_to_kg(4.4))
2.0
(If you see something like 1.9976000000000003
, it's also fine.)
kg_to_lb(2)
4.4
def increase_by_one(number):
new = number + 1
print(new)
value = increase_by_one(6)
7
print(value)
None
def increase_by_one(number):
new = number + 1
return new
value = increase_by_one(6)
print(value)
7
def increase_by_one(number):
new = number + 1
return new
value = increase_by_one(6)
print(value)
7
def increase_by_one(number):
new = number + 1
print(new)
value = increase_by_one(6)
7
print(value)
None
Write a function called count_consonants
that can be used in the following way.
word = 'morphogenesis'
count_consonants(word)
8
Try not to look at the hint. If you really want a hint, press the downward arrow in the bottom right corner.
Think about how we wrote count_vowels
yesterday.
What will the following line return?
count_consonants('ivana')
a) Error
b) 2
c) '2'
count_consonants('ivana')
2
What will the following line return?
count_consonats('')
a) Error
b) 0
c) '0'
count_consonats('')
--------------------------------------------------------------------------- NameError Traceback (most recent call last) <ipython-input-27-2e12d6f07702> in <module>() ----> 1 count_consonats('') NameError: name 'count_consonats' is not defined
What will the following line return?
count_consonants(100)
a) Error
b) 3
c) 100
count_consonants(100)
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) <ipython-input-30-5b835d6cc9df> in <module>() ----> 1 count_consonants(100) <ipython-input-22-4fc31d8eae71> in count_consonants(word) 2 vowels = ["a", "e", "i", "o", "u", "A", "E", "I", "O", "U"] 3 count = 0 ----> 4 for letter in word: 5 if letter not in vowels: 6 count += 1 TypeError: 'int' object is not iterable
def smaller(a, b):
minimum = a
if b < a:
minimum = b
return minimum
small_number = smaller(5, 2)
print(small_number)
2
print(smaller(-1, 10))
-1
print(smaller(9))
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) <ipython-input-34-bfe8226e0010> in <module>() ----> 1 print(smaller(9)) TypeError: smaller() missing 1 required positional argument: 'b'
Write a function that takes 2 strings and returns the longer one. When the two strings have the same length, return the first string.
def longer_string(stringA, stringB):
if len(stringA) >= len(stringB):
return stringA
else:
return stringB
There are countless ways to write a program. Your program is correct as long as it produces the correct output
longer_string("cilantro", "mint")
'cilantro'
longer_string("cheddar", "mozzarella")
'mozzarella'
longer_string("poutine", "pizza")
'poutine'
import
that libraryNumpy: for dealing with sequences of numbers
Matplotlib: for plotting these sequences
import numpy as np
numbers = np.arange(10)
print(numbers)
[0 1 2 3 4 5 6 7 8 9]
type(numbers)
numpy.ndarray
np.zeros(5)
array([0., 0., 0., 0., 0.])
np.ones(50)
array([1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1.])
NumPy arrays can look very much like lists, but they are used for different things:
array = np.arange(5)
li = [0, 1, 2, 3, 4]
print(array, ' is ', type(array))
print(li, 'is', type(li))
[0 1 2 3 4] is <class 'numpy.ndarray'> [0, 1, 2, 3, 4] is <class 'list'>
Similar handling like lists:
print('The first element of numbers is:', numbers[0])
print('The last element of numbers is:', numbers[-1])
print('Numbers has', len(numbers), 'elements')
The first element of numbers is: 0 The last element of numbers is: 9 Numbers has 10 elements
numbers[2:5]
array([2, 3, 4])
array+array
array([0, 2, 4, 6, 8])
li+li
[0, 1, 2, 3, 4, 0, 1, 2, 3, 4]
array*5
array([ 0, 5, 10, 15, 20])
li*5
[0, 1, 2, 3, 4, 0, 1, 2, 3, 4, 0, 1, 2, 3, 4, 0, 1, 2, 3, 4, 0, 1, 2, 3, 4]
mean = np.mean(numbers)
smallest_element = np.min(numbers)
print('Mean:', mean)
print('Smallest element:', smallest_element)
Mean: 4.5 Smallest element: 0
How would you get the largest element?
It would be difficult (impossible?) to guess all available functions and what they to. If we want to see what functions are available we press Tab
after dot in IPython.
To understand how to use a function, type ?
after the function name. For example, if we wanted to take a look at how to round up a number using np.round
:
np.round?
Using the loadtxt function from NumPy:
chocolate = np.loadtxt('chocolate.csv', delimiter=',', skiprows=1)
Parameters in this function:
print(chocolate)
[[ 0. 0.] [ 1. 9.] [ 2. 16.] [ 3. 21.] [ 4. 24.] [ 5. 25.] [ 6. 24.] [ 7. 21.] [ 8. 16.] [ 9. 9.] [10. 0.]]
type(chocolate)
numpy.ndarray
len(chocolate)
11
But we also have columns, so instead we can use .shape
(notice no brackets ()
at the end of shape):
chocolate.shape
(11, 2)
shape = chocolate.shape
print('Number of rows', shape[0])
print('Number of columns', shape[1])
Number of rows 11 Number of columns 2
print("The first row:", chocolate[0])
The first row: [ 0. 0.]
print("The first five rows:")
print(chocolate[0:5])
The first five rows: [[ 0. 0.] [ 1. 9.] [ 2. 16.] [ 3. 21.] [ 4. 24.]]
print("All rows:")
chocolate[0:8]
All rows:
array([[ 0., 0.], [ 1., 9.], [ 2., 16.], [ 3., 21.], [ 4., 24.], [ 5., 25.], [ 6., 24.], [ 7., 21.]])
chocolate[2:11]
array([[ 2., 16.], [ 3., 21.], [ 4., 24.], [ 5., 25.], [ 6., 24.], [ 7., 21.], [ 8., 16.], [ 9., 9.], [10., 0.]])
chocolate[2:]
array([[ 2., 16.], [ 3., 21.], [ 4., 24.], [ 5., 25.], [ 6., 24.], [ 7., 21.], [ 8., 16.], [ 9., 9.], [10., 0.]])
How would you get the following rows?
a) The first two rows:
[[ 0., 0.],
[ 1., 9.]]
b) The last two rows:
[[ 9., 9.],
[ 10., 0.]]
c) Seventh to ninth row (count the rows if you are confused about this one):
[[ 6., 24.],
[ 7., 21.],
[ 8., 16.]]
chocolate[:2] # you an also write chocolate[:2], but shorter is better!
array([[ 0., 0.], [ 1., 9.]])
chocolate[-2:]
array([[ 9., 9.], [ 10., 0.]])
chocolate[6:9]
array([[ 6., 24.], [ 7., 21.], [ 8., 16.]])
But how do we get columns? Use comma to separate rows from columns!
chocolate[3] # the forth row
array([ 3., 21.])
print("Fourth row, first column:", chocolate[3, 0])
Fourth row, first column: 3.0
print("Fourth row, second column", chocolate[3, 1])
Fourth row, second column 21.0
Get all rows and the first column:
chocolate[:, 0]
array([ 0., 1., 2., 3., 4., 5., 6., 7., 8., 9., 10.])
And all rows and the second column:
chocolate[:, 1]
array([ 0., 9., 16., 21., 24., 25., 24., 21., 16., 9., 0.])
number_of_chocolates = chocolate[:, 0]
print(number_of_chocolates)
[ 0. 1. 2. 3. 4. 5. 6. 7. 8. 9. 10.]
happiness = chocolate[:, 1]
print("Happiness is:", happiness)
Happiness is: [ 0. 9. 16. 21. 24. 25. 24. 21. 16. 9. 0.]
Use NumPy to find the maximal happiness value with chocolate bars
Find the average amount of chocolate bars in this data set
print("Maximal happiness:", np.max(happiness))
Maximal happiness: 25.0
print("Average number oof chocolates:", np.average(chocolate))
Average number oof chocolates: 10.0
Next: Plotting!
import matplotlib.pyplot as plt
line = np.arange(5)
print('Line:', line)
squared_line = line**2
print('Squared line:', squared_line)
Line: [0 1 2 3 4] Squared line: [ 0 1 4 9 16]
plt.figure()
plt.plot(line, squared_line)
plt.show()
plt.figure()
plt.title('Squares')
plt.plot(line, squared_line)
plt.xlabel('x')
plt.ylabel('x squared')
plt.show()
chocolate = np.loadtxt('chocolate.csv', delimiter=',', skiprows=1)
number_of_chocolates = chocolate[:, 0]
happiness = chocolate[:, 1]
plt.figure()
plt.plot(number_of_chocolates, happiness)
plt.xlabel('Number of chocolates')
plt.ylabel('Happiness')
plt.savefig('chocolate.png')
plt.show()
plt.figure()
plt.bar(number_of_chocolates, happiness)
plt.show()
(Hint for 3: plt.subplot('111', axisbg='black')
)
plt.figure()
plt.subplot('111', facecolor='yellow')
plt.bar(number_of_chocolates, happiness, color='cornflowerblue', width=0.5)
plt.show()
Matplotlib gallery:
The project: https://github.com/uwpyb/materials/blob/master/projects/Day2_DataAnalysis.ipynb
Or a shorter link: https://goo.gl/7aRpZZ
We'll be back with demos and a short wrap-up discussion (i.e., what next?) at around 16:15!
We will send you more information about the next steps
Take advantage of CS courses at the Uni: CS 116 is also using Python (has a prerequisite CS115)
Lunches and coffee breaks provided by:
<3
people all over the world who write programs for free, so other people can use them and do awesome things!Help us to continue doing what we do by filling out the short survey! (you'll receive the link today)
Front graphics, cookies image: Graphics Provided by www.Vecteezy.com