{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# 1. Simple function" ] }, { "cell_type": "code", "execution_count": 2, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "This is foo\n" ] } ], "source": [ "def foo():\n", " print(\"This is foo\")\n", "\n", "foo()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# 2. Function with parameters" ] }, { "cell_type": "code", "execution_count": 3, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Sum is 8\n" ] } ], "source": [ "def bar(x, y):\n", " print(\"Sum is \", x + y)\n", " \n", "bar(3, 5)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# 3. Default parameter value" ] }, { "cell_type": "code", "execution_count": 5, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "__________\n", "________________________________________\n", "____________________\n" ] } ], "source": [ "def drawLine(length = 10):\n", " str = \"\"\n", " for i in range(0, length):\n", " str += \"_\"\n", " print(str)\n", "\n", "drawLine()\n", "\n", "drawLine(40)\n", "\n", "drawLine(length=20)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# 4. Lambda expressions" ] }, { "cell_type": "code", "execution_count": 6, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Hello Alice!\n", "Hello Bob!\n" ] } ], "source": [ "def greeter(val):\n", " return lambda x: val + x\n", "\n", "greet = greeter(\"Hello \")\n", "\n", "print(greet(\"Alice!\"))\n", "print(greet(\"Bob!\"))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# 5. Recursive functions" ] }, { "cell_type": "code", "execution_count": 1, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "The factorial of 4 is 24\n" ] } ], "source": [ "def factorial(x):\n", " if x == 1:\n", " return 1\n", " else:\n", " return (x * factorial(x-1))\n", "\n", "x = 4\n", "print(\"The factorial of\", x, \"is\", factorial(x))" ] } ], "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.6" } }, "nbformat": 4, "nbformat_minor": 2 }