[Python Basic] 04. 변수 타입(Variable Type)
0. 변수란
변수는 프로그래밍에서 "하나의 데이터(숫자, 문자등)를 저장할 수 있는 메모리 공간"으로, 데이터 타입에 따라 정수, 소수, 문자등을 저장할 수 있다.
변수의 이름을 정의함에 있어 일반적인 룰은 아래와 같다.
- 파이썬에서 예약어는 사용할 수 없다.
- 변수는 하나의 문자(a letter)나 밑줄(underscore) 시작해야 한다.
- 변수의 두번째 문자부터는 문자(letter), 숫자(number) 또는 밑줄(underscore)를 사용할 수 있다.
- 변수는 대, 소문자을 구분한다.
- 변수명의 타입은 값에 따라 변화한다.
# 04_00_00_PythonNameingRule
import keyword
# 예약어의 확인
print(keyword.kwlist)
# ['False', 'None', 'True', 'and', 'as', 'assert', 'async', 'await', 'break', 'class',
# 'continue', 'def', 'del', 'elif', 'else', 'except', 'finally', 'for', 'from',
# 'global', 'if', 'import', 'in', 'is', 'lambda', 'nonlocal', 'not', 'or', 'pass',
# 'raise', 'return', 'try', 'while', 'with', 'yield']
# 변수의 이름에 예약어 사용
# 아래 프로그램은 실행이 되지 않습니다. 테스트를 하시려면 주석 처리를 해제하고 사용하세요
# while = 0 # SyntaxError: invalid syntax
# 변수의 이름에 숫자로 시작하는 문자 사용
# 아래 프로그램은 실행이 되지 않습니다. 테스트를 하시려면 주석 처리를 해제하고 사용하세요
# 0Value = 1 # SyntaxError: invalid syntax
# 변수의 이름에 문자나 밑줄로 시작하는 변수 할당
sValue = "letter"
_Value = "underscore"
# 변수의 이름에 두번째 자리에 문자, 숫자 또는 밑줄 사용
iValue = 10
i00000 = 20
i_____ = 30
# 변수의 이름이 대, 소 문자를 구분하는지
# 아래 프로그램은 실행이 되지 않습니다. 정상적으로 작동하려면 주석 처리를 하고 사용하세요
SVALUE = "Upper Case String"
print(svalue) # name 'svalue' is not defined
# 변수의 타입이 바뀌는지에 따른 점검
sChangeType = "String type"
print(type(sChangeType)) # <class 'str'>
sChangeType = 10
print(type(sChangeType)) # <class 'int'>
1. 변수에 값 할당
변수는 변수에 값을 할당하기 위해서는 변수명, 등호(=), 변수값으로 구성되며, 변수값의 할당으로 자료의 타입이 결정된다. 등호(=)의 왼쪽에 피 연산자인 변수명을 두고 오른쪽에 변수값을 적으면된다.
<variable name = value>
파이썬이 다른 언어와 상이한 것은 변수의 Type을 확인해 보면 클래스(Classes)라는 것을 알 수 있다.
# 04_01_00_PythonVariableAssignment
import sys
# Integer
iValue = 7
print(iValue) # 7
print(type(iValue)) # <class 'int'>
# Floating point
fValue = 3.1415926535897932384626433
print(fValue) # 3.1415926535897932384626433
print(type(fValue)) # <class 'float'>
# String
sValue = 'First String'
print(sValue) # First String
print(type(sValue)) # <class 'str'>
# Boolen
bValue = False
print(bValue) # False
print(type(bValue)) # <class 'bool'>
# Empty Value
nValue = None
print(nValue) # None
print(type(nValue)) # <class 'NoneType'>
2. 동시에 할당
여러개의 변수를 한번에 값을 할당하는 방법은 두가지가 있다.
첫째는 <변수명, 변수명, .... = 값, 값, .....> 같은 방법으로 할당할 수 있다.
두번째는 제한적이지만 <변수명 = 변수명 = 변수명 = 값> 과 같은 방법으로 할당할 수있다.
# 04_03_00_PythonMultipleValue
# 한번에 여러개의 변수 할당
iValue0, iValue1, iValue2 = 10, 20, 30
print(iValue0, iValue1, iValue2) # 10 20 30
# 변수의 갯수와 값의 갯수가 맞지 않을 경우
# 아래 프로그램은 실행이 되지 않습니다. 정상적으로 작동하려면 주석 처리를 하고 사용하세요
#jValue0, jValue1 = 10, 20, 30 # too many values to unpack (expected 2)
#kValue0, kValue1, kValue2 = 10, 20 # not enough values to unpack (expected 3, got 2)
# 여러개의 변수에 하나의 값을 입력할 때
lValue0 = lValue1 = lValue2 = 10
print(lValue0, lValue1, lValue2) # 10 10 10
3. 표준 데이터 유형
파이썬에서 제공하는 표준 데이터 유형은 아래와 같다.
테이터 유형 | 할당 구분 | 아이템 구분 | 특징 |
숫자(Number Type) | |||
문자(String Type) | "" 또는 '' | ||
셋(Set Type) | { } | , | 중복제외, 순서없음 |
리스트(List Type) | [ ] | , | |
딕셔너리(Dictionary Type) | { } | , | 키와 값으로 분리 |
튜플(Tuple Type) | ( ) | , | 수정불가 |
4. 숫자 유형(Numbers Type)
숫자 유형의 데이터는 숫자 값을 저장하며, 3가지의 숫자 타입을 제공한다. Long 타입은 정수형 타입으로 대체되었다.
# 04_04_00_PythonNumberDataTypes
iNumber = 10
print(iNumber) # 10
print(type(iNumber)) # <class 'int'>
fNumber = 10.5
print(fNumber) # 10.5
print(type(fNumber)) # <class 'float'>
cNumber = 3.14j
print(cNumber) # 3.14j
print(type(cNumber)) # <class 'complex'>
5. 문자열 유형(Strings Type)
문자열은 연속된 문자 집합으로 홑 따옴표(')나 겹 따옴표(") 안에 문자를 넣어서 사용할 수 있다.
# 04_05_00_PythonStringDataTypes
sValue = "String Value"
# 문자 데이터의 타입 출력
print(type(sValue)) # <class 'str'>
# 문자 데이터 출력
print(sValue) # String Value
# 0번째 문자 출력
print(sValue[0]) # S
# 0부터 3번째 문자까지 출력
print(sValue[:3]) # Str
# 3번째부터 4번째 문째까지 출력
print(sValue[3:5]) # in
# 5번째부터 마지막까지 출력
print(sValue[5:]) # g Value
print(sValue * 3)
6. 셋 유형(Set Type)
셋 유형에는 셋(Set)과 프로전셋(frozenset)이 있다.
셋은 수정이 가능하나 중복된 데이터는 제외하는 속성을 가지고 있으며, 정렬 기준이 없다.
프로전셋은 수정이 불가능하다.
# 04_06_00_PythonSetDataTypes
# 셋 데이터 타입속에 하나의 문자 데이터 타입 할당
setString = set('ABBCCCDDDDCCCBBA')
print(type(setString)) # <class 'set'>
print(setString) # {'D', 'C', 'A', 'B'}
setString.add('ABCDEFGHIJKLMN')
print(setString) # {'B', 'A', 'D', 'ABCDEFGHIJKLMN', 'C'}
# 셋 데이터 타입에 하나의 요소 할당
setValue = {'ABBCCCDDDDCCCBBA'}
print(type(setValue)) # <class 'set'>
print(setValue) # {'ABBCCCDDDDCCCBBA'}
setValue.add('ABCDEF')
print(setValue) # {'ABCDEF', 'ABBCCCDDDDCCCBBA'}
# 셋 데이터 타입에 여러개의 요소 할당
setValues = {'first', 'second', 'third', 'fourth', 'fifth', 'second', 'third'}
print(type(setValues)) # <class 'set'>
print(setValues) # {'second', 'fourth', 'third', 'fifth', 'first'}
# 셋 데이터 타입에 동일한 요소값을 추가
setValues.add('first')
print(setValues) # {'second', 'fourth', 'third', 'fifth', 'first'}
# 셋 데이터 타입에 없는 요소값을 추가
setValues.add('ABCDEF')
print(setValues) # {'ABCDEF', 'second', 'fourth', 'third', 'fifth', 'first'}
# 프로전셋 데이터 타입에 요소값 할당
fsValue = frozenset('ABBCCCDDDDCCCBBA')
print(fsValue) # frozenset({'C', 'B', 'A', 'D'})
# 프로전셋 데이터 타입에 요소값 추가
# 아래 코드는 실행되지 않으며 실행시에는 주석 처리하고 사용하세요
fsValue.add('ABCDEF') # AttributeError: 'frozenset' object has no attribute 'add'
print(fsValue) # frozenset({'B', 'C', 'D', 'A'})
7. 리스트(Lists)
리스트는 복합 데이터 유형으로 꺽은 괄호([])로 묶어서 사용한다. 내부의 아이템은 콤마(,)를 사용하여 구분한다. 리스트의 아이템은 각기 다른 유형의 자료도 포함 할 수 있다는 장점이 있다.
# 04_07_00_PythonListDataTypes
# 리스트에 값 할당
listValue = [10, 'String', False, 10.5j]
print(listValue) # [10, 'String', False, 10.5j]
print(type(listValue)) # <class 'list'>
# 리스트의 인덱스를 통한 접근
print(listValue[1:2]) # ['String']
print(listValue[2:]) # [False, 10.5j]
print(listValue[:2]) # [10, 'String']
# 리스트의 계산 및 추가
print(listValue + listValue) # [10, 'String', False, 10.5j, 10, 'String', False, 10.5j]
print(listValue * 3) # [10, 'String', False, 10.5j, 10, 'String', False, 10.5j, 10, 'String', False, 10.5j]
# 리스트에 아이템 추가
listValue.append('AddString')
print(listValue) # [10, 'String', False, 10.5j, 'AddString']
# 리스트에 아이템 제거
listValue.remove('AddString')
print(listValue) # [10, 'String', False, 10.5j]
# 리스트에 리스트 추가
listValue.append([20, 'Duble String', True, 20.5j])
print(listValue) # [10, 'String', False, 10.5j, [20, 'Duble String', True, 20.5j]]
8. 딕셔너리 유형(Dictionary Type)
딕셔너리는 해시 테이블 유형으로, 키와 값이 동시에 저장되는 유형으로 중괄호({})로 묶어서 사용한다. 내부의 아이템은 콤마(,)로 구분한다.
# 04_08_00_PythonDictionaryDataTypes
# Dictionary 에 값을 할당
dicValue = {'Koran': 100, 'English': 90, 'Mathematics': 95, 'History': 93, 'Physics': 98, 'Chemistry': 97 }
print(dicValue)
# {'Koran': 100, 'English': 90, 'Mathematics': 95, 'History': 93, 'Physics': 98, 'Chemistry': 97}`
print(type(dicValue)) # <class 'dict'>
# Key를 이용한 값 불러 오기
print(dicValue['Physics']) # 98
# Key 값 불러오기
print(dicValue.keys()) # dict_keys(['Koran', 'English', 'Mathematics', 'History', 'Physics', 'Chemistry'])
# Value 값 불러오기
print(dicValue.values()) # dict_values([100, 90, 95, 93, 98, 97])
# Key를 이용한 값의 변경
dicValue['Physics'] = 100
print(dicValue['Physics']) # 100
9. 튜플 유형(Tuples Types)
튜플은 리스트와 같이 복합 데이터 유형으로 괄호(())로 묶어서 사용한다. 내부의 아이템은 콤마(,)를 사용하여 구분한다. 리스트와의 차이점은 읽기 전용으로 수정이 불가하다.
# 04_09_00_PythonTupleDataTypes
# Tuple 데이터 타입을 할당한다.
tupleValue = (10, 'String', False, 10.5j)
print(tupleValue) # (10, 'String', False, 10.5j)
print(type(tupleValue)) # <class 'tuple'>
# Tuple 데이터 인덱스를 통한 값 불러오기
print(tupleValue[0]) # 10
print(tupleValue[1:2]) # ('String',)
print(tupleValue[1:]) # ('String', False, 10.5j)
print(tupleValue[:2]) # (10, 'String')
# 인덱스를 통하여 수정
# 아래 코드는 작동하지 않습니다. 실행시에는 주석처리하여 사용하십시요
tupleValue[2] = 'Error'
10. 데이터 형식변환(Data Type Conversion)
프로그램을 하다보면 데이터 간에 형식의 변환이 필요하게 된다. 이를 때 사용할 수 있는 함수이다.
Function | Description |
int(x) | x 값을 정수 타입로 변환한다. |
float(x) | x 값을 부동 소숫점 타입으로 변환한다. |
complex(x) | x 값을 복소수 타입으로 변환한다. |
str(x) | x값을 문자 타입으로 변환한다. |
repr(x) | x값을 표현식 문자 타입으로 변환한다. |
eval(str) | x값이 문자 타입인지를 검증한다. |
tuple(s) | s를 튜플 타입으로 변환한다. |
list(s) | s값을 리스트 타입으로 변환한다. |
set(s) | s값을 셋 타입으로 변환한다. |
dict(d) | d값을 딕셔너리 타입으로 변환한다. |
frozenset(s) | s 값을 고정 셋 타입으로 변환한다. |
chr(x) | x 값을 문자 타입으로 변환한다. |
ord(x) | x 문자를 정수 타입으로 변환한다. |
hex(x) | x 값을 16진수 문자 타입으로 변환한다. |
oct(x) | x 값을 8진수 문자 타입으로 변환한다. |