Ex.
``` def cal(num1, num2): result = num1 + num2 return result print(cal(3, 5)) ```
Ex.
``` def cal(end, start=0): total = 0 for i in range(start, end): total += i return total print(cal(5, 1)) # start = 1 print(cal(5)) # start = 0 ```
Ex.
``` def cal(end, start=0): total = 0 for i in range(start, end): total += i return total print(cal(5, 1)) # start = 1 print(cal(5)) # start = 0 ```
Ex.
``` def cal(*args): total = 0 for i in args: total += i return total print(cal(3, 4, 5, 6)) # 18 ```
Ex.
``` def cal(**args): print(args) info = {'name':'James', 'age':44, 'address':'NY'} print(**info) # {'name': 'Jame', 'age': 44, 'address': 'NY'} ```
Ex. 일반매개변수와 가변매개변수를 함께 사용 (1)
``` def cal(name, *args): print(name, ':', args) cal('James', 3, 4, 5) # James : (3, 4, 5) cal(3, 4, 5, 'James') # 3 : (4, 5, 'James') ```
Ex.일반매개변수와 가변매개변수를 함께 사용 (2)
``` def cal(name, **args): print(name, ':', args) info = {'a':1, 'b':2, 'c':3} print('James', **info) # James : {'a': 1, 'b': 2, 'c': 3} ```
Ex.
``` power = lambda x : x * x under_3 = lambda x : x < 3 multi = lambda x, y : x * y a = lambda x, y, z : x + y - z b = lambda x, y : x * y if x > 0 else y c = lambda x : x * 10 if x < 2 else(x ** 2 if x < 4 else x + 10) # ------------------------------------------ print(power(2)) # 4 print(under_3(2)) # True print(multi(5, 9)) # 45 print(a(1, 2, 4)) # -1 print(a(y=1, z=2, x=4)) # 3 : 키워드 매개변수도 가능 print(b(-2, 4)) # 4 : 람다함수 안에 조건문을 걸어줄 수 있음 print(c(5)) # 15 : elif문도 비슷하게 작성 가능 ```
Ex. map & filter
``` def power(value): return value * value def under_3(value): return value < 3 # ---------------------------------------- list_input = [1, 2, 3, 4, 5] # ------------------ map ------------------ result_map = map(power, list_input) print(list(result_map)) # ---------------- filter ---------------- result_map2 = filter(under_3, list_input) print(list(result_map2)) ```
ㄴ> 출력값
``` [1, 4, 9, 16, 25] [1, 2] ```
Ex. map에 lambda 함수를 mapping
``` list_input = [1, 2, 3, 4, 5] result = map(lambda x : x * 2, list_input) print(list(result)) ```
ㄴ> 출력값
``` [2, 4, 6, 8, 10] ```
Ex. map에 multi parameter 넘겨주기
``` sample = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] sample2 = [2, 13, 4, 56, 7] print(list(map(lambda x, y : x + y, sample, sample2))) ```
ㄴ> 출력값
``` [3, 15, 7, 60, 12] ```
Ex. zip
``` pro_number = [111, 222, 333] pro_maker = ["laptop", "smartphone", "smartTV"] pro_price = [200, 80, 560, 3344444] # ------------------------------------------------- print(list(zip(pro_number, pro_maker, pro_price))) ```
ㄴ> 출력값
``` [(111, 'laptop', 200), (222, 'smartphone', 80), (333, 'smartTV', 560)] ```
Ex. zip : 딕셔너리 만들기
``` ssn = [7788, 1234, 6790] name = ['강호동', '민경훈', '이상민'] my_dic = {} for s, n in zip(ssn, name): my_dic[s] = n print(my_dic) ```
ㄴ> 출력값
``` {7788: '강호동', 1234: '민경훈', 6790: '이상민'} ```
Ex. enumerate
``` for i, v in enumerate([1, 2, 3, 4, 5]): print(i, " : " , v) # i : index ```
ㄴ> 출력값
``` 0 : 1 1 : 2 2 : 3 3 : 4 4 : 5 ```