Pourquoi et comment faire le changement – Real Python

By | septembre 9, 2019

python pour débutant

MATLAB® est largement reconnu comme environnement de haute qualité pour tout travail impliquant des tableaux, des matrices ou de l’algèbre linéaire. Python est plus récent dans ce domaine mais devient de plus en plus populaire pour des tâches similaires. Comme vous le verrez dans cet article, Python dispose de toute la puissance de calcul de MATLAB pour les tâches scientifiques et permet de développer rapidement et facilement des applications robustes. Toutefois, la comparaison entre MATLAB et Python présente des différences importantes dont vous aurez besoin pour apprendre à basculer efficacement.

Dans cet article, vous apprendrez comment:

  • Évaluez les différences entre MATLAB et Python
  • Configurer un environnement pour Python qui duplique la plupart des fonctions MATLAB
  • Convertir des scripts de MATLAB en Python
  • Évitez les problèmes courants que vous pourriez rencontrer lors du passage de MATLAB à Python
  • Écrivez un code qui ressemble à Python

MATLAB vs Python: Comparaison des fonctionnalités et de la philosophie

Python est un langage de programmation général et de haut niveau conçu pour la facilité d'utilisation par les êtres humains dans l'accomplissement de toutes sortes de tâches. Python a été créé par Guido van Rossum et a été publié au début des années 90. Python est un langage mature développé par des centaines de collaborateurs à travers le monde.

Python est utilisé par les développeurs travaillant sur de petits projets personnels jusqu'aux plus grandes entreprises Internet du monde. Non seulement Python exécute-t-il Reddit et Dropbox, mais l'algorithme original de Google a été écrit en Python. En outre, le framework Django basé sur Python utilise Instagram et de nombreux autres sites Web. Sur le plan scientifique et technique, les données nécessaires à la création de la photo d'un trou noir datant de 2019 ont été traitées en Python, et de grandes entreprises comme Netflix utilisent Python dans leurs analyses de données.

Il existe également une différence philosophique importante dans la comparaison entre MATLAB et Python. MATLAB est propriétaire, source fermée Logiciel. Pour la plupart des gens, une licence d'utilisation de MATLAB est assez chère, ce qui signifie que si vous avez du code dans MATLAB, seules les personnes ayant les moyens d'acheter une licence pourront l'exécuter. De plus, les utilisateurs sont facturés pour chaque boîte à outils supplémentaire qu'ils souhaitent installer pour étendre les fonctionnalités de base de MATLAB. Outre le coût, le langage MATLAB est développé exclusivement par Mathworks. Si Mathworks devait cesser ses activités, MATLAB ne pourrait plus être développé et pourrait éventuellement cesser de fonctionner.

D'autre part, Python est libre et open-source Logiciel. Vous pouvez non seulement télécharger gratuitement Python, mais également télécharger, consulter et modifier le code source. C'est un gros avantage pour Python car cela signifie que n'importe qui peut suivre le développement du langage si les développeurs actuels ne peuvent pas continuer pour une raison quelconque.

Si vous êtes chercheur ou scientifique, l’utilisation de logiciels à source ouverte présente de gros avantages. Paul Romer, lauréat du prix Nobel d'économie 2018, vient de se convertir à Python. Selon lui, le passage aux logiciels à code source ouvert en général, et à Python en particulier, a renforcé l'intégrité et la responsabilité de ses recherches. En effet, tout le code pouvait être partagé et exécuté par tout lecteur intéressé. Le professeur Romer a écrit un excellent article, Jupyter, Mathematica et l’avenir du document de recherche, sur son expérience avec les logiciels à code source ouvert.

De plus, Python étant disponible gratuitement, un public beaucoup plus large peut utiliser le code que vous développez. Comme vous le verrez un peu plus loin dans cet article, Python possède une formidable communauté qui peut vous aider à vous familiariser avec la langue et à faire progresser vos connaissances. Il existe des dizaines de milliers de tutoriels, d'articles et de livres sur le développement de logiciels Python. En voici quelques-uns pour vous aider à démarrer:

De plus, avec autant de développeurs dans la communauté, il existe des centaines de milliers de packages gratuits pour accomplir la plupart des tâches que vous voudrez effectuer avec Python. Vous en apprendrez plus sur la façon d’obtenir ces packages plus loin dans cet article.

Comme MATLAB, Python est un interprété la langue. Cela signifie que le code Python peut être transféré entre toutes les plates-formes de système d'exploitation et architectures de CPU majeures, avec seulement de petites modifications nécessaires pour les différentes plates-formes. Il existe des distributions de Python pour les processeurs et les microcontrôleurs d'ordinateurs de bureau et d'ordinateurs portables comme Adafruit. Python peut également communiquer avec d’autres microcontrôleurs comme Arduino grâce à une interface de programmation simple et pratiquement identique, quel que soit le système d’exploitation hôte.

Pour toutes ces raisons, et bien d’autres encore, Python est un excellent choix pour remplacer MATLAB en tant que langage de programmation de votre choix. Maintenant que vous êtes convaincu d’essayer Python, poursuivez votre lecture pour savoir comment l’obtenir sur votre ordinateur et comment passer de MATLAB!

Configuration de votre environnement pour Python

Dans cette section, vous apprendrez:

  • Comment installer Python sur votre ordinateur pour une transition transparente de MATLAB
  • Comment installer des remplaçants pour l'environnement de développement intégré MATLAB
  • Comment utiliser les remplacements de MATLAB sur votre ordinateur

Obtenir Python via Anaconda

Python peut être téléchargé à partir d’un certain nombre de sources différentes, appelées les distributions. Par exemple, le Python que vous pouvez télécharger sur le site Web officiel de Python est une distribution. Une autre distribution Python très populaire, en particulier pour les applications de mathématiques, sciences, ingénierie et informatique, est la distribution Anaconda.

Anaconda est si populaire pour deux raisons principales:

  1. Anaconda distribue des packages pré-construits pour Windows, macOS et Linux, ce qui signifie que le processus d'installation est très simple et identique pour les trois principales plates-formes.

  2. Anaconda inclut tous les packages les plus populaires pour les charges de travail de type ingénierie et science des données dans un seul programme d'installation.

Pour créer un environnement très similaire à MATLAB, vous devez télécharger et installer Anaconda. A ce jour, deux versions principales de Python sont disponibles: Python 2 et Python 3. Vous devez absolument installer la version d'Anaconda pour Python 3, car Python 2 ne sera plus pris en charge après le 1er janvier 2020. Python 3.7 est la version la plus récente. version récente au moment d'écrire ces lignes, mais Python 3.8 devrait sortir quelques mois après la publication de cet article. 3.7 ou 3.8 fonctionneront de la même manière, choisissez donc la version la plus récente que vous pouvez.

Une fois que vous avez téléchargé le programme d’installation d’Anaconda, vous pouvez suivre les procédures de configuration par défaut en fonction de votre plate-forme. Vous devez installer Anaconda dans un répertoire ne nécessitant pas l'autorisation de l'administrateur pour modifier, qui est le paramètre par défaut du programme d'installation.

Avec Anaconda installé, il existe quelques programmes spécifiques que vous devriez connaître. Le moyen le plus simple de lancer des applications consiste à utiliser Anaconda Navigator. Sous Windows, vous pouvez le trouver dans le menu Démarrer et sur macOS, dans le tableau de bord. Voici une capture d’Anaconda Navigator sous Windows:

Fenêtre principale d'Anaconda Navigator montrant les applications installées

Dans la capture d'écran, vous pouvez voir plusieurs applications installées, y compris JupyterLab, Jupyter Notebook, et Spyder, que vous en apprendrez plus tard dans ce tutoriel.

Sous Windows, vous devez connaître une autre application. C'est appelé Anaconda Invite, et c’est une invite de commande configurée spécifiquement pour fonctionner avec conda sous Windows. Si vous voulez taper conda commandes dans un terminal, plutôt que d'utiliser l'interface graphique de Navigator, vous devez utiliser Anaconda Prompt sous Windows.

Sur macOS, vous pouvez utiliser n’importe quelle application de terminal telle que Terminal.app ou iTerm2 par défaut pour accéder à conda à partir de la ligne de commande. Sous Linux, vous pouvez utiliser l'émulateur de terminal de votre choix. L'émulateur spécifique installé dépend de votre distribution Linux.

Python inclut également un autre moyen d’installer des paquets, appelé pépin. Si vous utilisez Anaconda, vous devriez toujours préférer installer les paquets en utilisant conda dès que possible. Parfois, cependant, un package est uniquement disponible avec pépin, et pour ces cas, vous pouvez lire What Is Pip? Un guide pour les nouveaux pythonistes.

Obtenir un environnement de développement intégré

L'un des gros avantages de MATLAB est qu'il inclut un environnement de développement avec le logiciel. C’est la fenêtre dans laquelle vous êtes probablement habitué. Une console au centre vous permet de taper des commandes, un explorateur de variables à droite et une liste de répertoires à gauche.

Contrairement à MATLAB, Python n’a pas d’environnement de développement par défaut. Il appartient à chaque utilisateur de trouver celui qui correspond à ses besoins. Heureusement, Anaconda est livré avec deux environnements de développement intégré (IDE) différents, similaires à ceux de MATLAB IDE, pour rendre votre commutateur transparent. Celles-ci s'appellent Spyder et JupyterLab. Dans les deux prochaines sections, vous verrez une introduction détaillée à Spyder et un bref aperçu de JupyterLab.

Spyder

Spyder est un IDE pour Python qui a été développé spécifiquement pour le travail scientifique sur Python. L’un des avantages de Spyder est qu’il dispose d’un mode spécialement conçu pour les personnes comme vous qui effectuent la conversion de MATLAB vers Python. Vous le verrez un peu plus tard.

Tout d’abord, vous devez ouvrir Spyder. Si vous avez suivi les instructions de la section précédente, vous pouvez ouvrir Spyder à l’aide du navigateur Anaconda. Il suffit de trouver l’icône Spyder et de cliquer sur le bouton lancement bouton. Vous pouvez également lancer Spyder à partir du menu Démarrer si vous utilisez Windows ou de Launchpad si vous utilisez macOS.

Modification de la disposition de la fenêtre par défaut dans Spyder

La fenêtre par défaut de Spyder ressemble à l'image ci-dessous. Ceci est valable pour la version 3.3.4 de Spyder sous Windows 10. Cela devrait ressembler beaucoup à Mac OS ou Linux:

Vue par défaut de l'IDE Spyder

Avant de vous familiariser avec l’interface utilisateur, vous pouvez lui donner l’apparence un peu plus semblable à MATLAB. dans le Affichage → Agencements de fenêtres menu choisir Mise en page MATLAB. Cela modifiera automatiquement la fenêtre afin qu'elle comporte les mêmes zones que celles de MATLAB, annotées sur la figure ci-dessous:

Spyder IDE comme MATLAB

En haut à gauche de la fenêtre se trouve le Explorateur de fichiers ou liste du répertoire. Dans ce volet, vous pouvez rechercher les fichiers que vous souhaitez modifier ou créer de nouveaux fichiers et dossiers à utiliser.

En haut au centre se trouve un éditeur de fichier. Dans cet éditeur, vous pouvez travailler sur les scripts Python que vous souhaitez enregistrer pour les réexécuter ultérieurement. Par défaut, l’éditeur ouvre un fichier appelé temp.py situé dans le répertoire de configuration de Spyder. Ce fichier est conçu comme un emplacement temporaire pour essayer des choses avant de les enregistrer dans un fichier ailleurs sur votre ordinateur.

En bas au centre se trouve la console. Comme dans MATLAB, la console est l'endroit où vous pouvez exécuter des commandes pour voir ce qu'elles font ou quand vous voulez déboguer du code. Les variables créées dans la console ne sont pas enregistrées si vous fermez Spyder et le rouvrez. La console exécute techniquement IPython par défaut.

Toutes les commandes que vous tapez dans la console seront consignées dans le fichier d’historique situé dans le volet inférieur droit de la fenêtre. De plus, toutes les variables que vous créez dans la console seront affichées dans l'explorateur de variables dans le volet supérieur droit.

Notez que vous pouvez ajuster la taille de n'importe quel volet en plaçant votre souris sur le séparateur entre les volets, en cliquant sur le bord et en le faisant glisser jusqu'à la taille souhaitée. Vous pouvez fermer l’un des volets en cliquant sur le bouton X en haut de la fenêtre.

Vous pouvez également supprimer n’importe quel volet de la fenêtre principale en cliquant sur le bouton qui ressemble à deux fenêtres en haut du volet, juste à côté de la fenêtre. X qui ferme le volet. Lorsqu'un volet est cassé dans la fenêtre principale, vous pouvez le faire glisser et le réorganiser comme vous le souhaitez. Si vous souhaitez remettre le volet dans la fenêtre principale, faites-le glisser avec la souris jusqu'à ce qu'un fond bleu ou gris transparent apparaisse et que les volets voisins se redimensionnent, puis relâchez-le et le volet s'emboîte.

Une fois que les panneaux sont disposés exactement comme vous le souhaitez, vous pouvez demander à Spyder de sauvegarder la mise en page. Aller au Vue menu et trouver le Dispositions de la fenêtre flyout à nouveau. Puis clique Enregistrer la mise en page actuelle et lui donner un nom. Cela vous permet de réinitialiser à tout moment votre mise en page préférée si quelque chose est modifié par accident. Vous pouvez également réinitialiser l'une des configurations par défaut à partir de ce menu.

Exécution d'instructions dans la console dans Spyder

Dans cette section, vous allez écrire quelques commandes Python simples, mais ne vous inquiétez pas si vous ne comprenez pas encore ce qu’elles signifient. Vous en apprendrez plus sur la syntaxe Python un peu plus loin dans cet article. Ce que vous voulez faire maintenant, c’est de comprendre en quoi l’interface de Spyder est similaire et différente de celle de MATLAB.

Vous allez beaucoup travailler avec la console Spyder dans cet article, vous devez donc vous renseigner sur son fonctionnement. Dans la console, vous verrez une ligne commençant par Dans [1]:, pour la ligne d’entrée 1. Spyder (en réalité, la console IPython) numérote toutes les lignes d’entrée que vous tapez. Comme il s’agit de la première entrée saisie, le numéro de ligne est 1. Dans la suite de cet article, vous verrez des références à «ligne d’entrée X», où X est le nombre entre crochets.

L’une des premières choses que j’aime faire avec les nouveaux venus dans Python est de leur montrer la Zen de python. Ce court poème vous donne une idée de ce qu'est Python et de la façon de travailler avec Python.

Voir le Zen de python, tapez importer cette sur la ligne 1, puis exécutez le code en appuyant sur Entrer. Vous verrez une sortie comme ci-dessous:

>>>

Dans [1]: importation ce
Le zen de python, de Tim Peters

Beau vaut mieux que moche.
Explicite est meilleur qu'implicite.
Simple c'est mieux que complexe.
Complexe vaut mieux que compliqué.
Flat est mieux que niché.
Clairsemé est mieux que dense.
La lisibilité compte.
Les cas spéciaux ne sont pas assez spéciaux pour enfreindre les règles.
Bien que la praticité bat la pureté.
Les erreurs ne doivent jamais passer silencieusement.
Sauf explicitement réduit au silence.
Face à l'ambiguïté, refusez la tentation de deviner.
Il devrait y avoir une - et de préférence une seule - manière évidente de le faire.
Bien que cela ne soit pas évident au premier abord, sauf si vous êtes néerlandais.
Maintenant, c'est mieux que jamais.
Bien que ne soit jamais mieux que * droit * maintenant.
Si la mise en œuvre est difficile à expliquer, c'est une mauvaise idée.
Si la mise en œuvre est facile à expliquer, cela peut être une bonne idée.
Les espaces de noms sont une idée géniale - faisons-en plus!

