def isprime2(n):
if n < 2:
return False
for d in range(2, round(n**0.5) + 1):
if n%d == 0:
return False
return True
isprime2(7)
isprime2(12)
Code comments start with #:
def mprimes2(n):
#plist is the list for storing prime numbers
plist = []
for k in range(n+1):
#iprime2 tests if a number is a prime or not
if isprime2(k):
plist.append(k) #adding a prime to the list
return plist
Docstring is string that can be used to explain what a function does and how to use it. Docstring must be placed immediately after the def
statement:
def myprimes2(n):
'''
Returns the list of all primes smaller or equal to n
'''
#plist is the list for storing prime numbers
plist = []
for k in range(n+1):
#iprime2 tests if a number is a prime or not
if isprime2(k):
plist.append(k) #adding a prime to the list
return plist
from math import sin
help(sin)
help(myprimes2)
states = ['AK', 'NY', 'MI', 'IL', 'TX']
print(states[0])
print(states[2])
Note: Indexing starts with 0!
Negative indexes count from the end of the list:
states[-1]
states[-3]
Changing a value on a list:
states[1] = 'CA'
print(states)
Inserting an element into a list:
states.insert(1, 'OH')
print(states)
states.pop(2)
print(states)
Indexing nested lists:
nested = [[1, 2], [4, 5, 6]]
print(nested[0])
print(nested[0][0])
print(nested[1][2])
nested[1][2] = 'hello'
print(nested)
List slicing produces a sublist of a list:
letter = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']
slice1 = letter[1:6]
print(slice1)
slice2 = letter[1:-1]
print(slice2)
Slice from 1st element to the end:
slice3 = letter[1:]
print(slice3)
From the beginning to the 5th element:
slice4 = letter[:6]
print(slice4)
Slicing can be used with the argument specifying step:
slice5 = letter[1:6:2]
print(slice5)
print(letter[-1::-1])
Slicing can be used to change several elements on a list at once:
a = [1, 2, 3, 4, 5, 6, 7, 8]
a[:3] = [100, 100, 100]
print(a)
vowels = ['a', 'e', 'i', 'o', 'u']
'u' in vowels
'n' in vowels
for letter in 'buffalo':
if letter in vowels:
print(letter)
for letter in 'buffalo':
if not (letter in vowels):
print(letter)
This also works:
for letter in 'buffalo':
if letter not in vowels:
print(letter)
a = [1, 2, 3]
print(a)
b = a
print(b)
b[0] = 1000
print(b)
print(a)
Compare this with the following:
a = 1
b = a
print(a)
print(b)
b += 1
print(b)
print(a)
a = [1, 2, 3]
id(a)
b = a
id(b)
a is b
c = [1, 2, 3]
id(c)
a is c
a == c
a = [1, 2, 3]
b = a.copy()
b[0] = 100
b
a
s = 'Minneapolis'
print(s[0])
print(s[-2])
print(s[1:-1])
print(s[::2])
'f' in 'Buffalo'
'c' in 'Buffalo'
s = 'cat'
s[0] = 'b'
def b_sub(s):
return 'b' + s[1:]
b_sub('cat')
b_sub('river')
from math import pi
def cyl_vol(r, h):
return pi*r**2*h
cyl_vol(1, 2)
cyl_vol(2, 1)
Passing arguments by keyword:
cyl_vol(r = 1, h=2)
cyl_vol(h=2, r=1)
You can specify some arguments by keyword and some by position, but position arguments must come first:
def timer(n, delay, msg):
from time import sleep
for i in range(n, 0, -1):
print(i)
sleep(delay)
print(msg)
timer(10, delay=0.5, msg='wake up!')
Default arguments:
def timer(n, delay = 1, msg = 'time up!'):
from time import sleep
for i in range(n, 0, -1):
print(i)
sleep(delay)
print(msg)
timer(5)
timer(5, msg = 'boom!!!')
import matplotlib.pyplot as plt
Basing plotting is done using plt.plot()
function.
Syntax: `plt.plot([list of x-ccords], [list of y-ccords])
plt.plot([1, 2, 3, 4], [2, 1, 1.5, 2])
plt.show() # use plt.show() to display the plot
You can use this to make plots look sharper:
%config InlineBackend.figure_format = 'retina'
plt.plot([1, 2, 3, 4], [2, 1, 1.5, 2])
plt.show()
plt.plot([1, 2, 3, 4], [2, 1, 1.5, 2])
plt.plot([0, 1, 2], [1, 2, 0])
plt.show()
xlist = range(-5, 6)
ylist = []
for x in xlist:
ylist.append(x**2)
list(xlist)
print(ylist)
plt.plot(xlist, ylist)
plt.show()
plt.plot(xlist, ylist, 'ro') # marker options: r = red, o = circle
plt.show()
plt.plot(xlist, ylist, 'gs') # marker options: g = green, s = square
plt.show()
plt.plot(xlist, ylist, 'gs-') # marker options: g = green, s = square, - = connect by lines
plt.show()
plt.plot(xlist, ylist, 'gs-', ms=20) # marker options: g = green, s = square, - = connect by lines
# ms specifies the marker size
plt.show()
plt.figure(figsize=(8, 4))
plt.title('My plot $f(x) = x^2$ ', fontsize = 20)
plt.plot(xlist, ylist, 'ro') # marker options: r = red, o = circle
plt.xlim(-10, 10)
plt.ylim(-2, 30)
plt.xlabel('This is x-axis')
plt.ylabel('This is y-axis')
plt.show()
xlist = []
for i in range(101):
xlist.append(i/100)
print(xlist)
from math import sin
ylist = []
for x in xlist:
ylist.append(sin(20*x))
print(ylist)
plt.plot(xlist, ylist)
plt.show()
squares = []
for i in range(11):
squares.append(i**2)
squares
The same code using list comprehensions:
squares2 = [i**2 for i in range(11)]
squares2
greetings = ['hello', 'hi', 'howdy']
mylist = [ x + '!' for x in greetings]
mylist
List comprehensions with if
statement:
# list of squares of even integers
evensq = []
for i in range(11):
if i%2 == 0:
evensq.append(i**2)
evensq
with list comprehensions:
evensq2 = [i**2 for i in range(11) if i%2 == 0]
evensq2
xlist = [x/100 for x in range(101)]
ylist = [sin(20*x) for x in xlist]
plt.plot(xlist, ylist)
plt.show()
from math import pi, cos
thetalist = [2*pi*i/1000 for i in range(1001)]
xlist = [sin(t) for t in thetalist]
ylist = [cos(t) for t in thetalist]
plt.axis('equal') # makes units on x and y axes equal
plt.plot(xlist, ylist)
plt.show()