{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "***\n", "***\n", "# 15. 파이썬 함수\n", "***\n", "***" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "***\n", "## 1 함수의 정의와 호출\n", "***\n", "- 함수: 여러 개의 Statement들을 하나로 묶은 단위\n", "- 함수 사용의 장점\n", " - 반복적인 수행이 가능하다\n", " - 코드를 논리적으로 이해하는 데 도움을 준다\n", " - 코드의 일정 부분을 별도의 논리적 개념으로 독립화할 수 있음\n", " - 수학에서 복잡한 개념을 하나의 단순한 기호로 대치하는 것과 비슷" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### 1-1 간단한 함수의 정의\n", "- 함수 정의시 사용하는 키워드: def" ] }, { "cell_type": "code", "execution_count": 1, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "3\n", "\n", "4\n", "4\n" ] } ], "source": [ "def add(a, b):\n", " return a + b\n", "\n", "print(add(1, 2))\n", "print()\n", "\n", "def myabs(x):\n", " if x < 0 : \n", " x = -x\n", " return x\n", "\n", "print(abs(-4))\n", "print(myabs(-4))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### 1-2 함수 객체와 함수 호출\n", "- 함수의 이름 자체는 함수 객체의 레퍼런스(Reference)를 지니고 있다." ] }, { "cell_type": "code", "execution_count": 2, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "\n" ] } ], "source": [ "def add(a, b):\n", " return a + b\n", "\n", "print(add)" ] }, { "cell_type": "code", "execution_count": 3, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "40\n" ] } ], "source": [ "c = add(10, 30)\n", "print(c)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "- 함수 이름에 저장된 레퍼런스를 다른 변수에 할당하여 그 변수를 이용한 함수 호출 가능 " ] }, { "cell_type": "code", "execution_count": 4, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "9\n" ] } ], "source": [ "f = add\n", "print(f(4, 5))" ] }, { "cell_type": "code", "execution_count": 9, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "\n", "True\n" ] } ], "source": [ "print(f)\n", "\n", "print(f is add)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "- 함수의 몸체에는 최소한 한개 이상의 statement가 존재해야 함\n", " - 아무런 내용이 없는 몸체를 지닌 함수를 만들 때에는 pass 라는 키워드를 몸체에 적어주어야 함" ] }, { "cell_type": "code", "execution_count": 8, "metadata": { "collapsed": true }, "outputs": [], "source": [ "def simpleFunction():\n", " pass\n", "\n", "simpleFunction()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "- 함수 사용 예" ] }, { "cell_type": "code", "execution_count": 6, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "['hwang', 'lee', 'park', 'youn', 'jo']\n" ] } ], "source": [ "def addmember(members, newmember):\n", " if newmember not in members: # 기존 멤버가 아니면\n", " members.append(newmember) # 추가\n", "\n", "members = ['hwang', 'lee', 'park', 'youn'] # 리스트에 초기 멤버 설정\n", "\n", "addmember(members, 'jo') # 새로운 멤버 추가\n", "\n", "addmember(members, 'hwang') # (이미 존재하는) 새로운 멤버 추가\n", "\n", "print(members)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### 1-3 함수 인수값 전달방법\n", "- 파이썬에서의 인수값 전달 방법\n", " - 기본적으로 값에 의한 호출(Call-by-Value)\n", " - 하지만 변수에 저장된 값이 참조값(Reference)이므로 실제로는 참조에 의한 호출(Call-by-Reference)로 실행됨" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "- 함수 인자에 변경불가능(Immutable) 객체인 숫자값을 전달\n", " - 함수 내에서 다른 숫자값으로 치환 --> 의미 없는 인자 전달" ] }, { "cell_type": "code", "execution_count": 7, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "200\n" ] } ], "source": [ "def f1(b):\n", " b = 100\n", "\n", "a = 200\n", "f1(a)\n", "print(a)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "![image](../images/function_arg_int.png)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "- 함수 인자에 변경불가능(Immutable) 객체인 문자열을 전달\n", " - 함수 내에서 다른 문자열로 치환 --> 의미 없는 인자 전달" ] }, { "cell_type": "code", "execution_count": 8, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "def\n" ] } ], "source": [ "def f2(b):\n", " b = \"abc\"\n", "\n", "a = \"def\"\n", "f2(a)\n", "print(a)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "![image](../images/function_arg_str.png)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "- 함수 인자에 변경불가능(Immutable) 객체인 튜플을 전달\n", " - 함수 내에서 다른 튜플로 치환 --> 의미 없는 인자 전달" ] }, { "cell_type": "code", "execution_count": 9, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "(4, 5, 6)\n" ] } ], "source": [ "def f3(b):\n", " b = (1,2,3)\n", "\n", "a = (4,5,6)\n", "f3(a)\n", "print(a)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "![image](../images/function_arg_tuple.png)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "- 함수 인자에 변경가능한(Mutable)한 객체인 리스트 전달 및 내용 수정\n", " - 전형적인 함수 인자 전달법 및 활용법" ] }, { "cell_type": "code", "execution_count": 10, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[4, 10, 6]\n" ] } ], "source": [ "def f4(b):\n", " b[1] = 10\n", "\n", "a = [4,5,6]\n", "f4(a)\n", "print(a)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "![image](../images/function_arg_list.png)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "- 함수 인자에 변경가능한(Mutable)한 객체인 사전 전달 및 내용 수정\n", " - 전형적인 함수 인자 전달법 및 활용법" ] }, { "cell_type": "code", "execution_count": 11, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "{'a': 10, 'b': 2}\n" ] } ], "source": [ "def f5(b):\n", " b['a'] = 10\n", "\n", "a = {\"a\":1, \"b\":2}\n", "f5(a)\n", "print(a)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "![image](../images/function_arg_dict.png)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### 1-4 반환(return)문" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "- 인수 없이 return 문을 사용하면 실제로는 None 객체가 전달된다.\n", " - None 객체: 파이썬 내장 객체로서 아무 값도 없음을 나타내기 위한 객체" ] }, { "cell_type": "code", "execution_count": 12, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "None\n" ] } ], "source": [ "def nothing():\n", " return\n", "\n", "print(nothing())" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "- return문 없이 리턴하기" ] }, { "cell_type": "code", "execution_count": 13, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "1. Snack\n", "2. Snake\n", "3. Snick\n" ] } ], "source": [ "def print_menu():\n", " print('1. Snack')\n", " print('2. Snake')\n", " print('3. Snick')\n", " \n", "print_menu()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "- return문이 없는 함수라 해도, 실제로는 None 객체가 리턴됨" ] }, { "cell_type": "code", "execution_count": 14, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "1. Snack\n", "2. Snake\n", "3. Snick\n", "None\n" ] } ], "source": [ "a = print_menu()\n", "\n", "print(a)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "- 한 개의 값을 리턴할 때" ] }, { "cell_type": "code", "execution_count": 15, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "10\n" ] } ], "source": [ "def abs_function(x):\n", " if x < 0 : return -x\n", " return x\n", "\n", "print(abs_function(-10))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "- 두 개 이상의 값을 리턴할 때" ] }, { "cell_type": "code", "execution_count": 16, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "10 20\n", "\n", "20 10\n", "\n", "20 10\n" ] } ], "source": [ "def swap(x, y):\n", " return y, x # 튜플로 리턴된다.\n", "\n", "a = 10\n", "b = 20\n", "print(a, b)\n", "print()\n", "\n", "a, b = swap(a, b) # 결과적으로 a, b = b, a와 동일\n", "print(a, b)\n", "print()\n", "\n", "a = 10\n", "b = 20\n", "x = swap(a, b)\n", "print(x[0], x[1]) # 하나의 이름으로 튜플을 받아서 처리할 수 도있다." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "- 새로운 리스트를 리턴하는 함수의 예\n", " - 문자열 리스트를 받아서 각 문자열의 길이 정보를 지닌 리스트를 리턴 " ] }, { "cell_type": "code", "execution_count": 17, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[6, 5, 7, 5]\n" ] } ], "source": [ "def length_list(l):\n", " res = []\n", " for el in l:\n", " res.append(len(el))\n", " return res\n", "\n", "l = ['python', 'pyson', 'pythong', 'pydon']\n", "print(length_list(l))" ] }, { "cell_type": "code", "execution_count": 18, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[6, 5, 7, 5]\n" ] } ], "source": [ "l = ['python', 'pyson', 'pythong', 'pydon']\n", "print([len(s) for s in l])" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### 1-5 함수 인자에 대한 동적인 자료형 결정\n", "- 파이썬에서는 모든 객체는 동적으로 (실행 시간에) 그 타입이 결정된다.\n", "- 그러므로, 함수 인자는 함수가 호출되는 순간 해당 인자에 전달되는 객체에 따라 그 타입이 결정된다.\n", " - 함수 몸체 내에서 사용되는 여러가지 연산자들은 함수 호출시에 결정된 객체 타입에 맞게 실행된다." ] }, { "cell_type": "code", "execution_count": 19, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "4.4\n", "dynamictyping\n", "['list', 'and', 'list']\n" ] } ], "source": [ "def add(a, b):\n", " return a + b\n", "\n", "c = add(1, 3.4)\n", "d = add('dynamic', 'typing')\n", "e = add(['list'], ['and', 'list'])\n", "print(c)\n", "print(d)\n", "print(e)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "***\n", "## 2 함수 인수 처리\n", "***" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### 2-1 기본 인수 값\n", "- 기본 인수 값\n", " - 함수를 호출할 때 인수를 넘겨주지 않아도 인수가 기본적으로 가지는 값" ] }, { "cell_type": "code", "execution_count": 20, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "2\n", "12\n" ] } ], "source": [ "def incr(a, step=1):\n", " return a + step\n", "\n", "b = 1\n", "b = incr(b) # 1 증가\n", "print(b)\n", "\n", "b = incr(b, 10) # 10 증가\n", "print(b)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "- [주의] 함수 정의를 할 때 기본 값을 지닌 인수 뒤에 일반적인 인수가 올 수 없음" ] }, { "cell_type": "code", "execution_count": 82, "metadata": {}, "outputs": [ { "ename": "SyntaxError", "evalue": "non-default argument follows default argument (, line 1)", "output_type": "error", "traceback": [ "\u001b[0;36m File \u001b[0;32m\"\"\u001b[0;36m, line \u001b[0;32m1\u001b[0m\n\u001b[0;31m def incr(step=1, a):\u001b[0m\n\u001b[0;31mSyntaxError\u001b[0m\u001b[0;31m:\u001b[0m non-default argument follows default argument\n" ] } ], "source": [ "def incr(step=1, a):\n", " return a + step" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "- 함수 정의 시에 여러 개의 기본 인수 값 정의 가능" ] }, { "cell_type": "code", "execution_count": 22, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "21\n" ] } ], "source": [ "def incr(a, step=1, step2=10):\n", " return a + step + step2\n", "\n", "print(incr(10))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### 2-2 키워드 인수\n", "- 키워드 인수\n", " - 인수 값 전달 시에 인수 이름과 함께 값을 전달하는 방식을 일컫는다." ] }, { "cell_type": "code", "execution_count": 23, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "height string height string height string \n", "200\n" ] } ], "source": [ "def area(height, width):\n", " return height * width\n", "\n", "#순서가 아닌 이름으로 값이 전달\n", "a = area(height='height string ', width=3)\n", "print(a)\n", "\n", "b = area(width=20, height=10)\n", "print(b)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "- 함수를 호출 할 때에 키워드 인수는 마지막에 놓여져야 한다." ] }, { "cell_type": "code", "execution_count": 24, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "100\n" ] } ], "source": [ "print(area(20, width=5))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "- [주의] 함수 호출시에 키워드 인수 뒤에 일반 인수 값이 올 수 없다. " ] }, { "cell_type": "code", "execution_count": 26, "metadata": {}, "outputs": [ { "ename": "SyntaxError", "evalue": "positional argument follows keyword argument (, line 1)", "output_type": "error", "traceback": [ "\u001b[1;36m File \u001b[1;32m\"\"\u001b[1;36m, line \u001b[1;32m1\u001b[0m\n\u001b[1;33m area(width=5, 20)\u001b[0m\n\u001b[1;37m ^\u001b[0m\n\u001b[1;31mSyntaxError\u001b[0m\u001b[1;31m:\u001b[0m positional argument follows keyword argument\n" ] } ], "source": [ "area(width=5, 20)\n", "# 기존: SyntaxError: non-keyword arg after keyword arg" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "- 기본 인수값 및 키워드 인수의 혼용" ] }, { "cell_type": "code", "execution_count": 27, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "212\n" ] } ], "source": [ "def incr(a, step=1, step2=10, step3=100):\n", " return a + step + step2 + step3\n", "\n", "print(incr(10, 2, step2=100))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "- 함수 호출 시에 키워드 인수 뒤에 일반 인수 값이 오면 에러 " ] }, { "cell_type": "code", "execution_count": 28, "metadata": {}, "outputs": [ { "ename": "SyntaxError", "evalue": "positional argument follows keyword argument (, line 4)", "output_type": "error", "traceback": [ "\u001b[1;36m File \u001b[1;32m\"\"\u001b[1;36m, line \u001b[1;32m4\u001b[0m\n\u001b[1;33m print(incr(10, 2, step2=100, 200))\u001b[0m\n\u001b[1;37m ^\u001b[0m\n\u001b[1;31mSyntaxError\u001b[0m\u001b[1;31m:\u001b[0m positional argument follows keyword argument\n" ] } ], "source": [ "def incr(a, step=1, step2=10, step3=100):\n", " return a + step + step2 + step3\n", "\n", "print(incr(10, 2, step2=100, 200))\n", "# 기존: SyntaxError: non-keyword arg after keyword arg" ] }, { "cell_type": "code", "execution_count": 29, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "312\n" ] } ], "source": [ "def incr(a, step=1, step2=10, step3=100):\n", " return a + step + step2 + step3\n", "\n", "print(incr(10, 2, step2=100, step3=200))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### 2-3 가변 인수 리스트" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "- 함수 정의시에 일반적인 인수 선언 뒤에 *args 형식의 인수로 가변 인수를 선언할 수 있음\n", "- The special syntax *args in function definitions in python is used to pass a variable number of arguments to a function." ] }, { "cell_type": "code", "execution_count": 11, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ " ('Hello', 'Welcome', 'to', 'GeeksforGeeks')\n", "\n", "Hello\n", "Welcome\n", "to\n", "GeeksforGeeks\n" ] } ], "source": [ "def myFun(*args):\n", " print(type(args), args)\n", " print()\n", " for arg in args:\n", " print(arg) \n", " \n", "myFun('Hello', 'Welcome', 'to', 'GeeksforGeeks')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "- 함수 호출시 넣어주는 인수 값들 중 일반 인수에 할당되는 값을 제외한 나머지 값들만을 지닌 튜플 객체가 할당된다." ] }, { "cell_type": "code", "execution_count": 12, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "1 ()\n", "2 (3,)\n", "2 (3, 4, 5, 6)\n" ] } ], "source": [ "def varg(a, *args):\n", " print(a, args)\n", "\n", "varg(1)\n", "varg(2, 3)\n", "varg(2, 3, 4, 5, 6)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "- C언어의 printf문과 유사한 형태의 printf 정의 방법" ] }, { "cell_type": "code", "execution_count": 13, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "I've spent 6 days and 5 night to do this\n" ] } ], "source": [ "def printf(format, *args):\n", " print(format % args)\n", "\n", "printf(\"I've spent %d days and %d night to do this\", 6, 5)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "- The special syntax ****kwargs** in function definitions in python is used to pass a keyworded, variable-length argument list. " ] }, { "cell_type": "code", "execution_count": 29, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ " {'first': 'Geeks', 'mid': 'for', 'last': 'Geeks'}\n", "\n", "first: Geeks\n", "mid: for\n", "last: Geeks\n" ] } ], "source": [ "def myFun(**kwargs):\n", " print(type(kwargs), kwargs)\n", " print()\n", " for key, value in kwargs.items(): \n", " print(\"{0}: {1}\".format(key, value)) \n", " \n", "myFun(first ='Geeks', mid ='for', last='Geeks') " ] }, { "cell_type": "code", "execution_count": 30, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Hi - first: Geeks\n", "Hi - mid: for\n", "Hi - last: Geeks\n" ] } ], "source": [ "def myFun(arg1, **kwargs): \n", " for key, value in kwargs.items(): \n", " print (\"{0} - {1}: {2}\".format(arg1, key, value)) \n", " \n", "myFun(\"Hi\", first ='Geeks', mid ='for', last='Geeks') " ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### 2-5 튜플 인수와 사전 인수로 함수 호출하기\n", "- 함수 호출에 사용될 인수값들이 튜플에 있다면 \"*튜플변수\"를 이용하여 함수 호출이 가능" ] }, { "cell_type": "code", "execution_count": 16, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "1 2 3\n" ] } ], "source": [ "def h(a, b, c):\n", " print(a, b, c)\n", " \n", "args = (1, 2, 3)\n", "h(*args)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "- 함수 호출에 사용될 인수값들이 사전에 있다면 \"**사전변수\"를 이용하여 함수 호출이 가능" ] }, { "cell_type": "code", "execution_count": 23, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "aa bb cc\n", "1 2 3\n" ] } ], "source": [ "def h(a, b, c):\n", " print(a, b, c)\n", " \n", "dargs = {'aa':1, 'bb':2, 'cc':3}\n", "h(*dargs)\n", "\n", "dargs = {'a':1, 'b':2, 'c':3}\n", "h(**dargs)" ] }, { "cell_type": "code", "execution_count": 32, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "arg1: Geeks\n", "arg2: for\n", "arg3: Geeks\n", "arg1: Geeks\n", "arg2: for\n", "arg3: Geeks\n" ] } ], "source": [ "def myFun(arg1, arg2, arg3): \n", " print(\"arg1:\", arg1) \n", " print(\"arg2:\", arg2) \n", " print(\"arg3:\", arg3) \n", " \n", "args = (\"Geeks\", \"for\", \"Geeks\") \n", "myFun(*args) \n", " \n", "kwargs = {\"arg1\" : \"Geeks\", \"arg2\" : \"for\", \"arg3\" : \"Geeks\"} \n", "myFun(**kwargs)" ] }, { "cell_type": "code", "execution_count": 33, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "a 1\n", "b 2\n", "c 3\n", "d 4\n" ] } ], "source": [ "def function(**arg):\n", " for i in arg:\n", " print (i, arg[i])\n", "\n", "function(a=1, b=2, c=3, d=4)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "- Asterisks in Python: what they are and how to use them\n", " - https://treyhunner.com/2018/10/asterisks-in-python-what-they-are-and-how-to-use-them/" ] }, { "cell_type": "code", "execution_count": 37, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "1\n", "[2, 3, 4]\n" ] } ], "source": [ "a, *b = [1, 2, 3, 4]\n", "print(a)\n", "print(b)" ] }, { "cell_type": "code", "execution_count": 40, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "1 (2, 3, 4)\n" ] } ], "source": [ "def func(a, *b):\n", " print(a, b)\n", " \n", "func(1, 2, 3, 4)" ] }, { "cell_type": "code", "execution_count": 44, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[2, 1, 3, 4, 7, 11, 18]\n" ] } ], "source": [ "numbers = [2, 1, 3, 4, 7]\n", "more_numbers = [*numbers, 11, 18]\n", "print(more_numbers)" ] }, { "cell_type": "code", "execution_count": 47, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "2 1 3 4 7 11 18\n" ] } ], "source": [ "print(*more_numbers)" ] }, { "cell_type": "code", "execution_count": 48, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "lemon pear watermelon tomato\n", "lemon pear watermelon tomato\n" ] } ], "source": [ "fruits = ['lemon', 'pear', 'watermelon', 'tomato']\n", "print(fruits[0], fruits[1], fruits[2], fruits[3])\n", "\n", "print(*fruits)" ] }, { "cell_type": "code", "execution_count": 49, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[[1, 2, 3], [4, 5, 6], [7, 8, 9]]\n" ] } ], "source": [ "def transpose_list(list_of_lists):\n", " return [list(row) for row in zip(*list_of_lists)]\n", "\n", "t_l = transpose_list([[1, 4, 7], [2, 5, 8], [3, 6, 9]])\n", "print(t_l)" ] }, { "cell_type": "code", "execution_count": 51, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "2020-01-01.txt\n" ] } ], "source": [ "date_info = {'year': \"2020\", 'month': \"01\", 'day': \"01\"}\n", "\n", "filename = \"{year}-{month}-{day}.txt\".format(**date_info)\n", "\n", "print(filename)" ] }, { "cell_type": "code", "execution_count": 52, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "2 1 3 4 7 lemon pear watermelon tomato\n" ] } ], "source": [ "fruits = ['lemon', 'pear', 'watermelon', 'tomato']\n", "numbers = [2, 1, 3, 4, 7]\n", "print(*numbers, *fruits)" ] }, { "cell_type": "code", "execution_count": 54, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "2020-01-01-Beethoven-Symphony No 5.txt\n" ] } ], "source": [ "date_info = {'year': \"2020\", 'month': \"01\", 'day': \"01\"}\n", "track_info = {'artist': \"Beethoven\", 'title': 'Symphony No 5'}\n", "\n", "filename = \"{year}-{month}-{day}-{artist}-{title}.txt\".format(\n", " **date_info,\n", " **track_info,\n", ")\n", "\n", "print(filename)" ] }, { "cell_type": "code", "execution_count": 57, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ " (20,)\n", "17\n", " (6, 6)\n", "10\n", " (6, 6, 6)\n", "12\n" ] } ], "source": [ "from random import randint\n", "\n", "def roll(*dice):\n", " print(type(dice), dice)\n", " return sum([randint(1, die) for die in dice])\n", "\n", "print(roll(20))\n", "\n", "print(roll(6, 6))\n", "\n", "print(roll(6, 6, 6))" ] }, { "cell_type": "code", "execution_count": 67, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "\n", "\n" ] } ], "source": [ "def tag(tag_name, **attributes):\n", " attribute_list = [\"{0}='{1}'\".format(name, value) for name, value in attributes.items()]\n", " return \"<{0} \".format(tag_name) + ' '.join(attribute_list) + \">\"\n", "\n", "print(tag('a', href=\"http://treyhunner.com\"))\n", "\n", "print(tag('img', height=20, width=40, src=\"face.jpg\"))" ] }, { "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 }