def add(a, b):
return a + b
print(add(1, 2))
print()
def myabs(x):
if x < 0 :
x = -x
return x
print(abs(-4))
print(myabs(-4))
3 4 4
def add(a, b):
return a + b
print(add)
<function add at 0x10d9ad6e0>
c = add(10, 30)
print(c)
40
f = add
print(f(4, 5))
9
print(f)
print(f is add)
<function add at 0x10b5ad758> True
def simpleFunction():
pass
simpleFunction()
def addmember(members, newmember):
if newmember not in members: # 기존 멤버가 아니면
members.append(newmember) # 추가
members = ['hwang', 'lee', 'park', 'youn'] # 리스트에 초기 멤버 설정
addmember(members, 'jo') # 새로운 멤버 추가
addmember(members, 'hwang') # (이미 존재하는) 새로운 멤버 추가
print(members)
['hwang', 'lee', 'park', 'youn', 'jo']
def f1(b):
b = 100
a = 200
f1(a)
print(a)
200
def f2(b):
b = "abc"
a = "def"
f2(a)
print(a)
def
def f3(b):
b = (1,2,3)
a = (4,5,6)
f3(a)
print(a)
(4, 5, 6)
def f4(b):
b[1] = 10
a = [4,5,6]
f4(a)
print(a)
[4, 10, 6]
def f5(b):
b['a'] = 10
a = {"a":1, "b":2}
f5(a)
print(a)
{'a': 10, 'b': 2}
def nothing():
return
print(nothing())
None
def print_menu():
print('1. Snack')
print('2. Snake')
print('3. Snick')
print_menu()
1. Snack 2. Snake 3. Snick
a = print_menu()
print(a)
1. Snack 2. Snake 3. Snick None
def abs_function(x):
if x < 0 : return -x
return x
print(abs_function(-10))
10
def swap(x, y):
return y, x # 튜플로 리턴된다.
a = 10
b = 20
print(a, b)
print()
a, b = swap(a, b) # 결과적으로 a, b = b, a와 동일
print(a, b)
print()
a = 10
b = 20
x = swap(a, b)
print(x[0], x[1]) # 하나의 이름으로 튜플을 받아서 처리할 수 도있다.
10 20 20 10 20 10
def length_list(l):
res = []
for el in l:
res.append(len(el))
return res
l = ['python', 'pyson', 'pythong', 'pydon']
print(length_list(l))
[6, 5, 7, 5]
l = ['python', 'pyson', 'pythong', 'pydon']
print([len(s) for s in l])
[6, 5, 7, 5]
def add(a, b):
return a + b
c = add(1, 3.4)
d = add('dynamic', 'typing')
e = add(['list'], ['and', 'list'])
print(c)
print(d)
print(e)
4.4 dynamictyping ['list', 'and', 'list']
def incr(a, step=1):
return a + step
b = 1
b = incr(b) # 1 증가
print(b)
b = incr(b, 10) # 10 증가
print(b)
2 12
def incr(step=1, a):
return a + step
File "<ipython-input-82-67693752f310>", line 1 def incr(step=1, a): SyntaxError: non-default argument follows default argument
def incr(a, step=1, step2=10):
return a + step + step2
print(incr(10))
21
def area(height, width):
return height * width
#순서가 아닌 이름으로 값이 전달
a = area(height='height string ', width=3)
print(a)
b = area(width=20, height=10)
print(b)
height string height string height string 200
print(area(20, width=5))
100
area(width=5, 20)
# 기존: SyntaxError: non-keyword arg after keyword arg
File "<ipython-input-26-020abdaed872>", line 1 area(width=5, 20) ^ SyntaxError: positional argument follows keyword argument
def incr(a, step=1, step2=10, step3=100):
return a + step + step2 + step3
print(incr(10, 2, step2=100))
212
def incr(a, step=1, step2=10, step3=100):
return a + step + step2 + step3
print(incr(10, 2, step2=100, 200))
# 기존: SyntaxError: non-keyword arg after keyword arg
File "<ipython-input-28-c7368e92bb98>", line 4 print(incr(10, 2, step2=100, 200)) ^ SyntaxError: positional argument follows keyword argument
def incr(a, step=1, step2=10, step3=100):
return a + step + step2 + step3
print(incr(10, 2, step2=100, step3=200))
312
*args
형식의 인수로 가변 인수를 선언할 수 있음*args
in function definitions in python is used to pass a variable number of arguments to a function.def myFun(*args):
print(type(args), args)
print()
for arg in args:
print(arg)
myFun('Hello', 'Welcome', 'to', 'GeeksforGeeks')
<class 'tuple'> ('Hello', 'Welcome', 'to', 'GeeksforGeeks') Hello Welcome to GeeksforGeeks
def varg(a, *args):
print(a, args)
varg(1)
varg(2, 3)
varg(2, 3, 4, 5, 6)
1 () 2 (3,) 2 (3, 4, 5, 6)
def printf(format, *args):
print(format % args)
printf("I've spent %d days and %d night to do this", 6, 5)
I've spent 6 days and 5 night to do this
def myFun(**kwargs):
print(type(kwargs), kwargs)
print()
for key, value in kwargs.items():
print("{0}: {1}".format(key, value))
myFun(first ='Geeks', mid ='for', last='Geeks')
<class 'dict'> {'first': 'Geeks', 'mid': 'for', 'last': 'Geeks'} first: Geeks mid: for last: Geeks
def myFun(arg1, **kwargs):
for key, value in kwargs.items():
print ("{0} - {1}: {2}".format(arg1, key, value))
myFun("Hi", first ='Geeks', mid ='for', last='Geeks')
Hi - first: Geeks Hi - mid: for Hi - last: Geeks
*튜플변수
"를 이용하여 함수 호출이 가능def h(a, b, c):
print(a, b, c)
args = (1, 2, 3)
h(*args)
1 2 3
**사전변수
"를 이용하여 함수 호출이 가능def h(a, b, c):
print(a, b, c)
dargs = {'aa':1, 'bb':2, 'cc':3}
h(*dargs)
dargs = {'a':1, 'b':2, 'c':3}
h(**dargs)
aa bb cc 1 2 3
def myFun(arg1, arg2, arg3):
print("arg1:", arg1)
print("arg2:", arg2)
print("arg3:", arg3)
args = ("Geeks", "for", "Geeks")
myFun(*args)
kwargs = {"arg1" : "Geeks", "arg2" : "for", "arg3" : "Geeks"}
myFun(**kwargs)
arg1: Geeks arg2: for arg3: Geeks arg1: Geeks arg2: for arg3: Geeks
def function(**arg):
for i in arg:
print (i, arg[i])
function(a=1, b=2, c=3, d=4)
a 1 b 2 c 3 d 4
a, *b = [1, 2, 3, 4]
print(a)
print(b)
1 [2, 3, 4]
def func(a, *b):
print(a, b)
func(1, 2, 3, 4)
1 (2, 3, 4)
numbers = [2, 1, 3, 4, 7]
more_numbers = [*numbers, 11, 18]
print(more_numbers)
[2, 1, 3, 4, 7, 11, 18]
print(*more_numbers)
2 1 3 4 7 11 18
fruits = ['lemon', 'pear', 'watermelon', 'tomato']
print(fruits[0], fruits[1], fruits[2], fruits[3])
print(*fruits)
lemon pear watermelon tomato lemon pear watermelon tomato
def transpose_list(list_of_lists):
return [list(row) for row in zip(*list_of_lists)]
t_l = transpose_list([[1, 4, 7], [2, 5, 8], [3, 6, 9]])
print(t_l)
[[1, 2, 3], [4, 5, 6], [7, 8, 9]]
date_info = {'year': "2020", 'month': "01", 'day': "01"}
filename = "{year}-{month}-{day}.txt".format(**date_info)
print(filename)
2020-01-01.txt
fruits = ['lemon', 'pear', 'watermelon', 'tomato']
numbers = [2, 1, 3, 4, 7]
print(*numbers, *fruits)
2 1 3 4 7 lemon pear watermelon tomato
date_info = {'year': "2020", 'month': "01", 'day': "01"}
track_info = {'artist': "Beethoven", 'title': 'Symphony No 5'}
filename = "{year}-{month}-{day}-{artist}-{title}.txt".format(
**date_info,
**track_info,
)
print(filename)
2020-01-01-Beethoven-Symphony No 5.txt
from random import randint
def roll(*dice):
print(type(dice), dice)
return sum([randint(1, die) for die in dice])
print(roll(20))
print(roll(6, 6))
print(roll(6, 6, 6))
<class 'tuple'> (20,) 17 <class 'tuple'> (6, 6) 10 <class 'tuple'> (6, 6, 6) 12
def tag(tag_name, **attributes):
attribute_list = ["{0}='{1}'".format(name, value) for name, value in attributes.items()]
return "<{0} ".format(tag_name) + ' '.join(attribute_list) + ">"
print(tag('a', href="http://treyhunner.com"))
print(tag('img', height=20, width=40, src="face.jpg"))
<a href='http://treyhunner.com'> <img height='20' width='40' src='face.jpg'>
참고 문헌: 파이썬(열혈강의)(개정판 VER.2), 이강성, FreeLec, 2005년 8월 29일