How was lab? Was anything confusing?
Last time we covered functions. Functions are critical to programming.
The general syntax for functions is:
def function_name(<arguments>):
<body>
return <expression>
There are several things to note about the syntax (we will go through examples):
:
after the functiondef minimum_two(x, y):
if x < y:
return x
else:
return y
minimum_two(1, 2)
1
def min_list(l):
minimum = l[0]
for x in l[1:]:
minimum = minimum_two(minimum, x)
return minimum
min_list([6, 5, 4, 3, 2, 1])
1
min(1, 2)
1
max(1, 2)
2
Conversion:
int
float
bool
str
list
dict
Build in:
min
max
sum
DO NOT USE THESE AS VARIABLE NAMES
We will go through examples of functions
def sum_list(l):
s = 0
for x in l:
s += x
return s
sum_list([1, 2, 3, 4, 5])
15
def is_palindrome(s):
for ind in range(len(s)):
if s[ind] != s[len(s) - ind - 1]:
return False
return True
print(is_palindrome("abccba"))
print(is_palindrome("abcba"))
print(is_palindrome("abcbab"))
True True False
def add_two_numbers(x, y):
return x + y
add_two_numbers(1, 2)
3
def add_three_numbers(x, y, z):
sum_two = add_two_numbers(x, y)
return sum_two + z
add_three_numbers(1, 2, 3)
6
def calls_itself(x):
if x < 0:
return 0
else:
print(x)
return calls_itself(x - 1)
calls_itself(2)
2 1 0
0
def sum_list(l):
if len(l) == 0:
return 0
return l[0] + sum_list(l[1:])
sum_list([1, 2, 3])
6
# WARNING
# WARNING
# WARNING
# DO NOT RUN THIS CELL
def calls_itself(x):
print(x)
return calls_itself(x - 1)
calls_itself(2)
When a function calls itself, it is called recursion. This is a powerful, yet confusing concept.
def nth_power(x, nth):
if nth == 0:
return 1
return x * nth_power(x, nth - 1)
nth_power(2, 5)
32
def fibonacci(n):
if n < 0:
return 0
if n == 0 or n == 1:
return n
return fibonacci(n - 1) + fibonacci(n - 2)
fibonacci(8)
21
def factorial(x):
if x == 1:
return 1
return x * factorial(x - 1)
factorial(5)
120
def sum_n(n):
if n == 1:
return 1
return n + sum_n(n - 1)
sum_n(5)
15
def reverse(s):
if len(s) == 0:
return s
else:
return reverse(s[1:]) + s[0]
reverse("hi")
'ih'
def is_palindrome(s):
if len(s) <= 1:
return True
return (s[0] == s[-1]) and is_palindrome(s[1:-1])
print(is_palindrome("abccba"))
print(is_palindrome("abcba"))
print(is_palindrome("abcbab"))
True True False