공부하기/Python

Python 기초) 연산자

hyunjicraft 2020. 12. 9. 19:25

Python도 일반적인 연산자(+, *, -, =, % 등)들을 사용할 수 있다.

익숙하지 않은 연산자는 다음과 같다.

 

제곱 연산자 **

print(3**2)
# 9

 

몫 연산자 //

print(10//2)
# 5

 

& 연산자와 | 연산자는 각각 and와 or로도 사용가능하다.

 

일반적인 수학 함수 예제

print(abs(-10)) 
# 10
print(pow(4, 2)) 
# 4 ^ 2 = 16

print(max(5, 12)) 
# 12
print(min(10, 6, 13)) 
# 6

print(round(3.14)) 
# 3
print(round(8.9)) 
# 9

 

math 라이브러리를 import하면 아래 함수도 사용가능하다.

from math import *

print(floor(3.99)) # 3
print(ceil(3.14)) #4
print(sqrt(16)) #4 제곱근

 

 

random 라이브러리

from random import *

print(random()) 
# 0.0부터 1.0미만의 임의의 값 생성

print(random() * 10)
# 0.0부터 10.0미만의 임의의 값 생성

print(int(random() * 10) + 1) 
# 1부터 10이하의 임의의 정수 생성

print(randrange(1, 100)) 
#1 ~ 100 미만의 임의의 정수, 100은 제외
print(randint(1, 45)) 
#1 ~ 45 이하의 임의의 정수, 45 포함