Difference between revisions of "Python"

From Sinfronteras
Jump to: navigation, search
(Class And Object Variables)
(Data types)
 
(147 intermediate revisions by the same user not shown)
Line 1: Line 1:
Este curso creo que está bueno: https://en.wikibooks.org/wiki/Non-Programmer%27s_Tutorial_for_Python_3
 
  
https://www.linkedin.com/groups/25827/25827-6252617967876530180?midToken=AQGAer8k7UG2aA&trk=eml-b2_anet_digest_of_digests-hero-12-view%7Ediscussion&trkEmail=eml-b2_anet_digest_of_digests-hero-12-view%7Ediscussion-null-6adzns%7Ej11y530y%7Ebq&lipi=urn%3Ali%3Apage%3Aemail_b2_anet_digest_of_digests%3BG9uUYE5oSqCC6IiHvBuPAQ%3D%3D
+
<br />
 +
https://www.python.org/
  
https://www.udemy.com/the-python-mega-course/?utm_source=facebook&utm_medium=udemyads&utm_campaign=NEW-FB-PROS-TECH-Dev-Core-Python-EN-ENG_._ci_692188_._sl_ENG_._vi_TECH_._sd_All_._la_EN_.&utm_term=_._ag_Dev-Core-Python-Affinity-Secondary-Worldwide-_._ci_692188_._._pi_1500516769988382_._gi_all_._ai_18--65_._an_w2JZ7e&k_clickid=06af6ff1-3223-44a3-ac5a-faf35c3045d8_116713439&pmtag=730e4958-3f44-4290-b5bb-1fb0fb62b7d5
+
https://docs.python.org/3/
  
https://openclassrooms.com/courses/apprenez-a-programmer-en-python/les-structures-conditionnelles
 
  
http://www.enlistq.com/10-python-idioms-to-help-you-improve-your-code/
+
<br />
 +
==Online Python Interpreters==
 +
These ones supports many languages:  
  
https://www.linkedin.com/groups/25827/25827-6226729936229666816?midToken=AQGAer8k7UG2aA&trk=eml-b2_anet_digest_of_digests-hero-11-discussion%7Esubject&trkEmail=eml-b2_anet_digest_of_digests-hero-11-discussion%7Esubject-null-6adzns%7Eiy47cgxw%7Eys
+
*https://repl.it/
 +
*https://www.onlinegdb.com
  
https://www.linkedin.com/pulse/python-top-10-programming-languages-year-2017-alok-kumar
 
  
 +
<br />
 +
==Installation==
  
==Qu'est-ce que Python? - Pourquoi Python? - À quoi peut servir Python?==
 
* Python est un langage de programmation interprété, à ne pas confondre avec un langage compilé.
 
  
* Il permet de créer toutes sortes de programmes, comme des jeux, des logiciels, des progiciels, etc.
+
<br />
 +
===Installing python on Ubuntu===
 +
The last version of Python is usually installed this way. It can be verified in many sources: https://phoenixnap.com/kb/how-to-install-python-3-ubuntu
  
* Il est possible d'associer des bibliothèques à Python afin d'étendre ses possibilités.
+
sudo apt update
 +
sudo apt install software-properties-common
 +
sudo add-apt-repository ppa:deadsnakes/ppa
 +
sudo apt update
 +
sudo apt install python3.8
 +
 +
python --version
 +
 
 +
 
 +
<br />
  
