Introduction to Python/it: Difference between revisions

From FreeCAD Documentation
No edit summary
No edit summary
Line 40: Line 40:
Si ottiene una lunga e completa descrizione di tutto quello che può fare il comando print.
Si ottiene una lunga e completa descrizione di tutto quello che può fare il comando print.


Ora che si ha il controllo totale dell'interprete, si può cominciare con le cose significative.
Now that we totally dominate our interpreter, we can begin with the serious stuff.


===Variabili===
===Variabili===

Revision as of 20:32, 12 June 2017

Questo è una breve guida realizzata per chi si avvicina per la prima volta a Python. Python è un linguaggio di programmazione multi-piattaforma open-source. Python dispone di numerose funzionalità che lo rendono molto diverso dagli altri comuni linguaggi di programmazione, ed è facilmente accessibile ai nuovi utenti:

  • È stato progettato appositamente per essere letto facilmente dalle persone, quindi è molto facile da imparare e da capire.
  • È interpretato, ciò significa che, a differenza dei linguaggi compilati come il C, non è necessario compilare il programma prima di poterlo eseguire. Quando si desidera, il codice che si scrive può essere eseguito immediatamente, riga dopo riga. Siccome si procede gradualmente, passo dopo passo, è facile impararlo e trovare gli eventuali errori nel codice.
  • Può essere incorporato in altri programmi per essere usato come linguaggio di script. FreeCAD ha un interprete Python integrato, così, in FreeCAD, è possibile scrivere dei codici Python che manipolano parti di FreeCAD, ad esempio per creare la geometria. Questo è estremamente performante, perché invece di premere semplicemente un pulsante denominato "Crea sfera", che un programmatore ha messo a disposizione, si ha la libertà di creare facilmente dei propri strumenti per produrre una particolare geometria desiderata.
  • È estensibile. Si possono inserire facilmente dei nuovi moduli nella propria installazione di Python ed estenderne le funzionalità. Ad esempio, esistono moduli Python che permettono di leggere e scrivere le immagini jpg, di comunicare con Twitter, di programmare le operazioni del proprio sistema operativo, ecc.

Ora, mettiamoci al lavoro! Ricordare che ciò che verrà dopo è solamente una semplice introduzione e non un tutorial completo. Ma la speranza è che dopo si avranno basi sufficienti per esplorare più in profondità i meccanismi di FreeCAD.

L'interprete

