본문 바로가기
python

파이썬 기초 - 변수와 데이터 타입

by kyeongseo.oh 2025. 3. 15.

변수의 개념과 활용

변수란?

변수는 프로그램에서 데이터를 저장하는 상자다. 이름표가 붙은 상자에 값을 넣어두고, 필요할 때마다 그 이름표를 통해 값을 꺼내 쓸 수 있다.

# 변수에 값 저장하기
name = "Kim"
age = 25
height = 175.5

변수의 특징

  • 변수는 언제든지 값을 바꿀 수 있다 (그래서 '변수'라고 부른다)
  • 파이썬은 다른 프로그래밍 언어와 달리 변수의 타입을 미리 선언할 필요가 없다
score = 95       # 처음에는 숫자
score = "A+"     # 나중에 문자열로 변경 가능

변수 이름 짓기와 변수 사용하기

변수 이름 규칙

  1. 문자, 숫자, 밑줄(_)만 사용할 수 있다
  2. 숫자로 시작할 수 없다
  3. 공백은 사용할 수 없다
  4. 대소문자를 구분한다 (name과 Name은 다른 변수)
# 올바른 변수명
user_name = "Hong"
age1 = 30
_private = "Secret"

# 잘못된 변수명
# 2name = "Error"  # 숫자로 시작할 수 없음
# user name = "Error"  # 공백 사용 불가
# if = "Error"  # 파이썬 예약어 사용 불가

권장하는 변수명 작성법

  • 의미 있는 이름 사용하기 (x보다는 age, score 같은 구체적인 이름)
  • 소문자와 밑줄로 작성하기 (snake_case) - 파이썬 표준 스타일
  • 이해하기 쉬운 이름 사용하기
# 좋은 변수명
student_name = "Kim"
average_score = 88.5
is_passed = True

# 좋지 않은 변수명
a = "Kim"  # 의미를 알 수 없음
s = 88.5  # 무슨 값인지 알기 어려움

파이썬 기본 데이터 타입 다루기

1. 숫자 (Numbers)

정수 (int)

소수점이 없는 숫자다.

age = 25
student_count = 30

# 정수 연산
sum_result = 10 + 5  # 더하기: 15
difference = 10 - 5  # 빼기: 5
product = 10 * 5  # 곱하기: 50
quotient = 10 // 3   # 나눗셈(몫): 3
remainder = 10 % 3  # 나머지: 1
power = 2 ** 3   # 2의 3제곱: 8

실수 (float)

소수점이 있는 숫자다.

height = 175.5
weight = 68.7

# 실수 연산
sum_float = 10.5 + 5.2  # 15.7
division = 10 / 3    # 3.3333333333333335

# 소수점 자리수 조절하기
rounded = round(3.14159, 2)  # 3.14 (소수점 2자리까지)

2. 문자열 (String)

텍스트를 표현하는 데이터 타입이다. 따옴표로 묶어서 표현한다.

name = "John"
greeting = 'Hello'
address = "Seoul, Gangnam"

# 문자열 연결하기
full_greeting = greeting + ", " + name + "!"  # "Hello, John!"

# 문자열에서 특정 글자 가져오기 (인덱싱)
first_char = name[0]  # "J"
last_char = name[-1]  # "n"

# 문자열 일부분 가져오기 (슬라이싱)
part = address[7:14]  # "Gangnam"

# 유용한 문자열 함수들
upper_case = "hello".upper()  # "HELLO"
lower_case = "HELLO".lower()  # "hello"
stripped = "  hello  ".strip()  # "hello"
replaced = "I like apples".replace("apples", "bananas")  # "I like bananas"
split_result = "apple,banana,orange".split(",")  # ["apple", "banana", "orange"]
contains = "apple" in "I like apples"  # True

# 문자열 포맷팅 (f-string)
name = "John"
age = 25
intro = f"My name is {name} and I am {age} years old."

3. 불린 (Boolean)

참(True) 또는 거짓(False) 값을 가지는 데이터 타입이다.

is_passed = True
is_failed = False

# 비교 연산자로 불린 값 만들기
is_equal = (5 == 5)  # True
is_not_equal = (5 != 10)  # True
is_greater = (10 > 5)  # True
is_less = (5 < 10)  # True
is_greater_equal = (5 >= 5)  # True
is_less_equal = (5 <= 10)  # True

# 논리 연산자
logical_and = True and False  # False (둘 다 True여야 True)
logical_or = True or False  # True (하나라도 True면 True)
logical_not = not True  # False (True는 False로, False는 True로)