Ce code a importer cette sur la ligne d'entrée 1. La sortie de l'exécution importer cette est d'imprimer le Zen de python sur la console. Nous reviendrons sur plusieurs strophes de ce poème plus loin dans l’article.

Dans la plupart des blocs de code de cet article, vous verrez trois signes plus grand que (>>>) en haut à droite du bloc de code. Si vous cliquez dessus, les invites de saisie et les lignes de sortie seront supprimées, ce qui vous permettra de copier et coller le code directement dans votre console.

De nombreux pythonistes conservent un sens de l'humour sain. Ceci est affiché à de nombreux endroits dans la langue, y compris le Zen de python. Pour un autre, dans la console Spyder, tapez le code suivant, suivi de Entrer pour l'exécuter:

>>>

Dans [2]: importation anti-gravité

Cette déclaration ouvrira votre navigateur Web au Webcomic appelé XCKD, en particulier la bande dessinée n ° 353, où l'auteur a découvert que Python lui avait permis de voler!

Vous avez maintenant exécuté vos deux premières instructions Python avec succès! Félicitations

Si vous consultez l'historique, vous devriez voir les deux premières commandes que vous avez tapées dans la console (importer cette et importer l'antigravité). Définissons quelques variables et faisons maintenant quelques calculs arithmétiques de base. Dans la console, tapez les instructions suivantes en appuyant sur Entrer après chacun:

>>>

Dans [3]: var_1 = dix
Dans [4]: var_2 = 20
Dans [5]: var_3 = var_1 + var_2
Dans [6]: var_3
En dehors[6]: 30

Dans ce code, vous avez défini 3 variables: var_1, var_2, et var_3. Vous avez assigné var_1 la valeur 10, var_2 la valeur 20, et var_3 la somme de var_1 et var_2. Ensuite, vous avez montré la valeur de la var_3 variable en l’écrivant comme la seule chose sur la ligne d’entrée. La sortie de cette déclaration est montrée à la prochaine En dehors ligne et le numéro sur la En dehors ligne correspond à la associée Dans ligne.

Vous devez remarquer deux choses principales dans ces commandes:

  1. Si une déclaration n'inclut pas une cession (avec un =), il est imprimé sur un En dehors ligne. Dans MATLAB, vous auriez besoin d'inclure un point-virgule pour supprimer la sortie même des instructions d'affectation, mais cela n'est pas nécessaire en Python.

  2. Sur les lignes d’entrée 3, 4 et 5, le Explorateur de variables dans le volet en haut à droite mis à jour.

Après avoir exécuté ces trois commandes, votre Explorateur de variables devrait ressembler à l'image ci-dessous:

Spyder IDE Variable Explorer

Dans cette image, vous pouvez voir un tableau à quatre colonnes:

  1. prénom montre le nom que vous avez donné à var_1, var_2, et var_3.
  2. Type affiche le type Python de la variable, dans ce cas, tous int pour des nombres entiers.
  3. Taille affiche la taille de la variable de données stockée, ce qui est plus utile pour les listes et autres structures de données.
  4. Valeur montre la valeur actuelle de la variable.

Exécuter du code dans des fichiers dans Spyder

Le dernier arrêt de notre brève visite de l'interface de Spyder est le volet Editeur de fichier. Dans ce volet, vous pouvez créer et modifier des scripts Python et les exécuter à l'aide de la console. Par défaut, Spyder crée un fichier temporaire appelé temp.py qui vous permet de stocker temporairement des commandes pendant que vous travaillez avant de les déplacer ou de les enregistrer dans un autre fichier.

Écrivons du code dans le répertoire temp.py fichier et voir comment l'exécuter. Le fichier commence par le code suivant, que vous pouvez simplement laisser en place:

    1 # - * - codage: utf-8 - * -
    2 "" "
    3 Spyder éditeur
    4 
    5 Ceci est un fichier de script temporaire.
    6 "" "

Dans ce code, vous pouvez voir deux structures de syntaxe Python:

  • La ligne 1 a un commentaire. En Python, le caractère de commentaire est le signe dièse ou dièse (#). MATLAB utilise le symbole de pourcentage (%) en tant que caractère de commentaire. Tout ce qui suit le hachage sur la ligne est un commentaire et est généralement ignoré par l'interpréteur Python.

  • À partir de la ligne 2, une chaîne fournit un contexte pour le contenu du fichier. Ceci est souvent appelé un chaîne de documentation ou docstring pour faire court. Vous en apprendrez plus sur les docstrings dans une section ultérieure.

Vous pouvez maintenant commencer à ajouter du code à ce fichier. À partir de la ligne 8 de temp.py, entrez le code suivant, similaire à celui que vous avez déjà saisi dans la console:

    8 var_4 = dix
    9 var_5 = 20
dix var_6 = var_4 + var_5

Ensuite, il existe trois façons d’exécuter le code:

  1. Vous pouvez utiliser le F5 raccourci clavier pour exécuter le fichier comme dans MATLAB.
  2. Vous pouvez cliquer sur le triangle vert à droite dans la barre de menu juste au-dessus de la Éditeur et Explorateur de fichiers vitres.
  3. Vous pouvez utiliser le Run → Run option de menu.

La première fois que vous exécutez un fichier, Spyder ouvre une fenêtre de dialogue vous demandant de confirmer les options que vous souhaitez utiliser. Pour ce test, les options par défaut conviennent et vous pouvez cliquer sur Courir au bas de la boîte de dialogue:

Paramètres d'exécution de la Spyder IDE

Ceci exécutera automatiquement le code suivant dans la console:

>>>

Dans [7]: fichier d'exécution('C: /Users/Eleanor/.spyder-py3/temp.py',
            ...:         wdir='C: /Utilisateurs/Eleanor/.spyder-py3')

Ce code exécutera le fichier sur lequel vous travailliez. Notez que l'exécution du fichier a ajouté trois variables à l'explorateur de variables: var_4, var_5, et var_6. Ce sont les trois variables que vous avez définies dans le fichier. Vous verrez aussi runfile () ajouté au journal de l'historique.

Dans Spyder, vous pouvez également créer des cellules de code pouvant être exécutées individuellement. Pour créer une cellule de code, ajoutez une ligne commençant par # %% dans le fichier ouvert dans l'éditeur:

11 # %% Ceci est une cellule de code
12 var_7 = 42
13 var_8 = var_7 * 2
14 
15 # %% Ceci est une deuxième cellule de code
16 impression("Ce code sera exécuté dans cette cellule")

Dans ce code, vous avez créé votre première cellule de code sur la ligne 11 avec le code # %% code. Ce qui suit est un commentaire de ligne et est ignoré par Python. À la ligne 12, vous attribuez var_7 pour avoir la valeur 42, puis la ligne 13 attribue var_8 être var_7 fois deux. La ligne 15 commence une autre cellule de code qui peut être exécutée séparément de la première.

Pour exécuter les cellules de code, cliquez sur le bouton Run Current Cell ou Exécuter la cellule actuelle et passer à la suivante boutons à côté du générique Courir bouton dans la barre d'outils. Vous pouvez également utiliser les raccourcis clavier Ctrl+Entrer pour exécuter la cellule actuelle et la laisser sélectionnée, ou Décalage+Entrer pour exécuter la cellule actuelle et sélectionnez la cellule suivante.

Spyder offre également des fonctionnalités de débogage faciles à utiliser, comme dans MATLAB. Vous pouvez double-cliquer sur l’un des numéros de ligne dans la liste. Éditeur définir un point d'arrêt dans votre code. Vous pouvez exécuter le code en mode débogage à l’aide du triangle bleu orienté à droite avec deux lignes verticales dans la barre d’outils, ou Ctrl+F5 raccourci clavier. Cela suspend l'exécution à tous les points d'arrêt spécifiés et ouvre le ipdb débogueur dans la console, qui est une méthode améliorée par IPython pour exécuter le débogueur Python pdb. Vous pouvez en savoir plus dans le débogage Python avec pdb.

Résumer votre expérience dans Spyder

Vous disposez maintenant des outils de base pour utiliser Spyder en remplacement de l'environnement de développement intégré MATLAB. Vous savez comment exécuter du code dans la console ou taper du code dans un fichier et exécuter le fichier. Vous savez également où chercher pour voir vos répertoires et fichiers, les variables que vous avez définies et l'historique des commandes que vous avez saisies.

Une fois que vous êtes prêt à organiser votre code en modules et packages, vous pouvez consulter les ressources suivantes:

Spyder est un très gros logiciel, et vous ne faites qu’effleurer la surface. Vous pouvez en apprendre beaucoup plus sur Spyder en lisant la documentation officielle, le guide de dépannage et le guide de FAQ, ainsi que le wiki Spyder.

JupyterLab

JupyterLab est un IDE développé par Project Jupyter. Vous avez peut-être entendu parler de Jupyter Notebooks, en particulier si vous êtes un informaticien. JupyterLab est la prochaine itération du Jupyter Notebook. Bien que JupyterLab soit toujours en version bêta à l’heure actuelle, Project Jupyter s’attend à ce que JupyterLab remplace éventuellement l’interface actuelle du serveur Notebook. JupyterLab étant toutefois entièrement compatible avec les ordinateurs portables existants, la transition devrait donc être relativement transparente.

JupyterLab est préinstallé avec Anaconda, vous pouvez donc le lancer à partir du navigateur Anaconda. Recherchez la boîte JupyterLab et cliquez sur lancement. Cela ouvrira votre navigateur Web à l'adresse http: // localhost: 8888 / lab.

La fenêtre principale de JupyterLab est montrée dans l'image ci-dessous:

La fenêtre principale de JupyterLab

Il y a deux sections principales de l'interface:

  1. Sur la gauche est un Explorateur de fichiers qui vous permet d’ouvrir des fichiers à partir de votre ordinateur.
  2. Sur le côté droit de la fenêtre, voyez comment vous pouvez ouvrir pour créer de nouveaux fichiers Notebook, travailler dans une console IPython ou un terminal système ou créer un nouveau fichier texte.

Si vous souhaitez en savoir plus sur JupyterLab, vous pouvez en savoir plus sur la prochaine évolution du Bloc-notes dans le billet de blog annonçant la version bêta ou dans la documentation de JupyterLab. Vous pouvez également en savoir plus sur l'interface Notebook dans Jupyter Notebook: Introduction et sur le cours Utilisation de Jupyter Notebooks. Un élément intéressant du document de style Jupyter Notebook est que les cellules de code que vous avez créées dans Spyder sont très similaires aux cellules de code d'un Jupyter Notebook.

En savoir plus sur les bibliothèques mathématiques de Python

Maintenant, vous avez Python sur votre ordinateur et vous avez un IDE où vous vous sentez chez vous. Alors, comment apprendre à accomplir une tâche en Python? Avec MATLAB, vous pouvez utiliser un moteur de recherche pour trouver le sujet que vous recherchez simplement en incluant MATLAB dans votre requête. Avec Python, vous obtiendrez généralement de meilleurs résultats de recherche si vous pouvez être un peu plus spécifique dans votre requête que de simplement inclure Python.

Dans cette section, vous allez passer à l’étape suivante pour vous sentir vraiment à l’aise avec Python en apprenant comment la fonctionnalité Python est divisée en plusieurs bibliothèques. Vous apprendrez également ce que fait chaque bibliothèque afin d’obtenir des résultats de premier ordre avec vos recherches!

Python est parfois appelé un batteries incluses la langue. Cela signifie que la plupart des fonctions importantes dont vous avez besoin sont déjà incluses lors de l’installation de Python. Par exemple, Python a un math bibliothèque et un statistiques bibliothèque intégrée qui inclut les opérations de base.

Parfois, cependant, vous voulez faire quelque chose qui n’est pas inclus dans la langue. L'un des gros avantages de Python est que quelqu'un d'autre a probablement fait tout ce que vous devez faire et a publié le code pour accomplir cette tâche. Il y a plusieurs centaines de milliers packages disponibles gratuitement au public que vous pouvez facilement installer pour effectuer diverses tâches. Cela va du traitement de fichiers PDF à la création et à l'hébergement d'un site Web interactif, en passant par l'utilisation de fonctions mathématiques et scientifiques hautement optimisées.

L'utilisation de tableaux ou de matrices, l'optimisation ou le traçage nécessite l'installation de bibliothèques supplémentaires. Heureusement, si vous installez Python avec le programme d’installation Anaconda, ces bibliothèques sont préinstallées et vous n'avez pas à vous inquiéter. Même si vous n’utilisez pas Anaconda, ils sont généralement assez faciles à installer pour la plupart des systèmes d’exploitation.

L’ensemble des bibliothèques importantes que vous devrez passer de MATLAB est généralement appelé le Pile SciPy. À la base de la pile se trouvent des bibliothèques qui fournissent des opérations fondamentales sur les matrices et les matrices (NumPy), d’intégration, d’optimisation, de traitement du signal et d’algèbre linéaire (SciPy), et tracé (Matplotlib). Parmi les autres bibliothèques développant ces fonctionnalités pour offrir des fonctionnalités plus avancées, citons: Pandas, scikit-learn, SymPy, et plus.

NumPy (Python numérique)

NumPy est probablement le package le plus fondamental pour l'informatique scientifique en Python. Il fournit une interface très efficace pour créer et interagir avec des tableaux multidimensionnels. Presque tous les autres packages de la pile SciPy utilisent ou s’intègrent avec NumPy d’une manière ou d’une autre.

Les tableaux NumPy sont l'équivalent de la structure de données de tableau de base dans MATLAB. Avec les tableaux NumPy, vous pouvez effectuer des opérations telles que les produits internes et externes, la transposition et les opérations relatives aux éléments. NumPy contient également un certain nombre de méthodes utiles pour lire du texte et des fichiers de données binaires, ajuster des fonctions polynomiales, de nombreuses fonctions mathématiques (sinus, cosinus, racine carrée, etc.) et générer des nombres aléatoires.

Les parties de NumPy sensibles à la performance sont toutes écrites en langage C, elles sont donc très rapides. NumPy peut également tirer parti des bibliothèques d’algèbre linéaire optimisées telles que MKL ou OpenBLAS d’Intel pour améliorer encore les performances.

SciPy (Python Scientifique)

Le package SciPy (à la différence de la pile SciPy) est une bibliothèque qui fournit un grand nombre de fonctions utiles pour les applications scientifiques. Si vous devez effectuer un travail nécessitant une optimisation, une algèbre linéaire ou une algèbre linéaire creuse, des transformations discrètes de Fourier, un traitement du signal, des constantes physiques, un traitement de l'image ou une intégration numérique, alors SciPy est la bibliothèque qu'il vous faut! Etant donné que SciPy implémente un grand nombre de fonctionnalités différentes, il s’agit presque d’avoir accès à un ensemble de boîtes à outils MATLAB dans un seul package.

SciPy s'appuie fortement sur les baies NumPy pour faire son travail. Comme NumPy, de nombreux algorithmes de SciPy sont implémentés en C ou en Fortran, ils sont donc également très rapides. De même que NumPy, SciPy peut tirer parti des bibliothèques optimisées d’algèbre linéaire pour améliorer les performances.

Matplotlib (bibliothèque de traçage de type MATLAB)

Matplotlib est une bibliothèque permettant de produire des tracés bidimensionnels interactifs de haute qualité. Matplotlib est conçu pour fournir une interface de traçage semblable au terrain() fonctionner dans MATLAB, afin que les personnes passant de MATLAB le sachent quelque peu familier. Bien que les fonctions principales de Matplotlib concernent les tracés de données bidimensionnelles, il existe des extensions permettant de tracer en trois dimensions avec le paquet mplot3d, de tracer des données géographiques avec cartopy et bien d’autres répertoriées dans la documentation de Matplotlib.

Autres bibliothèques importantes de Python

