-
2. 숫자 계산하기Python/Grammar 2022. 11. 28. 12:52
# 정수 계산하기
사칙연산하기: + - * /
>>> 10 + 1 11
>>> 10 / 2 5.0 # 파이썬3은 몫으로 완전히 나누어떨어져도 5.0과 같이 실수가 나옴
버림 나눗셈 몫 구하기: //
>>> 7 // 3 2 >>> 6 // 3 2
나눗셈 나머지 구하기: %
>>> 3 % 1 0
거듭제곱 구하기: **
>>> 3 ** 3 27
값을 정수로 만들기
: integer(정수)를 의미하는 int를 사용한다.
- int(숫자)
- int(계산식)
- int(문자열)
>>> int('500') 500
객체의 자료형 알아내기
- type(값)
>>> type(500) <class 'int'>
몫과 나머지 함께 구하기
: divmod를 사용해 피제수를 제수로 나누면 튜플 형태로 몫과 나머지가 반환된다.
- divmod(피제수, 제수) -> (몫, 나머지)
>>> divmod(10, 3) (3, 1)
# 실수 계산하기
실수와 정수를 함께 계산하기
: 표현 범위가 넓은 실수로 계산된다.
>>> 1.1 * 5 5.5
값을 실수로 만들기
: floating point(부동소수점)을 의미하는 float을 사용한다.
- float(숫자)
- float(계산식)
- float(문자열)
>>> float(1) 1.0 >>> float(3 + 1) 4.0 >>> float('6') 6.0
# 괄호 사용하기
: 연산자 우선순위에 따라 곱셈, 나눗셈은 덧셈, 뺄셈보다 먼저 계산한다. 덧셈, 뺄셈을 우선순위로 두기 위해서는 괄호를 사용한다.
>>> (1 + 2) * 3 9
연산자 우선순위
: 사칙연산 이외에도 다양한 연산자에 대한 우선순위가 파이썬 공식문서 6.17에 정리되어 있다.
https://docs.python.org/ko/3/reference/expressions.html#operator-precedence
'Python > Grammar' 카테고리의 다른 글
6. 문자열 사용하기 (0) 2022.11.30 5. 불과 비교, 논리 연산자 알아보기 (0) 2022.11.30 4. 출력 방법 알아보기 (0) 2022.11.29 3. 변수와 입력 사용하기 (0) 2022.11.29 1. 기본 문법 (0) 2022.11.28