How to define function:
def func_name(param1, param2):
return param1 + param2
Default parameter
def add(x, y, z=1):
a = x + y + z
return a
add(10, 6) # 17
SyntaxError: non-default argument follows default argumnet
def good1(a, b, c=2):
def good2(a, b=1, c=2):
def bad1(a, b=1, c):
def bad2(a=1, b=2, c):
Keyword parameter
add(y=5, x=10, z=1) # 16
Return
def add_mul(x, y):
s = x + y
m = x * y
return s, m
c = add_mul(20, 3)
print(c) # (23, 60)
a, b = add_mul(20, 3) # Can use tuple unpacking
Variable scope
Variable length argument (가변길이 인자)
e.g.) print(), format(), …
def test(*args):
print(type(args))
test(10, 20, 30) # <class 'tuple'>
test() # acknowledge as empty tuple
Keyword paramenter
def test(**kwargs):
print(type(kwargs))
for k, v in kwargs.items():
print(k, v)
test(a=10, b=20, name='Shaun') # <class 'dict'>
# a 10
# b 20
# name Shaun
asd = 'Hi {}, I am Mee{}!'
print(asd) # Hi {}, I am Mee{}!
asd = 'Hi {}, I am Mee{}!'.format('Shaun', 6)
print(asd) # Hi Shaun, I am Mee6!
asd = 'Hi {name}, I am Mee{number}!'.format(name = 'Shaun', number = 6)
print(asd) # Hi Shaun, I am Mee6!
For more info about .format() method: https://pyformat.info/
Lambda
def square(param):
return x**2
square(5) # 25
square2 = lambda param:returnValue**2 # input:output
square2(5) # 25
mult = lambda x,y:x*y
mult(2,3) # 6
e.g.) .sort(), filter(), map(), reduce()
def str_len(s):
return len(s)
strings = ['bnm', 'asd', 'cvb']
strings.sort(key=str_len) # key's input => LOCAL function
strings.sort(key=lambda s:len(s))
print(strings)
# filter(function, list)
nums = [1, 2, 3, 4, 5, 6]
list(filter(lambda n:n%2==0, nums)) # 2, 4, 6
# map(function, list)
list(map(lambda n:n**2, nums)) # 1, 4, 9, ...
list(map(lambda n:n**2==0, nums)) # False, True, False, ...
# reduce: consecutive operation of 2 previous elements
import functools
a = [1, 3, 5, 8]
functools.reduce(lambda x,y:x+y, a) # 17