[Python] 2. 파이썬 연산자

강미진·2023년 4월 9일

연산자 기초

  • 연산자란? result = data1 + data2
  • 연산자 종류
    • 산술 연산자 : +,=,*,/,%(나머지),//(몫),**(제곱)
    • 할당 연산자: =,+=,-=,*=,/=,%=,//=
    • 비교 연산자 : >,>=,<,<=,==,!=(같지 않다)
    • 논리 연산자 : and, or, not

산술 연산자

  • 실수랑 실수를 계산하면 정수가 나와도 실수 타입이 된다.
  • 문자열을 통한 덧셈은 가능하지만 문자열을 통한 뺄셈은 불가능하다.
    • 'hello' + 'world' = 'hello world'
str1="hi "
result=str1*5
print('result " {}'.format(result))
num1 = 10
num2 = 3
result = num1/num2
print('result : %.2f' %result)
print(type(result))
result " hi hi hi hi hi 
result : 3.33
<class 'float'>

divmod{}

divmod() 함수를 사용하면 나머지와 몫을 동시에 구할수 있다.

num1= 10
num2 =3
result = divmod(num1, num2)
print('result: {}' .format(result))
print('몫: {}'.format(result[0]))
print('나머지: {}'.format(result[1]))
result: (3, 1)
몫: 3
나머지: 1

(몫, 나머지) 로 결과가 나온다.

거듭제곱 연산자(**)

num1 = 4
num2 = 2
oper1 = num1 ** num2
print('result :  {}'.format(oper1))
result :  16

거듭제곱 연산자를 활용해 제곱근을 구할 수 있다.

num1 = 4
num2 = 2
oper2 = num1 **(1/num2)
print('result : %.2f' %oper2)
result : 2.00

sqrt()

sqrt() 함수를 이용해 제곱근을 구할 수 있다.

import math
print('2의 제곱근 %f' % math.sqrt(2))
print('2의 제곱근 %.2f' % math.sqrt(2))
print('4의 제곱근 : %f' %math.sqrt(4))
print('4의 제곱근 : %.2f' %math.sqrt(4))
2의 제곱근 1.414214
2의 제곱근 1.41
4의 제곱근 : 2.000000
4의 제곱근 : 2.00

그러나 3제곱근 이상은 n**(1/m) 을 사용해야 한다.

pow()

pow() 함수를 이용해 거듭제곱을 구할 수 있다.

import math
print('2의 3제곱 %f' % math.pow(2, 3))
print('2의 4제곱 %f' %math.pow(2,4))
2의 3제곱 8.000000
2의 4제곱 16.000000

복합연산자

  • += : 덧셈 연산 후 할당
  • -= : 뺄셈 연산 후 할당
  • *= : 곱셈 연산 후 할당
  • /= : 나누기 연산 후 할당
  • %= : 나머지 연산 후 할당
  • //= : 몫 연산 후 할당
num = 10
num += 3  # num = num + 3
print('num : {}'.format(num))
num : 13

비교연산자

  • 문자 비교 : 아스키 코드 값을 활용한다.
cha1 = 'A' #65
cha2 = 'S' #83
print('\'{}\' > \'{}\' : {}' .format(cha1, cha2,(cha1 > cha2)))
'A' > 'S' : False
  • 문자와 아스키코드 변화 : ord함수, chr함수
print('\'A\' -> {}'.format(ord('A')))
print('\'A\' -> {}'.format(ord('a')))
print('\'A\' -> {}'.format(ord('S')))
print(' 65 -> {}' .format(chr(65)))
print(' 83 -> {}' .format(chr(83)))
'A' -> 65
'A' -> 97
'A' -> 83
 65 -> A
 83 -> S
  • 문자열 비교는 문자열 자체를 비교하기 때문에 크고 작고는 비교할 수 없다. 같거나 같지 않다만 비교할 수 있다.
str1 = 'Hello'
str2 = 'Hello'
print('{}=={} : {}'.format(str1, str2, (str1==str2)))
print('{}!={} : {}'.format(str1, str2, (str1!=str2)))
Hello==Hello : True
Hello!=Hello : False

논리 연산자

  • 논리 연산자란, 피연산자의 논리(True, False)를 이용해 연산하는 것을 말한다.
  • and :양쪽의 연산이 모두 true가 나와야 true가 나온다
  • or : 양쪽의 연산자 중 하나만 true여도 true 가 나온다
  • not : 현재의 상태를 부정한다. True를 부정하면 False. False를 부정하면 True
print('{} and {} : {}'.format(True, True, (True and False)))
print('{} and {} : {}'.format(False, True, (False and True)))
print('{} and {} : {}'.format(True, False, (True and False)))
print('{} and {} : {}'.format(False, False, (False and False)))
-----------------------------------------------------------------
print('{} or {} : {}'.format(True, True, (True or False)))
print('{} or {} : {}'.format(False, True, (False or True)))
print('{} or {} : {}'.format(True, False, (True or False)))
print('{} or {} : {}'.format(False, False, (False or False)))
-----------------------------------------------------------------
print('not {} : {}'.format(True,(not True)))
print('not {} : {}'.format(False,(not False)))
True and True : False
False and True : False
True and False : False
False and False : False
-------------------------
True or True : True
False or True : True
True or False : True
False or False : False
-------------------------
not True : False
not False : True

< Operator 모듈 >

import operator 를 사용해 연산자를 쉽게 작성할 수 있다.

import operator
num1 = 8
num2 = 3
print('{} + {} : {} '.format(num1, num2, operator.add(num1, num2)))
print('{} - {} : {} '.format(num1, num2, operator.sub(num1, num2)))
print('{} * {} : {} '.format(num1, num2, operator.mul(num1, num2)))
print('{} / {} : {} '.format(num1, num2, operator.truediv(num1, num2)))
print('{} % {} : {} '.format(num1, num2, operator.mod(num1, num2)))
print('{} // {} : {} '.format(num1, num2, operator.floordiv(num1, num2)))
print('{} ** {} : {} '.format(num1, num2, operator.pow(num1, num2)))
print('{} == {} : {}'.format(num1, num2, operator.eq(num1, num2)))
print('{} != {} : {}'.format(num1, num2, operator.ne(num1, num2)))
print('{} > {} : {}'.format(num1, num2, operator.gt(num1, num2)))
print('{} >= {} : {}'.format(num1, num2, operator.ge(num1, num2)))
print('{} < {} : {}'.format(num1, num2, operator.lt(num1, num2)))
print('{} <= {} : {}'.format(num1, num2, operator.le(num1, num2)))
8 + 3 : 11 
8 - 3 : 5 
8 * 3 : 24 
8 / 3 : 2.6666666666666665 
8 % 3 : 2 
8 // 3 : 2 
8 ** 3 : 512 
8 == 3 : False
8 != 3 : True
8 > 3 : True
8 >= 3 : True
8 < 3 : False
8 <= 3 : False
profile
g'day mate

0개의 댓글