diff --git a/pythonSource/Basic/exam1.ipynb b/pythonSource/Basic/exam1.ipynb new file mode 100644 index 0000000..5f9411d --- /dev/null +++ b/pythonSource/Basic/exam1.ipynb @@ -0,0 +1,1513 @@ +{ + "cells": [ + { + "cell_type": "code", + "execution_count": 7, + "id": "327c097c", + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "10\n" + ] + } + ], + "source": [ + "a = 10\n", + "print(a)" + ] + }, + { + "cell_type": "code", + "execution_count": 8, + "id": "4929f0bd", + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Hello, World!\n" + ] + } + ], + "source": [ + "print(\"Hello, World!\")" + ] + }, + { + "cell_type": "code", + "execution_count": 12, + "id": "40c1b43b", + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "[1, 2, 3, 4, 5]\n" + ] + } + ], + "source": [ + "b = [1, 2, 3, 4, 5]\n", + "print(b)\n" + ] + }, + { + "cell_type": "markdown", + "id": "d5b219e7", + "metadata": {}, + "source": [ + "- control + enter = 현재 셀만 실행\n", + "- shift + enter = 현재 셀 실행 + 아래 빈 셀 추가" + ] + }, + { + "cell_type": "code", + "execution_count": 14, + "id": "c621c863", + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "True" + ] + }, + "execution_count": 14, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "a = True\n", + "a" + ] + }, + { + "cell_type": "code", + "execution_count": 22, + "id": "6af4a82e", + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "14\n", + "6\n", + "40\n", + "2.5\n", + "2\n", + "2\n", + "10000\n" + ] + } + ], + "source": [ + "a, b = 10, 4\n", + "a\n", + "b\n", + "# 사칙연산 (+, -, *, /, //, %)\n", + "print(a + b)\n", + "print(a - b)\n", + "print(a * b)\n", + "print(a / b)\n", + "print(a // b) # 몫만 남김\n", + "print(a % b) # 나머지 연산자, a를 b로 나눈 나머지를 구하는 연산자\n", + "print(a ** b)" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "97d1e1ad", + "metadata": {}, + "outputs": [ + { + "ename": "SyntaxError", + "evalue": "unterminated string literal (detected at line 2) (3330389451.py, line 2)", + "output_type": "error", + "traceback": [ + " \u001b[36mCell\u001b[39m\u001b[36m \u001b[39m\u001b[32mIn[28]\u001b[39m\u001b[32m, line 2\u001b[39m\n\u001b[31m \u001b[39m\u001b[31m- 홀따옴표 (') 또는 쌍따옴표 (\")로 감싸서 표현\u001b[39m\n ^\n\u001b[31mSyntaxError\u001b[39m\u001b[31m:\u001b[39m unterminated string literal (detected at line 2)\n" + ] + } + ], + "source": [ + "### 문자열 자료형\n", + "- 홀따옴표 (') 또는 쌍따옴표 (\")로 감싸서 표현\n", + "- 문자열 안에서 홀따옴표나 쌍따옴표를 사용\n", + "- 홀따옴표 (''') 또는 쌍따옴표 (\"\"\")로 감싸서 표현\n", + " \n", + " \n", + "msg = 'Hello, World!'\n", + "msg = \"Hello, World!\"\n", + "msg = 'Hello, \"World!\"'\n", + "msg = \"Hello, 'World!'\"\n", + "msg = '''Hello\n", + " World!'''\n", + "msg = \"\"\"Hello, \n", + " World!\"\"\"" + ] + }, + { + "cell_type": "code", + "execution_count": 31, + "id": "9c73bd1b", + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "'Life is too shortyou need python'" + ] + }, + "execution_count": 31, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "multiline = \"Life is too short\" \\\n", + "\"you need python\"\n", + "multiline" + ] + }, + { + "cell_type": "code", + "execution_count": 38, + "id": "0900fed7", + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "\n", + "Life is too short \n", + "you need python\n", + "\n" + ] + } + ], + "source": [ + "multiline = '''\n", + "Life is too short \n", + "you need python\n", + "'''\n", + "print(multiline)" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "cb1fc46d", + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "'Python is fun!'" + ] + }, + "execution_count": 40, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "# 문자열 연산\n", + "head = \"Python\"\n", + "tail = \" is fun!\"\n", + "head + tail\n", + "\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "5259347d", + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "'PythonPython'" + ] + }, + "execution_count": 42, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "# 문자열 반복\n", + "head * 2 " + ] + }, + { + "cell_type": "code", + "execution_count": 44, + "id": "faad4d62", + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "6" + ] + }, + "execution_count": 44, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "# len() 함수는 문자열의 길이를 구하는 함수입니다.\n", + "len(head)" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "da78c7ec", + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "'s'" + ] + }, + "execution_count": 48, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "# 문자열 인덱싱과 슬라이싱\n", + "a = \"Life is too short, you need Python\"\n", + "a[0] # 문자열의 첫 번째 문자\n", + "a[12] # 문자열의 13번째 문자\n", + "a[-1] # 문자열의 마지막 문자\n", + "a[-2] # 문자열의 끝에서 두 번째 문자\n", + "a[0:4] # 문자열의 첫 번째 문자부터 네 번째 문자까지 (0\n", + "a[19:] # 문자열의 20번째 문자부터 끝까지\n", + "a[:17] # 문자열의 처음부터 17번째 문자까지 (0~16)\n" + ] + }, + { + "cell_type": "code", + "execution_count": 51, + "id": "b34f4f42", + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Life is too short, you need Python\n", + "Life is too short, you need Pytho\n", + "short\n", + "on\n" + ] + } + ], + "source": [ + "# 슬라이싱 : 인덱싱을 이용해 문자열 분리\n", + "print(a[0:]) # 0 부터 끝까지\n", + "print(a[0:-1]) # 0 부터 -1까지(마지막 인덱싱 포함하지 않음)\n", + "print(a[12:17]) # 12 부터 17까지(마지막 인덱싱 포함하지 않음)\n", + "print(a[-2:]) # -2 부터 끝까지\n" + ] + }, + { + "cell_type": "code", + "execution_count": 53, + "id": "baa487b9", + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "20260512\n", + "Rainy\n" + ] + } + ], + "source": [ + "a = '20260512Rainy'\n", + "\n", + "# 날짜\n", + "print(a[0:8])\n", + "# 날씨\n", + "print(a[8:15])" + ] + }, + { + "cell_type": "code", + "execution_count": 62, + "id": "c10a8379", + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "현재 온도는 20 도입니다.\n", + "현재 온도는 20도 입니다.\n", + "현재 온도는 20도 입니다.\n", + "현재 온도는 20도 입니다.\n" + ] + } + ], + "source": [ + "a = 20\n", + "#print(\"현재 온도는 \" + a + \"도입니다.\") # TypeError: can only concatenate str (not \"int\") to str\n", + "print(\"현재 온도는\",a, \"도입니다.\") # str()\n", + "print(\"현재 온도는 %d도 입니다.\" % a) # str() 함수를 이용하여 정수 a를 문자열로 변환하여 출력\n", + "print(\"현재 온도는 {}도 입니다.\".format(a)) # str() 함수를 이용하여 정수 a를 문자열로 변환하여 출력\n", + "print(f\"현재 온도는 {a}도 입니다.\") # str() 함수를 이용하여 정수 a를 문자열로 변환하여 출력\n" + ] + }, + { + "cell_type": "markdown", + "id": "bca24b2c", + "metadata": {}, + "source": [ + "### 함수 : 이미 기능을 가지고 있음\n", + "- len() : 문자열의 길이를 구하는 함수\n", + "- str() : 정수나 실수를 문자열로 변환하는 함수\n", + "- int() : 문자열을 정수로 변환하는 함수\n", + "- float() : 문자열을 실수로 변환하는 함수\n" + ] + }, + { + "cell_type": "code", + "execution_count": 63, + "id": "a2a40240", + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "2" + ] + }, + "execution_count": 63, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "a = 'habby'\n", + "a.count('b')" + ] + }, + { + "cell_type": "code", + "execution_count": 65, + "id": "09cdebd0", + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "2\n", + "2\n" + ] + } + ], + "source": [ + "# find() : 문자열에서 특정 문자열이 처음으로 등장하는 위치를 반환하는 함수입니다. 만약 찾는 문자열이 존재하지 않으면 -1을 반환합니다.\n", + "# a.find('b')\n", + "print(a.find('b'))\n", + "print(a.index('b')) # find()와 index()는 거의 동일하지만, index()는 찾는 문자열이 존재하지 않을 때 ValueError 예외를 발생시킵니다. find()는 -1을 반환하는 반면, index()는 예외를 발생시키므로, 찾는 문자열이 반드시 존재해야 하는 경우에는 index()를 사용하는 것이 좋습니다. " + ] + }, + { + "cell_type": "code", + "execution_count": 66, + "id": "2264a946", + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "apple,banana,cherry\n" + ] + } + ], + "source": [ + "#join() : 문자열을 연결하는 함수입니다. join() 함수는 문자열을 연결할 때 사용되며, 연결할 문자열들을 리스트나 튜플 등의 시퀀스 자료형으로 전달받습니다. join() 함수는 시퀀스 자료형의 각 요소를 문자열로 변환한 후, 지정된 구분자(separator)를 사용하여 연결된 문자열을 반환합니다. 예를 들어, \",\".join([\"apple\", \"banana\", \"cherry\"])는 \"apple,banana,cherry\"를 반환합니다. join() 함수는 문자열을 연결할 때 효율적이며, 여러 개의 문자열을 한 번에 연결할 때 유용하게 사용됩니다.\n", + "print(\",\".join([\"apple\", \"banana\", \"cherry\"]))\n", + "\n", + "\n" + ] + }, + { + "cell_type": "code", + "execution_count": 67, + "id": "3fc4ce33", + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "HELLO\n", + "hello\n" + ] + } + ], + "source": [ + "# 대소문자 변경 : upper() : 문자열을 모두 대문자로 변환하는 함수입니다. lower() : 문자열을 모두 소문자로 변환하는 함수입니다. capitalize() : 문자열의 첫 번째 문자를 대문자로 변환하고 나머지 문자를 소문자로 변환하는 함수입니다. title() : 문자열의 각 단어의 첫 번째 문자를 대문자로 변환하고 나머지 문자를 소문자로 변환하는 함수입니다.\n", + "print(\"hello\".upper()) # \"HELLO\"\n", + "print(\"HELLO\".lower()) # \"hello\"\n" + ] + }, + { + "cell_type": "code", + "execution_count": 69, + "id": "04065ada", + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + " Hello, World! \n", + "Hello, World!\n", + "Hello, World! \n", + " Hello, World!\n" + ] + } + ], + "source": [ + "# 공백 제거 : strip() : 문자열의 양쪽 끝에 있는 공백을 제거하는 함수입니다. lstrip() : 문자열의 왼쪽 끝에 있는 공백을 제거하는 함수입니다. rstrip() : 문자열의 오른쪽 끝에 있는 공백을 제거하는 함수입니다.\n", + "a = \" Hello, World! \"\n", + "print(a)\n", + "print(a.strip()) # \"Hello, World!\"\n", + "print(a.lstrip()) # \"Hello, World! \"\n", + "print(a.rstrip()) # \" Hello, World!\"\n", + "\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "840303d9", + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Life is too short\n" + ] + } + ], + "source": [ + "# replace() : 문자열에서 특정 문자열을 다른 문자열로 대체하는 함수입니다. replace() 함수는 원본 문자열에서 지정된 문자열을 찾아서 새로운 문자열로 대체한 결과를 반환합니다. 예를 들어, \"Hello, World!\".replace(\"World\", \"Python\")는 \"Hello, Python!\"을 반환합니다. replace() 함수는 원본 문자열을 변경하지 않고, 대체된 새로운 문자열을 반환하므로, 원본 문자열은 그대로 유지됩니다.\n", + "a = \"Life is too short\" \n", + "a.replace(\"Life\", \"Your leg\")\n", + "\n", + "print(a) # 원본 문자열은 변경되지 않음" + ] + }, + { + "cell_type": "code", + "execution_count": 75, + "id": "7114f4ab", + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "['a,', 'b,', 'c,', 'd,', 'e']" + ] + }, + "execution_count": 75, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "# split() : 문자열을 특정 구분자(separator)를 기준으로 나누어 리스트로 반환하는 함수입니다. split() 함수는 문자열을 나눌 때 사용되며, 구분자를 지정하지 않으면 공백을 기준으로 문자열을 나눕니다. 예를 들어, \"Hello, World!\".split(\",\")는 [\"Hello\", \" World!\"]를 반환합니다. split() 함수는 문자열을 나눌 때 효율적이며, 여러 개의 문자열을 한 번에 나눌 때 유용하게 사용됩니다.\n", + "\n", + "a.split() # 공백을 기준으로 문자열을 나눔\n", + "\n", + "b = \"a, b, c, d, e\"\n", + "b.split() # 리스트는 split() 함수를 사용할 수 없습니다. split() 함수는 문자열에서만 사용할 수 있습니다. 리스트를 문자열로 변환한 후에 split() 함수를 사용할 수 있습니다. 예를 들어, \",\".join(b).split(\",\")는 ['1', '2', '3', '4', '5']를 반환합니다.\n", + "\n" + ] + }, + { + "cell_type": "markdown", + "id": "c3b8118c", + "metadata": {}, + "source": [ + "# list 자료형\n", + "- [1, 3, 5, 7] \n", + "- 인덱스 번호를 가지고 있어 슬라이싱이 가능" + ] + }, + { + "cell_type": "code", + "execution_count": 81, + "id": "795cb215", + "metadata": {}, + "outputs": [], + "source": [ + "# 리스트 생성\n", + "a = []\n", + "b = [ 1, 3, 5, 7, 9 ]\n", + "c = list()\n", + "d = ['Life', 'is', 'too', 'short']\n", + "f = [ 1, 2, 'too', 'short']\n", + "g = [1, 2, ['life', 'is' ]]" + ] + }, + { + "cell_type": "code", + "execution_count": 84, + "id": "caf4c5ca", + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "3\n", + "too\n", + "['life', 'is']\n", + "['life', 'is']\n" + ] + } + ], + "source": [ + "# 인덱싱\n", + "print(b[1])\n", + "print(d[2])\n", + "print(g[2])\n", + "print(g[-1])\n" + ] + }, + { + "cell_type": "code", + "execution_count": 95, + "id": "379aa915", + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "4" + ] + }, + "execution_count": 95, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "# + 연결\n", + "a + b\n", + "b + d\n", + "\n", + "# * 반복\n", + "b * 2\n", + "\n", + "# 리스트 길이 구하기\n", + "len(d)" + ] + }, + { + "cell_type": "code", + "execution_count": 96, + "id": "7e58ae86", + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "[]\n", + "[]\n" + ] + } + ], + "source": [ + "print(a)\n", + "print(c)\n" + ] + }, + { + "cell_type": "code", + "execution_count": 98, + "id": "d5d35993", + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "['hello', 'world', 'hello', 'world']" + ] + }, + "execution_count": 98, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "# append() : 리스트에 요소를 추가하는 함수입니다. append() 함수는 리스트의 끝에 새로운 요소를 추가합니다. 예를 들어, a.append(10)은 리스트 a의 끝에 10을 추가합니다. append() 함수는 원본 리스트를 변경하며, 반환값은 없습니다.\n", + "a.append(\"hello\")\n", + "a.append(\"world\")\n", + "a\n", + "\n" + ] + }, + { + "cell_type": "code", + "execution_count": 101, + "id": "99d7f463", + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "[['hello', 'bye'], ['hello', 'bye']]" + ] + }, + "execution_count": 101, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "c.append(['hello', 'bye'])\n", + "c" + ] + }, + { + "cell_type": "code", + "execution_count": 102, + "id": "71e05f8d", + "metadata": {}, + "outputs": [], + "source": [ + "# 정렬" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "b2e5f9db", + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "[1, 2, 3, 4]" + ] + }, + "execution_count": 108, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "# 정렬 : sort() 함수는 리스트를 정렬하는 함수입니다. sort() 함수는 원본 리스트를 변경하며, 반환값은 없습니다. sort() 함수는 기본적으로 오름차순으로 정렬하지만, reverse=True 매개변수를 사용하여 내림차순으로 정렬할 수도 있습니다.\n", + "\n", + "a = [1, 4, 2, 3]\n", + "a.sort() # 리스트 a를 오름차순으로 정렬합니다. sort() 함수는 원본 리스트를 변경하며, 반환값은 없습니다.\n", + "a" + ] + }, + { + "cell_type": "code", + "execution_count": 109, + "id": "8d2c7520", + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "[4, 3, 2, 1]" + ] + }, + "execution_count": 109, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "a.sort(reverse=True) # 리스트 a를 내림차순으로 정렬합니다. sort() 함수는 원본 리스트를 변경하며, 반환값은 없습니다.\n", + "a" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "b02ccd37", + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "2" + ] + }, + "execution_count": 111, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "# index()\n", + "a.index(2) # 리스트 a에서 값 2가 처음으로 등장하는 인덱스를 반환합니다. 만약 찾는 값이 존재하지 않으면 ValueError 예외를 발생시킵니다. index() 함수는 리스트에서 특정 값을 찾을 때 유용하게 사용됩니다.\n", + "a.fin" + ] + }, + { + "cell_type": "code", + "execution_count": 112, + "id": "30d312fe", + "metadata": {}, + "outputs": [], + "source": [ + "# append() : 리스트에 요소를 추가하는 함수입니다. append() 함수는 리스트의 끝에 새로운 요소를 추가합니다. 예를 들어, a.append(10)은 리스트 a의 끝에 10을 추가합니다. append() 함수는 원본 리스트를 변경하며, 반환값은 없습니다.\n", + "# insert() : 리스트의 특정 위치에 요소를 추가하는 함수입니다. insert() 함수는 리스트의 특정 인덱스에 새로운 요소를 삽입합니다. 예를 들어, a.insert(1, 10)은 리스트 a의 인덱스 1에 10을 삽입합니다. insert() 함수는 원본 리스트를 변경하며, 반환값은 없습니다. \n", + "b.insert(1, 10) # 리스트 b의 인덱스 1에 10을 삽입합니다. insert() 함수는 원본 리스트를 변경하며, 반환값은 없습니다.\n", + "\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "112b51a1", + "metadata": {}, + "outputs": [], + "source": [ + "# 제거\n", + "b.remove(5) # 리스트 b에서 값 10을 제거합니다. remove() 함수는 리스트에서 첫 번째로 등장하는 지정된 값을 제거하며, 원본 리스트를 변경합니다. 만약 찾는 값이 존재하지 않으면 ValueError 예외를 발생시킵니다. remove() 함수는 리스트에서 특정 값을 제거할 때 유용하게 사용됩니다." + ] + }, + { + "cell_type": "code", + "execution_count": 114, + "id": "08f068a4", + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "9" + ] + }, + "execution_count": 114, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "b.pop()\n" + ] + }, + { + "cell_type": "code", + "execution_count": 115, + "id": "d80c64e6", + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "[1, 10, 3, 5, 7]" + ] + }, + "execution_count": 115, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "b" + ] + }, + { + "cell_type": "code", + "execution_count": 116, + "id": "8d47b622", + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "[1, 10, 5, 7]" + ] + }, + "execution_count": 116, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "# 2번 idx 요소 제거\n", + "b.pop(2)\n", + "b\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "8acdac0e", + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "1" + ] + }, + "execution_count": 117, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "# count() : 리스트에서 특정 값이 몇 번 등장하는지 세는 함수입니다. count() 함수는 리스트에서 지정된 값이 몇 번 나타나는지를 반환합니다. 예를 들어, b.count(1)은 리스트 b에서 값 1이 몇 번 등장하는지를 반환합니다. count() 함수는 리스트에서 특정 값의 빈도를 확인할 때 유용하게 사용됩니다.\n", + "b.count(1)\n" + ] + }, + { + "cell_type": "markdown", + "id": "0f898293", + "metadata": {}, + "source": [ + "### 튜플\n", + "- ()\n", + "- 튜플은 리스트와 유사하나, 요소값을 변경할 수 없다. ( 리스트는 요소값 생성, 수정 , 삭제 가능)" + ] + }, + { + "cell_type": "code", + "execution_count": 119, + "id": "3ecdc347", + "metadata": {}, + "outputs": [], + "source": [ + "# 생성\n", + "t1 = ()\n", + "t2 = (1, )\n", + "t3 = 1, 2, 3\n", + "t4 = (1, 2, 3)\n", + "t5 = ('a', 'b', ('ab', 'cd'))\n", + "\n" + ] + }, + { + "cell_type": "code", + "execution_count": 120, + "id": "028f2ca3", + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "(1, 1, 2, 3)" + ] + }, + "execution_count": 120, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "t2 + t3" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "24aeeb93", + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "[88, 10, 5, 7]\n", + "(1, 2, 3)\n" + ] + } + ], + "source": [ + "# 리스트 요소 수정\n", + "b[0] = 88\n", + "print(b)\n", + "\n", + "# 튜플 요소 수정 불가\n", + "# t4[0] = 88 # 튜플은 요소를 수정할 수 없습니다. 튜플은 불변(immutable)한 자료형이므로, 한 번 생성된 튜플의 요소는 변경할 수 없습니다. 따라서 t4[0] = 88과 같은 코드는 TypeError 예외를 발생시킵니다. 튜플의 요소를 변경하려면 새로운 튜플을 생성해야 합니다. 예를 들어, t4 = (88,) + t4[1:]와 같이 새로운 튜플을 생성하여 요소를 변경할 수 있습니다.\n", + "print(t4)" + ] + }, + { + "cell_type": "code", + "execution_count": 126, + "id": "06ef8c0b", + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "(1, 2)" + ] + }, + "execution_count": 126, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "t4[0:2]" + ] + }, + { + "cell_type": "code", + "execution_count": 124, + "id": "1cbca157", + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "3" + ] + }, + "execution_count": 124, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "len(t4)" + ] + }, + { + "cell_type": "markdown", + "id": "c37a5c87", + "metadata": {}, + "source": [ + "### 딕셔너리 자료형\n", + "- {key1:value1, key2:value2}\n", + "- key 값 중복 불가\n" + ] + }, + { + "cell_type": "code", + "execution_count": 128, + "id": "db7a6a5b", + "metadata": {}, + "outputs": [], + "source": [ + "dict1 = {'name': 'Alice', 'age': 30, 'city': 'New York'}\n", + "dict2 = {1:'kim', 2:22, 3:\"part\"}\n", + "dict3 = {\"arr\": [1, 2, 3, 4, 5]}\n" + ] + }, + { + "cell_type": "code", + "execution_count": 132, + "id": "cd658f9f", + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Alice\n", + "Alice\n", + "part\n" + ] + } + ], + "source": [ + "# kim 출력\n", + "print(dict1[\"name\"])\n", + "print(dict1.get(\"name\")) # 추천\n", + "print(dict2.get(3))\n" + ] + }, + { + "cell_type": "code", + "execution_count": 135, + "id": "2abdb89f", + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "{'name': 'Alice', 'city': 'New York'}" + ] + }, + "execution_count": 135, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "del dict1['age'] # 딕셔너리 dict1에서 키 'age'와 해당 값을 삭제합니다. del 키워드는 딕셔너리에서 특정 키를 제거하는 데 사용됩니다. del dict1['age']는 dict1에서 'age' 키와 해당 값을 삭제하며, 원본 딕셔너리를 변경합니다. 만약 삭제하려는 키가 존재하지 않으면 KeyError 예외를 발생시킵니다. del 키워드는 딕셔너리에서 특정 키를 제거할 때 유용하게 사용됩니다.\n", + "dict1\n" + ] + }, + { + "cell_type": "code", + "execution_count": 137, + "id": "861fe8a2", + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "{'name': 'Alice', 'city': 'New York', 'birth': '1990-01-01'}" + ] + }, + "execution_count": 137, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "# 추가 birth : '1990-01-01'\n", + "dict1['birth'] = '1990-01-01'\n", + "dict1" + ] + }, + { + "cell_type": "code", + "execution_count": 146, + "id": "7376720f", + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "{'name': 'Alice',\n", + " 'city': 'New York',\n", + " 'birth': '1990-01-01',\n", + " 'rank': [15, 17, 19]}" + ] + }, + "execution_count": 146, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "# rank = [15, 17, ,19]\n", + "dict1['rank'] = [15, 17, 19]\n", + "dict1" + ] + }, + { + "cell_type": "code", + "execution_count": 148, + "id": "8fd35f51", + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "dict_keys(['name', 'city', 'birth', 'rank'])\n", + "dict_values(['Alice', 'New York', '1990-01-01', [15, 17, 19]])\n", + "dict_items([('name', 'Alice'), ('city', 'New York'), ('birth', '1990-01-01'), ('rank', [15, 17, 19])])\n" + ] + } + ], + "source": [ + "# 키 값만 가져오기\n", + "print(dict1.keys()) # dict1의 모든 키를 반환하는 함수입니다. keys() 함수는 딕셔너리에서 모든 키를 반환하는 뷰 객체를 반환합니다. 예를 들어, dict1.keys()는 dict1의 모든 키를 반환합니다. keys() 함수는 딕셔너리에서 키를 확인하거나 반복할 때 유용하게 사용됩니다.\n", + "print(dict1.values()) # dict1의 모든 값을 반환하는 함수입니다. values() 함수\n", + "print(dict1.items()) # dict1의 모든 키-값 쌍을 반환하는 함수입니다. items() 함수는 딕셔너리에서 모든 키-값 쌍을 반환하는 뷰 객체를 반환합니다. 예를 들어, dict1.items()는 dict1의 모든 키-값 쌍을 반환합니다. items() 함수는 딕셔너리에서 키와 값을 동시에 확인하거나 반복할 때 유용하게 사용됩니다." + ] + }, + { + "cell_type": "code", + "execution_count": 151, + "id": "ef7f8e27", + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "True\n", + "False\n", + "True\n" + ] + } + ], + "source": [ + "# in\n", + "print('사과' in ['사과', '바나나', '체리']) # 리스트에서 '사과'가 존재하는지 확인합니다. in 연산자는 시퀀스 자료형에서 특정 요소가 존재하는지 여부를 확인하는 데 사용됩니다. 예를 들어, '사과' in ['사과', '바나나', '체리']는 True를 반환합니다. in 연산자는 리스트, 튜플, 문자열 등 다양한 시퀀스 자료형에서 사용할 수 있습니다.\n", + "# 키가 포함되어 있는가?\n", + "print('사과' in dict1) # 딕셔너리 dict1에서 '사과'라는 키가 존재하는지 확인합니다. in 연산자는 딕셔너리에서 특정 키가 존재하는지 여부를 확인하는 데 사용됩니다. 예를 들어, '사과' in dict1은 dict1에 '사과'라는 키가 존재하면 True를 반환하고, 그렇지 않으면 False를 반환합니다. in 연산자는 딕셔너리에서 키의 존재 여부를 확인할 때 유용하게 사용됩니다.\n", + "print('name' in dict1) # 딕셔너리 dict1에서 'name'이라는 키가 존재하는지 확인합니다. in 연산자는 딕셔너리에서 특정 키가 존재하는지 여부를 확인하는 데 사용됩니다. 예를 들어, 'name' in dict1은 dict1에 'name'이라는 키가 존재하면 True를 반환하고, 그렇지 않으면 False를 반환합니다. in 연산자는 딕셔너리에서 키의 존재 여부를 확인할 때 유용하게 사용됩니다.\n" + ] + }, + { + "cell_type": "markdown", + "id": "c5536c53", + "metadata": { + "notebookRunGroups": { + "groupValue": "2" + } + }, + "source": [ + "### 조건문\n", + "- 조건에 맞는 상황을 판단한 후 수행하는 것\n", + "- ex) 현재 변수에 값이 5라면, dict1 키가 name이 포힘돠어 있다면\n", + "\n", + "``` if 조건문: ```\n", + " ``` 조건이 참일때 수행할 문장```" + ] + }, + { + "cell_type": "markdown", + "id": "a87ee145", + "metadata": {}, + "source": [] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "66d9e5ac", + "metadata": {}, + "outputs": [], + "source": [ + "# money 10,000 이상을 가지고 있다면 택시 타기\n", + "money = 5000\n", + "\n", + "if money > 10000:\n", + " print(\"택시타기\")\n", + " \n", + "\n", + "\n" + ] + }, + { + "cell_type": "code", + "execution_count": 154, + "id": "ad742983", + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "걸어가기\n" + ] + } + ], + "source": [ + "# money 10,000 이상을 가지고 있다면 택시 타기\n", + "money = 5000\n", + "\n", + "if money >= 10000:\n", + " print(\"택시타기\")\n", + "else:\n", + " print(\"걸어가기\")" + ] + }, + { + "cell_type": "code", + "execution_count": 155, + "id": "58f6afd8", + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "B\n" + ] + } + ], + "source": [ + "# >=90, A / >=80, B / >=70 / c, d\n", + "# if 조건 :\n", + "# pass\n", + "# elif 조건 :\n", + "# pass\n", + "# elif 조건 :\n", + "# pass\n", + "# else :\n", + "# pass\n", + " \n", + "su = 88\n", + "\n", + "if su >= 90:\n", + " print(\"A\")\n", + "elif su >= 80:\n", + " print(\"B\")\n", + "elif su >= 70:\n", + " print(\"C\")\n", + "else:\n", + " print(\"D\")\n", + "\n", + "\n", + "\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "d3890a4c", + "metadata": {}, + "outputs": [], + "source": [ + "su = int(input(\"점수를 입력하세요 : \"))" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "03c3042e", + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "C\n" + ] + } + ], + "source": [ + "su = int(su) # 입력받은 문자열을 정수로 변환합니다. input() 함수는 사용자로부터 입력을 받을 때 문자열 형태로 반환하므로, su = int(su)를 사용하여 입력받은 문자열을 정수로 변환해야 합니다. 이렇게 하면 su 변수에 정수 값이 저장되어 이후의 조건문에서 올바르게 비교할 수 있습니다.\n", + "\n", + "\n", + "if su >= 90:\n", + " print(\"A\")\n", + "elif su >= 80:\n", + " print(\"B\")\n", + "elif su >= 70:\n", + " print(\"C\")\n", + "else:\n", + " print(\"D\")" + ] + }, + { + "cell_type": "code", + "execution_count": 179, + "id": "af6f7357", + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "\n", + "\n", + "\n" + ] + } + ], + "source": [ + "a = '99'\n", + "b = 98\n", + "# print(a >= 90)\n", + "print(type(a))\n", + "print(type(b))\n", + "\n", + "# a를 int 타입 변경\n", + "a = int(a)\n", + "print(type(a))\n" + ] + }, + { + "cell_type": "code", + "execution_count": 186, + "id": "ff6d1883", + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "합격\n" + ] + } + ], + "source": [ + "su = int(input(\"점수를 입력하세요 : \"))\n", + "\n", + "if su >= 90:\n", + " z = \"A\"\n", + "elif su >= 80:\n", + " z = \"B\"\n", + "elif su >= 70:\n", + " z = \"C\"\n", + "else:\n", + " z = \"D\"\n", + "\n", + "if(su >= 90 and z == \"A\"):\n", + " print(\"합격\")\n", + "else: \n", + " print(\"불합격\")" + ] + }, + { + "cell_type": "code", + "execution_count": 187, + "id": "a18e0c62", + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "사과\n" + ] + } + ], + "source": [ + "# 키가 포함되어 있는가?\n", + "print('사과')" + ] + }, + { + "cell_type": "code", + "execution_count": 189, + "id": "c6c03f4e", + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "12\n", + "1\n" + ] + } + ], + "source": [ + "num1 = 25\n", + "print(num1 // 2)\n", + "print(num1 % 2) # 나머지 연산자, a를 b로 나눈 나머지를 구하는 연산자\n" + ] + }, + { + "cell_type": "code", + "execution_count": 190, + "id": "d3e98df6", + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "홀수입니다.\n" + ] + } + ], + "source": [ + "# 숫자를 입력바등ㄴ 후 홀, 짝 구분\n", + "\n", + "# 비교 연산자\n", + "# == : 두 값이 같은지 비교하는 연산자입니다. 예를 들어, 5 == 5는 True를 반환하고, 5 == 4는 False를 반환합니다. == 연산자는 값의 동등성을 비교할 때 사용됩니다.\n", + "# != : 두 값이 다른지 비교하는 연산자입니다. 예를 들어, 5 != 4는 True를 반환하고, 5 != 5는 False를 반환합니다. != 연산자는 값의 부등성을 비교할 때 사용됩니다.\n", + "\n", + "\n", + "num = int(input(\"숫자를 입력하세요 : \"))\n", + "\n", + "if num % 2 == 0:\n", + " print(\"짝수입니다.\")\n", + "else:\n", + " print(\"홀수입니다.\")" + ] + }, + { + "cell_type": "code", + "execution_count": 192, + "id": "414aa9d0", + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "success\n" + ] + } + ], + "source": [ + "# score가 60 이상이면 success / failure\n", + "score = int(input(\"점수를 입력하세요 : \"))\n", + "\n", + "if score >= 60:\n", + " print(\"success\")\n", + "else:\n", + " print(\"failure\")" + ] + }, + { + "cell_type": "code", + "execution_count": 195, + "id": "746a8f64", + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Failure\n" + ] + } + ], + "source": [ + "score = int(input(\"점수를 입력하세요 : \"))\n", + "\n", + "msg = \"Success\" if score >= 60 else \"Failure\"\n", + "print(msg)\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "b7c22708", + "metadata": {}, + "outputs": [], + "source": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": ".venv", + "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.14.4" + } + }, + "nbformat": 4, + "nbformat_minor": 5 +} diff --git a/pythonSource/Basic/hello.py b/pythonSource/Basic/hello.py index 6b17aad..be2f9af 100644 --- a/pythonSource/Basic/hello.py +++ b/pythonSource/Basic/hello.py @@ -1 +1,26 @@ -print("안녕하세요!") \ No newline at end of file +print("안녕하세요!") + +# 줄 단위 실행 > 특정 행에서 실행 오류가 나는 경우 프로그램은 멈추게 된다. +# 파이썬 자료형 = 정수형, 문자형, 불린형 , 리스트 , 튜플 , 딕셔너리, set(x) + +# 변수 : 프로그램 내부에 값을 담아놓기위한 공간(이름 사용) +a = 10 # 정수형 (Integer) +b = 3.14 # 실수형 (Floating-point number) +c = "Hello, World!" # 문자열형 (String) +d = True # 불리언형 (Boolean) - 참(True) 또는 거짓(False) 값을 가질 수 있다. +e = [1, 2, 3, 4, 5] # 리스트형 (List) - 여러 값을 순서대로 저장할 수 있는 자료형 +f = (1, 2, 3) # 튜플형 (Tuple) - 리스트와 유사하지만, 한 번 생성된 후에는 변경할 수 없는 자료형 +g = {1, 2, 3} # 집합형 (Set) - 중복되지 않는 요소들의 모음으로, 순서가 없다. +h = {"name": "Alice", "age": 30} # 딕셔너리형 (Dictionary) - 키-값 쌍으로 데이터를 저장하는 자료형 + +print(a) +print(b) +print(c) +print(d) +print(e) +print(f) +print(g) +print(h) + +multiline = "Life is too short\n you need python" +print(multiline) \ No newline at end of file