Difference between revisions of "Python"

From Sinfronteras
Jump to: navigation, search
(Writing and Running Python a code)
(Data types)
 
(49 intermediate revisions by the same user not shown)
Line 1: Line 1:
 +
 +
<br />
 +
https://www.python.org/
 +
 +
https://docs.python.org/3/
 +
 +
 +
<br />
 +
==Online Python Interpreters==
 +
These ones supports many languages:
 +
 +
*https://repl.it/
 +
*https://www.onlinegdb.com
 +
 +
 +
<br />
 
==Installation==
 
==Installation==
  
Line 4: Line 20:
 
<br />
 
<br />
 
===Installing python on Ubuntu===
 
===Installing python on Ubuntu===
Python est pré-installé sur la plupart des distributions Linux. Sinon, or if you want to install the last version using apt:
+
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
https://linuxize.com/post/how-to-install-python-3-7-on-ubuntu-18-04/
+
 
 +
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 />
 
<br />
 +
 
===[[Python_for_Data_Science#Anaconda|Installing Anaconda]]===
 
===[[Python_for_Data_Science#Anaconda|Installing Anaconda]]===
  
Line 68: Line 93:
  
 
==IDE for Python==
 
==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/
 +
 +
 +
<br />
 +
===Python on eclipse===
 +
Para utilizar Python en Eclipse debemos instalar PyDev:
 +
 +
Help > Eclipse Marketplace
 +
Find: PyDev
  
  
Line 134: Line 194:
  
 
<br />
 
<br />
===PyCharm===
 
  
 
<br />
 
====Installation====
 
https://itsfoss.com/install-pycharm-ubuntu/
 
 
 
<br />
 
=====Using umake=====
 
De esta forma lo instalé correctamente:
 
 
sudo add-apt-repository ppa:ubuntu-desktop/ubuntu-make
 
sudo apt-get update
 
sudo apt-get install ubuntu-make
 
 
Once you have umake, use the command below to install PyCharm Community Edition in Ubuntu:
 
umake ide pycharm
 
 
Se instaló en la siguiente ruta:
 
/home/adelo/.local/share/umake/ide/pycharm
 
 
 
<br />
 
=====Using Snap=====
 
De esta forma lo instalé correctamente:
 
 
sudo snap install pycharm-community --classic
 
 
<span style="color:#FFF;background:#FF0000">'''Sin embargo, luego de instalarlo de esta manera, cuando iniciaba pycharm, se creaba automáticamente el directorio /home/adelo/snap. Traté de cambiar la ubicación de este directorio y no di con la solución.'''</span>
 
 
 
<br />
 
===Python on eclipse===
 
Para utilizar Python en Eclipse debemos instalar PyDev:
 
 
Help > Eclipse Marketplace
 
Find: PyDev
 
 
 
<br />
 
===[[Python_for_Data_Science#Jupyter|Jupyter]]===
 
 
 
<br />
 
 
==Using Python==
 
==Using Python==
  
Line 207: Line 223:
  
 
<br />
 
<br />
===Writing and Running Python a code===
+
===Writing and Running a Python code===
 
You can use your favorite Text Editor or IDE to write your Python code:
 
You can use your favorite Text Editor or IDE to write your Python code:
  
Line 238: Line 254:
  
 
<br />
 
<br />
===online Python Interpreters===
+
 
These ones supports many languages:  
+
==pip and virtualenv==
* https://repl.it/
+
https://pypi.org/project/pip/
* https://www.onlinegdb.com
+
 
 +
https://pip.pypa.io/en/stable/installation/
 +
 
 +
 
 +
To display the version of pip:
 +
<syntaxhighlight lang="shell">
 +
python3.11 -m pip --version
 +
</syntaxhighlight>
 +
 
 +
 
 +
Upgrade pip:
 +
<syntaxhighlight lang="shell">
 +
python3 -m pip install --upgrade pip
 +
</syntaxhighlight>
 +
 
 +
 
 +
<syntaxhighlight lang="shell">
 +
pip install librarie
 +
</syntaxhighlight>
 +
 
 +
 
 +
'''Para especificar la versión de python a la cual será instalada la libreria:'''
 +
<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
 +
 
 +
 
 +
'''To list all pakages installed :'''
 +
<syntaxhighlight lang="shell">
 +
pip list
 +
python3.11 -m pip list
 +
</syntaxhighlight>
 +
 
 +
 
 +
'''How can I install packages using pip according to the requirements.txt'''
 +
<syntaxhighlight lang="shell">
 +
pip install -r requirements.txt
 +
python3.8 -m pip install -r requirements.txt
 +
</syntaxhighlight>
 +
 
 +
 
 +
'''Puede ser necesario instalar venv para la version de python deseada:'''
 +
<syntaxhighlight lang="shell">
 +
sudo apt install python3.11-venv
 +
</syntaxhighlight>
 +
 
 +
 
 +
'''Crear un virtualenv:'''
 +
<syntaxhighlight lang="shell">
 +
python3 -m venv myenv  # This will install a local copy of Python and pip into a directory called myprojectenv
 +
</syntaxhighlight>
 +
 
 +
 
 +
'''Activar el virtualenv:'''
 +
<syntaxhighlight lang="shell">
 +
source myenv/bin/activate
 +
</syntaxhighlight>
 +
 
 +
 
 +
'''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="shell">
 +
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)
 +
</syntaxhighlight>
 +
 
 +
 
 +
'''Para salir del virtualenv:'''
 +
<syntaxhighlight lang="shell">
 +
(myproject_env)$ deactivate
 +
</syntaxhighlight>
 +
 
 +
 
 +
<br />
 +
 
 +
==Keep a python script running on a remote server==
  
  
 
<br />
 
<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==
 
==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:
 
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
 
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'''
 +
|
 +
|
 +
|}
  
  
Line 257: Line 520:
 
! colspan="2" |
 
! colspan="2" |
 
!Type/Class
 
!Type/Class
 +
!Description
 
!Example
 
!Example
 
!Setting the Specific Data Type
 
!Setting the Specific Data Type
!Description
+
!Operations/Functions/Methods
 
|-
 
|-
 
| colspan="2" rowspan="3" |'''Numeric Types'''
 
| colspan="2" rowspan="3" |'''Numeric Types'''
 
|<code>int</code>
 
|<code>int</code>
 +
|Int, or integer, is a whole number, positive or negative, without decimals, of unlimited length.
 
|x = 20
 
|x = 20
 
|x = int(20)
 
|x = int(20)
|Int, or integer, is a whole number, positive or negative, without decimals, of unlimited length.
+
| rowspan="3" |https://www.w3schools.com/python/python_numbers.asp
 
|-
 
|-
 
|<code>float</code>
 
|<code>float</code>
 +
|Float, or "floating point number" is a number, positive or negative, containing one or more decimals.
 
|x = 20.5
 
|x = 20.5
 
|x = float(20.5)
 
|x = float(20.5)
|Float, or "floating point number" is a number, positive or negative, containing one or more decimals.
 
 
|-
 
|-
 
|<code>complex</code>
 
|<code>complex</code>
 +
|Complex numbers are written with a "j" as the imaginary part
 
|x = 1j
 
|x = 1j
 
|x = complex(1j)
 
|x = complex(1j)
|Complex numbers are written with a "j" as the imaginary part
 
 
|-
 
|-
 
| colspan="2" |'''Text Type'''
 
| colspan="2" |'''Text Type'''
 
|<code>str</code>
 
|<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 = "Hello World"
 
|x = str("Hello World")
 
|x = str("Hello World")
|'''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.
+
|https://www.w3schools.com/python/python_strings.asp
 
|-
 
|-
 
| colspan="2" |'''Boolean Type'''
 
| colspan="2" |'''Boolean Type'''
 
|<code>bool</code>
 
|<code>bool</code>
 +
|Booleans represent one of two values: <code>True</code> or <code>False</code>.
 
|x = True
 
|x = True
 
|x = bool(5)
 
|x = bool(5)
|Booleans represent one of two values: <code>True</code> or <code>False</code>.
+
|https://www.w3schools.com/python/python_booleans.asp
 
|-
 
|-
 
| colspan="2" rowspan="3" |'''Binary Types'''
 
| colspan="2" rowspan="3" |'''Binary Types'''
 
|<code>bytes</code>
 
|<code>bytes</code>
 +
|
 
|x = b"Hello"
 
|x = b"Hello"
 
|x = bytes(5)
 
|x = bytes(5)
Line 296: Line 564:
 
|-
 
|-
 
|<code>bytearray</code>
 
|<code>bytearray</code>
 +
|
 
|x = bytearray(5)
 
|x = bytearray(5)
 
|x = bytearray(5)
 
|x = bytearray(5)
Line 301: Line 570:
 
|-
 
|-
 
|<code>memoryview</code>
 
|<code>memoryview</code>
 +
|
 
|x = memoryview(bytes(5))
 
|x = memoryview(bytes(5))
 
|x = memoryview(bytes(5))
 
|x = memoryview(bytes(5))
Line 308: Line 578:
 
| rowspan="4" |'''Sequence Types'''
 
| rowspan="4" |'''Sequence Types'''
 
|<code>list</code>
 
|<code>list</code>
 +
|A list is a collection which is ordered and changeable.
 
|x = ["apple", "banana", "cherry"]
 
|x = ["apple", "banana", "cherry"]
 
|x = list(("apple", "banana", "cherry"))
 
|x = list(("apple", "banana", "cherry"))
|A list is a collection which is ordered and changeable.
+
|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>
 
|<code>tuple</code>
 +
|A tuple is a collection which is ordered and '''unchangeable'''.
 
|x = ("apple", "banana", "cherry")
 
|x = ("apple", "banana", "cherry")
 
|x = tuple(("apple", "banana", "cherry"))
 
|x = tuple(("apple", "banana", "cherry"))
|A tuple is a collection which is ordered and '''unchangeable'''.
+
|https://www.w3schools.com/python/python_tuples.asp
 
|-
 
|-
 
|<code>Array</code>
 
|<code>Array</code>
| colspan="2" |Python does not have built-in support for Arrays. You have to import it from a Library:
+
|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>
  
'''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
|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.
 
Lists are containers for elements having differing data types but arrays are used as containers for elements of the same data type.
Line 330: Line 611:
 
Arrays are specially optimised for arithmetic computations, Ex:
 
Arrays are specially optimised for arithmetic computations, Ex:
  
x = array([3, 6, 9, 12])
+
<code>x = array([3, 6, 9, 12])</code>
  
divided_x = x/2     # This would return an error if using List
+
<code>divided_x = x/2</code>  # This would return an error if using List
  
print(divided_x)
+
<code>print(divided_x)</code>
  
 
[1.5 3.  4.5 6. ]
 
[1.5 3.  4.5 6. ]
 +
|
 +
|
 +
|[[Python_for_Data_Science#Arrays]]
 
|-
 
|-
 
|<code>range</code>
 
|<code>range</code>
 +
|
 
|x = range(6)
 
|x = range(6)
 
|x = range(6)
 
|x = range(6)
Line 345: Line 630:
 
|'''Mapping Type'''
 
|'''Mapping Type'''
 
|<code>dict</code>
 
|<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 = {"name" : "John", "age" : 36}
 
|x = dict(name="John", age=36)
 
|x = dict(name="John", age=36)
|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.
+
|https://www.w3schools.com/python/python_dictionaries.asp
 
|-
 
|-
 
| rowspan="2" |'''Set Types'''
 
| rowspan="2" |'''Set Types'''
 
|<code>set</code>
 
|<code>set</code>
 +
|A set is a collection which is unordered and unindexed.
 
|x = {"apple", "banana", "cherry"}
 
|x = {"apple", "banana", "cherry"}
 
|x = set(("apple", "banana", "cherry"))
 
|x = set(("apple", "banana", "cherry"))
|A set is a collection which is unordered and unindexed.
+
|https://www.w3schools.com/python/python_sets.asp
 
|-
 
|-
 
|<code>frozenset</code>
 
|<code>frozenset</code>
 +
|
 
|x = frozenset({"apple", "banana", "cherry"})
 
|x = frozenset({"apple", "banana", "cherry"})
 
|x = frozenset(("apple", "banana", "cherry"))
 
|x = frozenset(("apple", "banana", "cherry"))
Line 364: Line 652:
  
 
<br />
 
<br />
 +
 
==Operators==
 
==Operators==
  
Line 623: Line 912:
  
 
==Functions and Methods==
 
==Functions and Methods==
 +
 +
 +
<br />
 +
===How to define a Function===
 +
 +
<source lang="python">
 +
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))
 +
</source>
 +
 +
 +
<source lang="python">
 +
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())
 +
</source>
  
  
Line 667: Line 991:
 
!Example
 
!Example
 
|-
 
|-
| rowspan="7" |'''Built-in functions'''
+
| rowspan="7" |<h5 style="text-align:left">Built-in functions</h5>
 
https://docs.python.org/3/library/functions.html
 
https://docs.python.org/3/library/functions.html
  
Line 701: Line 1,025:
 
|<code>len('Hello!')</code>
 
|<code>len('Hello!')</code>
 
|-
 
|-
| rowspan="6" |'''String methods'''
+
| rowspan="6" |<h5 style="text-align:left">String methods</h5>
 
https://www.w3schools.com/python/python_ref_string.asp
 
https://www.w3schools.com/python/python_ref_string.asp
 
|'''<code>a.lower()</code>'''
 
|'''<code>a.lower()</code>'''
Line 730: Line 1,054:
 
<code>' '.join(a)</code>
 
<code>' '.join(a)</code>
 
|-
 
|-
| rowspan="4" |'''Methods fo Lists'''
+
| rowspan="4" |<h5 style="text-align:left">List methods</h5>
 
https://docs.python.org/3/tutorial/datastructures.html
 
https://docs.python.org/3/tutorial/datastructures.html
  
Line 753: Line 1,077:
 
|<code>dog.clear()</code>
 
|<code>dog.clear()</code>
 
|-
 
|-
| rowspan="3" |'''Methods for Dictionaries'''
+
| rowspan="3" |<h5 style="text-align:left">Dictionaries methods</h5>
  
 
https://www.w3schools.com/python/python_ref_dictionary.asp
 
https://www.w3schools.com/python/python_ref_dictionary.asp
Line 768: Line 1,092:
 
|
 
|
 
|-
 
|-
|'''Python Tuple Methods'''
+
|<h5 style="text-align:left">Tuple methods</h5>
  
 
https://www.w3schools.com/python/python_ref_tuple.asp
 
https://www.w3schools.com/python/python_ref_tuple.asp
Line 775: Line 1,099:
 
|
 
|
 
|-
 
|-
|'''Python Set Methods'''
+
|<h5 style="text-align:left">Set methods</h5>
 
https://www.w3schools.com/python/python_ref_set.asp
 
https://www.w3schools.com/python/python_ref_set.asp
 
|
 
|
Line 781: Line 1,105:
 
|
 
|
 
|-
 
|-
|'''Python File Methods'''
+
|<h5 style="text-align:left">File methods</h5>
 
https://www.w3schools.com/python/python_ref_file.asp
 
https://www.w3schools.com/python/python_ref_file.asp
 
|
 
|
Line 787: Line 1,111:
 
|
 
|
 
|}
 
|}
 
 
<br />
 
 
===How to define a Function===
 
 
<source lang="python">
 
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))
 
</source>
 
 
 
<source lang="python">
 
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())
 
</source>
 
  
  
Line 841: Line 1,129:
 
<br />
 
<br />
  
==OOP with Python==
+
==Some example codes==
https://python.swaroopch.com/oop.html
 
  
  
 
<br />
 
<br />
===The ''self''===
+
===Factorial function using recursion===
Class methods have only one specific difference from ordinary functions - they must have an extra first parameter 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'''''.
+
<span style="background:#E6E6FA; color:red">'''A VERY VERY NICE example of recursion is the factorial function:'''</span>
 
+
<syntaxhighlight lang="python3">
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.
+
Example:
 
+
4! = 4 * 3!
This also means that if you have a method which takes no arguments, then you still have to have one argument - the self.
+
3! = 3 * 2!
 
+
2! = 2 * 1
<syntaxhighlight lang="python">
+
Replacing the calculated values gives us the following expression
class Person:
+
4! = 4 * 3 * 2 * 1
    def say_hi(self):
 
        print('Hello, how are you?')
 
 
 
p = Person()
 
p.say_hi()
 
# The previous 2 lines can also be written as
 
# Person().say_hi()
 
</syntaxhighlight>
 
 
 
 
 
<br />
 
 
 
===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.
 
 
 
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.
 
 
 
Example (save as oop_init.py):
 
 
 
<syntaxhighlight lang="python">
 
class Person:
 
    def __init__(self, name):
 
        self.name = name
 
 
 
    def say_hi(self):
 
        print('Hello, my name is', self.name)
 
 
 
p = Person('Swaroop')
 
p.say_hi()
 
# The previous 2 lines can also be written as
 
# Person('Swaroop').say_hi()
 
</syntaxhighlight>
 
 
 
Output:
 
$ python oop_init.py
 
Hello, my name is Swaroop
 
 
 
 
 
<br />
 
===Class And Object Variables===
 
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.
 
 
 
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.
 
 
 
Instead of Robot.population, we could have also used self.__class__.population because every object refers to its class via the self.__class__ attribute
 
 
 
'''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'''
 
 
 
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.
 
 
 
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:
 
 
 
how_many = classmethod(how_many)
 
 
 
'''Docstrings:'''
 
 
 
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__
 
print(Robot.__doc__)
 
print(Robot.say_hi.__doc__)
 
 
 
 
 
<syntaxhighlight lang="python">
 
class Robot:
 
    # Docstrings
 
    """Represents a robot, with a name."""
 
 
 
    # A class variable, counting the number of robots
 
    population = 0
 
 
 
    def __init__(self, name):
 
        # Docstrings
 
        """Initializes the data."""
 
        self.name = name
 
        print("(Initializing {})".format(self.name))
 
 
 
        # When this person is created, the robot
 
        # adds to the population
 
        Robot.population += 1
 
 
 
    def die(self):
 
        """I am dying."""
 
        print("{} is being destroyed!".format(self.name))
 
 
 
        Robot.population -= 1
 
 
 
        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):
 
        """Greeting by the robot.
 
 
 
        Yeah, they can do that."""
 
        print("Greetings, my masters call me {}.".format(self.name))
 
 
 
    @classmethod
 
    def how_many(cls):
 
        """Prints the current population."""
 
        print("We have {:d} robots.".format(cls.population))
 
 
 
 
 
droid1 = Robot("R2-D2")
 
droid1.say_hi()
 
Robot.how_many()
 
 
 
droid2 = Robot("C-3PO")
 
droid2.say_hi()
 
Robot.how_many()
 
 
 
print("\nRobots can do some work here.\n")
 
 
 
print("Robots have finished their work. So let's destroy them.")
 
droid1.die()
 
droid2.die()
 
 
 
Robot.how_many()
 
 
 
print(Robot.__doc__)
 
print(Robot.say_hi.__doc__)
 
 
</syntaxhighlight>
 
</syntaxhighlight>
  
Output:
 
$ 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.
 
 
 
<br />
 
 
===Inheritance===
 
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'''.
 
 
We will now see this example as a program (save as oop_subclass.py):
 
 
<syntaxhighlight lang="python">
 
