.feed-links {display:none !important;} -->

Install Python

 

Install python on Linux or MacOS

Linux Python

If you work in a Linux or MacOS environment : good news Python already installed!

Install python on Windows

If you are on Windows , change your operating system ...

Personally, I love working with Ubuntu , as a developer you really feel like you have your machine and everything is free. In addition, you will often have to migrate your work on a production server which can run on a linux distro. You should know that today more projects are hosted on linux servers than on proprietary licenses.

But if you still want to keep Windows - despite my best efforts to convert to the free world - you can download a python installation file at this address: Download Python

Python interpreter

 To use Python on Ubuntu for example, run a terminal:

Then run the "python" command:

You notice the 3 chevrons >>> , this means that the python interpreter is ready to receive instructions. Generally speaking, if you see the 3 chevrons symbol on a tutorial page, it means you need to run the code displayed in the python interpreter. For example, you can ask it to perform a simple addition:

Voila, you have understood the essence of what the python interpreter can be .

In some editors - Wing IDE for example - the python interpreter is directly included. I talk about it in the next chapter.

Python IDE Editors

 

The PyCharm IDE

PyCharm is quite simply the best IDE. Its free version is very complete and meets all the needs of a python developer.

PyCharm IDE python

Visual Studio Code

Visual Studio Code (or VSC) is a recent code editor (2015) it is excellent for your python projects but also javascript / coffeescript / etc.

Atom

Atom is an editor which will allow you to have some freedom in the configuration. It is not as complete as a PyCharm.

Sublime Text

Sublime text

So he's my little favorite. It is ultra light, it is beautiful, it is strong, it is powerful!

Sublime Text has a whole range of plugins that you will quickly be hooked on! Its basic version is free, a little alert will ask you from time to time if you want to buy a license to support the project but nothing forces you to do so.

Remember to install the packagecontrol which will allow you to install the tools necessary for your project

Here is a small list of the most useful shortcuts:

Ctrl + XDelete a row
Ctrl + PAllows you to browse any file
Ctrl + RMove the cursor to a function in the current file
Ctrl + LSelect the current line
Ctrl + DSelect the entire current word
Ctrl + Shift + DDuplicate the current row
Ctrl + MPoint the cursor to the other end of a function
Ctrl + GMove the cursor to line X of the file
Ctrl + Shift + TReopen the last closed file
CTRL + SHIFT + FSearch for files in a folder
CTRL + ALT + PProject switcher

VIM

VIM is a much more complete console-accessible editor than nano

sudo apt install vim

When you edit a file with VIM you are first in command mode, which allows you to manipulate the file. In fact you are not in a mode where you can directly write but where you can manipulate the data. For example the key will move you to the next word and will not write It's quite confusing at first. To enter text editing mode, you will need to press the key which will switch you to text editing mode.

Here is a small list of the actions most used in command mode in VIM:

i => Switch to the word insertion
: q! => Exit without saving
: qw => Exit after saving
: w => Save file
d $ => Delete the data until the end of the line
dw => Delete data until next word
de => Delete the current word
w => Go to next word
2w => Skip two words
2dw => Delete the last two words
0 => Go to start of line
u => Undo the last action
yy => Copy line
4yy => Copy 4 lines
p => Paste after
P => Insert before
Ctrl + R => Undoes the last undo
Ctrl + Z => Close
/ => Research
? => Search in the opposite direction
n => Next occurrence

Wing IDE editor

WingIDE is a very good editor - with integrated interpreter - for beginners in its free version.

WingIDE was designed by python developers for python developers primarily for teaching python. The free version obviously has fewer options than the professional version (the price remains quite low for the pro version: $ 45).

You can download the software in its free version here: IDE python WingIDE .

If you are in Ubuntu download the .deb , double click on the file and click on install . If you have dependency issues consider running the following command:

sudo  apt - get  install  - f

Here is an overview of the software:

Python editor

Modules and packages in python

 So far we have managed to create small pieces of code without much interest because very unambitious. The problem with the interpreter is that once it is closed your work is lost.

The idea of ​​a program is to save your work to a file and then run it. This increases your productivity but has many advantages such as massive copy and paste or just collaborative work. When code is saved in an executable file, we talk about script .

Create your first python script

First of all you must create a file with the extension .py - in our example it will be named fiche.py - in the folder you want (the location does not matter).

Then open the file.

Bonjour Monde

The traditional hello world is done as follows:

# coding: utf-8 
print ( "Hello world" )

The first line indicates that this is python code.
The second line indicates the type of encoding used. I always advise you whatever your project and your programming language to go through UTF-8 and the third line you already know.

Run a python script

To run a python script on ubuntu you just need to run the following command:

python  / path_to_your_script / form . py

Make the user interact

A program is not very interesting if the user cannot interact with it.

We will create a small script that asks the age of the user and we will display this value afterwards:

# coding: utf-8

age =  input ( "How old are you?:" ) 
print ( "You are% d years old"  % age)

Note that if you are working with python 2.7, it is impossible to pass data other than numeric to the function input , for python 2.7 we will prefer to use the function raw_input which does much the same thing.

Comments in python

Whether you are alone developing your scripts or with others, it will always be essential to comment on your work. For example if you are creating a function that spans hundreds of lines of code, it will be more efficient to write a small description of your function above it rather than having to re-read all the code to understand this function. months later.

Comments in python begin with the sign #

Example:

# coding: utf-8

# This function asks a question to the user 
# and this one must answer by a number obligatorily

age  =  input ( "How old are you?:" ) 
print ( "You are % d years old"  %  age )

Import features from other files

For the most ambitious projects, it will quickly be important to organize your work. The functions will multiply and it will be necessary to save them in separate files for more flexibility.

Let's create another file that we will name func.py in the same folder as the file fiche.py

func.py

# coding: utf-8

def  add_a ( v ): 
	return  v  +  1

fiche.py

# coding: utf-8

from  func  import  *

age  =  input ( "How old are you?:" ) 
print ( "You are % d years old"  %  age )

age_plus_un  =  add_un ( age )

print ( "In a year you will be % d years old"  %  age_plus_un )

Instructions, functions, modules, packages

We have therefore seen that when we combine functions in a file, we create a set of functions which we call " module ".

When we seek to group modules together, we speak of a package .

Create a package

To create your own package, first create in the same folder as your program - a folder with the name of your package. In our example, we will name it " utils ".

In this folder, let's create the following file: __init__.py , this tells python that this is a package . This file can be empty, only its presence is important.

Then create a file still in this utils directory that we will name for example " operations.py "

Content of your project file:

Contents of the dossier utils:

Now let's edit the file operations.py and create a new function

# coding: utf-8

def  add_two ( v ): 
	return  v  +  2

Then add a call to this function in the file fiche.py

# coding: utf-8

from  func  import  * 
from  utils.operations  import  add_two

age  =  input ( "How old are you?:" ) 
print ( "You are % d years old"  %  age )

age_plus_un  =  add_un ( age )

print ( "In a year you will be % d years old"  %  age_plus_un )

age_plus_deux  =  add_two ( age )

print ( "In a year you will be % d years old"  %  age_plus_deux )

So what do we notice? First we import a package with the keywords from and import , then to call a specific function, we go through the following hierarchy:

from  package.module  import  function

If you want to import all the functions of a module, you can indicate a star * which often means "ALL" in computer science.

Python modules

Here is a list of basic modules that you will have to use one day or another.

random: functions allowing to work with random values
math: all the functions useful for mathematical operations (cosine, sine, exp, etc.)
sys: system functions
os: functions allowing to interact with the operating system
time: functions for working over time
calendar: calendar functions
profile: functions used to analyze the execution of functions
urllib2: functions for retrieving information from the internet
re: functions allowing to work on regular expressions

Python file extensions

There are several file extensions that revolve around python:

.py -> editable script
.pyc -> compiled script
.pyw -> script executed without launching a terminal (under windows)

PEP 8 learn best practices for coding in python

 

What is PEP 8?

PEP 8 (for Python Extension Proposal) is a set of rules that allows code to be homogenized and best practices to be applied. The best known example is the war between developers over whether to indent code with spaces or with tabs. PEP 8 slices: the spaces win, 4 in number. End of the debate.

It is a very interesting logic for Python which wants to be a language "which is read" rather than "a language which is written". So yes this sentence does not mean anything but writing an understandable code for a machine is rather easy, but writing a code understandable by the greatest number of coders (of any level) is another story ...

PEP 8 makes it possible to establish rules and conventions to make it easier for the coder to read and thus make him less stressed and more productive. The advantage of PEP 8 makes it possible to embellish the code. So I still don't know if the code is embellished with PEP 8 or if making rules doesn't make the code without PEP 8 ugly. We can tell ourselves when reading a script that the author has not respected these basic rules and therefore is not a good coder. This is not necessarily the case but ...

More rules to learn?

It is not necessary to learn all the rules of PEP 8, I will list the most interesting rules here.

Note that a good IDE will help you write your code. It will highlight the inconsistencies and even offer to correct them. Tools like Black will help you get in shape, for example.

Encoding

For python 3: UTF-8 , yes the base. Is it still necessary to specify it? Never use anything other than utf-8.

Indentation

The indentation of your code must be 4 characters long. More is too much, less is not enough. On the side of coffeescript for example it's 2, it's ugly. Shame on them. It had to be written somewhere, here it is.

Layout code

79 characters per line, no more.

Writing in python is like writing some kind of Alexandrian poem. There is the substance but also the form. If you are a perfectionist, review your code, even for a single overflow character; it will not change the execution of your code, it will only waste your time,
but passion is passion, rules are rules.

Import

The imports are declared at the beginning of the script. It seems obvious, but it's always good to remember it. You can add it in a function as well (if you cannot do otherwise or for exceptional reasons) but after the docstring. Provide one line per import .

The spaces

So the spaces you have to be concise, avoid putting them there you don't have to:

name  =  'Batman'  # yes it's clean 
name = 'name'  # no it's ugly 
batmobile  [ 'color' ]  =  'black'  # no 
batmobile [ 'color' ]  =  'black'  # yes

Comment your code in English

We recommend that you comment on your code in English, so that you can share it with as many people as possible.

But if you are in a French-French team or if you are the only one working on your project, it is better to write good comments in French than bad in English.

Black, the uncompromising python code trainer

 black

Black, what is it?

Black is a python code trainer . Formatting your code is essential, as we saw in the previous chapter, writing your code must respect a certain number of visual rules. For example, the code must not exceed 79 characters.

It's essential ... but it's a waste of time.

To not waste this time, this precious time, delegate this task to a program! ... And this program is Black , your new best friend.

Why is Black so good?

It is always amazing how much we prefer his code to that of others. We have our little habits; and when we see the code of another developer, the first thing we see is not the quality of its content or the intelligence that it was able to put in a script coded in 10 lines whereas d 'others would have done it in 20. No. What we see first is that it has exceeded the maximum of 79 by 1 character, and there is a newline that was not needed.

We look at the form before the substance. It's like that.

Black will homogenize the shape of your code.

After finalizing your Python code , you run the Black mill and there, as if by magic, your code will be perfectly formatted. No more criticism of the form can be heard. The reader of your code will finally be able to devote himself directly to the content of your code.

Time saving

Beyond all the psychological and regulatory aspects, running Black at the end of your code will save you a lot of time both writing and reading. You will be used to the form, and if you work in a team of developers it is great fun to read code in a format you are familiar with.

Install Black

We use pip to install Black:

pip  install  black

Then in command line:

black  { your_file }