[Python][기초] 2. 프로그램의 기본재료

나나콘·2023년 10월 31일

Python 기초 공부

목록 보기
2/11
post-thumbnail

🔢 int, float

## int, float
my_int = 3
my_float = 3.14
my_float
# 3.14

type(my_int)
# <class 'int'>

type(my_float)
# <class 'float'>

type(1)
# <class 'int'>

1+2
# 3

🔤 string

큰 따옴표 "" or 작은 따옴표 ''

'hello'
# 'hello'

"hello"
# 'hello'

⚪✖ boolean

True / False (true, false 안되고 정확하게 써야함)

True
# True
False
# False

💫 type()

변수의 타입을 확인하는 함수

my_int = 3
type(my_int)
# <class 'int'>

my_float = 3.14
type(my_float)
# <class 'float'>

List (mutable)

[value1, value2, value3, ...]

💬 예제

my_list = [1, 2, 3]
my_list
# [1, 2, 3]

students = ['가가가', '나나나', '다다다']
students
# ['가가가', '나나나', '다다다']

for std in students:
    print(std)
# 가가가
# 나나나
# 다다다


import random
print(random.choice(students))
# 다다다
print(random.choice(students))
# 가가가
students.append('라라라')
students
# ['가가가', '나나나', '다다다', '라라라']

Tuple (immutable)

(value1, value2, value3)

💬 예제

my_tuple = ('가', '나', '다')
my_tuple
# ('가', '나', '다')

my_tuple[0]
# '가'
my_tuple[0] = '마'
# TypeError: 'tuple' object does not support item assignment
##--> tuple에서는 값을 변경할 수 없다

Dictionary

{Key1: Value1, Key2: Value2, Key3: Value3, ... }

딕셔너리는 단어 그대로 ‘사전’이라는 뜻이다. 즉 "people"이라는 단어에 "사람", "baseball"이라는 단어에 "야구"라는 뜻이 부합되듯이 딕셔너리는 Key와 Value를 한 쌍으로 가지는 자료형이다. 예컨대 Key가 "baseball"이라면 Value는 "야구"가 될 것이다.

요즘 사용하는 대부분의 언어도 이러한 대응 관계를 나타내는 자료형을 가지고 있는데 이를 딕셔너리라고 하고, ‘연관 배열(associative array)’또는 ‘해시(hash)’라고도 한다.

💬 예제

my_dict = {'가': '남', '나':'여', '다': '남'}

my_dict[]
# Traceback (most recent call last):
# File "<pyshell#42>", line 1, in <module>
#   my_dict[가]
# NameError: name '가' is not defined
##--> 에러발생

my_dict['가']
# '남'

my_dict['나'] = '남'
my_dict
# {'가': '남', '나': '남', '다': '남'}
profile
지식을 기록하고, 경험을 코드로 남겨라.

0개의 댓글