
보통 맥에는 python 2.x버전이 자동으로 설치되어 있지만 강의는 python3을 기준으로 작성되었기 때문에 별도로 python3을 설치해야 됩니다.
터미널을 치고, 엔터를 눌러서 터미널실행
print("Hello!")
터미널python test.py가 아니라 python3 test.py와 같이 꼭 3을 붙여서 파이썬 버전을 명시해주시기 바랍니다.(모든 파이썬 강의에서 python3 으로 실행)print('hello, world')identity = '지구인'identity = '지구인'이라고 변수를 선언하고 나면, 변수의 이름을 가지고 그 값을 불러와서 사용할 수 있다.print('안녕 나는','지구인','이야')print('안녕 나는',identity,'이야')identity = '외계인'이라고 쓰면 이후부터 identity라는 변수의 값은 '외계인'이라는 값을 가지게 된다.
#정체와 다리의 수를 출력하는 코드입니다.
identity = '지구인' #정체1
number_of_legs #다리의 수
print('안녕!')
#이 아래 줄은 주석처리 되었기 때문에 실행되지 않습니다.
#print('너는 누구니?')
"""
여러줄을
한 번에
주석처리할때는 이렇게 따옴표 3개로
내용을 감싸주세요.
"""
my_age = 25my_next_age = my_age + 1multiply = 9 * 9divide = 30 / 5power = 2 ** 10remainder = 15 % 4my_name = 'Python'text = '2015' + '1991'하고 나면 text에는 '20151991'이라는 값이 저장<폴더명>: 다른 폴더로 이동.. : 상위 폴더로 이동 if people > apple:
print('사람이 너무 많아! 몇 명은 못먹겠네')
구조
people > apple와 같이 참/거짓을 판단할 수 있는 조건print('사람이 너무 많아! 몇 명은 못먹겠네')and연산
or
not
예. a는 20대이다.
20 <= a and a < 30
예시. a는 18세 미만 또는 60세 이상이다.
a < 18 or 60 <= a
if mine == yours:
result = DRAW
else:
result = '이기거나 지거나'
if mine == SCISSOR:
result = '가위' # 조건이 참일 때 실행
elif mine == ROCK:
result = '바위' # 다른 조건이 참일 때 실행
else:
result = '나머지' # 조건이 거짓일 때 실행
def function(): # 함수의 정의
print('안녕, 함수!')
print('첫줄 실행')
function() # 함수의 호출
print('끝줄 실행')
def print_round(number): # 함수의 정의
rounded = round(number)
print(rounded)
print_round(4.6) # 함수의 호출
print_round(2.2)
def add_10(value):
result = value + 10
return result
n = add_10(5)
print(n)
여러 값 반환
print('{} 번 손님'.format(number,greeting))print('{} 번 손님 {}'.format(number)) number = 20
welcome = '환영합니다'
base = '{} 번 손님 {}'
#아래 3개의 print는 같은 값을 출력
print(number,'번 손님',welcome)
print(base.format(number,welcome))
print('{} 번 손님 {}'.format(number,welcome))
#=>20 번 손님 환영합니다
string1 = '따옴표로 싼 문자열 안에는 큰따옴표(")를 사용할 수 있다.'
string2 = "큰따옴표로 싼 문자열 안에는 따옴표(')를 사용할 수 있다."
string3="""줄도 바꾸고
큰따옴표"와 따옴표'를 마음대로 쓸 수 있음"""
a = 5//3 #계산결과 a=1
실수를 정수로 바꾸려면 int를 이용
a=int(5.4)라고 하면 a는 5를 값으로 가지게 된다. 0.1+0.1+0.1 == 0.3 #FALSE
정수를 실수로 바꾸려면 float를 사용
a=float(5)라고 하면 a는 5.0을 값으로 가지게 된다. print('가위 바위 보 중 하나를 내주세요> ', end = ' ')
mine = input()
print('mine:', mine)
mine = input('가위 바위 보 중 하나를 내주세요> ')
print('mine:', mine)
프로그램 즉시 종료
안내
강의에서 []를 중괄호라고 말하는 부분이 있어, 정정합니다. []는 중괄호가 아니라 대괄호입니다.
list1 = [1,2,3,4,5]
값 읽어오기
list1[0]list1[1]list1[-1]list1[-2]list1[5] 또는 list1[-6]은 에러값 쓰기
list1[0]=10이라고 하면 list의 첫번째 값이 10으로 변경 list1=[1,2,3]이라고 할 때list1.append(4)list2=list1+[4] #12라는 값이 리스트에 들어있는지 확인하는 코드
n=12
if n in list1:
print('{}가 리스트에 있다.'.format(n))
del list1[10] 리스트의 10번째 값을 지워라list1.remove(40)을 하면 리스트에 40이라는 값이 있는경우 삭제 for pattern in patterns:
print (pattern)
for i in range(5):
print(i)
names = ['철수', '영희', '영수']
for i, name in enumerate(names):
print('{}번: {}'.format(i + 1, name))
math.pi
random.choice()
import math
import random
import urllib.request
### my_module.py
def random_rsp():
import random
return random.choice(['가위', '바위', '보'])
PAPER = '보'
SCISSOR = '가위'
ROCK = '바위'
---
### use_module.py
import my_module
selected = my_module.random_rsp()
print(selected)
print('가위?', my_module.SCISSOR == selected)
wintable = {
'가위' : '보',
'바위' : '가위',
'보' : '바위',
}
print(wintable['가위'])
dict['three'] = 3
dict['one'] = 11
del(dict['one'])
dict.pop('two')
for key in ages.keys(): # keys() 생략 가능
print(key)
for value in ages.values():
print(value)
for key, value in ages.items():
print('{}의 나이는 {} 입니다'.format(key, value))
| List | Dictionary | |
|---|---|---|
| 생성 | list = [ 1, 2 ,3 ] | dict = { 'one':1, 'two':2 } |
| 호출 | list[ 0 ] | dict[ 'one' ] |
| 삭제 | del( list[ 0 ] ) | del( dict[ 'one' ] ) |
| 개수 확인 | len( list ) | len( dict ) |
| 값 확인 | 2 in list | 'two' in dict.keys( ) |
| 전부 삭제 | list.clear( ) | dict.clear( ) |
| List | Dictionary | |
|---|---|---|
| 순서 | 삭제 시 순서가 바뀌기 때문에 인덱스에 대한 값이 바뀐다 | key로 값을 가져오기 때문에 삭제 여부와 상관없다 |
| 결합 | list1 + list2 | dict1.update( dict2 ) |
tuple1 = (1, 2, 3, 4)
tuple2 = 1, 2, 3, 4
mylist = [1,2,3,4]
tuple3 = tuple(mylist)
c = (3, 4)
d, e = c # c의 값을 언패킹하여 d, e에 값을 넣었다
f = d, e # 변수 d와 e를 f에 패킹
for a in enumerate(list):
print('{}번째 값: {}'.format(a[0], a[1]))
for a in enumerate(list):
print('{}번째 값: {}'.format(*a))
for a in dict.items():
print('{}의 나이는:{}'.format(a[0], a[1]))
for a in dict.items():
print('{}의 나이는:{}'.format(*a))
while selected not in ['가위', '바위', '보']:
selected = input('가위, 바위, 보 중에 선택하세요>')
try:
# 에러가 발생할 가능성이 있는 코드
except Exception: # 에러 종류
#에러가 발생 했을 경우 처리할 코드
try:
# 에러가 발생할 가능성이 있는 코드
except Exception as ex: # 에러 종류
print('에러가 발생 했습니다', ex)
# ex는 발생한 에러의 이름을 받아오는 변수
raise Exception # 에러 종류def rsp(mine,yours):
allowed = ['가위','바위','보']
if mine not in allowed:
raise ValueError
if yours not in allowed:
raise ValueError
try:
rsp('가이', '바이')
except ValueError:
print('잘못된 값을 넣었습니다.')
school = {'1반'= [172,185,198,177,165,199], '2반' = [165,177,167,180,191]}
try:
for class_number, students in school.items():
for student in students:
if student>90:
print(class_number,'반에 190넘는 학생이 있음')
raise StopIteration
except StopIteration:
print('정상종료')
list.index( value ) : 값을 이용하여 위치를 찾는 기능list.extend( [value1, value2] ) : 리스트 뒤에 값을 추가list.insert( index, value ) : 원하는 위치에 값을 추가list.sort( ) : 값을 순서대로 정렬list.reverse( ) : 값을 역순으로 정렬list = str.split( ) : 문자열에서 리스트로str.split("{자르는 기준}")" ".join( list ) : 리스트에서 문자열으로"{붙일기준}".join(list)
str = "오늘은 날씨가 흐림"
# split()을 이용해서 str을 공백으로 나눈 문자열을 words에 저장하세요
words = str.split()
# index()를 이용해서 "흐림"이 words의 몇번째에 있는지 찾고,
# position에 저장하세요.
position = words.index("흐림")
words[position] = "맑음"
# join()을 이용해서 words를 다시 문자열로 바꿔 new_str에 저장하세요.
# words를 문자열로 바꿀때는 공백 한 칸을 기준으로 붙이면 됩니다.
new_str = ' '.join(words)
print(new_str)
text = "hello world"
text = text[ 1:5 ]
list = [ 0, 1, 2, 3, 4, 5 ]
list = list[ 1:3 ]
slice를 하면 해당하는 부분의 리스트나 문자열을 새로 만들어 준다.
시작과 끝부분을 얻어 오는 방법
list[ 2: ] : 2번째부터 끝까지 반환list[ : 2 ] : 처음부터 2번째 까지 반환list[ : ] : 처음부터 끝까지 전부 반환
list(range(20)): [ 0, 1, 2, ⋯, 18, 19 ]
del list[ :5 ] : 처음부터 5번째까지 삭제list[ 1:3 ] = [ 77, 88 ]list[ 1:3 ] = [ 77, 88 ,99 ] : 더 많은 개수로 변환list[ 1:4 ] = [ 8 ] : 더 적은 개수로 변환type( a ) # type( 변수명 ) : 자료형isinstance( 42, int ) # isinstance( 값, 자료형 ) : 자료형 검사 class Human( ):
'''사람'''
person1 = Human( )
person2 = Human( )


