Difference between revisions of "Python"

From Sinfronteras
Jump to: navigation, search
(Definir una función)
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
 
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
  
Line 488: Line 490:
 
'''4. Remove any old versions of Django'''
 
'''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 are upgrading your installation of Django from a previ
 
 
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__)"
 
 
 
======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
 
 
 
=====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
 
 
 
======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
 
 
 
====Flask====
 

Revision as of 17:48, 18 April 2017

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

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://openclassrooms.com/courses/apprenez-a-programmer-en-python/les-structures-conditionnelles

http://www.enlistq.com/10-python-idioms-to-help-you-improve-your-code/

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://www.linkedin.com/pulse/python-top-10-programming-languages-year-2017-alok-kumar


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.
  • Il est possible d'associer des bibliothèques à Python afin d'étendre ses possibilités.
  • Il est portable, c'est à dire qu'il peut fonctionner sous différents systèmes d'exploitation (Windows, Linux, Mac OS X,…).

Instalación

Python est pré-installé sur la plupart des distributions Linux. Sinon:

Versión instalada

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.
>>>

Cambiar la versión por defecto

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 list all available python alternatives:

# update-alternatives --list 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:

# 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.


Ubuntu

apt-get install python3.x

Si se descarga:

  • 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).
  • 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).
  • 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

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).

Si, par exemple, vous avez installé Python 3.4, vous pouvez y accéder grâce à la commande

python3.4

Premiers pas avec l'interpréteur de commandes Python

Opérations courantes

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

Les types de données

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

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).

Les chaînes de caractères

On peut écrire une chaîne de caractères de différentes façons :

   entre guillemets ("ceci est une chaîne de caractères") ;
   entre apostrophes ('ceci est une chaîne de caractères') ;
   entre triples guillemets ("""ceci est une chaîne de caractères""").
   entre triples apostrophes (ceci est une chaîne de caractères).

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.

chaine = 'J\'aime le Python!'

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 « \\ »).

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 ».

>>> chaine3 = """Ceci est un nouvel
... essai sur plusieurs
... lignes"""
>>>

Vous pouvez utiliser, à la place des trois guillemets, trois apostrophes qui jouent exactement le même rôle.

Les booléens

>>> a = 0
>>> 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
>>> majeur = False
>>> if age >= 18:
>>>     majeur = True
>>>

Les mots-clés and, or et not

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:
    print("a n'est pas dans l'intervalle.")
else:
    print("a est dans l'intervalle.")


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 :

>>> majeur = False
>>> if majeur is not True:
...     print("Vous n'êtes pas encore majeur.")
... 
Vous n'êtes pas encore majeur.
>>>

Les opérateurs

« + » « - » « / »

>>> 3 + 4
7
>>> -2 + 93
91
>>> 9.5 + 2
11.5
>>> 3.11 + 2.08
5.1899999999999995
>>> 10 / 5
2.0
>>> 10 / 3
3.3333333333333335

« // » permet d'obtenir la partie entière d'une division (cociente)

>>> 10 // 3
3
>>> 10 // 4
2

« % », que l'on appelle le « modulo », permet de connaître le reste de la division (resto)

>>> 10%3
1

« += » « -= » « *= » « /= »

variable = variable + 1 

La operación anterior puede resumirse utilizando el operador +=:

variable += 1

Les opérateurs -=, *= et /= existent également, bien qu'ils soient moins utilisés.

Potencia

>>> 9**(1/2)
3.0
>>> pow(3,2)
9

Valor absoluto

>>> abs(-3.0)
3.0

Complejos

>>> complex(2,3)
(2+3j)
>>> complex(2,3)*complex(3,4)
(-6+17j)
>>> a=complex(3,5)
>>> a.real
3.0
>>> a.imag
5.0

Maximo y minimo

>>> max(3,45,6,7)
45
>>> min(32,23,2,13,4.3)
2

Redondeo

>>> round(34.5)
35.0
>>> round(35.345,1)
35.3

La clase math

>>> import math

Raiz cuadrada

>>> math.sqrt(2)
1.4142135623730951

Factorial

>>> math.factorial(5)
120

PI

>>> math.pi
3.1415926535897931

Funciones trigonométricas

>>> math.sin(math.pi)
1.2246063538223773e-16

Logaritmos

>>> math.log(11)
2.3978952727983707

Permutation

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 :

>>> a = 5
>>> b = 32
>>> a,b = b,a # permutation
>>> a
32
>>> b
5
>>>

Asignar un mismo valor a varias variables

On peut aussi affecter assez simplement une même valeur à plusieurs variables :

>>> x = y = 3
>>> x
3
>>> y
3

Couper une instruction Python, pour l'écrire sur deux lignes ou plus

>>> 1 + 4 - 3 * 19 + 33 - 45 * 2 + (8 - 3) \
... -6 + 23.5
-86.5
>>>

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

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.

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 :

nom_de_la_fonction(parametre_1,parametre_2,…,parametre_n)

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 :

type(nom_de_la_variable)

La fonction renvoie le type de la variable passée en paramètre.

>>> type(3)
<class 'int'>

print - input

>>> a=3
>>> b=4
// Las variables int deben ser delimitadas entre comas:
>>> print("a =",a,"et b =",b)
a = 6 et b = 4
>>> a='3'
>>> b='4'
// Las variables str pueden ser delimitadas entre comas o entre +:
>>> print("a = "+a+" et b = "+b)
a = 6 et b = 4
>>> print("Hello World !")
Hello World !


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'>

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

IF / ELSE / ELIF

>>> a = 5
>>> if a > 0:
...     print("a est supérieur à 0.") # Si no se coloca la identation dentro del if, se genera un error: IndentationError: expected an indented block
... 
a est supérieur à 0.


>>> age = 21
>>> if age >= 18:
...    print("Vous êtes majeur.")
... else:
...    print("Vous êtes mineur.")
... 
Vous êtes majeur.


>>> a=5
>>> if a > 0: # Positif
...      print("a est positif.")
... elif a < 0:
...      print("a est négatif.")
... else:
...      print("a est nul.")
... 
>>> a est positif.

Definir una función

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())

Python Web Development

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/

Frameworks

Django

Página oficial: https://www.djangoproject.com/

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

Aquí se muestran distintas formas de instalar django: https://www.howtoforge.com/tutorial/how-to-install-django-on-ubuntu/

Prerequisitos

1. Install Python

Si ya está instalado. Setup python 3 as Default Python version: Ver 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 previ