{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "***\n", "***\n", "# 5. 파이썬의 각종 연산자\n", "***\n", "***" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "***\n", "## 1 산술 연산자\n", "***" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "| 연산자 | 우선순위 | 설명 | 결합순서 |\n", "|:------:|:------:|:-----------------:|:-----------:|\n", "| +, - | 1 | 단항 연산자 | - | \n", "| ** | 2 |지수 연산자 | 왼쪽 <- 오른쪽 | \n", "| *,/,%,// | 3 |곱하기,나누기,나머지,몫 | 왼쪽 -> 오른쪽 | \n", "| +, - | 4 |더하기,빼기 | 왼쪽 -> 오른쪽 |" ] }, { "cell_type": "code", "execution_count": 1, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "8\n", "1\n", "1\n" ] } ], "source": [ "print(2 ** 3)\n", "print(5 % 2)\n", "print(-5 % 2)" ] }, { "cell_type": "code", "execution_count": 2, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "8\n", "8.0\n" ] } ], "source": [ "print(3 + 5)\n", "print(3 + 5.0) # 정수 + 실수의 결과는 실수" ] }, { "cell_type": "code", "execution_count": 3, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "2.5\n", "2.5\n", " \n" ] } ], "source": [ "a = 5 / 2.0\n", "b = 5 / 2\n", "print(a) # 정수 / 실수의 결과\n", "print(b) # 정수 / 정수의 결과 <-- python 3 부터는 /의 결과는 언제나 실수\n", "\n", "print(type(a), type(b))" ] }, { "cell_type": "code", "execution_count": 4, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "1.6666666666666667 2\n", "(1, 2)\n" ] } ], "source": [ "a = 5 / 3\n", "b = 5 % 3\n", "\n", "print(a, b)\n", "print(divmod(5,3))\n", "# 1 2\n", "# (1, 2)" ] }, { "cell_type": "code", "execution_count": 1, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "1\n", "1.0\n" ] } ], "source": [ "print(5 // 3) # Floor Division\n", "print(5 // 3.0) # Floor Division - Floor Division은 '정수 // 정수'와 '정수 // 실수'의 결과 다름 " ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "- 단항 연산자(-)의 우선순위가 이항 연산자(/)의 우선순위보다 높다" ] }, { "cell_type": "code", "execution_count": 6, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "-1.75\n", "-1.75\n" ] } ], "source": [ "print(-7/4) # -7을 4로 나눈다\n", "print(-(7/4))" ] }, { "cell_type": "code", "execution_count": 7, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "14\n", "20\n" ] } ], "source": [ "print(2 + 3 * 4)\n", "print((2 + 3) * 4)" ] }, { "cell_type": "code", "execution_count": 8, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "4.0\n" ] } ], "source": [ "print(4 / 2 * 2)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "- ** 연산자의 결합순서는 오른쪽에서 왼쪽" ] }, { "cell_type": "code", "execution_count": 9, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "512\n", "64\n" ] } ], "source": [ "print(2 ** 3 ** 2)\n", "print((2 ** 3) ** 2)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "***\n", "## 2 관계 연산자\n", "***" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "- 관계 연산자: 객체가 지닌 값의 크기(대소)를 비교하여 True 또는 False를 반환함" ] }, { "cell_type": "code", "execution_count": 10, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "False\n", "True\n", "False\n", "True\n", "True\n" ] } ], "source": [ "print(6 == 9)\n", "print(6 != 9)\n", "print(1 > 3)\n", "print(4 <= 5)\n", "\n", "a = 5\n", "b = 10\n", "print(a < b)" ] }, { "cell_type": "code", "execution_count": 11, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "True\n" ] } ], "source": [ "a = 5\n", "b = 10\n", "print(0 < a < b)" ] }, { "cell_type": "code", "execution_count": 12, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "True\n" ] } ], "source": [ "a = 5\n", "b = 10\n", "print(0 < a and a < b)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "- 문자열, 튜플, 리스트의 관계 연산 비교는 일반 사전 순서 " ] }, { "cell_type": "code", "execution_count": 20, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "False\n", "True\n", "False\n" ] } ], "source": [ "print('abcd' > 'abd') \n", "print((1, 2, 4) < (2, 1, 0)) \n", "print([1, 3, 2] < [1, 2, 3])" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "- 사전에 대해서는 대소관계 평가하는 관계연산 불가" ] }, { "cell_type": "code", "execution_count": 21, "metadata": {}, "outputs": [ { "ename": "TypeError", "evalue": "'>' not supported between instances of 'dict' and 'dict'", "output_type": "error", "traceback": [ "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m", "\u001b[0;31mTypeError\u001b[0m Traceback (most recent call last)", "\u001b[0;32m\u001b[0m in \u001b[0;36m\u001b[0;34m()\u001b[0m\n\u001b[0;32m----> 1\u001b[0;31m \u001b[0mprint\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m{\u001b[0m\u001b[0;36m0\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;36m0\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0;36m1\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;36m1\u001b[0m\u001b[0;34m}\u001b[0m \u001b[0;34m>\u001b[0m \u001b[0;34m{\u001b[0m\u001b[0;36m2\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;36m2\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0;36m3\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;36m3\u001b[0m\u001b[0;34m}\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m", "\u001b[0;31mTypeError\u001b[0m: '>' not supported between instances of 'dict' and 'dict'" ] } ], "source": [ "print({0:0, 1:1} > {2:2, 3:3})" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "- 사전에 대해 내용이 동일한지 알아보는 관계연산자는 수행가능함" ] }, { "cell_type": "code", "execution_count": 22, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "False\n", "True\n" ] } ], "source": [ "print({0:0, 1:1} == {2:2, 3:3})\n", "print({0:0, 1:1} == {0:0, 1:1})" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "- 서로 다른 자료형간의 크기 관계 비교\n", " - Python 3 버전에서는 지원하지 않음" ] }, { "cell_type": "code", "execution_count": 24, "metadata": {}, "outputs": [ { "ename": "TypeError", "evalue": "'<' not supported between instances of 'int' and 'str'", "output_type": "error", "traceback": [ "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m", "\u001b[0;31mTypeError\u001b[0m Traceback (most recent call last)", "\u001b[0;32m\u001b[0m in \u001b[0;36m\u001b[0;34m()\u001b[0m\n\u001b[0;32m----> 1\u001b[0;31m \u001b[0mprint\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;36m9999999999999999999999\u001b[0m \u001b[0;34m<\u001b[0m \u001b[0;34m'abc'\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m", "\u001b[0;31mTypeError\u001b[0m: '<' not supported between instances of 'int' and 'str'" ] } ], "source": [ "print(9999999999999999999999 < 'abc')" ] }, { "cell_type": "code", "execution_count": 25, "metadata": {}, "outputs": [ { "ename": "TypeError", "evalue": "'<' not supported between instances of 'dict' and 'list'", "output_type": "error", "traceback": [ "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m", "\u001b[0;31mTypeError\u001b[0m Traceback (most recent call last)", "\u001b[0;32m\u001b[0m in \u001b[0;36m\u001b[0;34m()\u001b[0m\n\u001b[0;32m----> 1\u001b[0;31m \u001b[0mprint\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m{\u001b[0m\u001b[0;36m3\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;36m2\u001b[0m\u001b[0;34m}\u001b[0m \u001b[0;34m<\u001b[0m \u001b[0;34m[\u001b[0m\u001b[0;36m1\u001b[0m\u001b[0;34m,\u001b[0m\u001b[0;36m2\u001b[0m\u001b[0;34m,\u001b[0m\u001b[0;36m3\u001b[0m\u001b[0;34m]\u001b[0m \u001b[0;34m<\u001b[0m \u001b[0;34m(\u001b[0m\u001b[0;36m1\u001b[0m\u001b[0;34m,\u001b[0m\u001b[0;36m2\u001b[0m\u001b[0;34m,\u001b[0m\u001b[0;36m3\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m", "\u001b[0;31mTypeError\u001b[0m: '<' not supported between instances of 'dict' and 'list'" ] } ], "source": [ "print({3:2} < [1,2,3] < (1,2,3))" ] }, { "cell_type": "code", "execution_count": 26, "metadata": {}, "outputs": [ { "ename": "TypeError", "evalue": "'<' not supported between instances of 'str' and 'int'", "output_type": "error", "traceback": [ "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m", "\u001b[0;31mTypeError\u001b[0m Traceback (most recent call last)", "\u001b[0;32m\u001b[0m in \u001b[0;36m\u001b[0;34m()\u001b[0m\n\u001b[1;32m 1\u001b[0m \u001b[0mL\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0;34m[\u001b[0m\u001b[0;36m1\u001b[0m\u001b[0;34m,\u001b[0m\u001b[0;36m2\u001b[0m\u001b[0;34m,\u001b[0m\u001b[0;36m3\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0;34m'abc'\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0;34m'a'\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0;34m'z'\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0;34m(\u001b[0m\u001b[0;36m1\u001b[0m\u001b[0;34m,\u001b[0m\u001b[0;36m2\u001b[0m\u001b[0;34m,\u001b[0m\u001b[0;36m3\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0;34m[\u001b[0m\u001b[0;36m1\u001b[0m\u001b[0;34m,\u001b[0m\u001b[0;36m2\u001b[0m\u001b[0;34m,\u001b[0m\u001b[0;36m3\u001b[0m\u001b[0;34m]\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0;34m{\u001b[0m\u001b[0;36m1\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;36m2\u001b[0m\u001b[0;34m}\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0;34m[\u001b[0m\u001b[0;34m'abc'\u001b[0m\u001b[0;34m]\u001b[0m\u001b[0;34m]\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m----> 2\u001b[0;31m \u001b[0mL\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0msort\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m\u001b[1;32m 3\u001b[0m \u001b[0mprint\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mL\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 4\u001b[0m \u001b[0;31m# [1, 2, 3, {1: 2}, [1, 2, 3], ['abc'], 'a', 'abc', 'z', (1, 2, 3)]\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n", "\u001b[0;31mTypeError\u001b[0m: '<' not supported between instances of 'str' and 'int'" ] } ], "source": [ "L = [1,2,3, 'abc', 'a', 'z', (1,2,3), [1,2,3], {1:2}, ['abc']]\n", "L.sort()\n", "print(L)\n", "# [1, 2, 3, {1: 2}, [1, 2, 3], ['abc'], 'a', 'abc', 'z', (1, 2, 3)]" ] }, { "cell_type": "code", "execution_count": 27, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "True\n", "True\n", "False\n", "False\n", "True\n" ] } ], "source": [ "x = [1,2,3]\n", "y = [1,2,3]\n", "z = y\n", "\n", "print(x == y)\n", "print(x == z)\n", "print(x is y)\n", "print(x is z)\n", "print(y is z)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "![image](../images/objectIdentity.png)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "- [문제] 아래 예제를 통하여 위 그림의 오류를 지적하시오" ] }, { "cell_type": "code", "execution_count": 29, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "True\n", "True\n" ] } ], "source": [ "print(x[0] == y[0])\n", "print(x[0] is y[0])" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "***\n", "## 3 논리 연산자 (or 부울 연산자)\n", "***" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "- 피연산자의 값으로 진리값인 True 또는 False을 취하여 논리 적인 계산을 수행하는 연산자\n", " - and\n", " - or\n", " - not\n", "- [주의] 논리 연산자 자체가 값을 반환하지는 않는다. \n", " - 대신, 논리 연산을 따라 최종적으로 평가(Evaluation)되어진 값이 반환된다." ] }, { "cell_type": "code", "execution_count": 32, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "True\n", "True\n" ] } ], "source": [ "a = 20\n", "b = 30\n", "print(a > 10 and b < 50)\n", "print(a > 10 or b < 50)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "- 진리값에 해당하는 True와 False는 다른 사칙연산자를 만나면 다음과 같이 평가됨\n", " - True: 1\n", " - False: 0" ] }, { "cell_type": "code", "execution_count": 26, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "2\n", "1\n", "0\n", "75\n" ] } ], "source": [ "print(True + 1)\n", "print(False + 1)\n", "print(False * 75)\n", "print(True * 75)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "- bool() 내장 함수를 이용해서 수치 값을 진리 값으로 교환 가능" ] }, { "cell_type": "code", "execution_count": 34, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "False\n", "True\n", "True\n", "True\n", "\n", "False\n", "True\n", "True\n" ] } ], "source": [ "print(bool(0)) # 정수 0은 거짓\n", "print(bool(1))\n", "print(bool(100))\n", "print(bool(-100))\n", "print()\n", "print(bool(0.0)) # 실수 0.0은 거짓\n", "print(bool(0.1))\n", "print(bool(0.00000000000000000000000000000000000000000001))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "- 값이 없는 빈 객체나 None 객체는 False로 평가됨" ] }, { "cell_type": "code", "execution_count": 28, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "True\n", "False\n", "\n", "False\n", "True\n", "\n", "False\n", "True\n", "\n", "False\n", "True\n", "\n", "False\n" ] } ], "source": [ "print(bool('abc'))\n", "print(bool('')) # 빈 문자열은 거짓 \n", "print()\n", "print(bool([])) # 공 리스트는 거짓\n", "print(bool([1,2,3]))\n", "print()\n", "print(bool(())) # 공 튜플은 거짓\n", "print(bool((1,2,3)))\n", "print()\n", "print(bool({})) # 공 사전은 거짓\n", "print(bool({1:2}))\n", "print()\n", "print(bool(None)) # None 객체는 거짓" ] }, { "cell_type": "code", "execution_count": 37, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "2\n", "0\n", "\n", "2\n", "1\n", "\n", "1\n", "()\n", "[]\n" ] } ], "source": [ "print(1 and 2)\n", "print(1 and 0)\n", "print()\n", "\n", "print(0 or 2)\n", "print(1 or 0)\n", "print()\n", "\n", "print([] or 1) # [] 거짓\n", "print([] or ()) # [], () 거짓\n", "print([] and 1) # [] 거짓이므로 1은 참조할 필요 없음" ] }, { "cell_type": "code", "execution_count": 38, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[[]]\n", "[{}]\n", "1\n" ] } ], "source": [ "print([[]] or 1) # [[]] 참으로 간주\n", "print([{}] or 1) # [{}] 참으로 간주\n", "print('' or 1) # 빈 문자열('')은 거짓" ] }, { "cell_type": "code", "execution_count": 31, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "False\n", "False\n", "False\n" ] } ], "source": [ "print(not(True))\n", "print(not(1 and 2))\n", "print(not('' or 1))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "***\n", "## [참고] 연산자 우선 순위 표\n", "***" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "- 연산자 우선 순위 표: https://wikidocs.net/1165\n", "- 실제 코드 개발을 할 때에는 연산자 우선 순위에 많은 의존 없이 괄호(())를 적절하게 사용하여 코드의 가독성을 높이는 것이 좋다." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "

참고 문헌: 파이썬(열혈강의)(개정판 VER.2), 이강성, FreeLec, 2005년 8월 29일

" ] } ], "metadata": { "kernelspec": { "display_name": "Python 3", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.6.8" } }, "nbformat": 4, "nbformat_minor": 1 }