4. None

값이 없음을 나타내는 특별한 데이터 타입이다.

result = None

# None 확인하기
is_none = result is None  # True

파이썬 컬렉션 데이터 타입 다루기

1. 리스트 (List)

여러 값을 순서대로 저장하는 데이터 타입이다. 대괄호 []로 표현한다.

# 리스트 만들기
fruits = ["apple", "banana", "orange"]
scores = [85, 92, 78, 90]
mixed = ["John", 25, True]  # 다양한 타입 저장 가능

# 리스트에서 값 가져오기 (인덱싱)
first_fruit = fruits[0]  # "apple"
last_fruit = fruits[-1]  # "orange"

# 리스트 일부분 가져오기 (슬라이싱)
some_fruits = fruits[0:2]  # ["apple", "banana"]

# 리스트 값 바꾸기
fruits[1] = "kiwi"  # ["apple", "kiwi", "orange"]

# 리스트에 값 추가하기
fruits.append("strawberry")  # ["apple", "kiwi", "orange", "strawberry"]

# 특정 위치에 값 넣기
fruits.insert(1, "melon")  # ["apple", "melon", "kiwi", "orange", "strawberry"]

# 값 제거하기
fruits.remove("kiwi")  # ["apple", "melon", "orange", "strawberry"]
last_fruit = fruits.pop()  # "strawberry"를 빼고 반환, fruits = ["apple", "melon", "orange"]

# 리스트 정렬하기
scores.sort()  # [78, 85, 90, 92] (오름차순)
fruits.sort(reverse=True)  # ["orange", "melon", "apple"] (내림차순)

# 리스트 길이 확인하기
fruit_count = len(fruits)  # 3

# 리스트 합치기
list1 = [1, 2, 3]
list2 = [4, 5, 6]
combined_list = list1 + list2  # [1, 2, 3, 4, 5, 6]

# 리스트에 특정 값이 있는지 확인
exists = "apple" in fruits  # True

2. 딕셔너리 (Dictionary)

키(key)와 값(value)의 쌍으로 데이터를 저장하는 데이터 타입이다. 중괄호 {}와 콜론 :으로 표현한다.

# 딕셔너리 만들기
student = {
    "name": "John",
    "age": 18,
    "grade": 2,
    "hobbies": ["football", "gaming"]
}

# 값 가져오기
name = student["name"]  # "John"

# 안전하게 값 가져오기 (키가 없어도 오류 안 남)
address = student.get("address")  # None
address = student.get("address", "No info")  # "No info"

# 값 추가/수정하기
student["address"] = "Seoul"  # 새 키-값 추가
student["age"] = 19  # 기존 값 수정

# 값 삭제하기
del student["hobbies"]

# 모든 키 가져오기
keys = student.keys()  # dict_keys(['name', 'age', 'grade', 'address'])

# 모든 값 가져오기
values = student.values()  # dict_values(['John', 19, 2, 'Seoul'])

# 키-값 쌍 가져오기
items = student.items()  # dict_items([('name', 'John'), ('age', 19), ...])

# 특정 키가 있는지 확인하기
exists = "name" in student  # True

3. 세트 (Set)

중복되지 않는 값들의 모음이다. 중괄호 {}로 표현한다.

# 세트 만들기
fruit_set = {"apple", "banana", "orange"}
number_set = {1, 2, 3, 3, 3}  # {1, 2, 3} (중복 제거됨)

# 빈 세트 만들기 (중괄호만 쓰면 빈 딕셔너리가 됨)
empty_set = set()

# 값 추가하기
fruit_set.add("kiwi")  # {"apple", "banana", "orange", "kiwi"}

# 값 제거하기
fruit_set.remove("banana")  # {"apple", "orange", "kiwi"}

# 세트 연산하기
set1 = {1, 2, 3}
set2 = {3, 4, 5}
union = set1 | set2  # {1, 2, 3, 4, 5} (모든 원소)
intersection = set1 & set2  # {3} (공통 원소)
difference = set1 - set2  # {1, 2} (set1에만 있는 원소)

# 세트의 주요 용도: 중복 제거
name_list = ["John", "Alice", "John", "Bob", "Alice"]
unique_names = set(name_list)  # {"John", "Alice", "Bob"}
back_to_list = list(unique_names)  # ["John", "Alice", "Bob"]

4. 튜플 (Tuple)

