복습 파이썬 기초 문법(1)
Date: 2023-07-04
TOPIC: 연산자, 조건문, 반복문, 자료형, 함수
기초 문법
- 파이썬
- 대소문자 구분O
- 들여쓰기 민감 (암묵적으로 tab 1=space 4)
- python 및 대부분 프로그래밍 언어는 인덱스 시작 0
- 연산자
- 몫(//)
- 나머지(%)
- 한번에 구하기( divmod (a,b) )
divmod(10,3)
#op: (3, 1)
-
- 거듭제곱(**)
- 조건문 if
a=10
if a > 1 :
print('a는 1보다 크다')
#output: a는 1보다 크다
- 반복문 for : 정확히 N번, 횟수로 반복하고 싶을 때
for a in [1,2,3] :
print(a)
'''
1
2
3
'''
- 반복문 while : 몇 번째일지는 몰라도 특정 조건을 만족할 때까지
a=0
while a < 3:
a=a+1
print(a)
'''
1
2
3
'''
- 함수
: def와 return을 통한 함수 선언
def sum(a,b):
c=a+b
return c
sum(1,2)
#op: 3
자료형
- 숫자형(int, float)
- 문자형(str)
- 참/거짓(bool)
- 리스트(list)
- 튜플(tuple)
- 딕셔너리(dict)
- 집합(set)
- 변수명 규칙
- 대체적으로 알파벳 소문자 + 숫자(혹은 언더바 _ )
- 숫자로 시작X
- 언더바 외 특수문자X
- 공백X
- 문자형(str)
#여러 줄 표현하기 (따옴표(큰 or 작은) 3개)
a="""Life is too short,
you need Python.
My life would be so long!
"""
type(a)
#op: str
#문자열 더하기
a='Python'
b=' is fun!'
a+b
#op: Python is fun!
#문자열 곱하기
a='python'
a*3
#op: pythonpythonpython
#문자열 나누기
a="Life is too short, You need Python"
split_a=a.split(' ')
print(split_a)
split_a[0]
#op: ['Life', 'is', 'too', 'short,', 'You', 'need', 'Python']
# 'Life'
- 리스트형(list)
- 대괄호 [ ]
a=[1,2,3]
print(a[0])
print(a[0]+a[1])
print(a[0:2]) # 끝자리-1
b=a,4
print(b) #([1,2,3], 4)
print(b[0][-1]) # 출력값: 3, b[0]은 [1,2,3], 그 중 [-1]이니까 3
#op:
1
3
[1, 2]
([1, 2, 3], 4)
3
#리스트 더하기
a=[1,2,3]
b=['d','e','f']
a+b
#op: [1,2,3,'d','e','f']
#리스트 곱하기
a=[1,2,3]
a*3
#op: [1, 2, 3, 1, 2, 3, 1, 2, 3]
#리스트 값 변경
a=[1,2,3]
a[0]=4
a
#op: [4, 2, 3]
#리스트 요소 추가
a=[1,2,3]
a.append(4)
a
#op: [1, 2, 3, 4]
#리스트 요소 제거
a=[1,2,3]
a.remove(3)
a
#op: [1, 2]
#리스트 요소 추가
a=[1,2,3]
a.insert(1,4) #insert(index, element)
a
#op: [1, 4, 2, 3] # index 1 자리에 '4' 삽입
#리스트 정렬
a.sort()
a
#op: [1, 2, 3, 4]
a.sort(reverse=True)
a
#op: [4, 3, 2, 1]
#리스트 위치 반환
a=[12,45,38]
a.index(38)
#op: 2
#리스트 개수 세기
a=[10,10,20,30]
a.count(10)
#op: 2
#리스트 길이 파악
a=[1,2,3,4]
len(a) #length
#op: 4
- 튜플형(tuple)
- 리스트형과 거의 비슷하지만 변수를 읽기 전용으로 만들 때 사용
- 튜플 값은 삭제, 수정 불가능 (append, remove 등 사용 시 에러)
- 괄호 ( ) 사용
- 딕셔너리형(dict)
- 키(key): 값(value) → 사전(dictionary) 형태의 자료형
- 리스트나 튜플과 다르게 순서 없음
- 값을 찾을 때 매우 빠르게O
- 모든 자료형 담을 수 있음
- 중괄호 { }
a={'bulldog':'dog','munchikin':'cat'}
#키 검색
a.keys()
#op: dict_keys(['bulldog', 'munchikin'])
#값 검색
a['bulldog']
#op: dog
#값 추가
a['poodle']='dog'
a
#op: {'bulldog': 'dog', 'munchikin': 'cat', 'poodle': 'dog'}
#값 변경
a['bulldog']='cat'
a
#op: {'bulldog': 'cat', 'munchikin': 'cat', 'poodle': 'dog'}
#요소 삭제
del a['bulldog']
a
#op: {'munchikin': 'cat', 'poodle': 'dog'}
#모두 삭제
a.clear()
a
#op: {}
- 집합형(set)
- 순서가 없고, 중복 허용X
- 묶고 싶은 요소들을 { } (중괄호)로 감싸주어 사용
- 집합명 = {요소1, 요소2, 요소3, ... }
a={1,2,3,}
type(a)
#op: set
#중복 허용X
a={1,1,2,3}
a
#op: {1,2,3}
#순서 없고 중복 허용X
b={'H','E','L','L','O'}
b
#op: {'E','H','L','O'}
#교집합 &
a={1,2,3,4}
b={4,5,6,7}
a&b
#op: {4}
#합집합 |
a={1,2,3,4}
b={4,5,6,7}
a|b
#op: {1, 2, 3, 4, 5, 6, 7}
#차집합 -
a={1,2,3,4}
b={4,5,6,7}
a-b
#op: {1, 2, 3}
#다른 자료형으로 변환
a={1,2,3,4,5}
print(type(a))
a=list(a)
print(type(a))
#op:<class 'set'>
# <class 'list'>
연산자
- (일반적으로) 비교 연산자를 기준으로 참/거짓 판단
- 조건문 안에 있는 동작문을 순차적 실행
- 비교 연산자 : 값끼리 비교 ( >, <, >=, <=, ==(같다), !=(같지 않다) )
- 논리 연산자 : 논리 연산을 이용한 참/거짓 판정 ( and, or, not )
- A and B : A와 B가 모두 참이다.
- A or B : A와 B 중 적어도 하나는 참이다.
- not A : A가 거짓일 때 참이다.
- in, not in :
in 연산자 | not in 연산자 |
A in list | A not in list |
A in tuple | A not in tuple |
A in str | A not in str |
a=[1,2,3]
1 in a
#op: True
b='python'
'z' in b
#op: False
조건문
- if, else문
- ex1)
"잠이 오면 커피를 마시고, 그렇지 않으면 차를 마셔라"
조건문 if : 잠이 오면 동작문A : 커피를 마시고 (True) 동작문B : 차를 마셔라 (False)
#코드를 입력
sleepy=True
if sleepy == True:
print("drink coffee") #동작문A
else:
print("drink tea") #동작문B
#op: drink coffee (졸린 코드를 입력했으므로. False를 입력하면 else구문(drink tea)이 출력된다.)
- elif문 (else if) : 여러 개의 조건
- ex2) "잠이 오면 커피를 마시고, 잠이 오진 않지만 화가 나면 차를 마시고, 잠도 안오고 화도 안나면 물을 마셔라"
- 잠O (True) → 커피
- 잠X / 화O (else if) → 차
- 잠X / 화X (False) → 물
status = ['happy', 'angry', 'sleepy']
if 'sleepy' in status:
print("drink coffee") #동작문A
elif 'angry' in status:
print("drink tea") #동작문B
else:
print("drink water") #동작문C
- elif는 여러 개 사용 가능
hobby = ['dance']
if 'tennis' in hobby:
print("아침에 그걸 어떻게 해")
elif 'swim' in hobby:
print("점심 수영이면 하루에 몇번을 샤워해")
elif 'dance' in hobby:
print("아 배고파")
else:
print("골프는 노잼이야")
#op: 아 배고파
반복문
- 조건문이 거짓(False)일 때까지 반복을 명령하는 구문
- python에서는
- for문을 통해 변수를 받아 반복하거나
- while문을 통해 일정 조건까지 반복O
- ex1) while문 : "잠이 오지 않을 때까지 커피를 마셔라"
- 시작
- 조건식 : 잠이 오는가?
- True : print("drink coffee")
- while : 잠이 오지 않을 때까지 반복
- 잠이 깨는 시점 = 커피 10잔
- False : print("not sleepy anymore")
- True : print("drink coffee")
- 종료
sleepy=True
awake_point=10 #잠이 깨는 시점
num_coffee=0
while sleepy==True: #조건1: 잠이 오면, 아래 실행
num_coffee=num_coffee+1
print("I have drunk {} cup(s) of coffee.".format(num_coffee))
#.format: 중괄호 안의 변수의 값을 프린트하는 기능. 변수에 어떤 값이 들어있는지 보고 싶을 때 편리
if num_coffee >= awake_point: #조건2: 잠이 깨는 시점이 되면, 아래 실행
sleepy=False
print("I'm not sleepy anymore.")
- num_coffee에 0 입력 시 출력값 (10번 반복)
I have drunk 1 cup(s) of coffee.
I have drunk 2 cup(s) of coffee.
I have drunk 3 cup(s) of coffee.
I have drunk 4 cup(s) of coffee.
I have drunk 5 cup(s) of coffee.
I have drunk 6 cup(s) of coffee.
I have drunk 7 cup(s) of coffee.
I have drunk 8 cup(s) of coffee.
I have drunk 9 cup(s) of coffee.
I have drunk 10 cup(s) of coffee.
I'm not sleepy anymore.
- num_coffee에 12 입력 시 (커피를 10잔 이상 마셔(awake_point) 더이상 졸리지 않을 때)
I have drunk 13 cup(s) of coffee.
I'm not sleepy anymore.
ex2) while문 : 반복문에서 중간에 빠져나오고 싶을 때? 명령어 break
"잠이 오지 않을 때까지 커피를 마시지만, 커피가 떨어지면 멈춰라"
sleepy=True
awake_point=10 #잠이 깨는 시점
max_coffee=5
num_coffee=0
while sleepy==True: #조건1: 잠이 오면, 아래 실행
num_coffee=num_coffee+1
print("I have drunk {} cup(s) of coffee.".format(num_coffee))
if num_coffee >= awake_point: #조건2: 잠이 깨는 시점이 되면, 아래 실행
sleepy=False
print("I'm not sleepy anymore.")
if num_coffee >= max_coffee: #조건3: 커피가 떨어지면, 아래 실행
print("It's out of coffee.")
break
#break 실행으로 특정 조건 달성 시 반복문 중지
- num_coffee=0 → 커피 5잔 마시기를 반복하면 커피가 다 떨어진다(max_coffee=5)
I have drunk 1 cup(s) of coffee.
I have drunk 2 cup(s) of coffee.
I have drunk 3 cup(s) of coffee.
I have drunk 4 cup(s) of coffee.
I have drunk 5 cup(s) of coffee.
It's out of coffee.
- 무한 루프 : 조건식에 참을 넣으면 됨
#무한 루프
num_coffee=0
while True:
num_coffee=num_coffee+1
print('I have drunk {} cup(s) of coffee.'.format(num_coffee))
- for문
- python에서 가장 직관적이고 많이 쓰는 반복문
- 리스트나 튜플, 문자열의 첫 번째 요소부터 마지막 요소까지 차례로 변수를 받아서 동작문이 반복
- 기본 문법
- for 받아올 변수 in [변수1, 변수2, 변수3, ...]:
- ex1) "커피, 차, 물을 차례로 마셔라"
- 시작
- ['커피', '차', '물'] 첫 번째 요소부터 전달
- True : print("I have drunk { }.") (동작문)
- 요소가 남아 있는가? 반복(for) → 다음 요소 반복 동작
- False : 종료
drink=['coffee', 'tea', 'water']
for item in drink:
print("I have drunk {}.".format(item))
#output:
I have drunk coffee.
I have drunk tea.
I have drunk water.
- 동작문 Skip 하기 : 명령어 continue
#동작문 skip 하기
drink=['coffee', 'tea', 'water']
for item in drink:
if item=='tea':
continue
print("I have drunk {}.".format(item))
#output:
I have drunk coffee.
I have drunk water.
(두 번째 요소인 'tea'가 스킵됨)
- range 함수 사용하기
: range(N) → 0~N-1까지
#range 함수 사용하기
for I in range(10):
print("I have drunk {}.".format(I))
#op:
I have drunk 0.
I have drunk 1.
I have drunk 2.
I have drunk 3.
I have drunk 4.
I have drunk 5.
I have drunk 6.
I have drunk 7.
I have drunk 8.
I have drunk 9.
drink=['coffee', 'tea', 'water']
for I in range(len(drink)): #len(drink)는 3과 동일(요소가 3개이므로) 따라서 range(3)과 같다
item=drink[I] #drink에 인덱싱하면 item에 커피,차,물이 나옴
print("I have drunk {}".format(item))
#op:
I have drunk coffee.
I have drunk tea.
I have drunk water.
함수 (function)
- 입력값을 받아서 일정한 처리를 진행하고 출력값을 반환
- 반복되는 작업을 묶어서 재사용⭐
- 기본 문법
- def 함수명(입력인수):
return 출력인수
- def 함수명(입력인수):
#함수 정의
def sum(a,b):
return a+b
a=2
b=6
sum(a,b) #op: 8
- ex) 똑같은 구문이 반복되는 아래 코드를
#똑같은 구문이 반복
drink=['coffee', 'tea', 'water']
for item in drink:
print('I have drunk {}.'.format(item))
drink=['coke', 'soda', 'milk']
for item in drink:
print('I have drunk {}.'.format(item))
''' op:
I have drunk coffee.
I have drunk tea.
I have drunk water.
I have drunk coke.
I have drunk soda.
I have drunk milk.
'''
아래와 같이 함수를 정의해서 단 두 줄의 코드로( drink_beverage( ) ) 간결하게 작성할 수 있다. (출력값은 동일)
def drink_beverage(drink):
for item in drink:
print("I have drunk {}.".format(item))
drink_beverage(['coffee','tea','water'])
drink_beverage(['coke','soda','milk'])
''' op:
I have drunk coffee.
I have drunk tea.
I have drunk water.
I have drunk coke.
I have drunk soda.
I have drunk milk.
'''
- 출력값 활용하기
- ex) 출력값이 하나일 경우
def drink_beverage(drink):
for item in drink:
print('I have drunk {}'.format(item))
return len(drink) #len(drink)를 출력값으로 받음
num_drink=drink_beverage(['coffee','tea','water'])
print('I drank a total of {} cups.'.format(num_drink)) #return값을 받아서 num_drink에 3이 들어간 것
''' op:
I have drunk coffee
I have drunk tea
I have drunk water
I drank a total of 3 cups. #출력값1
'''
#출력값이 여러 개일 때
def drink_beverage(drink):
for item in drink:
print('I have drunk {}'.format(item))
return len(drink), drink[-1] #두 개의 변수, 두 개의 함수
num_drink,last_drink=drink_beverage(['coffee','tea','water']) #리턴값이 두 개, 따라서 출력값도 두 개
print('I drank a total of {} cups.'.format(num_drink))
print('I drank {} last.'.format(last_drink))
''' op:
I have drunk coffee
I have drunk tea
I have drunk water
I drank a total of 3 cups. #출력값1
I drank water last. #출력값2
'''
- 다중 입력값 사용하기
- ex)
def drink_beverage(drink1, drink2, drink3): #입력값이 3개
drink=[drink1, drink2, drink3]
for item in drink:
print('I have drunk {}.'.format(item))
drink1='coffee' #3개의 변수에 각각 요소를 할당
drink2='tea'
drink3='water'
drink_beverage(drink1, drink2, drink3) #출력 시 각 3개의 출력값이 나옴
''' op:
I have drunk coffee.
I have drunk tea.
I have drunk water.
'''
- 함수를 쓸 땐 꼭 함수를 먼저 정의해준 뒤 코드를 실행할 것. (에러남)
- 코드는 무조건 직접 스스로 작성해보기. (언어는 문법)
- 구조를 이해하기.
- 문제 많이 풀어보기.
- 기본적인 특징은 빨리 외우기
- 리스트 [ ], 튜플 ( ), 딕셔너리 { }, 집합 { }, 인덱스 시작0