728x90
반응형
Python의 반복문, 함수¶
- List, For문, If문의 사용법
- 사용자 정의 함수 사용법
In [1]:
list(range(1, 10, 1))
Out[1]:
[1, 2, 3, 4, 5, 6, 7, 8, 9]
In [2]:
range(1, 10, 1)
Out[2]:
range(1, 10)
In [3]:
r = range(0, 20, 2)
r
Out[3]:
range(0, 20, 2)
In [4]:
r[5]
Out[4]:
10
In [5]:
r[:5]
Out[5]:
range(0, 10, 2)
In [6]:
a = 10
b = 20
In [7]:
score = int(input('점수 입력: '))
if score >= 90:
print('A')
elif score >= 80:
print('B')
elif score >= 70:
print('C')
else:
print('D')
점수 입력: 88 B
In [8]:
colors = ['red', 'orange', 'black', 'blue']
for c in colors:
print(c)
red orange black blue
In [9]:
result = [90, 35, 68, 44, 81]
count = 1
for i in result:
if i >= 60:
print(count, '번 학생은 합격', sep='')
else:
print(count, '번 학생은 불합격', sep='')
count+=1
1번 학생은 합격 2번 학생은 불합격 3번 학생은 합격 4번 학생은 불합격 5번 학생은 합격
In [10]:
result = [90, 35, 68, 44, 81]
for i in range(len(result)):
if result[i] >= 60:
print(i+1, '번 학생은 합격', sep='')
else:
print(i+1, '번 학생은 불합격', sep='')
1번 학생은 합격 2번 학생은 불합격 3번 학생은 합격 4번 학생은 불합격 5번 학생은 합격
- sep = '' 을 이용하여 공백 제거
In [11]:
result = [90, 35, 68, 44, 81]
for i, v in enumerate(result):
if v >= 60:
print(i+1, '번 학생은 합격', sep='')
else:
print(i+1, '번 학생은 불합격', sep='')
1번 학생은 합격 2번 학생은 불합격 3번 학생은 합격 4번 학생은 불합격 5번 학생은 합격
In [12]:
a = [10, 20]
a
Out[12]:
[10, 20]
In [13]:
a, b = [10, 20]
print(a, b)
10 20
In [14]:
a, b, c, d = 10, 20, 30, 40
- for 문으로 Mylist 살펴보기
- for 문의 변수 i 가 interable 형태이다. ['a', 'b','b'] ...
In [15]:
mylist = [list('abc'), list('edf'), list('dkx')]
mylist
Out[15]:
[['a', 'b', 'c'], ['e', 'd', 'f'], ['d', 'k', 'x']]
In [16]:
for i in mylist:
for j in i:
print(j)
a b c e d f d k x
In [17]:
mylist = [list('abc'), 1, tuple('ghi')]
mylist
Out[17]:
[['a', 'b', 'c'], 1, ('g', 'h', 'i')]
- list 사이에 문자열이 섞여 있을경우 어떻게 출력 할 것 인가?
In [18]:
for i in mylist:
# print (type(i))
if type(i) == list: # 문자열이 섞였을 경우
for j in i:
print(j)
else:
print(i)
a b c 1 ('g', 'h', 'i')
- Mylist에 여러가지 타입이 섞여 있을 경우 어떻게 출력 할 것인가?
In [19]:
mylist = [list('abc'), 1, tuple('dkx')]
mylist
Out[19]:
[['a', 'b', 'c'], 1, ('d', 'k', 'x')]
In [20]:
for i in mylist:
if type(i) in [list, tuple]:
for j in i:
print(j)
else:
print(i)
a b c 1 d k x
- 함수, 사용자 정의 함수
- sum
- any 한개라도 참이 있으면 true
- all 전체가 다 참이면 True
In [21]:
sum([1,2,3,4])
Out[21]:
10
In [22]:
any([0,2,3,4]), all([0,2,3,4])
Out[22]:
(True, False)
- any 예시를 위한 array 생성. numpy는 뒤에 이어서
In [23]:
import numpy as np
arr = np.array([0,1,2,3,4,5])
arr
Out[23]:
array([0, 1, 2, 3, 4, 5])
In [24]:
np.any(arr%2==0) #이런 용도 any 사용
Out[24]:
True
In [25]:
a = [1,2,3,4]
b = []
for i in a:
b.append(i%2==0)
b
Out[25]:
[False, True, False, True]
In [26]:
c = (i for i in a if i%2==0)
c
Out[26]:
<generator object <genexpr> at 0x000001CC539D67B0>
- def 를 이용하여 사용자 함수를 정의한다.
- ex) def 함수명(매개변수) :
- return에 원하는 함수 수식을 입력한다.
- return이 없어도 호출한 곳으로 돌아가 함수가 적용된다.
- return이 두개 있는경우, 첫번째 return을 적용후 함수가 종료되어 두번째 return 값은 적용되지 않는다.
In [27]:
def myfunc(x, y):
return x+y
myfunc(10, 20)
Out[27]:
30
In [ ]:
In [28]:
def myfunc(x, y):
c = x + y
return
print(myfunc(10, 20))
None
In [29]:
def myfunc(x, y):
c = x + y
print(myfunc(10, 20))
None
In [30]:
def myfunc(x, y):
return x+y
c = x+2*y
return c
myfunc(10, 20)
Out[30]:
30
매개변수¶
- 전역변수와 지역변수
- 전역변수 : 전체적으로 코드 내에서 공통적으로 사용할 수 있는 변수
- 지역변수 : 특정 범위 내에서 사용이 가능한 변수 (함수 내부 선언 변수)
- 함수 내부에서 전역변수를 수정하고 싶은경우, global 전역변수 를 선언후 수정 가능
In [31]:
전역변수 = 10000
def func1(x, y):
변수 = 1000
return x+y+변수+전역변수
def func2(x, y):
전역변수 = 100
전역변수 += 10000
return x-y-전역변수
print(func2(10, 20))
print(func1(10, 20))
-10110 11030
- if 문 내부의 변수는 일반 local 변수로 쓰인다.
In [32]:
요일 = '월'
if 요일 == '월':
변수1 = '월요일'
else:
변수1 = '화요일'
변수1
Out[32]:
'월요일'
In [33]:
def myfunc(x, y):
return x + y
myfunc(10, 10 , 20)
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) ~\AppData\Local\Temp/ipykernel_2676/4019214905.py in <module> 2 return x + y 3 ----> 4 myfunc(10, 10 , 20) TypeError: myfunc() takes 2 positional arguments but 3 were given
In [34]:
def myfunc(x, y, z=100, a=100):
return x + y + z + a
myfunc(10, 10)
Out[34]:
220
In [35]:
range?
In [36]:
def myfunc(x, y, z=100, a=100):
return x + y + z + a
myfunc(10, a=10000, y=100)
Out[36]:
10210
In [37]:
def mysum(x):
ret = 0
for i in x:
ret+=i
return ret
mysum([10, 10, 20, 30, 50])
Out[37]:
120
함수의 매개변수¶
- *x 를 매개변수로 지정하여 여러개의 변수를 받을 수 있다. packing
- 출력시 *을 사용하여 값으로 출력가능. unpacking
In [38]:
def mysum(*x):
ret = 0
for i in x:
ret+=i
return ret
mysum(10, 10, 20, 30, 50)
mysum(*[10, 10, 20, 30, 50])
Out[38]:
120
In [39]:
def mysum(a,b,c,d,e):
return a+b+c+d+e
mysum(*[10, 10, 20, 30, 50])
Out[39]:
120
In [40]:
a, b = [1,2]
b
Out[40]:
2
In [41]:
def myadd(**a):
print(a)
myadd(b=10, c=20)
{'b': 10, 'c': 20}
In [42]:
def myadd(a, b):
print(a, b)
myadd(**{'a':10, 'b':20})
10 20
- b는 myadd에 있기에 값으로 나오고 나머지는 없기에 dcit형식으로 전달
In [43]:
def myadd(b, **a):
print(b, a)
myadd(b=10, c=20)
10 {'c': 20}
- 아무것도 들어오지 않는 경우 빈값
In [44]:
def myadd(*a, **b):
print(a)
print(b)
myadd(c=10, d=20)
() {'c': 10, 'd': 20}
- 매개변수에 들어올 값이 여러개가 섞여 있으면, 알아서 나뉜다.
In [45]:
def myadd(*a, **b):
print(a)
print(b)
myadd(10,30, d=10, e=50)
(10, 30) {'d': 10, 'e': 50}
함수의 활용¶
- 덧셈과 곱셈을 해주는 함수
In [46]:
def calc_many(choice, *args):
ret = 0 if choice=='sum' else 1
for i in args:
ret = (ret+i) if choice=='sum' else (ret*i)
return ret
print(calc_many('sum', 1,2,3,4))
print(calc_many('mul', 1,2,3,4))
10 24
In [47]:
def mysum(args):
return sum(args)
def mymul(args):
ret = 1
for i in args:
ret*=i
return ret
def calc_many(choice, *args):
func = {'sum': mysum, 'mul': mymul}[choice]
return func(args)
print(calc_many('sum', 1,2,3,4))
print(calc_many('mul', 1,2,3,4))
10 24
In [48]:
a = calc_many
a('sum', 1,2,3,4)
Out[48]:
10
In [49]:
def calc_many(choice, *args):
func = {'sum': mysum, 'mul': mymul}[choice]
return func
In [50]:
a = calc_many('mul', 1,2,3,4)
a([1,2,3,4])
Out[50]:
24
In [51]:
print('''hello
안녕하세요
python
파이썬''')
hello 안녕하세요 python 파이썬
In [52]:
def calc_many(choice, *args):
'''
안녕하세요
'''
func = {'sum': mysum, 'mul': mymul}[choice]
'''
asdfasdf
adfasdf
'''
a = 10
b = 10
return func
In [53]:
calc_many.__doc__
Out[53]:
'\n 안녕하세요\n '
In [54]:
def func(a, /, b, *, c):
print(a,b,c)
func(10, 20, c=30)
10 20 30
In [55]:
func(10, b=20, c=30)
10 20 30
In [56]:
func(a=10, b=20, c=30) # positional only를 키워드로 전달
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) ~\AppData\Local\Temp/ipykernel_2676/3538529970.py in <module> ----> 1 func(a=10, b=20, c=30) # positional only를 키워드로 전달 TypeError: func() got some positional-only arguments passed as keyword arguments: 'a'
In [57]:
func(10, 20, 30) # 키워드 only를 positional로 전달
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) ~\AppData\Local\Temp/ipykernel_2676/3946576282.py in <module> ----> 1 func(10, 20, 30) # 키워드 only를 positional로 전달 TypeError: func() takes 2 positional arguments but 3 were given
In [58]:
range?
In [59]:
dir(__builtins__)
Out[59]:
['ArithmeticError', 'AssertionError', 'AttributeError', 'BaseException', 'BlockingIOError', 'BrokenPipeError', 'BufferError', 'BytesWarning', 'ChildProcessError', 'ConnectionAbortedError', 'ConnectionError', 'ConnectionRefusedError', 'ConnectionResetError', 'DeprecationWarning', 'EOFError', 'Ellipsis', 'EnvironmentError', 'Exception', 'False', 'FileExistsError', 'FileNotFoundError', 'FloatingPointError', 'FutureWarning', 'GeneratorExit', 'IOError', 'ImportError', 'ImportWarning', 'IndentationError', 'IndexError', 'InterruptedError', 'IsADirectoryError', 'KeyError', 'KeyboardInterrupt', 'LookupError', 'MemoryError', 'ModuleNotFoundError', 'NameError', 'None', 'NotADirectoryError', 'NotImplemented', 'NotImplementedError', 'OSError', 'OverflowError', 'PendingDeprecationWarning', 'PermissionError', 'ProcessLookupError', 'RecursionError', 'ReferenceError', 'ResourceWarning', 'RuntimeError', 'RuntimeWarning', 'StopAsyncIteration', 'StopIteration', 'SyntaxError', 'SyntaxWarning', 'SystemError', 'SystemExit', 'TabError', 'TimeoutError', 'True', 'TypeError', 'UnboundLocalError', 'UnicodeDecodeError', 'UnicodeEncodeError', 'UnicodeError', 'UnicodeTranslateError', 'UnicodeWarning', 'UserWarning', 'ValueError', 'Warning', 'WindowsError', 'ZeroDivisionError', '__IPYTHON__', '__build_class__', '__debug__', '__doc__', '__import__', '__loader__', '__name__', '__package__', '__spec__', 'abs', 'all', 'any', 'ascii', 'bin', 'bool', 'breakpoint', 'bytearray', 'bytes', 'callable', 'chr', 'classmethod', 'compile', 'complex', 'copyright', 'credits', 'delattr', 'dict', 'dir', 'display', 'divmod', 'enumerate', 'eval', 'exec', 'execfile', 'filter', 'float', 'format', 'frozenset', 'get_ipython', 'getattr', 'globals', 'hasattr', 'hash', 'help', 'hex', 'id', 'input', 'int', 'isinstance', 'issubclass', 'iter', 'len', 'license', 'list', 'locals', 'map', 'max', 'memoryview', 'min', 'next', 'object', 'oct', 'open', 'ord', 'pow', 'print', 'property', 'range', 'repr', 'reversed', 'round', 'runfile', 'set', 'setattr', 'slice', 'sorted', 'staticmethod', 'str', 'sum', 'super', 'tuple', 'type', 'vars', 'zip']
- '==' 와 is의 비교. True,False의 논리 연산 비교
In [60]:
a = 511
b = 511
a == b
Out[60]:
True
In [61]:
a is b
Out[61]:
False
In [62]:
id(a), id(b)
Out[62]:
(1977089097776, 1977089097808)
In [63]:
a = 100
b = 100
a == b
Out[63]:
True
In [64]:
a is b
Out[64]:
True
In [65]:
id(a), id(b)
Out[65]:
(140712293569296, 140712293569296)
In [66]:
a = -6
b = -6
a is b
Out[66]:
False
In [67]:
a= [1,2,3]
b= [1,2,3]
a is b
Out[67]:
False
In [68]:
a = 'abcd'
b = 'abcd'
a is b
Out[68]:
True
In [69]:
a = 511
b = a
In [70]:
a is b
Out[70]:
True
- List에 자동으로 index 부여
In [71]:
list(enumerate('abcd', start=0))
Out[71]:
[(0, 'a'), (1, 'b'), (2, 'c'), (3, 'd')]
In [72]:
enumerate('abcd', start=0)
Out[72]:
<enumerate at 0x1cc53b04ec0>
In [73]:
for i, v in enumerate('abcd'):
print(i, v)
0 a 1 b 2 c 3 d
In [74]:
for i, (v1,v2,v3) in enumerate([[1,2,3], [4,5,6]]):
print(i, v1, v2, v3)
0 1 2 3 1 4 5 6
다양한 List 생성방법¶
- map 을 이용한 숫자형 List 생성
- Lamda를 이용한 사용자 정의 List 생성
In [75]:
list(map(int, '123'))
Out[75]:
[1, 2, 3]
In [76]:
[int(i) for i in '123']
Out[76]:
[1, 2, 3]
In [77]:
list(map(lambda x: x%2==0 , [1,2,3,4,5,6]))
Out[77]:
[False, True, False, True, False, True]
In [78]:
[i%2==0 for i in [1,2,3,4,5,6]]
Out[78]:
[False, True, False, True, False, True]
In [79]:
list(filter(lambda x: x%2==0 , [1,2,3,4,5,6]))
Out[79]:
[2, 4, 6]
In [80]:
[i for i in [1,2,3,4,5,6] if i%2==0]
Out[80]:
[2, 4, 6]
In [81]:
list(map(lambda x: x-1 , [1,2,3,4,5,6]))
Out[81]:
[0, 1, 2, 3, 4, 5]
In [82]:
list(filter(lambda x: x-1 , [1,2,3,4,5,6]))
Out[82]:
[2, 3, 4, 5, 6]
Numpy 패키지의 Array¶
- Array(배열)을 생성하기 위하여 Numpy 패키지를 로딩한다.
In [83]:
import numpy as np
arr = np.array([1,2,3,4])
arr2 = arr
In [84]:
arr2 is arr
Out[84]:
True
In [85]:
arr2
Out[85]:
array([1, 2, 3, 4])
In [86]:
arr
Out[86]:
array([1, 2, 3, 4])
In [87]:
arr[0] = 1000
arr
Out[87]:
array([1000, 2, 3, 4])
In [88]:
arr2
Out[88]:
array([1000, 2, 3, 4])
In [89]:
a = 511
print(id(a))
a += 1
print(id(a))
1977089099568 1977089099856
In [90]:
a = (1,2)
a
Out[90]:
(1, 2)
In [91]:
a[0] = 10
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) ~\AppData\Local\Temp/ipykernel_2676/2539478077.py in <module> ----> 1 a[0] = 10 TypeError: 'tuple' object does not support item assignment
In [92]:
a = ([1,2],2)
a
Out[92]:
([1, 2], 2)
In [93]:
a[0][1] = 10
a
Out[93]:
([1, 10], 2)
- zip 을 이용하여 동일 index끼리 배열을 짝지을 수 있다.
In [94]:
a = list('abc')
b = list('123')
c = list('*/1')
list(zip(a,b,c))
Out[94]:
[('a', '1', '*'), ('b', '2', '/'), ('c', '3', '1')]
In [95]:
for i in zip(a,b,c):
print(i[0], i[1], i[2])
a 1 * b 2 / c 3 1
In [96]:
for i, j , k in zip(a,b,c):
print(i, j, k)
a 1 * b 2 / c 3 1
In [97]:
for i in range(len(a)):
print(a[i], b[i], c[i])
a 1 * b 2 / c 3 1
In [98]:
%%time
count = 0
for i in range(10000000):
count+=i
count
Wall time: 2.31 s
Out[98]:
49999995000000
728x90
'Study > Python' 카테고리의 다른 글
[Python] 파이썬 변수, 데이터 타입, Container (0) | 2021.12.15 |
---|---|
[Python] 파이썬 Study 기록 Day 1 (0) | 2021.12.15 |