무료 파이썬 풀코스: 왕초보도 20가지 프로젝트로 취업까지! 🐍
파이썬 코딩 배우기: 중학생 눈높이 정리
이 영상은 파이썬으로 코딩을 시작하는 방법을 알려주는 영상이야. 20가지 실습 프로젝트도 포함되어 있고, 마지막 프로젝트는 날씨 앱을 만드는 거야. 코딩 경험이 전혀 없어도 괜찮아. 프로그래밍의 기초부터 차근차근 알려줄 거야.
1. 파이썬 설치
- 파이썬 인터프리터: 코드를 컴퓨터가 알아들을 수 있는 언어로 바꿔주는 프로그램이야.
python.org에 가서 최신 버전을 다운로드 받아.- 설치할 때 "Add Python X.X to PATH" 옵션을 꼭 체크해줘.
- IDE (통합 개발 환경): 코드를 작성하는 곳이야.
- PyCharm: 초보자에게 친절한 IDE야.
jetbrains.com/pycharm에서 다운로드 받아.- 무료인 Community Edition을 사용하면 돼.
- VS Code: 이미 사용하고 있다면 그대로 사용해도 괜찮아. 단, 파이썬 확장 프로그램을 설치해야 해.
- PyCharm: 초보자에게 친절한 IDE야.
2. 첫 파이썬 프로그램 만들기
- 프로젝트 생성: PyCharm에서 새 프로젝트를 만들고 이름을 정해줘.
- 파이썬 파일 생성: 프로젝트 폴더 안에
main.py같은 이름으로 새 파이썬 파일을 만들어. (파일 이름은 아무거나 상관없어..py확장자로 끝나야 해.) - 코드 작성:
python print("I like pizza") # 좋아하는 음식을 출력해봐! print("It's really good") # 두 번째 줄도 출력해봐. - 주석:
#뒤에 오는 내용은 코드로 실행되지 않아. 나중에 코드를 다시 볼 때 기억하기 위한 메모 같은 거야.
python # This is my first Python program - 실행: PyCharm의 실행 버튼 (▶️ 모양)을 누르면 아래 콘솔 창에 결과가 출력돼.
3. 변수와 데이터 타입
변수는 값을 담는 상자라고 생각하면 돼. 파이썬에는 여러 가지 데이터 타입이 있어.
- 문자열 (String): 글자나 문장이야. 따옴표(
"또는')로 감싸줘.
python first_name = "홍길동" # 이름 food = "pizza" # 좋아하는 음식 email = "myemail@example.com" # 이메일 print(f"Hello, {first_name}") # f-string을 사용하면 변수와 문자열을 쉽게 합칠 수 있어. print(f"You like {food}") print(f"Your email is {email}") - 정수 (Integer): 소수점 없는 숫자야.
python age = 25 # 나이 quantity = 3 # 개수 num_students = 30 # 학생 수 print(f"You are {age} years old") print(f"You are buying {quantity} items") print(f"Your class has {num_students} students") - 실수 (Float): 소수점이 있는 숫자야.
python price = 10.99 # 가격 gpa = 3.2 # 학점 distance = 5.5 # 거리 print(f"The price is ${price}") print(f"Your GPA is {gpa}") print(f"You ran {distance} km") -
불리언 (Boolean): 참 (True) 또는 거짓 (False) 값이야.
```python
is_student = True # 학생인가?
is_for_sale = False # 판매 중인가?
is_online = True # 온라인인가?if is_student:
print("You are a student")
else:
print("You are not a student")if is_online:
print("You are online")
else:
print("You are offline")
```
4. 타입 변환 (Type Casting)
데이터 타입을 다른 타입으로 바꾸는 거야.
int(): 숫자로 변환 (소수점 버림)float(): 숫자로 변환 (소수점 포함)str(): 문자열로 변환bool(): 불리언으로 변환 (빈 문자열, 0은 False, 나머지는 True)
# 예시
gpa = 3.2
age = 25
# float를 int로 변환
gpa_int = int(gpa) # gpa_int는 3이 됨
# int를 float로 변환
age_float = float(age) # age_float는 25.0이 됨
# int를 str로 변환
age_str = str(age) # age_str는 "25"가 됨
# str를 bool로 변환
name = "홍길동"
is_name_valid = bool(name) # is_name_valid는 True가 됨
name_empty = ""
is_name_empty_valid = bool(name_empty) # is_name_empty_valid는 False가 됨
# 타입 확인
print(type(gpa_int)) # <class 'int'>
print(type(age_str)) # <class 'str'>
print(type(is_name_valid)) # <class 'bool'>
5. 사용자 입력 받기
input() 함수를 사용하면 사용자로부터 값을 입력받을 수 있어. 입력받은 값은 항상 문자열이야.
name = input("What is your name? ")
print(f"Hello, {name}")
age_str = input("How old are you? ")
# 숫자로 사용하려면 int()나 float()로 변환해야 해.
age = int(age_str)
print(f"You are {age} years old")
# 바로 변환해서 사용하기
# age = int(input("How old are you? "))
# 숫자 계산 시 타입 변환 필수!
# age = age + 1 # 오류 발생! 문자열에 숫자를 더할 수 없어.
# age = int(age) + 1 # 이렇게 해야 돼.
# 또는 더 짧게: age += 1
6. 연습 문제: 사각형 넓이 구하기
사용자로부터 가로와 세로 길이를 입력받아 사각형의 넓이를 계산해보자.
# 길이를 입력받을 때 숫자로 변환하는 것을 잊지 마!
length = float(input("Enter the length: "))
width = float(input("Enter the width: "))
area = length * width
print(f"The area is {area} cm^2") # ^2는 제곱을 의미해.
7. 연습 문제: 쇼핑 카트 만들기
사용자가 사고 싶은 물건과 가격, 개수를 입력받아 총 금액을 계산하는 프로그램을 만들어보자.
item = input("What item would you like to buy? ")
price = float(input("What is the price of each item? $"))
quantity = int(input("How many would you like? "))
total = price * quantity
print(f"You have bought {quantity} x {item}s.")
print(f"Your total is ${total}.")
8. Mad Libs 게임 만들기
빈칸을 채워 재미있는 이야기를 만드는 게임이야.
print("Today, I went to a {} zoo.".format(input("Enter an adjective: ")))
print("In an exhibit, I saw a {}.".format(input("Enter a noun: ")))
print("{} was {} and {}ing.".format(input("Enter a noun: "), input("Enter an adjective: "), input("Enter a verb ending with ing: ")))
print("I was {}.".format(input("Enter an adjective: ")))
9. 수학 연산자 및 함수
- 기본 연산자:
+: 덧셈-: 뺄셈*: 곱셈/: 나눗셈**: 거듭제곱%: 나머지 (나머지 연산자)
- 증감 연산자:
+=,-=,*=,/=,**=
python friends = 5 friends += 1 # friends = friends + 1 과 같음 print(friends) # 6 - 내장 함수:
round(숫자): 반올림abs(숫자): 절댓값pow(밑, 지수): 거듭제곱max(값1, 값2, ...): 최댓값min(값1, 값2, ...): 최솟값
math모듈: 더 많은 수학 함수를 사용하려면import math를 해야 해.math.pi: 원주율 파이math.sqrt(숫자): 제곱근math.ceil(숫자): 올림math.floor(숫자): 내림
10. 조건문 (If Statements)
어떤 조건이 맞을 때만 코드를 실행하고 싶을 때 사용해.
if 조건:: 조건이 맞으면 실행else:: 조건이 맞지 않으면 실행elif 조건:: 여러 조건을 순서대로 확인할 때 사용
age = int(input("Enter your age: "))
if age >= 18:
print("You are now signed up.")
elif age < 0:
print("You haven't been born yet.")
else:
print("You must be 18+ to sign up.")
# 비교 연산자: == (같다), != (다르다), > (크다), < (작다), >= (크거나 같다), <= (작거나 같다)
response = input("Would you like food? (y/n): ")
if response == 'y':
print("Have some food.")
else:
print("No food for you.")
name = input("Enter your name: ")
if name == "": # 이름이 비어있으면
print("You did not type in your name.")
else:
print(f"Hello, {name}")
11. 논리 연산자 (Logical Operators)
여러 조건을 합치거나 반대로 만들 때 사용해.
or: 둘 중 하나라도 맞으면 참and: 둘 다 맞아야 참not: 반대로 (참이면 거짓, 거짓이면 참)
temp = 25
is_raining = False
if temp > 35 or temp < 0 or is_raining:
print("The outdoor event is cancelled.")
else:
print("The outdoor event is still scheduled.")
# and 예시
if temp >= 28 and is_raining: # temp가 28 이상이고 비가 오면
print("It is hot and raining.")
# not 예시
if not is_raining:
print("It is not raining.")
12. 조건부 표현식 (Conditional Expressions)
if-else 문을 한 줄로 간단하게 표현하는 방법이야.
결과값1 if 조건 else 결과값2
num = 5
result = "positive" if num > 0 else "negative"
print(result) # positive
num = 6
result = "even" if num % 2 == 0 else "odd"
print(result) # even
a = 6
b = 7
max_num = a if a > b else b
print(max_num) # 7
13. 문자열 메소드 (String Methods)
문자열을 다루는 유용한 기능들이야.
.len(): 문자열 길이.find(): 특정 문자열의 첫 번째 위치 찾기 (-1은 못 찾음).rfind(): 특정 문자열의 마지막 위치 찾기.capitalize(): 첫 글자만 대문자로.upper(): 모든 글자를 대문자로.lower(): 모든 글자를 소문자로.isdigit(): 숫자로만 이루어져 있는지 확인 (True/False).isalpha(): 알파벳으로만 이루어져 있는지 확인 (True/False).count(문자): 특정 문자가 몇 개 있는지 세기.replace(바꿀 내용, 바꿀 것): 문자열 바꾸기
name = input("Enter your full name: ")
print(f"Length of name: {len(name)}")
space_index = name.find(" ")
print(f"Index of first space: {space_index}")
last_o_index = name.rfind("o")
print(f"Index of last 'o': {last_o_index}")
print(f"Capitalized name: {name.capitalize()}")
print(f"Uppercase name: {name.upper()}")
print(f"Lowercase name: {name.lower()}")
phone_number = "123-456-7890"
print(f"Number of dashes: {phone_number.count('-')}")
new_phone_number = phone_number.replace("-", " ")
print(f"Phone number with spaces: {new_phone_number}")
new_phone_number = phone_number.replace("-", "")
print(f"Phone number without dashes: {new_phone_number}")
14. 문자열 인덱싱 (String Indexing)
문자열의 특정 글자에 접근하는 방법이야.
문자열[위치]: 해당 위치의 글자 가져오기 (0부터 시작)문자열[시작:끝]: 특정 범위의 글자 가져오기 (끝은 포함 안 됨)문자열[시작:끝:간격]: 특정 범위의 글자를 간격만큼 가져오기문자열[-1]: 마지막 글자 가져오기문자열[::-1]: 문자열 뒤집기
credit_card = "1234-5678-9012-3456"
print(credit_card[0]) # 1
print(credit_card[4]) # -
print(credit_card[0:4]) # 1234
print(credit_card[5:9]) # 5678
print(credit_card[::2]) # 13479135
print(credit_card[-4:]) # 3456
print(credit_card[::-1]) # 6543-2109-8765-4321
last_digits = credit_card[-4:]
print(f"Last four digits: ****{last_digits}")
15. 포맷 지정자 (Format Specifiers)
f-string 안에서 숫자를 보기 좋게 꾸밀 때 사용해.
{변수:포맷지정자}.2f: 소수점 둘째 자리까지 표시10: 총 10칸 확보 (오른쪽 정렬 기본)010: 총 10칸 확보, 빈칸은 0으로 채우기<: 왼쪽 정렬>: 오른쪽 정렬^: 가운데 정렬+: 양수 앞에 + 붙이기,: 천 단위 구분 기호 (쉼표)
price1 = 3.14159
price2 = 987.65
price3 = 12.34
print(f"Price 1: ${price1:.2f}") # Price 1: $3.14
print(f"Price 2: ${price2:10.2f}") # Price 2: $ 987.65 (10칸 확보)
print(f"Price 3: ${price3:010.2f}") # Price 3: $0000012.34 (0으로 채우고 10칸 확보)
num = 5
print(f"Left aligned: {num:<10}") # Left aligned: 5
print(f"Right aligned: {num:>10}") # Right aligned: 5
print(f"Center aligned: {num:^10}") # Center aligned: 5
positive_num = 10
negative_num = -5
print(f"With plus: {positive_num:+}") # With plus: +10
print(f"With space: {positive_num: }") # With space: 10 (양수 앞에 공백)
large_num = 1234567
print(f"With comma: {large_num:,}") # With comma: 1,234,567
# 여러 개 조합
print(f"Formatted: ${price2:+,15.2f}") # Formatted: $+, 987.65
16. 반복문 (While Loops)
조건이 참인 동안 코드를 계속 반복해서 실행할 때 사용해.
# 이름 입력받기 (빈칸 입력하면 다시 입력받기)
name = input("Enter your name: ")
while name == "":
print("You did not enter your name.")
name = input("Enter your name: ")
print(f"Hello, {name}")
# 나이 입력받기 (0보다 작으면 다시 입력받기)
age = int(input("Enter your age: "))
while age < 0:
print("Age can't be negative.")
age = int(input("Enter your age: "))
print(f"You are {age} years old")
# Q를 입력하면 종료
food = input("Enter a food you like (Q to quit): ")
while food.lower() != 'q': # 소문자로 바꿔서 비교
print(f"You like {food}")
food = input("Enter another food you like (Q to quit): ")
print("Bye")
# 1부터 10 사이 숫자 입력받기
num = int(input("Enter a number between 1 through 10: "))
while num < 1 or num > 10: # 1보다 작거나 10보다 크면
print(f"{num} is not valid.")
num = int(input("Enter a number between 1 and 10: "))
print(f"Your number is {num}")
17. for 반복문 (For Loops)
정해진 횟수만큼 코드를 반복하거나, 리스트, 문자열 등을 순회할 때 사용해.
for 변수 in 순회할것:range(시작, 끝): 시작부터 끝-1까지 숫자 생성reversed(순회할것): 거꾸로 순회step(간격):range(시작, 끝, 간격)
# 1부터 10까지 출력
for x in range(1, 11):
print(x)
# 10부터 0까지 거꾸로 출력
for x in reversed(range(11)): # 0부터 10까지 거꾸로
print(x)
# 1부터 10까지 2씩 증가하며 출력
for x in range(1, 11, 2):
print(x) # 1 3 5 7 9
# 문자열 순회
credit_card = "1234-5678-9012-3456"
for char in credit_card:
print(char)
# continue: 현재 반복 건너뛰기
for x in range(1, 21):
if x == 13:
continue # 13은 건너뛰고 다음으로
print(x)
# break: 반복문 완전히 종료
for x in range(1, 21):
if x == 13:
break # 13에서 반복문 종료
print(x)
18. 함수 (Functions)
코드를 묶어서 재사용할 수 있게 해주는 거야.
def 함수이름(매개변수):: 함수 정의return 값: 함수 결과 반환함수이름(인수): 함수 호출
# 함수 정의
def happy_birthday(name, age):
print(f"Happy birthday to {name}")
print(f"You are {age} years old")
# 함수 호출
happy_birthday("홍길동", 20)
happy_birthday("김철수", 30)
def create_full_name(first, last):
return first.capitalize() + " " + last.capitalize()
full_name = create_full_name("hong", "gildong")
print(full_name) # Hong Gildong
# 기본값 인수 (Default Arguments)
def count_up(start, end=10): # end는 기본값이 10이야.
for i in range(start, end + 1):
print(i)
time.sleep(1) # 1초 대기 (time 모듈 필요)
count_up(1) # 1부터 10까지 출력
count_up(5, 15) # 5부터 15까지 출력
19. 키워드 인수 (Keyword Arguments)
함수를 호출할 때 매개변수 이름을 명시해서 전달하는 거야. 순서가 바뀌어도 괜찮아.
def hello(greeting, title, first_name, last_name):
print(f"{greeting} {title} {first_name} {last_name}")
# 위치 인수 (Positional Arguments)
hello("Hello", "Mr.", "Spongebob", "Squarepants")
# 키워드 인수 (Keyword Arguments) - 순서 바꿔도 됨
hello(title="Mr.", first_name="Spongebob", greeting="Hello", last_name="Squarepants")
# 위치 인수와 키워드 인수 섞어 쓰기 (위치 인수가 먼저 와야 함)
hello("Hello", title="Mr.", first_name="Spongebob", last_name="Squarepants")
20. 임의 인수 (Arbitrary Arguments)
함수에 몇 개의 인수가 들어올지 모를 때 사용해.
*args: 여러 개의 위치 인수를 튜플로 받음**kwargs: 여러 개의 키워드 인수를 딕셔너리로 받음
# *args 예시
def add(*args): # args는 튜플이 됨
total = 0
for num in args:
total += num
return total
print(add(1, 2, 3)) # 6
print(add(1, 2, 3, 4, 5)) # 15
print(add(10)) # 10
# **kwargs 예시
def print_address(**kwargs): # kwargs는 딕셔너리가 됨
for key, value in kwargs.items():
print(f"{key}: {value}")
print_address(street="123 Fake St", city="Detroit", state="MI", zip="54321")
# street: 123 Fake St
# city: Detroit
# state: MI
# zip: 54321
# *args와 **kwargs 함께 사용 (args가 먼저 와야 함)
def my_function(*args, **kwargs):
for arg in args:
print(f"Positional arg: {arg}")
for key, value in kwargs.items():
print(f"Keyword arg: {key} = {value}")
my_function(1, 2, 3, name="Alice", age=30)
# Positional arg: 1
# Positional arg: 2
# Positional arg: 3
# Keyword arg: name = Alice
# Keyword arg: age = 30
21. 반복 가능한 객체 (Iterables)
반복문(for)으로 순회할 수 있는 객체들을 말해.
- 리스트 (
list) - 튜플 (
tuple) - 문자열 (
str) - 세트 (
set) - 딕셔너리 (
dict)
numbers = [1, 2, 3, 4, 5]
for num in numbers:
print(num)
# reversed()로 거꾸로 순회
for num in reversed(numbers):
print(num)
# print() 함수의 end 인수로 구분자 변경
for num in numbers:
print(num, end=" ") # 1 2 3 4 5
fruits = {"apple", "orange", "banana", "coconut"}
for fruit in fruits:
print(fruit) # 순서는 랜덤
name = "Python"
for char in name:
print(char, end="-") # P-y-t-h-o-n-
my_dict = {"A": 1, "B": 2, "C": 3}
for key in my_dict: # 기본적으로 키를 순회
print(key) # A B C
for value in my_dict.values(): # 값만 순회
print(value) # 1 2 3
for key, value in my_dict.items(): # 키와 값 모두 순회
print(f"{key} = {value}") # A = 1, B = 2, C = 3
22. 멤버십 연산자 (Membership Operators)
어떤 값이 시퀀스 안에 있는지 없는지 확인할 때 사용해.
in: 안에 있으면 True, 없으면 Falsenot in: 안에 없으면 True, 있으면 False
secret_word = "apple"
guess = input("Guess a letter: ")
if guess.lower() in secret_word: # 소문자로 바꿔서 비교
print(f"'{guess}' is in the word.")
else:
print(f"'{guess}' was not found.")
students = {"Spongebob", "Patrick", "Sandy"}
student_name = input("Enter a student name: ")
if student_name in students:
print(f"{student_name} is a student.")
else:
print(f"{student_name} was not found.")
grades = {"Sandy": "A", "Squidward": "B", "Spongebob": "C"}
student = input("Enter student name: ")
if student in grades: # 딕셔너리에서는 키를 확인
print(f"{student}'s grade is {grades[student]}") # grades[student]로 값 가져오기
else:
print(f"{student} was not found.")
email = "test@example.com"
if "@" in email and "." in email:
print("Valid email.")
else:
print("Invalid email.")
23. 리스트 컴프리헨션 (List Comprehensions)
리스트를 간결하고 쉽게 만드는 방법이야.
[표현식 for 변수 in 순회할것 if 조건]
# 1부터 10까지 숫자를 두 배로 만들기
doubles = [x * 2 for x in range(1, 11)]
print(doubles) # [2, 4, 6, 8, 10, 12, 14, 16, 18, 20]
# 1부터 10까지 숫자를 세 배로 만들기
triples = [y * 3 for y in range(1, 11)]
print(triples) # [3, 6, 9, 12, 15, 18, 21, 24, 27, 30]
# 1부터 10까지 숫자를 제곱하기
squares = [z**2 for z in range(1, 11)]
print(squares) # [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
# 과일 이름을 대문자로 바꾸기
fruits = ["apple", "orange", "banana", "coconut"]
upper_fruits = [fruit.upper() for fruit in fruits]
print(upper_fruits) # ['APPLE', 'ORANGE', 'BANANA', 'COCONUT']
# 첫 글자만 가져오기
fruit_chars = [fruit[0] for fruit in fruits]
print(fruit_chars) # ['a', 'o', 'b', 'c']
# 양수만 골라내기
numbers = [1, -2, 3, -4, 5, -6]
positive_nums = [num for num in numbers if num >= 0]
print(positive_nums) # [1, 3, 5]
# 짝수만 골라내기
even_nums = [num for num in numbers if num % 2 == 0]
print(even_nums) # [-2, -4, -6]
# 60점 이상인 점수만 골라내기
grades = [85, 42, 79, 90, 56, 61, 30]
passing_grades = [grade for grade in grades if grade >= 60]
print(passing_grades) # [85, 79, 90, 61]
24. Match Case 문 (Match Case Statements)
if-elif-else 문을 더 깔끔하게 만들어주는 기능이야.
# 요일 맞추기 게임
def get_day_of_week(day_num):
match day_num:
case 1:
return "Sunday"
case 2:
return "Monday"
case 3:
return "Tuesday"
case 4:
return "Wednesday"
case 5:
return "Thursday"
case 6:
return "Friday"
case 7:
return "Saturday"
case _: # 그 외 모든 경우 (else 역할)
return "Invalid day"
print(get_day_of_week(1)) # Sunday
print(get_day_of_week(7)) # Saturday
print(get_day_of_week(9)) # Invalid day
# 요일이 주말인지 확인하기
def is_weekend(day_name):
match day_name:
case "Saturday" | "Sunday": # | 는 or 와 같음
return True
case "Monday" | "Tuesday" | "Wednesday" | "Thursday" | "Friday":
return False
case _:
return False # 그 외는 모두 False
print(is_weekend("Monday")) # False
print(is_weekend("Saturday")) # True
print(is_weekend("Pizza")) # False
25. 모듈 (Modules)
다른 파이썬 파일에 있는 코드들을 가져와서 사용하는 거야.
import 모듈이름import 모듈이름 as 별명from 모듈이름 import 특정기능
# math 모듈 사용
import math
print(math.pi)
print(math.sqrt(16))
# math 모듈을 m으로 별명 붙여 사용
import math as m
print(m.pi)
# math 모듈에서 pi만 가져오기
from math import pi
print(pi)
# 직접 모듈 만들기
# 1. 새 파이썬 파일 만들기 (예: my_module.py)
# 2. 파일 안에 함수나 변수 정의
# pi = 3.14159
# def square(x): return x**2
# 3. 다른 파일에서 import하여 사용
# import my_module
# print(my_module.pi)
# print(my_module.square(5))
26. 변수 범위 (Variable Scope)
변수를 어디서 사용할 수 있는지 정해주는 거야.
- 지역 변수 (Local): 함수 안에서만 사용 가능
- 전역 변수 (Global): 함수 밖 어디서든 사용 가능
- 내장 변수 (Built-in): 파이썬 자체에서 제공하는 변수 (예:
print,len,math.e)
# 지역 변수
def func1():
a = 1
print(a) # 1
# func1() # a = 1 출력
# 전역 변수
x = 3
def func1():
print(x) # 전역 변수 x 사용
def func2():
print(x) # 전역 변수 x 사용
func1() # 3
func2() # 3
# 함수 안에서 전역 변수 변경 시 'global' 키워드 사용
# x = 3
# def func1():
# global x
# x = 1
# print(x) # 1
# func1()
# print(x) # 1 (전역 변수 x가 변경됨)
27. if __name__ == "__main__":
이 코드는 현재 파일이 직접 실행될 때만 아래 코드를 실행하도록 하는 거야. 다른 파일에서 이 파일을 가져와서 사용할 때는 아래 코드가 실행되지 않아.
# my_module.py
def greet(name):
print(f"Hello, {name}")
def main():
print("This is my_module.py")
greet("World")
if __name__ == "__main__":
main()
# main.py
# import my_module
# my_module.greet("Python") # Hello, Python (main 함수는 실행 안 됨)
28. 함수 (Functions) - 심화
- 매개변수 (Parameters): 함수 정의 시 사용하는 변수
- 인수 (Arguments): 함수 호출 시 전달하는 값
- 기본값 인수 (Default Arguments): 함수 정의 시 매개변수에 기본값을 지정 (호출 시 생략 가능)
- 키워드 인수 (Keyword Arguments):
매개변수이름=값형태로 전달 (순서 상관 없음) - 임의 인수 (*args, **kwargs): 몇 개의 인수가 들어올지 모를 때 사용
29. 객체 지향 프로그래밍 (Object-Oriented Programming, OOP)
- 클래스 (Class): 객체를 만들기 위한 설계도
- 객체 (Object): 클래스로 만들어진 실체
- 속성 (Attribute): 객체가 가진 데이터 (변수)
- 메소드 (Method): 객체가 할 수 있는 동작 (함수)
- 생성자 (
__init__): 객체를 만들 때 자동으로 호출되는 특별한 메소드 self: 현재 객체를 가리킴- 상속 (Inheritance): 다른 클래스의 속성과 메소드를 물려받는 것
- 다중 상속: 여러 클래스를 상속받는 것
- 다단계 상속: 부모가 또 부모를 상속받는 것
super(): 부모 클래스의 메소드를 호출할 때 사용- 다형성 (Polymorphism): 같은 이름의 메소드가 객체에 따라 다르게 동작하는 것
- 상속: 부모 클래스의 메소드를 자식 클래스에서 재정의 (오버라이딩)
- 덕 타이핑 (Duck Typing): "오리처럼 생기고 오리처럼 꽥꽥거리면 오리다" 처럼, 필요한 메소드만 있으면 같은 타입으로 취급하는 것
- 정적 메소드 (Static Methods): 클래스 자체에 속하며, 객체나 클래스 데이터에 접근할 필요 없을 때 사용 (
@staticmethod데코레이터) - 클래스 메소드 (Class Methods): 클래스 자체에 속하며, 클래스 데이터에 접근할 때 사용 (
@classmethod데코레이터, 첫 매개변수는cls) - 매직 메소드 (Magic Methods / Dunder Methods):
__init__,__str__,__eq__등__로 둘러싸인 메소드. 파이썬 내장 기능과 연동될 때 자동으로 호출됨.
30. PIQT5 (GUI 라이브러리)
그래픽 사용자 인터페이스 (GUI)를 만들 때 사용하는 라이브러리야.
- 설치:
pip install PyQt5 -
기본 구조:
```python
import sys
from PyQt5.QtWidgets import QApplication, QWidgetapp = QApplication(sys.argv)
window = QWidget()
window.show()
sys.exit(app.exec_())
`` * **주요 위젯:** *QWidget: 모든 위젯의 기본 클래스 *QLabel: 텍스트나 이미지를 표시 *QPushButton: 버튼 *QLineEdit: 텍스트 입력 상자 *QCheckBox: 체크박스 *QRadioButton: 라디오 버튼 (하나만 선택 가능) * **레이아웃:** 위젯들을 배치하는 방법 *QVBoxLayout: 수직 배치 *QHBoxLayout: 수평 배치 *QGridLayout: 격자 형태로 배치 * **스타일시트 (Stylesheet):** CSS처럼 위젯의 디자인을 꾸밀 수 있어. * **시그널과 슬롯 (Signal & Slot):** 위젯의 이벤트 (시그널)와 특정 동작 (슬롯)을 연결하는 방식. (예: 버튼 클릭 시 특정 함수 실행) * **타이머 (QTimer):** 일정 시간 간격으로 특정 동작을 반복할 때 사용 (시계, 애니메이션 등에 활용) * **API 연동:**requests` 라이브러리를 사용해 외부 API와 통신할 수 있어. (날씨 앱, 포켓몬 정보 등)
이 외에도 다양한 기능들이 있지만, 이 정도만 알아도 파이썬으로 많은 것을 만들 수 있을 거야! 궁금한 점이 있다면 언제든지 다시 물어봐!