Avec NumPy, SciPy et Matplotlib, vous pouvez basculer une grande partie de votre code MATLAB vers Python. Mais il y a quelques bibliothèques supplémentaires qu'il pourrait être utile de connaître.

  • Pandas fournit un DataFrame, un tableau avec la possibilité de nommer des lignes et des colonnes pour un accès facile.
  • SymPy fournit des mathématiques symboliques et un système de calcul formel.
  • scikit-learn fournit de nombreuses fonctions liées aux tâches d'apprentissage automatique.
  • scikit-image fournit des fonctions liées au traitement des images, compatibles avec la bibliothèque similaire de SciPy.
  • Tensorflow fournit une plate-forme commune pour de nombreuses tâches d’apprentissage automatique.
  • Keras fournit une bibliothèque pour générer des réseaux de neurones.
  • multitraitement fournit un moyen d'effectuer un parallélisme multi-processus. Il est intégré à Python.
  • Pinte fournit une bibliothèque d'unités pour effectuer une conversion automatique entre les systèmes d'unités physiques.
  • PyTables fournit un lecteur et un graveur pour les fichiers au format HDF5.
  • PyMC3 fournit des fonctionnalités de modélisation statistique bayésienne et d'apprentissage automatique probabiliste.

Différences de syntaxe entre MATLAB® et Python

Dans cette section, vous apprendrez à convertir votre code MATLAB en code Python. Vous découvrirez les principales différences de syntaxe entre MATLAB et Python, un aperçu des opérations élémentaires sur les tableaux et leur différence entre MATLAB et Python, ainsi que des méthodes permettant de tenter la conversion automatique de votre code.

La principale différence technique entre MATLAB et Python est que, dans MATLAB, tout est traité comme un tableau, alors que dans Python, tout est un objet plus général. Par exemple, dans MATLAB, les chaînes sont des tableaux de caractères ou des tableaux de chaînes, tandis qu'en Python, les chaînes ont leur propre type d'objet appelé str. Cela a des conséquences profondes sur la manière dont vous abordez le codage dans chaque langue, comme vous le verrez ci-dessous.

Avec ça, commençons! Pour vous aider, les sections ci-dessous sont organisées en groupes en fonction de la probabilité que vous rencontriez cette syntaxe.

Vous verrez probablement cette syntaxe

Les exemples de cette section représentent du code que vous êtes très susceptible de voir dans la nature. Ces exemples illustrent également certaines des fonctionnalités les plus élémentaires du langage Python. Vous devez vous assurer de bien comprendre ces exemples avant de poursuivre.