Di solito, per scrivere programmi per computer, basta aprire un editor di testo (o l'ambiente di programmazione preferito che, in genere, è un editor di testo con strumenti aggiuntivi), scrivere il programma, quindi compilarlo ed eseguirlo. Il più delle volte si fanno degli errori di scrittura, per cui il programma non funziona, e si ottiene un messaggio di errore che dà informazioni su cosa è andato storto. Quindi si ritorna all'editor di testo, si correggono gli errori, si esegue di nuovo, e così via fino a quando il programma funziona bene.

In Python, l'intero processo, può essere eseguito in modo trasparente all'interno del suo interprete. L'interprete Python è una finestra con un prompt dei comandi, dove si può digitare direttamente il codice Python. Se si installa Python sul ​​proprio computer (scaricarlo dal sito web di Python se lavorate su Windows o Mac, installarlo dal repository dei pacchetti se utilizzate GNU/Linux), si avrà un interprete Python nel menu di avvio. FreeCAD dispone di un proprio interprete Python visualizzato nella sua finestra inferiore:

Se non è visibile, cliccare su Visualizza → Viste → Console Python.

L'interprete mostra la versione di Python, quindi il simbolo >>>, che è il suo prompt dei comandi, cioè, dove si deve inserire il codice Python. Scrivere il codice nell'interprete è semplice: ogni riga è una istruzione. Quando si preme Invio, la riga di codice viene eseguita (dopo essere stata istantaneamente e invisibilmente compilata). Ad esempio, provare a scrivere questo:

print "hello"

per Python print è una speciale parola chiave che, ovviamente, serve per stampare qualcosa sullo schermo. Quando si preme Invio, l'operazione viene eseguita, e viene stampato il messaggio "ciao". Se si commette un errore, provare, per esempio, a scrivere:

print hello

Python dice che non conosce ciao. I caratteri " " specificano che il contenuto è una stringa. In gergo tecnico, una stringa è semplicemente un pezzo di testo. Senza i segni ", la parola ciao viene vista come una specificazione del comando di stampa, cioè come una speciale parola chiave di Python, e non come un testo. Il fatto importante è che l'errore viene immediatamente notificato. Premendo la freccia verso l'alto (o, nell'interprete di FreeCAD, CTRL + freccia su), si può tornare all'ultimo comando scritto e correggerlo.

L'interprete Python possiede anche un sistema di aiuto incorporato. Provare a digitare:

help

oppure, ad esempio, se non si riesce a capire cosa è andato storto con il precedente comando print ciao, e si desiderano delle informazioni specifiche sul comando "print" digitare:

help("print")

Si ottiene una lunga e completa descrizione di tutto quello che può fare il comando print.

Ora che si ha il controllo totale dell'interprete, si può cominciare con le cose significative.

Variabili

Of course, printing "hello" is not very interesting. More interesting is printing stuff you didn't know before, or let Python find for you. That's where the concept of the variable comes in. A variable is simply a value that you store under a name. For example, type this:

a = "hello"
print a

I guess you understood what happened, we "saved" the string "hello" under the name "a." Now, "a" is not an unknown name any more! We can use it anywhere, for example in the print command. We can use any name we want, just follow some simple rules, like not using spaces or punctuation. For example, we could write:

hello = "my own version of hello"
print hello

See? now hello is not an undefined word any more. What if, by terrible bad luck, we choose a name that already exists in Python? Let's say we want to store our string under the name "print":

print = "hello"

Python is very intelligent and will tell us that this is not possible. It has some "reserved" keywords that cannot be modified. But our variables can be modified any time, that's why they are called variables, the contents can vary. For example:

myVariable = "hello"
print myVariable
myVariable = "good bye"
print myVariable

Il valore di myVariable è stato cambiato. Le variabili possono anche essere copiate:

var1 = "hello"
var2 = var1
print var2

Note that it is important to give meaningful names to your variables. After a while you won't remember what your variable named "a" represents. But if you named it, for example myWelcomeMessage, you'll easily remember its purpose. Plus your code is a step closer to being self-documenting.

Case is very important. myVariable is not the same as myvariable, the difference in the upper/lower case v. If you were to enter print myvariable it would come back with an error as not defined.

Numeri

Of course you must know that programming is useful to treat all kinds of data, and especially numbers, not only text strings. One thing is important, Python must know what kind of data it is dealing with. We saw in our print hello example, that the print command recognized our "hello" string. That is because by using the ", we told specifically the print command what follows next is a text string.

We can always check the data type of a variable with the special Python keyword type:

myVar = "hello"
type(myVar)

It will tell us the contents of myVar is 'str', short for string in Python jargon. We have also other basic types of data, such as integer and float numbers:

firstNumber = 10
secondNumber = 20
print firstNumber + secondNumber
type(firstNumber)

This is much more interesting, isn't it? Now we have a powerful calculator! Look at how well it worked, Python knows that 10 and 20 are integer numbers. So they are stored as "int", and Python can do with them everything it can do with integers. Look at the results of this:

firstNumber = "10"
secondNumber = "20"
print firstNumber + secondNumber

See? We forced Python to consider that our two variables are not numbers but mere pieces of text. Python can add two pieces of text together, but it won't try to find out any sum. But we were talking about integer numbers. There are also float numbers. The difference is that integer numbers don't have decimal part, while float numbers can have a decimal part:

var1 = 13
var2 = 15.65
print "var1 is of type ", type(var1)
print "var2 is of type ", type(var2)

I numeri Int e Float possono essere mescolati tra di loro senza problemi:

total = var1 + var2
print total
print type(total)

Of course the total has decimals, right? Then Python automatically decided that the result is a float. In several cases such as this one, Python automatically decides what type to use. In other cases it doesn't. For example:

varA = "hello 123"
varB = 456
print varA + varB

This will give us an error, varA is a string and varB is an int, and Python doesn't know what to do. However, we can force Python to convert between types:

varA = "hello"
varB = 123
print varA + str(varB)

Ora entrambi sono stringhe, e l'operazione funziona! Notare che, con questi comandi, varB è convertita in "stringa" solo al momento della stampa, però varB originale non viene modificata. Per trasformare varB permanentemente in una stringa, si deve fare:

varB = str(varB)

Inoltre è possibile usare int() e float() per convertire in int e in float:

varA = "123"
print int(varA)
print float(varA)

Note sui comandi Python

You must have noticed that in this section we used the print command in several ways. We printed variables, sums, several things separated by commas, and even the result of other Python command such as type(). Maybe you also saw that doing those two commands,

type(varA)
print type(varA)

have exactly the same result. That is because we are in the interpreter, and everything is automatically printed. When we write more complex programs that run outside the interpreter, they won't print automatically, so we'll need to use the print command. From now on, let's stop using it here, it'll go faster. So we can simply write:

myVar = "hello friends"
myVar

You must have seen that most of the Python commands (or keywords) type(), int(), str(), etc. have parenthesis to limit the command contents. The only exception is the print command, which in fact is not really an exception, as it also works normally: print("hello"). However, since it is used often, the Python designers allowed a simpler version.

Liste

Another interesting data type is a list. A list is simply a collection of other data. The same way that we define a text string by using " ", we define a list by using [ ]:

myList = [1,2,3]
type(myList)
myOtherList = ["Bart", "Frank", "Bob"]
myMixedList = ["hello", 345, 34.567]

You see that it can contain any type of data. Lists are very useful because you can group variables together. You can then do all kinds of things within that group, for example counting them:

len(myOtherList)

o recuperare un elemento da una lista:

myName = myOtherList[0]
myFriendsName = myOtherList[1]

You see that while the len() command returns the total number of items in a list, their "position" in the list begins with 0. The first item in a list is always at position 0, so in our myOtherList, "Bob" will be at position 2. We can do much more with lists, you can read here, such as sorting contents, removing or adding elements.

A funny and interesting thing: a text string is very similar to a list of characters! Try doing this:

myvar = "hello"
len(myvar)
myvar[2]

Usually, what you can do with lists can also be done with strings. In fact both lists and strings are sequences.

Outside strings, ints, floats and lists, there are more built-in data types, such as dictionaries, or you can even create your own data types with classes.

Indentazione

Un tipico uso della lista consiste nel navigare al suo interno e di operare con i suoi elementi. Per esempio osservare questo:

alldaltons = ["Joe", "William", "Jack", "Averell"]
for dalton in alldaltons:
   print dalton + " Dalton"

We iterated (programming jargon) through our list with the "for ... in ..." command and did something with each of the items. Note the special syntax: the for command terminates with : indicating the following will be a block of one of more commands. In the interpreter, immediately after you enter the command line ending with :, the command prompt will change to ... which means Python knows that a colon (:) ended line has happened and more is coming.

How will Python know how many of the next lines will be to be executed inside the for...in operation? For that, Python uses indentation. That is, your next lines won't begin immediately. You will begin them with a blank space, or several blank spaces, or a tab, or several tabs. Other programming languages use other methods, like putting everything inside parenthesis, etc. As long as you write your next lines with the same indentation, they will be considered part of the for-in block. If you begin one line with 2 spaces and the next one with 4, there will be an error. When you finished, just write another line without indentation, or simply press Enter to come back from the for-in block

Indentation is cool because it aids in program readability. If you use large indentations (for example use tabs instead of spaces because it's larger), when you write a big program you'll have a clear view of what is executed inside what. We'll see that commands other than for-in, can have indented blocks of code too.

For-in commands can be used for many things that must be done more than once. It can, for example, be combined with the range() command:

serie = range(1,11)
total = 0
print "sum"
for number in serie:
   print number
   total = total + number
print "----"
print total

(If you have been running the code examples in an interpreter by Copying and Pasting, you will find the previous block of text will throw an error. Instead, copy to the end of the indented block, i.e. the end of the line total = total + number and then paste to the interpreter. In the interpreter issue an <enter> until the three dot prompt disappears and the code runs. Then copy the final two lines into the interpreter followed by one or more <enter> The final answer should appear.)

If you would type into the interpreter help(range) you would see:

range(...)
    range(stop) -> list of integers
    range(start, stop[, step]) -> list of integers

Here the square brackets denote an optional parameter. However all are expected to be integers. Below we will force the range parameters to be an integer using int()

decimales = 1000                     # for 3 decimales 
#decimales = 10000                   # for 4 decimales ...
for i in range(int(0 * decimales),int(180 * decimales),int(0.5 * decimales)):
    print float(i) / decimales

O per operazioni più complesse tipo questa:

alldaltons = ["Joe", "William", "Jack", "Averell"]
for n in range(4):
   print alldaltons[n], " is Dalton number ", n

Come si vede, anche il comando range() ha la strana particolarità di iniziare con 0 (quando non si specifica il numero di partenza) e che il suo ultimo numero è uno in meno del numero finale specificato. Ciò, naturalmente, perché questo modo funziona bene con gli altri comandi di Python. Ad esempio:

alldaltons = ["Joe", "William", "Jack", "Averell"]
total = len(alldaltons)
for n in range(total):
   print alldaltons[n]

Un altro uso interessante dei blocchi indentati si ha con il comando if. Il comando if esegue un blocco di codice solo se una certa condizione è soddisfatta, ad esempio:

alldaltons = ["Joe", "William", "Jack", "Averell"]
if "Joe" in alldaltons:
   print "We found that Dalton!!!"

Naturalmente, questo esempio stampa sempre la prima frase, ma provare a sostituire la seconda riga con:

if "Lucky" in alldaltons:

Ora non viene più stampato nulla. Si può anche specificare una dichiarazione: else:

alldaltons = ["Joe", "William", "Jack", "Averell"]
if "Lucky" in alldaltons:
   print "We found that Dalton!!!"
else:
   print "Such Dalton doesn't exist!"

Funzioni

There are few standard Python commands. In the current version of Python, there are about 30, and we already know several of them. But imagine if we could invent our own commands? Well, we can, and it's extremely easy. In fact, most the additional modules that you can plug into your Python installation do just that, they add commands that you can use. A custom command in Python is called a function and is made like this:

def printsqm(myValue):
   print str(myValue)+" square meters"
 
printsqm(45)

(Another copy and paste error, only copy through the end of the indented section i.e. " square meters" Paste to the interpreter, and issue <enter> until the three dot prompt goes a way, then copy and paste the final line.)

Extremely simple: the def() command defines a new function. You give it a name, and inside the parenthesis you define arguments that we'll use in our function. Arguments are data that will be passed to the function. For example, look at the len() command. If you just write len() alone, Python will tell you it needs an argument. That is, you want len() of something, right? Then, for example, you'll write len(myList) and you'll get the length of myList. Well, myList is an argument that you pass to the len() function. The len() function is defined in such a way that it knows what to do with what is passed to it. Same as we did here.

The "myValue" name can be anything, and it will be used only inside the function. It is just a name you give to the argument so you can do something with it, but it also serves to tell the function how many arguments to expect. For example, if you do this:

printsqm(45,34)

Si ottiene un errore. La funzione è stata programmata per ricevere un solo argomento, ma ne ha ricevuto due, 45 e 34. In sostituzione, si può eseguire qualcosa di simile a:

def sum(val1,val2):
   total = val1 + val2
   return total

sum(45,34)
myTotal = sum(45,34)

Dove si crea una funzione che riceve due argomenti, li somma, e restituisce il valore. Ottenere qualcosa è molto utile, perché permette di utilizzare il risultato ottenuto e, ad esempio, memorizzarlo nella variabile myTotal. Naturalmente, visto che siamo nell'interprete e tutto quello che facciamo viene stampato, digitando:

sum(45,34)

will print the result on the screen, but outside the interpreter, since there is no print command inside the function, nothing would appear on the screen. You would need to:

print sum(45,34)

Per ulteriori informazioni sulle funzioni leggere qui.

Moduli

Ora che si ha un'idea di come funziona Python, serve una ultima cosa: Come lavorare con i file e i moduli.

Until now, we wrote Python instructions line by line in the interpreter, right? What if we could write several lines together, and have them executed all at once? It would certainly be handier for doing more complex things. And we could save our work too. Well, that too, is extremely easy. Simply open a text editor (such as the windows notepad, Linux gedit, emacs, or vi), and write all your Python lines, the same way as you write them in the interpreter, with indentations, etc. Then, save that file somewhere, preferably with a .py extension. That's it, you have a complete Python program. Of course, there are much better editors than notepad, but it is just to show you that a Python program is nothing else than a text file.

To make Python execute that program, there are hundreds of ways. In windows, simply right-click your file, open it with Python, and execute it. But you can also execute it from the Python interpreter itself. For this, the interpreter must know where your .py program is. In FreeCAD, the easiest way is to place your program in a place that FreeCAD's Python interpreter knows by default, such as FreeCAD's bin folder, or any of the Mod folders. (In Linux, you probably have a directory /home/<username>/.FreeCAD/Mod, let's add a subdirectory to that called scripts where we will put the text file.) Suppose we write a file like this:

def sum(a,b):
    return a + b

print "myTest.py succesfully loaded"

and we save it as myTest.py in our FreeCAD/bin directory (or on Linux to /home/<username>/.FreeCAD/Mod/scripts.) Now, let's start FreeCAD, and in the interpreter window, write:

import myTest

senza l'estensione. py. Questo comando esegue semplicemente il contenuto del file, riga per riga, esattamente come quando viene scritto nell'interprete. Viene creata la funzione somma, poi viene stampato il messaggio. Però c'è una grande differenza: il comando di importazione (import) serve non solo per eseguire i programmi contenuti in un file, come il nostro, ma anche per caricare le funzioni interne, in modo da renderle disponibili nell'interprete. I file, come il nostro, contenenti funzioni sono chiamati moduli.

Di solito, come si è fatto in precedenza, quando si scrive la funzione sum() nell'interprete, si digita semplicemente:

sum(14,45)

Invece, quando si importa un modulo contenente una funzione sum(), la sintassi è un po' diversa. Si scrive:

myTest.sum(14,45)

That is, the module is imported as a "container", and all its functions are inside. This is extremely useful, because we can import a lot of modules, and keep everything well organized. So, basically, everywhere you see something.somethingElse, with a dot in between, that means somethingElse is inside something.

We can also import our sum() function directly into the main interpreter space, like this:

from myTest import *
sum(12,54)

Basically all modules behave like that. You import a module, then you can use its functions: module.function(argument). Almost all modules do that: they define functions, new data types and classes that you can use in the interpreter or in your own Python modules, because nothing prevents you from importing other modules inside your module!

Un'ultima cosa estremamente utile. Come si fa per sapere quali moduli sono disponibili, quali funzioni sono al loro interno e come usarli (cioè, di che tipo di argomenti hanno bisogno)? Si è già visto che Python ha una funzione help(). Digitare:

help()
modules

Viene restituito un elenco di tutti i moduli disponibili. Digitare q per uscire dall'aiuto interattivo e importare qualsiasi di essi.

Si può anche sfogliare il contenuto del modulo tramite il comando dir():

import math
dir(math)

In questo caso, si vedono tutte le funzioni contenute nel modulo di matematica (il modulo math), come, ad esempio, cose con strani nomi __ doc__, __ FILE__, __ name__. L'oggetto doc__ __ è estremamente utile, è un testo di documentazione. Ogni funzione dei moduli (se fatti bene) ha un proprio __doc__ che spiega come usarla. Se, per esempio, si vuole sapere come usare la funzione sin (seno) contenuta all'interno del modulo math, basta digitare:

print math.sin.__doc__

(It may not be evident, but on either side of doc are two underscore characters.)

And finally one last little goodie: When we work on a new or existing module, it's best to replace the file extension with py such as: myModule.FCMacro => myModule.py. We often want to test it so we will load it as above.

import myModule
myModule.myTestFunction()

But what if we see that myTestFunction() doesn't work correctly? We go back to our editor and make changes. Then, instead of closing and reopening the python interpreter, we can simply update the module like this:

reload(myModule)

This file renaming is because Python doesn't know about the extension FCMacro.

However, there are two alternates: Inside the one macro use Python's exec or execfile functions.

f = open("myModule","r")
d = f.read()
exec d

oppure

execfile "myModule"

To share code across macros, you can access the FreeCAD or FreeCADGui module (or any other Python module) and set any attribute to it. This should survive the execution of the macro.

import FreeCAD
if hasattr(FreeCAD,"macro2_executed"):
    ...
else:
    FreeCAD.macro2_executed = True # you can assign any value because we only check for the existence of the attribute
    ... execute macro2

Iniziare con FreeCAD

Well, I think you now have a good idea of how Python works, and you can start exploring what FreeCAD has to offer. FreeCAD's Python functions are all well organized in different modules. Some of them are already loaded (imported) when you start FreeCAD. So, just do

dir()

e continuate a leggere in Script base in FreeCAD...

Of course, we saw here only a very small part of the Python world. There are many important concepts that we didn't mention. There are three very important Python reference documents on the net:

Be sure to bookmark them!