Python 3 :: Lesson 9
▶ Function: your own machine # Define a function
▶ Input → Operations → Output # that converts a decimal integer to binary
▶ Input: def fname(args) def dec2bin(a):
# start a list to store binary digits
▶ def is Python keyword
b = []
▶ fname is the name of the function
# start a while loop to keep dividing a by 2
▶ args: the input parameter(s) while a>0:
▶ Operations: code block with # store the remainder in b
indent c = a%2
▶ Output: return variables b.append(c)
▶ Example: # store the quotient in a
a = a//2
def fn1(x, y):
# Finally reverse the order of b (optional)
z = x + 2*y
b.reverse()
return z
return b
▶ Why functions?
▶ Less repeatition x = int(input('x = '))
▶ Reusable codes
▶ Easy debugging print(dec2bin(x))
Python 3 :: Lesson 10
▶ Global and local variables
▶ Local variables are defined within a function
x = 1 # x is global
def f(s):
x = s + 1 # x is defined locally (not globally)
y = x + 1 # y is local
return y
print(x)
▶ Local variables are defined outside a function
x = 1 # x is global
def f(s):
y = x + 1 # x retains its global value
return y
print(x)
▶ x = 'test' # x is global
def f():
x = 'clear'
f()
print(x)