01.Python
by SANGGI JEON
Python
- Interpreter
- Object Oriented
- Dynamic Tpyed
- non-type binding
파이썬 철학
https://www.python.org/dev/peps/pep-0020/
- 아름다운게 추한 것보다 낫다. (Beautiful is better than ugly.)
- 명시적인 것이 암시적인 것 보다 낫다. (Explicit is better than implicit.)
- 단순함이 복잡함보다 낫다. (Simple is better than complex.)
- 복잡함이 난해한 것보다 낫다. (Complex is better than complicated.)
- 가독성이 중요하다. (Readability counts.)
1. Python 기본 문법
1.1 Mod 연산
- A%B => (A+B)%B
print(7%2) ## 1
print(1%5) ## 1
print(-1%5) ## 4
print(1%-5) ## -4
1.2 자료형 변환
a = 10
b = float(a)
c = str(a)
d = int(a)
type(a) ## <class 'float'>
1.3 주석
# 한줄 단위 주석
"""
여러줄 주석
"""
1.4 None
- None is for non-exist value
x = None
assert x == None # pytonic 하지 않음
assert x is None # Pythonic 함
- 파이썬이나 사용하는 false
- False, None, [], {}, “”, set(), 0, 0.0
s = "hello"
first_char = s and s[0]
s = ""
first_char = s and s[0]
1.5 조건문
# 예제 1
score = int(input("Enter your score: "))
if score >= 90:
grade = 'A'
elif score >= 80:
grade = 'B'
elif score >= 70:
grade = 'C'
elif score >= 60:
grade = 'D'
else:
grade = 'F'
print(grade)
# 예제2
a = 10
b = a * 10 if a % 2 == 0 else a + 10
print(b)
1.6 반복문
- for n in range([start,] end, [step] )
for n in [1, 2, 3, 4, 5]:
print('No.', n)
for n in range(5):
print('No.', n)
for n in range(1, 6, 2):
print('No.', n)
- 이중 for 문
for n in ['banana', 'pineapple', 'mango']:
for k in n:
print(k)
print()
- while 반복문
i = 1
while i < 10:
print(i)
i+=1
- break
for i in range(10):
if i == 5:
break
print(i)
print("End of program")
- continue
for i in range(10):
if i == 5:
continue
print(i)
print("End of program")
- for-else
- for문이 정상적으로 끝났을 때 else문 실행
for i in range(10):
if i == 5: break
print(i)
else:
print("End of program")
1.7 Function
def 함수 이름 (인자1, 인자2,....):
실행문 1
실행문 2
return 반환값 (옵션)
def shopping_cart(goods):
goods.append('coupon')
goods = [1, 2]
print("In shopping_cart:", goods)
shopping_list = ['bean', 'salt', 'beef']
shopping_cart(shopping_list)
print("Goods I bought:", shopping_list)
1.8 assert
- 가정 설정문
- 함수 값이 제대로 작동하는 지 확인
- 방어적 프로그래밍
- 에러나 가는 부분을 설정하여 출력할 수 있음
def calculate_rectangle_area(x,y):
return x * y;
assert calculate_rectangle_area(2, 3) == 6
#assert calculate_rectangle_area(2, 3) == 7
rectangle_x = 10
rectangle_y = 20
print("사각형 x의 길이", rectangle_x)
print("사각형 y의 길이", rectangle_y)
print("사각형의 넓이:", calculate_rectangle_area(rectangle_x, rectangle_y))
1.9 global
def f():
# 함수에서는 자신만의 스택을 가지고 있음
# local namespace
global s
s = "I love Doosan!"
print(s)
# global namespace
s = "I love Hanhwa!"
f()
print(s)
1.10 Format
- 문자열 출력 방식 중 하나
def print_name(my_name, your_name):
print("Hello {0}, My name is {1}".format(your_name, my_name))
print_name("Tom", "Jane")
print_name(your_name="jane", my_name="Tom")
def print_name(my_name, your_name="Jane"):
print("Hello {0}, My name is {1}".format(your_name, my_name))
print_name("Tom", "Jane")
print_name("Tom")
1.11 String Method
s = "BLACK liVES mATTER"
print(s.upper()) # 대문자
print(s.lower()) # 소문자
print(s.title()) # 각 단어의 첫 문자를 대문자로 변경
print(s.capitalize()) # 첫 문자를 대문자로 변경
print(s.count("T")) # 특정 단어의 수
print(s.startswith("B")) # 특정 단어로 시작하는지 확인 (True/False)
k = "123"
print(k.isdigit()) # 숫자인지 확인 (True/False)
1.12 split
- 구분자를 기준으로 문자열을 나눠서 리스트 만들어 줌
items = 'zero on two three'.split()
print(items)
examples = 'python,javascript,sql'
print(examples.split(','))
a, b, c = examples.split(',')
print(a, b, c)
Subscribe via RSS