Edu/01. Language: Python

데이터 타입: 숫자형

Lacuna028 2021. 11. 30. 11:23

- 데이터 타입

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

bytearray
byte
frozenset
 
 
 
# 데이터 타입 확인하는 함수: type()
v_str = "Hello python!"
print(type(v_str))
 
 
# 숫자형 데이터 타입 연산
+
-
*
/
// : 몫
% : 나머지
abs(x) : 절댓값
int(x) : 정수로 출력
float(x) : 실수로 출력
complex(x) : 복소수로 출력
pow(x, y) : 제곱. pow(제곱, 제곱근)
x ** y : 제곱

 

 

# math 외부 모듈

import math

 

print(math.ceil(5.1))   # x 이상의 수 중에서 가장 작은 정수. output: 6
print(math.floor(3.874)) # x 이하의 수 중에서 가장 큰 정수. output: 3
print(math.pi)
print(bin(50)) # 2진수 변환. 0b로 시작. output: 0b110010

 

기타 math 함수: https://docs.python.org/3/library/math.html

 

math — Mathematical functions — Python 3.10.1 documentation

math — Mathematical functions This module provides access to the mathematical functions defined by the C standard. These functions cannot be used with complex numbers; use the functions of the same name from the cmath module if you require support for co

docs.python.org

 

 

 

+ 추가

- 반올림: round()

:round() 함수는 소숫점 값이 5이상부터 올림을 적용한다. 그러나 python3부터 round to nearest even이라고 해서 정수부분이 짝수일 경우 가까운 짝수를 만들기 위해 소숫점 값이 5이더라도 그 값을 버린다.

예로 들면

print(round(4.4))는 4를 출력,

print(round(4.5))는 4를 출력,

print(round(4.6))는 5를 출력,

print(round(3.4))는 3를 출력,

print(round(3.5))는 4를 출력,

print(round(3.6))는 4를 출력한다.

 

반올림하고 싶은 자리수를 지정하고 싶을 경우, 하이퍼파라미터로 소숫점아래 몇번째 자리에서 반올림하고 싶은지 속성값으로 지정한다.

예로 들어 print(round(3.141592, 2))로 작성하면 3.141592의 소숫점 아래 두번째 자리에서 반올림한 값을 반영하고 싶다는 뜻이고 그 출력값은 3.14가 된다. (참고로 print(round(3.15, 1))의 값은 3.2로 출력된다.)

 

- 올림: math.ceil()

사용법은 round와 유사. 단 자릿수를 설정할 수 없다. 

 

- 내림: math.truncate(), math.floor()

truncate는 0의 방향으로 내림을 하고, floor는 일반적으로 알고있는 내림을 한다.

예로 들어

math.truncate(-3.14)는 -3을 출력하고

math.floor(3.14)sms -4를 출력한다.

 

- 나눗셈: divmod(v1, v2) 

몫과 나머지를 구하는 또다른 나눗셈 방법 중 하나. 큰 수의 나눗셈을 할 때 속도면에서 //나 %보다 좋다.

튜플값으로 (몫, 나머지)를 반환한다.