* Il est portable, c'est à dire qu'il peut fonctionner sous différents systèmes d'exploitation (Windows, Linux, Mac OS X,…).
+
===[[Python_for_Data_Science#Anaconda|Installing Anaconda]]===
  
==Instalación==
 
Python est pré-installé sur la plupart des distributions Linux. Sinon:
 
  
===Versión instalada===
+
<br />
 +
===Display the installed version===
 
Para ver la versión por defecto:
 
Para ver la versión por defecto:
 
  python --version
 
  python --version
Line 43: Line 54:
 
  >>>
 
  >>>
  
===Cambiar la versión por defecto===
+
 
 +
<br />
 +
===Change the default version===
 
https://linuxconfig.org/how-to-change-from-default-to-alternative-python-version-on-debian-linux
 
https://linuxconfig.org/how-to-change-from-default-to-alternative-python-version-on-debian-linux
  
 +
 +
<br />
 
====Change python version on per user basis====
 
====Change python version on per user basis====
 
To change a python version on per user basis you simply create an alias within user's home directory. Open ~/.bashrc file and add new alias to change your default python executable:
 
To change a python version on per user basis you simply create an alias within user's home directory. Open ~/.bashrc file and add new alias to change your default python executable:
Line 53: Line 68:
 
  . ~/.bashrc
 
  . ~/.bashrc
  
 +
 +
<br />
 
====Change python version system-wide====
 
====Change python version system-wide====
To change python version system-wide we can use '''update-alternatives''' command. Logged in as a root user, first list all available python alternatives:
+
To change python version system-wide we can use '''update-alternatives''' command.
  
 +
Logged in as a root user. First we can list all available python alternatives:
 
  # update-alternatives --list python
 
  # update-alternatives --list python
 
  update-alternatives: error: no alternatives for python
 
  update-alternatives: error: no alternatives for python
  
The above error message means that no python alternatives has been recognized by update-alternatives command. For this reason we need to update our alternatives table and include both python2.7 and python3.5:
+
El comando anterio debería mostrar las alternativas (por ejemplo python2.7 , python3.5) que ya han sido incluidas a través del comando update-alternatives --install. The above error message means that no python alternatives has been recognized by update-alternatives command. For this reason we need to update our alternatives table and include both python2.7 and python3.5:
  
 +
Debemos entonces contruir la tabla de alternativas de la siguiente forma:
 
  # update-alternatives --install /usr/bin/python python /usr/bin/python2.7 1
 
  # update-alternatives --install /usr/bin/python python /usr/bin/python2.7 1
 
  update-alternatives: using /usr/bin/python2.7 to provide /usr/bin/python (python) in auto mode
 
  update-alternatives: using /usr/bin/python2.7 to provide /usr/bin/python (python) in auto mode
Line 66: Line 85:
 
  update-alternatives: using /usr/bin/python3.4 to provide /usr/bin/python (python) in auto mode
 
  update-alternatives: using /usr/bin/python3.4 to provide /usr/bin/python (python) in auto mode
  
The --install option take multiple arguments from which it will be able to create a symbolic link. The last argument specified it priority means, if no manual alternative selection is made the alternative with the highest priority number will be set. In our case we have set a priority 2 for /usr/bin/python3.4 and '''as a result the /usr/bin/python3.5 was set as default python version automatically by update-alternatives command.'''  
+
The --install option take multiple arguments from which it will be able to create a symbolic link. The last argument specified it priority means, if no manual alternative selection is made the alternative with the highest priority number will be set. In our case we have set a priority 2 for /usr/bin/python3.4 and '''as a result the /usr/bin/python3.5 was set as default python version automatically by update-alternatives command.'''
 +
 
 +
Es decir, si queremos que python2.7 sea la versión por defecto podemos ejecutar el comando update-alternatives --intall de la forma mostrada arriba y ajustar el último argumento de forma tal que el mayor valor sea asociado a la versión que queremos por defecto.
 +
 
 +
 
 +
<br />
 +
 
 +
==IDE for Python==
 +
<br />
 +
===PyCharm===
 +
https://www.jetbrains.com/pycharm/
 +
 
 +
 
 +
'''Installation:''' <br />
 +
https://www.jetbrains.com/help/pycharm/installation-guide.html
 +
 
 +
sudo snap install pycharm-community --classic
 +
 
 +
 
 +
<br />
 +
 
 +
===[[Node.js - Express.js#Visual Studio Code|Visual Studio Code]]===
 +
Python in Visual Studio Code
 +
 
 +
https://code.visualstudio.com/docs/languages/python
 +
 
 +
 
 +
<br />
 +
===[[Python_for_Data_Science#Jupyter|Jupyter]]===
 +
.
 +
 
  
 +
<br />
 +
===Atom===
 +
https://flight-manual.atom.io/getting-started/sections/installing-atom/
  
===Ubuntu===
 
apt-get install python3.x
 
  
Si se descarga:
+
<br />
* Décompressez l'archive en tapant : tar -xzf Python-3.4.0.tar.bz2 (cette commande est bien entendu à adapter suivant la version et le type de compression).
+
===Python on eclipse===
* Attendez quelques instants que la décompression se termine, puis rendez-vous dans le dossier qui vient d'être créé dans le répertoire courant (Python-3.4.0 dans mon cas).
+
Para utilizar Python en Eclipse debemos instalar PyDev:
* Exécutez le script configure en tapant ./configure dans la console.
 
* Une fois que la configuration s'est déroulée, il n'y a plus qu'à compiler en tapant make puis make install en tant que super-utilisateur.
 
  
==Lancer Python==
+
Help > Eclipse Marketplace
Lorsque vous l'avez installé sur votre système, Python a créé un lien vers l'interpréteur sous la forme python3.X (le X étant le numéro de la version installée).
+
Find: PyDev
  
Si, par exemple, vous avez installé Python 3.4, vous pouvez y accéder grâce à la commande
 
  
python3.4
+
<br />
 +
===Sublime Text===
 +
https://www.sublimetext.com/
  
==Premiers pas avec l'interpréteur de commandes Python==
+
https://en.wikipedia.org/wiki/Sublime_Text
  
===Opérations courantes===
+
Sublime Text is a proprietary cross-platform source code editor '''with a Python application programming interface (API)'''. It natively supports many programming languages and markup languages, and functions can be added by users with plugins.
  
>>> 3 + 4
 
7
 
  
>>> 9.5 + 2
+
<br />
11.5
+
====Installation====
 +
https://linuxconfig.org/how-to-install-sublime-text-on-ubuntu-18-04-bionic-beaver-linux
  
  >>> 3.11 + 2.08
+
  wget -qO - https://download.sublimetext.com/sublimehq-pub.gpg | sudo apt-key add -
  5.1899999999999995
+
  sudo apt-add-repository "deb https://download.sublimetext.com/ apt/stable/"
  
==Les types de données==
+
sudo apt install sublime-text
  
==='''int''': Les nombres entiers===
 
Le type entier se nomme int en Python (qui correspond à l'anglais « integer », c'est-à-dire entier). La forme d'un entier est un nombre sans virgule.
 
  
==='''float''': Les nombres flottants===
+
<br />
Les flottants sont les nombres à virgule. Ils se nomment float en Python (ce qui signifie « flottant » en anglais). La syntaxe d'un nombre flottant est celle d'un nombre à virgule (n'oubliez pas de remplacer la virgule par un point). Si ce nombre n'a pas de partie flottante mais que vous voulez qu'il soit considéré par le système comme un flottant, vous pouvez lui ajouter une partie flottante de 0 (exemple 52.0).
+
====Keyboard shortcut to comment lines in Sublime Text 3====
 +
http://stackoverflow.com/questions/17742781/keyboard-shortcut-to-comment-lines-in-sublime-text-3
  
===Les chaînes de caractères===
+
https://forum.sublimetext.com/t/st3-3012-toggle-comments-broken/8930/8
  
On peut écrire une chaîne de caractères de différentes façons :
+
As a workaround, go to Preferences->Key Bindings - User and add these keybindings (if you're using Linux):
  
    entre guillemets ("ceci est une chaîne de caractères") ;
+
{ "keys": ["ctrl+7"], "command": "toggle_comment", "args": { "block": false } },
 +
{ "keys": ["ctrl+shift+7"], "command": "toggle_comment", "args": { "block": true } }
  
    entre apostrophes ('ceci est une chaîne de caractères') ;
 
  
    entre triples guillemets ("""ceci est une chaîne de caractères""").
+
<br />
 +
====Indentation====
 +
https://stackoverflow.com/questions/9474090/how-do-i-force-sublime-text-to-indent-two-spaces-per-tab
  
    entre triples apostrophes ('''ceci est une chaîne de caractères''').
+
If you want it for all files, go to Preferences -> Settings - Default/User. But as several comments below indicate, Syntax Specific settings can limit it to just the languages you choose.
  
Si vous utilisez les délimiteurs simples (le guillemet ou l'apostrophe) pour encadrer une chaîne de caractères, il faut échapper les apostrophes se trouvant au cœur de la chaîne. On insère ainsi un caractère anti-slash « \ » avant les apostrophes contenues dans le message.
+
To limit this configuration to Ruby files, first open up a Ruby file in the editor, and then go to Preferences -> Settings -> More -> Syntax Specific -> User. This should open a settings window named Ruby.sublime-settings
  
chaine = 'J\'aime le Python!'
+
Save these settings:
  
Le caractère d'échappement « \ » est utilisé pour créer d'autres signes très utiles. Ainsi, « \n » symbolise un saut de ligne ("essai\nsur\nplusieurs\nlignes"). Pour écrire un véritable anti-slash dans une chaîne, il faut l'échapper lui-même (et donc écrire « \\ »).
+
<syntaxhighlight lang="php">
 +
{
 +
  "tab_size": 2,
 +
  "translate_tabs_to_spaces": true,
 +
  "detect_indentation": false
 +
}
 +
</syntaxhighlight>
  
L'interpréteur affiche les sauts de lignes comme on les saisit, c'est-à-dire sous forme de « \n ». Nous verrons dans la partie suivante comment afficher réellement ces chaînes de caractères et pourquoi l'interpréteur ne les affiche pas comme il le devrait.
 
  
Utiliser les triples guillemets pour encadrer une chaîne de caractères dispense d'échapper les guillemets et apostrophes, et permet d'écrire plusieurs lignes sans symboliser les retours à la ligne au moyen de « \n ».
+
<br />
 +
====Crear un proyecto en Sublime Text====
  
>>> chaine3 = """Ceci est un nouvel
+
#Abrimos una nueva ventana: File > New Window
... essai sur plusieurs
+
#Add folder to project
... lignes"""
+
#Save project as: es apropiado guardarlo en el mismo directorio en donde fue creado el proyecto.
>>>
 
  
Vous pouvez utiliser, à la place des trois guillemets, trois apostrophes qui jouent exactement le même rôle.
+
Esto creará dos archivos:
  
===Les booléens===
+
*nombre-111.sublime-project
>>> a = 0
+
*nombre-111.sublime-workspace : Este es el que debemos abrir para ingresar al proyecto.
>>> a == 5
 
False
 
>>> a > -8
 
True
 
>>> a != 33.19
 
True
 
>>>
 
  
Les variables de ce type ne peuvent prendre comme valeur que True ou False.
 
  
>>> age = 21
+
<br />
>>> majeur = False
 
>>> if age >= 18:
 
>>>    majeur = True
 
>>>
 
  
===Les mots-clés and, or et not===
+
==Using Python==
if a>=2 and a<=8:
 
    print("a est dans l'intervalle.")
 
else:
 
    print("a n'est pas dans l'intervalle.")
 
  
  
if a<2 or a>8:
+
<br />
    print("a n'est pas dans l'intervalle.")
+
===Python Shell===
else:
+
From the terminal, you can start the Python Shell/Interpreter (Also know as Python Interactive Shell) using the command:
    print("a est dans l'intervalle.")
 
  
 +
python3.x
  
Enfin, il existe le mot clé '''not''' qui « inverse » un prédicat. Le prédicat '''not a==5''' équivaut donc à '''a!=5'''.
 
  
'''not''' rend la syntaxe plus claire. Pour cet exemple, j'ajoute à la liste un nouveau mot clé, '''is''', qui teste l'égalité non pas des valeurs de deux variables, mais de leurs références. Je ne vais pas rentrer dans le détail de ce mécanisme avant longtemps. Il vous suffit de savoir que pour les entiers, les flottants et les booléens, c'est strictement la même chose. Mais pour tester une égalité entre variables dont le type est plus complexe, préférez l'opérateur « == ». Revenons à cette démonstration :
+
<br />
 +
====Premiers pas avec l interpreteur de commandes Python====
  
>>> majeur = False
 
>>> if majeur is not True:
 
...    print("Vous n'êtes pas encore majeur.")
 
...
 
Vous n'êtes pas encore majeur.
 
>>>
 
  
==Les opérateurs==
+
<br />
===« + » « - » « / »===
+
=====Operations courantes=====
  
 
  >>> 3 + 4
 
  >>> 3 + 4
 
  7
 
  7
 
>>> -2 + 93
 
91
 
  
 
  >>> 9.5 + 2
 
  >>> 9.5 + 2
Line 192: Line 221:
 
  5.1899999999999995
 
  5.1899999999999995
  
>>> 10 / 5
 
2.0
 
  
>>> 10 / 3
+
<br />
3.3333333333333335
+
===Writing and Running a Python code===
 +
You can use your favorite Text Editor or IDE to write your Python code:
  
===« // » permet d'obtenir la partie entière d'une division (cociente)===
+
example.py
>>> 10 // 3
+
<syntaxhighlight lang="python">
3
+
#!/usr/bin/python3.6
>>> 10 // 4
 
2
 
  
===« % », que l'on appelle le « modulo », permet de connaître le reste de la division (resto)===
+
c=input("Ingrese un caracter: ")
>>> 10%3
+
e=int(input("Entrez un entier: "))
1
 
  
===« += » « -= » « *= » « /= »===
+
for i in range(1,e+1):
variable = variable + 1  
+
for j in range(1,i+1):
 +
print(c,end="")
 +
print()
 +
</syntaxhighlight>
  
La operación anterior puede resumirse utilizando el operador +=:
 
  
variable += 1
+
*If we use the line '''''#!/usr/bin/python3.6''''' to indicate the path to the Python Interpreter, then we can then run our code as a Executable file this way:
  
Les opérateurs -=, *= et /= existent également, bien qu'ils soient moins utilisés.
+
./example.py
  
===Potencia===
 
>>> 9**(1/2)
 
3.0
 
  
>>> pow(3,2)
+
*However, the most common way is not including '''''#!/usr/bin/python3.6''''' and calling the Python Interpreter through the '''''python''''' command:
9
 
  
===Valor absoluto===
+
  python3 example.py
  >>> abs(-3.0)
 
3.0
 
  
===Complejos===
 
>>> complex(2,3)
 
(2+3j)
 
  
>>> complex(2,3)*complex(3,4)
+
*Of course, you can also run a Python program through a button on a IDE Graphical Interface.
(-6+17j)
 
  
>>> a=complex(3,5)
 
>>> a.real
 
3.0
 
>>> a.imag
 
5.0
 
  
===Maximo y minimo===
+
<br />
>>> max(3,45,6,7)
 
45
 
  
>>> min(32,23,2,13,4.3)
+
==pip and virtualenv==
2
+
https://pypi.org/project/pip/
  
===Redondeo===
+
https://pip.pypa.io/en/stable/installation/
>>> round(34.5)
 
35.0
 
  
>>> round(35.345,1)
 
35.3
 
  
===La clase math===
+
To display the version of pip:
>>> import math
+
<syntaxhighlight lang="shell">
 +
python3.11 -m pip --version
 +
</syntaxhighlight>
  
====Raiz cuadrada====
 
>>> math.sqrt(2)
 
1.4142135623730951
 
  
====Factorial====
+
Upgrade pip:
>>> math.factorial(5)
+
<syntaxhighlight lang="shell">
120
+
python3 -m pip install --upgrade pip
 +
</syntaxhighlight>
  
====PI====
 
>>> math.pi
 
3.1415926535897931
 
  
====Funciones trigonométricas====
+
<syntaxhighlight lang="shell">
>>> math.sin(math.pi)
+
pip install librarie
1.2246063538223773e-16
+
</syntaxhighlight>
  
====Logaritmos====
 
>>> math.log(11)
 
2.3978952727983707
 
  
===Permutation===
+
'''Para especificar la versión de python a la cual será instalada la libreria:'''
Python propose un moyen simple de permuter deux variables (échanger leur valeur). Dans d'autres langages, il est nécessaire de passer par une troisième variable qui retient l'une des deux valeurs… ici c'est bien plus simple :
+
<syntaxhighlight lang="shell">
 +
python3 -m pip install pandas
 +
</syntaxhighlight>
 +
En este caso, cuando usemos python3 «pandas» estará disponible, pero no necesariamente para otras versiones de python
  
>>> a = 5
 
>>> b = 32
 
>>> a,b = b,a # permutation
 
>>> a
 
32
 
>>> b
 
5
 
>>>
 
  
===Asignar un mismo valor a varias variables===
+
'''To list all pakages installed :'''
On peut aussi affecter assez simplement une même valeur à plusieurs variables :
+
<syntaxhighlight lang="shell">
 +
pip list
 +
python3.11 -m pip list
 +
</syntaxhighlight>
  
>>> x = y = 3
 
>>> x
 
3
 
>>> y
 
3
 
  
===Couper une instruction Python, pour l'écrire sur deux lignes ou plus===
+
'''How can I install packages using pip according to the requirements.txt'''
>>> 1 + 4 - 3 * 19 + 33 - 45 * 2 + (8 - 3) \
+
<syntaxhighlight lang="shell">
... -6 + 23.5
+
pip install -r requirements.txt
-86.5
+
python3.8 -m pip install -r requirements.txt
>>>
+
</syntaxhighlight>
  
===Les opérateurs de comparaison===
 
'''<''' Strictement inférieur à
 
'''>''' Strictement supérieur à
 
'''<=''' Inférieur ou égal à
 
'''>=''' Supérieur ou égal à
 
'''==''' Égal à
 
'''!=''' Différent de
 
  
==Funciones más utilizadas==
+
'''Puede ser necesario instalar venv para la version de python deseada:'''
Une fonction exécute un certain nombre d'instructions déjà enregistrées. En gros, c'est comme si vous enregistriez un groupe d'instructions pour faire une action précise et que vous lui donniez un nom. Vous n'avez plus ensuite qu'à appeler cette fonction par son nom autant de fois que nécessaire.
+
<syntaxhighlight lang="shell">
 +
sudo apt install python3.11-venv
 +
</syntaxhighlight>
  
La plupart des fonctions ont besoin d'au moins un paramètre pour travailler sur une donnée ; ces paramètres sont des informations que vous passez à la fonction afin qu'elle travaille dessus.
 
  
Les fonctions s'utilisent en respectant la syntaxe suivante :
+
'''Crear un virtualenv:'''
  nom_de_la_fonction(parametre_1,parametre_2,…,parametre_n)
+
<syntaxhighlight lang="shell">
 +
python3 -m venv myenv # This will install a local copy of Python and pip into a directory called myprojectenv
 +
</syntaxhighlight>
  
===La fonction « type »===
 
Une des grandes puissances de Python est qu'il comprend automatiquement de quel type est une variable et cela lors de son affectation.  Mais il est pratique de pouvoir savoir de quel type est une variable.
 
  
La syntaxe de cette fonction est simple :
+
'''Activar el virtualenv:'''
type(nom_de_la_variable)
+
<syntaxhighlight lang="shell">
 +
source myenv/bin/activate
 +
</syntaxhighlight>
  
La fonction renvoie le type de la variable passée en paramètre.
 
>>> type(3)
 
<class 'int'>
 
  
===print - input===
+
'''Para especificar la versión de Python que del virtualenv:''' https://stackoverflow.com/questions/45293436/how-to-specify-python-version-used-to-create-virtual-environment
<syntaxhighlight lang="python">
+
<syntaxhighlight lang="shell">
>>> a=3
+
virtualenv -p python3.8 myproject_env    # Creates a new default python3.8 (python3.8 must be a valid command i.e found in the PATH)  
>>> b=4
 
// Las variables int deben ser delimitadas entre comas:
 
>>> print("a =",a,"et b =",b)
 
a = 6 et b = 4
 
 
</syntaxhighlight>
 
</syntaxhighlight>
  
<syntaxhighlight lang="python">
+
 
>>> a='3'
+
'''Para salir del virtualenv:'''
>>> b='4'
+
<syntaxhighlight lang="shell">
// Las variables str pueden ser delimitadas entre comas o entre +:
+
(myproject_env)$ deactivate
>>> print("a = "+a+" et b = "+b)
 
a = 6 et b = 4
 
 
</syntaxhighlight>
 
</syntaxhighlight>
  
<syntaxhighlight lang="python">
 
>>> print("Hello World !")
 
Hello World !
 
</syntaxhighlight>
 
  
 +
<br />
 +
 +
==Keep a python script running on a remote server==
 +
 +
 +
<br />
 +
===Screen===
 +
 +
Create a screen:
 +
screen -S bot
 +
 +
Disconnect: Ctrl+A+D
 +
 +
Reconnecting:
 +
screen -r bot
 +
 +
 +
List screens:
 +
screen -ls
 +
 +
 +
Kill all sessions
 +
killall screen
 +
 +
 +
Kill a specific session
 +
screen -S bot -X quit
 +
 +
 +
Creating the screen without attaching to it
 +
screen -dmS bot
 +
 +
 +
Activating the venv on the screen previously created without attaching to it
 +
screen -S bot -p 0 -X stuff $'source .venv/bin/activate\n'
 +
 +
 +
To create the screen and activate the venv at the same time without attaching to it:
 +
screen -dmS bot bash -c 'source .venv/bin/activate && exec sh'    # This is working but the prompt is sh so not very good. (&& can be replaced by ;)
 +
screen -dmS bot bash -c 'source .venv/bin/activate && exec bash'  # This is not activating the venv
 +
 +
 +
<br />
 +
==Data types==
 +
https://docs.python.org/2.0/ref/types.html
 +
 +
https://upload.wikimedia.org/wikipedia/commons/1/10/Python_3._The_standard_type_hierarchy.png
 +
 +
In this source you can find a very good documentation about Python Data Types and the most important Operations and Methods for each Data Type:
 +
https://www.w3schools.com/python/python_datatypes.asp
 +
 +
{| class="wikitable"
 +
|+
 +
!
 +
!
 +
!
 +
!
 +
|-
 +
|'''None'''
 +
|
 +
|
 +
|
 +
|-
 +
|'''Ellipsis'''
 +
|
 +
|
 +
|
 +
|-
 +
|'''Numbers'''
 +
|'''Integers'''
 +
|'''Plain integers'''
 +
|
 +
|-
 +
|
 +
|
 +
|'''Long integers'''
 +
|
 +
|-
 +
|
 +
|'''Floating point numbers'''
 +
|
 +
|
 +
|-
 +
|
 +
|'''Complex numbers'''
 +
|
 +
|
 +
|-
 +
|'''Sequences'''
 +
|'''Immutable sequences'''
 +
|'''Strings'''
 +
|
 +
|-
 +
|
 +
|
 +
|'''Unicode'''
 +
|
 +
|-
 +
|
 +
|
 +
|'''Tuples'''
 +
|
 +
|-
 +
|
 +
|'''Mutable sequences'''
 +
|'''Lists'''
 +
|
 +
|-
 +
|'''Mappings'''
 +
|'''Dictionaries'''
 +
|
 +
|
 +
|-
 +
|'''Callable types'''
 +
|'''User-defined functions'''
 +
|
 +
|
 +
|-
 +
|
 +
|'''User-defined methods'''
 +
|
 +
|
 +
|-
 +
|
 +
|'''Built-in functions'''
 +
|
 +
|
 +
|-
 +
|
 +
|'''Built-in methods'''
 +
|
 +
|
 +
|-
 +
|
 +
|'''Classes'''
 +
|
 +
|
 +
|-
 +
|
 +
|'''Class instances'''
 +
|
 +
|
 +
|-
 +
|'''Modules'''
 +
|
 +
|
 +
|
 +
|-
 +
|'''Classes'''
 +
|
 +
|
 +
|
 +
|-
 +
|'''Class instances'''
 +
|
 +
|
 +
|
 +
|-
 +
|'''Files'''
 +
|
 +
|
 +
|
 +
|-
 +
|'''Internal types'''
 +
|'''Code objects'''
 +
|
 +
|
 +
|-
 +
|
 +
|'''Frame objects'''
 +
|
 +
|
 +
|-
 +
|
 +
|'''Traceback objects'''
 +
|
 +
|
 +
|-
 +
|
 +
|'''Slice objects'''
 +
|
 +
|
 +
|}
 +
 +
 +
'''Getting the Data Type:''' You can get the data type of any object by using the type() function:
 +
print(type(x))
 +
{| class="wikitable"
 +
|+Source: https://www.w3schools.com/python/python_datatypes.asp
 +
! colspan="2" |
 +
!Type/Class
 +
!Description
 +
!Example
 +
!Setting the Specific Data Type
 +
!Operations/Functions/Methods
 +
|-
 +
| colspan="2" rowspan="3" |'''Numeric Types'''
 +
|<code>int</code>
 +
|Int, or integer, is a whole number, positive or negative, without decimals, of unlimited length.
 +
|x = 20
 +
|x = int(20)
 +
| rowspan="3" |https://www.w3schools.com/python/python_numbers.asp
 +
|-
 +
|<code>float</code>
 +
|Float, or "floating point number" is a number, positive or negative, containing one or more decimals.
 +
|x = 20.5
 +
|x = float(20.5)
 +
|-
 +
|<code>complex</code>
 +
|Complex numbers are written with a "j" as the imaginary part
 +
|x = 1j
 +
|x = complex(1j)
 +
|-
 +
| colspan="2" |'''Text Type'''
 +
|<code>str</code>
 +
|'''Strings are Arrays:''' Like many other popular programming languages, strings in Python are arrays of bytes representing unicode characters. However, Python does not have a character data type, a single character is simply a string with a length of 1.
 +
|x = "Hello World"
 +
|x = str("Hello World")
 +
|https://www.w3schools.com/python/python_strings.asp
 +
|-
 +
| colspan="2" |'''Boolean Type'''
 +
|<code>bool</code>
 +
|Booleans represent one of two values: <code>True</code> or <code>False</code>.
 +
|x = True
 +
|x = bool(5)
 +
|https://www.w3schools.com/python/python_booleans.asp
 +
|-
 +
| colspan="2" rowspan="3" |'''Binary Types'''
 +
|<code>bytes</code>
 +
|
 +
|x = b"Hello"
 +
|x = bytes(5)
 +
|
 +
|-
 +
|<code>bytearray</code>
 +
|
 +
|x = bytearray(5)
 +
|x = bytearray(5)
 +
|
 +
|-
 +
|<code>memoryview</code>
 +
|
 +
|x = memoryview(bytes(5))
 +
|x = memoryview(bytes(5))
 +
|
 +
|-
 +
| rowspan="7" |'''Python Collections (Arrays)'''
 +
| rowspan="4" |'''Sequence Types'''
 +
|<code>list</code>
 +
|A list is a collection which is ordered and changeable.
 +
|x = ["apple", "banana", "cherry"]
 +
|x = list(("apple", "banana", "cherry"))
 +
|https://www.w3schools.com/python/python_lists.asp
 +
 +
 +
 +
'''Nice way to create a list:'''<syntaxhighlight lang="python3">
 +
lista = [x**2 for x in range(12) if x%3 == 0]
 +
print(lista)
 +
# Output:
 +
[0, 9, 36, 81]
 +
</syntaxhighlight><br />
 +
|-
 +
|<code>tuple</code>
 +
|A tuple is a collection which is ordered and '''unchangeable'''.
 +
|x = ("apple", "banana", "cherry")
 +
|x = tuple(("apple", "banana", "cherry"))
 +
|https://www.w3schools.com/python/python_tuples.asp
 +
|-
 +
|<code>Array</code>
 +
|Python does not have built-in support for Arrays. You have to import it from a Library:<br />
 +
<code>from numpy import array</code>
 +
 +
<code>x = array([3, 6, 9, 12])</code>
 +
 +
 +
There are some differences between Array and List: https://medium.com/backticks-tildes/list-vs-array-python-data-type-40ac4f294551
 +
 +
Lists are containers for elements having differing data types but arrays are used as containers for elements of the same data type.
 +
 +
Arrays are specially optimised for arithmetic computations, Ex:
 +
 +
<code>x = array([3, 6, 9, 12])</code>
 +
 +
<code>divided_x = x/2</code>  # This would return an error if using List
 +
 +
<code>print(divided_x)</code>
 +
 +
[1.5 3.  4.5 6. ]
 +
|
 +
|
 +
|[[Python_for_Data_Science#Arrays]]
 +
|-
 +
|<code>range</code>
 +
|
 +
|x = range(6)
 +
|x = range(6)
 +
|
 +
|-
 +
|'''Mapping Type'''
 +
|<code>dict</code>
 +
|A dictionary is a collection which is unordered, changeable and indexed. In Python dictionaries are written with curly brackets, and they have keys and values.
 +
|x = {"name" : "John", "age" : 36}
 +
|x = dict(name="John", age=36)
 +
|https://www.w3schools.com/python/python_dictionaries.asp
 +
|-
 +
| rowspan="2" |'''Set Types'''
 +
|<code>set</code>
 +
|A set is a collection which is unordered and unindexed.
 +
|x = {"apple", "banana", "cherry"}
 +
|x = set(("apple", "banana", "cherry"))
 +
|https://www.w3schools.com/python/python_sets.asp
 +
|-
 +
|<code>frozenset</code>
 +
|
 +
|x = frozenset({"apple", "banana", "cherry"})
 +
|x = frozenset(("apple", "banana", "cherry"))
 +
|
 +
|}
 +
<br />
 +
 +
 +
<br />
 +
 +
==Operators==
 +
 +
{{#lst:Java|operators}}
 +
 +
 +
<br />
 +
==Control flow statements==
 +
 +
 +
<br />
 +
===If statements===
 +
https://www.w3schools.com/python/python_conditions.asp
  
'''input'''
 
  
 
<syntaxhighlight lang="python">
 
<syntaxhighlight lang="python">
name = input("What's your name? ")
+
a = 200
print("Nice to meet you " + name + "!")
+
b = 33
age = input("Your age? ")
+
if b > a:
print("So, you are already " + age + " years old, " + name + "!")
+
    print("b is greater than a")
 +
elif a == b:
 +
    print("a and b are equal")
 +
else:
 +
    print("a is greater than b")
 
</syntaxhighlight>
 
</syntaxhighlight>
  
  
La función input asigna por defecto una variable de tipo '''str'''. Si queremos que la variable sea tipo '''int''' o '''list''':
+
'''Short Hand If:'''
 
 
 
<syntaxhighlight lang="python">
 
<syntaxhighlight lang="python">
>>> population = int(input("Population of Toronto? "))
+
if a > b: print("a is greater than b")  
Population of Toronto? 2615069
 
>>> print(population, type(population))
 
2615069 <class 'int'>
 
 
</syntaxhighlight>
 
</syntaxhighlight>
  
 +
 +
'''One line if else statement, with 3 conditions:'''
 
<syntaxhighlight lang="python">
 
<syntaxhighlight lang="python">
>>> cities_canada = eval(input("Largest cities in Canada: "))
+
print("A") if a > b else print("=") if a == b else print("B")  
Largest cities in Canada: ["Toronto", "Montreal", "Calgara", "Ottawa"]
 
>>> print(cities_canada, type(cities_canada))
 
['Toronto', 'Montreal', 'Calgara', 'Ottawa'] <class 'list'>
 
 
</syntaxhighlight>
 
</syntaxhighlight>
  
====Input and Output funtions====
 
Esta página creo que no está actualizada para python 3, pero está bien organizada: https://en.wikibooks.org/wiki/Python_Programming/Input_and_Output#input.28.29
 
  
==Les structures conditionnelles==
+
<br />
 +
===For Loops===
 +
https://www.w3schools.com/python/python_for_loops.asp
 +
 
  
===IF / ELSE / ELIF===
+
'''Print each fruit in a fruit list:'''
>>> a = 5
+
<syntaxhighlight lang="python">
>>> if a > 0:
+
fruits = ["apple", "banana", "cherry"]
...    print("a est supérieur à 0.") # Si no se coloca la identation dentro del if, se genera un error: IndentationError: expected an indented block
+
for fruit in fruits:
...
+
    print(fruit)
a est supérieur à 0.
 
  
 +
# Output:
 +
apple
 +
banana
 +
cherry
 +
</syntaxhighlight>
  
>>> age = 21
 
>>> if age >= 18:
 
...    print("Vous êtes majeur.")
 
... else:
 
...    print("Vous êtes mineur.")
 
...
 
Vous êtes majeur.
 
  
 +
<syntaxhighlight lang="python">
 +
fruits = ["apple", "banana", "cherry"]
 +
for fruit_no, fruit in enumerate(fruits):
 +
    print(fruit_no, fruit)
  
>>> a=5
+
# Output:
>>> if a > 0: # Positif
+
0 apple
...      print("a est positif.")
+
1 banana
... elif a < 0:
+
2 cherry
...      print("a est négatif.")
+
</syntaxhighlight>
... else:
 
...      print("a est nul.")
 
...
 
>>> a est positif.
 
  
==Definir una función==
 
  
<source lang=python>
+
'''Looping Through a String:'''
def hello():
+
<syntaxhighlight lang="python">
    print("Hello")
+
for x in "banana":
 +
    print(x)
 +
</syntaxhighlight>
  
def area(width, height):
 
    return width * height
 
  
def print_welcome(name):
+
'''The break Statement:'''
    print("Welcome", name)
+
<syntaxhighlight lang="python">
 +
fruits = ["apple", "banana", "cherry"]
 +
for x in fruits:
 +
    print(x)
 +
    if x == "banana":
 +
          break
 +
</syntaxhighlight>
  
hello()
 
hello()
 
  
print_welcome("Fred")
+
'''The continue Statement:''' With the continue statement we can stop the current iteration of the loop, and continue with the next:
w = 4
+
<syntaxhighlight lang="python">
h = 5
+
fruits = ["apple", "banana", "cherry"]
print("width =", w, " height =", h, " area =", area(w, h))
+
for x in fruits:
</source>
+
    if x == "banana":
 +
          continue
 +
    print(x)
 +
</syntaxhighlight>
  
  
<source lang=python>
+
'''The range() Function:'''
def factorial():
+
The range() function returns a sequence of numbers, starting from 0 by default, and increments by 1 (by default), and ends at a specified number.
        n=int(input("Entrez un entier positif: "))
+
<syntaxhighlight lang="python">
        fac=1
+
for x in range(6):
        for i in range(n,1,-1):
+
    print(x)
                fac=fac*i
+
</syntaxhighlight>
        return(fac)
+
Note that range(6) is not the values of 0 to 6, but the values 0 to 5.
  
print(factorial())
 
</source>
 
  
==Exceptions==
+
'''The range() Function:'''
 +
The range() function returns a sequence of numbers, starting from 0 by default, and increments by 1 (by default), and ends at a specified number.
 +
<syntaxhighlight lang="python">
 +
for x in range(2, 30, 3):
 +
    print(x)
 +
</syntaxhighlight>
  
<source language=python>
 
while True:
 
    try:
 
        x = int(raw_input("Please enter a number: "))
 
        break
 
    except ValueError:
 
        print "Oops!  That was no valid number.  Try again..."
 
</source>
 
  
==OOP with Python==
+
<br />
https://python.swaroopch.com/oop.html
 
  
===Object Oriented Programming===
+
===While Loops===
 +
https://www.w3schools.com/python/python_while_loops.asp
  
In all the programs we wrote till now, we have designed our program around functions i.e. blocks of statements which manipulate data. This is called the procedure-oriented way of programming. There is another way of organizing your program which is to combine data and functionality and wrap it inside something called an object. This is called the object oriented programming paradigm.
 
  
'''Classes and objects''' are the two main aspects of object oriented programming. '''A class''' creates a new type where '''objects''' are instances of the class. An analogy is that you can have variables of type int which translates to saying that variables that store integers are variables which are instances (objects) of the int class.
+
<syntaxhighlight lang="python">
 +
i = 1
 +
while i < 6:
 +
    print(i)
 +
    i += 1
 +
</syntaxhighlight>
  
Note for Static Language Programmers:
 
  
Note that even integers are treated as objects (of the int class). This is unlike C++ and Java (before version 1.5) where integers are primitive native types.
+
'''The break Statement:'''
 +
<syntaxhighlight lang="python">
 +
i = 1
 +
while i < 6:
 +
    print(i)
 +
    if i == 3:
 +
          break
 +
    i += 1  
 +
</syntaxhighlight>
  
See help(int) for more details on the class.
 
  
'''Fields:'''
+
'''The continue Statement:''' With the continue statement we can stop the current iteration, and continue with the next:
 +
<syntaxhighlight lang="python">
 +
i = 0
 +
while i < 6:
 +
    i += 1
 +
    if i == 3:
 +
          continue
 +
    print(i)
 +
</syntaxhighlight>
  
Variables that belong to an object or class are referred to as fields.
 
  
'''Methods:'''
+
'''The else Statement:''' With the else statement we can run a block of code once when the condition no longer is true:
 +
<syntaxhighlight lang="python">
 +
i = 1
 +
while i < 6:
 +
  print(i)
 +
  i += 1
 +
else:
 +
  print("i is no longer less than 6")
 +
</syntaxhighlight>
  
Objects can also have functionality by using functions that belong to a class. Such functions are called methods of the class.
 
  
'''Attributes:'''
+
<br />
 +
==Input and Output==
 +
Input and Output funtions:  
 +
Esta página creo que no está actualizada para python 3, pero está bien organizada: https://en.wikibooks.org/wiki/Python_Programming/Input_and_Output#input.28.29
  
the fields and methods can be referred to as the '''attributes''' of that class.
 
  
'''Instance variables and class variables:'''
+
<br />
 +
===input===
 +
<syntaxhighlight lang="python">
 +
name = input("What's your name? ")
 +
print("Nice to meet you " + name + "!")
 +
age = input("Your age? ")
 +
print("So, you are already " + age + " years old, " + name + "!")
 +
</syntaxhighlight>
  
Fields are of two types - they can belong to each instance/object of the class or they can belong to the class itself. They are called instance variables and class variables respectively.
 
  
===The ''self''===
+
La función input asigna por defecto una variable de tipo '''str'''. Si queremos que la variable sea tipo '''int''' o '''list''':
Class methods have only one specific difference from ordinary functions - they must have an extra first name that has to be added to the beginning of the parameter list, but you do not give a value for this parameter when you call the method, Python will provide it. This particular variable refers to the object itself, and by convention, it is given the name self.
 
  
Say you have a class called MyClass and an instance of this class called myobject. When you call a method of this object as myobject.method(arg1, arg2), this is automatically converted by Python into MyClass.method(myobject, arg1, arg2) - this is all the special self is about.
+
<syntaxhighlight lang="python">
 +
>>> population = int(input("Population of Toronto? "))
 +
Population of Toronto? 2615069
 +
>>> print(population, type(population))
 +
2615069 <class 'int'>
 +
</syntaxhighlight>
  
This also means that if you have a method which takes no arguments, then you still have to have one argument - the self.
+
<syntaxhighlight lang="python">
 +
>>> cities_canada = eval(input("Largest cities in Canada: "))
 +
Largest cities in Canada: ["Toronto", "Montreal", "Calgara", "Ottawa"]
 +
>>> print(cities_canada, type(cities_canada))
 +
['Toronto', 'Montreal', 'Calgara', 'Ottawa'] <class 'list'>
 +
</syntaxhighlight>
  
<source language=python>
 
class Person:
 
    def say_hi(self):
 
        print('Hello, how are you?')
 
  
p = Person()
+
<br />
p.say_hi()
+
===Output===
# The previous 2 lines can also be written as
 
# Person().say_hi()
 
</source>
 
  
===The __init__ method===
 
  
There are many method names which have special significance in Python classes. We will see the significance of the __init__ method now.
+
<br />
 +
====print====
 +
<blockquote>
 +
https://docs.python.org/3/tutorial/inputoutput.html
  
The __init__ method is run as soon as an object of a class is instantiated. The method is useful to do any initialization you want to do with your object. Notice the double underscores both at the beginning and at the end of the name.
+
The '''''print()''''' function prints the specified message to the screen, or other standard output device:
  
Example (save as oop_init.py):
+
<syntaxhighlight lang="python">
 +
print("Hello World")
 +
</syntaxhighlight>
  
<source language=python>
 
class Person:
 
    def __init__(self, name):
 
        self.name = name
 
  
    def say_hi(self):
+
'''The full syntax of print() is:'''
        print('Hello, my name is', self.name)
+
<syntaxhighlight lang="python">
 +
print(*objects, sep=' ', end='\n', file=sys.stdout, flush=False)
 +
</syntaxhighlight>
  
p = Person('Swaroop')
 
p.say_hi()
 
# The previous 2 lines can also be written as
 
# Person('Swaroop').say_hi()
 
</source>
 
  
Output:
+
'''Print more than one object:'''
$ python oop_init.py
+
<syntaxhighlight lang="python">
Hello, my name is Swaroop
+
a = 5
 +
b = a
  
===Class And Object Variables===
+
print('a =', a, '= b')
 +
</syntaxhighlight>
  
We have already discussed the functionality part of classes and objects (i.e. methods), now let us learn about the data part. The data part, i.e. fields, are nothing but ordinary variables that are bound to the namespaces of the classes and objects. This means that these names are valid within the context of these classes and objects only. That's why they are called name spaces.
 
  
There are two types of '''fields''' - '''class variables''' and '''object variables''' which are classified depending on whether the class or the object owns the variables respectively.
+
'''print() with separator and end parameters:'''
  
'''Public or private members:'''
+
<syntaxhighlight lang="python">
 +
a = 5
 +
print("a =", a, sep='00000', end='\n\n\n')
 +
print("a =", a, sep='0', end='')
 +
</syntaxhighlight>
  
All class members are public. One exception: If you use data members with names using the double underscore prefix such as __privatevar, Python uses name-mangling to effectively make it a private variable.
 
  
Thus, the convention followed is that any variable that is to be used only within the class or object should begin with an underscore and all other names are public and can be used by other classes/objects. Remember that this is only a convention and is not enforced by Python (except for the double underscore prefix).
+
'''Print a tuple:'''
 +
<syntaxhighlight lang="python">
 +
x = ("apple", "banana", "cherry")
 +
print(x)  
 +
</syntaxhighlight>
 +
</blockquote>
  
'''Class variables''' are shared, they can be accessed by all instances of that class. There is only one copy of the class variable and when any one object makes a change to a class variable, that change will be seen by all the other instances.
 
  
En el siguiente ejemplo, '''population''' belongs to the Robot class and hence is a class variable. The name variable belongs to the object (it is assigned using self) and hence is an object variable.
+
<br />
 +
====The String format() Method====
 +
<blockquote>
 +
Basic usage of the str.format() method looks like this:
 +
<syntaxhighlight lang="python">
 +
print('{0} and {1}'.format('spam', 'eggs'))
 +
</syntaxhighlight>
  
Thus, we refer to the population class variable as '''Robot.population and not as self.population'''. We refer to the object variable name using self.name notation in the methods of that object.
+
Positional and keyword arguments can be arbitrarily combined. <span style="color:#FF0000">It is better to use keyword arguments because it is less likely to make mistake because of the position of the arguments.</span>
 +
<syntaxhighlight lang="python">
 +
print('The story of {0}, {1}, and {other}.'.format('Bill', 'Manfred', other='Georg'))
 +
</syntaxhighlight>
  
Instead of Robot.population, we could have also used self.__class__.population because every object refers to its class via the self.__class__ attribute
+
</blockquote>
  
'''Object variables''' are owned by each individual object/instance of the class. In this case, each object has its own copy of the field i.e. they are not shared and are not related in any way to the field by the same name in a different instance. An example will make this easy to understand (save as oop_objvar.py):
 
  
'''Class methods'''
+
<br />
  
The how_many method difined in the next example is actually a method that belongs to the class and not to the object. This means we can define it as either a classmethod or a staticmethod depending on whether we need to know which class we are part of. Since we refer to a class variable, let's use classmethod.
+
==Functions and Methods==
  
We have marked the how_many method as a class method using the '''classmethod decorator'''.
 
  
Decorators can be imagined to be a shortcut to calling a wrapper function, so applying the @classmethod decorator is same as calling:
+
<br />
 +
===How to define a Function===
  
how_many = classmethod(how_many)
+
<source lang="python">
 +
def hello():
 +
    print("Hello")
  
'''Docstrings:'''
+
def area(width, height):
 +
    return width * height
  
In this program, we also see the use of docstrings for classes as well as methods. We can access the class docstring at runtime using Robot.__doc__ and the method docstring as Robot.say_hi.__doc__
+
def print_welcome(name):
print(Robot.__doc__)
+
    print("Welcome", name)
print(Robot.say_hi.__doc__)
 
  
 +
hello()
 +
hello()
  
<source language=python>
+
print_welcome("Fred")
class Robot:
+
w = 4
    # Docstrings
+
h = 5
    """Represents a robot, with a name."""
+
print("width =", w, " height =", h, " area =", area(w, h))
 +
</source>
  
    # A class variable, counting the number of robots
 
    population = 0
 
  
    def __init__(self, name):
+
<source lang="python">
         # Docstrings
+
def factorial():
        """Initializes the data."""
+
         n=int(input("Entrez un entier positif: "))
         self.name = name
+
         fac=1
         print("(Initializing {})".format(self.name))
+
         for i in range(n,1,-1):
 +
                fac=fac*i
 +
        return(fac)
  
        # When this person is created, the robot
+
print(factorial())
        # adds to the population
+
</source>
        Robot.population += 1
 
  
    def die(self):
 
        """I am dying."""
 
        print("{} is being destroyed!".format(self.name))
 
  
        Robot.population -= 1
+
<br />
 +
===Some important Functions and Methods===
  
        if Robot.population == 0:
 
            print("{} was the last one.".format(self.name))
 
        else:
 
            print("There are still {:d} robots working.".format(
 
                Robot.population))
 
  
    def say_hi(self):
+
<br />
        """Greeting by the robot.
+
====type====
 +
<blockquote>
 +
'''''type()'''''returns the type of these objects:
 +
<syntaxhighlight lang="python">
 +
a = ('apple', 'banana', 'cherry')
 +
b = "Hello World"
 +
c = 33
  
        Yeah, they can do that."""
+
x = type(a)
        print("Greetings, my masters call me {}.".format(self.name))
+
y = type(b)
 +
z = type(c)
 +
</syntaxhighlight>
  
    @classmethod
+
</blockquote>
    def how_many(cls):
 
        """Prints the current population."""
 
        print("We have {:d} robots.".format(cls.population))
 
  
  
droid1 = Robot("R2-D2")
+
<br />
droid1.say_hi()
 
Robot.how_many()
 
  
droid2 = Robot("C-3PO")
+
====List of Functions and Methods====
droid2.say_hi()
 
Robot.how_many()
 
  
print("\nRobots can do some work here.\n")
+
https://www.w3schools.com/python/python_ref_functions.asp
  
print("Robots have finished their work. So let's destroy them.")
 
droid1.die()
 
droid2.die()
 
  
Robot.how_many()
+
'''What’s the difference between Python functions and methods?''':
</source>
 
  
Output:
+
After reading this far in the article, I bet you have this question: '''''“Why on Earth do we have both functions and methods, when they practically do the same thing?”'''''
$ python oop_objvar.py
 
(Initializing R2-D2)
 
Greetings, my masters call me R2-D2.
 
We have 1 robots.
 
(Initializing C-3PO)
 
Greetings, my masters call me C-3PO.
 
We have 2 robots.
 
 
Robots can do some work here.
 
 
Robots have finished their work. So let's destroy them.
 
R2-D2 is being destroyed!
 
There are still 1 robots working.
 
C-3PO is being destroyed!
 
C-3PO was the last one.
 
We have 0 robots.
 
  
===Inheritance===
+
I remember that when I started learning Python, I had a hard time answering this question. This is still the most confusing topic for newcomers in the Python-world.
One of the major benefits of object oriented programming is reuse of code and one of the ways this is achieved is through the inheritance mechanism. Inheritance can be best imagined as implementing a type and subtype relationship between classes.
 
  
Suppose you want to write a program which has to keep track of the teachers and students in a college. They have some common characteristics such as name, age and address. They also have specific characteristics such as salary, courses and leaves for teachers and, marks and fees for students.
+
The official answer is that there is a small difference between them. Namely: a method always belongs to an object (e.g. in the <code>dog.append(4)</code> method <code>.append()</code> needed the <code>dog</code> object to be applicable), while a function doesn’t necessarily. To make this answer even more twisted: a method is in fact nothing else but a specific function. Got it? All methods are functions, but not all functions are methods!
 +
{| class="wikitable"
 +
|+
 +
!https://www.w3schools.com/python/python_reference.asp
 +
!Function/Method
 +
!Description
 +
!Example
 +
|-
 +
| rowspan="7" |<h5 style="text-align:left">Built-in functions</h5>
 +
https://docs.python.org/3/library/functions.html
  
You can create two independent classes for each type and process them but adding a new common characteristic would mean adding to both of these independent classes. This quickly becomes unwieldy.
+
https://www.w3schools.com/python/python_ref_functions.asp
 +
|'''<code>abs()</code>'''
 +
|Returns the absolute value of a numeric value
 +
|<code>abs(-4/3)</code>
 +
|-
 +
|'''<code>round()</code>'''
 +
|Returns the rounded value of a numeric value.
 +
|<code>round(-4/3)</code>
 +
|-
 +
|'''<code>min()</code>'''
 +
|Returns the smallest item of a list or of the typed-in arguments. It can even be a string.
 +
|<code>min(3,2,5)</code>
  
A better way would be to create a common class called SchoolMember and then have the teacher and student classes inherit from this class i.e. they will become sub-types of this type (class) and then we can add specific characteristics to these sub-types.
+
<code>min('c','a','b')</code>
 +
|-
 +
|'''<code>max()</code>'''
 +
|
 +
|
 +
|-
 +
|'''<code>sorted()</code>'''
 +
|It sorts a list into ascending order. The list can contain strings or numbers.
 +
|<code>a = [3, 2, 1]</code><code>sorted(a)</code>
 +
|-
 +
|'''<code>sum()</code>'''
 +
|It sums a list.
 +
|<code>a = [3, 2, 1]</code><code>sum(a)</code>
 +
|-
 +
|'''<code>len()</code>'''
 +
|Returns the number of elements in a list or the number of characters in a string.
 +
|<code>len('Hello!')</code>
 +
|-
 +
| rowspan="6" |<h5 style="text-align:left">String methods</h5>
 +
https://www.w3schools.com/python/python_ref_string.asp
 +
|'''<code>a.lower()</code>'''
 +
|Returns the lowercase version of a string.
 +
|<code>a = 'MuG'</code><code>a.lower()</code>
 +
|-
 +
|'''<code>a.upper()</code>'''
 +
|
 +
|
 +
|-
 +
|'''<code>a.strip()</code>'''
 +
|If the string has whitespaces at the beginning or at the end, it removes them.
 +
|<code>a = ' Mug '</code><code>a.strip()</code>
 +
|-
 +
|'''<code>a.replace('old', 'new')</code>'''
 +
|Replaces a given string with another string. Note that it’s case sensitive.
 +
|<code>a = 'muh'</code><code>a.replace('h','g')</code>
 +
|-
 +
|'''<code>a.split('delimiter')</code>'''
 +
|Splits your string into a list. Your argument specifies the delimiter.
 +
|<code>a = 'Hello World'</code><code>a.split(' ')</code>
 +
|-
 +
|'''<code>'delimiter'.join(a)</code>'''
 +
|It joins elements of a list into one string. You can specify the delimiter again.
 +
|<code>a = ['Hello', 'World']</code>
  
There are many advantages to this approach. If we add/change any functionality in SchoolMember, this is automatically reflected in the subtypes as well. For example, you can add a new ID card field for both teachers and students by simply adding it to the SchoolMember class. However, changes in the subtypes do not affect other subtypes. Another advantage is that if you can refer to a teacher or student object as a SchoolMember object which could be useful in some situations such as counting of the number of school members. This is called '''polymorphism''' where a sub-type can be substituted in any situation where a parent type is expected i.e. the object can be treated as an instance of the '''parent class'''.
 
  
Also observe that we reuse the code of the parent class and we do not need to repeat it in the different classes as we would have had to in case we had used independent classes.
+
<code>' '.join(a)</code>
 +
|-
 +
| rowspan="4" |<h5 style="text-align:left">List methods</h5>
 +
https://docs.python.org/3/tutorial/datastructures.html
  
'''The SchoolMember class in this situation is known as the base class or the superclass. The Teacher and Student classes are called the derived classes or subclasses.'''
+
https://www.w3schools.com/python/python_ref_list.asp
 +
|'''<code>a.append(arg)</code>'''
 +
|Adds an element to the end of our list.
 +
|<code>dog = ['Freddie', 9, True, 1.1, 2001, ['bone', 'little ball']]</code>
  
We will now see this example as a program (save as oop_subclass.py):
 
  
==Python Web Development==
+
<code>dog.append(4)</code>
https://www.fullstackpython.com/web-development.html
+
|-
 +
|'''<code>a.remove(arg)</code>'''
 +
|We have to specify the element that we want to remove and Python will remove the first item with that value from the list.
 +
|<code>dog.remove(2001)</code>
 +
|-
 +
|'''<code>a.count(arg)</code>'''
 +
|Returns the number of the specified value in a list.
 +
|<code>dog.count('Freddie')</code>
 +
|-
 +
|'''<code>a.clear()</code>'''
 +
|removes all elements of the list. It will basically delete Freddie. No worries, we will get him back.
 +
|<code>dog.clear()</code>
 +
|-
 +
| rowspan="3" |<h5 style="text-align:left">Dictionaries methods</h5>
  
Web Frameworks for Python:  
+
https://www.w3schools.com/python/python_ref_dictionary.asp
 +
|'''<code>a.keys()</code>'''
 +
|It returns all the keys from your dictionary.
 +
|
 +
|-
 +
|'''<code>dog_dict.values()</code>'''
 +
|It returns all the values from your dictionary.
 +
|
 +
|-
 +
|'''<code>dog_dict.clear()</code>'''
 +
|It deletes everything from your dictionary.
 +
|
 +
|-
 +
|<h5 style="text-align:left">Tuple methods</h5>
  
https://wiki.python.org/moin/WebFrameworks
+
https://www.w3schools.com/python/python_ref_tuple.asp
 +
|
 +
|
 +
|
 +
|-
 +
|<h5 style="text-align:left">Set methods</h5>
 +
https://www.w3schools.com/python/python_ref_set.asp
 +
|
 +
|
 +
|
 +
|-
 +
|<h5 style="text-align:left">File methods</h5>
 +
https://www.w3schools.com/python/python_ref_file.asp
 +
|
 +
|
 +
|
 +
|}
  
https://fr.wikipedia.org/wiki/Liste_de_frameworks_Python
 
  
Ejemplos de Web Applications in Python: https://wiki.python.org/moin/WebApplications
+
<br />
  
Complete Python Web Course (15€): https://www.udemy.com/the-complete-python-web-course-learn-by-building-8-apps/
+
==Exceptions==
  
===Frameworks===
+
<syntaxhighlight lang="python">
====Django====
+
while True:
Página oficial: https://www.djangoproject.com/
+
    try:
 +
        x = int(raw_input("Please enter a number: "))
 +
        break
 +
    except ValueError:
 +
        print "Oops!  That was no valid number.  Try again..."
 +
</syntaxhighlight>
  
Documentación: https://docs.djangoproject.com/en/1.11/
 
=====Instalación de django=====
 
Documentación oficial sobre la instalación: https://docs.djangoproject.com/en/1.11/topics/install/#installing-official-release
 
  
En este video se muestra la instalación dentro del virtual environement: https://www.youtube.com/watch?v=oRGK9klCn00#t=107.337193
+
<br />
  
Aquí se muestran distintas formas de instalar django: https://www.howtoforge.com/tutorial/how-to-install-django-on-ubuntu/
+
==Some example codes==
  
======Prerequisitos======
 
  
'''1. Install Python'''
+
<br />
 +
===Factorial function using recursion===
 +
<span style="background:#E6E6FA; color:red">'''A VERY VERY NICE example of recursion is the factorial function:'''</span>
 +
<syntaxhighlight lang="python3">
 +
Example:
 +
4! = 4 * 3!
 +
3! = 3 * 2!
 +
2! = 2 * 1
 +
Replacing the calculated values gives us the following expression
 +
4! = 4 * 3 * 2 * 1
 +
</syntaxhighlight>
  
Si ya está instalado. Setup python 3 as Default Python version:''' Ver [[Python#Cambiar la versión por defecto|Cambiar la versión por defecto]]
 
  
'''2. Install Apache and mod_wsgi'''
+
<syntaxhighlight lang="python3">
 +
def factorial(n):
 +
    if n == 1:
 +
        return 1
 +
    else:
 +
        return n * factorial(n-1)
 +
</syntaxhighlight>
  
If you just want to experiment with Django, skip ahead to the next section; Django includes a lightweight web server you can use for testing, so you won’t need to set up Apache until you’re ready to deploy Django in production.
 
  
'''3. Get your database running'''
+
<br />
  
By default, the configuration uses SQLite. If you’re new to databases, or you’re just interested in trying Django, this is the easiest choice. SQLite is included in Python, so you won’t need to install anything else to support your database.
+
==[[Python for Data Science]]==
  
When starting your first real project, however, you may want to use a more scalable database like PostgreSQL, to avoid database-switching headaches down the road.
 
  
If you plan to use Django’s database API functionality, you’ll need to make sure a database server is running. Django supports many different database servers and is officially supported with PostgreSQL, MySQL, Oracle and SQLite.
+
<br />
 +
==[[Manim]]==
  
'''4. Remove any old versions of Django'''
 
  
If you are upgrading your installation of Django from a previ
+
<br />

Latest revision as of 15:47, 11 September 2024


https://www.python.org/

https://docs.python.org/3/



Online Python Interpreters

These ones supports many languages:



Installation


Installing python on Ubuntu

The last version of Python is usually installed this way. It can be verified in many sources: https://phoenixnap.com/kb/how-to-install-python-3-ubuntu

sudo apt update
sudo apt install software-properties-common
sudo add-apt-repository ppa:deadsnakes/ppa
sudo apt update
sudo apt install python3.8

python --version



Installing Anaconda


Display the installed version

Para ver la versión por defecto:

python --version

O simplemente entrando a la línea de comandos python a través de:

python

Ahora, en un SO pueden haber más de una versión instalada. Para ver que versiones de python se encuentran ya instaladas en nuestro sistema operativo podemos ir al directorio /usr/bin y ver que ejecutables de python se encuentran:

ls /usr/bin/python
python      python2     python2.7   python3     python3.5   python3.5m  python3m    pythontex   pythontex3

y para ver la versión exacta (Python 3.5.2) ejecutamos python3.5 y este nos muestra la versión exacta al entrar a la línea de comandos python:

python3.5
Python 3.5.2 (default, Nov 17 2016, 17:05:23) 
[GCC 5.4.0 20160609] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>>



Change the default version

https://linuxconfig.org/how-to-change-from-default-to-alternative-python-version-on-debian-linux



Change python version on per user basis

To change a python version on per user basis you simply create an alias within user's home directory. Open ~/.bashrc file and add new alias to change your default python executable:

alias python='/usr/bin/python3.4'

Once you make the above change, re-login or source your .bashrc file:

. ~/.bashrc



Change python version system-wide

To change python version system-wide we can use update-alternatives command.

Logged in as a root user. First we can list all available python alternatives:

# update-alternatives --list python
update-alternatives: error: no alternatives for python

El comando anterio debería mostrar las alternativas (por ejemplo python2.7 , python3.5) que ya han sido incluidas a través del comando update-alternatives --install. The above error message means that no python alternatives has been recognized by update-alternatives command. For this reason we need to update our alternatives table and include both python2.7 and python3.5:

Debemos entonces contruir la tabla de alternativas de la siguiente forma:

# update-alternatives --install /usr/bin/python python /usr/bin/python2.7 1
update-alternatives: using /usr/bin/python2.7 to provide /usr/bin/python (python) in auto mode
# update-alternatives --install /usr/bin/python python /usr/bin/python3.5 2
update-alternatives: using /usr/bin/python3.4 to provide /usr/bin/python (python) in auto mode

The --install option take multiple arguments from which it will be able to create a symbolic link. The last argument specified it priority means, if no manual alternative selection is made the alternative with the highest priority number will be set. In our case we have set a priority 2 for /usr/bin/python3.4 and as a result the /usr/bin/python3.5 was set as default python version automatically by update-alternatives command.

Es decir, si queremos que python2.7 sea la versión por defecto podemos ejecutar el comando update-alternatives --intall de la forma mostrada arriba y ajustar el último argumento de forma tal que el mayor valor sea asociado a la versión que queremos por defecto.



IDE for Python


PyCharm

https://www.jetbrains.com/pycharm/


Installation:
https://www.jetbrains.com/help/pycharm/installation-guide.html

sudo snap install pycharm-community --classic



Visual Studio Code

Python in Visual Studio Code

https://code.visualstudio.com/docs/languages/python



Jupyter

.



Atom

https://flight-manual.atom.io/getting-started/sections/installing-atom/



Python on eclipse

Para utilizar Python en Eclipse debemos instalar PyDev:

Help > Eclipse Marketplace Find: PyDev



Sublime Text

https://www.sublimetext.com/

https://en.wikipedia.org/wiki/Sublime_Text

Sublime Text is a proprietary cross-platform source code editor with a Python application programming interface (API). It natively supports many programming languages and markup languages, and functions can be added by users with plugins.



Installation

https://linuxconfig.org/how-to-install-sublime-text-on-ubuntu-18-04-bionic-beaver-linux

wget -qO - https://download.sublimetext.com/sublimehq-pub.gpg | sudo apt-key add -
sudo apt-add-repository "deb https://download.sublimetext.com/ apt/stable/"
sudo apt install sublime-text



Keyboard shortcut to comment lines in Sublime Text 3

http://stackoverflow.com/questions/17742781/keyboard-shortcut-to-comment-lines-in-sublime-text-3

https://forum.sublimetext.com/t/st3-3012-toggle-comments-broken/8930/8

As a workaround, go to Preferences->Key Bindings - User and add these keybindings (if you're using Linux):

{ "keys": ["ctrl+7"], "command": "toggle_comment", "args": { "block": false } },
{ "keys": ["ctrl+shift+7"], "command": "toggle_comment", "args": { "block": true } }



Indentation

https://stackoverflow.com/questions/9474090/how-do-i-force-sublime-text-to-indent-two-spaces-per-tab

If you want it for all files, go to Preferences -> Settings - Default/User. But as several comments below indicate, Syntax Specific settings can limit it to just the languages you choose.

To limit this configuration to Ruby files, first open up a Ruby file in the editor, and then go to Preferences -> Settings -> More -> Syntax Specific -> User. This should open a settings window named Ruby.sublime-settings

Save these settings:

{
  "tab_size": 2,
  "translate_tabs_to_spaces": true,
  "detect_indentation": false
}



Crear un proyecto en Sublime Text

  1. Abrimos una nueva ventana: File > New Window
  2. Add folder to project
  3. Save project as: es apropiado guardarlo en el mismo directorio en donde fue creado el proyecto.

Esto creará dos archivos:

  • nombre-111.sublime-project
  • nombre-111.sublime-workspace : Este es el que debemos abrir para ingresar al proyecto.



Using Python


Python Shell

From the terminal, you can start the Python Shell/Interpreter (Also know as Python Interactive Shell) using the command:

python3.x



Premiers pas avec l interpreteur de commandes Python


Operations courantes
>>> 3 + 4
7
>>> 9.5 + 2
11.5
>>> 3.11 + 2.08
5.1899999999999995



Writing and Running a Python code

You can use your favorite Text Editor or IDE to write your Python code:

example.py
#!/usr/bin/python3.6

c=input("Ingrese un caracter: ")
e=int(input("Entrez un entier: "))

for i in range(1,e+1):
	for j in range(1,i+1):
		print(c,end="")
	print()


  • If we use the line #!/usr/bin/python3.6 to indicate the path to the Python Interpreter, then we can then run our code as a Executable file this way:
./example.py


  • However, the most common way is not including #!/usr/bin/python3.6 and calling the Python Interpreter through the python command:
python3 example.py


  • Of course, you can also run a Python program through a button on a IDE Graphical Interface.



pip and virtualenv

https://pypi.org/project/pip/

https://pip.pypa.io/en/stable/installation/


To display the version of pip:

python3.11 -m pip --version


Upgrade pip:

python3 -m pip install --upgrade pip


pip install librarie


Para especificar la versión de python a la cual será instalada la libreria:

python3 -m pip install pandas

En este caso, cuando usemos python3 «pandas» estará disponible, pero no necesariamente para otras versiones de python


To list all pakages installed :

pip list
python3.11 -m pip list


How can I install packages using pip according to the requirements.txt

pip install -r requirements.txt
python3.8 -m pip install -r requirements.txt


Puede ser necesario instalar venv para la version de python deseada:

sudo apt install python3.11-venv


Crear un virtualenv:

python3 -m venv myenv  # This will install a local copy of Python and pip into a directory called myprojectenv


Activar el virtualenv:

source myenv/bin/activate


Para especificar la versión de Python que del virtualenv: https://stackoverflow.com/questions/45293436/how-to-specify-python-version-used-to-create-virtual-environment

virtualenv -p python3.8 myproject_env    # Creates a new default python3.8 (python3.8 must be a valid command i.e found in the PATH)


Para salir del virtualenv:

(myproject_env)$ deactivate



Keep a python script running on a remote server


Screen

Create a screen:

screen -S bot

Disconnect: Ctrl+A+D

Reconnecting:

screen -r bot 


List screens:

screen -ls


Kill all sessions

killall screen


Kill a specific session

screen -S bot -X quit


Creating the screen without attaching to it

screen -dmS bot


Activating the venv on the screen previously created without attaching to it

screen -S bot -p 0 -X stuff $'source .venv/bin/activate\n' 


To create the screen and activate the venv at the same time without attaching to it:

screen -dmS bot bash -c 'source .venv/bin/activate && exec sh'    # This is working but the prompt is sh so not very good. (&& can be replaced by ;)
screen -dmS bot bash -c 'source .venv/bin/activate && exec bash'  # This is not activating the venv



Data types

https://docs.python.org/2.0/ref/types.html

Python_3._The_standard_type_hierarchy.png

In this source you can find a very good documentation about Python Data Types and the most important Operations and Methods for each Data Type: https://www.w3schools.com/python/python_datatypes.asp

None
Ellipsis
Numbers Integers Plain integers
Long integers
Floating point numbers
Complex numbers
Sequences Immutable sequences Strings
Unicode
Tuples
Mutable sequences Lists
Mappings Dictionaries
Callable types User-defined functions
User-defined methods
Built-in functions
Built-in methods
Classes
Class instances
Modules
Classes
Class instances
Files
Internal types Code objects
Frame objects
Traceback objects
Slice objects


Getting the Data Type: You can get the data type of any object by using the type() function:

print(type(x))
Source: https://www.w3schools.com/python/python_datatypes.asp
Type/Class Description Example Setting the Specific Data Type Operations/Functions/Methods
Numeric Types int Int, or integer, is a whole number, positive or negative, without decimals, of unlimited length. x = 20 x = int(20) https://www.w3schools.com/python/python_numbers.asp
float Float, or "floating point number" is a number, positive or negative, containing one or more decimals. x = 20.5 x = float(20.5)
complex Complex numbers are written with a "j" as the imaginary part x = 1j x = complex(1j)
Text Type str Strings are Arrays: Like many other popular programming languages, strings in Python are arrays of bytes representing unicode characters. However, Python does not have a character data type, a single character is simply a string with a length of 1. x = "Hello World" x = str("Hello World") https://www.w3schools.com/python/python_strings.asp
Boolean Type bool Booleans represent one of two values: True or False. x = True x = bool(5) https://www.w3schools.com/python/python_booleans.asp
Binary Types bytes x = b"Hello" x = bytes(5)
bytearray x = bytearray(5) x = bytearray(5)
memoryview x = memoryview(bytes(5)) x = memoryview(bytes(5))
Python Collections (Arrays) Sequence Types list A list is a collection which is ordered and changeable. x = ["apple", "banana", "cherry"] x = list(("apple", "banana", "cherry")) https://www.w3schools.com/python/python_lists.asp


Nice way to create a list:
lista = [x**2 for x in range(12) if x%3 == 0]
print(lista)
# Output:
[0, 9, 36, 81]

tuple A tuple is a collection which is ordered and unchangeable. x = ("apple", "banana", "cherry") x = tuple(("apple", "banana", "cherry")) https://www.w3schools.com/python/python_tuples.asp
Array Python does not have built-in support for Arrays. You have to import it from a Library:

from numpy import array

x = array([3, 6, 9, 12])


There are some differences between Array and List: https://medium.com/backticks-tildes/list-vs-array-python-data-type-40ac4f294551

Lists are containers for elements having differing data types but arrays are used as containers for elements of the same data type.

Arrays are specially optimised for arithmetic computations, Ex:

x = array([3, 6, 9, 12])

divided_x = x/2 # This would return an error if using List

print(divided_x)

[1.5 3. 4.5 6. ]

Python_for_Data_Science#Arrays
range x = range(6) x = range(6)
Mapping Type dict A dictionary is a collection which is unordered, changeable and indexed. In Python dictionaries are written with curly brackets, and they have keys and values. x = {"name" : "John", "age" : 36} x = dict(name="John", age=36) https://www.w3schools.com/python/python_dictionaries.asp
Set Types set A set is a collection which is unordered and unindexed. x = {"apple", "banana", "cherry"} x = set(("apple", "banana", "cherry")) https://www.w3schools.com/python/python_sets.asp
frozenset x = frozenset({"apple", "banana", "cherry"}) x = frozenset(("apple", "banana", "cherry"))




Operators

Operator Name/Description Example Same as
Python

s2

Java JS R Python Java F R
Arithmetic Operators + + Addition x + y
- - Subtraction x - y
* * Multiplication x * y
/ / Division x / y
% % Modulus x % y
** java.util.Math Exponentiation x ** y import java.util.Math

Double result = Math.pow(number, exponent);

// Floor division x // y
++ Increment: Increases the value of a variable by 1 ++x
-- Decrement: Decreases the value of a variable by 1 --x
Assignment Operators = = x = 5
+= += x+= 3 x = x + 3
-= -= x -= 3 x = x - 3
*= *= x *= 3 x = x * 3
/= /= x /= 3 x = x / 3
%= %= x %= 3 x = x % 3
//= x //= 3 x = x // 3
**= x **= 3 x = x ** 3
&= &= x &= 3 x = x & 3
|= |= x |= 3 x = x | 3
^= ^= x ^= 3 x = x ^ 3
>>= >>= x >>= 3 x = x >> 3
<<= <<= x <<= 3 x = x << 3
Comparison Operators == == Equal x == y
!= != Not equal x != y
> > Greater than x > y
< < Less than x < y
>= >= Greater than or equal to x >= y
<= <= Less than or equal to x <= y
Logical Operators and && Logical and: Returns True if both statements are true x < 5 and x < 10 x < 5 && x < 10
or || Logical or: Returns True if one of the statements is true x < 5 or x < 4 x < 5 || x < 4
not ! Logical not: Reverse the result, returns False if the result is true not(x < 5 and x < 10) !(x < 5 && x < 10)
Identity Operators is Returns true if both variables are the same object x is y
is not Returns true if both variables are not the same object x is not y
Membership Operators in Returns True if a sequence with the specified value is present in the object x in y
not in Returns True if a sequence with the specified value is not present in the object x not in y
Bitwise Operators &
AND

Sets each bit to 1 if both bits are 1

| OR

Sets each bit to 1 if one of two bits is 1

^ XOR

Sets each bit to 1 if only one of two bits is 1

~ NOT

Inverts all the bits

<< Zero fill left shift

Shift left by pushing zeros in from the right and let the leftmost bits fall off

>> Signed right shift

Shift right by pushing copies of the leftmost bit in from the left, and let the rightmost bits fall off

Added by myself
String concatenation +
"Coucou ' + 'c\'est ' + 'nous !";
conca()
'Coucou '.concat('c\'est ', 'nous !');
join()
['Coucou ', 'c\'est ', 'nous !'].join();



Control flow statements


If statements

https://www.w3schools.com/python/python_conditions.asp


a = 200
b = 33
if b > a:
     print("b is greater than a")
elif a == b:
     print("a and b are equal")
else:
     print("a is greater than b")


Short Hand If:

 if a > b: print("a is greater than b")


One line if else statement, with 3 conditions:

print("A") if a > b else print("=") if a == b else print("B")



For Loops

https://www.w3schools.com/python/python_for_loops.asp


Print each fruit in a fruit list:

fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
     print(fruit)

# Output:
apple
banana
cherry


fruits = ["apple", "banana", "cherry"]
for fruit_no, fruit in enumerate(fruits):
     print(fruit_no, fruit)

# Output:
0 apple
1 banana
2 cherry


Looping Through a String:

for x in "banana":
     print(x)


The break Statement:

fruits = ["apple", "banana", "cherry"]
for x in fruits:
     print(x)
     if x == "banana":
          break


The continue Statement: With the continue statement we can stop the current iteration of the loop, and continue with the next:

fruits = ["apple", "banana", "cherry"]
for x in fruits:
     if x == "banana":
          continue
     print(x)


The range() Function: The range() function returns a sequence of numbers, starting from 0 by default, and increments by 1 (by default), and ends at a specified number.

for x in range(6):
     print(x)

Note that range(6) is not the values of 0 to 6, but the values 0 to 5.


The range() Function: The range() function returns a sequence of numbers, starting from 0 by default, and increments by 1 (by default), and ends at a specified number.

for x in range(2, 30, 3):
     print(x)



While Loops

https://www.w3schools.com/python/python_while_loops.asp


i = 1
while i < 6:
     print(i)
     i += 1


The break Statement:

i = 1
while i < 6:
     print(i)
     if i == 3:
          break
     i += 1


The continue Statement: With the continue statement we can stop the current iteration, and continue with the next:

i = 0
while i < 6:
     i += 1
     if i == 3:
          continue
     print(i)


The else Statement: With the else statement we can run a block of code once when the condition no longer is true:

i = 1
while i < 6:
  print(i)
  i += 1
else:
  print("i is no longer less than 6")



Input and Output

Input and Output funtions: Esta página creo que no está actualizada para python 3, pero está bien organizada: https://en.wikibooks.org/wiki/Python_Programming/Input_and_Output#input.28.29



input

name = input("What's your name? ")
print("Nice to meet you " + name + "!")
age = input("Your age? ")
print("So, you are already " + age + " years old, " + name + "!")


La función input asigna por defecto una variable de tipo str. Si queremos que la variable sea tipo int o list:

>>> population = int(input("Population of Toronto? "))
Population of Toronto? 2615069
>>> print(population, type(population))
2615069 <class 'int'>
>>> cities_canada = eval(input("Largest cities in Canada: "))
Largest cities in Canada: ["Toronto", "Montreal", "Calgara", "Ottawa"]
>>> print(cities_canada, type(cities_canada))
['Toronto', 'Montreal', 'Calgara', 'Ottawa'] <class 'list'>



Output


print

https://docs.python.org/3/tutorial/inputoutput.html

The print() function prints the specified message to the screen, or other standard output device:

print("Hello World")


The full syntax of print() is:

print(*objects, sep=' ', end='\n', file=sys.stdout, flush=False)


Print more than one object:

a = 5
b = a

print('a =', a, '= b')


print() with separator and end parameters:

a = 5
print("a =", a, sep='00000', end='\n\n\n')
print("a =", a, sep='0', end='')


Print a tuple:

x = ("apple", "banana", "cherry")
print(x)



The String format() Method

Basic usage of the str.format() method looks like this:

print('{0} and {1}'.format('spam', 'eggs'))

Positional and keyword arguments can be arbitrarily combined. It is better to use keyword arguments because it is less likely to make mistake because of the position of the arguments.

print('The story of {0}, {1}, and {other}.'.format('Bill', 'Manfred', other='Georg'))



Functions and Methods


How to define a Function

def hello():
    print("Hello")

def area(width, height):
    return width * height

def print_welcome(name):
    print("Welcome", name)

hello()
hello()

print_welcome("Fred")
w = 4
h = 5
print("width =", w, " height =", h, " area =", area(w, h))


def factorial():
        n=int(input("Entrez un entier positif: "))
        fac=1
        for i in range(n,1,-1):
                fac=fac*i
        return(fac)

print(factorial())



Some important Functions and Methods


type

type()returns the type of these objects:

a = ('apple', 'banana', 'cherry')
b = "Hello World"
c = 33

x = type(a)
y = type(b)
z = type(c)



List of Functions and Methods

https://www.w3schools.com/python/python_ref_functions.asp


What’s the difference between Python functions and methods?:

After reading this far in the article, I bet you have this question: “Why on Earth do we have both functions and methods, when they practically do the same thing?”

I remember that when I started learning Python, I had a hard time answering this question. This is still the most confusing topic for newcomers in the Python-world.

The official answer is that there is a small difference between them. Namely: a method always belongs to an object (e.g. in the dog.append(4) method .append() needed the dog object to be applicable), while a function doesn’t necessarily. To make this answer even more twisted: a method is in fact nothing else but a specific function. Got it? All methods are functions, but not all functions are methods!

https://www.w3schools.com/python/python_reference.asp Function/Method Description Example
Built-in functions

https://docs.python.org/3/library/functions.html

https://www.w3schools.com/python/python_ref_functions.asp

abs() Returns the absolute value of a numeric value abs(-4/3)
round() Returns the rounded value of a numeric value. round(-4/3)
min() Returns the smallest item of a list or of the typed-in arguments. It can even be a string. min(3,2,5)

min('c','a','b')

max()
sorted() It sorts a list into ascending order. The list can contain strings or numbers. a = [3, 2, 1]sorted(a)
sum() It sums a list. a = [3, 2, 1]sum(a)
len() Returns the number of elements in a list or the number of characters in a string. len('Hello!')
String methods

https://www.w3schools.com/python/python_ref_string.asp

a.lower() Returns the lowercase version of a string. a = 'MuG'a.lower()
a.upper()
a.strip() If the string has whitespaces at the beginning or at the end, it removes them. a = ' Mug 'a.strip()
a.replace('old', 'new') Replaces a given string with another string. Note that it’s case sensitive. a = 'muh'a.replace('h','g')
a.split('delimiter') Splits your string into a list. Your argument specifies the delimiter. a = 'Hello World'a.split(' ')
'delimiter'.join(a) It joins elements of a list into one string. You can specify the delimiter again. a = ['Hello', 'World']


' '.join(a)

List methods

https://docs.python.org/3/tutorial/datastructures.html

https://www.w3schools.com/python/python_ref_list.asp

a.append(arg) Adds an element to the end of our list. dog = ['Freddie', 9, True, 1.1, 2001, ['bone', 'little ball']]


dog.append(4)

a.remove(arg) We have to specify the element that we want to remove and Python will remove the first item with that value from the list. dog.remove(2001)
a.count(arg) Returns the number of the specified value in a list. dog.count('Freddie')
a.clear() removes all elements of the list. It will basically delete Freddie. No worries, we will get him back. dog.clear()
Dictionaries methods

https://www.w3schools.com/python/python_ref_dictionary.asp

a.keys() It returns all the keys from your dictionary.
dog_dict.values() It returns all the values from your dictionary.
dog_dict.clear() It deletes everything from your dictionary.
Tuple methods

https://www.w3schools.com/python/python_ref_tuple.asp

Set methods

https://www.w3schools.com/python/python_ref_set.asp

File methods

https://www.w3schools.com/python/python_ref_file.asp



Exceptions

while True:
     try:
         x = int(raw_input("Please enter a number: "))
         break
     except ValueError:
         print "Oops!  That was no valid number.  Try again..."



Some example codes


Factorial function using recursion

A VERY VERY NICE example of recursion is the factorial function:

Example:
4! = 4 * 3!
3! = 3 * 2!
2! = 2 * 1
Replacing the calculated values gives us the following expression
4! = 4 * 3 * 2 * 1


def factorial(n):
    if n == 1:
        return 1
    else:
        return n * factorial(n-1)



Python for Data Science


Manim