# Hàm¶

## Định nghĩa hàm¶

In [1]:
def is_even(i):
"""
Input: i, a positive int
Returns True if i is even, otherwise False
"""
print("hi")
return i % 2 == 0

is_even(3)

hi

Out[1]:
False

### Bài tập¶

Write a function isIn that accepts two strings as arguments and returns True if either string occurs anywhere in the other, and False otherwise. Hint: you might want to use the built-in str operation in.

## Phạm vi của biến¶

In [3]:
def f( x ):
x = x + 1
print('in f(x): x =', x)
return x

x = 3
z = f( x )
print('out f(x): x =', x)

in f(x): x = 4
out f(x): x = 3

In [2]:
def is_even( i ):
i % 2 == 0

a = is_even(3)
type(a)

Out[2]:
NoneType
In [11]:
def func_a():
print('inside func_a')
def func_b(y):
print('inside func_b')
return y
def func_c(z):
print('inside func_c')
return z()

print(func_a())
print(5 + func_b(2))
print(func_c(func_a))

inside func_a
None
inside func_b
7
inside func_c
inside func_a
None

In [12]:
def f(y):
x = 1
x += 1
print(x)

x = 5
f(x)
print(x)

2
5

In [13]:
def g(y):
print(x)
print(x + 1)

x = 5
g(x)
print(x)

5
6
5

In [14]:
def h(y):
x = x + 1

x = 5
h(x)
print(x)

---------------------------------------------------------------------------
UnboundLocalError                         Traceback (most recent call last)
<ipython-input-14-b0af8d3408f0> in <module>()
3
4 x = 5
----> 5 h(x)
6 print(x)

<ipython-input-14-b0af8d3408f0> in h(y)
1 def h(y):
----> 2     x = x + 1
3
4 x = 5
5 h(x)

UnboundLocalError: local variable 'x' referenced before assignment
In [16]:
def g(x):
def h():
x = 'abc'
x = x + 1
print('in g(x): x =', x)
h()
return x

x = 3
z = g(x)
z

in g(x): x = 4

Out[16]:
4

## Tham số đặt tên - Keyword Arguments¶

In [19]:
def printName(firstName, lastName, reverse):
if reverse:
print(lastName + ', ' + firstName)
else:
print(firstName, lastName)

printName('Eric', 'Grimson', False)

printName('Eric', 'Grimson', reverse = False)

printName('Eric', lastName = 'Grimson', reverse = False)

printName(lastName = 'Grimson', firstName = 'Eric', reverse = False)

Eric Grimson
Eric Grimson
Eric Grimson
Eric Grimson


## Giá trị mặc định - default values¶

In [20]:
def printName(firstName, lastName, reverse = False):
if reverse:
print(lastName + ', ' + firstName)
else:
print(firstName, lastName)

printName('Eric', 'Grimson')

printName('Eric', 'Grimson', True)

Eric Grimson
Grimson, Eric


## Các đặt tả - specification/docstring¶

In [24]:
def is_even( i ):
"""
Input: i, a positive int
Returns True if i is even, otherwise False
"""
print('hi')
return i % 2 == 0

# hit Shift-Tab to see docstring
is_even(3)

hi

Out[24]:
False

## Đệ qui¶

In [47]:
def mult_iter(a, b):
result = 0
while b > 0:
result += a
b -= 1
return result

mult_iter(2, 3)

Out[47]:
6
In [48]:
def mult(a, b):
if b == 1:
return a
else:
return a + mult(a, b-1)

mult(2, 3)

Out[48]:
6
In [49]:
def fact(n):
if n == 1:
return 1
else:
return n*fact(n-1)

fact(4)

Out[49]:
24

## Towers of Hanoi¶

Video giới thiệu

In [53]:
def printMove(fr, to):
print('move from ' + str(fr) + ' to ' + str(to))

def Towers(n, fr, to, spare):
if n == 1:
printMove(fr, to)
else:
Towers(n - 1, fr, spare, to)
Towers(1, fr, to, spare)
Towers(n - 1, spare, to, fr)

Towers(4, 'P1', 'P2', 'P3')

move from P1 to P3
move from P1 to P2
move from P3 to P2
move from P1 to P3
move from P2 to P1
move from P2 to P3
move from P1 to P3
move from P1 to P2
move from P3 to P2
move from P3 to P1
move from P2 to P1
move from P3 to P2
move from P1 to P3
move from P1 to P2
move from P3 to P2


## Đệ qui với nhiều trường hợp ngừng (base cases)¶

In [43]:
def fib(x):
"""
assumes x an int >= 0
return Fibonacci of x
"""
if x == 0 or x == 1:
return 1
else:
return fib(x - 1) + fib(x - 2)

def testFib(n):
for i in range(n + 1):
print('fib of', i, '=', fib(i))

testFib(10)

fib of 0 = 1
fib of 1 = 1
fib of 2 = 2
fib of 3 = 3
fib of 4 = 5
fib of 5 = 8
fib of 6 = 13
fib of 7 = 21
fib of 8 = 34
fib of 9 = 55
fib of 10 = 89


### Bài tập¶

When the implementation of fib in the above program is used to compute fib(5), how many times does it compute the value of fib(2) on the way to computing fib(5)?

## Đệ qui với phi số¶

In [44]:
def isPalindrome(s):
def toChars(s):
s = s.lower()
ans = ''
for c in s:
if c in 'abcdefghijklmnopqrstuvwxyz':
ans = ans + c
return ans

def isPal(s):
if len(s) <= 1:
return True
else:
return s[0] == s[-1] and isPal(s[1:-1])

return isPal(toChars(s))

def testIsPalindrome():
print('Try dogGod')
print(isPalindrome('dogGod'))
print('Try Able was I, ere I saw Elba')
print(isPalindrome("Able was I, ere I saw Elba"))

testIsPalindrome()

Try dogGod
True
Try Able was I, ere I saw Elba
True


## Tập tin¶

In [30]:
# %load Files/circle.py
pi = 3.14159

def area(radius):
return pi * (radius**2)

def circumference(radius):
return 2*pi*radius

In [2]:
from Files import circle
pi = 3
print(pi)
print(circle.pi)
print(circle.area(3))
print(circle.circumference(3))

3
3.14159
28.27431
18.849539999999998

In [39]:
nameHandle = open('Files/kids', 'w')
for i in range(2):
name = input('Enter name: ')
nameHandle.write(name + '\n')
nameHandle.close()

Enter name: man
Enter name: le

In [40]:
nameHandle = open('Files/kids', 'r')
for line in nameHandle:
print(line)
nameHandle.close()

man

le