Try to 개발자 EthanJ의 성장 로그

Python Operator 파이썬 연산자 본문

CS & DS/Basic Python with Data Crawling

Python Operator 파이썬 연산자

EthanJ 2022. 10. 6. 18:31

> Python Operator 파이썬 연산자

  • 산술 연산: +, -, *, /, //(몫), %(나머지)
  • 비교 연산: ==, !=, <=, >=, <, >
  • 논리 연산: and, or
  • 할당 연산: =, +=, -=, *=. /=, %=

1. 산술 연산자 : 숫자를 계산하기 위한 문법

# 덧셈: +

# 정수 + 정수 == 정수
10 + 3
13

 

# 실수 + 실수 == 실수
13.3 + 2.4

#floating point 문제로 정확한 표기 불가능
15.700000000000001

 

# 정수 + 실수 == 실수 (type promotion)
10 + 3.4
13.4

 

# 뺄셈: -

# jupyter notebook은 print() 함수를 사용하지 않을 시 last line의 결과만 출력한다.
# 모든 line의 결과를 화면에 보여주려면 매 line마다 print() 함수를 사용해야 한다.
10 - 3
3 - 7.7
-4.7

 

print(10 - 3)
print(3 - 7.7)
7
-4.7

 

# 나눗셈: /

# Python만 정수 / 정수 > 실수 출력
# Java, C++등 대다수 언어는 정수 / 정수 > 정수 출력
print(3 / 3)
print(7 / 2)
1.0
3.5

 

# 곱셈: *

print(3 * 4)
print(-3 * 5)
12
-15

 

# Python에서도 사칙연산의 우선순위를 괄호()로 조절할 수 있다
print(3 - 4 * 5)
print((3 - 4) * 5)

# 사칙연산에는 원래 덧셈+, 뺄셈-밖에 없었다
# 덧셈을 줄여서 곱셈*으로 표현했기 때문에 곱셈을 먼저 풀어서 계산해야 한다
-17
-5

 

# 정수 몫 반환: //

print(5 / 4)
print(5 // 4)
1.25
1

 

# 나눗셈의 결과보다 작은 정수중에 가장 큰 정수
print(-5 / 4)
print(-5 // 4)
# 소수부 버림 아님 주의!
-1.25
-2

 

# 정수 몫을 구하고 나머지 반환: %

print(5 % 4)
print(-5 % 4)

# 음수의 나눗셈에는 사용 X
1
3

 

# 지수: **

print(2 ** 3)
# 제곱근, 세제곱근등도 계산 가능
print(2 ** 0.5)
8
1.4142135623730951

 

2. 비교 연산자

- 비교 연산의 결과는 숫자 type이 아닌 bool type

 

bool type

  1. True: !=0인 숫자, 참인 조건식 등
  2. False: 0, 거짓인 조건식 등

    (Python은 T, F 대문자 표기)

 

  • 값에 대한 비교: ==, !=
  • 크기에 대한 비교: >, <, >=, <=

 

# 두 값이 같은 지 비교: ==

print(1 == 1.0)
# (z == z.0) > 비교"연산"자 > type promotion 발생 > True 출력 
print(type(1), type(1.0))
# z와 z.0의 type은 다름 (z는 정수)
True
<class 'int'> <class 'float'>

 

# 두 값이 다른 지 비교: !=

# 두 값이 다르면 > True, 두 값이 같으면 > False
type(0) != type(0.0)
True

 

# 두 값의 크기를 비교: >=, <=, <, >

2 >= 3
False

 

 

#True(bool type) vs "True"(str type)
print(True)
print("True")
print("\n")

print((2 == 2) == True)
print((2 == 2) == "True")
print("\n")

print(type(True), type("True"))
True
True


True
False


<class 'bool'> <class 'str'>

 

3. 논리연산자

- 여러 개의 조건식을 활용하기 위한 연산자

- bool type 결과 반환 > True, False

 

### 3. 논리연산자
    - 여러 개의 조건식을 활용하기 위한 연산자
    - bool type 결과 반환 > True, False
# and 연산자: (조건식1) and (조건식2) 
# > 둘 다 True > True
# > 하나라도 False > False

print(10 < 12 and 0 > -3) # True and True > True
print(10 < 12 and 0 < -3) # True and False > False
print(10 > 12 and 0 < -3) # False and False > False
True
False
False

 

# or 연산자: (조건식1) or (조건식2)
# > 하나라도 True > True
# > 둘 다 False > False

print(10 < 12 or 0 > -3) # True or True > True
print(10 < 12 or 0 < -3) # True or False > True
print(10 > 12 or 0 < -3) # False or False > False
True
True
False

 

# 자료의 참, 거짓 판단 함수 > bool(자료)

print(bool(10))
print(bool(0))
print(bool(0.0))
print(bool(-23))
# data != 0 > True
True
False
False
True

 

4. 할당연산자

- 변수 할당

- 누적 연산

 

# 변수명(l-value)에 변수값(r-value)를 할당(==초기화==저장)하는 연산자: =

# x에 10을 할당/ 초기화/ 저장
x = 10
x
10

 

# 숫자형의 누적 합계: +=

# 변수 result 에 누적합 저장
result = 0

result = result + x
result
10

 

result = 0

result += x
result
# (a = a + b) == (a += b)
10

 

# 숫자형의 누적 차: -=

result -= 5
result
5

 

# 누적 곱: *=

result *= 3
result
15

 

# 누적 몫: /=
# 누적 나머지: %=

result = 10

result /= 1.4
print(result)

result %= 2
print(result)

# (실수 %= 실수) 가능!  
result %= 0.3
print(result)
7.142857142857143
1.1428571428571432
0.24285714285714327

 

> 연습문제 

  • 홍길동의 시험 성적 평균 구하기
  •  영어 80점, 국어 72점, 수학 90점, 사회 66점
eng = 80
kor = 72
math = 90
soc = 66
# 총합 구해서 변수 total에 저장
total = eng + kor + math + soc
# 평균 구해서 avg 변수에 저장
avg = total / 4
# print문을 이용해 총합과 평균 출력
print("총합", total)
print("평균", avg)
총합 308
평균 77.0
Comments