{ "cells": [ { "cell_type": "markdown", "metadata": { "nbsphinx": "hidden" }, "source": [ "[prev: *Unpacking*](unpacking.ipynb) | [home](../index.ipynb) | [next: Utilisation avancée des conteneurs](container-methods.ipynb)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# Le retour des fonctions\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Retourner plusieurs valeurs" ] }, { "cell_type": "code", "execution_count": 1, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "(tuple, (1, 2, 3, 4, 5))" ] }, "execution_count": 1, "metadata": {}, "output_type": "execute_result" } ], "source": [ "def compte_sur_une_main():\n", " return 1, 2, 3, 4, 5\n", "\n", "result = compte_sur_une_main()\n", "\n", "type(result), result" ] }, { "cell_type": "code", "execution_count": 2, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "lolo\n", "lololo\n" ] } ], "source": [ "# on peut utiliser l'unpacking pour nommer directement les résultats\n", "\n", "def double_triple(x):\n", " return 2 * x, 3 * x\n", "\n", "a = 'lo'\n", "\n", "double_a, triple_a = double_triple(a)\n", "\n", "print(double_a)\n", "print(triple_a)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Nommer les arguments" ] }, { "cell_type": "code", "execution_count": 3, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Help on function divise in module __main__:\n", "\n", "divise(numerateur, denominateur)\n", " calcul la division de numerateur par denominateur\n", "\n" ] } ], "source": [ "# Les noms des arguments font partie de l'interface d'une fonction\n", "\n", "def divise(numerateur, denominateur):\n", " \"calcul la division de numerateur par denominateur\"\n", " return numerateur / denominateur\n", "\n", "help(divise)" ] }, { "cell_type": "code", "execution_count": 4, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "5.0" ] }, "execution_count": 4, "metadata": {}, "output_type": "execute_result" } ], "source": [ "divise(10, 2)" ] }, { "cell_type": "code", "execution_count": 5, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "5.0" ] }, "execution_count": 5, "metadata": {}, "output_type": "execute_result" } ], "source": [ "divise(numerateur=10, denominateur=2)" ] }, { "cell_type": "code", "execution_count": 6, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "5.0" ] }, "execution_count": 6, "metadata": {}, "output_type": "execute_result" } ], "source": [ "divise(denominateur=2, numerateur=10)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Arguments avec une valeur par défaut" ] }, { "cell_type": "code", "execution_count": 7, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "toto\n", " toto\n", "- - toto\n", "~~~~toto\n" ] } ], "source": [ "def indente(texte, indentation=' '):\n", " return indentation + texte\n", "\n", "print('toto')\n", "print(indente('toto'))\n", "print(indente('toto', '- - '))\n", "print(indente('toto', indentation='~~~~'))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Nombre d'arguments variables" ] }, { "cell_type": "code", "execution_count": 8, "metadata": {}, "outputs": [], "source": [ "# En pratique\n", "\n", "def somme(*args):\n", " \"calcule la somme de tous les arguments\"\n", " result = 0\n", " for valeur in args:\n", " result += valeur\n", " return result" ] }, { "cell_type": "code", "execution_count": 9, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "4" ] }, "execution_count": 9, "metadata": {}, "output_type": "execute_result" } ], "source": [ "somme(2, 2)" ] }, { "cell_type": "code", "execution_count": 10, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "85" ] }, "execution_count": 10, "metadata": {}, "output_type": "execute_result" } ], "source": [ "somme(2, 5, 78)" ] }, { "cell_type": "code", "execution_count": 11, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ " (2, 2)\n", " (2, 5, 78)\n" ] } ], "source": [ "# `args` est un tuple\n", "\n", "def test(*args):\n", " print(type(args), args)\n", "\n", "test(2, 2)\n", "test(2, 5, 78)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Utiliser un list/tuple pour passer les arguments d'une fonction" ] }, { "cell_type": "code", "execution_count": 12, "metadata": {}, "outputs": [], "source": [ "# une fonction avec plusieurs arguments\n", "\n", "def affiche_abc(a, b, c):\n", " print('voici a :', a)\n", " print('voici b :', b)\n", " print('voici c :', c)" ] }, { "cell_type": "code", "execution_count": 13, "metadata": {}, "outputs": [], "source": [ "# 'arguments' contient mes arguments\n", "\n", "arguments = ['^ ^', ' o ', '\\_/']" ] }, { "cell_type": "code", "execution_count": 14, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "voici a : ^ ^\n", "voici b : o \n", "voici c : \\_/\n" ] } ], "source": [ "# si l'on sait comme ici que 'affiche_abc()' prend 3 arguments\n", "# on peut faire ainsi\n", "\n", "affiche_abc(arguments[0], arguments[1], arguments[2])" ] }, { "cell_type": "code", "execution_count": 15, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "voici a : ^ ^\n", "voici b : o \n", "voici c : \\_/\n" ] } ], "source": [ "# voici une solution plus courte et robuste\n", "\n", "affiche_abc(*arguments)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Nombre d'arguments 'mot-clef' variables" ] }, { "cell_type": "code", "execution_count": 16, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ " {'a': 2, 'b': 2}\n", " {'toto': 2, 'tata': 5, 'titi': 78}\n" ] } ], "source": [ "# `kwargs` est un dict\n", "\n", "def test(**kwargs):\n", " print(type(kwargs), kwargs)\n", "\n", "test(a=2, b=2)\n", "test(toto=2, tata=5, titi=78)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Utiliser un dict pour passer les arguments d'une fonction" ] }, { "cell_type": "code", "execution_count": 17, "metadata": {}, "outputs": [], "source": [ "# gardons notre fonction avec plusieurs arguments\n", "\n", "def affiche_abc(a, b, c):\n", " print('voici a :', a)\n", " print('voici b :', b)\n", " print('voici c :', c)" ] }, { "cell_type": "code", "execution_count": 18, "metadata": {}, "outputs": [], "source": [ "# cette fois, nos arguments sont stockés dans un dict\n", "\n", "keyword_arguments = {\n", "'a' : \"* *\",\n", "'b' : \" ' \",\n", "'c' : \" ~ \",\n", "}" ] }, { "cell_type": "code", "execution_count": 19, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "voici a : * *\n", "voici b : ' \n", "voici c : ~ \n" ] } ], "source": [ "# si on connait bien les mots-clefs\n", "\n", "affiche_abc(a=keyword_arguments['a'], b=keyword_arguments['b'], c=keyword_arguments['c'])" ] }, { "cell_type": "code", "execution_count": 20, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "voici a : * *\n", "voici b : ' \n", "voici c : ~ \n" ] } ], "source": [ "# si on connait la bonne formule\n", "\n", "affiche_abc(**keyword_arguments)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## fonction anonyme : `lambda`" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "- Pour définir rapidement une fonction simple.\n", "- Le traitement des arguments est le même que pour les fonctions.\n", "- Mais le corps est réduit à une instruction dont le résultat est la valeur retournée." ] }, { "cell_type": "code", "execution_count": 21, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "function" ] }, "execution_count": 21, "metadata": {}, "output_type": "execute_result" } ], "source": [ "double = lambda x: 2 * x\n", "\n", "type(double)" ] }, { "cell_type": "code", "execution_count": 22, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "6" ] }, "execution_count": 22, "metadata": {}, "output_type": "execute_result" } ], "source": [ "double(3)" ] }, { "cell_type": "code", "execution_count": 23, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'toto'" ] }, "execution_count": 23, "metadata": {}, "output_type": "execute_result" } ], "source": [ "double('to')" ] }, { "cell_type": "code", "execution_count": 24, "metadata": {}, "outputs": [], "source": [ "# Situation la plus courante d'utilisation de lambda:\n", "# définir une fonction sans la nommer\n", "\n", "def applique_sur_42(fonction):\n", " \"renvoie fonction(42)\"\n", " return fonction(42)" ] }, { "cell_type": "code", "execution_count": 25, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "6.0" ] }, "execution_count": 25, "metadata": {}, "output_type": "execute_result" } ], "source": [ "applique_sur_42(lambda x: x / 7)" ] }, { "cell_type": "code", "execution_count": 26, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^'" ] }, "execution_count": 26, "metadata": {}, "output_type": "execute_result" } ], "source": [ "applique_sur_42(lambda x: x * '^')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Exercices" ] } ], "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.10.12" } }, "nbformat": 4, "nbformat_minor": 4 }