바로 위 그림에서 Human.speak는 새로운 함수를 의미하고 = speak는 원래만들어 두었던 speak함수를 의미한다.
그리고 위 두 그림의 결과는 동일하다.
의미적으로는 첫번째 그림은 두 인간이 말을 할 수 있나? 하는 것이고, 두번째 그림은 인간이 이미 말할 수 있다는 것을 내포시켜 준 것이다.

class Human( ):
'''인간'''
def create( name, weight ): # 다음 강의에서 자세히 설명
person = Human()
person.name = name
person.weight = weight
return person
def eat( self ):
self.weight += 0.1
print("{}가 {}kg이 되었습니다".format(self.name, self.weight))
def walk( self ):
self.weight -= 0.1
print("{}가 {}kg이 되었습니다".format(self.name, self.weight))
person = Human.create("철수", 60.5)
person.eat()
__init__ : 인스턴스를 만들 때 자동으로 호출되는 함수__str__ : 인스턴스 자체를 출력 할 때의 형식을 지정해주는 함수 class Human( ):
'''인간'''
def __init__( self, name, weight ):
'''초기화 함수'''
self.name = name
self.weight = weight
def __str__( self )
'''문자열화 함수'''
return "{} ( 몸무게 {}kg )".format( self.name, self.weight )
person = Human( "사람", 60.5 ) # 초기화 함수 사용
print( person ) # 문자열화 함수 사용
class Animal( ):
def walk( self ):
print( "걷는다" )
def eat( self ):
print( "먹는다" )
class Human( Animal ):
def wave( self ):
print( "손을 흔든다" )
class Dog( Animal ):
def wag( self ):
print( "꼬리를 흔든다" )
class Animal( ):
def greet( self ):
print( "인사한다" )
class Human( Animal ):
def greet( self ):
print( "손을 흔든다" )
class Dog( Animal ):
def greet( self ):
print( "꼬리를 흔든다" )
class Animal( ):
def __init__( self, name ):
self.name = name
class Human( Animal ):
def __init__( self, name, hand ):
super().__init__( name ) # 부모클래스의 __init__ 메소드 호출
self.hand = hand
person = Human( "사람", "오른손" )
try:
sign_up( )
except BadUserName:
print( "이름으로 사용할 수 없는 입력" )
except PasswordNotMatched:
print( "입력한 패스워드 불일치")
[ i*i for i in range(1,11) ]
# [ 계산식 for문 ]
[ i*i for i in range(1,11) if i % 2 == 0 ]
# [ 계산식 for문 조건문 ]
[ ( x, y ) for x in range(15) for y in range(15) ]
# [ 계산식 for문 for문 ]
# [ 형식 for문 ]
{ "{}번".format(number):name for number, name in enumerate(students) }
{student:score for student, score in zip(students, scores)}
import datetime
start_time = datetime.datetime.now() # 현재 시간
start_time = start_time.replace(year=2017, month=2, day=1) # 시간변경
start_time = datetime.datetime(2016,3,4) # 초기 시간 설정
### datetime클래스는 (-) 연산 지원
how_long = start_time - datetime.datetime.now() # 현재시간과 시작시간 차이
how_long.days
how_long.seconds
import datetime
after_hundred = datetime.timedelta(days = 100)
before_hundred = datetime.timedelta(days = -100)
hundred_before = datetime.datetime.now() + before_hundred # 100일 이전
# hundred_before = datetime.datetime.now() - after_hundred와 동일
tomorrow = datetime.datetime.now().replace(hour=9, minute=0, second=0)
+ datetime.timedelta(days=1)