snake case : fast_campus : 변수, 함수 _ camel case : FastCampus, fastCampus : 클래스
4. 데이터 다입
RAM 저장공간을 효율적으로 사용하기 위해 저장공간의 타입을 설정
동적타이핑
변수 선언시 저장되는 값에 따라서 자동으로 데이터 타입이 설정
기본 데이터 타입 : int, float, bool, str
컬렉션 데이터 타입 : list, tuple, dict
1 2 3 4
a = 1 # int a = 1 b = "python" type(a), type(b)
(int, str)
1 2 3 4 5 6
# 기본 데이터 타입 : int, float, bool, str a = 1 b = 1.2 c = True d = "data" type(a),type(b),type(c),type(d)
(int, float, bool, str)
1
a + b
2.2
1
a + d
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-22-4fbab87c839c> in <module>
----> 1 a + d
TypeError: unsupported operand type(s) for +: 'int' and 'str'
1 2 3
# 데이터 타입에 함수 : 문자열 # upper : 대문자로 변환 e = d.upper()
# string 데이터 타입의 format 함수 print("현재 잔액은 {}원, 인출금액은 {}원 입니다.".format(account, draw_money)) print("현재 잔액은 {data1}원, 인출금액은 {data2}원 입니다.".format(data2 = draw_money, data1 = account))
현재 잔액은 5000원, 인출금액은 5000원 입니다.
현재 잔액은 5000원, 인출금액은 5000원 입니다.
1
f'현재 {account}'
'현재 5000'
삼항연산자
간단한 if, else 구문을 한줄의 코드로 표현할 수 있는 방법
(True) if (condition) else (False)
1 2 3 4 5 6
# data 변수에 0이면 "zero" 출력, 아니면 "not zero" 출력 data = 0 if data: print("not zero") else: print("zero")
zero
1 2 3
data = 1 result = "not zero"if data else"zero" result
'not zero'
2. 반복문
반복되는 코드를 실행할 때 사용
while, for, break, continue
list comprehention
1 2 3 4 5 6
# while data = 3 while data:# 조건이 False가 될때까지 구문의 코드를 실행 # 반복되는 코드 print(data) data -= 1
3
2
1
1 2 3 4 5 6 7 8
# 무한루프 # break : 반복문을 중단 시킬때 사용되는 예약어 result = 1 while result: if result >= 10: break result += 1 print(result)
10
for
iterable한 값을 하나씩 꺼내서 value에 대입시킨 후 코드를 iterable 변수의 값 갯수 만큼 실행
1 2
for <variable> in <iterables>: <code>
1 2 3 4 5 6 7
# for : continue : 조건부분으로 올라가서 코드가 실행 ls = [0, 1, 2, 3, 4] for data in ls: # data가 홀수면 continue 실행 if data % 2: continue # data가 짝수면 print 실행 print(data, end=" ")
0 2 4
1 2 3 4 5 6 7
# for문을 이용하여 코드를 100번 실행 # range 함수 list(range(100)) result = 0 for data inrange(100): result += data result
4950
1 2
# offset index 개념과 비슷하게 사용 list(range(5)), list(range(5, 10)), list(range(0, 10, 2)), list(range(10, 0, -2))
defecho(msg): """ echo return its input agument The operation is: 1. print msg 2. return msg parameter param : msg : str return str """ return msg
1
echo?
1
echo??
1
help(echo)
Help on function echo in module __main__:
echo(msg)
echo return its input agument
The operation is:
1. print msg
2. return msg parameter
param : msg : str
return str
1
print(echo.__doc__)
echo return its input agument
The operation is:
1. print msg
2. return msg parameter
param : msg : str
return str
# global gv = 10 defecho(): global gv gv = 100 print(gv) echo() gv # 100
100
100
3. Inner Function
함수가 지역영역에 선언, 함수 안에 함수가 선언
1 2 3 4 5 6
defouter(a, b): definner(c, d): return c + d return inner(a, b)
1
outer(1,2)
3
1
inner(2, 3)
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
<ipython-input-14-468e0d571ba5> in <module>
----> 1 inner(2, 3)
NameError: name 'inner' is not defined
1 2 3 4 5 6
defouter(a, b): definner(c, d): return c + d return inner
1
outer(1,2)(3, 4)
7
1
# callback function : 함수를 아규먼트 파라미터로 설정해서 사용
1 2 3 4 5
defcalc(func, a, b): # code a **= 2 b **= 2 return func(a, b)
# user data를 입력 받아서 아이디와 패스워드를 체크하는 데코레이터 함수를 코드로 작성하세요. # 로그인 될때마다 count를 1씩 증가 defneed_login(func): defwrapper(*args, **kwargs): # 아이디 패스워드 입력 user, pw = tuple(input("insert user pw :").split(" ")) # 존재하는 아이디, 패스워드 확인 # for idx, user_data in zip(range(len(user_datas)), user_datas): for idx, user_data inenumerate(user_datas): if user_data["user"] == user and user_data["pw"] == pw: # count 데이터 추가 user_datas[idx]["count"] += 1 # 함수 실행 return func(*args, **kwargs) return"wrong login data!" # 카운트 증가 및 함수 실행 return wrapper
Once deleted, variables cannot be recovered. Proceed (y/[n])? y
1
%whos
Interactive namespace is empty.
1 2
# 모듈 호출 : import import dss
1
%whos
Variable Type Data/Info
------------------------------
dss module <module 'dss' from 'C:\\Code\\01_python\\dss.py'>
1
dss.num
1234
1
dss.disp1("python")
disp1 python
1
calc = dss.Calc()
1
calc.plus(1,2,3,4)
10
1
import random
1
random.randint(1, 5)
1
1
# 모듈 안에 특정 함수, 변수, 클래스 호출
1
from dss import num, disp2
1
%whos
Variable Type Data/Info
--------------------------------
calc Calc <dss.Calc object at 0x0000026C12554340>
disp2 function <function disp2 at 0x0000026C12626670>
dss module <module 'dss' from 'C:\\Code\\01_python\\dss.py'>
num int 1234
random module <module 'random' from 'C:<...>aconda3\\lib\\random.py'>
1
dss.num
1234
1
num
1234
1
%reset
Once deleted, variables cannot be recovered. Proceed (y/[n])? y
1
from dss import *
1
%whos
Variable Type Data/Info
--------------------------------
Calc type <class 'dss.Calc'>
disp1 function <function disp1 at 0x0000026C12626940>
disp2 function <function disp2 at 0x0000026C12626670>
num int 1234
grep: #: No such file or directory
grep: dss媛�: No such file or directory
grep: �뱾�뼱媛�: No such file or directory
grep: �뙣�궎吏�: No such file or directory
grep: �솗�씤: No such file or directory
ERROR: Pipe to stdout was broken
Exception ignored in: <_io.TextIOWrapper name='<stdout>' mode='w' encoding='cp949'>
OSError: [Errno 22] Invalid argument
1 2 3 4 5
# 패키지 설치 # school $ python setup.py develop # 커널 리스타트 # develop : 개발자모드, 코드를 수정하면 설치된 패키지도 같이 수정 # build : 일반모드, 코드를 수정하면 다시 설치해야 수정된 코드가 적용
1
!pip list | grep dss
1
!pip list | grep numpy
numpy 1.19.2
numpydoc 1.1.0
1
from dss import *
1
%whos
Variable Type Data/Info
------------------------------
dss module <module 'school.dss.data1<...>\\school\\dss\\data1.py'>
np module <module 'numpy' from 'C:\<...>ges\\numpy\\__init__.py'>
packages SList ['__future__.py', '__phel<...>file.py', 'zipimport.py']
path str C:\Users\USER\.ipython
random module <module 'random' from 'C:<...>aconda3\\lib\\random.py'>
school module <module 'school' (namespace)>
sys module <module 'sys' (built-in)>
url module <module 'school.web.url' <...>on\\school\\web\\url.py'>
1
data1.plus(1,2)
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
<ipython-input-64-572e254ac59d> in <module>
----> 1 data1.plus(1,2)
NameError: name 'data1' is not defined
# try, except : 에러가 발생해도 코드의 실행을 계속하고 싶을때 ls = [1, 2, 3]
1 2
print(ls[3]) print("Done!")
---------------------------------------------------------------------------
IndexError Traceback (most recent call last)
<ipython-input-4-f88f334466aa> in <module>
----> 1 print(ls[3])
2 print("Done!")
IndexError: list index out of range
1 2 3 4 5 6
try: print(ls[3]) except Exception as e: print("error") print(e) print("Done")
error
list index out of range
Done
1 2 3 4 5 6 7
# finally : try, except 구문 실행된 후 finally 구문이 실행 try: 1/0 except: print("error") finally: print("Done!")
error
Done!
1
# raise : 강제로 에러를 발생시키는 명령
1 2 3 4 5 6 7
try: 1/0 except Exception as e: print("error") raise(e)
print("Done!")
error
---------------------------------------------------------------------------
ZeroDivisionError Traceback (most recent call last)
<ipython-input-9-bcde7d6d4636> in <module>
3 except Exception as e:
4 print("error")
----> 5 raise(e)
6
7 print("Done!")
<ipython-input-9-bcde7d6d4636> in <module>
1 try:
----> 2 1/0
3 except Exception as e:
4 print("error")
5 raise(e)
ZeroDivisionError: division by zero
1 2
# 에러 생성 : 10이상의 숫자가 입력되도록 하는 에러 # LowNumber
1 2 3 4
classLowNumber(Exception): def__str__(self): return"Number grater than 10"
1 2 3 4
definput_number(num): if num <= 10: raise LowNumber() print(num)
1
input_number(8)
---------------------------------------------------------------------------
LowNumber Traceback (most recent call last)
<ipython-input-15-8684a0e33c0b> in <module>
----> 1 input_number(8)
<ipython-input-13-2dcc4faaa999> in input_number(num)
1 def input_number(num):
2 if num <= 10:
----> 3 raise LowNumber()
4 print(num)
LowNumber: Number grater than 10