
2024.12.27
def <함수명>(매개변수):
명령문
[return <반환값>]
<함수명>(<인자>)
from <모듈명> import <함수명>
def <함수명>(<인자>):
명령문
[return <반환값>]
def <함수명>():
명령문
[return <반환값>]
def <함수명>(<인자>):
명령문
# 인자도 있고 반환 값도 있는 함수
def my_calc(x, y):
# z = x * y
# return z
return x*y
my_calc(1,5)
def my_sum(start, end=10):
pass
keyword arguments
Non-keyword 가변인자
keyword 가변인자
global 키워드 사용<전역변수>
def <함수명>():
global <전역변수>
lambda <인자> : <인자 활용 명령문>
(lambda <인자명> : <인자 활용 명령문>)(<인자>)
def cal_footage(square):
footage = square/3.3057
footage = round(footage,1)
return footage
# return round(footage,1)
cal_footage(84) = (lambda x : round(x/3.3057,1))(84)
def factorial(n):
if n ==0:
result = 1
else:
result = 1
for i in range(1, n+1):
result *= i
return result
= factorial(5)
# 정수형 변환, 숫자로 변환 가능한 값이여야 함
int(<인자>)
# 실수형 변환
float(<인자>)
# 문자형 변환
str(<인자>)
# 리스트, 튜플, 세트형 변환
list(<인자>)
tuple(<인자>)
set(<인자>)
# 숫자형 인자
bool(<숫자 인자>)
# 문자열, 리스트, 튜플, 세트형 인자
bool(<인자>)
# 최대값
max()
# 최소값
min()
# 숫자형의 절대값 변환 (복소수일 경우, 유클리드거리변환)
abs()
# 리스트, 튜플, 세트형 데이터의 모든 원소의 합
sum()
# 모듈/객체가 가지고 있는 변수나 함수를 확인
dir()
# 객체의 주소값
id()
# 순서가 있는 자료형을 순서와 함께 활용
enumerate(순서가 있는 자료, start=0)
# 동일한 개수로 이루어진 자료형을 묶어줌
zip(*iterable)
# 모든 항목에 function을 적용하여 리턴
map(function, iterable)
import <모듈명>
모듈명.함수명()
import time
# 연도, 월, 일, 시, 분, 초 정보 제공 (UTC-0기준)
now = time.localtime()
now
import random
random.seed(4)
print(random.random())
print(random.randint(1,100))
a = [1,2,3,4,5]
random.shuffle(a)
a


