#!/usr/bin/env python # coding: utf-8 # # Prise en main de Python et des notebooks # *** # > __Auteur__: Joseph Salmon # > # In[ ]: import numpy as np import matplotlib.pyplot as plt # ## Connaître la version de Python utilisée # In[ ]: from platform import python_version print(python_version()) # ## Creation de tableau 1D avec valeurs numériques # In[ ]: # Ceci est un commenatire x1 = np.linspace(0.0, 5.0, num=50) x2 = np.linspace(0.0, 2.0, num=50) y1 = np.cos(2 * np.pi * x1) * np.exp(-x1) y2 = np.cos(2 * np.pi * x2) # In[ ]: # Affichage graphique fig1=plt.figure(figsize=(7,7)) plt.subplot(2, 1, 1) plt.plot(x1, y1, 'o-') plt.title('A tale of 2 subplots') plt.ylabel('Damped oscillation') plt.subplot(2, 1, 2) plt.plot(x2, y2, '.-') plt.xlabel('Time (s)') plt.ylabel('Undamped') plt.show() # Pour forcer l'affichage # ### Fin de la première partie de la démo du cours ici # ## Affichage et aide # In[ ]: print('Salut toute le monde') # In[ ]: get_ipython().run_line_magic('pinfo', 'print') # In[ ]: get_ipython().run_line_magic('pinfo2', 'print') # In[ ]: dir('Salut toute le monde') # In[ ]: print('Salut # ## Chaînes de caractères # In[ ]: first_name = 'Joseph' last_name = 'Salmon' print('Prénom = {} ; nom = {};'.format(first_name, last_name)) print(type(first_name)) # In[ ]: len(first_name),len(last_name) # In[ ]: print('l\'apostrophe dans une chaîne') print('Hacque ,\n post \n postridie') print('\t \t descriptione, post \npostridie') # Concaténation: # In[ ]: 'Et un,' + ' et deux,' + ' et trois zéros' # Répétition: # In[ ]: 'Et un,' * 8 # Remplacement: # In[ ]: 'Et un,'.replace('un', 'deux') # Découpage: # In[ ]: chaine = 'aaa, bbb, cccc, dd' chaine.split(',') # Extraction: # In[ ]: chef_gaulois = 'Abraracourcix' print(chef_gaulois[1], chef_gaulois[-2]) test = 4 print(chef_gaulois[test:], chef_gaulois[:test]) print(chef_gaulois[2:5]) print(chef_gaulois[::4], chef_gaulois[::-2]) # ## Entier / int # In[ ]: fact5 = 1 * 2 * 3 * 4 * 5 print(fact5) # In[ ]: 7 / 3 # In[ ]: type(7) # In[ ]: 7 // 3 # In[ ]: 7 % 3 # In[ ]: type(7 // 3) # In[ ]: type(7 / 3) # ## Flottants / floats # In[ ]: 1e-3 # In[ ]: 1e15 # Exemples à méditer: # In[ ]: 0.1 + 0.2 - 0.3 # In[ ]: nb_small1 = 1e-41 nb_small2 = 1e-40 nb_small1 - nb_small2 # In[ ]: nb_big1 = 1e150 nb_big2 = 1e150 nb_big1 * nb_big2 # In[ ]: too_big = nb_big1 * nb_big2 ** 2 print(too_big) # In[ ]: too_big / too_big # In[ ]: too_big -too_big # In[ ]: int(3.0),type(int(3.0)) # In[ ]: float(3), type(float(3)) # In[ ]: type(float(3)), str(3.) # In[ ]: float('3.'), type(float('3.')) # # Complexes # In[ ]: 1j**2 # In[ ]: z=complex(4,3) print(z,type(z)) # In[ ]: import cmath z = complex(4, 3) print(abs(z), cmath.polar(z)) print(z.real, z.imag) # ## Booléens # In[ ]: a = 3 b = 4 print(a == 4) # In[ ]: print( a < b) # In[ ]: petit_nb = 0.1 + 0.2 - 0.3 mon_test = petit_nb == 0 print(mon_test) # In[ ]: import math print(petit_nb) print(math.isclose(0., petit_nb, abs_tol=1e-5)) print(math.isclose(0., petit_nb, abs_tol=1e-17)) # ## Listes # In[ ]: a = ["bras", "jambes", 10, 12] a # In[ ]: a[0:2] = [] a # In[ ]: a[1:1] = ['main', 'coude'] # Insertion a # In[ ]: # In[ ]: a[:] = [] a, len(a), type(a) # In[ ]: dir(a) # ## Dictionnaires # In[ ]: dico = {} dico['car'] = 'voiture' dico['plane'] ='avion' dico['bus'] ='bus' print(dico) # In[ ]: del(dico['bus']) dico # In[ ]: print(dico[1:2]) # attention erreur! # In[ ]: print(dico + dico) # attention erreur! # In[ ]: # Zipping dico_2 = dict(zip(['car', 'plane'], ['voiture', 'avion'])) print(dico_2) # In[ ]: dico_3 = {'nom': {'first': 'Alexandre', 'last': 'PetitChateau'}, 'emploi': ['enseignant', 'chercheur'], 'age': 36} print(dico_3) # ## If then else # In[ ]: nb_a = 14 if nb_a%2==0: print("nb_a est paire") else: print("nb_a est impaire") # In[ ]: nb_a = 11 if nb_a%3==0: print("nb_a est congru à 0 modulo 3") elif nb_a%3==1: print("nb_a est congru à 1 modulo 3") else: print("nb_a est congru à 2 modulo 3") # ## Boucle *for* # In[ ]: for i in range(4): print("La racine de {:d} est {:.3f}". format(i, i**0.5)) # In[ ]: a = [1,4,2,7,1,9,0,3,4,6,6,6,8,3] [x for x in a if x > 5] # In[ ]: print([c * 2 for c in 'ohé']) # ## Enumerate # In[ ]: liste_carres =[] # init: liste vide for i in range(4): liste_carres.append(i**2) # In[ ]: for i, carre in enumerate(liste_carres): print(int(carre**0.5)) # affichage en passant de float à int # ## Boucle *while* # In[ ]: i = 0 print("Nb x t.q. 2^x < 100:") while (2**i < 10): print("{0}".format(i)) i += 1 # incrémente le compteur # # Fonctions # In[ ]: def fonction1(): print("mon test") # In[ ]: fonction1() # In[ ]: def fonction2(s): """ Affichage d'une chaîne et de sa longueur """ print("{} est de longueur : ".format(s) + str(len(s))) # In[ ]: fonction2("Cette chaine de test") # Pour afficher la documentation de la fonction fonction2: # In[ ]: get_ipython().run_line_magic('pinfo', 'fonction2') # Pour afficher le code source de la fonction fonction2: # In[ ]: get_ipython().run_line_magic('pinfo2', 'fonction2') # In[ ]: def square(x): """ Retourne le carré de x. """ return x ** 2 # In[ ]: square(3), square(0.4) # In[ ]: def powers(x): """ Retourne les premières puissances de x. """ return x ** 2, x ** 3, x ** 4 # In[ ]: out = powers(3) print(out) print(type(out)) x2, x3, x4 = powers(3) print(x2, x3) # In[ ]: def ma_puissance(x, exposant=3, verbose=False): """ Fonction calculant une puissance Paramètres ---------- x : float, Valeur du nombre dont on calcule la puissance exposant : float, default 3 Paramètre de l'exposant choisi verbose : bool, default False Paramètre d'affichage Retours: ------- Retourne x élevé à la puissance exposant (default=3) """ if verbose is True: print('version verbeuse') return x ** exposant # In[ ]: ma_puissance(5), ma_puissance(5, verbose=False, exposant=2) # In[ ]: get_ipython().run_line_magic('pinfo', 'ma_puissance') # # Input: entrées interactives / boites de dialogue # In[ ]: nom = input('Entrer votre nom de famille: ') prenom = input('Entrer votre prénom: ') # In[ ]: print("Je m'appelle {} {}.".format(prenom, nom)) # # Questions sur les textes: comment mettre des apostrophes ' et des guillemets " dans un texte? # In[ ]: texte1 = '"Isn\'t," she said.' print(texte1) # In[ ]: texte2 = '''"Isn't," she said.''' print(texte2) # In[ ]: type(9 / 3) # In[ ]: