숫자 자료형
print(5)
문자열 자료형
print("나비")
print("나비" \* 9)
boolen 자료형
print (5>1)
print (5<1)
변수
변수 출력을 '+' 로 할경우
animal="강아지"
age=4
print("우리집 " +animal +"나이는" +str(age)+"살")
정수형 변수인경우 문자열러 감싸줘야 한다.
str(변수)
변수 출력을 ',' 로 할경우
주석
''' 주석 '''
연산자
from math import \*
from random import \*
print (random()) #0.0
~1.0 미만의 임의의 값 생성
print (random() \* 10) # 0.0~
10.0 미만의 임의의 값 생성
print ( int (random()) \* 10) # 0 ~10 미만의 임의의 값 생성
print ( int (random() \* 10) + 1) # 1 ~10 이하의 임의의 값 생성
print ( int (random() \* 45) + 1) $ 1
~45 이하의 임의의 값 생성
print ( randrange(1,46) ) # 1~
45 이하의 임의의 값 생성
print ( randint(1,45) ) # 1~45 이하의 임의의 값 생성
문자열
test='문자열'
test1="문자열"
test2="""
#문자열
"""
슬라이싱
jumin="1234-1234"
print("테스트" + jumin\[0:2\]) #처음부터 2직전까지
print("테스트" + jumin\[:2\]) #처음부터 2직전까지
print("테스트" + jumin\[2:\]) #2부터 끝까지
문자열 처리 함수
python ="Python is Amazing "
print(python.lower())
print(python.upper())
print(python\[0\].isupper())
print(len(python))
print(python.replace("Python", "java"))
index=python.index("n")
print(index)
print(python.find("n"))
print(python.count("n"))
문자열 포맷
print ("a" + "b")
print ("a","b")
#방법1
print("나는 %d 살입니다. " % 20)
print("나는 %s 을 좋아해요 " % "파이썬")
print("Apple은 %c 로 시작해요 " % "A")
print("나는 %s와 %s를 좋아해요 " % ("사과","배"))
#방법2
print("나는 {} 살입니다. " .format(20))
print("나는 {}와 {}를 좋아해요 " .format("사과","배"))
print("나는 {1}와 {0}를 좋아해요 " .format("사과","배"))
#방법3
print("나는 {age}살이며, {color}를 좋아해요 " .format(age=20,color="빨강"))
#방법4(v3.6~)
age=18
color="노랑"
print(f"나는 {age}살이며, {color}를 좋아해요 " )
#탈출문자
#\\n
print("오늘 날씨가 매우 좋다.\\n 내일 날씨도 좋을 것이다. ")
print("저는 \\"천재\\"입니다. ")
#\\r 커서를 맨 앞으로 이동
#\\b 백스페이스
#\\t 탭
리스트
#변수를 연속적으로 저장
subway=\[1,2,3\]
print(subway)
print(subway.index(2))
subway.append(5)
print(subway)
subway.insert(1, "하하")
print(subway)
# print(subway.pop())
# print(subway)
subway.append("하하")
print(subway)
print(subway.count("하하"))
정렬
.sort()
뒤집기
.reverse()
지우기 .clear()
리스트합치기
리스트1.extend(리스트2)
사전
cabinet={3:"유지석",100:"김태호"}
print(cabinet\[100\])
print(cabinet.get(3))
print(cabinet.get(5,"사용가능"))
print(3 in cabinet)
print(5 in cabinet)
cabinet={"a-3":"유지석","b-100":"김태호"}
print(cabinet\["a-3"\])
#삭제
del cabinet\["a-3"\]
#key들만 출력
print(cabinet.keys())
#value들만 출력
print(cabinet.values())
print(cabinet.items())
#삭제
cabinet.clear()
print(cabinet)
튜플
속도가 리스트 보다 빠르다.
menu=("돈까스", "치즈까스")
print(menu\[0\])
print(menu\[1\])
#값을 추가할 수 없다.
#menu.add("생선까스")
(name, age, hobby) = ("김종국",20,"코딩")
print(name, age, hobby)
세트 (set, 집합)
중복이 안되고 순서가 없다.
my\_set={1,2,3,4,4,4,}
print(my\_set)
java={"유재석","김태호","유재석"}
python = set(\["유재석","박명수"\])
#교집합(java 와 python 을 모두 할 수 있는 개발자 )
print(java & python )
print(java.intersection(python))
#합집합
print(java | python )
print(java.union(python))
#차집합
print(java - python )
print(java.difference(python))
#자료구조의 변경
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))
if
weather = "비"
if 조건:
실행 명령문
weather = input("오늘 날씨는 어때요?")
if weather == "비" or weather == "눈":
print("우산을 챙기세요")
elif weather == "미세먼지":
print("마스크를 챙겨요")
else:
print("준비물 필요 없어요")
temp= int (input("기온은 어떄요?"))
if 30 <= temp:
print("너무 더워요. 나가지 마세요")
elif 10 <= temp and temp < 30:
print ("괜찮은 날씨에요")
elif 0 <= temp and temp < 10:
print ("외투를 챙기세요 ")
else:
print ("너무 추워요. 나가지 마세요 ")
for 반복문
조건이 만족할떄까지 계속 반복한다.
for wating\_no in range(1,6) :
print ("대기번호:{0}".format(wating\_no))
starbucks = \["아이언맨","토르","아이엠 그루트"\]
for customer in starbucks :
print("{0}, 커피가 준비되었습니다. ".format(customer))
while 반복문
조건이 만족할때까지 계속 반복한다.
customer="토르"
index=5
while index >= 1:
print("{0}, 커피가 준비 되었습니다. {1} 번 남았습니다. ".format(customer, index))
index -=1
if index ==0:
print("커피는 폐기처분되었습니다." )
continue 와 break
반복문 내에서 사용한다.
continue: 조건이 맞으면 해당 조건을 skip 한다. 다음 반복문으로 이동한다.
break 반복문을 탈출 한다.
absent =\[2,5\] #결석
no\_book =\[7\]
for student in range(1,11): #1~10
if student in absent:
continue
elif student in no\_book:
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\]
print (students)
students =\[ i+100 for i in students\]
print(students)
학생 이름을 길이로 변환
students =\["Iron man","Thor","I am groot"\]
students =\[len(i) for i in students\]
print (students)
#학생 이름을 대문자로 변환
students =\["Iron man","Thor","I am groot"\]
students =\[ i.upper for i in students\]
print (students)
함수
def open\_account():
print("새로운 계좌가 생성되었습니다. ")
open\_account()
#전달값과 반환값
def deposit(balance, money):
print("입금이 완료되었습니다. 잔액은 {0} 원입니다. ".format(balance + money))
return balance + money
balance=0
balance = deposit(balance, 1000 )
기본값
값이 없을때 사용할 기본 값을 함수 정의 시 설정해 준다.
def profile (name, age=17, main\_lang="파이썬") :
print("이름: {0}\\t 나이: {1}\\t주 사용 언어: {2}" .format(name, age, main\_lang))
profile ("유재석", 20, "파이썬")
profile ("김태호", 25, "자바")
profile ("유재석")
profile ("김태호")
키워드값
함수를 호출할때 키워드의 값을 설정하면 순서가 바뀌어있어서 적용된다.
def profile (name, age, main\_lang) :
print(name, age, main\_lang)
profile (name="유재석", main\_lang="파이썬", age=20 )
가변인자
인자 값이 변경될 수 있다. (서로 다른 값의 인자를 넣어줄 때 사용할 수 있다. )
def profile(name, age, \*language ): #lang1, lang2, lang3, lang4, lang5
print ("이름: {0}\\t나이: {1}\\t" .format(name, age), end=" ")
for lang in language:
print (lang, end=" ")
print ()
profile("유재석",20, "Python","java","c","C++","C#","javascript")
profile("유재석",20, "Python")
지역번수와 전역변수
지역변수 함수호출시에만 사용할 수 있는 것.
전역변수 프로그램 어디에서나 사용할 수 있는 것.
gun=10
def checkpoint(soldiers):
global gun #전역공간에 있는 gun 사용
gun = gun - soldiers
print("\[함수 내\] 남은 총 {0}".format(gun))
print("전체 총: {0}".format(gun))
checkpoint(2)
print("전체 총: {0}".format(gun))
gun=10
def checkpoint(soldiers):
global gun #전역공간에 있는 gun 사용
gun = gun - soldiers
print("\[함수 내\] 남은 총 {0}".format(gun))
def check\_point\_ret(gun, soldiers):
gun= gun-soldiers
print("\[함수 내 \] 남은 총: {0} " .format(gun))
return gun
print("전체 총: {0}".format(gun))
# checkpoint(2)
gun = check\_point\_ret(gun,2)
print("전체 총: {0}".format(gun))
표준입출력
sep 구분자, end 문장의 끝
print("Python","Java", sep=",", end="?")
print("무엇이 더 재미있을까요?")
로그레벨 지정
import sys
print("Python","Java", file=sys.stdout)
print("Python","Java", file=sys.stderr)
정렬
scorees = {"수학":0 , "영어":40, "코딩":100}
for subject, score in scorees.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))
다양한 출력 포맷
# 빈 자리는 빈공간으로 두고, 오른쪽 정렬을 하되, 총 10자리 공간을 확보
print("{0: >10}".format(500))
# 양수일땐 + 로 표기, 음수일땐 -로 표기
print("{0: >+10}".format(500))
#왼쪽 정렬하고, 빈칸으로 \_fh codna
print("{0:\_<10}".format(500))
#3자리 마다 콤마를 찍어주기
print("{0:,}".format(100000000))
#3자리 마다 콤마를 찍어주기, +- 부호도 붙이기
print("{0:+,}".format(100000000))
print("{0:+,}".format(-100000000))
#3자리 마다 콤마를 찍어주기, +- 부호도 붙이고, 자랏수로 확보
#빈자리는 ^로 채워주기
print("{0:^<+30,}".format(100000000))
#소수점 출력
print("{0:f}" .format(5/3))
#소수점 특정 자리수 까지만 표시 (소수점 3째 자리에서 반올림)
print("{0:.2f}" .format(5/3))
파일 입출력
# w 덮어쓰기
# score\_file = open("score.txt", "w", encoding="utf8")
# print("수학: 0", file=score\_file )
# print("영어: 50", file=score\_file )
# score\_file.close()
#a append
# score\_file = open("score.txt", "a", encoding="utf8")
# score\_file.write("과학: 90 ")
# score\_file.write("\\n코딩: 90 ")
score\_file = open("score.txt", "r", encoding="utf8")
# print(score\_file.read())
# score\_file.close()
# print(score\_file.readline(), end=" ") #줄별읽기, 한줄 읽고 커서는 다음줄로 이동
# print(score\_file.readline()) #줄별읽기, 한줄 읽고 커서는 다음줄로 이동
# print(score\_file.readline()) #줄별읽기, 한줄 읽고 커서는 다음줄로 이동
# print(score\_file.readline()) #줄별읽기, 한줄 읽고 커서는 다음줄로 이동
# print(score\_file.readline()) #줄별읽기, 한줄 읽고 커서는 다음줄로 이동
반복문 이용
# while True:
# line = score\_file.readline()
# if not line:
# break
# print(line)
lines = score\_file.readlines() #list 형태로 저장
for line in lines:
print(line, end=" ")
score\_file.close()
pickie 피클
프로그램상태에서 데이터를 파일형태로 저장.
프로그램에서 데이터 가져와서 사용 가능
import pickle
profile\_file = open ("profile.pickle", "wb")
profile = {"이름":"박명수", "나이": 30, "취미":\["축구","골프","코딩"\]}
print(profile)
pickle.dump (profile, profile\_file) #profile 에 있는 정보를 file 에 저장
profile\_file.close()
#불러오
import pickle
profile\_file = open ("profile.pickle", "rb")
profile = pickle.load(profile\_file) #file 에 있는 정보를 profile 에 불러오기
print(profile)
profile\_file.close()
with
파일을 열때 close 필요가 없다.
import pickle
with open("profile.pickle", "rb") as profile\_file:
print(pickle.load(profile))
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())
클래스
클래스 는 붕어빵 틀에 비유를 많이 한다.
name="마린"
hp=40
damage=5
print("{} 유닛이 생성되었습니다. " .format(name))
print("체력 {0}, 공격력{1} \\n " .format(hp, damage))
#탱크
tank\_name="탱크"
tank\_hp=150
tank\_damage=35
print("{} 유닛이 생성되었습니다. " .format(tank\_name))
print("체력 {0}, 공격력{1} \\n " .format(tank\_hp, tank\_damage))
def attack(name, location, damage) :
print("{0} : {1} 방향으로 적군을 공격합니다. \[공격력 {2}" .format(name, location, damage))
attack(name, "1시", damage)
attack(tank\_name, "1시", tank\_damage)
클래스 사용법
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("탱크", 50, 150)
# \_\_init\_\_ : 생성자
# 객채는 클래스로부터 생성되는 것.
# 마린과 탱크는 \_\_init\_\_ 함수인스턴스이다.
# 멤버 변수 : 클래스 내에 정의된 변수
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("탱크", 50, 150)
# . 으로 클래스의 멤버 변수에 접근할 수 있다.
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))
메소드
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))
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} 방향으로 날가압니다. [threh {2}]".format(name, location, self.flying_speed))
class FlaybleAttackUnit(AttackUnit, Flyable):
def \_\_init\_\_(self, name, hp, damage, flying\_speed):
AttackUnit.\_\_init\_\_(self, name, hp, damage)
Flyable.\_\_init\_\_(self, flying\_speed)
valkyrie = FlaybleAttackUnit("발키리", 200, 6, 5)
valkyrie.fly(valkyrie.name, "3시")
pass 그냥 넘어간다.
super 상속받을시 사용
예외처리
에러가 발생할때 처리
try:
print("나누기 전용 계산기 입니다. ")
num1 = int(input("첫 번쨰 숫자를 입력하세요: "))
num2 = int(input("두 번쨰 숫자를 입력하세요: "))
print("{0} / {1} = {2}".format(num1, num2, int(num1/num2)))
except ValueError:
print("에러! 잘못된 값을 입력하였습니다.")
except ZeroDivisionError as err:
print(err)
except :
print("알 수 없는 에러가 발생하였습니다.")
에러발생시키기
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 error :
print(error)
finally:
print("감사합니다.")
#finally: 예외처리 상관없이 무조건 실행
#모듈: 필요한 것들을 묶은 파일, 확장자는 .py
import theater
theater.price(3)
theater.price\_morning(4)
theater.price\_soldier(5)
import theater as mv
mv.price\_soldier(10)
from theater import \*
price(3)
from theater import price, price\_morning
price(3)
price\_morning(5)
패키지 모듈들을 모두 모아놓은 집합
__all__ 패키지 공개여부 지정
모듈직접 실행
if __name__ == "__main__" :
#패키지 모듈 위치
import inspect
import random
print(inspect.getfile(random))
pip install
구글에서 pypi
내장함수
외장함수
'코딩생활 > Python' 카테고리의 다른 글
[파이썬] 파이썬 에러 SyntaxError: Non-ASCII character '\xeb' (0) | 2021.05.02 |
---|