Lecture 8
Lecture 8
OPTIONAL PARAMETERS
def func_name(par1, par2 = 5):
>>> func_name(4,9)
>>> func_name(3)
REVIEW: FUNCTION
CALLING:
Positional
Keyword arguments
REVIEW: BOOLEAN
FUNCTIONS
Functions that return Boolean
values
def is_divisible_by_2(num):
return (num % 2 == 0)
REVIEW: DEBUGGING IN
FUNCTIONS
▪ Preconditions
▪ Postconditions
UNKNOWN NUMBER OF
PARAMETERS
def add(*params):
total = 0
for i in params:
total += I
return total
>>> add(1,2,4)
>>> add(1,2,3,5,4,3)
RECURSION
n! = n*(n-1)!
f(n) = n * f(n-1)
FACTORIAL
RECURSION PARTS
1. Base case
2. Recursive Call
FIBONACCI SEQUENCE
0, 1, 1, 2, 3, 5, 8, 13…
FIBONACCI SEQUENCE
string
TRAVERSING
Computations on string start at the
beginning, select each character in turn, do
something to it, and continue until the end.
This pattern of processing is called a
traversal.
TRAVERSAL: FOR LOOP
for letter in
'banana' : b a n a n a
print(letter)
b a n a n a
We can get at any
single character in 0 1 2 3 4 5
a string using an
index specified in
>>> fruit =
square brackets
'banana‘
>>> print(fruit[1])
INDEXING OPERATOR
The expression in >>> fruit =
brackets is called an 'banana'
index
>>> letter = fruit[1]
>>> print(letter)
The index value must
be an integer and a
starts at zero >>> n = 3
>>> w = fruit[n - 1]
INDEXING OPERATOR
b a n a n a
0 1 2 3 4 5
>>> print(fruit[-1])
LENGTH OF A STRING
▪The len function, when applied to a
string, returns the number of characters
in a string
ctr = 0
ctr <
while ( ):
len(fruit)
fruit[ctr
print( ):
]
ctr+=1
SLICING STRINGS