[Python]데이터타입 및 형변환

파이썬에서 지원하는 데이터 타입과 형변환에 대해서 알아보자

"""
int : 정수
float : 실수
complex : 복소수
bool : 불린
str : 문자열
list : 리스트
tuple : 튜플
set : 집합
dict : 사전
"""

# 데이터타입
str1 = "jigi"
bool = True
str2 = "파이썬"
float_v1 = 10.0  # 10 != 10.0
int_v1 = 7
list_v = [str1, str2]
dict_v = {
    "name": "Machine Learning",
    "version": 1.0
}
tuple_v = (1, 3, 5, 7)  # tuple = 1, 3, 5, 7 처럼 괄호를 빼도 된다.
set_v = {2, 4, 6, 8}

# 데이터 타입 출력
print(type(str1))
print(type(bool))
print(type(str2))
print(type(float_v1))
print(type(int_v1))
print(type(list_v))
print(type(dict_v))
print(type(tuple_v))
print(type(set_v))
print()

# 숫자형 연산자
"""
+
-
*
/ 
// : 몫
% : 나머지
abs(x) : 절대값
pow(a, b) = a ** b : 2 ** 3 = 8 
"""

# 정수 선언
i1 = 10
i2 = -15
big_int = 12351223412312312335443453456345345345345

# 정수 출력
print(i1, i2, big_int)
print()

# 실수 출력
f1 = 0.9999
f2 = 3.123123
f3 = -4.234
f4 = 3 / 9

print(f1)
print(f2)
print(f3)
print(f4)
print()

# 연산 실습
int1 = 39
int2 = 123
big_int1 = 1231413452345222222222324234523452345234523452345
big_int2 = 213413412431234123412341234133567578435356735763456

print("int1 + int2 =", int1 + int2);
print("f1 + f2 =", f1 + f2);
print("big_int1 + big_int2 =", big_int1 + big_int2);
print()

print("int1 * int2 =", int1 * int2);
print("f1 * f2 =", f1 * f2);
print("big_int1 * big_int2 =", big_int1 * big_int2)

# 형변환 실습
a = 3.  # 소수점 생략 가능
b = 6
c = .7  # 정수 생략가능
d = 12.7

# 타입출력
print(type(a), type(b), type(c), type(d))

# 형변환
print(float(b))
print(int(c))
print(int(d))
print(int(True))  # True = 1, False = 0
print(float(False))
print(complex(3))  # 복소수
print(complex('3'))  # 문자형 -> 숫자형으로 형변환
print(complex(False))
print()

# 수치 연산함수
print(abs(-7))
x, y = divmod(10, 3)  # 몫, 나머지 !! 자주 쓰이는 함수
print(x, y)
print(pow(2, 10), 2 ** 10)  # 1024

# 외부모듈
import math

print(math.pi)  # 원주율
print(math.ceil(5.1))  # 6

출력 :

<class 'str'>
<class 'bool'>
<class 'str'>
<class 'float'>
<class 'int'>
<class 'list'>
<class 'dict'>
<class 'tuple'>
<class 'set'>

10 -15 12351223412312312335443453456345345345345

0.9999
3.123123
-4.234
0.3333333333333333

int1 + int2 = 162
f1 + f2 = 4.123023
big_int1 + big_int2 = 214644825883579345634563558368091030780591259215801

int1 * int2 = 4797
f1 * f2 = 3.1228106877
big_int1 * big_int2 = 262800146978720777022945178368799299310118175482212197134956801870743897985651843587215630408504320
<class 'float'> <class 'int'> <class 'float'> <class 'float'>
6.0
0
12
1
0.0
(3+0j)
(3+0j)
0j

7
3 1
1024 1024
3.141592653589793

You may also like...

답글 남기기

이메일 주소는 공개되지 않습니다. 필수 필드는 *로 표시됩니다