본문 바로가기
728x90
반응형

Programming/Python16

[Python] 파이썬 예외처리 # 예외처리# 프로그램 실행 중에 발생하는 에러를 미연에 방지하기 위한 것try : # 예외가 발생할 수 있는 코드except : # 예외 발생시 실행할 코드 # except ValueError as e # except ZeroDivisionError as eelse : # 예외가 발생하지 않은 경우 실행할 코드finally : # 항상 실행할 코드 2025. 2. 2.
[Python] 파이썬 파일입출력 # 파일입출력# input(), print() X# 프로그램에 유의미한 데이터를 읽기/저장/출력# 1) 파일 열기# w : 쓰기 모드 write 덮어쓰기# a : 추가 모드 append 이어쓰기# r : 읽기 모드 readfile = open("data.txt", "w")file = open("data.txt", "a")file = open("data.txt", "r")# 2) 파일 작업 file.write("start python") # 쓰기/추가 모드data = file.read() # 읽기 모드# 3) 파일 닫기file.close() 2025. 2. 2.
[Python] 파이썬 pickle module 사용법 # pickle모듈# 1) 파일에 파이썬 객체 저장하기import pickledata = { "목표1" : "돈모으기", "목표2" : "취업하기"}file = open(data.pickle, "wb") # wb : 바이너리모드(컴퓨터가 바로 읽을 수 있는 모드)pickle.dump(data, file) # dump함수 : data객체와 file 넘겨주기file.close() # pickle모듈# 2) 파일로부터 파이썬 객체 읽기import pickle# with구문 사용Xfile = open("data.pickle", "rb")data = pickle.load(file) # 파일 읽어주는 함수#print(data)file.close()# with구문 사용 -> file.close() 자동 호.. 2025. 2. 2.
[Python] 파이썬 모듈/패키지 # 모듈 : 한 개의 완성된 프로그램 파일# 1) 내장모듈 : 파이썬 설치 시 자동으로 설치되는 모듈 # import 모듈이름 import mathfrom math import pi,ceil# 모듈이름.변수print(math.pi)print(pi)# 모듈이름.함수()print(math.ceil(5.8)) # 올림함수print(ceil(4.3))# 2) 외부모듈 : 다른 사람이 만든 파이썬 파일을 pip로 설치해서 사용# pip install 모듈이름# pip install pyautogui 설치 -> 터미널# http://pyautogui.readthedocs.io/en/latest/index.htmlimport pyautogui as pgpg.moveTo(500, 500, duration=2) # ->.. 2025. 2. 2.
[Python] 파이썬 상속 오버라이딩 / 클래스 변수 import random# 1. 메서드 오버라이딩 -> 부모클래스를 자식클래스가 상속하여 재정의# 2. 클래스 변수 -> 인스턴스들이 모두 공유하는 변수(공개변수)# 부모클래스class Monster : max_num = 1000 #클래스 자체의 변수 def __init__(self, name, health, attack) : self.name = name self.health = health self.attack = attack Monster.max_num -= 1 # 인스턴스를 사용할 때마다 변수값 감소 def move(self) : print(f"[{self.name}] : 지상에서 이동하기")# 자식클래스1class.. 2025. 1. 31.
[Python] 파이썬 상속 - 오버라이딩/오버로딩 # 상속# 부모클래스의 속성과 메서드를 그대로 가지고 와서 사용할 수 있는 것 -> 오버라이딩, 오버로딩# 부모클래스class Monster : def __init__(self, name, health, attack) : self.name = name self.health = health self.attack = attack def move(self) : print(f"[{self.name}] : 지상에서 이동하기")# 자식클래스1class Wolf(Monster) : pass # ★클래스 그대로 사용# 자식 클래스2class Shark(Monster) : def move(self) : # 오버라이딩 : 메서드 재정의 .. 2025. 1. 31.
[Python] 파이썬 생성자 # 생성자 : 인스턴스를 만들 때 호출되는 메서드class Monster : def __init__(self, health, attack, speed) : self.health = health self.attack = attack self.speed = speed def decrease_health(self, num) : self.health = num def get_health(self) : return self.health# 인스턴스 생성goblin = Monster(800, 120, 400)goblin.decrease_health(100)print(goblin.get_health()) 2025. 1. 31.
[Python] 파이썬 클래스와 객체 # 클래스와 객체# 클래스 : 객체를 만들기 위한 설계도 -> 속성 + 메서드드# 객체 : 설계도로 만들어낸 작품c_name = "이즈리얼"c_health = 700c_attack = 90c2_name = "리신"c2_health = 900c2_attack = 60# 함수정의def basic_attck(name, attack) : print (f"{name} 기본 공격 {attack}" )# 함수호출basic_attck(c_name, c_attack)basic_attck(c2_name, c2_attack)# =================== 클래스를 사용한 경우 =====================class Campion : def __init__(self, name, health, att.. 2025. 1. 31.
[Python] 파이썬 딕셔너리 dictionary # 딕셔너리 {중괄호}# 시퀀스 자료형 -> 순서가 있는 자료형# '키'와 '데이터'를 가지고 있는 사전형 자료형dict1 = {'key1' : '1', 'key2' : 2, 'key3' : True}# 딕셔너리 접근dict1['key1']# 딕셔너리 할당dict1['key1'] = '할당데이터'# 딕셔너리 삭제del dict1['key3']# 딕셔너리 함수# 키와 데이터 쌍dict1.items()# 키dict1.keys()# 데이터dict1.values()for item in dict1.items() : print(item) 2025. 1. 16.
[Python] 파이썬 튜플 tuple # 튜플 -> () 소괄호# 시퀀스자료형 # 1. 순서가 있는 자료형# 2. 수정/추가/삭제 불가 -> 읽기전용# 3. 메모리 사용이 효율적, 데이터 손실 Xtuple1 = ('데이터1,', 1, True)tuple2 = False, '데이터5', 44print(tuple1, tuple2)# 튜플 -> 리스트 자료형 변환# 리스트를 튜플 함수로 감싸기a = tuple([5, 6, 7]) # tuple(리스트자료형)# 패킹 -> 여러개의 데이터를 하나의 변수에 할당numbers = 3, 4, 5# 언패킹-> 컬렉션의 각 데이터를 각각의 변수에 할당a, b, c = numbers# 튜플 함수a = 10, 20, 30, 40, 50# 1. 특정값의 인덱스 구하기a.index(20)# 2. 특정값의 개수a.co.. 2025. 1. 16.
[Python] 파이썬의 괄호 의미 # () 함수/튜플# [] 리스트/인덱스# {} fstring 2025. 1. 16.
[Python] 파이썬 함수 def / 재사용성 유지보수성 가독성 # 함수# 재사용성, 유지보수성, 가독성# 함수 정의# def 함수이름() : # 명령블록def hello() : print("hello")def sum(x, y) : print(x + y)def bye() : return ("bye")# 함수 호출# 함수이름()hello()sum(10, 20)a = bye()print(a) 2025. 1. 10.
728x90
반응형