리스트와 비슷하지만 한번 만들면 내용을 바꿀 수 없다. 소괄호 ()로 표현한다.

# 튜플 만들기
coordinates = (10, 20)
rgb_color = (255, 0, 0)  # 빨간색
person_info = ("John", 30, "Seoul")

# 값 가져오기 (리스트와 같음)
name = person_info[0]  # "John"
age = person_info[1]  # 30

# 여러 값을 한번에 가져오기 (언패킹)
x, y = coordinates  # x = 10, y = 20
name, age, region = person_info  # 각 변수에 값이 들어감

# 튜플은 값을 바꿀 수 없음
# coordinates[0] = 15  # 오류 발생!

# 튜플의 주요 용도: 여러 값 반환하기
def calculate_rectangle(width, height):
    area = width * height
    perimeter = 2 * (width + height)
    return (area, perimeter)

area, perimeter = calculate_rectangle(5, 3)  # area = 15, perimeter = 16

예제

예제 1: 학생 성적 관리

요구사항

  1. 다음 조건을 만족하는 학생 성적 관리 프로그램을 작성한다.
    • 최소 3명 이상의 학생 정보를 딕셔너리 형태로 저장한다.
    • 각 학생마다 이름, 국어, 수학, 영어 점수를 포함해야 한다.
    • 모든 점수는 0점부터 100점 사이여야 한다.
  2. 프로그램은 다음 기능을 수행해야 한다.:
    • 각 학생의 세 과목 평균 점수를 계산하고 출력. (소수점 첫째 자리까지 반올림)
    • 수학 점수가 90점 이상인 학생들의 이름을 찾아 출력
    • 전체 평균이 가장 높은 학생의 이름과 점수를 출력
  3. 출력 형식은 다음과 같아야 한다.
    • 각 학생의 평균: "[학생이름]'s average score: [평균점수]"
    • 수학 고득점자 목록: "Students with math score 90+: [이름1], [이름2], ..."
    • 최고 평균 학생: "Top student: [학생이름] ([평균점수] points)"

 

# 학생들의 성적 정보 저장
students = [
    {"name": "Hong", "korean": 90, "math": 85, "english": 92},
    {"name": "Kim", "korean": 82, "math": 95, "english": 88},
    {"name": "Lee", "korean": 94, "math": 90, "english": 95}
]

# 각 학생의 평균 점수 계산하기
for student in students:
    total = student["korean"] + student["math"] + student["english"]
    average = total / 3
    student["average"] = round(average, 1)  # 소수점 첫째 자리까지 반올림
    print(f"{student['name']}'s average score: {student['average']}")

# 수학 점수가 90점 이상인 학생들 찾기
math_high_scorers = []
for student in students:
    if student["math"] >= 90:
        math_high_scorers.append(student["name"])

print(f"Students with math score 90+: {', '.join(math_high_scorers)}")

# 전체 평균이 가장 높은 학생 찾기
highest_avg = 0
top_student = ""

for student in students:
    if student["average"] > highest_avg:
        highest_avg = student["average"]
        top_student = student["name"]

print(f"Top student: {top_student} ({highest_avg} points)")

 

변수와 데이터 타입 정리

  1. 변수: 데이터를 저장하는 이름표가 붙은 상자
  2. 기본 데이터 타입:
    • 정수(int): 소수점 없는 숫자 (예: 10, -5)
    • 실수(float): 소수점 있는 숫자 (예: 3.14, -0.5)
    • 문자열(str): 텍스트 데이터 (예: "Hello")
    • 불린(bool): 참/거짓 값 (True, False)
    • None: 값이 없음을 나타냄
  3. 컬렉션 데이터 타입:
    • 리스트(list): 여러 값을 순서대로 저장, 변경 가능 (예: [1, 2, 3])
    • 딕셔너리(dict): 키-값 쌍으로 저장, 변경 가능 (예: {"name": "John"})
    • 세트(set): 중복 없는 값들의 모음, 변경 가능 (예: {1, 2, 3})
    • 튜플(tuple): 여러 값을 순서대로 저장, 변경 불가능 (예: (1, 2, 3))

'python' 카테고리의 다른 글

파이썬 기초 - 함수 기초  (0) 2025.03.16
파이썬 기초 - 조건문과 반복문  (1) 2025.03.16
aiosmtpd pytest  (0) 2023.02.09
이것저것  (0) 2023.01.27
report 생성  (0) 2023.01.23

댓글