class 클래스명():
[변수1]
[변수2]
def 함수1(self, 인자1, 인자2,...):
[코드 블록]
def 함수2(self, 인자1, 인자2,...):
[코드 블록]
class 클래스명():
[변수1]
[변수2]
def 함수1(self, 인자1, 인자2,...):
[코드 블록]
def 함수2(self, 인자1, 인자2,...):
[코드 블록]
객체명.변수명 = 속성값객체명.변수명# 클래스 선언
class Bicycle():
pass
# 객체 생성
my_bicycle = Bicycle()
# 객체 속성 설정
my_bicycle.wheel_size = 26
my_bicycle.color = 'black'
# 객체의 속성 출력
print("바퀴 크기:", my_bicycle.wheel_size)
print("색상:", my_bicycle.color)
__init__()를 이용하여 객체를 생성하는 동시에 속성값 초기화객체명 = 클래스명(속성1, 속성2, ...)class Bicycle():
## 속성값 초기화
def __init__(self, wheel_size, color):
self.wheel_size = wheel_size
self.color = color
def move(self, speed):
print("자전거: 시속 {0}킬로미터로 전진".format(speed))
def turn(self, direction):
print("자전거: {0}회전".format(direction))
def stop(self):
print("자전거({0}, {1}): 정지 ".format(self.wheel_size, self.color))
# 객체 생성과 동시에 속성값을 지정.
my_bicycle = Bicycle(26, 'black')
my_bicycle.move(30) # 객체 메서드 호출
my_bicycle.turn('좌')
my_bicycle.stop()
__del__()를 이용하여 객체를 소멸시켜 메모리에서 제거class Bicycle():
## 속성값 초기화
def __init__(self, wheel_size, color):
self.wheel_size = wheel_size
self.color = color
def move(self, speed):
print("자전거: 시속 {0}킬로미터로 전진".format(speed))
def turn(self, direction):
print("자전거: {0}회전".format(direction))
def stop(self):
print("자전거({0}, {1}): 정지 ".format(self.wheel_size, self.color))
def __del__(self):
print("자전거 객체가 소멸합니다.")
클래스명.변수명형식으로 접근self.변수명형식으로 정의, 객체에서는 `객체명.변수명'형식으로 접근self.변수명으로 클래스 변수에 접근class Car():
instance_count = 0 # 클래스 변수 생성 및 초기화
def __init__(self, size, color):
self.size = size # 인스턴스 변수 생성 및 초기화
self.color = color # 인스턴스 변수 생성 및 초기화
Car.instance_count = Car.instance_count + 1 # 클래스 변수 이용
print("자동차 객체의 수: {0}".format(Car.instance_count))
def move(self):
print("자동차({0} & {1})가 움직입니다.".format(self.size, self.color))
self.변수명으로 클래스의 변수(속성값) 활용 가능 객체명.메서드명(인자1,인자2,..)class Bicycle():
def move(self, speed):
print("자전거: 시속 {0}킬로미터로 전진".format(speed))
def turn(self, direction):
print("자전거: {0}회전".format(direction))
def stop(self):
print("자전거({0}, {1}): 정지 ".format(self.wheel_size, self.color))
# Bicycle 클래스의 인스턴스인 my_bicycle 객체 생성
my_bicycle = Bicycle()
# 객체의 속성 설정
my_bicycle.wheel_size = 26
my_bicycle.color = 'black'
# 객체의 메서드 호출
my_bicycle.move(30)
my_bicycle.turn('좌')
my_bicycle.stop()
# Bicycle 클래스의 인스턴스인 bicycle1 객체 생성
bicycle1 = Bicycle()
bicycle1.wheel_size = 27 # 객체의 속성 설정
bicycle1.color = 'red'
bicycle1.move(20)
bicycle1.turn('좌')
bicycle1.stop()
# Bicycle 클래스의 인스턴스인 bicycle2 객체 생성
bicycle2 = Bicycle()
bicycle2.wheel_size = 24 # 객체의 속성 설정
bicycle2.color = 'blue'
bicycle2.move(15)
bicycle2.turn('우')
bicycle2.stop()
Library 클래스를 만들고, 책을 추가하고 빌릴 수 있는 기능을 제공하는 프로그램Librarybook_list 도서관이 보유하고 있는 도서 목록add_book(book) : 책이름을 인자로 받아 도서 목록에 추가borrow_book(book)# book_list를 딕셔너리 타입으로 지정한 경우 {책이름 : 대여여부}
class Library:
def __init__(self):
self.book_list = {}
def add_book(self, book):
self.book_list[book] = True
def borrow_book(self, book):
if book in self.book_list:
if self.book_list[book]:
self.book_list[book] = False
print(f"\"{book}\"책을 대여합니다.")
else:
print(f"\"{book}\"책은 현재 대여중입니다.")
else:
print(f"\"{book}\"책은 저희 도서관에서 보유하고 있지 않습니다.")
lib = Library()
lib.add_book("파이썬")
lib.add_book("인공지능")
lib.borrow_book("파이썬")
lib.borrow_book("머신러닝")
lib.borrow_book("파이썬")
BankAccount클래스BankAccountbalance (계좌의 잔액)check_balance() : 계좌의 잔액 balance를 출력deposit(amount) : balance에 amount(금액)을 입금withdraw(amount) : balance에서 amount(금액)을 출금 class BankAccount:
def __init__(self, balance=0):
self.balance = balance
def check_balance(self):
print(f"계좌의 잔액은 {self.balance}원입니다.")
def deposit(self, amount):
self.balance += amount
print(f"{amount}원을 입금하였습니다. 잔액은 {self.balance}입니다.")
def withdraw(self, amount):
if self.balance < amount:
print("계좌에 잔액이 충분하지 않습니다.")
else:
self.balance -= amount
print(f"{amount}원을 출금하였습니다. 잔액은 {self.balance}입니다.")
acc2 = BankAccount(1000)
acc2.check_balance()
acc2.deposit(1000)
acc2.deposit(500)
acc2.withdraw(1000)
acc2.withdraw(1000)
acc2.withdraw(1000)
StudentGradesgrades (딕셔너리 타입, 이름과 성적으로 이루어짐)add_grade(name, grade)name과 성적grade를 입력받아 성적목록에 추가get_grade(name)name을 입력받아 해당 학생의 성적을 조회get_average_grade()class StudentGrades:
def __init__(self):
self.grades = {}
def add_grade(self, name, grade):
self.grades[name] = grade
print(f"성적 목록에 있는 학생: {self.grades.keys()}")
# 이름과 성적을 여러개의 쌍으로 입력
def add_grade_multi(self, **kwargs):
for name, grade in kwargs.items():
self.grades[name] = grade
print(f"성적 목록에 있는 학생: {self.grades.keys()}")
def get_grade(self, name):
if name in self.grades:
print(f"{name}의 성적은 {self.grades[name]}점입니다")
else:
print(f"학생 \'{name}\'의 성적을 찾을 수 없습니다")
def get_average_grade(self):
if len(self.grades) == 0:
avg = 0
else:
avg = sum(self.grades.values()) / len(self.grades)
print(f"모든 학생의 평균 성적은 {avg}점 입니다.")
math_grades = StudentGrades()
math_grades.add_grade("A", 100)
math_grades.add_grade("B", 70)
math_grades.add_grade("C", 80)
math_grades.add_grade_multi(D=65, E=90)
math_grades.get_grade("A")
math_grades.get_grade("D")
math_grades.get_average_grade()