# 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)
99 A
#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
raise Exception('Boom!')
--------------------------------------------------------------------------- Exception Traceback (most recent call last) <ipython-input-17-19c2dbb533f1> in <module> ----> 1 raise Exception('Boom!') Exception: Boom!
raise NotImplementedError()
--------------------------------------------------------------------------- NotImplementedError Traceback (most recent call last) <ipython-input-18-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)¶# a range is a sequence type (immutable), default start is 0
# a 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
)¶for i in range(10):
print (i)
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)
2
next(it)
3
next(it)
4
next(it)
5
next(it)
6
next(it)
7
next(it)
8
next(it)
9
next(it)
--------------------------------------------------------------------------- StopIteration Traceback (most recent call last) <ipython-input-39-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-44-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-52-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:
# all instance methods must have first argument self (invisible argument)
def __init__(self, newX=1): # __init__ is constructor
self.x=newX # all instance attributes(variables) are prefixed with self.
print('I got constructed')
i=Foo() # create a Foo object, assign it to variable i
i.x #all instance attributes are public by default
i
I got constructed
1
<__main__.Foo at 0x1c1b2b4f5b0>
j=Foo(-10)
j.x
j
I got constructed
-10
<__main__.Foo at 0x1c1b2b4f790>
class Foo:
# all instance methods must have first argument self (invisible argument)
def __init__(self, newX=1): # __init__ is constructor
self.x=newX # all instance attributes(variables) are prefixed with self.
print('I got constructed')
# toString in java
def __str__(self):
return "x = "+ str(self.x)
def __repr__(self): # representation of the object (instance attributes)
return str(self.x)
k=Foo(456)
k.x
print(k) # calls __str__
k #calls the __repr__
I got constructed
456
x = 456
456
class Foo:
# all instance methods must have first argument self (invisible argument)
def __init__(self, newX=1): # __init__ is constructor
self.x=newX # all instance attributes(variables) are prefixed with self.
print('I got constructed')
# toString in java
def __str__(self):
return "x = "+ str(self.x)
def __repr__(self): # representation of the object (instance attributes)
return str(self.x)
def __eq__(self, that):
# compare self.x to that.x
return self.x==that.x
i==j
j==j
False
True
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
str(s)
'CIRCLE'
s.area()
--------------------------------------------------------------------------- NotImplementedError Traceback (most recent call last) <ipython-input-17-88799e7f1f86> in <module> ----> 1 s.area() <ipython-input-13-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
c.area()
print(s) # calls __str__
circle
78.5
CIRCLE
class Circle(Shape):
def __init__(self, radius):
super().__init__('circle')
self.radius = radius
def area(self):
return 3.14 * self.radius ** 2
def __str__(self):
return "circle with radius " + str(self.radius)
def __eq__(self, that):
return isinstance(that, Circle) and self.radius==that.radius
def __add__(self, that):
if isinstance(that,Circle): # check if argument is a circle object
return Circle(self.radius+that.radius)
else:
return None
c1 = Circle(2.0)
c2 = Circle(4.0)
c3 = Circle(2.0)
c1.area()
c1, c2, c3
c1 == c2
c1 == c3
str(c1 + c2) #c1.__add__(c2) c2__add__(c1) c2+c1
str(c1 + Shape("blob"))
12.56
(circle, circle, circle)
False
True
'circle with radius 6.0'
'None'
class Circle(Shape):
def __init__(self, radius):
super().__init__('circle')
self.radius = radius
def area(self):
return 3.14 * self.radius ** 2
def __str__(self):
return "circle with radius " + str(self.radius)
def __eq__(self, that):
return isinstance(that, Circle) and self.radius==that.radius
def __add__(self, that):
if isinstance(that,Circle): # check if argument is a circle object
return Circle(self.radius+that.radius)
else:
return None
@staticmethod
def whatever():
print("in class method")
Circle.whatever()
in class method
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'
range(10)
range(10, 20)
range(20, 50, 5)
range(10, 0, -1)
()
()
(1, 2, 3)
(1, 2, 3)
('a', 10, False, 'hello')
('a', 10, False, 'hello')
x=tuple(range(10))
x
x[4]
x[0]
x[-1]
(0, 1, 2, 3, 4, 5, 6, 7, 8, 9)
4
0
9
x[0]=3
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) <ipython-input-37-a7a7f361dc30> in <module> ----> 1 x[0]=3 TypeError: 'tuple' object does not support item assignment
for i in x:
print(i)
0 1 2 3 4 5 6 7 8 9
min(x)
max(x)
0
9
y=x+x
x
y
(0, 1, 2, 3, 4, 5, 6, 7, 8, 9)
(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9)
tuple('hello')
('h', 'e', 'l', 'l', 'o')
def sumN(n): # sum up the values 1 to n
if n==0:
return 0
else:
return n+sumN(n-1)
# return n*(n+1)/2
sumN(5)
15