{ "cells": [ { "cell_type": "code", "execution_count": 1, "metadata": {}, "outputs": [], "source": [ "import time\n", "import random\n", "from IPython.display import clear_output" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# Introduction to Python \n", "\n", "## [Functions](https://docs.python.org/3.0/tutorial/controlflow.html#defining-functions)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "+ A function is a block of code which only runs when it is called. \n", "+ You can pass data, known as parameters, into a function. \n", "+ A function can return data as a result. " ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### Sintax:\n", "\n", " def function_name():\n", " ...\n", " return (optional)\n", " yield (optional)\n", " ...\n", "\n", "\n", "#### Function Parameters: Parameters are the names that appear in the function definition.\n", "#### Function Arguments: Arguments are the names that appear in the function call.\n", "\n", "![](../../Data/Figs/function1.png)\n", "\n", "\n", "#### Keyword Arguments and Positional Arguments\n", "\n", "![](../../Data/Figs/function2.png)\n", "\n", "\n", "#### Types of Parameters:\n", "+ Positional or keyword\n", "\n", " def func(pos1, key1=None):\n", " pass\n", " \n", "\n", "+ Positional-only\n", "\n", " def func(pos_only1, pos_only2, /, positional_or_keyword):\n", " pass\n", "\n", "\n", "+ Keyword-only\n", "\n", " def func(pos_only1, pos_only2, *, key_only1, key_only2): \n", " pass\n", "\n", "\n", "+ Var-positional\n", "\n", " def func(*args): \n", " pass\n", "\n", "\n", "+ Var-keyword\n", "\n", " def func(**kwargs): \n", " pass\n", "\n", "\n", "\n", "(source: https://medium.com/better-programming/python-parameters-and-arguments-demystified-e4f77b6d002e)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Now let's explore practical examples" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### A function without parameters, and not returning anything" ] }, { "cell_type": "code", "execution_count": 2, "metadata": {}, "outputs": [], "source": [ "def my_function1():\n", " print(\"Hello, dear Python user!\")" ] }, { "cell_type": "code", "execution_count": 3, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Hello, dear Python user!\n" ] } ], "source": [ "my_function1()" ] }, { "cell_type": "code", "execution_count": 4, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Hello, dear Python user!\n", "None\n" ] } ], "source": [ "x = my_function1()\n", "print(x)" ] }, { "cell_type": "code", "execution_count": 5, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "NoneType" ] }, "execution_count": 5, "metadata": {}, "output_type": "execute_result" } ], "source": [ "type(x)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### A function with parameters, returning values" ] }, { "cell_type": "code", "execution_count": 6, "metadata": {}, "outputs": [], "source": [ "def do_sum(x,y):\n", " print('will sum x and y')\n", " return x + y\n", " print('done') #will be ignored" ] }, { "cell_type": "code", "execution_count": 7, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "will sum x and y\n" ] } ], "source": [ "a = do_sum(2,9)" ] }, { "cell_type": "code", "execution_count": 8, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "11\n" ] } ], "source": [ "print(a)" ] }, { "cell_type": "code", "execution_count": 9, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "will sum x and y\n" ] }, { "data": { "text/plain": [ "'onestring'" ] }, "execution_count": 9, "metadata": {}, "output_type": "execute_result" } ], "source": [ "do_sum('one','string')" ] }, { "cell_type": "code", "execution_count": 10, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "will sum x and y\n" ] }, { "data": { "text/plain": [ "[1, 2, 3, 4]" ] }, "execution_count": 10, "metadata": {}, "output_type": "execute_result" } ], "source": [ "do_sum([1,2],[3,4])" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### When the arguments are not compatible with operations --> error" ] }, { "cell_type": "code", "execution_count": 11, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "will sum x and y\n" ] }, { "ename": "TypeError", "evalue": "unsupported operand type(s) for +: 'int' and 'list'", "output_type": "error", "traceback": [ "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m", "\u001b[0;31mTypeError\u001b[0m Traceback (most recent call last)", "Input \u001b[0;32mIn [11]\u001b[0m, in \u001b[0;36m\u001b[0;34m()\u001b[0m\n\u001b[0;32m----> 1\u001b[0m do_sum(\u001b[38;5;241m2\u001b[39m,[\u001b[38;5;241m2\u001b[39m,\u001b[38;5;241m3\u001b[39m])\n", "Input \u001b[0;32mIn [6]\u001b[0m, in \u001b[0;36mdo_sum\u001b[0;34m(x, y)\u001b[0m\n\u001b[1;32m 1\u001b[0m \u001b[38;5;28;01mdef\u001b[39;00m \u001b[38;5;21mdo_sum\u001b[39m(x,y):\n\u001b[1;32m 2\u001b[0m \u001b[38;5;28mprint\u001b[39m(\u001b[38;5;124m'\u001b[39m\u001b[38;5;124mwill sum x and y\u001b[39m\u001b[38;5;124m'\u001b[39m)\n\u001b[0;32m----> 3\u001b[0m \u001b[38;5;28;01mreturn\u001b[39;00m \u001b[43mx\u001b[49m\u001b[43m \u001b[49m\u001b[38;5;241;43m+\u001b[39;49m\u001b[43m \u001b[49m\u001b[43my\u001b[49m\n\u001b[1;32m 4\u001b[0m \u001b[38;5;28mprint\u001b[39m(\u001b[38;5;124m'\u001b[39m\u001b[38;5;124mdone\u001b[39m\u001b[38;5;124m'\u001b[39m)\n", "\u001b[0;31mTypeError\u001b[0m: unsupported operand type(s) for +: 'int' and 'list'" ] } ], "source": [ "do_sum(2,[2,3]) #error" ] }, { "cell_type": "code", "execution_count": 12, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "will sum x and y\n", "11\n" ] } ], "source": [ "x = do_sum(6,5)\n", "print(x)" ] }, { "cell_type": "code", "execution_count": 13, "metadata": {}, "outputs": [], "source": [ "def is_even(number):\n", " if number%2 == 0:\n", " return True\n", " else:\n", " return False" ] }, { "cell_type": "code", "execution_count": 14, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "True\n" ] } ], "source": [ "response = is_even(2342)\n", "print(response)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### Reminder: tuple unpacking" ] }, { "cell_type": "code", "execution_count": 15, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "1\n", "2\n", "[3, 4, 5]\n", "6\n" ] } ], "source": [ "x,y,*z,t = 1,2,3,4,5,6\n", "print(x)\n", "print(y)\n", "print(z)\n", "print(t)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### A function with a variable number of parameters (var-positional)" ] }, { "cell_type": "code", "execution_count": 16, "metadata": {}, "outputs": [], "source": [ "def many_args(*args):\n", " print(f\"the tuple contains {len(args)} arguments\")\n", " print(args)\n", " for arg in args:\n", " print(arg)" ] }, { "cell_type": "code", "execution_count": 17, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "the tuple contains 7 arguments\n", "(1, 2, 3, 4, 5, 6, 6)\n", "1\n", "2\n", "3\n", "4\n", "5\n", "6\n", "6\n" ] } ], "source": [ "many_args(1,2,3,4,5,6,6)" ] }, { "cell_type": "code", "execution_count": 18, "metadata": {}, "outputs": [], "source": [ "def do_multiple_sum(*args):\n", " print(args)\n", " print('the total is {}'.format(sum(args)))\n", " print(f'total is {sum(args)}')\n", " return sum(args)" ] }, { "cell_type": "code", "execution_count": 19, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "(23, 45, 18, 45, 21)\n", "the total is 152\n", "total is 152\n", "152\n" ] } ], "source": [ "y = do_multiple_sum(23, 45, 18,45,21)\n", "print(y)" ] }, { "cell_type": "code", "execution_count": 20, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)\n", "the total is 55\n", "total is 55\n" ] }, { "data": { "text/plain": [ "55" ] }, "execution_count": 20, "metadata": {}, "output_type": "execute_result" } ], "source": [ "do_multiple_sum(1,2,3,4,5,6,7,8,9,10)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### A function without variable number of parameters (positional and keyword)" ] }, { "cell_type": "code", "execution_count": 21, "metadata": {}, "outputs": [], "source": [ "def many_args_and_kwargs(*args, **kwargs):\n", " print(args)\n", " print()\n", " print(kwargs)" ] }, { "cell_type": "code", "execution_count": 22, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "(2, 3, 4, 5, 6)\n", "\n", "{'name': 'Renato', 'inst': 'FGV', 'place': 'Botafogo', 'yearclass': '2021.1'}\n" ] } ], "source": [ "many_args_and_kwargs(2,3,4,5,6, name='Renato',inst='FGV', place='Botafogo', yearclass='2021.1')" ] }, { "cell_type": "code", "execution_count": 23, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "()\n", "\n", "{'message': 'Hello World'}\n" ] } ], "source": [ "many_args_and_kwargs(message='Hello World')" ] }, { "cell_type": "code", "execution_count": 24, "metadata": {}, "outputs": [], "source": [ "def grades(**kwargs):\n", " for key, value in kwargs.items():\n", " print('The key is {} and the value is {}'.format(key,value))\n", " if 'Math' in kwargs:\n", " print('The Math grade is {}'.format(kwargs['Math']))\n", " else:\n", " print('No grades for Math')" ] }, { "cell_type": "code", "execution_count": 25, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "The key is Physics and the value is 9\n", "The key is Language and the value is 8\n", "The key is History and the value is 6\n", "No grades for Math\n" ] } ], "source": [ "grades(Physics=9,Language=8, History=6, )" ] }, { "cell_type": "code", "execution_count": 26, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "The key is Python and the value is 8\n", "No grades for Math\n" ] } ], "source": [ "grades(Python=8)" ] }, { "cell_type": "code", "execution_count": 27, "metadata": {}, "outputs": [], "source": [ "def show_and_sum(*args):\n", " for value in args:\n", " print('Value:\\t{0:7.2f}'.format(value))\n", " print('_______________')\n", " print('Sum:\\t{0:7.2f}'.format(sum(args)))" ] }, { "cell_type": "code", "execution_count": 28, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Value:\t 23.00\n", "Value:\t 45.00\n", "Value:\t 124.00\n", "Value:\t 34.60\n", "Value:\t 98.24\n", "_______________\n", "Sum:\t 324.84\n" ] } ], "source": [ "show_and_sum(23,45,124,34.6,98.236)" ] }, { "cell_type": "code", "execution_count": 29, "metadata": {}, "outputs": [], "source": [ "def greeting():\n", " name = input('What is your name? ')\n", " print('How are you today, {} ?'.format(name))" ] }, { "cell_type": "code", "execution_count": 30, "metadata": {}, "outputs": [ { "name": "stdin", "output_type": "stream", "text": [ "What is your name? Renato\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "How are you today, Renato ?\n" ] } ], "source": [ "greeting()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Default parameters" ] }, { "cell_type": "code", "execution_count": 31, "metadata": {}, "outputs": [], "source": [ "def forecast(weather = 'rainy', umidity = 'high'):\n", " print('The umidity is {}'.format(umidity))\n", " print('The weather forecast is {}'.format(weather))" ] }, { "cell_type": "code", "execution_count": 32, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "The umidity is high\n", "The weather forecast is rainy\n" ] } ], "source": [ "forecast()" ] }, { "cell_type": "code", "execution_count": 33, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "The umidity is low\n", "The weather forecast is rainy\n" ] } ], "source": [ "forecast(umidity = 'low')" ] }, { "cell_type": "code", "execution_count": 34, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "The umidity is low\n", "The weather forecast is sunny\n" ] } ], "source": [ "forecast(umidity='low', weather='sunny')" ] }, { "cell_type": "code", "execution_count": 35, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "The umidity is sunny\n", "The weather forecast is low\n" ] } ], "source": [ "forecast('low','sunny')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Recursive functions\n", "\n", "![](../../Data/Figs/recursive.jpg)" ] }, { "cell_type": "code", "execution_count": 36, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "9227465\n", "1.24666166305542\n" ] } ], "source": [ "def bad_fibonacci(n):\n", " if n <= 2:\n", " return 1\n", " else:\n", " return bad_fibonacci(n-1) + bad_fibonacci(n-2)\n", " \n", "t0 = time.time()\n", "print(bad_fibonacci(35))\n", "print(time.time() - t0)" ] }, { "cell_type": "code", "execution_count": 37, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "9227465\n", "7.677078247070312e-05\n" ] } ], "source": [ "def good_fibonacci(n):\n", " x = 1\n", " y = 0\n", " for elem in range(n-1):\n", " x,y = x+y, x\n", " return(x)\n", " \n", "t0 = time.time()\n", "print(good_fibonacci(35))\n", "print(time.time() - t0)" ] }, { "cell_type": "code", "execution_count": 38, "metadata": {}, "outputs": [], "source": [ "def bmi(weight=0, height=0):\n", " if weight == 0:\n", " weight = input('What is your weight? ')\n", " if not str(weight).isdigit():\n", " print('Invalid input')\n", " bmi()\n", " return\n", " if height == 0:\n", " height = input('How tall are you? ')\n", " if not str(height).isdigit():\n", " print('Invalid input')\n", " bmi(weight=weight)\n", " return\n", " BMI = float(weight)/((float(height)/100)**2)\n", " print('Your body mass index (BMI) is {}'.format(BMI))" ] }, { "cell_type": "code", "execution_count": 39, "metadata": {}, "outputs": [ { "name": "stdin", "output_type": "stream", "text": [ "What is your weight? 74.3\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Invalid input\n" ] }, { "name": "stdin", "output_type": "stream", "text": [ "What is your weight? 74,3\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Invalid input\n" ] }, { "name": "stdin", "output_type": "stream", "text": [ "What is your weight? 74\n", "How tall are you? 1.83\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Invalid input\n" ] }, { "name": "stdin", "output_type": "stream", "text": [ "How tall are you? 183\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Your body mass index (BMI) is 22.096807907073963\n" ] } ], "source": [ "bmi()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "How to treat the user input?" ] }, { "cell_type": "code", "execution_count": 40, "metadata": {}, "outputs": [], "source": [ "def get_height(height):\n", " height = str(height)\n", " print(height)\n", " height = height.replace(',','.')\n", " print(height)\n", " return height" ] }, { "cell_type": "code", "execution_count": 41, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "1,87\n", "1.87\n" ] }, { "data": { "text/plain": [ "'1.87'" ] }, "execution_count": 41, "metadata": {}, "output_type": "execute_result" } ], "source": [ "get_height('1,87')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### [Generator Functions](https://www.programiz.com/python-programming/generator)\n", "\n", "+ _yield_: Similar to the _return_, but freezes the actual state of the function instance \n", "+ _next_ yields the generator values one at at time, until it ends with : StopIteration " ] }, { "cell_type": "code", "execution_count": 42, "metadata": {}, "outputs": [], "source": [ "def squares(number):\n", " while True:\n", " yield(number**2)\n", " number+=1" ] }, { "cell_type": "code", "execution_count": 43, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "" ] }, "execution_count": 43, "metadata": {}, "output_type": "execute_result" } ], "source": [ "squares(4)" ] }, { "cell_type": "code", "execution_count": 44, "metadata": {}, "outputs": [], "source": [ "gen1 = squares(5)\n", "gen2 = squares(5)" ] }, { "cell_type": "code", "execution_count": 45, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "25\n", "36\n", "49\n", "64\n", "81\n", "100\n", "121\n", "144\n", "169\n", "196\n" ] } ], "source": [ "for i in range(10):\n", " print(next(gen1))" ] }, { "cell_type": "code", "execution_count": 46, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "25\n" ] } ], "source": [ "print(next(gen2))" ] }, { "cell_type": "code", "execution_count": 47, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "\n", "\n" ] } ], "source": [ "print(type(squares))\n", "print(type(gen1))" ] }, { "cell_type": "code", "execution_count": 48, "metadata": {}, "outputs": [], "source": [ "def counting_time():\n", " now = time.time()\n", " while True:\n", " yield(time.time() - now)" ] }, { "cell_type": "code", "execution_count": 49, "metadata": {}, "outputs": [], "source": [ "player1 = counting_time()\n", "player2 = counting_time()" ] }, { "cell_type": "code", "execution_count": 50, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "7.152557373046875e-07" ] }, "execution_count": 50, "metadata": {}, "output_type": "execute_result" } ], "source": [ "next(player1)" ] }, { "cell_type": "code", "execution_count": 51, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "4.76837158203125e-07" ] }, "execution_count": 51, "metadata": {}, "output_type": "execute_result" } ], "source": [ "next(player2)" ] }, { "cell_type": "code", "execution_count": 52, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "0.4046499729156494" ] }, "execution_count": 52, "metadata": {}, "output_type": "execute_result" } ], "source": [ "next(player2)" ] }, { "cell_type": "code", "execution_count": 53, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "0.3917124271392822" ] }, "execution_count": 53, "metadata": {}, "output_type": "execute_result" } ], "source": [ "next(player1) - next(player2)" ] }, { "cell_type": "code", "execution_count": 54, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "-0.39171338081359863" ] }, "execution_count": 54, "metadata": {}, "output_type": "execute_result" } ], "source": [ "next(player2) - next(player1)" ] }, { "cell_type": "code", "execution_count": 55, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "2.18056583404541" ] }, "execution_count": 55, "metadata": {}, "output_type": "execute_result" } ], "source": [ "next(player1)" ] }, { "cell_type": "code", "execution_count": 56, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "2.308818817138672" ] }, "execution_count": 56, "metadata": {}, "output_type": "execute_result" } ], "source": [ "next(player2)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### An example: the horse's game" ] }, { "cell_type": "code", "execution_count": 57, "metadata": {}, "outputs": [], "source": [ "def horse():\n", " position = 0\n", " while True:\n", " step = random.randint(1,3)\n", " position += step\n", " yield position " ] }, { "cell_type": "code", "execution_count": 58, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "**************************************\n", "****************************\n", "****************************************\n", "*************************************\n", "**************************************\n", "*****************************************\n", "***********************************\n", "The winner is Bobby!\n", "[38, 28, 40, 37, 38, 41, 35]\n" ] } ], "source": [ "Apollo = horse()\n", "Rosie = horse()\n", "Dexter = horse()\n", "Connie = horse()\n", "Pepper = horse()\n", "Bobby = horse()\n", "Malhado = horse()\n", "\n", "horses = [Apollo, Rosie, Dexter, Connie, Pepper, Bobby, Malhado]\n", "\n", "while True:\n", " positions = []\n", " clear_output()\n", " for racer in horses:\n", " positions.append(next(racer))\n", " for position in positions:\n", " print('*' * position)\n", " if max(positions) > 40:\n", " gen_winner = horses[positions.index(max(positions))]\n", " winner = [name for name in globals() if globals()[name] is gen_winner][0]\n", " print(f'The winner is {winner}!')\n", " break\n", " time.sleep(1)\n", "print(positions)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### Documenting a function (docstrings)" ] }, { "cell_type": "code", "execution_count": 59, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Help on built-in function print in module builtins:\n", "\n", "print(...)\n", " print(value, ..., sep=' ', end='\\n', file=sys.stdout, flush=False)\n", " \n", " Prints the values to a stream, or to sys.stdout by default.\n", " Optional keyword arguments:\n", " file: a file-like object (stream); defaults to the current sys.stdout.\n", " sep: string inserted between values, default a space.\n", " end: string appended after the last value, default a newline.\n", " flush: whether to forcibly flush the stream.\n", "\n" ] } ], "source": [ "help(print)" ] }, { "cell_type": "code", "execution_count": 60, "metadata": {}, "outputs": [], "source": [ "def my_function(string):\n", " '''This function does almost nothing\n", " It receives a name as input and prints\n", " the uppercase version of it'''\n", " print(string.upper())" ] }, { "cell_type": "code", "execution_count": 61, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Help on function my_function in module __main__:\n", "\n", "my_function(string)\n", " This function does almost nothing\n", " It receives a name as input and prints\n", " the uppercase version of it\n", "\n" ] } ], "source": [ "help(my_function)" ] }, { "cell_type": "code", "execution_count": 62, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "\u001b[0;31mSignature:\u001b[0m \u001b[0mmy_function\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mstring\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n", "\u001b[0;31mDocstring:\u001b[0m\n", "This function does almost nothing\n", "It receives a name as input and prints\n", "the uppercase version of it\n", "\u001b[0;31mFile:\u001b[0m /tmp/ipykernel_45398/1309085507.py\n", "\u001b[0;31mType:\u001b[0m function\n" ] }, "metadata": {}, "output_type": "display_data" } ], "source": [ "my_function?" ] }, { "cell_type": "code", "execution_count": 63, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "THE WIZARD DUCK\n" ] } ], "source": [ "my_function('The Wizard Duck')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### [Type hints](https://docs.python.org/3/library/typing.html)\n", "\n", "The Python runtime does not enforce function and variable type annotations, but they can be used, since Python 3.5, by third party tools such as type checkers, IDEs, linters, etc." ] }, { "cell_type": "code", "execution_count": 64, "metadata": {}, "outputs": [], "source": [ "def addTwo(x):\n", " return x + 2" ] }, { "cell_type": "code", "execution_count": 65, "metadata": {}, "outputs": [], "source": [ "def newaddTwo(x : int) -> int:\n", " return x + 2" ] }, { "cell_type": "code", "execution_count": 66, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "7" ] }, "execution_count": 66, "metadata": {}, "output_type": "execute_result" } ], "source": [ "addTwo(5)" ] }, { "cell_type": "code", "execution_count": 67, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "7" ] }, "execution_count": 67, "metadata": {}, "output_type": "execute_result" } ], "source": [ "newaddTwo(5)" ] }, { "cell_type": "code", "execution_count": 68, "metadata": {}, "outputs": [ { "ename": "TypeError", "evalue": "can only concatenate str (not \"int\") to str", "output_type": "error", "traceback": [ "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m", "\u001b[0;31mTypeError\u001b[0m Traceback (most recent call last)", "Input \u001b[0;32mIn [68]\u001b[0m, in \u001b[0;36m\u001b[0;34m()\u001b[0m\n\u001b[0;32m----> 1\u001b[0m addTwo(\u001b[38;5;124m'\u001b[39m\u001b[38;5;124mtwo\u001b[39m\u001b[38;5;124m'\u001b[39m)\n", "Input \u001b[0;32mIn [64]\u001b[0m, in \u001b[0;36maddTwo\u001b[0;34m(x)\u001b[0m\n\u001b[1;32m 1\u001b[0m \u001b[38;5;28;01mdef\u001b[39;00m \u001b[38;5;21maddTwo\u001b[39m(x):\n\u001b[0;32m----> 2\u001b[0m \u001b[38;5;28;01mreturn\u001b[39;00m \u001b[43mx\u001b[49m\u001b[43m \u001b[49m\u001b[38;5;241;43m+\u001b[39;49m\u001b[43m \u001b[49m\u001b[38;5;241;43m2\u001b[39;49m\n", "\u001b[0;31mTypeError\u001b[0m: can only concatenate str (not \"int\") to str" ] } ], "source": [ "addTwo('two')" ] }, { "cell_type": "code", "execution_count": 69, "metadata": {}, "outputs": [ { "ename": "TypeError", "evalue": "can only concatenate str (not \"int\") to str", "output_type": "error", "traceback": [ "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m", "\u001b[0;31mTypeError\u001b[0m Traceback (most recent call last)", "Input \u001b[0;32mIn [69]\u001b[0m, in \u001b[0;36m\u001b[0;34m()\u001b[0m\n\u001b[0;32m----> 1\u001b[0m newaddTwo(\u001b[38;5;124m'\u001b[39m\u001b[38;5;124mtwo\u001b[39m\u001b[38;5;124m'\u001b[39m)\n", "Input \u001b[0;32mIn [65]\u001b[0m, in \u001b[0;36mnewaddTwo\u001b[0;34m(x)\u001b[0m\n\u001b[1;32m 1\u001b[0m \u001b[38;5;28;01mdef\u001b[39;00m \u001b[38;5;21mnewaddTwo\u001b[39m(x : \u001b[38;5;28mint\u001b[39m) \u001b[38;5;241m-\u001b[39m\u001b[38;5;241m>\u001b[39m \u001b[38;5;28mint\u001b[39m:\n\u001b[0;32m----> 2\u001b[0m \u001b[38;5;28;01mreturn\u001b[39;00m \u001b[43mx\u001b[49m\u001b[43m \u001b[49m\u001b[38;5;241;43m+\u001b[39;49m\u001b[43m \u001b[49m\u001b[38;5;241;43m2\u001b[39;49m\n", "\u001b[0;31mTypeError\u001b[0m: can only concatenate str (not \"int\") to str" ] } ], "source": [ "newaddTwo('two')" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [] } ], "metadata": { "kernelspec": { "display_name": "Python 3 (ipykernel)", "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.8.10" } }, "nbformat": 4, "nbformat_minor": 4 }