class SchoolMember:
 
    '''Represents any school member.'''
 
    def __init__(self, name, age):
 
        self.name = name
 
        self.age = age
 
        print('(Initialized SchoolMember: {})'.format(self.name))
 
 
    def tell(self):
 
        '''Tell my details.'''
 
        print('Name:"{}" Age:"{}"'.format(self.name, self.age), end=" ")
 
 
 
class Teacher(SchoolMember):
 
    '''Represents a teacher.'''
 
    def __init__(self, name, age, salary):
 
        SchoolMember.__init__(self, name, age)
 
        self.salary = salary
 
        print('(Initialized Teacher: {})'.format(self.name))
 
 
    def tell(self):
 
        SchoolMember.tell(self)
 
        print('Salary: "{:d}"'.format(self.salary))
 
 
 
class Student(SchoolMember):
 
    '''Represents a student.'''
 
    def __init__(self, name, age, marks):
 
        SchoolMember.__init__(self, name, age)
 
        self.marks = marks
 
        print('(Initialized Student: {})'.format(self.name))
 
 
    def tell(self):
 
        SchoolMember.tell(self)
 
        print('Marks: "{:d}"'.format(self.marks))
 
 
t = Teacher('Mrs. Shrividya', 40, 30000)
 
s = Student('Swaroop', 25, 75)
 
  
# prints a blank line
+
<syntaxhighlight lang="python3">
print()
+
def factorial(n):
 
+
    if n == 1:
members = [t, s]
+
        return 1
for member in members:
+
     else:
     # Works for both Teachers and Students
+
        return n * factorial(n-1)
    member.tell()
 
 
</syntaxhighlight>
 
</syntaxhighlight>
 
Output:
 
 
$ python oop_subclass.py
 
(Initialized SchoolMember: Mrs. Shrividya)
 
(Initialized Teacher: Mrs. Shrividya)
 
(Initialized SchoolMember: Swaroop)
 
(Initialized Student: Swaroop)
 
 
Name:"Mrs. Shrividya" Age:"40" Salary: "30000"
 
Name:"Swaroop" Age:"25" Marks: "75"
 
 
 
<br />
 
 
==Some example codes==
 
  
  
Line 1,079: Line 1,160:
  
 
<br />
 
<br />
==Python Web Development==
+
==[[Manim]]==
https://www.fullstackpython.com/web-development.html
 
 
 
Web Frameworks for Python:
 
 
 
https://wiki.python.org/moin/WebFrameworks
 
 
 
https://fr.wikipedia.org/wiki/Liste_de_frameworks_Python
 
 
 
Ejemplos de Web Applications in Python: https://wiki.python.org/moin/WebApplications
 
 
 
Complete Python Web Course (15€): https://www.udemy.com/the-complete-python-web-course-learn-by-building-8-apps/
 
 
 
 
 
<br />
 
===Frameworks===
 
 
 
 
 
<br />
 
====Django====
 
Página oficial: https://www.djangoproject.com/
 
 
 
Documentación: https://docs.djangoproject.com/en/1.11/
 
 
 
 
 
<br />
 
=====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
 
 
 
Aquí se muestran distintas formas de instalar django: https://www.howtoforge.com/tutorial/how-to-install-django-on-ubuntu/
 
 
 
 
 
<br />
 
======Prerequisitos======
 
 
 
'''1. Install Python'''
 
 
 
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'''
 
 
 
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'''
 
 
 
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.
 
 
 
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.
 
 
 
'''4. Remove any old versions of Django'''
 
 
 
If you are upgrading your installation of Django from a previous version, you will need to uninstall the old Django version before installing the new version.
 
 
 
If you installed Django using pip or easy_install previously, installing with pip or easy_install again will automatically take care of the old version, so you don’t need to do it yourself.
 
 
 
If you previously installed Django using python setup.py install, uninstalling is as simple as deleting the django directory from your Python site-packages. To find the directory you need to remove, you can run the following at your shell prompt (not the interactive Python prompt):
 
 
 
$ python -c "import django; print(django.__path__)"
 
 
 
 
 
<br />
 
======Install the Django code======
 
 
 
'''<u>1- Installing an official release with pip</u>'''
 
 
 
'''1. Install pip.'''
 
 
 
https://www.howtoforge.com/tutorial/how-to-install-django-on-ubuntu/
 
 
 
The easiest is to use the standalone pip installer. If your distribution already has pip installed, you might need to update it if it’s outdated. If it’s outdated, you’ll know because installation won’t work.
 
 
 
Pip is a package management system for python. Python has a central package repository from which we can download the python package. It's called Python Package Index (PyPI).
 
 
 
In this tutorial, we will use python 3 for django as recommended by the django website. Next, we will install pip for python 3 from the ubuntu repository with this apt command:
 
 
 
apt-get install python3-pip
 
 
 
The installation will add a new binary file called 'pip3'. To make it easier to use pip, I will create a symlink for pip3 to pip:
 
 
Para saber donde se encuentra el ejecutable pip3:
 
which pip3
 
 
 
Luego creamos el symlink:
 
ln -s /usr/bin/pip3 /usr/bin/pip
 
 
 
Now check the version :
 
pip -V
 
 
 
Para actualizar pip a su más reciente versión:
 
pip install --upgrade pip
 
 
 
 
 
'''2. Installer virtualenv avec pip'''
 
 
 
Este programa permite crear un '''python virtual environment'''.
 
 
 
http://python-guide-pt-br.readthedocs.io/en/latest/dev/virtualenvs/
 
 
 
Take a look at virtualenv and virtualenvwrapper. These tools provide isolated Python environments, which are more practical than installing packages systemwide. They also allow installing packages without administrator privileges. The contributing tutorial walks through how to create a virtualenv on Python 3.
 
 
 
virtualenv is a tool to create isolated Python environments. Virtualenv creates a folder which contains all the necessary executables to use the packages that a Python project would need.
 
 
 
Install virtualenv via pip:
 
$ pip install virtualenv
 
 
 
Test your installation
 
$ virtualenv --version
 
 
 
Create a virtual environment for a project:
 
$ cd my_project_folder
 
$ virtualenv my_project
 
 
 
O si estamos dentro del directorio donde queremos crear el virtual environment:
 
$ virtualenv .
 
 
 
You can also use the Python interpreter of your choice (like python2.7).
 
$ virtualenv -p /usr/bin/python2.7 my_project
 
 
 
Then, to begin using the virtual environment, it needs to be activated:
 
$ source my_project/bin/activate
 
 
 
The name of the current virtual environment will now appear on the left of the prompt (e.g. (my_project)Your-Computer:your_project UserName$) to let you know that it’s active. From now on, any package that you install using pip will be placed in the my_project folder, isolated from the global Python installation.
 
 
 
Install packages as usual, for example:
 
pip install django==1.11
 
 
 
If you are done working in the virtual environment for the moment, you can deactivate it:
 
$ deactivate
 
 
 
This puts you back to the system’s default Python interpreter with all its installed libraries.
 
 
 
To delete a virtual environment, just delete its folder. (In this case, it would be rm -rf my_project.)
 
 
 
 
 
In order to keep your environment consistent, it’s a good idea to “freeze” the current state of the environment packages. To do this, run
 
$ pip freeze > requirements.txt
 
 
 
This will create a requirements.txt file, which contains a simple list of all the packages in the current environment, and their respective versions. You can see the list of installed packages without the requirements format using “pip list”. Later it will be easier for a different developer (or you, if you need to re-create the environment) to install the same packages using the same versions:
 
 
 
$ pip install -r requirements.txt
 
 
 
 
 
'''3. Install Django with Pip'''
 
 
 
After you’ve created and activated a virtual environment, enter the command:
 
 
 
pip install django==1.11 (ejecutarlo dentro del virtual environment)
 
 
 
Para ver la versión de '''django:'''
 
python
 
import django
 
print(django.get_version())
 
 
 
o a través de:
 
django-admin --version
 
 
 
'''<u>2- Installing a distribution-specific package</u>'''
 
 
 
https://code.djangoproject.com/wiki/Distributions
 
 
 
Check the distribution specific notes to see if your platform/distribution provides official Django packages/installers. Distribution-provided packages will typically allow for automatic installation of dependencies and easy upgrade paths; however, these packages will rarely contain the latest release of Django.
 
 
 
En Ubuntu:
 
sudo apt-get install python3-django
 
 
 
 
 
<br />
 
=====Crear un proyecto django=====
 
https://docs.djangoproject.com/en/1.11/intro/tutorial01/
 
 
 
https://www.youtube.com/watch?v=oRGK9klCn00#t=107.337193
 
 
 
https://www.youtube.com/watch?v=kl3c00dq6BI&t=30s
 
 
 
