# by default, only the result of the last expression in a cell is displayed after evaluation.
# the following forces display of *all* self-standing expressions in a cell.
from IPython.core.interactiveshell import InteractiveShell
InteractiveShell.ast_node_interactivity = "all"
if
-else
statements¶age=16
if age>=16:
print("old enough to drive")
print("not old enough to vote")
print("in high school")
old enough to drive not old enough to vote in high school
age=15
if age>=16:
print("old enough to drive")
else:
print("NOT old enough to drive")
NOT old enough to drive
from random import randint
score = randint(50, 100)
grade = None
if score >= 90:
grade = 'A'
elif score >= 80:
grade = 'B'
elif score >= 70:
grade = 'C'
elif score >= 60:
grade = 'D'
else:
grade = 'E'
print(score, grade)
86 B
#modules
import random
random
dir(random)
<module 'random' from 'C:\\Users\\bauerm\\anaconda3\\lib\\random.py'>
['BPF', 'LOG4', 'NV_MAGICCONST', 'RECIP_BPF', 'Random', 'SG_MAGICCONST', 'SystemRandom', 'TWOPI', '_Sequence', '_Set', '__all__', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', '_accumulate', '_acos', '_bisect', '_ceil', '_cos', '_e', '_exp', '_inst', '_log', '_os', '_pi', '_random', '_repeat', '_sha512', '_sin', '_sqrt', '_test', '_test_generator', '_urandom', '_warn', 'betavariate', 'choice', 'choices', 'expovariate', 'gammavariate', 'gauss', 'getrandbits', 'getstate', 'lognormvariate', 'normalvariate', 'paretovariate', 'randint', 'random', 'randrange', 'sample', 'seed', 'setstate', 'shuffle', 'triangular', 'uniform', 'vonmisesvariate', 'weibullvariate']
import random
?random.random
?random.randint
?random.randrange
import random as r
print(r.randint(1,10))
6
while
loops¶f0 = 0
f1 = 1
while f0 < 100:
print(f0)
f0, f1 = f1, f0+f1
0 1 1 2 3 5 8 13 21 34 55 89
i = 0
to_find = 10
while i < 5:
i += 1
if i == to_find:
print('Found; breaking early')
break
else:
print('Not found; terminated loop')
Not found; terminated loop
i = 0
to_find = 10
while i < 100:
i += 1
if i == to_find:
print('Found; breaking early')
break
else:
print('Not found; terminated loop')
Found; breaking early
# java throw exceptions, and try catch to
raise Exception('Boom!')
--------------------------------------------------------------------------- Exception Traceback (most recent call last) <ipython-input-20-9ea23f4001bb> in <module> 1 # java throw exceptions, and try catch to ----> 2 raise Exception('Boom!') Exception: Boom!
raise NotImplementedError()
--------------------------------------------------------------------------- NotImplementedError Traceback (most recent call last) <ipython-input-21-03b9be105f74> in <module> ----> 1 raise NotImplementedError() NotImplementedError:
try:
raise Exception('Boom')
except:
print('Exception encountered!')
Exception encountered!
try:
x = 1/0
except LookupError as e:
print('LookupError:', e)
except ArithmeticError as e:
print('ArithmeticError:', e)
except Exception as e:
print(e)
finally: #optional
print('Done')
ArithmeticError: division by zero Done
try:
x = 1/1
except LookupError as e:
print('LookupError:', e)
except ArithmeticError as e:
print('ArithmeticError:', e)
except Exception as e:
print(e)
finally: #optional
print('Done')
Done
for
loops (iteration)¶# range is a sequence type (immmutable), refault start is 0
# single argument is the end, stops at end-1
for x in range(10):
print(x)
0 1 2 3 4 5 6 7 8 9
# range with multiple arguments are start, end, increment (only goes up to end-1)
for i in range(9, 81, 9):
print(i)
9 18 27 36 45 54 63 72
for c in 'hello world':
print(c)
h e l l o w o r l d
to_find = 50
for i in range(100):
if i == to_find:
break
else:
print('Completed loop')
iter
and next
)¶r = range(10)
r
range(0, 10)
r = range(10)
it = iter(r) #iter generates an iterator on a sequence type
# an iterator can walk a sequence type using the .next() method
type(it)
type(r)
range_iterator
range
next(it)
0
next(it)
1
next(it)
--------------------------------------------------------------------------- StopIteration Traceback (most recent call last) <ipython-input-86-bc1ab118995a> in <module> ----> 1 next(it) StopIteration:
r = range(10)
# for x in r:
# print(x)
it = iter(r)
while True:
try:
x = next(it)
print(x)
except StopIteration:
break
0 1 2 3 4 5 6 7 8 9
it = iter(r)
while True:
try:
x = next(it)
y = next(it)
print(x, y, x+y)
except StopIteration:
break
0 1 1 2 3 5 4 5 9 6 7 13 8 9 17
def foo():
pass
foo()
foo(1)
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) <ipython-input-91-7d8d25071659> in <module> ----> 1 foo(1) TypeError: foo() takes 0 positional arguments but 1 was given
dir(foo)
['__annotations__', '__call__', '__class__', '__closure__', '__code__', '__defaults__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__get__', '__getattribute__', '__globals__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__kwdefaults__', '__le__', '__lt__', '__module__', '__name__', '__ne__', '__new__', '__qualname__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__']
?foo
import math
def quadratic_roots(a, b, c): #ax^2+bx+c
disc = b**2-4*a*c
if disc < 0:
return None
else:
return (-b+math.sqrt(disc))/(2*a), (-b-math.sqrt(disc))/(2*a)
quadratic_roots(1, -5, 6) # eq = (x-3)(x-2)
(3.0, 2.0)
?quadratic_roots
quadratic_roots(a=1, b=-5, c=6)
(3.0, 2.0)
quadratic_roots(c=6, a=1, b=-5)
(3.0, 2.0)
quadratic_roots(a=1, -5, 6)
File "<ipython-input-101-5cc2733929e2>", line 1 quadratic_roots(a=1, -5, 6) ^ SyntaxError: positional argument follows keyword argument
quadratic_roots(1, c=6, b=-5)
(3.0, 2.0)
def create_character(name, race, hitpoints, ability):
print('Name:', name)
print('Race:', race)
print('Hitpoints:', hitpoints)
print('Ability:', ability)
create_character('Legolas', 'Elf', 100, 'Archery')
Name: Legolas Race: Elf Hitpoints: 100 Ability: Archery
def create_character(name, race='Human', hitpoints=100, ability=None):
print('Name:', name)
print('Race:', race)
print('Hitpoints:', hitpoints)
if ability:
print('Ability:', ability)
create_character('Michael')
Name: Michael Race: Human Hitpoints: 100
def create_character(name, race='Human', hitpoints=100, abilities=()):
print('Name:', name)
print('Race:', race)
print('Hitpoints:', hitpoints)
if abilities:
print('Abilities:')
for ability in abilities:
print(' -', ability)
create_character('Gimli', race='Dwarf')
Name: Gimli Race: Dwarf Hitpoints: 100
create_character('Gandalf', hitpoints=1000)
Name: Gandalf Race: Human Hitpoints: 1000
create_character('Aragorn', abilities=('Swording', 'Healing'))
Name: Aragorn Race: Human Hitpoints: 100 Abilities: - Swording - Healing
def create_character(name, *abilities, race='Human', hitpoints=100):
print('Name:', name)
print('Race:', race)
print('Hitpoints:', hitpoints)
if abilities:
print('Abilities:')
for ability in abilities:
print(' -', ability)
create_character('Michael')
Name: Michael Race: Human Hitpoints: 100
create_character('Michael', 'Coding', 'Teaching', 'Sleeping', hitpoints=25, )
Name: Michael Race: Human Hitpoints: 25 Abilities: - Coding - Teaching - Sleeping
def foo():
print('Foo called')
bar = foo
bar()
Foo called
def foo(f):
f()
def bar():
print('Bar called')
foo(bar)
Bar called
foo = lambda: print('Anonymous function called')
foo()
Anonymous function called
f = lambda x,y: x+y
f(1,2)
3
def my_map(f, it):
for x in it:
print(f(x))
my_map(lambda x: x*2, "matt")
mm aa tt tt
my_map(lambda x: x*2, range(1,10))
2 4 6 8 10 12 14 16 18
?map
for x in map(lambda x: x*2, range(1,10)):
print(x)
2 4 6 8 10 12 14 16 18
def foo():
print('Foo called')
type(foo)
function
dir(foo)
['__annotations__', '__call__', '__class__', '__closure__', '__code__', '__defaults__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__get__', '__getattribute__', '__globals__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__kwdefaults__', '__le__', '__lt__', '__module__', '__name__', '__ne__', '__new__', '__qualname__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__']
foo()
foo.__call__()
Foo called Foo called
class Foo:
pass
Basic Class Example
class Foo:
def __init__(self, newX=1):
self.x=newX
print('I got constructed')
i=Foo()
i
I got constructed
<__main__.Foo at 0x143a38df160>
j=Foo(5)
j
j.x
I got constructed
<__main__.Foo at 0x143a38dfc10>
5
class Foo:
def __init__(self, newX=1):
self.x=newX
print('I got constructed')
def __str__(self):
return 'x='+str(self.x)
k=Foo(3)
k
print(k)
I got constructed
<__main__.Foo at 0x143a38c52e0>
x=3
dir(Foo)
['__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__']
class Foo:
def __init__(self, newX=1):
self.x=newX
print('I got constructed')
def __str__(self):
return 'x='+str(self.x)
def __repr__(self):
return str(self.x)
m=Foo('Matt')
m
print(m)
I got constructed
Matt
x=Matt
m==k
j==j
False
True
class Foo:
def __init__(self, newX=1):
self.x=newX
print('I got constructed')
def __str__(self):
return 'x='+str(self.x)
def __repr__(self):
return str(self.x)
def __eq__(self, that):
return self.x==that.x
print(i)
print(j)
print(k)
print(m)
<__main__.Foo object at 0x00000143A38DF160> <__main__.Foo object at 0x00000143A38DFC10> x=3 x=Matt
n=Foo(3)
k==n
m==n
I got constructed
True
False
Inheritance Example
class Shape:
def __init__(self, name):
self.name = name
def __repr__(self):
return self.name
def __str__(self):
return self.name.upper()
def area(self):
raise NotImplementedError()
s = Shape('circle')
s
circle
print(s)
CIRCLE
s.area()
--------------------------------------------------------------------------- NotImplementedError Traceback (most recent call last) <ipython-input-25-88799e7f1f86> in <module> ----> 1 s.area() <ipython-input-21-24ae96e78afe> in area(self) 10 11 def area(self): ---> 12 raise NotImplementedError() NotImplementedError:
class Circle(Shape):
def __init__(self, radius):
super().__init__('circle')
self.radius = radius
def area(self):
return 3.14 * self.radius ** 2
c = Circle(5.0)
c #call repr for Shape
print(c) #call str for Shape
c.area()
circle
CIRCLE
78.5
class Circle(Shape):
def __init__(self, radius):
super().__init__('circle')
self.radius = radius
def area(self):
return 3.14 * self.radius ** 2
def __eq__(self, other): #-->bool
return self.radius==other.radius
# if self.radius==other.radius:
# return true
# else:
# return false
def __add__(self, other): #make and return a new circle! wiht radius of the two cirlce radii added
#return Circle(self.radius+other.radius) no error checking on other datatype
if isinstance(other, Circle):
return Circle(self.radius+other.radius)
else:
return None
def __str__(self):
return super().__str__()+' radius='+str(self.radius)
# return str(super())+' radius='+str(self.radius)
c1 = Circle(2.0)
c2 = Circle(4.0)
c3 = Circle(2.0)
c1.area()
c1, c2, c3
c1 == c2
c1 == c3
d=c1 + c2
d.area()
print(c2+c2)
12.56
(circle, circle, circle)
False
True
113.04
<super: <class 'Circle'>, <Circle object>> radius=8.0
class Circle(Shape):
def __init__(self, radius):
super().__init__('circle')
self.radius = radius
def area(self):
return 3.14 * self.radius ** 2
def __eq__(self, other): #-->bool
return self.radius==other.radius
# if self.radius==other.radius:
# return true
# else:
# return false
def __add__(self, other): #make and return a new circle! wiht radius of the two cirlce radii added
#return Circle(self.radius+other.radius) no error checking on other datatype
if isinstance(other, Circle):
return Circle(self.radius+other.radius)
else:
return None
def __str__(self):
return super().__str__()+' radius='+str(self.radius)
# return str(super())+' radius='+str(self.radius)
@staticmethod
def whatever():
print("hello")
Circle.whatever()
hello
c1.whatever()
--------------------------------------------------------------------------- AttributeError Traceback (most recent call last) <ipython-input-46-c3d3d9e49e4c> in <module> ----> 1 c1.whatever() AttributeError: 'Circle' object has no attribute 'whatever'
Recall: All immutable sequences support the common sequence operations. For many sequence types, there are constructors that allow us to create them from other sequence types.
'hello'
'hello'[0]
'hello'
'h'
x="matt"
x[0]="M"
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) <ipython-input-48-4f6b14978d6a> in <module> 1 x="matt" ----> 2 x[0]="M" TypeError: 'str' object does not support item assignment
range(10) # default range starts at 0 and goes up to argument-1 default increment is 1
range(0, 10)
for i in range(5):
print(i)
0 1 2 3 4
for i in range(10, 20): # two arguments are start and end, stops at end-1 default increment is 1
print(i)
10 11 12 13 14 15 16 17 18 19
for k in range(20, 50, 5): #third argument is increment
print(k)
20 25 30 35 40 45
for j in range(10, 0, -1):
print(j)
10 9 8 7 6 5 4 3 2 1
g=range(5)
g
print(g)
h=range(6)
g==h
g+h
range(0, 5)
range(0, 5)
False
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) <ipython-input-56-44cdebb7a628> in <module> 4 h=range(6) 5 g==h ----> 6 g+h TypeError: unsupported operand type(s) for +: 'range' and 'range'
dir(range)
['__bool__', '__class__', '__contains__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__reversed__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'count', 'index', 'start', 'step', 'stop']
()
a=()
a
()
()
(1, 2, 3)
(1, 2, 3)
('a', 10, False, 'hello')
('a', 10, False, 'hello')
tuple(range(10))
(0, 1, 2, 3, 4, 5, 6, 7, 8, 9)
str(range(10))
'range(0, 10)'
tuple('hello')
('h', 'e', 'l', 'l', 'o')
('hello')
'hello'
('hello',)
('hello',)
w=(3,)
w[0]
w[1]
3
--------------------------------------------------------------------------- IndexError Traceback (most recent call last) <ipython-input-16-46c48757cdcd> in <module> 1 w[0] ----> 2 w[1] IndexError: tuple index out of range
t=('lions', 'tigers', False, (1,2,3))
t
('lions', 'tigers', False, (1, 2, 3))
t[2]
False
t[3]
(1, 2, 3)
t[3][1]
2
t[0]=1
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) <ipython-input-22-531e22094236> in <module> ----> 1 t[0]=1 TypeError: 'tuple' object does not support item assignment
#min(t)
#max(t)
t.append(5)
--------------------------------------------------------------------------- AttributeError Traceback (most recent call last) <ipython-input-24-2e0e2db6ce86> in <module> 1 #min(t) 2 #max(t) ----> 3 t.append(5) AttributeError: 'tuple' object has no attribute 'append'