자료형
print(type('a')) # str
print(type('안뇽')) #str
print(type(1)) #int
print(type(False)) #bool
print(type(3.14)) #float
# 자료구조 변경
menu = {'커피','우유','쥬스'} # 세트 중괄호
print(menu, type(menu))
menu = list(menu) # 리스트 대괄호
print(menu, type(menu))
menu = tuple(menu) # 튜플 소괄호
print(menu, type(menu))
menu = set(menu) # 세트
print(menu, type(menu))
연산자
print((1 < 2) & (2 < 3))
print(1 < 2 and 2 < 3)
print((1 > 2) | (2 < 3))
print(1 > 2 or 2 < 3)
print(1+1) #2
print(1-1) #0
print(5*2) #10
print(6/3) #2
print(2**3) #2^3
print(5%3) #나머지 2
print(10%3) #나머지 3
print(5//3) #몫 1
print(10//3) #몫 3
print(1==1) #true
print(1!=1) #false
print(not(1==1)) #false
print(5>4>3) #true
print(5>4>7) #false
수식
number = 10 + 5 + 2 # 17
number += 2 # 19
number -= 10 # 9
number *= 2 # 18
number /= 2 # 9
number **= 2 # 81
number //= 5 # 16
number %= 3 # 1
number = (number % 2 == 0) # false
함수
# 함수
print(abs(-5)) # 5
print(pow(4,2)) # 4^2
print(max(5,12)) # 12
print(min(5,12)) # 5
print(round(3.14)) # 3
print(round(4.99)) # 5
from math import *
print(floor(4.99)) # 내림 4
print(ceil(3.14)) # 올림 4
print(sqrt(16)) # 제곱근 4
# 랜덤 함수
from random import *
print(random()) # 0.0 ~ 1.0 미만의 랜덤 값
print(random() * 10)
print(int(random() * 10))
print(randrange(1,46)) # 1 ~ 46 미만의 랜덤 값
# 문자열 처리 함수
python = 'python is amazing'
print(python.upper()) # 대문자
print(python.lower()) # 소문자
print(python[0].isupper()) # index 대문자 확인
print(len(python)) # 자리수
print(python.replace('python','c#'))
index = python.index('n') # 문자 자릿수
print(index)
index = python.index('n', index +1) # 첫번째 n 다음부터
print(index)
print(python.find('java')) # find와 index의 차이는 해당 값이 없을 때, find 는 -1 반환하고 index 는 error
print(python.count('n')) # count
# 함수 생성
def openAccount():
print('새로운 계좌가 생성되었습니다.')
def deposit(balance, money): # 입금
print('입금이 완료 되었습니다. 잔액은 {0} 원 입니다.'.format(balance + money))
return balance + money
def withdraw(balance, money): # 출금
if balance > money: # 잔액이 출금보다 많으면
print('출금이 완료되었습니다. 잔액은 {0} 원 입니다.'.format(balance-money))
return balance - money
else:
print('출금이 완료되지 않았습니다. 잔액은 {0} 원 입니다.' .format(balance))
return balance
def withdrawNight(balance, money):
commission = 100
return commission, balance - money - commission
balance = 0
balance = deposit(balance, 1000)
balance = withdraw(balance, 2000)
commission, balance = withdrawNight(balance, 500)
print('수수료 {0} 원이며, 잔액은 {1} 원 입니다.'.format(commission, balance))
# 기본값
def profile(name, age, Language):
print('이름 : {0} \t 나이 : {1} \t 사용 언어 : {2}'.format(name, age, Language))
profile('유재석', 20, '파이썬')
profile('김태호', 25, '자바')
def profile(name, age=17, Language='파이썬'):
print('이름 : {0} \t 나이 : {1} \t 사용 언어 : {2}'.format(name, age, Language))
profile('유재석')
profile('김태호')
# 키워드 값
def profile(name, age, language):
print(name, age, language)
profile(name='유재석', language='파이썬', age=20)
profile(language='자바', age=25, name='김태호')
# 가변인자
def profile(name, age, lang1, lang2, lang3, lang4, lang5):
print('이름 : {0} \t 나이 : {1} \t'.format(name, age), end="") # end 줄바꿈
print(lang1, lang2, lang3, lang4, lang5)
profile('유재석', 20, '파이썬', 'java', 'c', 'c++', 'c#')
profile('김태호', 25, 'kotlin', 'swift', '', '', '')
def profile(name, age, *laguage):
print('이름 : {0} \t 나이 : {1} \t'.format(name, age), end=" ") # end 줄바꿈
for lang in laguage:
print(lang, end=" ")
print()
profile('유재석', 20, '파이썬', 'java', 'c', 'c++', 'c#', 'javascript')
profile('김태호', 25, 'kotlin', 'swift', '', '', '')
슬라이싱
# 슬라이싱
jumin = '930107-1234567'
print('성별 : ' + jumin[7])
print('연 : ' + jumin[0:2]) # 0 ~ 2 직전까지
print('월 : ' + jumin[2:4])
print('일 : ' + jumin[4:6])
print('생년월일 : ' + jumin[:6]) # 처음부터 6 직전까지
print('뒤 7자리 : ' + jumin[7:]) # 7부터 끝까지
print('뒤 7자리 (뒤에서부터) : ' + jumin[-7:])
문자열 포멧
# 문자열 포멧
print('나는 %d살 입니다.' % 33) # %d == 정수
print('나는 %s를 좋아해요.' % '파이썬') # %s == 문자열
print('apple은 %c로 시작해요.' % 'a') # %c == 문자
print('나는 %s색과 %s색을 좋아해요.' %('파랑','노랑'))
print('나는 {}살 입니다.' .format(33))
print('나는 {}색과 {}색을 좋아해요.' .format('파랑','노랑'))
print('나는 {1}색과 {0}색을 좋아해요.' .format('파랑','노랑'))
print('나는 {age}살이며, {color}색을 좋아해요.' .format(age = 33 , color = '파랑'))
age = 33
color = '파랑'
print(f'나는 {age}살이며, {color}색을 좋아해요.')
리스트
# 리스트
subway1 = 10
subway2 = 20
wubway3 = 30
subway = [10,20,30]
print(subway)
subway = ['유재석', '조세호', '박명수']
# 조세호가 몇 번째 칸에 있는가
print(subway.index('조세호'))
# 하하 추가
subway.append('하하')
print(subway)
# 정현돈을 유재석과 조세호 사이에
subway.insert(1, '정형돈')
print(subway)
# 뒤에서 부터 제거
print(subway.pop())
print(subway.pop())
print(subway.pop())
print(subway)
# 같은 이름이 몇명 있는지
subway.append('유재석')
print(subway.count('유재석'))
# 정렬
num_list = [5,2,1,4,3]
num_list.sort()
print(num_list)
num_list.reverse()
print(num_list)
# 모두 삭제
num_list.clear()
# 다양한 자료형 사용 가능
mix = ['조세호', 10 , False]
# 리스트 확장
num_list.extend(mix)
print(num_list)
사전
# 사전
cabinet = {3 : '유재석', 100 : '김태호'}
print(cabinet[3])
print(cabinet[100])
print(cabinet.get(3))
print(cabinet.get(5)) # none
print(cabinet.get(5), 'default') # none 대신 value 설정 가능
# print(cabinet[5]) # 오류
print(3 in cabinet) # true
print(5 in cabinet) # false
cabinet = {'a-3':'유재석', 'b-100' : '김태호'}
# new
cabinet['c-20'] = '조세호'
cabinet['a-3'] = '김종국'
print(cabinet)
# delete
del cabinet['a-3']
print(cabinet)
# key 출력
print(cabinet.keys())
# value 출력
print(cabinet.values())
# key , value 출력
print(cabinet.items())
# 초기화
cabinet.clear()
튜플
# 튜플 (변경이 불가능함)
menu = ('돈까스', '치즈까스')
print(menu[0]) # 돈까스
print(menu[1]) # 치즈까스
name, age, hobby = ('김종국',20,'운동')
print(name,age,hobby)
집합
# 집합
## 중복 X , 순서 X
sets = {1,2,3,3,3,3}
print(sets) # 1,2,3
java = {'유재석','김태호','양세형'}
python = set(['유재석','박명수'])
# 교집합
print(java & python)
print(java.intersection(python))
# 합집합
print(java | python)
print(java.union(python))
# 차집합
print(java - python)
print(java.difference(python))
# python 추가
python.add('김태호')
# java 삭제
java.remove('김태호')
예제
조건 1 : 1~20까지의 숫자로 1개는 치킨, 3개는 커피 당첨자를 구하라
조건 2 : 중복은 없다.
from random import *
users = range(1,21)
users = list(users)
print(users)
shuffle(users)
print(users)
winners = sample(users,4)
print('당첨자 발표')
print('치킨 당첨자 : {0}' .format(winners[0]))
print('커피 당첨자 : {0}' .format(winners[1:]))
조건문
weather = '비'
if weather == '비' or weather == '눈':
print('우산 챙기세요.')
elif weather == '미세먼지':
print('마스크 챙기세요.')
else :
print('그냥 나가세요.')
반복문
for waitingNumber in range(1,6): # 1,2,3,4,5
print('대기번호 : {0}' .format(waitingNumber))
startbucks = ['아이언맨','토르','그루트']
for customer in startbucks:
print('{0}, 커피가 준비되었습니다.' .format(customer))
customer = '토르'
index = 5
while index >= 1:
print('{0}, 커피가 준비 되었습니다. {1}번 남았어요.' .format(customer, index))
index -= 1
if index == 0:
print('커피가 폐기되었습니다.')
# continue
# break
absent = [2, 5] # 결석
noBook = [7] # 책을 두고옴
for student in range(1, 11):
if student in absent:
continue
elif student in noBook:
print('오늘 수업 여기까지. {0}는 교무실로 따라와'.format(student))
break
print('{0}, 책을 읽어줘'.format(student))
# 한 줄 for
# 출석번호가 1,2,3,4 앞에 100을 붙이기로 함 -> 101,102,103,104
students = [1, 2, 3, 4, 5]
students = [i + 100 for i in students]
print(students)
# 이름을 길이로 변환
students = ['유재석', 'yammy', '구루루루루']
students = [len(i) for i in students]
print(students)
# 이름을 대문자로 변환
students = ['aman', 'bman', '씨맨']
students = [i.upper() for i in students]
print(students)
전역변수, 지역변수
# 지역변수, 전역변수
gun = 10 # 전역변수
def checkpoint(soldiers): #경계 근무
global gun # 전역 공간에 있는 gun 사용
gun = gun - soldiers
print('[함수 내] 남은 총 : {0}' .format(gun))
def checkpointreturn(gun , soldiers):
gun = gun - soldiers
print('[함수 내] 남은 총 : {0}' .format(gun))
return gun
print('전체 총 : {0}' .format(gun))
checkpoint(2)
gun = checkpointreturn(gun,2)
print('남은 총 : {0}' .format(gun))
입출력
# 표준 입출력
# print('python', 'java', 'javascript', sep="," , end="?")
# print('무엇이 더 재밌을까요?')
# import sys
# print('python','java',file=sys.stdout)
# print('python','java',file=sys.stderr)
# scores = {'수학':0,'영어':50,'코딩':100}
# for subject , score in scores.items():
# # print(subject, score)
# print(subject.ljust(8), str(score).rjust(4), sep=":")
# 은행 대기순번표
# 001,002,003 ...
# for num in range(1,21):
# print('대기번호 : ' + str(num).zfill(3))
# answer = input('아무 값이나 입력하세요. : ')
# print(type(answer))
# print('입력하신 값은 {0} 입니다.' .format(answer) )
# 다양한 출력 포멧
# 빈 자리는 빈공간으로 두고, 오른쪽 정렬을 하되, 총 10자리 공간을 확보
print('{0: >10}'.format(500))
# 양수일 땐 +로 표시, 음수일 땐 -로 표시
print('{0: >+10}'.format(500))
print('{0: >+10}'.format(-500))
# 왼쪽 정렬하고, 빈칸으로 _로 채움
print('{0:_<10}'.format(500))
# 3자리 마다 콤마를 찍어주기
print('{0:,}'.format(10000000000))
# 3자리 마다 콤마르 찍어주기, +- 부호 붙히기
print('{0:+,}'.format(999999999999))
print('{0:+,}'.format(-999999999999))
# 3자리 마다 콤마를 찍어주기, 부호도 붙히고, 자릿수 확보
# 돈이 많으면 행복하니까 빈 자리는 ^ 채우기
print('{0:^<+30}'.format(555555555555))
## 소수점 출력
print('{0:f}'.format(5/3))
## 소수점 특정 자리수 까지만 표시 (소수점 3째 자리에서 반올림)
print('{0:.2f}'.format(5/3))
# 파일 입출력
scorefile = open('score.txt', 'w', encoding='utf8')
print('수학 : 0', scorefile)
print('영어 : 50', scorefile)
scorefile.close()
scorfile = open('score_txt', 'a', encoding='utf8')
scorfile.write('과학 : 80')
scorfile.write('\n코딩 : 100')
scorfile.close()
scorefile = open('score_txt', 'r', encoding='utf8')
# print(scorefile.read())
print(scorefile.readline(), end='') # 한 줄 읽고 커서는 다음 줄로 이동
print(scorefile.readline(), end='')
scorefile.close()
scorefile = open('score.txt', 'r', encoding='utf8')
while True:
line = scorefile.readline()
if not line:
break
print(line, end='')
scorefile.close()
scorefile = open('score.txt', 'r', encoding='utf8')
lines = scorefile.readline() # list 형태로 저장
for line in lines:
print(line, end='')
scorefile.close()
pickle
# pickle
import pickle
profile_file = open('profile.pickle', 'wb')
profile = {'이름': '박명수', '나이': 30, '취미': ['축구', '골프', '코딩']}
print(profile)
pickle.dump(profile, profile_file) # profile에 있는 정보를 file 에 저장
profile_file.close()
profile_file = open('profile.pickle', 'rb')
profile = pickle.load(profile_file) # file에 있는 정보를 profile에 불러오기
print(profile)
profile_file.close()
# with
import pickle
with open('profile.pickle','rb') as profile_file:
print(pickle.load(profile_file))
with open('study.txt','w',encoding='utf8') as study_file:
study_file.write('파이썬을 열심히 공부하고 있어요.')
with open('study.txt','r',encoding='utf8') as study_file:
print(study_file.read())
class
# class
class Unit:
def __init__(self, name, hp, damage):
self.name = name # 멤버 변수
self.hp = hp # 멤버 변수
self.damage = damage # 멤버 변수
print('{0} 유닛이 생성 되었습니다.'.format(self.name))
print('체력 {0}, 공격력 {1}' .format(self.hp, self.damage))
marine1 = Unit('마린', 40, 5)
marine2 = Unit('마린', 40, 5)
tank = Unit('탱크', 150, 35)
wraith1 = Unit('레이스', 80, 5)
print('유닛 이름 : {0}, 공격력 : {1}'.format(wraith1.name, wraith1.damage))
wraith2 = Unit('레이스', 80, 5)
wraith2.clocking = True # 확장 객체
if (wraith2.clocking == True):
print('{0} 는 현재 클로킹 상태 입니다'.format(wraith2.name))
method
class Unit:
def __init__(self, name, hp, damage):
self.name = name # 멤버 변수
self.hp = hp # 멤버 변수
self.damage = damage # 멤버 변수
print('{0} 유닛이 생성 되었습니다.'.format(self.name))
print('체력 {0}, 공격력 {1}' .format(self.hp, self.damage))
class AttackUnit:
def __init__(self, name, hp, damage):
self.name = name
self.hp = hp
self.damage = damage
def attack(self, location):
print('{0} : {1} 방향으로 적군을 공격 합니다. [공격력 {2}]'.format(
self.name, location, self.damage))
def damaged(self, damage):
print('{0} : {1} 데미지를 입었습니다.' .format(self.name, damage))
self.hp -= damage
print('{0} : 현재 체력은 {1} 입니다.'.format(self.name, self.hp))
if self.hp <= 0:
print('{0} : 파괴되었습니다.'.format(self.name))
firebat1 = AttackUnit('파이어뱃', 50, 16)
firebat1.attack('5시')
firebat1.damaged(25)
firebat1.damaged(25)
상속
class Unit:
def __init__(self, name, hp):
self.name = name # 멤버 변수
self.hp = hp # 멤버 변수
class AttackUnit(Unit):
def __init__(self, name, hp, damage):
Unit.__init__(self,name,hp)
self.damage = damage
def attack(self, location):
print('{0} : {1} 방향으로 적군을 공격 합니다. [공격력 {2}]'.format(
self.name, location, self.damage))
def damaged(self, damage):
print('{0} : {1} 데미지를 입었습니다.' .format(self.name, damage))
self.hp -= damage
print('{0} : 현재 체력은 {1} 입니다.'.format(self.name, self.hp))
if self.hp <= 0:
print('{0} : 파괴되었습니다.'.format(self.name))
# 다중 상속
class Flyable:
def __init__(self, flying_speed):
self.flying_speed = flying_speed
def fly(self, name, location):
print('{0} : {1} 방향으로 날아갑니다. [속도 {2}]'.format(
name, location, self.flying.speed))
class FlyableAttackUnit(AttackUnit,Flyable):
def __init__(self,name,hp,damage,flying_speed):
AttackUnit.__init__(self,name,hp,damage)
Flyable.__init__(self,flying_speed)
valkyrie = FlyableAttackUnit('발키리',200,6,5)
valkyrie.fly(valkyrie.name,'3시')
pass
class BuildingUnit(Unit):
def __init__(self, name, hp, location):
pass
supplier_depot = BuildingUnit('서플라이 디폿', 500, '7시')
def game_start():
print('[알림] 새로운 게임을 시작합니다.')
def game_over():
pass
game_start()
game_over
super
class Unit:
def __init__(self):
print('Unit 생성자')
class Flyable:
def __init__(self):
print('plyable 생성자')
class FlyableUnit(Flyable,Unit):
def __init__(self):
super().__init__()
Unit.__init__(self)
Flyable.__init__(self)
dropship = FlyableUnit()
예외처리
# 예외 처리
try:
print('나누기 전용 계산기 입니다.')
nums = []
nums.append(int(input('첫번째 숫자를 입력하시오.')))
nums.append(int(input('두번째 숫자를 입력하시오.')))
nums.append(int(nums[0] / nums[1]))
print('{0} / {1} = {2}'.format(nums[0],nums[1],nums[2]))
except ValueError:
print('에러! 잘못된 값을 입력하였습니다.')
except ZeroDivisionError as err:
print(err)
except Exception as err:
print('알 수 없는 에러가 발생하였습니다.')
print(err)
try:
print('한 자리 숫자 나누기 전용 계산기')
num1 = int(input('첫 번째 숫자를 입력'))
num2 = int(input('두 번째 숫자를 입력'))
if num1 >= 10 or num2 >= 10:
raise ValueError
print('{0} / {1} = {2}'.format(num1,num2,int(num1/num2)))
except ValueError:
print('잘못된 값을 입력')
# 사용자 정의 예외처리
class BigNumberError(Exception):
def __init__(self,msg):
self.msg = msg
def __str__(self):
return self.msg
try:
print('한 자리 숫자 나누기 전용 계산기')
num1 = int(input('첫 번째 숫자를 입력'))
num2 = int(input('두 번째 숫자를 입력'))
if num1 >= 10 or num2 >= 10:
raise BigNumberError('입력값 : {0, {1}}'.format(num1,num2))
print('{0} / {1} = {2}'.format(num1,num2,int(num1/num2)))
except ValueError:
print('잘못된 값을 입력')
except BigNumberError as err:
print('에러가 발생')
print(err)
모듈
# 일반 가격
def price(people):
print('{0}명 가격은 {1}원 입니다.'.format(people, people * 10000))
# 조조할인
def price_morning(people):
print('{0}명 조조 할인 가격은 {1}원 입니다.'.format(people, people*6000))
# 군인 할인 가격
def price_soldier(people):
print('{0}명 군인 할인 가격은 {1}원 입니다.'.format(people, people * 4000))
import helloworld
helloworld.price(3)
helloworld.price_morning(4)
helloworld.price_soldier(5)
import helloworld as mv
mv.price(1)
mv.price_morning(2)
mv.price_soldier(3)
from helloworld import *
price(3)
price_morning(4)
price_soldier(5)
from helloworld import price,price_morning
price(5)
price_morning(6)
from helloworld import price_soldier as price
price(10)