Dans MATLAB, un commentaire est tout ce qui suit un signe de pourcentage (%) sur une ligne. En Python, les commentaires sont tout ce qui suit le signe dièse ou dièse (#). Vous avez déjà vu un commentaire Python dans la section précédente sur Spyder. En général, l'interpréteur Python ignore le contenu des commentaires, tout comme l'interpréteur MATLAB, afin que vous puissiez écrire le contenu souhaité dans le commentaire. Une exception à cette règle en Python est l'exemple que vous avez vu précédemment dans la section sur Spyder:

Lorsque l'interpréteur Python lit cette ligne, il définit l'encodage qu'il utilise pour lire le reste du fichier. Ce commentaire doit apparaître dans l'une des deux premières lignes du fichier pour être valide.

Une autre différence entre MATLAB et Python réside dans la manière dont la documentation en ligne est écrite. Dans MATLAB, la documentation est écrite au début d'une fonction dans un commentaire, comme dans l'exemple de code ci-dessous:

une fonction [total] = une addition(num_1, num_2)
% ADDITION Ajoute deux nombres ensemble
% TOTAL = ADDITION (NUM_1, NUM_2) ajoute NUM_1 et NUM_2 ensemble
%
% Voir aussi SUM et PLUS

Cependant, Python n'utilise pas les commentaires de cette manière. Au lieu de cela, Python a une idée appelée chaînes de documentation ou docstrings pour faire court. En Python, vous documenteriez la fonction MATLAB ci-dessus comme suit:

def une addition(num_1, num_2):
    "" "Ajoute deux nombres ensemble.

                Exemple
                -------
                >>> total = addition (10, 20)
                >>> total
                30

                "" "

Notez dans ce code que la chaîne de documents se situe entre deux jeux de trois caractères de citation ("" "). Cela permet à la chaîne de documents de s'exécuter sur plusieurs lignes tout en préservant les espaces et les nouvelles lignes. Les caractères triples cotes sont un cas particulier de littéraux de chaîne. Ne vous inquiétez pas trop de la syntaxe de définition d’une fonction pour le moment. You’ll see more about that in a later section.

Whitespace at the Beginning of a Line Is Significant in Python

When you write code in MATLAB, blocks like si statements, pour et tandis que loops, and function definitions are finished with the fin keyword. It is generally considered a good practice in MATLAB to indent the code within the blocks so that the code is visually grouped together, but it is not syntactically necessary.

For example, the following two blocks of code are functionally equivalent in MATLAB:

    1 num = dix;
    2 
    3 si num == dix
    4 disp("num est égal à dix")
    5 autre
    6 disp("num est ne pas égal à dix")
    7 fin
    8 
    9 disp("je un m à présent à l'extérieur le si bloc")

In this code, you are first creating num to store the value 10 and then checking whether the value of num is equal to 10. If it is, you are displaying the phrase num is equal to 10 on the console from line 2. Otherwise, the autre clause will kick in and display num is not equal to 10. Of course, if you run this code, you will see the num is equal to 10 output and then I am now outside the if block.

Now you should modify your code so it looks like the sample below:

    1 num = dix;
    2 
    3 si num == dix
    4     disp("num est égal à dix")
    5 autre
    6     disp("num est ne pas égal à dix")
    7 fin
    8 
    9 disp("je un m à présent à l'extérieur le si bloc")

In this code, you have only changed lines 3 and 5 by adding some spaces or indentation in the front of the line. The code will perform identically to the previous example code, but with the indentation, it is much easier to tell what code goes in the si part of the statement and what code is in the autre part of the statement.

In Python, indentation at the start of a line is used to delimit the beginning and end of class and function definitions, si statements, and pour et tandis que loops. There is no fin keyword in Python. This means that indentation is very important in Python!

In addition, in Python the definition line of an if/else/elif statement, a pour ou tandis que loop, a function, or a class is ended by a colon. In MATLAB, the colon is not used to end the line.

Consider this code example:

    1 num = dix
    2 
    3 si num == dix:
    4     impression("num is equal to 10")
    5 autre:
    6     impression("num is not equal to 10")
    7 
    8 impression("I am now outside the if block")

On the first line, you are defining num and setting its value to 10. On line 2, writing if num == 10: tests the value of num compared to 10. Notice the colon at the end of the line.

Next, line 3 doit be indented in Python’s syntax. On that line, you are using impression() to display some output to the console, in a similar way to disp() in MATLAB. You’ll read more about impression() contre disp() in a later section.

On line 4, you are starting the autre block. Notice that the e dans le autre keyword is vertically aligned with the je dans le si keyword, and the line is ended by a colon. Because the autre is dedented relative to impression() on line 3, and because it is aligned with the si keyword, Python knows that the code within the si part of the block has finished and the autre part is starting. Line 5 is indented by one level, so it forms the block of code to be executed when the autre statement is satisfied.

Lastly, on line 6 you are printing a statement from outside the si/autre block. This statement will be printed regardless of the value of num. Notice that the p dans impression() is vertically aligned with the je dans si et le e dans autre. This is how Python knows that the code in the si/autre block has ended. If you run the code above, Python will display num is equal to 10 suivi par I am now outside the if block.

Now you should modify the code above to remove the indentation and see what happens. If you try to type the code without indentation into the Spyder/IPython console, you will get an IndentationError:

>>>

Dans [1]: num = dix
Dans [2]: si num == dix:
            ...: impression("num is equal to 10")
        Fichier    "", line 2
    impression("num is equal to 10")
        ^
IndentationError: expected an indented block

In this code, you first set the value of num to 10 and then tried to write the si statement without indentation. In fact, the IPython console is smart and automatically indents the line after the si statement for you, so you’ll have to delete the indentation to produce this error.

When you’re indenting your code, the official Python style guide called PEP 8 recommends using 4 space characters to represent one indentation level. Most text editors that are set up to work with Python files will automatically insert 4 spaces if you press the Tab key on your keyboard. You can choose to use the tab character for your code if you want, but you shouldn’t mix tabs and spaces or you’ll probably end up with a TabError if the indentation becomes mismatched.

Conditional Statements Use elif in Python

In MATLAB, you can construct conditional statements with si, elseif, et autre. These kinds of statements allow you to control the flow of your program in response to different conditions.

You should try this idea out with the code below, and then compare the example of MATLAB vs Python for conditional statements:

    1 num = dix;
    2 si num == dix
    3     disp("num est égal à dix")
    4 elseif num == 20
    5     disp("num est égal à 20")
    6 autre
    7     disp("num est ni dix ni 20")
    8 fin

In this code block, you are defining num to be equal to 10. Then you are checking if the value of num is 10, and if it is, using disp() to print output to the console. Si num is 20, you are printing a different statement, and if num is neither 10 nor 20, you are printing the third statement.

In Python, the elseif keyword is replaced with elif:

    1 num = dix
    2 si num == dix:
    3     impression("num is equal to 10")
    4 elif num == 20:
    5     impression("num is equal to 20")
    6 autre:
    7     impression("num is neither 10 nor 20")

This code block is functionally equivalent to the previous MATLAB code block. There are 2 main differences. On line 4, elseif is replaced with elif, and there is no fin statement to end the block. Au lieu de cela, le si block ends when the next dedented line of code is found after the autre. You can read more in the Python documentation for si statements.

Calling Functions and Indexing Sequences Use Different Brackets in Python

In MATLAB, when you want to call a function or when you want to index an array, you use round brackets (()), sometimes also called parentheses. Square brackets ([]) are used to create arrays.

You can test out the differences in MATLAB vs Python with the example code below:

>>>

>> arr = [[[[dix, 20, 30];
>> arr(1)

ans =

                dix

>> somme(arr)

ans =

                60

In this code, you first create an array using the square brackets on the right side of the equal sign. Then, you retrieve the value of the first element by arr(1), using the round brackets as the indexing operator. On the third input line, you are calling sum() and using the round brackets to indicate the parameters that should be passed into sum(), in this case just arr. MATLAB computes the sum of the elements in arr and returns that result.

Python uses separate syntax for calling functions and indexing sequences. In Python, using round brackets means that a function should be executed and using square brackets will index a sequence:

>>>

Dans [1]: arr = [[[[dix, 20, 30]
Dans [2]: arr[[[[0]
Out[2]: dix

Dans [3]: somme(arr)
Out[3]: 60

In this code, you are defining a Python list on input line 1. Python lists have some important distinctions from arrays in MATLAB and arrays from the NumPy package. You can read more about Python lists in Lists and Tuples in Python, and you’ll learn more about NumPy arrays in a later section.

On the input line 2, you are displaying the value of the first element of the list with the indexing operation using square brackets. On input line 3, you are calling sum() using round brackets and passing in the list stored in arr. This results in the sum of the list elements being displayed on the last line. Notice that Python uses square brackets for indexing the list and round brackets for calling functions.

The First Index in a Sequence Is 0 in Python

In MATLAB, you can get the first value from an array by using 1 as the index. This style follows the natural numbering convention and starts how you would count the number of items in the sequence. You can try out the differences of MATLAB vs Python with this example:

>>>

>> arr = [[[[dix, 20, 30];
>> arr(1)

ans =

                dix

>> arr(0)
Array indices must be positive integers or logical values.

In this code, you are creating an array with three numbers: dix, 20, et 30. Then you are displaying the value of the first element with the index 1, which is dix. Trying to access the zeroth element results in an error in MATLAB, as shown on the last two lines.

In Python, the index of the first element in a sequence is 0, not 1:

>>>

Dans [1]: arr = [[[[dix, 20, 30]
Dans [2]: arr[[[[0]
Out[2]: dix

Dans [3]: arr[[[[1]
Out[3]: 20

Dans [4]: a_string = "a string"
Dans [5]: a_string[[[[0]
Out[5]: 'a'

Dans [6]: a_string[[[[1]
Out[6]: ' '

In this code, you are defining arr as a Python list with three elements on input line 1. On input line 2, you are displaying the value of the first element of the list, which has the index 0. Then you are displaying the second element of the list, which has the index 1.

On input lines 4, 5, and 6, you are defining a_string with the contents "a string" and then getting the first and second elements of the string. Notice that the second element (character) of the string is a space. This demonstrates a general Python feature, that many variable types operate as sequences and can be indexed, including lists, tuples, strings, and arrays.

The Last Element of a Sequence Has Index -1 in Python

In MATLAB, you can get the last value from an array by using fin as the index. This is really useful when you don’t know how long an array is, so you don’t know what number to access the last value.

Try out the differences in MATLAB vs Python with this example:

>>>

>> arr = [[[[dix, 20, 30];
>> arr(fin)

ans =

                30

In this code, you are creating an array with three numbers, dix, 20, et 30. Then you are displaying the value of the last element with the index fin, which is 30.

In Python, the last value in a sequence can be retrieved by using the index -1:

>>>

Dans [1]: arr = [[[[dix, 20, 30]
Dans [2]: arr[[[[-1]
Out[2]: 30

In this code, you are defining a Python list with three elements on input line 1. On input line 2, you are displaying the value of the last element of the list, which has the index -1 and the value 30.

In fact, by using negative numbers as the index values you can work your way backwards through the sequence:

>>>

Dans [3]: arr[[[[-2]
Out[3]: 20

Dans [4]: arr[[[[-3]
Out[4]: dix

In this code, you are retrieving the second-to-last and third-to-last elements from the list, which have values of 20 et dix, respectively.

Exponentiation Is Done With ** in Python

In MATLAB, when you want to raise a number to a power you use the caret operator (^). The caret operator is a binary operator that takes two numbers. Other binary operators include addition (+), subtraction (-), multiplication (*), and division (/), among others. The number on the left of the caret is the base and the number on the right is the exponent.

Try out the differences of MATLAB vs Python with this example:

In this code, you are raising 10 to the power of 2 using the caret resulting an answer of 100.

In Python, you use two asterisks (**) when you want to raise a number to a power:

>>>

Dans [1]: dix ** 2
Out[1]: 100

In this code, you are raising 10 to the power of 2 using two asterisks resulting an answer of 100. Notice that there is no effect of including spaces on either side of the asterisks. In Python, the typical style is to have spaces on both sides of a binary operator.

The Length of a Sequence Is Found With len() in Python

In MATLAB, you can get the length of an array with length(). This function takes an array as the argument and returns back the size of the largest dimension in the array. You can see the basics of this function with this example:

>>>

>> longueur([[[[dix, 20, 30])

ans =

                3

>> longueur("une chaîne")

ans =

                1

In this code, on the first input line you are finding the length of an array with 3 elements. As expected, length() returns an answer of 3. On the second input line, you are finding the length of the tableau de chaînes that contains one element. Notice that MATLAB implicitly creates a string array, even though you did not use the square brackets to indicate it is an array.

In Python, you can get the length of a sequence with len():

>>>

Dans [1]: len([[[[dix, 20, 30])
Out[1]: 3

Dans [2]: len("a string")
Out[2]: 8

In this code, on the input line 1 you are finding the length of a list with 3 elements. As expected, len() returns a length of 3. On input line 2, you are finding the length of a string as the input. In Python, strings are sequences and len() counts the number of characters in the string. In this case, un string has 8 characters.

Console Output Is Shown With impression() in Python

In MATLAB, you can use disp(), fprintf(), et sprintf() to print the value of variables and other output to the console. disp() is the simplest of these commands but does not give you any control over the format of the output. fprintf() et sprintf() give you total control over the output format, but the format specification is a little bit complicated.

In Python, impression() serves the same function as disp(). Unlike disp(), impression() can send its output to a file similar to fprintf().

Python’s impression() will display any number of arguments passed to it, separating them by a space in the output. This is different from disp() in MATLAB, which only takes one argument. The following example shows how Python’s impression() can take any number of arguments, and the each argument is separated by a space in the output:

>>>

Dans [1]: val_1 = dix
Dans [2]: val_2 = 20
Dans [3]: str_1 = "any number of arguments"
Dans [4]: impression(val_1, val_2, str_1)
10 20 any number of arguments

In this code, the input lines 1, 2, and 3 define val_1, val_2, et str_1, où val_1 et val_1 are integers, and str_1 is a string of text. On input line 4, you are printing the three variables using impression(). The output below this line the value of the three variables are shown in the console output, separated by spaces.

You can control the separator used in the output between arguments to impression() en utilisant le sep keyword argument:

>>>

Dans [5]: impression(val_1, val_2, str_1, sep="; ")
10; 20; any number of arguments

In this code, you are printing the same three variables but setting the separator to be a semicolon followed by a space. This separator is printed between the first and second and the second and third arguments, but not after the third argument. To control the character printed after the last value, you can use the fin keyword argument to impression():

>>>

Dans [6]: impression(val_1, val_2, str_1, sep="; ", fin=";")
10; 20; any number of arguments;

In this code, you have added the fin keyword argument to impression(), setting it to print a semicolon after the last value. This is shown in the output on line below the input.

Comme disp() from MATLAB, impression() cannot directly control the output format of variables. If you want more control over the format of the output, you should use f-strings ou format(). In these strings, you can use very similar formatting style codes as fprintf() in MATLAB to format numbers. You can read a lot more about f-strings and other string formatting in Python 3’s f-Strings or the official documentation:

>>>

Dans [7]: impression(F"Python's print() can handle str_1")
Python's print() can handle any number of arguments

Dans [8]: impression(F"The value of val_1 = val_1:8.3f")
The value of val_1 =   10.000

Dans [9]: # The following line will only work in Python 3.8

Dans [10]: impression(F"The value of val_1= and val_2=")
The value of val_1 = 10, and val_2 = 20

In this code, input line 7 includes an f-string, indicated by the F to start the string. This means that Python will substitute the value of any variables it encounters between , or curly braces, within the string. You can see that in the output, Python has replaced str_1 avec any number of arguments, the value of str_1. On input line 8, you are using some of the formatting syntax to print the value of val_1 as a floating point number with 8 columns in the output and 3 digits of precision.

On input line 10, a new feature that is coming in Python 3.8 (due out in late 2019) is demonstrated. If a variable name is immediately followed by an equals sign inside curly braces, the name of the variable and the value will be printed automatically.

You can take a deep dive into Python’s impression() by checking out The Ultimate Guide to Python Print.

You Will Probably See These, but You Can Learn Them When You Need To

In this section, you’ll find examples of code that you’ll probably see in the wild, but you can wait a little while to understand them if you want. These examples use some intermediate features in Python but are still in the core of how Python works. Just like in the last section, you’ll see comparisons of the MATLAB vs Python syntax differences.

Function Definitions Start With def et revenir Values in Python

In MATLAB, you can define a function by placing the une fonction keyword at the start of a line. This is followed by the name of any output variables, an equals (=) sign, then the name of the function and any input arguments in parentheses. Within the the function you have to assign to any variables you specified in the definition line as outputs. A simple example MATLAB function is shown below:

    1 une fonction [total] = une addition(num_1,num_2)
    2 total = num_1 + num_2;
    3 fin

In this code, you see the une fonction definition on line 1. There is only one output variable, called total, for this function. The name of the function is une addition and it takes two arguments, which will be assigned the names num_1 et num_2 in the function body. Line 2 is the implementation of the function. The value of total is set equal to the sum of num_1 et num_2. The last line of the function is the fin keyword that tells the MATLAB interpreter the definition of the function has finished.

To use this function in MATLAB, you should save it in a file called addition.m, matching the name of the function. Alternatively, it can be placed in file with other commands provided that the function definition is the last thing in the file and the file is ne pas nommé addition.m. Then, you can run the function by typing the following code in the MATLAB console:

>>>

>> var_1 = 20;
>> var_2 = dix;
>> sum_of_vars = une addition(var_1,var_2)

sum_of_vars =

                30

In this code, you have defined two variables called var_1 et var_2 that hold the values 20 and 10, respectively. Then you created a third variable called sum_of_vars that stores the output from addition(). Vérifiez Variable explorer, and you’ll see that sum_of_vars has the value 30, as expected. Notice that the name sum_of_vars did not have to be the same name as the output variable used in the function definition, which was total.

MATLAB does not require a function to provide an output value. In this case, you would remove the output variable and the equals sign from the function definition. Modify your addition.m file so that the code looks like this:

    1 une fonction une addition(num_1,num_2)
    2 total = num_1 + num_2;
    3 fin

The only change in this code from the earlier code is that you deleted the [total] = from line 1, the other lines are exactly the same. Now if you try to assign the result of calling this function to a variable, MATLAB will generate an error in the console:

>>>

>> var_1 = 20;
>> var_2 = dix;
>> sum_of_vars = une addition(var_1,var_2)
Error using addition
Too many output arguments.

In this code, you defined the same two variables var_1 et var_2 as before and called addition() in the same way as before. However, since addition() no longer specifies an output variable, MATLAB generates an error message that there are too many output arguments. Clicking on the word une addition will open the definition of the function for you to edit or view the source code to fix the problem.

In Python, the def keyword starts a function definition. le def keyword must be followed by the name of the function and any arguments to the function inside parentheses, similar to MATLAB. The line with def must be ended with a colon (:).

Starting on the next line, the code that should be executed as part of the function must be indented one level. In Python, the function definition ends when a line of code starts at the same indentation level as the def keyword on the first line.

If your function returns some output back to the caller, Python does not require that you specify a name for an output variable. Instead, you use the revenir statement to send an output value from the function.

An equivalent function in Python to your first addition() example with an output variable is shown below:

    1 def une addition(num_1, num_2):
    2     total = num_1 + num_2
    3     revenir total

In this code, you see the def keyword followed by the function name and the two arguments num_1 et num_2 on line 1. On line 2 you can see the creation of a new variable total to store the sum of num_1 et num_2, and on line 3 the value of total is returned to the point where this function was called. Notice that lines 2 and 3 are indented by 4 spaces because they make up the body of the function.

The variable that stores the sum of num_1 et num_2 can have any name, it doesn’t have to be called total. In fact, you don’t need to create a variable there at all. You can simplify your previous function definition by eliminating total and simply returning the value of num_1 + num_2:

    1 def une addition(num_1, num_2):
    2     revenir num_1 + num_1

Line 1 in this code is the same as it was before, you have only changed line 2 and deleted line 3. Line 2 now computes the value of num_1 + num_2 and returns that value back to the caller of the function. Line 2 is indented by 4 spaces because it makes up the body of the function.

To use this function in Python, you do not need to save it in a file with a special name. You can place the function definition in any Python file, at any point in the file. There is no restriction that the function definition has to be last. In fact, you can even define functions right from the console, which is not possible in MATLAB.

Open Spyder and in the Console pane type:

>>>

Dans [1]: def une addition(num_1, num_2):

On this line of code you are creating the function definition. In the Spyder/IPython console, once you start a function definition and press Enter, the start of the line becomes three dots and the cursor is automatically indented. Now you can type the remainder of the function definition. You’ll have to press Enter twice to complete the definition:

>>>

Dans [1]: def une addition(num_1, num_2):
            ...:     revenir num_1 + num_2
            ...:

In this code, you have the definition of the function on the first line and the body of the function on the second line. The console automatically adds the ...: at the start of the lines to indicate these are continuation lines that apply to the function definition.

Once you’ve completed the definition, you can execute the function from the console as well. You should type this code:

>>>

Dans [2]: var_1 = 20
Dans [3]: var_2 = dix
Dans [4]: sum_of_vars = une addition(var_1, var_2)
Dans [5]: sum_of_vars
Out[5]: 30

In this code, you first create two variables var_1 et var_2 that store the values you want to add together. Then, on input line 4, you assign sum_of_vars to the result that is returned from addition(). On input line 5, you are outputting the value of sum_of_vars to the console screen. This displays 30, the sum of 10 and 20.

In Python, if you do not explicitly put a revenir statement, your function will implicitly return the special value Aucun. You should change your Python definition of addition() to see how this works. In the Spyder/IPython console, type the following:

>>>

Dans [6]: def une addition(num_1, num_2):
            ...:     total = num_1 + num_2
            ...:

In this code, you have the same def line on input line 6. You have changed the first continuation line to assign the result of the addition to total instead of returning. Now you should see what happens when we execute this modified function:

>>>

Dans [7]: sum_of_vars = une addition(var_1, var_2)
Dans [8]: sum_of_vars
Dans [9]:

In this code, on input line 7 you are assigning sum_of_vars to be the returned value from addition(). Then, on input line 8, you are showing the value of sum_of_vars on the console screen, just like before. This time though, there is no output! By default, Python prints nothing when it outputs a variable whose value is Aucun. You can double check the value of the sum_of_vars variable by looking at the Variable explorer. dans le Type column, it should list NoneType, telling you that sum_of_vars is the special Aucun value.

Functions Accept Positional and Keyword Arguments in Python

In MATLAB, functions have input arguments specified on the first line, in the une fonction définition. When you call a function in MATLAB, you can pass from zero up to the number of arguments that are specified. In the body of the function, you can check the number of input arguments the caller actually passed to execute different code. This is useful when you want different arguments to have different meaning, like in the example below:

    1 une fonction [result] = addOrSubtract(num_1,num_2,subtract)
    2 % ADDORSUBTRACT  Add or subtract two value
    3 %   RESULT = addOrSubtract(NUM_1,NUM_2) adds NUM_1 and NUM_2 together
    4 %
    5 %   RESULT = addOrSubtract(NUM_1,NUM_2,true) subtracts NUM_2 from NUM_1
    6 
    7     commutateur nargin
    8         Cas 2
    9             résultat = num_1 + num_2;
dix         Cas 3
11             résultat = num_1 - num_2;
12         autrement
13             résultat = 0;
14     fin
15 fin

In this code, you are defining a function with three possible input arguments. On line 7, you are starting a commutateur/Cas block that determines how many input arguments were passed to the function by using the special variable nargin. This variable stores the actual number of arguments the caller passed into the function.

In your code above, you are defining three cases:

  1. If the number of input arguments is 2, you are adding num_1 et num_2 together.
  2. If the number of input arguments is 3, you are subtracting num_2 de num_1.
  3. If fewer than 2 arguments are passed, the output will be 0.

If more than 3 arguments are passed, MATLAB will raise an error.

Now you should experiment with this function. Save the code above into a file called addOrSubtract.m and then on the MATLAB console, try the version with two input arguments:

>>>

>> addOrSubtract(dix,20)

ans =
                30

In this code, you are calling addOrSubtract() with two arguments, so the arguments are added together, resulting in an answer of 30. Next, try calling addOrSubtract() with three arguments:

>>>

>> addOrSubtract(dix,20,vrai)

ans =
            -10

In this code, you used three input arguments, and found that the second argument was subtracted from the first, resulting in an answer of -10. Third, try calling addOrSubtract() with one argument:

>>>

>> addOrSubtract(dix)

ans =
                    0

In this code, you used one input argument and found the answer was 0, because MATLAB only found one argument to the function and used the autrement case. Finally, try calling addOrSubtract() with four arguments:

>>>

>> addOrSubtract(dix,20,vrai,30)
Error using addOrSubtract
Too many input arguments.

In this code, you find that MATLAB raises an error because there were more input arguments passed than were defined in the une fonction line.

There are four key takeaways from this example with MATLAB:

  1. There is only one kind of argument in a function definition.
  2. The meaning of an argument in the code is determined by its position in the function definition.
  3. The maximum number of arguments that can be passed to a function is determined by the number of arguments specified in the function definition.
  4. Any number of arguments up to the maximum can be passed by the caller.

In Python, there are two kinds of arguments you can specify when defining a function. Ceux-ci sont Champs obligatoires et optionnel arguments. The key difference between these is that required arguments must be passed when a function is called, while optional are given a default value in the function definition.

You can see the differences between these two styles in the next example:

    1 def add_or_subtract(num_1, num_2, soustraire=Faux):
    2     """Add or subtract two numbers, depending on the value of subtract."""
    3     si soustraire:
    4         revenir num_1 - num_2
    5     autre:
    6         revenir num_1 + num_2

In this code, you are defining a function called add_or_subtract() that has three arguments: num_1, num_2, et soustraire. In the function definition, you can see the two types of arguments. The first two arguments, num_1 et num_2, are required arguments.

The third argument, soustraire, has a default value assigned to it by specifying a value after an equals sign in the function definition. This means that when the function is called, passing a value for soustraire is optional. If no value is passed, the default as defined in the function definition line will be used. In this case, the default value is Faux.

In the body of the function, you are testing the value of soustraire avec le si statement to determine whether addition or subtraction should be performed. Si soustraire est Vrai, num_2 will be subtracted from num_1. Otherwise, if soustraire est Faux, then num_1 will be added to num_2. In either case, the result of the arithmetic operation will be returned to the caller.

In addition to the two types of arguments you can use when définissant a function, there are two kinds of arguments you can specify when appel a function. These are called positionnel et mot-clé arguments. You can see the difference between these in the following example. First, try passing only two arguments to the function:

>>>

Dans [1]: add_or_subtract(dix, 20)
Out[1]: 30

In this code, you passed only two arguments to add_or_subtract(), dix et 20. In this case, you passed these values as positional arguments, and the meaning of the arguments is defined by their position in the function call.

Since only the two required arguments were passed, soustraire will take on the default value, which is Faux. Therefore, 10 and 20 will be added together, which you can see on the output line. Next, try passing a value for soustraire:

>>>

Dans [2]: add_or_subtract(dix, 20, Faux)
Out[2]: 30
Dans [3]: add_or_subtract(dix, 20, Vrai)
Out[3]: -10

In this code, you passed three arguments to add_or_subtract(), with two different values for the soustraire argument. First, you passed Faux on input line 2. The result was the addition of 10 and 20. Then, you passed Vrai on input line 3, resulting in the difference between 10 and 20, or -10.

In these examples, you saw that it is possible in Python to define default values for arguments to a function. This means when you call the function, any arguments with default values are optional and do not have to be passed. If no value is passed for any default arguments, the default value will be used. However, you doit pass a value for every argument without a default value. Otherwise, Python will raise an error:

>>>

Dans [4]: add_or_subtract(dix)
Traceback (most recent call last):

        File "", line 1, in 
                add_or_subtract(10)

TypeError: add_or_subtract() missing 1 required positional argument: 'num_2'

In this code, you have only passed one of the two required arguments to add_or_subtract(), so Python raises a TypeError. The error message tells you that you did not pass a value for num_2, because it does not have a default value.

In these last three example, you have used positionnel arguments, so which parameter is assigned to the variables in the function depends on the order they are passed. There is another method to pass arguments to functions in Python, called mot-clé arguments. To use keyword arguments, you specify the name of the argument in the function call:

>>>

Dans [5]: add_or_subtract(num_1=dix, num_2=20, soustraire=Vrai)
Out[5]: -10

In this code, you have used keyword arguments for all three arguments to add_or_subtract(). Keyword arguments are specified by stating the argument name, then an equals sign, then the value that argument should have. One of the big advantages of keyword arguments is that they make your code more explicit. (As the Zen of Python says, explicit is better than implicit.) However, they make the code somewhat longer, so it’s up to your judgement when to use keyword arguments or not.

Another benefit of keyword arguments is that they can be specified in any order:

>>>

Dans [6]: add_or_subtract(soustraire=Vrai, num_2=20, num_1=dix)
Out[6]: -10

In this code, you have specified the three arguments for add_or_subtract() as keyword arguments, but the order is different from in the function definition. Nonetheless, Python connects the right variables together because they are specified as keywords instead of positional arguments.

You can also mix positional and keyword arguments together in the same function call. If positional and keyword arguments are mixed together, the positional arguments doit be specified first, before any keyword arguments:

>>>

Dans [7]: add_or_subtract(dix, 20, soustraire=Vrai)
Out[7]: -10

In this code, you have specified the values for num_1 et num_2 using positional arguments, and the value for soustraire using a keyword argument. This is probably the most common case of using keyword arguments, because it provides a good balance between being explicit and being concise.

Finally, there is one last benefit of using keyword arguments and default values. Spyder, and other IDEs, provide introspection of function definitions. This will tell you the names of all of the defined function arguments, which ones have default arguments, and the value of the default arguments. This can save you time and make your code easier and faster to read.

There Are No commutateur/Cas Blocks in Python

In MATLAB, you can use commutateur/Cas blocks to execute code by checking the value of a variable for equality with some constants. This type of syntax is quite useful when you know you want to handle a few discrete cases. Try out a commutateur/Cas block with this example:

num = dix;
commutateur num
    Cas dix
        disp("num est dix")
    Cas 20
        disp("num est 20")
    autrement
        disp("num est ni dix ni 20")
fin

In this code, you start by defining num and setting it equal to 10 and on the following lines you test the value of num. This code will result in the output num is 10 being displayed on the console, since num is equal to 10.

This syntax is an interesting comparison of MATLAB vs Python because Python does not have a similar syntax. Instead, you should use an si/elif/autre block:

num = dix
si num == dix:
    impression("num is 10")
elif num == 20:
    impression("num is 20")
autre:
    impression("num is neither 10 nor 20")

In this code, you start by defining num and setting it equal to dix. On the next several lines you are writing an si/elif/autre block to check the different values that you are interested in.

Namespaces Are One Honking Great Idea in Python

In MATLAB, all functions are found in a single scope. MATLAB has a defined search order for finding functions within the current scope. If you define your own function for something that MATLAB already includes, you may get unexpected behavior.

As you saw in the Zen of Python, namespaces are one honking great idea. Namespaces are a way to provide different scopes for names of functions, classes, and variables. This means you have to tell Python which library has the function you want to use. This is a good thing, especially in cases where multiple libraries provide the same function.

For instance, the built-in math library provides a square root function, as does the more advanced NumPy library. Without namespaces, it would be more difficult to tell Python which square root function you wanted to use.

To tell Python where a function is located, you first have to importation the library, which creates the namespace for that library’s code. Then, when you want to use a function from the library, you tell Python which namespace to look in:

>>>

Dans [1]: importation math
Dans [2]: math.sqrt(4)
Out[2]: 2.0

In this code, on input line 1 you imported the math library that is built-in to Python. Then, input line 2 computes the square root of 4 using the square root function from within the math library. le math.sqrt() line should be read as “from within math, find sqrt(). "

le importation keyword searches for the named library and binds the namespace to the same name as the library by default. You can read more about how Python searches for libraries in Python Modules and Packages – An Introduction.

You can also tell Python what name it should use for a library. For instance, it is very common to see numpy raccourci à np with the following code:

>>>

Dans [3]: importation numpy comme np
Dans [4]: np.sqrt(4)
Out[4]: 2.0

In this code, input line 3 imports NumPy and tells Python to put the library into the np namespace. Then, whenever you want to use a function from NumPy, you use the np abbreviation to find that function. On input line 4, you are computing the square root of 4 again, but this time, using np.sqrt(). np.sqrt() should be read as “from within NumPy, find sqrt(). "

There are two main caveats to using namespaces where you should be careful:

  1. You should not name a variable with the same name as one of the functions built into Python. You can find a complete list of these functions in the Python documentation. The most common variable names that are also built-in functions and should not be used are dir, identifiant, contribution, liste, max, min, somme, str, type, et vars.

  2. You should not name a Python file (one with the extension .py) with the same name as a library that you have installed. In other words, you should not create a Python file called math.py. This is because Python searches the current working directory first when it tries to import a library. If you have a file called math.py, that file will be found before the built-in math library and you will probably see an AttributeError.

The Most Recent Unassigned Result Is Available as _ in Python

The MATLAB console uses ans to store the result of the most recent calculation if that result was not assigned to a variable. This is really useful when you forgot to assign the result of a calculation to a variable or when you just want to chain a few simple calculations together. To see the differences between MATLAB vs Python, try out this example:

>>>

>> somme([[[[dix, 20, 30])

ans =

                60

>> ans + dix

ans =

                70

In this code, you use sum() to calculate the sum of the array. Since there is no equal sign with a variable name on the left, MATLAB assigns the output from sum() à ans. You can then use that variable in further calculations, as you do here by adding 10 to the last result. Note that this will only work in the MATLAB console, not in a script file.

In the Python console (including the IPython/Spyder console), the output from the most recent calculation is stored in _ (the underscore character). Try the following code:

>>>

Dans [1]: somme([[[[dix, 20, 30])
Out[1]: 60

Dans [2]: _ + dix
Out[2]: 70

In this code, you use sum() to calculate the sum of the list. Since there is no equal sign with a variable name on the left, Python assigns the output from sum() to the underscore (_), in addition to printing it on the output line. You can then use that variable in further calculations, as you do here by adding 10 to the last result. Note that this will only work in the Python console, not in a script file.

In the IPython console, there is one additional feature enabled. You can append a number after the underscore to retrieve the result of any previous line. Try the following code:

>>>

Dans [3]: _1 + 20
Out[3]: 80

Dans [4]: _2 + 20
Out[4]: 90

In this code on input line 3 you are using _1 to mean the value of output line 1, the sum() line. To that result (60) you are adding 20, producing a result of 80. On input line 4, you are adding 20 to the value of output line 2, accessed with _2, so the result is 90.

Notice that the Spyder Variable explorer does not show this variable by default, whereas ans is shown in the MATLAB Variable explorer. In a few sections, you’ll see why the underscore isn’t shown by default and how you can see it.

Anonymous Functions Are Created With the lambda Keyword in Python

MATLAB uses the the at-symbol (@) to indicate that what follows is the definition of an anonymous function. Anonymous functions are functions that are not defined in a program file and do not use the une fonction keyword. A program file is a MATLAB file with a filename ending in .m. Anonymous functions are limited to a single statement so they are intended for simple computations.

You can try out the differences of anonymous functions in MATLAB vs Python with this example:

>>>

>> sayHello = @(X) fprintf("Bonjour, %sn",x);
>> sayHello("Eleanor")
Hello, Eleanor

In this code, the first input line defines the anonymous function with one input parameter, X. The body of the function follows, which uses fprintf() to format the input into a string. This function is assigned to sayHello. On the second input line, sayHello() is executed and passed "Eleanor" as the value. The result the string Hello, Eleanor printed on the console.

Anonymous functions are most often used when you need to pass one function into another function. In these cases, it is often not necessary to assign the function definition to a variable:

>>>

>> intégral(@(X) X.^2,0,9)

ans =

                243

In this code, the first input line executes integral(), a function that computes the definite integral of a given function. The first argument to integral() must be a function, so this is a perfect place to use an anonymous function. Here, your anonymous function squares whatever the input value is. The other two arguments to integral() are the limits of the integration, such that the result of integrating x.^2 from 0 to 9 is 243.

Python uses the lambda keyword to define anonymous functions. Other than this syntax difference, anonymous functions work the same way in Python as in MATLAB:

>>>

Dans [1]: say_hello = lambda X: impression(F"Bonjour, x:s")
Dans [2]: say_hello("Eleanor")
Hello, Eleanor

In this code, input line 1 defines the lambda function with one parameter, X. You use impression() within the function definition to show an f-string with the value of the input parameter. The function is then stored in say_hello(). Input line 2 evaluates say_hello() with the input string "Eleanor" and produces the Hello, Eleanor output.

In Python, the official style guide called PEP 8 specifically disrecommends assigning lambda expressions to variable names, as you saw in the last example. If you want to give a function a name to refer to it several times, the preference is to use the def syntax and define a full function, even for one-line functions.

cependant, lambda functions are still useful when they are passed as arguments into another function:

>>>

Dans [3]: de scipy importation intégrer
Dans [4]: intégrer.quad(lambda X: X ** 2, 0, 9)
Out[4]: (243.0, 2.6978419498391304e-12)

In this code, input line 3 imports the scipy.integrate library and stores it in the intégrer namespace. On input line 4, you are using quad() de scipy.integrate to compute the integral using quadrature, very similar to integral() in MATLAB. The first argument to quad() is the function to be integrated, and you use a lambda function to specify that x ** 2 should be integrated. The second and third arguments to quad() specify that the integral should be conducted from 0 to 9.

You can see that the result on output line 4 has two values, 243.0 et 2.6978419498391304e-12. The first value is the result of the integration, and is equal to the result from MATLAB. The second value is an estimate of the absolute error in the result. An error this small is approximately the precision of the numbers used to store the result, so the answer is about as accurate as it can be.

You can read more about lambda in How to Use Python lambda Functions or watch the videos in the How to Use Python Lambda Functions course.

You Will Only Need These in Specialized Situations

In this section, the examples are more advanced concepts that you will need as you become more advanced in Python development. Some of the examples here deal with developing applications or higher-level code than the other sections. When you see these concepts in other code, you can dig in to them when you feel comfortable.

Class Definitions Start With classe in Python

MATLAB has two ways to define a class. With the first way, you can put all of the class definition in a single file with the name of the class as the filename. Then within the file, you can use the classdef keyword to define the properties and methods that belong to the class.

With the second way, you can create a folder that starts with @ and has the same name as the class. In that folder, you can create a single file that has the same name as the class. The function definition in that file will be used as the class initializer, and it should call class() to instantiate the class. Methods of the class can be defined in other files in the same folder, where the name of each file must be the same as the name of the method.

Python only has one way to define a class, using the classe keyword. Since Python uses indentation to find the end of the class definition, the entire definition must be contained in a single file:

classe MyClass:
    # The rest of the class definition goes here

In this code, the first line defines the name of the class. It starts with the classe keyword, followed by the name of the class and a colon. Underneath this line, all of the code that is part of the class definition (methods and attributes) must be indented. Once a line of code starts in the same column as the c dans classe, the class definition will be ended.

The second line in this code is a comment to note that the rest of the class definition would follow the classe line.

As in all object-oriented code, Python classes can inherit from superclasses. The superclass of a given class can be given as a parameter in the class definition, as shown below:

classe MyClass(MySuperClass):
    # The rest of the class definition goes here

In this code, the only change is that the name of the superclass is listed inside round brackets before the colon.

There Are No Private Properties or Methods in Python

MATLAB allows class properties and method to be set as one of four Access options:

  • Publique: Access to the property or method is unrestricted.
  • protégé: Access to the property or method is only allowed in this class or subclasses.
  • privé: Access to the property or method is only allowed in this class.
  • meta.class ou meta.class: Access to the property or method is only allowed in the listed class or classes.

This allows you to specifically control the ways that a property or class method can be accessed.

In Python, there is no way to set a class or instance attribute or method as protected or private. All classes and class instances can have their attributes and methods changed at runtime. Python’s convention is that attributes and methods that start with an underscore (_) are intended to be private, or at least non-public. However, this convention is not enforced by any checks in the language and all attributes and methods can be modified by the user at runtime.

As you saw in the section about using the underscore to retrieve values in the console, the underscore is not visible by default in the Spyder Variable explorer. This is because Spyder and other tools respect the convention that underscore indicates something should be non-public. However, underscores can be shown in the Spyder Variable explorer if you click the gear icon in the top right of that pane and uncheck the Exclude private variables item. This will also show other non-public variables as well.

Python uses several special methods that start with a double-underscore (__), called dunder methods, to implement specific behavior for classes. The most commonly used dunder method is __init__(), which is the class initializer or constructor. You can read a lot more about dunder methods in Enriching Your Python Classes With Dunder (Magic, Special) Methods.

If you want more information about Python’s classes, you can read Object-Oriented Programming in Python vs Java. Even though that article is about Java, Java is similar to the MATLAB OOP paradigm in terms of the nature of attributes and methods.

A Class Refers to Itself as soi in Python

MATLAB uses the name obj when a class wants to refer to the current instance of itself. le obj should be the first argument passed to an ordinary method. MATLAB also defines static methods that have no reference to the class instance.

Python uses the name soi when a class wants to refer to the current instance of itself, but this is actually only a convention. You can call the first argument to an instance method any name you want, but soi is the most common convention. Python also defines static methods that don’t take an argument of the class instance and class methods that take an argument of the class object instead of the instance. You can read more about instance, static, and class methods in Python’s Instance, Class, and Static Methods Demystified.

There Is One String Type in Python

In MATLAB, strings of characters are stored in string arrays when you use double quotes (") or in character arrays if you use single quotes ('). If you use both single and double quotes in an array assignment, the array will be promoted to a string array.

In character arrays, each character in the string occupies one column in the array. For multidimensional character arrays, each row of the array must have the same number of characters, which is to say, the same number of columns. This is shown in the example below:

>>>

    1 >> charArray = [[[['Real'; 'Python'];
    2 Dimensions of arrays being concatenated are not consistent.
    3 
    4 >> charArray = [[[['MATLAB'; 'Python'];
    5 >> Taille(charArray)
    6 
    7 ans =
    8 
    9                     2     6

In this example, line 1 shows an attempt to define a 2-row character array using single quotes. However, the number of characters in Real is not the same as in Python, so MATLAB shows an error message that the dimensions are not consistent.

On line 4, you successfully create a character array, and on the third input line you are checking the size of the array. The output shows that there are 2 rows, as expected, and 6 columns, since the length of both MATLAB et Python are 6 characters.

This is not the case for string arrays. In string arrays, each string occupies one column in the array and each row in a multidimensional array must have the same number of strings, although each string can have different length. This is shown in the example below:

>>>

    1 >> stringArray = [[[["Real", "Python"; "Real"];
    2 Error using vertcat
    3 Dimensions of arrays being concatenated are not consistent.
    4 
    5 >> stringArray = [[[["Real"; "Python"];
    6 >> Taille(stringArray)
    7 
    8 ans =
    9 
dix                     2     1

In this code, line 1 shows an attempt to define a 2-row string array using double quotes. However, the number of strings on the first row (2) does not match the number of strings in the second row (1), so MATLAB raises an error.

On line 5, you successfully create a string array. Notice that even though the number of characters is different between Real et Python, MATLAB is able to create the string array. On line 6 you are checking the size of the string array, which shows that there are 2 rows and 1 column, as expected.

In Python, there is only one string literal type, called str. You can create a string literal using single quotes (') or double quotes ("), there is no difference between the two definitions. However, there are some good arguments to prefer double quotes when defining string literals in Python, which are well expressed by the Black code formatting library.

There is one additional way to define strings in Python, using triple-single-quotes (''') or triple-double-quotes ("""). This method of creating strings allows the strings to be defined across multiple lines with the newline characters retained. You can see an example of this in the section about comments and docstrings.

You can read a lot more about defining strings in Basic Data Types in Python and Strings and Character Data in Python.

You can generate similar data structures to the string arrays and character arrays in MATLAB using NumPy in Python. NumPy has several data types, or dtypes, that are related to strings. In Python 3, the default string dtype for arrays is a fixed-width Unicode string:

>>>

Dans [1]: importation numpy comme np
Dans [2]: arr = np.tableau(("Real", "Python"))
Dans [3]: arr
Out[3]: array(['Real', 'Python'], dtype='<U6')

In this code, you are importing the NumPy library on input line 1 and assigning it to the np abbreviation. On input line 2, you are creating a NumPy tableau with 2 string elements, Real et Python, and assigning the array to arr.

On input line 3, you are showing the value of arr. The output from the third line shows that arr is storing an tableau that has 2 elements, 'Real' et 'Python', as expected. Notice that although you defined the array with double-quote strings, Python is displaying them with single-quote strings. Remember that there is no difference between single and double quotes in Python.

Output line 3 also shows the dtype of the data in the array. For this array, the dtype is <U6. The three characters here represent the aspects of how the strings are arranged in memory. le < means that the byte order of the array is little endian. le U means the string is of the Unicode type. Finalement, le 6 means the maximum length of an element is 6 characters. This was chosen as the length of the longest string in the input.

Notice that the string Real only has 4 characters. In NumPy string dtype arrays, elements can have fewer than the maximum number of characters without problems, but assigning to elements with strings that are longer than the maximum length will truncate the input:

>>>

Dans [4]: arr[[[[0] = "My favorite language is Python"
Dans [5]: arr
Out[5]: array(['My fav', 'Python'], dtype='<U6')

In this code, you are attempting to reassign the first element of the array with the string My favorite language is Python. Clearly, this string is longer than 6 characters, so it is truncated to only 6 when it is assigned, My fav. (The space counts as 1 character.)

If you want to create an array that can hold strings of any length, you should pass the objet dtype when you create the array:

>>>

Dans [6]: arr_2 = np.tableau(("Real", "Python"), dtype=objet)
Dans [7]: arr_2
Out[7]: array(['Real', 'Python'], dtype=object)

In this code, you are creating a new array, arr_2, with two elements again, but this time you specified the dtype to be objet, which you confirmed by showing the output on the console. Now you should see how the objet dtype affects assigning long strings to an element:

>>>

Dans [8]: arr_2[[[[0] = "My favorite language is Python"
Dans [9]: arr_2
Out[9]: array(['My favorite language is Python', 'Python'], dtype=object)

In this code, you are again assigning the first element of the array to have the value My favorite language is Python. You can see from the output line that that string is stored as the first element of the array without truncation, because the dtype is objet. The disadvantage of using the objet dtype is that it is usually much slower than the more specific U dtype, because it has to create a a whole Python object for each element rather than just a NumPy-optimized Unicode object.

One other difference you will notice from MATLAB is how the shape or size of the array is determined:

>>>

Dans [10]: arr.forme
Out[10]: (2,)
Dans [11]: arr_2.forme
Out[11]: (2,)

In this code, we are printing the shape of arr et arr_2. Notice that they both have the same shape, two elements in a one-dimensional array. This is similar to the string array from MATLAB, where each string counts as one element in the array. However, the fact that NumPy arrays with the U dtype have a fixed maximum size behaves more like the character array from MATLAB. You’ll see more about differences in how MATLAB and NumPy compute the shape of arrays in a later section.

Libraries Are Not Automatically Reloaded in Python

When executing a function or script, MATLAB will always use the most up-to-date copy of the file on the disk. Therefore, as you’re developing a script, you can run it in the console many times and new changes that you make will automatically be picked up.

Python operates somewhat differently. Remember that when you want to access code from a file, you have to importation it into a namespace. When Python imports a file or module, it only reads the code the first time it is imported. This saves quite a bit of time if you’re importing the same file several times. However, if you’re testing your code in the interactive console prompt as you work on it, Python will not pick up any changes if you importation it again.

When you’re developing a module, you have a few options to have Python reload your code when it is imported. If you’re using the Spyder IDE, this is not a problem at all, since Spyder has an automatic User Module Reloading feature enabled by default.

Otherwise, if you’re using the IPython console outside of Spyder, or the Jupyter Notebook, you can use a magic command defined in those interpreters called autoreload:

>>>

Dans [1]: %load_ext autoreload
Dans [2]: %autoreload 2

In this code, you are using the load_ext magic command to load the autoreload extension. In IPython and Jupyter Notebooks, commands prefixed with the percent sign % are magic commands. le autoreload extension defines the autoreload magic function, which you use on input line 2. You are passing the parameter 2 au autoreload magic function, which means that all modules should be reloaded every time a line of code is executed.

An Overview of Basic Array Operations

As you have seen, Python does not include a high-speed library for arrays in its standard library. However, the excellent NumPy library is easily available if you install Anaconda. NumPy functions as the de facto array and matrix library for Python.

NumPy has two array-like types:

  1. numpy.ndarray, also known as numpy.array
  2. numpy.matrix

The main difference between these two types is that the ndarray can be any number of dimensions, while the matrice is limited to exactly two dimensions. Pour ndarray, all operations such as addition, subtraction, multiplication, exponentiation, and division operate element-wise. However, for the matrice type, operations like multiplication and exponentiation are matrix operations.

When you’re converting from MATLAB, the matrice type may seem more familiar. It offers similar behavior that you may be used to from MATLAB in terms of operation syntax. However, NumPy strongly recommends that you use the ndarray type because it is more flexible and because matrice will eventually be removed.

In the rest of this section, you will get to know the major differences between MATLAB and NumPy arrays. You can go in-depth on how to use NumPy arrays by reading Look Ma, No For-Loops: Array Programming With NumPy.

Basic Mathematical Operators Work Element-Wise in NumPy

MATLAB, with its heritage as a matrix scripting language, assumes that all arithmetic operators will be operating on arrays. Therefore, MATLAB treats the multiplication of matrices or vectors as matrix multiplication. Consider this example:

>>>

>> arr_1 = [[[[1,2,3];
>> arr_2 = [[[[4,5,6];
>> arr_1 * arr_2
Error using  *
Incorrect dimensions for matrix multiplication. Check that the number of
columns in the first matrix matches the number of rows in the second
matrix. To perform elementwise multiplication, use '.*'.

In this code, you are creating two 1×3 matrices, arr_1, et arr_2. Then, you are attempting to multiply them together. For these 1xN arrays, this is equivalent to taking the dot or scalar product. However, the scalar product only works when the left operand is 1xN and the right is Nx1, so MATLAB produces an error message and suggests the dot-star operator (.*) as the proper syntax for element-wise multiplication:

>>>

>> arr_1 .* arr_2

ans =

                    4    10    18

In this code, you are performing the element-wise multiplication of arr_1 et arr_2. This multiplies the first element of arr_1 with the first element of arr_2 (4*1 = 4), second with second (2*5 = 10), and third with third (3*6 = 18).

To perform the scalar product, you can take the transpose of arr_2 to convert it to a 3×1 array:

>>>

>> arr_1 * transposer(arr_2)

ans =

                32

In this code, you are performing matrix multiplication with arr_1 and the transpose of arr_2. Note that you can use either transpose() or the quote operator (') to take the transpose of arr_2. Puisque arr_1 is 1×3 and transpose(arr_2) is 3×1, this results in the scalar, or dot, product.

With NumPy arrays, operations like multiplication with the asterisk (*) operate element-wise by default:

>>>

Dans [1]: importation numpy comme np
Dans [2]: arr_1 = np.tableau([[[[1, 2, 3])
Dans [3]: arr_2 = np.tableau([[[[4, 5, 6])

Dans [4]: arr_1 * arr_2
Out[4]: np.array([ 4, 10, 18])

In this code, you are first importing the NumPy package and assigning it to the name np. Then you are creating two one-dimensional arrays. Notice the syntax for creating arrays in NumPy. It starts with np.array(), which should be read as “from within np, find array().” Then, you have to pass a Python list or tuple to the array constructor that contains the elements of the array. In this case, you are passing a Python list, denoted by the square brackets.

Finally, on input line 4, you are multiplying arr_1 et arr_2. Notice that the result on output line 4 is another array with the elements 4, 10, and 18, the same result as the element-wise multiplication in MATLAB.

If you want to perform the dot or scalar product for two arrays in NumPy, you have two options. The preferred option is to use the matrix multiplication operator (@) added in Python 3.5. You may see some older code also use dot() from the NumPy library and pass the two arrays:

>>>

Dans [5]: arr_1 @ arr_2
Out[5]: 32

Dans [6]: np.point(arr_1, arr_2)
Out[6]: 32

In this code, input line 5 uses the matrix multiplication operator to find the scalar product of arr_1 et arr_2. As expected, the result is 32. Input line 5 uses dot() and should be read as “from within np, find dot() et passe arr_1 et arr_2.” You can see that the result is identical.

Notice that NumPy did not require you to transpose arr_2 before performing the scalar product. You’ll learn more about this feature in the next section.

One-Dimensional Arrays Are Vectors in NumPy

As you saw in the last section, MATLAB insists that the dimensions of arrays align when performing matrix multiplication, while NumPy is a little bit more flexible. This is because of how one-dimensional arrays are treated in MATLAB versus in NumPy.

In MATLAB, every array always has at least two dimensions, even if only implicitly. You can see this by checking the size() of a single number:

Here, you are finding the size of the integer 1. You can see that the result is an array with 1 row and 1 column.

You can create row vectors or column vectors in MATLAB, and switch between them with the transpose operator (') ou transpose():

>>>

>> arr_1 = [[[[1,2,3];
>> arr_2 = [[[[1;2;3];
>> arr_1' == arr_2

ans =

        3×1 logical array

            1
            1
            1

>> arr_2' == arr_1

ans =

        1×3 logical array

            1   1   1

In this code, you are creating two vectors: arr_1 et arr_2. Arrays with values in one dimension only are called vectors. arr_1 is a row vector because the elements are arranged in one row and three columns, whereas arr_2 is a column vector because the elements are arranged in three rows and one column. In MATLAB, elements are put into different columns by separating them with a comma in the assignment and elements are put into different rows by separating them with a semicolon.

Then, you are checking the equality of the transpose of arr_1 avec arr_2, and you find that all of the elements are equal and the result is a column vector of logical values. Finally, you are checking the equality of the transpose of arr_2 avec arr_1, and you find that all of the elements are equal and the result is a row vector of logical values.

You can see that in MATLAB, even vectors have two dimensions associated with them: rangées et des colonnes. When the transpose is performed, the rows are switched with the columns, and the shape of the array is changed. This means there are two types of vectors in MATLAB: row-vectors et column-vectors.

In NumPy, there are three types of one-dimensional arrays or vectors. The default is an N-element vector with only one dimension. This is different from the default in MATLAB, where every array has at least 2 dimensions. This one-dimensional vector in NumPy does not have a sense of rows and columns, since for a one-dimensional structure, it does not matter in general whether the elements are stored in rows or in columns, only how many elements there are.

You can see an example of creating this kind of array in the following example. In the next few examples, there are extra spaces added before and after parentheses to clarify the syntax. These spaces are usually not considered good Python style, but they’re in the example to help you see what’s going on:

>>>

Dans [1]: importation numpy comme np
Dans [2]: arr_vec = np.tableau( [[[[1, 2, 3] )
Dans [3]: arr_vec.forme
Out[3]: (3,)

In this code, you are creating a default 3-element vector in NumPy. On input line 1, you import NumPy and make it available under np. On input line 2 you are creating the array and storing it in arr_vec. You are passing the list [1, 2, 3] à array(), where the list has 3 elements and none of the elements are themselves lists. This creates the 3-element array with only one dimension.

You can verify that this is the case by displaying the shape of the array, as shown on input line 3. That line should be read as “from within arr_vec (an array), find the forme.” The forme of the array is equivalent to size() in MATLAB. In this case, the shape is (3,), indicating there are three elements and only one dimension, since there is not a second number after the comma.

You can also create row-vectors and column-vectors in NumPy, analogous to the row-vectors and column-vectors in MATLAB. NumPy’s array() takes a flat list or a nested list as input. Using the flat list gets you a one-dimensional, N-element vector. By using the nested list, you can create arrays of any dimension that you want. A nested list means that there are one or more lists contained within an outer list. Here’s an example of a nested list:

In this code, you see an outer list that has 2 elements. Each of these 2 elements of the outer list is another, nested, list that has three elements, the integers 1-3 and 4-6. In terms of arrays, you can think of the number of elements of each inner list as the number of columns, and the number of nested lists is the number of rows. This is easier to see if you change the formatting:

This code is still valid Python syntax, but it emphasizes how the inner lists are each a row of the array, and the number of elements in each inner list is the number of columns. In this case, we would have an array with 2 rows and 3 columns. We can use these nested lists to create row-vectors and column-vectors in NumPy arrays:

>>>

Dans [4]: arr_row = np.tableau( [[[[[[[[1, 2, 3]] )
Dans [5]: arr_row.forme
Out[5]: (1, 3)

In this code, you are creating a row array or vector by using a nested list. Input line 4 is passing [[[[[1, 2, 3]] à array(). You can break out the formatting of this nested list to see how it looks:

As you can see, there is one row in this nested list with three columns. On input line 5, you are displaying the shape of this array. As expected, the shape is (1, 3), or one row with three columns.

Finally, you can create a column array by including three nested lists in the input:

>>>

Dans [6]: arr_col = np.tableau( [[[[[[[[1], [[[[2], [[[[3]] )
Dans [7]: arr_col.forme
Out[7]: (3, 1)

In this code, input line 6 is passing [[[[[1], [2], [3]] to the array constructor. You can break out the formatting of this nested list to see how it looks:

As you can see, there are three rows in this nested list with one column each. On input line 7, you are displaying the shape of this array. As expected, the shape is (3, 1), or three rows with one column.

Since the general N-element vector has no sense of rows and columns, NumPy is able to shape the vector in whatever way makes sense for the operation being performed. You saw this in the last section, where the NumPy array did not need to be transposed to perform the scalar product, whereas the MATLAB array did need to be transposed.

Trying to take the transpose of the N-element vector does not change the shape of the array. You can take the transpose using either np.transpose() ou la .T attribute of the array:

>>>

Dans [8]: arr_vec_transp = np.transposer(arr_vec)
Dans [9]: arr_vec_transp.forme
Out[9]: (3,)

In this code, you are taking the transpose of the N-element vector arr_vec and printing its shape. Notice that the shape is the same as the shape of the original arr_vec.

However, if you are using row-vectors and column-vectors, you will need to ensure that the dimensions are appropriate for the particular operation. For instance, trying to take the scalar product of the row vector with itself will result in an error:

>>>

Dans [10]: arr_row @ arr_row
Traceback (most recent call last):

        File "", line 1, in 
                arr_row @ arr_row

ValueError: matmul: Input operand 1 has a mismatch in its core dimension 0,
with gufunc signature (n?,k),(k,m?)->(n?,m?) (size 1 is different from 3)

In this code, trying to find the scalar product of the row vector with itself results in a ValueError informing you that the dimensions of the arrays are not aligned. Using dot() gives the same error but a slightly different message:

>>>

Dans [11]: np.point(arr_row, arr_row)
Traceback (most recent call last):

        File "", line 1, in 
                np.dot(arr_row, arr_row)

ValueError: shapes (1,3) and (1,3) not aligned: 3 (dim 1) != 1 (dim 0)

In this code, you are using dot() du np namespace to attempt to find the scalar product of two 1×3 row-vectors. Since this operation is not permitted, NumPy raises a ValueError, similar to the matrix multiplication operator.

Instead, you need to take the transpose of one of the arguments:

>>>

Dans [12]: arr_row.T
Out[12]:
array([[[[[1],
       [2],
       [3]])
Dans [13]: sc_prod = arr_row @ arr_row.T
Dans [14]: sc_prod
Out[14]: array([[[[[14]])

On input line 12, you are taking the transpose of the row vector to turn it into a column vector using the transpose attribute (.T). This is shown in corresponding output line, where the elements are arranged to form a column for printing purposes. Then, you are taking the scalar product of the vector with its transpose, producing an array with a single value, 14. Notice that this is a 1×1 array, so to access just the value, you need to access the first element in each dimension:

>>>

Dans [15]: sc_prod.forme
Out[15]: (1, 1)
Dans [16]: sc_prod[[[[0, 0]
Out[16]: 14

In this code, you are verifying that the shape is 1×1, and then accessing the first element in each dimension located at the 0th index. Remember that Python uses 0 as the first index, not 1.

You can use the nested lists to create arrays of any shape that you want. To create a three-by-three array (two-dimensional), simply include three elements in each of your three nested lists:

>>>

Dans [17]: arr_2d = np.tableau( [[[[[[[[1, 2, 3], [[[[4, 5, 6], [[[[7, 8, 9]] )
Dans [18]: arr_2d.forme
Out[18]: (3, 3)

In this code, you have nested three lists with three elements each into the constructor. As shown by the shape, this produces a 3×3 array with the elements 1 through 9.

Creating Arrays Is Very Flexible in NumPy

MATLAB and NumPy both allow you to explicitly specify the specific elements in an array, as you have seen in the previous section. In addition to this direct creation of arrays, both MATLAB and NumPy support a number of other methods to create arrays without explicitly specifying each element. The NumPy project maintains a detailed list of the equivalent functions between MATLAB and NumPy.

Many functions operate identically between MATLAB and NumPy. This includes commonly used functions like linspace() et logspace() to generate evenly spaced data and ones() et zeros() to generate arrays of a given shape filled with ones and zeros, respectively. The full list of ways to create arrays in NumPy is listed in the official documentation.

The one big difference between MATLAB and NumPy in terms of array creation routines is that MATLAB supports simply using the colon to create an array, while NumPy does not. Instead, NumPy uses arange() to create an array between specified values.

In MATLAB, you can use a colon to create an array specification range. In general, you can use up to 2 colons in a specification. The syntax is as follows:

début : Arrêtez
début : étape : Arrêtez

In this syntax, the, first method only uses one colon and specifies the start and stop values. The second method includes a second colon, where the value before the first colon is the start, the middle value is the step, and the last value is the stop.

Try out these examples to experiment with this syntax:

>>>

>> arr_1 = 1:6

arr_1 =

                    1     2     3     4     5     6

>> Taille(arr_1)

ans =

                    1     6

In this example, you are using the single colon with the start and stop to generate an array with the values from 1 to 6. You can see that when the step is omitted, it defaults to a value of 1. Notice that MATLAB includes both the start and the stop values in the array, and that the size of the array is 6 elements long. Next, change the value of the step size to create a new array:

>>>

>> arr_2 = 1:2:6

arr_2 =

                    1     3     5

In this example, you are using the two colons syntax with the start, step, and stop. The start value is 1, the step is 2, and the stop value is 6, so MATLAB starts with 1, increments to 3, and then to 5. The next step would exceed the stop value, so MATLAB does not include the stop value in the array. Next, change the starting value to create another new array:

>>>

>> arr_3 = 2:2:6

arr_3 =

                    2     4     6

In this example, you are again using the two colon method, but you are specifying the start value as 2 instead of 1. In this case, MATLAB starts at 2, increments to 4, increments to 6, and then has reached the stop value so does not go further. Notice that in this case, the the stop value of 6 is included in the array.

With NumPy, you can use arange() to create an array with specific start, stop, and step values. cependant, arange() has one big difference from MATLAB, which is that the stop value is ne pas included in the resulting array. The reason for this is so that the size of the array is equal to stop - start for the default case of a step size of 1. Notice in MATLAB that the size of the array of the integers from 1 to 6 is 6, but 6 – 1 = 5.

There are three ways to use arange():

importation numpy comme np
np.arange(Arrêtez)
np.arange(début, Arrêtez)
np.arange(début, Arrêtez, étape)

If you only pass one argument to arange(), it will be interpreted as the stop value. The start value defaults to 0 and the step defaults to 1. If you pass two arguments to arange(), they are interpreted as the start and stop values. Finally, you can pass all three of start, stop, and step to arange().

Notice that the order of the arguments is different from MATLAB, going début, Arrêtez, étape in Python. If you’re having trouble remembering the order that these arguments go, remember that you can use keyword arguments in Python to be explicit about what each argument means.

You can try out arange() with the following examples:

>>>

Dans [1]: importation numpy comme np
Dans [2]: arr_1 = np.arange(1, 7)
Dans [3]: arr_1
Out[3]: array([1, 2, 3, 4, 5, 6])
Dans [4]: arr_1.forme
Out[4]: (6,)

In this example, you are creating an array that contains the values from 1 to 6. As in MATLAB, if the step is omitted, it defaults to 1. Notice that you had to pass the stop value 7 so that the array stopped at 6. However, the size of the resulting array is 7 – 1 = 6 elements long. Next, you should see how to change the step size:

>>>

Dans [5]: arr_2 = np.arange(1, 7, 2)
Dans [6]: arr_2
Out[6]: array([1, 3, 5])

In this code, you are creating an array that contains the values from 1 to 6, incrementing by two between each element. The step is two, so NumPy starts with 1, increments to 3, and then to 5. The next step would equal the stop value, but NumPy does not include the stop value in the array. Notice that the formula to compute the size of the array is a little bit different, since the step size is not 1.

With step sizes other than 1, the size of the array can be computed by (stop - start)/step if this results in an integer value. In this case, the size of the array is (7 – 1)/2 = 3 elements, as expected. Si (stop - start)/step results in a floating point number, the size of the array is equal to the next largest integer as demonstrated in the next example:

>>>

Dans [7]: arr_3 = np.arange(2, 7, 2)
Dans [8]: arr_3
Out[8]: array([2, 4, 6])

In this example, you are creating an array that contains the values from 2 to 6, incrementing by two between each element. The step is two, so NumPy starts with 2, increments to 4, and then to 6. The next step would exceed the stop value, so NumPy stops at 6. Notice that the size of the array is (7 – 2)/2 = 2.5, so the next highest integer is 3 elements, as expected.

Finally, you should usually use integer arguments to arange() in NumPy and the colon operator in MATLAB. If you use floating point values (numbers with decimals), especially for the step, the elements may not come out exactly as you expect. If you want to use floating point numbers, linspace() is a better choice in general.

The Colon Operator Is Very Powerful in NumPy

In MATLAB, the colon operator is used to perform a number of useful tasks. As you saw, it can be used to create arrays, and it can also be used to index or slice arrays. When indexing arrays, MATLAB supports the fin keyword to extend the specified range to the end of that dimension, as you saw earlier:

>>>

>> arr_1 = 1:2:6;
>> arr_1(2:fin)

ans =

                    4     6

In this code, you are indexing arr_1 starting at the second index and going to the end of the array. You can also specify a specific index as the stop value:

>>>

>> arr_2 = 1:6;
>> arr_2(2:4)

ans =

                    2     3     4

In this code, you are creating an array arr_2 with the numbers 1 through 6, inclusive. Then, you are specifying the second element as the start value and the fourth element as the stop value in the slice. MATLAB supports the two-colon increment syntax when indexing as well:

>>>

>> arr_2(2:2:fin)

ans =

                    2     4     6

In this code, you are indexing the array, starting at the second element, skipping every other element, until the end of the array. You can also use fin as the starting point of the slice with a negative step:

>>>

>> arr_2(fin:-1:4)

ans =

                    6     5     4

In this code, you are indexing arr_2 starting from the last value, decrementing by 1, and ending at the 4th element. Finally, you can slice all of the element in a dimension by using just a bare colon:

>>>

>> arr_2(:)

ans =

                    1     2     3     4     5     6

In this code, you are selecting all of the first dimension of the array using just the colon.

NumPy and Python in general also use the colon for the slice syntax, but the order of the values is slightly different. In Python, the order is start : stop : step, whereas in MATLAB, it is start : step : stop, as you saw earlier. In addition, in NumPy you can omit start or stop and they will have default a value of 0 (or the first element) for start and the last element for stop. In MATLAB, you must specify start et stop if you want to specify either of them. Thus, Python does not have the fin keyword, since you can omit Arrêtez to achieve the same behavior.

Try out the following examples of the slice syntax in NumPy:

>>>

Dans [1]: importation numpy comme np
Dans [2]: arr_1 = np.arange(1, 7, 2)
Dans [3]: arr_1[[[[1:]
Out[3]: array([4, 6])

In this code, you are creating an array with the integers from 1 to 6, inclusive, skipping every other number. Then, you are slicing the array taking the second element (index 1) until the end of the array. Notice that the stop value was omitted, so it defaulted to the last element in the array.

You can also specify a specific element as the stop value. You saw in using arange() that the array did not include the stop value. The same is true of the slice syntax in Python, the slice will include everything up to, but not including, the stop index:

>>>

Dans [4]: arr_2 = np.arange(1, 7)
Dans [5]: arr_2[[[[1:4]
Out[5]: array([2, 3, 4])

In this code, you are creating an array with the integers from 1 to 6, inclusive. Then, you are slicing the array starting at the second element (index 1, value 2) until the fourth element (index 3, value 4). However, you specified the stop index as 4 (the fifth element in the array, value 5). The reason Python includes up to the (stop – 1) index is the same reason arange() does not include the stop value, so that the length of the resulting array is equal to stop - start. Next, try changing the step of the slice:

>>>

Dans [6]: arr_2[[[[1::2]
Out[6]: array([2, 4, 6])

In this code, you are slicing the array starting at the second element (index 1), going until the end of the array, and taking every second element. This results in an array with the values 2, 4, and 6. Notice that the stop value was omitted in the slice syntax, so it defaulted to the last element in the array.

You can also use a negative step in the slicing syntax for Python:

>>>

Dans [7]: arr_2[:[:[:[:2:-1]
Out[7]: array([6, 5, 4])

In this code, you are not specifying the start index of the slice, you are specifying the stop value should be index 2, and the step should be -1. Since the start index is not specified and the step is negative, the start value is assumed to be the last element in the array (or the first element in the reversed array). For the stop value, index 2 has the value of 3 and one index before that (in the reversed array) is index 3 with the value of 4.

Finally, just like in MATLAB, a bare colon means to select all of the elements from that dimension:

>>>

Dans [8]: arr_2[:]
Out[8]: array([1, 2, 3, 4, 5, 6])

Array Slices Are Views of Arrays in NumPy

In MATLAB, when you access a slice of an array and assign it to a variable, MATLAB will make a copy of that portion of the array into your new variable. This means that when you assign values to the slice, the original array is not affected. Try out this example to help explain the differences of MATLAB vs Python:

>>>

>> arr_1 = [[[[1,2,3;4,5,6;7,8,9];
>> arr_2 = arr_1(2:fin,2:fin)

arr_2 =

                    5     6
                    8     9

>> arr_2(1, 1) = dix

arr_2 =

                10     6
                    8     9

>> arr_1

arr_1 =

                    1     2     3
                    4     5     6
                    7     8     9

In this code, you have created a 3×3 array arr_1 storing the values from 1 through 9. Then, you create a 2×2 slice of the original array storing from the second value to the end in both dimensions, arr_2. On the third input line, you assign the value 10 to the upper left element in arr_2. Finally, you print arr_1 again to verify that none of the values in arr_1 have changed.

In NumPy, slices of arrays are views to the original array. This behavior saves memory and time, since the values in the array don’t have to be copied to a new location. However, it means that changes that you make to a slice from an array will change the original array. You should try the following code to see how this works:

>>>

Dans [1]: importation numpy comme np
Dans [2]: arr_1 = np.tableau([[[[[[[[1, 2, 3], [[[[4, 5, 6], [[[[7, 8 ,9]])
Dans [3]: arr_2 = arr_1[[[[1:, 1:]
Dans [4]: arr_2
Out[4]:
array([[5, 6],
       [8, 9]])

In this code, you are creating a 3×3 array arr_1 storing the values from 1 through 9. Then, you create a 2×2 slice of the original array storing from the second value to the end in both dimensions, arr_2. Notice that the Python indexing is 0-based, so the second element has the index 1. Finally, you are printing arr_2 to verify that it is a 2×2 array.

Now you should see what happens when you change a value in arr_2. Like in the MATLAB example, you should change the upper left element of arr_2:

>>>

Dans [5]: arr_2[[[[0, 0] = dix
Dans [6]: arr_2
Out[6]:
array([[10,  6],
       [ 8,  9]])
Dans [7]: arr_1
Out[7]:
array([[ 1,  2,  3],
       [ 4, 10,  6],
       [ 7,  8,  9]])

In this code, you first assign the upper left element in arr_2, at index (0, 0) to have a value of 10. Then you print arr_2 to verify that the appropriate value has changed. Finally, you print arr_1 and see that the value in the middle of the array has changed from 5 to 10!

This is what is meant by arr_2 être un vue de arr_1. Since it is a view, arr_2 points to the same memory location as arr_1, so updating arr_2 also updates arr_1 because the value stored in the memory location accessed by both arr_2 et arr_1 has been updated. This also goes the other direction, where changing values in arr_1 will update the value in arr_2:

>>>

Dans [8]: arr_1[[[[-1, -1] = 42
Dans [9]: arr_1
Out[9]:
array([[ 1,  2,  3],
       [ 4, 10,  6],
       [ 7,  8, 42]])
Dans [10]: arr_2
Out[10]:
array([[10,  6],
       [ 8, 42]])

In this code, you are assigning the bottom right element of arr_1 to have the value 42. Remember that in Python, an index of -1 means the last value on that dimension. Then you are printing arr_1 to verify that the lower right value has changed from 9 to 42. Finally, you are printing arr_2, and you see for arr_2 as well, the bottom right value has changed from 9 to 42.

If you want to generate a copy of an array, you can use np.copy(). Copying an array creates a new place in memory for the copy to be stored, so changes to the copied array do not affect the original:

>>>

Dans [11]: arr_3 = np.copie(arr_2)
Dans [12]: arr_3[[[[1, 0] = 37
Dans [13]: arr_3
Out[13]:
array([[10,  6],
       [37, 42]])
Dans [14]: arr_2
Out[14]:
array([[10,  6],
       [ 8, 42]])

In this code, you are creating arr_3 as a copy of arr_2. Then, you are changing the element in the second row, first column to have the value of 37. Then, you are printing arr_3 to verify that the specified change has been made. Finally, you are printing arr_2 to verify that no changes have occurred in arr_2, as expected.

Tips and Tricks to Make Your Code Pythonic

Like any other programming language, Python code written by experienced Python developers often has a particular look and feel to it. This is because they are able to take advantage of specific idioms in Python to work with Python rather than against Python. Developers coming from other languages often miss out on what makes code Pythonic in their first projects.

In this section, you’ll learn some tips and tricks to make your code Pythonic and level up your Python skills. There are many more tips and tricks than you can learn here, so feel free to check out Write More Pythonic Code.

You Should Not Use Semicolons to End Lines in Python

In MATLAB, ending a line of code with a semicolon ; suppresses the output from that line. For instance, assigning a variable will print the value of the variable after the assignment if the semicolon is omitted.

In Python, you should not end lines of code with semicolons. It is unnecessary, since Python does not change its behavior whether the line is ended with a semicolon or not. So you can save yourself a key stroke and not bother including the semicolon in your scripts and libraries.

There is one case in Python where the semicolon is useful. When you want to execute several statements, but you cannot include a newline character in the input, you can separate the statements with semicolons. This is mostly useful to execute very short scripts from the command prompt or terminal. For instance, to find the particular Python executable that is running, you can type the following:

$ python -c "import sys; print(sys.executable)"
/home/eleanor/anaconda3/bin/python

In this code, you are executing the Python interpreter in the python executable and passing the -c switch. This switch takes the next argument and executes it within the interpreter. Since the shell environment would execute if you pressed Enter to insert a new line, you can type the whole script on one line.

In this case, you have two logical statements that need to be separated by the semicolon. First you are importing the built-in sys library and then you are printing the value of sys.executable. In this example, the Python interpreter that the shell is running comes from the /home/eleanor/anaconda3/bin/python file.

You Should Not Import * From a Module in Python

In a previous section, you read about how namespaces are one honking great idea in Python. In MATLAB, all functions are part of the global namespace by default, so every function and class name has to be unique. Python solves this problem by using namespaces and requiring you to specify which module a function should come from.

You will find tutorials around the Web that suggest you write the following:

In this code, you are using the * to indicate that Python should import everything that is contained in a_module and put it in the current scope without a prefix. This is slightly more convenient, because you no longer have to prefix functions and classes from a_module with anything, you can just use them directly. However, it is not a good practice because you don’t know what names are defined in a_module and whether or not they will override any existing names in your current scope.

You Should Take Advantage of the Different Data Types in Python

MATLAB, with its heritage as a linear algebra and array focused language, treats most data types as arrays of some sort. This often makes it a little bit tricky to work with more advanced data types like structs, containers.Map, cell arrays, and more.

Python has several built-in data types that are very flexible and can be used to accomplish a number of useful tasks. The major ones that you’ll learn about in this section are lists and dictionaries.

Lists

Python lists are mutable sequences of values. Lists can contain heterogeneous data, which means that each element of the list can be of a different type. Because lists are mutable, you can change the value of any element in the list, or add or remove values from the list, without creating a new list object.

Since lists are sequences, you can create loops that iterate over them. In Python, you do not need to access each element of a list with an index in a pour loop, as you would do in MATLAB:

>>>

>> arr_1 = 1:2:6;
>> pour je = 1:longueur(arr_1)
                disp(arr_1(i))
fin
1
3
5

In this code, you are creating an array arr_1 with the integers from 1 to 6, taking every other number. Then you are creating a pour loop where the loop variable goes from 1 to the length of arr_1. Finally, you are displaying the value of the element of arr_1 at the loop variable on each step by using the loop variable je indexer arr_1.

In Python, you should not use an index for the list when you loop over it. Instead, you should loop directly over the items in a list:

>>>

Dans [1]: lst_1 = [[[[1, "b", 3.0]
Dans [2]: pour article dans lst_1:
            ...:     impression(article)
            ...:
1
b
3.0

In this code, on input line 1 you are first creating a Python list with three elements:

  1. The integer 1
  2. The string "b"
  3. The float 3.0

This list is assigned to lst_1. Then you are using a pour loop to access each item in the list in turn. On each iteration, the next value in the list is put into the variable article that you specified on the pour line. Then, you are printing the value of article on each iteration.

Notice in the previous example that you could loop over the value of each element in the list without using an index. Nonetheless, sometimes you want to access the index of each item in the list as you’re looping over it. For those cases, Python provides enumerate() that returns the index and the value of the item:

>>>

Dans [3]: pour indice, article dans énumérer(lst_1):
            ...:     impression(F"The index is index    and the item is item")
            ...:
The index is 0 and the item is 1
The index is 1 and the item is b
The index is 2 and the item is 3.0

In this code, you are looping over lst_1 again, but this time, you are using enumerate() to get both the index and the item. Then you are printing the value of the index and item on each loop iteration. As you can see from the result, the index values start at 0 as expected, but you do not need to use the index to access the item from the list.

In summary, you should not write Python code like this:

pour je dans intervalle(len(lst_1)):
    impression(lst_1[[[[je])

In this code, you are creating a range of integers from 0 to the length of lst_1 and then you are accessing each element in the list by its index. This can lead to off-by-one and fencepost errors. Instead, you should write code that loops over the list directly:

pour article dans lst_1:
    impression(article)

You can read a lot more about lists in Lists and Tuples in Python and about pour loops and iteration in Python “for” Loops (Definite Iteration). There is also a more advanced concept called comprendre la liste that you can learn about in Using List Comprehensions Effectively.

Dictionaries

In MATLAB, you can create a map data type with containers.Map(). This kind of data structure is useful when you have two pieces of data that are always related to each other and you want to connect them together. For instance, you can map cities to their population with a containers.Map():

>>>

>> villes = des conteneurs.Map('Cleveland';'Pittsburgh';'Hartford',
                           [383793,301048,122587])
>> villes('Cleveland')

ans =

                    383793

In this code, you are creating a containers.Map() on the first line. The first argument is a cell array of character arrays with the city names. These are called the clés of the map. The second argument is an array of populations. These are called the valeurs of the map. Then, you are accessing the value of the population in Cleveland by indexing the map with a character array.

You can assign new values into the map by assigning to an undefined key value:

>>>

>> villes('Providence') = 180393;

If you try to access a key that does not exist, you will receive an error message:

>>>

>> villes('New York City')
Error using containers.Map/subsref
The specified key is not present in this container.

Python has an equivalent data structure called a dictionnaire. To create a Python dictionary, you can use curly braces and specify the keys and values with each other:

>>>

Dans [1]: villes = 
            ...: "Cleveland": 383_793,
            ...: "Pittsburgh": 301_048,
            ...: "Hartford": 122_587
Dans [2]: villes[[[["Cleveland"]
Out[2]: 383793

In this code, on input line 1 you are creating the dictionary of cities using curly braces. Notice that the key and value are specified together, separated by a colon. The values are specified with _ in the numbers, a feature available since Python 3.6. This does not change the value of the number, it only makes it easier to read very large numbers. Then, you are accessing the value at the "Cleveland" key using square brackets, similar to the indexing syntax for lists and arrays.

You can add new keys to the dictionary by assigning to them:

>>>

Dans [3]: villes[[[["Providence"] = 180_393

In this code, you assigned a new key "Providence" to the dictionary with a value of 180,393. If you try to access a key that is not in the dictionary, you will get a KeyError:

>>>

Dans [4]: villes[[[["New York City"]
Traceback (most recent call last):

        File "", line 1, in 
                villes["New York City"]

KeyError: 'New York City'

In this code, you are trying to access the dictionary using the "New York City" key. However, this key does not exist in the dictionary so Python raises a KeyError letting you know that "New York City" is not an option.

You can read a lot more about Python dictionaries in Dictionaries in Python and KeyError exceptions in Python KeyError Exceptions and How to Handle Them. You can also iterate through dictionaries and use dictionary comprehensions, similar to list comprehensions. You can read about these topics in How to Iterate Through a Dictionary in Python.

Exceptions Help You Control Program Flow in Python

MATLAB and Python both use errors and exceptions to let you know when something has gone wrong in the code. In this section, you will learn about common exceptions in Python and how you can handle them appropriately.

If you want an introduction to Python exceptions overall, you can read Python Exceptions: An Introduction. When a Python exception is raised, it produces a traceback. You can read about how to interpret the traceback in Understanding Python Tracebacks. Understanding tracebacks is very helpful to interpret and correct Python exceptions in general. There are a few specific cases that usually have the same resolution. You’ll see those described in the rest of this section.

NameError

Python NameError exceptions are usually the result of a variable being undefined. When you see a NameError, check your code for typos and misspelled variable names. You can use the debugging features and the variable explorer in Spyder to find out which variables are defined.

SyntaxError

Python SyntaxError exceptions mean that you have input some improper syntax. This is usually caused by mismatched brackets, when you have only the opening bracket or closing bracket but not the matching one. These exceptions usually point to the line après the place where the problem is located.

Another common SyntaxError is using only one equals sign in an si statement. In this case, you either meant not-equals (!=) or equals (==), so you can correct the line.

KeyError

Python KeyError exceptions occur when you try to access a key in a dictionary that does not exist. Vous pouvez utiliser .get() to retrieve a key from a dictionary if it exists, or return a default value if the key does not exist. You can read more about KeyError exceptions in Python KeyError Exceptions and How to Handle Them.

IndexError

Python IndexError exceptions occur when you are trying to access the index of an array or list that does not exist. This usually means the array or list you are trying to access has fewer elements than the index you are trying to access. You can use the debugging features and the variable explorer in Spyder to see the size of lists and arrays and make sure you’re only accessing indices that exist.

ImportError/ModuleNotFoundError

Python ImportError et ModuleNotFoundError exceptions occur when you try to import a module that Python cannot find. This might be because it is installed in a different conda environment or virtualenv, or it might be because you forgot to install the package.

The solution to this error is usually to conda install ou pip install the package and make sure the correct environment is activated. If you’re not using the base environment in conda, you also need to make sure to install Spyder or Jupyter into your environment.

TypeError/ValueError

Python TypeError exceptions happen when an argument is of the wrong type. This happens most commonly when you pass an argument of the wrong type into a function. For instance, a function that works with numbers would raise a TypeError if a string were passed in.

A related exception is the ValueError. This exception happens when an argument is of the correct type, but has an incorrect value. For instance, a function that works only with positive numbers would raise a ValueError if a negative number were passed in.

AttributeError

Python AttributeError exceptions happen when you try to access an attribute of an object when the object does not have that attribute. You will often see this error associated with the message NoneType object has no attribute. This message most likely means that a function has returned Aucun instead of the object you were expecting and you are trying to access an attribute that would be present on the real object, but is not defined for Aucun.

How to Handle Exceptions in Python

MATLAB allows you to essayer a statement of code and capture any errors that are thrown by the code. Once you have caught an error, you can do further processing of the error and assign variables based on the type of error. The MATLAB documentation has several good examples of how this would look in MATLAB.

In Python, one big difference from MATLAB is that you can choose to catch only certain types of exceptions and handle them. This allows all other exceptions to continue to be displayed to the user. If you want to learn more about how to do this in Python, you can read The essayer et sauf Block: Handling Exceptions.

To see how this works, you can try the following example:

>>>

Dans [1]: importation math
Dans [2]: def my_sqrt(nombre):
            ...:    impression(F"You passed the argument: number!r")
            ...:    essayer:
            ...:        revenir math.sqrt(nombre)
            ...:    sauf ValueError:
            ...:        impression("You passed a number that cannot be operated on")
            ...:    sauf TypeError:
            ...:        impression("You passed an argument that was not a number")
            ...:

Dans [3]: my_sqrt(4.0)
You passed the argument: 4.0
Out[3]: 2.0

Dans [4]: my_sqrt(-1,0)
You passed the argument: -1.0
You passed a number that cannot be operated on

Dans [4]: my_sqrt("4.0")
You passed the argument: '4.0'
You passed an argument that was not a number

In this code, on input line 1 you are importing the built-in math library. Then, starting on input line 2, you are defining a function called my_sqrt() that will take one argument, called nombre. Inside the function definition, you first print the argument that the user passed.

Next, you enter the essayer/sauf block. First, you try to take the square root of the input argument and return the result. If taking the square root of the argument results in an error, Python will catch that error and check which type of error was raised.

You have defined code that handles two specific exceptions: ValueError et TypeError. Si math.sqrt() raises a ValueError, your code will print a message that the number cannot be operated on. Si math.sqrt() raises a TypeError, your code will print a message that the argument was not a number. If any other type of exception is raised by math.sqrt(), that error will be passed through without any processing, since there is no handler for any other error types.

More specifically, Python checks for any error that is raised by the code in the essayer block. In your case, you only defined one line of code in the essayer block, but this is not required, and you can have as many lines as you want there. However, it is usually a good practice to minimize the number of lines of code in the essayer block so you can be very specific about which code is raising any errors.

On input line 3, you are testing out my_sqrt(). First, you pass the value 4.0 to the function. The function prints the argument, and math.sqrt() has no problems taking the square root of 4, resulting in 2.0 on the output line.

On input line 4, you are passing -1.0 as the argument to my_sqrt(). As you may recall, taking the square root of negative numbers results in a complex number, which the math.sqrt() function is not equipped to handle. Taking the square root of a negative number using math.sqrt() raises a ValueError. You exception handler catches this ValueError and prints the message that the number cannot be operated on.

On input line 5, you are passing "4.0" as the argument to my_sqrt(). In this case, math.sqrt() does not know how to take the square root of a string, even though that string appears to represent a number. You can see that you have passed a string by the quotes in the statement giving the value of the argument: You passed the argument: '4.0'. Puisque math.sqrt() cannot take the square root of a string, it raises a TypeError, and your function prints the message that the argument was not a number.

There Is an Official Guide to Writing Good Code in Python

The Python community has developed a set of recommendations for how to style your Python code. These are codified in a document called PEP 8, which stands for Python Enhancement Proposal #8. PEP 8 can be found in full on the Python website. You can also learn more about good Python style in How to Write Beautiful Python Code With PEP 8 and Idiomatic Python 101.

Perhaps the most important principle in PEP 8 is the saying that “a foolish consistency is the hobgoblin of little minds.” This means that you should follow the recommendations in PEP 8 for almost all of your code, but there may be some limited cases where it is a good idea not to follow the PEP 8 recommendations. For instance, if you are working with an existing codebase that has its own style, you should follow that style where it diverges from PEP 8. You can see an excellent discussion of this principle from Raymond Hettinger, one of the core Python developers, in a talk from PyCon 2015.

Aside from reading PEP 8, you can use a few Python packages to automatically make sure that your code fits the style guidelines. Flake8 is a code linter that reads your code and makes suggestions for how you can improve it. This is similar to the feature in the MATLAB code editor that makes improvement suggestions. In addition, packages such as Black, yapf, and autopep8 will automatically format your code to be compliant with PEP 8 or your own style rules. Using these packages can help your code feel more Pythonic and help you learn good Python style!

Python Has a Fantastic and Supportive Community

Python is known for having a very supportive, open, and welcoming community. Whether you are a brand new developer or an experienced one, whether you’re brand new to Python or have been to a dozen conferences, the community is there to support you and what you want to do.

The community starts with the Python Package Index (called PyPI or the CheeseShop, a reference to the Monty Python sketch), which houses hundreds of thousands of different Python packages that you can download for free. These packages can be installed using pépin, a package manager that comes bundled with Python. This means that adding the functionality you need to Python can be as simple as pip install package or if you’re using Anaconda, conda install package.

Since Python is used in so many different areas of software development, data science, science, and engineering, there are always people around who want to talk about Python. Most large cities around the world have Python meetup groups. You can go to these groups to learn about Python by hearing people speak about their work or work on some open-source code.

A few times a year, these groups coalesce into different PyCons which happen on every continent around the globe. PyCon North America is the largest of these, with several thousand attendees every year. You can read all about what it’s like to attend in How to Get the Most Out of PyCon.

Python also has a very strong online community. If you have a question about programming in Python, you can ask on StackOverflow and some of the world-leading Python experts will be able to help you out. Make sure to follow the instructions for how to ask a question on StackOverflow. Remember that the more effort you put into your question, the more likely you are to either find the answer yourself (hourra!) or get a good answer from someone else.

If you want to follow along with Python’s development, you can sign up for one of the mailing lists covering different aspects of Python’s community. The general mailing list for asking questions about writing programs in Python is called comp.lang.python. If you are interested in the development of Python itself, you can follow the python-dev mailing list.

If you’re interested in learning much, much more about Python development, you can check out the Real Python Learning Paths!

Areas Where You Should Still Use MATLAB®

In spite of the awesome community and terrific packages, there are still one or two areas where MATLAB works better than Python. The main place where Python can’t compete with MATLAB is the Simulink Toolbox. This toolbox offers advanced capabilities for signal processing and modeling in a convenient graphical interface.

Python does not have an equivalent graphical interface to these kinds of functions. However, to the extent that Simulink is a convenient interface to ordinary differential equation solvers, Python has equivalent solvers as in MATLAB and the underlying functionality of Simulink can certainly be replicated in Python.

Otherwise, you can do anything in Python that you can do in MATLAB! If you can think of work that you can do with MATLAB, but you’re not sure how to do it in Python, let us know in the comments and we’ll be able to help with suggestions.

Conclusion

Congratulations, you now have the knowledge you need to switch your MATLAB code to Python! In this article, you learned a little bit about what Python is, how to set up your computer to use Python, and how to convert your code from MATLAB to Python.

Python is a really huge language and community, with lots to learn and lots of people to learn from. Remember, you weren’t a MATLAB expert the first time you opened the MATLAB development environment, and the same is true about the first time you write some Python code. Come back to this article as often as you need to improve your skills and learn more about becoming a Python wizard!

Lectures complémentaires

There are tons of resources on the Web covering the differences in MATLAB vs Python. Here are a few of the resources that I found helpful when I transitioned from MATLAB to Python: