변수와 메모리
가장 기초적인 프로그래밍 문법 개념
데이터(값)을 저장하기 위한 메모리(memory) 공간의 장소
변수에는 값이 할당되고 해당 값은 메모리 주소(물리적인 공간)에 할당된다.
변수명 작명법
A = 8 # A 라는 __변수__에 8이라는 __값__을 넣어라
사용자가 컴퓨터에 값을 입력하거나 프로그램을 실행할 경우 그 정보를 먼저 메모리에 저장시키고 CPU가 순차적으로 그 정보를 해석하고 계산하여 사용자에게 결과값을 전달한다.
기초 연산자
Dynamic Typing
코드 실행시점에 데이터의 Type을 결정하는 방법
first_integer = 100
second_integer = 100
print(first_integer == second_integer)
연산자(Operator)와 피연산자(Operand)
데이터 형변환
컴퓨터와 이진수
시퀀스 자료형의 여러 데이터들 집합
int와 float 같은 다양한 데이터 타입을 포함한다.
List의 특징
인덱싱 (Indexing)
list에 있는 값들은 주소(offset)를 가지고, 주소를 사용해 할당된 값을 호출한다.
슬라이싱 (Slicing)
list의 값들을 잘라서 쓰는 것을 슬라이싱이라 하고, 주소 값을 기반으로 부분 값을 반환한다.
연산
concatenation, is_in, append, extend, insert, remove, del 등이 있다.
color = ['red', 'blue', 'green']
color2 = ['orange', 'black', 'white']
print (color + color2) # 두 리스트 합치기
len(color) # 리스트 길이
color[0] = 'yellow' # 0번째 리스트의 값을 변경
print (color * 2) # color 리스트 2회 반복
'blue' in color2 # 문자열 ‘blue‘가 color2 존재 여부 반환
total_color = color + color2
color.append("white") # 리스트에 “white” 추가
color.extend(["black","purple"]) # 리스트에 새로운 리스트 추가
color.insert(0,"orange") # 0번째 주소에 “orange” 추가
print (color)
# ['orange', 'yellow', 'blue', 'green', 'white', 'black', 'purple']
color.remove("white") # 리스트에 “white” 삭제
del color[0] # 0번째 주소 리스트 객체 삭제
print (color)
# ['yellow', 'blue', 'green', 'black', 'purple']
a = ["color", 1, 0.2]
color = ['yellow', 'blue', 'green', 'black', 'purple']
a[0] = color # 리스트 안에 리스트도 입력 가능
print (a)
# [['yellow', 'blue', 'green', 'black', 'purple'], 1, 0.2]
메모리 저장 방식
파이썬은 해당 List 변수에 List의 주소값이 저장된다.
a = [5, 4, 3, 2, 1]
b = [1, 2, 3, 4, 5]
b = a
print (b)
# [5, 4, 3, 2, 1]
a.sort()
print (b)
# [1, 2, 3, 4, 5]
b = [6,7,8,9,10]
print (a, b)
# [1, 2, 3, 4, 5] [6, 7, 8, 9, 10]
패킹과 언패킹
t = [1, 2, 3] # 1,2,3을 변수 t에 패킹
a , b , c = t # t에 있는 값 1, 2, 3 을 변수 a, b, c에 언패킹
print(t, a, b, c) # [1, 2, 3] 1 2 3
이차원 List
List 안에 List를 만들어 행렬(Matrix)을 생성한다.
kor_score = [49,79,20,100,80]
math_score = [43,59,85,30, 90]
eng_score = [49,79,48,60,100]
midterm_score = [kor_score, math_score, eng_score]
print (midterm_score[0][2])
# 20
어떤 일을 수행하는 코드의 덩어리
def 함수 이름 (parmaeter #1,…,):
수행문 #1(statements)
수행문 #2(statements)
return <반환값>
# 사각형의 넓이를 구하는 함수
def calculate_rectangle_area (x , y):
return x * y # 가로, 세로를 곱해서 반환
rectangle_x = 10
rectangle_y = 20
print ("사각형 x의 길이: ", rectangle_x)
print ("사각형 y의 길이: ", rectangle_y)
# 넓이를 구하는 함수 호출
print ("사각형의 넓이: ", calculate_rectangle_area(rectangle_x, rectangle_y))
def f(x): # f(x) 함수 선언
return 2 * x + 7
def g(x): # g(x) 함수 선언
return x ** 2
x = 2
print (f(x) + g(x) + f(g(x)) + g(f(x)))
Parameter
함수의 입력값
Argument
실제 Parameter에 대입된 값
Parameter 유무, 반환 값(return value) 유무에 따라 함수의 형태가 다르다.
- | Parameter 없음 | Parameter 존재 |
---|---|---|
반환 값 없음 | 함수 내의 수행문만 수행 | Parameter를 사용, 수행문만 수행 |
반환 값 존재 | Parameter 없이 수행문 수행 후 결과값 반환 | Parameter를 사용하여 수행문 수행 후 결과 값 반환 |
Conesole 창 입출력
print ("Enter your name:")
somebody = input() # 콘솔창에서 입력한 값을 somebody에 저장
print ("Hi", somebody, "How are you today?")
형식(format)에 맞춰서 출력
print(1,2,3)
print("a" + " " + "b" + " " + "c")
print("%d %d %d" % (1,2,3))
print("{} {} {}".format("a","b","c"))
print(f"value is {value}
%datatype %(variable)
Type | 설명 |
---|---|
%s | 문자열 (string) |
%c | 문자 1개 (character) |
%d | 정수 (intger) |
%f | 부동소수 (floating point) |
%o | 8진수 |
%x | 16진수 |
%% | Literal % (문자 % 자체) |
print("I eat %d apples." % 3)
print("I eat %s apples." % "five")
number = 3; day="three"
print("I ate %d apples. I was sick for %s days."
% (number, day))
print("Product: %s, Price per unit: %f." % ("Apple", 5.243))
age = 36; name='Sungchul Choi'
print("I’m {0} years old.".format(age))
print("My name is {0} and {1} years old.".format(name,age))
print("Product: {0}, Price per unit: {1:.3f}.".format("Apple", 5.243))
print("Product: %5s, Price per unit: %.5f." % ("Apple", 5.243))
print("Product: {0:5s}, Price per unit: {1:.5f}.".format("Apple", 5.243))
print("Product: %10s, Price per unit: %10.3f." % ("Apple", 5.243))
print("Product: {0:>10s}, Price per unit: {1:10.3f}.".format("Apple", 5.243))
Naming
표시할 내용을 변수로 입력하여 표시한다.
print("Product: %(name)10s, Price per unit: %(price)10.5f." %
{"name":"Apple", "price":5.243})
print("Product: {name:>10s}, Price per unit: {price:10.5f}.".format(name="Apple", price=5.243))
fstring
python 3.6 이후, PEP498에 근거한 formatting 기법
name = "Sungchul"
age = 39
print(f"Hello, {name}. You are {age}.")
print(f'{name:20}')
print(f'{name:>20}')
print(f'{name:*<20}')
print(f'{name:*>20}')
print(f'{name:*^20}')
number = 3.141592653589793
print(f'{number:.2f}')
조건에 따라 특정한 동작시키는 명령어
가장 기본적인 조건문으로 조건에 따른 명령을 실행
조건 판단 방법
if 다음에 조건을 표기하여 참 또는 거짓을 판단한다.
참 / 거짓의 구분을 위해서 비교연산자를 활용한다.
비교연산자 | 비교상태 | 설명 |
---|---|---|
x < y | ~보다 작음 | x과 y보다 작은지 검사 |
x > y | ~ 보다 큼 | x과 y보다 큰지 검사 |
x == y | 같음 | x와 y과 같은지 검사 |
x is y | 같음 | x와 y과 같은지 검사(값과 메모리 주소) |
x != y | 같지 않음 | x와 y과 다른지 검사 |
x is not y | 같지 않음 | x와 y과 다른지 검사(값과 메모리 주소) |
x >= y | 크거나 같음 | x과 y보다 이상인지 검사 |
x <= y | 작거나 같음 | x과 y보다 이하인지 검사 |
숫자형의 경우는 수학에서의 참 / 거짓과 동일하다.
컴퓨터는 존재하면 참 없으면 거짓이라고 판단한다.
if “abc”는 참이다.
if “”는 거짓이다.
논리 키워드 사용: and, or, not
조건문을 표현할 때 집합의 논리 키워드를 함께 사용하여 참과 거짓을 판단하기도 한다.
Python은 -5 ~ 256 사이의 숫자는 고정된 특정 메모리에 저장해놓고 사용한다.
a = 8, b = 5 일 때
if a == 8 and b == 4 # 거짓
if a > 7 or b > 7 # 참
if not (a > 7) # 거짓, a>7인 것이 참 이므로 거짓으로 판단됨
a = -6
print(a is -6)
a = -5
print(a is -5)
a = 256
print(a is 256)
a = 257
print(a is 257)
조건 일치 시 수행 명령 block":" 과 들여쓰기
조건 불일치 시 수행 명령 block
if <조건>: # if를 쓰고 조건 삽입 후 “:” 입력
<수행 명령1-1> # 들여쓰기(indentation)후 수행명령 입력
<수행 명령1-2> # 같은 조건하에 실행일 경우 들여쓰기 유지
else: # 조건이 불일치할 경우 수행할 명령 block
<수행 명령2-1> # 조건 불일치 시 수행할 명령 입력
<수행 명령2-2> # 조건 불일치 시 수행할 명령 들여쓰기 유지
print ("Tell me your age?")
myage = int(input()) # 나이를 입력 받아 myage 변수에 할당
if myage < 30: # myage 가 30 미만일 때
print ("Welcome to the club")
else: # myage 가 30 이상일 때
print ("Oh! No. You are not accepted.")
삼항 연산자 (Ternary operators)
조건문을 사용하여 참일 경우와 거짓일 경우의 결과를 한 줄에 표현한다.
value = 12
is_even = True if value % 2 == 0 else False
print(is_even)
# True
if score >= 90:
grade = 'A'
if score >= 80:
grade = 'B'
if score >= 70:
grade = 'C'
if score >= 60:
grade = 'D'
if score < 60:
grade = 'F'
print grade
if문이 순차적으로 실행되면 95는 90초과이지만 동시에 60초과이기도 하므로 마지막 조건문에 따라 grade 값에 “D”가 할당된다.
위와 같은 문제를 해결 하기 위해 elif와 else구문이 사용된다.
if score >= 90: grade = 'A' # 90 이상일 경우 A
elif score >= 80: grade = 'B' # 80 이상일 경우 B
elif score >= 70: grade = 'C' # 70 이상일 경우 C
elif score >= 60: grade = 'D' # 60 이상일 경우 D
else: grade = 'F' # 모든 조건에 만족하지 못할 경우 F
정해진 동작을 반복적으로 수행하게 하는 명령문
기본적인 반복문
for looper in [1,2,3,4,5]:
print ("hello")
for looper in [1,2,3,4,5]:
print (looper)
for looper in [1,2,3,4,5]:
print ("hello")
for looper in range(0,5):
print ("hello")
for loop의 다양한 반복문 조건 표현
for i in "abcdefg":
print (i)
for i in ["americano", "latte", "frafuchino"]:
print (i)
for i in range(1, 10, 2):
# 1부터 10까지 2씩 증가시키면서 반복문 수행
print (i)
for i in range(10, 1, -1):
# 10부터 1까지 -1씩 감소시키면서 반복문 수행
print (i)
조건이 만족하는 동안 반복하는 조건문
i = 1 # i 변수에 1 할당
while i < 10: # i가 10 미만인지 판단, i가 10이 되면 반복 종료
print (i) # 조건에 만족할 때 i 출력
i += 1 # i에 1을 더함
for문은 while문으로 변환 가능하다.
# 반복 실행횟수를 명확히 알 때
for i in range(0,5):
print (i)
# 반복 실행횟수가 명확하지 않을 때
i = 0
while i < 5:
print (i)
i = i + 1
특정 조건에서 반복 종료
for i in range(10):
if i == 5: break # i가 5가 되면 반복 종료
print (i)
print (“EOP”) # 반복 종료 후 “EOP” 출력
특정 조건에서 남은 반복 명령 skip
for i in range(10):
if i == 5: continue # i가 5가 되면 i를 출력하지 않음
print (i)
print (“EOP”) # 반복 종료 후 “EOP” 출력
반복 조건이 만족하지 않을 경우 반복 종료 시 1회 수행
for i in range(10):
print (i,)
else:
print ("EOP")
i = 0
while i < 10:
print (i,)
i += 1
else:
print ("EOP")
sentence = "I love you"
reverse_sentence = ''
for char in sentence:
reverse_sentence = char + reverse_sentence
print (reverse_sentence)
decimal = 10
result = ''
while (decimal > 0):
remainder = decimal % 2
decimal = decimal // 2
result = str(remainder) + result
print (result)
Debugging Loop
Loop 내에 변수들의 값을 print문으로 확인한다.
print ("input decimal number: ",)
decimal = int(input())
result =""
loop_counter = 0
while (decimal > 0):
temp_decimal_input = decimal
temp_result_input=result
remainder = decimal % 2
decimal = decimal // 2
result = str(remainder) + result
print ("-----------", loop_counter, "loop value check -------- ")
print ("Initial decimal:", temp_decimal_input,
", Remainder:",remainder,
", Initial result", temp_result_input)
print ("Output decimal:", decimal,
"Output result:", result)
print ("------------------------------------------------------")
print ("")
loop_counter += 1
print ("Binary number is", result)
가변적인 중첩 반복문 (variable nested loops)
실제 프로그램에서 반복문은 사용자의 입력에 따라 가변적으로 반복된다.
# -*- coding: utf-8 -*-
import random # 난수 발생 함수 호출
guess_number = random.randint(1, 100) # 1~100 사이 정수 난수 발생
print ("숫자를 맞춰보세요 (1 ~ 100)")
users_input = int(input()) # 사용자 입력을 받음
while (users_input is not guess_number): # 사용자 입력과 난수가 같은지 판단
if users_input > guess_number: # 사용자 입력이 클 경우
print ("숫자가 너무 큽니다")
else: # 사용자 입력이 작은 경우
print ("숫자가 너무 작습니다")
users_input = int(input()) # 다시 사용자 입력을 받음
else: print ("정답입니다. ", "입력한 숫자는 ", users_input , "입니다") # 종료 조건
코드의 오류를 발견하여 수정하는 과정
# 들여쓰기 오류 (Indentation Error)
x = 2
y = 5 # IndentationError
print (x+y)
# 오탈자 오류
pront (x+y) # Not Print, But Pront
# 대소문자 구분 오류
Data = “Python"
print (Data) # d는 소문자
def addition(x, y):
return x + y
def multiplication(x, y):
return x * y
def divided_by_2(x):
return x / 2
# __name__ 코드 부분은 python Shell에서 호출 할 경우 실행되지 않음
if __name__ == '__main__':
print(addition(10,5))
print(multiplication(10,5))
print(divided_by_2(50))
시퀀스 자료형으로 문자형 data를 메모리에 저장
import sys # sys 모듈을 호출
print (sys.getsizeof("a"), sys.getsizeof("ab"), sys.getsizeof("abc"))
# 50 51 52 # “a”, “ab”, “abc”의 각 메모리 사이즈 출력
컴퓨터는 문자를 직접적으로 인식하지 않는다.
-> 모든 데이터는 2진수로 인식되고, 이를 위해 2진수를 문자로 변환하는 표준 규칙이 있다.
ex) 대문자 U는 이진수로 “1000011” 변환된다. (UTF-8기준)
인덱싱 (Indexing)
a = "abcde"
print (a[0], a[4]) # a 변수의 0번째, 4번째 주소에 있는 값
# a e
print (a[-1], a[-5]) # a 변수의 오른쪽에서 0번째, 4번째 주소에 있는 값
# e a
슬라이싱 (Slicing)
문자열의 주소값을 기반으로 문자열의 부분값을 반환한다.
a = "Artificial Intelligence and Machine Learning"
print (a[0:6], " AND ", a[-9:]) # a 변수의 0부터 5까지, -9부터 끝까지
# Artifi AND Learning
print (a[:]) # a변수의 처음부터 끝까지
# Artificial Intelligence and Machine Learning
print (a[-50:50]) # 범위를 넘어갈 경우 자동으로 최대 범위를 지정
# Artificial Intelligence and Machine Learning
print (a[::2], " AND ", a[::-1]) # 2칸 단위로, 역으로 슬라이싱
# Atfca nelgneadMcieLann AND gninraeL enihcaM dna ecnegilletnI laicifitrA
문자열 연산 및 포함여부 검사
덧셈과 뺄셈 연산 가능, in 명령으로 포함 여부 체크
a = “TEAM"
b = “LAB"
print (a + " " + b) # 덧셈으로 a와 b 변수 연결하기
# TEAM LAB
print (a * 2 + " " + b * 2)
# TEAMTEAM LABLAB # 곱하기로 반복 연산 가능
if 'A' in a: # ‘U‘가 a에 포함되었는지 확인
print (a)
else:
print (b)
문자열 함수
함수명 | 기능 |
---|---|
len(a) | 문자열의 문자 개수를 반환 |
a.upper() | 대문자로 변환 |
a.lower() | 소문자로 변환 |
a.capitalize() | 첫 문자를 대문자로 변환 |
a.titile() | 제목형태로 변환, 띄워쓰기 후 첫 글자만 대문자 |
a.count('abc') | 문자열 a에 'abc'가 들어간 횟수 반환 |
a.find('abc') | 문자열 a에 'abc'가 들어간 위치(오프셋) 반환 (왼쪽부터 검색) |
a.rfind('abc') | 문자열 a에 'abc'가 들어간 위치(오프셋) 반환 (오른쪽부터 검색) |
a.startswith('ab'c) | 문자열 a는 'abc'로 시작하는 문자열여부 반환 |
a.endswith('abc') | 문자열 a는 'abc'로 끝나는 문자열여부 반환 |
a.strip() | 좌우 공백을 없앰 |
a.rstrip() | 오른쪽 공백을 없앰 |
a.lstrip() | 왼쪽 공백을 없앰 |
a.split() | 공백을 기준으로 나눠 리스트로 반환 |
a.split('abc') | abc를 기준으로 나눠 리스트로 반환 |
a.isdigit() | 문자열이 숫자인지 여부 반환 |
a.islower() | 문자열이 소문자인지 여부 반환 |
a.isupper() | 문자열이 대문자인지 여부 반환 |
title = "TEAMLAB X Upstage"
title.upper()
# 'TEAMLAB X UPSTAGE'
title.lower()
# 'teamlab x upstage'
title.split(" ")
# ['TEAMLAB', 'X', 'Upstage']
title.isdigit()
# False
title.title()
# 'Teamlab X Upstage'
title.startswith("a")
# False
title.count("a")
# 1
title.upper().count("a")
# 0
"12345".isdigit()
# True
title.find(“Naver")
# 0
title.upper().find(“Naver")
# -1
" Hello ".strip()
# 'Hello'
"A-B-C-D-E-F".split("-")
# ['A', 'B', 'C', 'D', 'E', 'F']
다양한 문자열 표현
a = ‘It\’ ok.’
# \’는 문자열 구분자가 아닌 출력 문자로 처리
a = “It’s ok.” #
# 큰따옴표로 문자열 선언 후 작은 따옴표는 출력 문자로 사용
특수 문자
문자열을 표시할 때 백슬래시 “\” 를 사용하여 키보드로 표시하기 어려운 문자들을 표현한다.
문자 | 설명 | 문자 | 설명 |
---|---|---|---|
\[Enter] | 다음 줄과 연속임을 표현 | \n | 줄 바꾸기 |
\\ | \ 문자 자체 | \t | TAB 키 |
\` | ` 문자 | \e | ESC 키 |
\" | " 문자 | \b | 백 스페이스 |
raw string
특수문자 특수 기호인 \ escape 글자를 무시하고 그대로 출력한다.
raw_string = "이제 파이썬 강의 그만 만들고 싶다. \n 레알"
print(raw_string)
# 이제 파이썬 강의 그만 만들고 싶다.
# 레알
raw_string = r"이제 파이썬 강의 그만 만들고 싶다. \n 레알"
print(raw_string)
# 이제 파이썬 강의 그만 만들고 싶다. \n 레알
함수에서 parameter를 전달하는 방식
값에 의한 호출(Call by Value)
참조의 의한 호출(Call by Reference)
객체 참조에 의한 호출(Call by Object Reference)
def spam(eggs):
eggs.append(1) # 기존 객체의 주소값에 [1] 추가
eggs = [2, 3] # 새로운 객체 생성
ham = [0]
spam(ham)
print(ham) # [0, 1]
swap
함수를 통해 변수 간의 값을 교환(Swap)하는 함수
-> Call By XXXX를 설명하기 위한 전통적인 함수 예시
def swap_value (x, y):
temp = x
x = y
y = temp
def swap_offset (offset_x, offset_y): # a 리스트의 전역 변수 값을 직접 변경
temp = a[offset_x]
a[offset_x] = a[offset_y]
a[offset_y] = temp
def swap_reference (list, offset_x, offset_y): # a 리스트 객체의 주소 값을 받아 값을 변경
temp = list[offset_x]
list[offset_x] = list[offset_y]
list[offset_y] = temp
a = [1,2,3,4,5]
swap_value(a[1], a[2])
print (a) # [1,2,3,4,5]
swap_offset(1,2)
print (a) # [1,3,2,4,5]
swap_reference(a, 1, 2)
print (a) # [1,3,2,4,5]
변수가 사용되는 범위 (함수 또는 메인 프로그램)
def test(t):
print(x)
t = 20
print ("In Function :", t)
x = 10
test(x)
print(t)
def test(t):
t = 20
print ("In Function :", t)
x = 10
print ("Before :", x) # 10
test(x) # 함수 호출
print ("After :", x) # 10 – 함수 내부의 t는 새로운 주소값을 가짐
def f():
s = "I love London!"
print(s)
s = "I love Paris!"
f()
print(s)
def f():
global s
s = "I love London!"
print(s)
s = "I love Paris!"
f()
print(s)
def calculate(x, y):
total = x + y # 새로운 값이 할당되어 함수 내 total은 지역변수가 됨
print ("In Function")
print ("a:", str(a), "b:", str(b), "a+b:", str(a+b), "total :", str(total))
return total
a = 5 # a와 b는 전역변수
b = 7
total = 0 # 전역변수 total
print ("In Program - 1")
print ("a:", str(a), "b:", str(b), "a+b:", str(a+b))
sum = calculate (a,b)
print ("After Calculation")
print ("Total :", str(total), " Sum:", str(sum)) # 지역변수는 전역변수에 영향 X
자기자신을 호출하는 함수
def factorial(n):
if n == 1:
return 1
else:
return n + factorial(n-1)
print (factorial(int(input("Input Number for Factorial Calculation: "))))
함수 입력 paramter hint
def do_function(var_name: var_type) -> return_type:
pass
def type_hint_example(name: str) -> str:
return f"Hello, {name}"
함수를 설명하는 string
파이썬 함수에 대한 상세스펙을 사전에 작성하면 함수 사용자의 이행도가 올라간다.
def kos_root():
"""Return the pathname of the KOS root directory."""
global _kos_root
if _kos_root: return _kos_root
...
def print_hello_world():
print("Hello, World")
def get_hello_world():
return "Hello, World")
def add_variables(x,y):
return x + y
def add_variables(x,y):
print (x, y) # 이런 코드는 지양한다.
return x + y
# 지양하는 코드
def count_word(string_variable):
string_variable = list(string_variable)
return len(string_variable)
# 지향하는 코드
def count_word(string_variable):
return len(string_variable)
공통적으로 사용되는 코드는 함수로 변환
a = 5
if (a > 3):
print "Hello World"
print "Hello Gachon"
if (a > 4):
print "Hello World"
print "Hello Gachon"
if (a > 5):
print "Hello World"
print "Hello Gachon"
# 위 코드를 아래 코드처럼 바꾼다.
def print_hello():
print "Hello World"
print "Hello Gachon"
a = 5
if (a > 3):
helloMethod()
if (a > 4):
helloMethod()
if (a > 5):
helloMethod()
복잡한 수식 → 식별 가능한 이름의 함수로 변환
import math
a = 1; b = -2; c = 1
print ((-b + math.sqrt(b ** 2 - (4 * a * c)) ) / (2 * a))
print ((-b - math.sqrt(b ** 2 - (4 * a * c)) ) / (2 * a))
# 위 코드를 아래 코드처럼 바꾼다.
import math
def get_result_quadratic_equation(a, b, c):
values = []
values.append((-b + math.sqrt(b ** 2 - (4 * a * c)) ) / (2 * a))
values.append((-b - math.sqrt(b ** 2 - (4 * a * c)) ) / (2 * a))
return values
print (get_result_quadratic_equation(1,-2,1))
복잡한 조건 → 식별 가능한 이름의 함수로 변환
사람이 이해할 수 있는 코드
이해를 돕기 위한 규칙(코딩 컨벤션)이 필요하다.
코딩 컨벤션
명확한 규칙은 없다.
때로는 팀마다, 프로젝트마다 따로
중요한 건 일관성
읽기 좋은 코드가 좋은 코드
일반적으로 들여쓰기는 Tab 보다는 4 Space를 권장한다. (혼합하지 말아야 한다.)
한 줄은 최대 79자까지
불필요한 공백은 피한다.
def factorial( n ):
if n == 1:
return 1
= 연산자는 1칸 이상 안 띄운다.
주석은 항상 갱신, 불필요한 주석은 삭제
코드의 마지막에는 항상 한 줄 추가
소문자 l, 대문자 O, 대문자 I 금지
함수명은 소문자로 구성하고 필요하면 밑줄로 나눈다.
"flake8" 모듈로 체크 – flake8 <파일명>
-> conda install -c anaconda flake8
lL0O = "123"
for i in 10 :
print ("Hello")
flake8 flake8_test.py
flake8_test.py:2:12: E203 whitespace before ':'
flake8_test.py:3:10: E211 whitespace before '('