Primero es apropiado crear un nuevo proyecto '''Sublime Text''' que contenga el directorio correspondiente a nuestro virtual environment. Ver [[Linux#Crear un proyecto en Sublime Text|Crear un proyecto en Sublime Text]]
 
 
 
Si hemos instalado django en un virtual envirnment, vamos al virtual environment (si no está activado el virtual environment, debemos hacerlo a través de "source bin/activate") (Ver [[Python#Instalación de django|Instalación de django]]) y ejecutamos el comando:
 
django-admin.py startproject nombre_proyecto
 
 
 
Si lo hemos instalado de forma global a través de un distribution-specific package, go into any directory where you’d like to store your code, then run the following command:
 
django-admin startproject nombre_proyecto
 
 
 
Vemos que la diferencia entre la instalación global y la instalación en el virtual environment es que en esta última el comando contiene la extensión .py.
 
 
 
 
 
Esto creará un directorio llamado "nombre_proyecto" dentro del cual se encuentra otro directorio con el mismo nombre. Se recomienda renombrar el directorio padre como, por ejemplo, "src".
 
mv nombre_proyecto src
 
 
 
Luego:
 
cd src
 
python manage.py makemigrations
 
python manage.py migrate
 
 
 
By running makemigrations, you’re telling Django that you’ve made some changes to your models (in this case, you’ve made new ones) and that you’d like the changes to be stored as a migration.
 
 
 
The migrate command looks at the INSTALLED_APPS setting and creates any necessary database tables according to the database settings in your mysite/settings.py file and the database migrations shipped with the app (we’ll cover those later).
 
 
 
'''Creación del superusuario:'''
 
 
 
Dentro del directorio src:
 
python manage.py createsuperuser
 
 
 
Luego podemos comprobar que nuestro proyecto django está corriendo correctamente ejecutando:
 
  python manage.py runserver
 
Lo cual debe imprimir una línea como la siguiente:
 
Starting development server at http://127.0.0.1:8000/
 
 
 
Si copiamos http://127.0.0.1:8000/ en nuestro navegador internet, se abrirá una página que dice:
 
It worked!
 
Congratulations on your first Django-powered page
 
 
 
Podemos también ingresar a:
 
http://127.0.0.1:8000/admin
 
Lo cual nos lleva hacia la página de administración de django. De hecho, '''esta aplicación''' corresponde con la orden:
 
INSTALLED_APPS = [
 
    'django.contrib.admin'
 
que se encuentra en '''settings.py'''. Si queremos ver el código fuente de '''django.contrib.admin''' podemos simplemente ir a google y colocar: django.contrib.admin code. Lo cual nos llevará a esta página: https://github.com/django/django/tree/master/django/contrib/admin en donde podemos ver todos los archivos que conforman la aplicación '''django.contrib.admin'''
 
 
 
Viendo estos códigos podemos entender y aprender a construir aplicaciones de este tipo.
 
 
 
Luego de detener la ejecución del comando '''runserver''' ya no podremos ingresar a: http://127.0.0.1:8000/
 
 
 
Como se mencionó, '''django.contrib.admin''' es un ejemplo de una aplicación django. Ahora, queremos crear nuestra propia aplicación. Para ello ejecutamos (en src):
 
python manage.py startapp nombre_app shortener
 
 
 
Vamos a crear una aplicación llamada shortener:
 
python manage.py startapp shortener
 
 
 
https://www.youtube.com/watch?v=atNBuAjCDAs&t=306s
 
 
 
 
 
<br />
 
======Models======
 
Philosophy
 
 
 
A model is the single, definitive source of truth about your data. It contains the essential fields and behaviors of the data you’re storing. Django follows the DRY Principle. The goal is to define your data model in one place and automatically derive things from it.
 
 
 
En django se utiliza '''Models''' to map to the database. Es decir, debemos escribir un código en los Models to make a place to store our data.
 
 
 
Podríamos decir que un Modèle Django est un type particulier d'objet que nos permite interactuar con la base de datos.
 
 
 
'''Crear un Model'''
 
 
 
Para crear un model nos vamos al archivo '''models.py''' que ha sido creado dentro del directorio correspondiente a nuestra App (shorterner).
 
 
 
Este archivo luce así:
 
 
 
from django.db import models
 
 
# Create your models here.
 
class KirrURL(models.Model): # Creamos la clase KirrURL(cualquier nombre) that inherits(que proviene, que hereda) from models.Model
 
    url = models.CharFied(max_length=220, ) # Creamos el campo
 
    def __str__(self): # Definimos una función str
 
          return str(self.url)
 
     
 
 
 
Luego tenemos que adicionar este modelo que hemos creado a admin.py. Para ello, nos vamos a dicho archivo:
 
 
 
from django.contrib import admin
 
 
 
# Register your models here.
 
from .models import KirrURL
 
 
 
admin.site.register(KirrURL)
 
 
 
 
 
Luego tenemos que colocar neustra App (shortener) en '''INSTALLET_APPS''' del archivo '''settings.py'''.
 
 
 
INSTALLED_APPS = [
 
    'django.contrib.admin',
 
    'django.contrib.auth',
 
    'django.contrib.contenttypes',
 
    'django.contrib.sessions',
 
    'django.contrib.messages',
 
    'django.contrib.staticfiles',
 
       
 
    # Mis Apps:
 
    'shortener',
 
]
 
 
 
Luego debemos correr:
 
python manage.py makemigrations
 
python manage.py migrate
 
  
  
 
<br />
 
<br />
====Flask====
 

Latest revision as of 14: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