{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "## Modules" ] }, { "cell_type": "code", "execution_count": 19, "metadata": {}, "outputs": [ { "data": { "text/html": [ "
run previous cell, wait for 2 seconds
\n", "" ], "text/plain": [ "" ] }, "execution_count": 19, "metadata": {}, "output_type": "execute_result" } ], "source": [ "\n", "# Afficher la table des matières\n", "\n", "from jyquickhelper import add_notebook_menu\n", "add_notebook_menu()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "* Un module contient un ensemble de fonctions et commandes\n", "* Python dispose d’une bibliothèque de base quand il est initialisé. Et selon nos besoins ces bibliothèques vont être chargées.\n", "* Pour utiliser un module, il faut l’importer.\n", " * Nous avons deux types de modules : ceux disponibles sur Internet (programmés par d’autres) et ceux que l’on programme soi-même.\n", "* Pour les modules disponibles, les bibliothèques souvent utiles pour faire un programme python scientifique, nous avons :\n", " import os\n", " import sys\n", " import numpy as np\n", " import math \n", " import random\n", " import csv\n", " import scipy\n", " import matplotlib . pylab as plt" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Syntaxe d'importation" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Syntaxe 1 : importer le module sous son nom" ] }, { "cell_type": "code", "execution_count": 20, "metadata": { "collapsed": true }, "outputs": [], "source": [ "import math\n", "# on peut utiliser math.sin, math.sqrt..." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Syntaxe 2 : importer le module sous un nom différent\n", " - permet d’abréger le nom des modules" ] }, { "cell_type": "code", "execution_count": 21, "metadata": { "collapsed": true }, "outputs": [], "source": [ "import math as m\n", "\n", "# on utilise m.sin, m.sqrt..." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Syntaxe 3 : importer seulement certaines définitions" ] }, { "cell_type": "code", "execution_count": 22, "metadata": { "collapsed": true }, "outputs": [], "source": [ "from math import sqrt\n", "# on peut utiliser uniquement sqrt (les autres fonctions math.sin..., ne sont pas reconnu)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "* On peut utiliser **help** pour obtenir de l'aide sur les modules importés." ] }, { "cell_type": "code", "execution_count": 23, "metadata": { "collapsed": false }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Help on module math:\n", "\n", "NAME\n", " math\n", "\n", "MODULE REFERENCE\n", " https://docs.python.org/3.8/library/math\n", " \n", " The following documentation is automatically generated from the Python\n", " source files. It may be incomplete, incorrect or include features that\n", " are considered implementation detail and may vary between Python\n", " implementations. When in doubt, consult the module reference at the\n", " location listed above.\n", "\n", "DESCRIPTION\n", " This module provides access to the mathematical functions\n", " defined by the C standard.\n", "\n", "FUNCTIONS\n", " acos(x, /)\n", " Return the arc cosine (measured in radians) of x.\n", " \n", " acosh(x, /)\n", " Return the inverse hyperbolic cosine of x.\n", " \n", " asin(x, /)\n", " Return the arc sine (measured in radians) of x.\n", " \n", " asinh(x, /)\n", " Return the inverse hyperbolic sine of x.\n", " \n", " atan(x, /)\n", " Return the arc tangent (measured in radians) of x.\n", " \n", " atan2(y, x, /)\n", " Return the arc tangent (measured in radians) of y/x.\n", " \n", " Unlike atan(y/x), the signs of both x and y are considered.\n", " \n", " atanh(x, /)\n", " Return the inverse hyperbolic tangent of x.\n", " \n", " ceil(x, /)\n", " Return the ceiling of x as an Integral.\n", " \n", " This is the smallest integer >= x.\n", " \n", " comb(n, k, /)\n", " Number of ways to choose k items from n items without repetition and without order.\n", " \n", " Evaluates to n! / (k! * (n - k)!) when k <= n and evaluates\n", " to zero when k > n.\n", " \n", " Also called the binomial coefficient because it is equivalent\n", " to the coefficient of k-th term in polynomial expansion of the\n", " expression (1 + x)**n.\n", " \n", " Raises TypeError if either of the arguments are not integers.\n", " Raises ValueError if either of the arguments are negative.\n", " \n", " copysign(x, y, /)\n", " Return a float with the magnitude (absolute value) of x but the sign of y.\n", " \n", " On platforms that support signed zeros, copysign(1.0, -0.0)\n", " returns -1.0.\n", " \n", " cos(x, /)\n", " Return the cosine of x (measured in radians).\n", " \n", " cosh(x, /)\n", " Return the hyperbolic cosine of x.\n", " \n", " degrees(x, /)\n", " Convert angle x from radians to degrees.\n", " \n", " dist(p, q, /)\n", " Return the Euclidean distance between two points p and q.\n", " \n", " The points should be specified as sequences (or iterables) of\n", " coordinates. Both inputs must have the same dimension.\n", " \n", " Roughly equivalent to:\n", " sqrt(sum((px - qx) ** 2.0 for px, qx in zip(p, q)))\n", " \n", " erf(x, /)\n", " Error function at x.\n", " \n", " erfc(x, /)\n", " Complementary error function at x.\n", " \n", " exp(x, /)\n", " Return e raised to the power of x.\n", " \n", " expm1(x, /)\n", " Return exp(x)-1.\n", " \n", " This function avoids the loss of precision involved in the direct evaluation of exp(x)-1 for small x.\n", " \n", " fabs(x, /)\n", " Return the absolute value of the float x.\n", " \n", " factorial(x, /)\n", " Find x!.\n", " \n", " Raise a ValueError if x is negative or non-integral.\n", " \n", " floor(x, /)\n", " Return the floor of x as an Integral.\n", " \n", " This is the largest integer <= x.\n", " \n", " fmod(x, y, /)\n", " Return fmod(x, y), according to platform C.\n", " \n", " x % y may differ.\n", " \n", " frexp(x, /)\n", " Return the mantissa and exponent of x, as pair (m, e).\n", " \n", " m is a float and e is an int, such that x = m * 2.**e.\n", " If x is 0, m and e are both 0. Else 0.5 <= abs(m) < 1.0.\n", " \n", " fsum(seq, /)\n", " Return an accurate floating point sum of values in the iterable seq.\n", " \n", " Assumes IEEE-754 floating point arithmetic.\n", " \n", " gamma(x, /)\n", " Gamma function at x.\n", " \n", " gcd(x, y, /)\n", " greatest common divisor of x and y\n", " \n", " hypot(...)\n", " hypot(*coordinates) -> value\n", " \n", " Multidimensional Euclidean distance from the origin to a point.\n", " \n", " Roughly equivalent to:\n", " sqrt(sum(x**2 for x in coordinates))\n", " \n", " For a two dimensional point (x, y), gives the hypotenuse\n", " using the Pythagorean theorem: sqrt(x*x + y*y).\n", " \n", " For example, the hypotenuse of a 3/4/5 right triangle is:\n", " \n", " >>> hypot(3.0, 4.0)\n", " 5.0\n", " \n", " isclose(a, b, *, rel_tol=1e-09, abs_tol=0.0)\n", " Determine whether two floating point numbers are close in value.\n", " \n", " rel_tol\n", " maximum difference for being considered \"close\", relative to the\n", " magnitude of the input values\n", " abs_tol\n", " maximum difference for being considered \"close\", regardless of the\n", " magnitude of the input values\n", " \n", " Return True if a is close in value to b, and False otherwise.\n", " \n", " For the values to be considered close, the difference between them\n", " must be smaller than at least one of the tolerances.\n", " \n", " -inf, inf and NaN behave similarly to the IEEE 754 Standard. That\n", " is, NaN is not close to anything, even itself. inf and -inf are\n", " only close to themselves.\n", " \n", " isfinite(x, /)\n", " Return True if x is neither an infinity nor a NaN, and False otherwise.\n", " \n", " isinf(x, /)\n", " Return True if x is a positive or negative infinity, and False otherwise.\n", " \n", " isnan(x, /)\n", " Return True if x is a NaN (not a number), and False otherwise.\n", " \n", " isqrt(n, /)\n", " Return the integer part of the square root of the input.\n", " \n", " ldexp(x, i, /)\n", " Return x * (2**i).\n", " \n", " This is essentially the inverse of frexp().\n", " \n", " lgamma(x, /)\n", " Natural logarithm of absolute value of Gamma function at x.\n", " \n", " log(...)\n", " log(x, [base=math.e])\n", " Return the logarithm of x to the given base.\n", " \n", " If the base not specified, returns the natural logarithm (base e) of x.\n", " \n", " log10(x, /)\n", " Return the base 10 logarithm of x.\n", " \n", " log1p(x, /)\n", " Return the natural logarithm of 1+x (base e).\n", " \n", " The result is computed in a way which is accurate for x near zero.\n", " \n", " log2(x, /)\n", " Return the base 2 logarithm of x.\n", " \n", " modf(x, /)\n", " Return the fractional and integer parts of x.\n", " \n", " Both results carry the sign of x and are floats.\n", " \n", " perm(n, k=None, /)\n", " Number of ways to choose k items from n items without repetition and with order.\n", " \n", " Evaluates to n! / (n - k)! when k <= n and evaluates\n", " to zero when k > n.\n", " \n", " If k is not specified or is None, then k defaults to n\n", " and the function returns n!.\n", " \n", " Raises TypeError if either of the arguments are not integers.\n", " Raises ValueError if either of the arguments are negative.\n", " \n", " pow(x, y, /)\n", " Return x**y (x to the power of y).\n", " \n", " prod(iterable, /, *, start=1)\n", " Calculate the product of all the elements in the input iterable.\n", " \n", " The default start value for the product is 1.\n", " \n", " When the iterable is empty, return the start value. This function is\n", " intended specifically for use with numeric values and may reject\n", " non-numeric types.\n", " \n", " radians(x, /)\n", " Convert angle x from degrees to radians.\n", " \n", " remainder(x, y, /)\n", " Difference between x and the closest integer multiple of y.\n", " \n", " Return x - n*y where n*y is the closest integer multiple of y.\n", " In the case where x is exactly halfway between two multiples of\n", " y, the nearest even value of n is used. The result is always exact.\n", " \n", " sin(x, /)\n", " Return the sine of x (measured in radians).\n", " \n", " sinh(x, /)\n", " Return the hyperbolic sine of x.\n", " \n", " sqrt(x, /)\n", " Return the square root of x.\n", " \n", " tan(x, /)\n", " Return the tangent of x (measured in radians).\n", " \n", " tanh(x, /)\n", " Return the hyperbolic tangent of x.\n", " \n", " trunc(x, /)\n", " Truncates the Real x to the nearest Integral toward 0.\n", " \n", " Uses the __trunc__ magic method.\n", "\n", "DATA\n", " e = 2.718281828459045\n", " inf = inf\n", " nan = nan\n", " pi = 3.141592653589793\n", " tau = 6.283185307179586\n", "\n", "FILE\n", " /opt/anaconda3/lib/python3.8/lib-dynload/math.cpython-38-darwin.so\n", "\n", "\n" ] } ], "source": [ "help(math)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "ou, si on veut connaître en seul coup d’oeil toutes les méthodes ou variables associées à\n", "un module (ou objet), on peut utiliser la commande **dir**" ] }, { "cell_type": "code", "execution_count": 24, "metadata": { "collapsed": false, "scrolled": true }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "['__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', 'acos', 'acosh', 'asin', 'asinh', 'atan', 'atan2', 'atanh', 'ceil', 'comb', 'copysign', 'cos', 'cosh', 'degrees', 'dist', 'e', 'erf', 'erfc', 'exp', 'expm1', 'fabs', 'factorial', 'floor', 'fmod', 'frexp', 'fsum', 'gamma', 'gcd', 'hypot', 'inf', 'isclose', 'isfinite', 'isinf', 'isnan', 'isqrt', 'ldexp', 'lgamma', 'log', 'log10', 'log1p', 'log2', 'modf', 'nan', 'perm', 'pi', 'pow', 'prod', 'radians', 'remainder', 'sin', 'sinh', 'sqrt', 'tan', 'tanh', 'tau', 'trunc']\n" ] } ], "source": [ "print(dir(math))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### Modules courants" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Il existe une série de modules que vous serez probablement amenés à utiliser si vous programmez en Python. En voici une liste non exhaustive. Pour la liste complète, reportez-vous à[la page des modules](http://www.python.org/doc/current/modindex.html) sur [le site de Python](http://www.python.org/) :\n", "\n", " *[math](http://www.python.org/doc/current/library/math.html) : fonctions et constantes mathématiques de base (sin, cos, exp, pi...).\n", " \n", "*[sys](http://www.python.org/doc/current/library/sys.html) : passage d'arguments, gestion de l'entrée/sortie standard...\n", " \n", "*[os](http://www.python.org/doc/current/library/os.html) : dialogue avec le système d'exploitation (e.g. permet de sortir de Python, lancer une commande en {\\it shell}, puis de revenir à Python).\n", " \n", "*[random](http://www.python.org/doc/current/library/random.html) : génération de nombres aléatoires.\n", " \n", "*[time](http://www.python.org/doc/current/library/time.html) : permet d'accéder à l'heure de l'ordinateur et aux fonctions gérant le temps.\n", "\n", "*[calendar](http://www.python.org/doc/current/library/calendar.html) : fonctions de calendrier.\n", "\n", "*[profile](http://www.python.org/doc/current/library/profile.html) : permet d'évaluer le temps d'exécution de chaque fonction dans un programme ({\\it profiling} en anglais).\n", "\n", "*[urllib2](http://www.python.org/doc/current/library/urllib2.html) : permet de récupérer des données sur internet depuis python.\n", "\n", "*[Tkinter](http://www.python.org/doc/current/library/tkinter.html) : interface python avec Tk (permet de créer des objets graphiques; nécessite d'installer [Tk](http://www.tcl.tk/software/tcltk/index.html).\n", "\n", "*[re](http://www.python.org/doc/current/library/re.html) : gestion des expressions régulières.\n", "\n", "\n", "*Je vous conseille vivement d'aller surfer sur les pages de ces modules pour découvrir toutes leurs potentialités.*\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Création de vos propres modules" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "* Vous pouvez également définir vos propres modules.\n", "\n", "Considérez l'exemple suivant: le fichier mymodule.py contient des exemples simples d'implémentation d'une variable, d'une fonction et d'une classe :" ] }, { "cell_type": "code", "execution_count": 25, "metadata": { "collapsed": false }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Overwriting monmodule.py\n" ] } ], "source": [ "%%file monmodule.py\n", "\"\"\"\n", "Exemple de module python. Contient une variable appelée ma_variable,\n", "Une fonction appelée ma_fonction, et une classe appelée MaClasse.\n", "\"\"\"\n", "\n", "ma_variable = 0\n", "\n", "def ma_fonction():\n", " \"\"\"\n", " Exemple de fonction\n", " \"\"\"\n", " return ma_variable*2\n", " \n", "class MaClasse:\n", " \"\"\"\n", " Exemple de classe.\n", " \"\"\"\n", "\n", " def __init__(self):\n", " self.variable = ma_variable\n", " \n", " def set_variable(self, n_val):\n", " \"\"\"\n", " Définir self.variable à n_val\n", " \"\"\"\n", " self.variable = n_val\n", " \n", " def get_variable(self):\n", " return self.variable" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "On peut importer le module monmodule dans notre programme Python en utilisant import :" ] }, { "cell_type": "code", "execution_count": 26, "metadata": { "collapsed": false }, "outputs": [], "source": [ "import monmodule" ] }, { "cell_type": "code", "execution_count": 27, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "0" ] }, "execution_count": 27, "metadata": {}, "output_type": "execute_result" } ], "source": [ "monmodule.ma_variable" ] }, { "cell_type": "markdown", "metadata": { "collapsed": true }, "source": [ "#### La bibliothèque standard et ses modules" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Une bibliothèque standard Python (Python Standard Library) est une collection de modules qui donne accès à des fonctionnalités de bases : appels au système d'exploitation, gestion des fichiers, gestion des chaînes de caractères, interface réseau, etc." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### Références\n", "\n", "* The Python Language Reference: http://docs.python.org/2/reference/index.html\n", "* The Python Standard Library: http://docs.python.org/2/library/ (Pour une liste complète des modules python)" ] } ], "metadata": { "anaconda-cloud": {}, "interpreter": { "hash": "40d3a090f54c6569ab1632332b64b2c03c39dcf918b08424e98f38b5ae0af88f" }, "kernelspec": { "display_name": "Python [Root]", "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.8" } }, "nbformat": 4, "nbformat_minor": 0 }