Introduction to Python/ro: Difference between revisions

From FreeCAD Documentation
No edit summary
No edit summary
(41 intermediate revisions by the same user not shown)
Line 14: Line 14:
De obicei, când scrieți programe de calculator, deschideți pur și simplu un editor de text sau mediul de programare special (care este, de obicei, un editor de text cu mai multe instrumente suplimentare), scrieți programul, apoi compilați și executați. În mod obișnuit, au fost făcute una sau mai multe erori la intrare, astfel încât programul dvs. nu va funcționa. S-ar putea să primiți chiar și un mesaj de eroare care să vă spună ce sa întâmplat. Apoi, reveniți la editorul de text, corectați greșelile, executați din nou, repetând până când programul dvs. funcționează așa cum doriți.
De obicei, când scrieți programe de calculator, deschideți pur și simplu un editor de text sau mediul de programare special (care este, de obicei, un editor de text cu mai multe instrumente suplimentare), scrieți programul, apoi compilați și executați. În mod obișnuit, au fost făcute una sau mai multe erori la intrare, astfel încât programul dvs. nu va funcționa. S-ar putea să primiți chiar și un mesaj de eroare care să vă spună ce sa întâmplat. Apoi, reveniți la editorul de text, corectați greșelile, executați din nou, repetând până când programul dvs. funcționează așa cum doriți.


Întregul proces, în Python, poate fi făcut transparent în interiorul interpretrului Python. Interpretorul este o fereastră Python cu un prompt de comandă, unde puteți introduce pur și simplu codul Python. Dacă instalați Python pe computerul dvs. (descărcați-l din [http://www.python.org Python website] dacă sunteți pe Windows sau Mac, instalați-l din depozitul de pachete dacă sunteți pe GNU / Linux), veți avea un interpretor Python în meniul de pornire. Însă FreeCAD are și un interpret Python în fereastra inferioară:
Întregul proces, în Python, poate fi făcut transparent în interiorul interpretrului Python. Interpretorul este o fereastră Python cu un prompt de comandă, unde puteți introduce pur și simplu codul Python. Dacă instalați Python pe computerul dvs. (descărcați-l din [http://www.python.org Python website] dacă sunteți pe Windows sau Mac, instalați-l din depozitul de pachete dacă sunteți pe GNU / Linux), veți avea un interpretor Python în meniul de pornire. Însă FreeCAD are și un interpretor Python în fereastra inferioară:


[[Image:Screenshot_pythoninterpreter.jpg]]
[[Image:Screenshot_pythoninterpreter.jpg]]
Line 20: Line 20:
(Dacă nu o aveți, click pe View --> Panels --> Python console.)
(Dacă nu o aveți, click pe View --> Panels --> Python console.)


Interpretorul arată versiune Python, apoi un >>> symbol, care este command prompt, asta e, unde introduceți codul Python. Writing code in the interpreter is simple: one line is one instruction. When you press Enter, your line of code will be executed (after being instantly and invisibly compiled). For example, try writing this:
Interpretorul arată versiune Python, apoi un simbol >>> , care este promptul comenzii, chiar așa, unde introduceți codul Python. Scrierea unui cod în interpretor este simplă: o linie este o instrucțiune. Când apăsați Enter, linia de cod va fi executată (după ce a fost compilată instant și netransparent pentru user). De exemplu, încercați să scrieți acest lucru:
{{Code|code=
{{Code|code=
print "hello"
print "hello"
}}
}}
<code>print</code> is a special Python keyword that means, obviously, to print something on the screen. When you press Enter, the operation is executed, and the message "hello" is printed. If you make an error, for example let's write:
<code>print</code> este un cuvânt cheie în Python care înseamnă ca, bineînțeles, printezi ceva pe ecran. Când apeși Enter, operația este executată , și mesajul "hello" este afișat. Dacă faci o greșeală, scriem de exemplu:
{{Code|code=
{{Code|code=
print hello
print hello
}}
}}
Python îți va spune că nu știe ce este hello . Ghilimelele " spun despre conținut că este un șir de caractere, care pur și simplu în jargonul informatic înseamnă o bucată de test. Fără ghilimele ", comanda de afișare a lui hello, acesta nu este recunoscut ca fiind un text , ci ca un cuvânt comandă special rezervat în Python.Important este că obțineți imediat o notificare de eroare. Apăsând săgeata sus (sau, în interpretorul FreeCAD CTRL+Săgeată sus), puteți merge înapoi la ultima comandă și să o scrieți corect.
Python will tell us that it doesn't know what hello is. The " characters specify that the content is a string, which is simply, in programming jargon, a piece of text. Without the ", the print command believed hello was not a piece of text but a special Python keyword. The important thing is, you immediately get notified that you made an error. By pressing the up arrow (or, in the FreeCAD interpreter, CTRL+up arrow), you can go back to the last command you wrote and correct it.


Interpretorul Python dispune de asemenea de un sistem integrat de help. Încercați să tastați:
The Python interpreter also has a built-in help system. Try typing:
{{Code|code=
{{Code|code=
help
help
}}
}}
sau, de exemplu, sa spunem ca nu ințelegem ce a mers prost cu comanda de afișare a lui ”hello” de mai sus, dorim informații mai precise despre comanda "print":
or, for example, let's say we don't understand what went wrong with our print hello command above, we want specific information about the "print" command:
{{Code|code=
{{Code|code=
help("print")
help("print")
}}
}}
Veți obține o descriere lungă și completă a tot ceea ce poate face comanda ”print”.
You'll get a long and complete description of everything the print command can do.


Acum că stăpânim total interpretorul nostru , putem începe lucrurile serioase.
Now that we totally dominate our interpreter, we can begin with the serious stuff.


==Variables==
==Varibile==


Desigur, tipărirea lui "hello" nu este foarte interesantă. Mai interesant este să imprimați lucruri pe care nu le cunoșteați înainte sau să lăsați Python să le găsească pentru dvs. Aici vine conceptul de variabilă. O variabilă este pur și simplu o valoare pe care o stocați sub un nume. De exemplu, tastați:
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:
{{Code|code=
{{Code|code=
a = "hello"
a = "hello"
print a
print a
}}
}}
Presupun că ați înțeles ce sa întâmplat, am "salvat" șirul "hello" într-o variabilă care poartă numele "a". Acum, "a" nu mai este un nume necunoscut! Putem să o folosim oriunde, de exemplu în comanda de afișare pe ecran. Putem folosi orice nume dorim, trebuie doar să urmați câteva reguli simple, cum ar fi nu folosiți spații sau punctuație. De exemplu, am putea scrie:
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:
{{Code|code=
{{Code|code=
hello = "my own version of hello"
hello = "my own version of hello"
Line 77: Line 77:
==Numere==
==Numere==


Desigur, trebuie să știți că programarea este utilă pentru a trata toate tipurile de date, și mai ales numere, nu numai șiruri de text. Un lucru este important, Python trebuie să știe cu ce fel de date are de-a face. Am văzut în exemplul nostru de afișarea a lui ”hello”, că comanda de afișare a recunoscut șirul de caractere "hello". Acest lucru se datorează faptului că prin utilizarea ghilimelelor " ", am spus în mod specific că această comanda de afișare va trata un șir de caractere alfabetice (text).
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:
Întotdeauna putem verifica tipul de date al unei variabile folosind cuvântul cheie special Python type():
{{Code|code=
{{Code|code=
myVar = "hello"
myVar = "hello"
Line 132: Line 132:
print float(varA)
print float(varA)
}}
}}
'''Note on Python commands'''
'''Notă asupra comenzilor Python'''


Probabil că ați observat că în această secțiune am folosit comanda de afișare în mai multe moduri. Am tipărit variabile, sume, mai multe lucruri separate prin virgule și chiar rezultatul altor comenzi Python, cum ar fi type(). Poate că ați văzut de asemenea că făcând aceste două comenzi,
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,
{{Code|code=
{{Code|code=
type(varA)
type(varA)
print type(varA)
print type(varA)
}}
}}
avem exact același rezultat. Asta pentru că suntem în interpretor și totul este afișat automat. Când scriem programe mai complexe care rulează în afara interpretorului, nu se vor imprima automat, deci va trebui să folosim comanda de afișare. De acum încolo, haideți să-l oprim aici, va merge mai repede. Deci putem scrie pur și simplu:

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:
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:
{{Code|code=
{{Code|code=
Line 146: Line 148:
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.
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==
==Liste/matrici==


Un alt tip de date interesant este formată de către liste. O listă este pur și simplu o colecție de alte date. În același mod în care definim un șir de text folosind "", definim o listă folosind []:
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 [ ]:
{{Code|code=
{{Code|code=
myList = [1,2,3]
myList = [1,2,3]
Line 178: Line 180:
==Indentation==
==Indentation==


O mare utilizare rece a listelor este, de asemenea, navigarea prin ele și să facă ceva cu fiecare element. De exemplu, uitați-vă la acest lucru:
One big cool use of lists is also browsing through them and do something with each item. For example look at this:
{{Code|code=
{{Code|code=
alldaltons = ["Joe", "William", "Jack", "Averell"]
alldaltons = ["Joe", "William", "Jack", "Averell"]
Line 184: Line 186:
print dalton + " Dalton"
print dalton + " Dalton"
}}
}}
Am iterat(jargonul informatic) prin lista noastră cu comanda "for ... in ..." și am făcut ceva cu fiecare dintre ele. Rețineți sintaxa specială: comanda '''for''' se termină cu ''':''' indicând că următorul lucru va fi un bloc al uneia sau mai multor comenzi. În interpretor, imediat după ce ați introdus linia de comandă care se termină cu:, promptul de comandă se va schimba la ... Notați sintaxa particulară a buclei , comanda se termină cu un " : " ceea ce indică lui Python că urmarea va fi un bloc de una sau mai multe comenzi.
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.
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.
Line 252: Line 254:
==Funcții==
==Funcții==


There are few [http://docs.python.org/reference/lexical_analysis.html#identifiers 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:
Sunt câteva comenzi standard [http://docs.python.org/reference/lexical_analysis.html#identifiers standard Python commands]. În versiunea actuală a Python, există aproximativ 30, iar noi deja știm mai multe dintre ele. Dar imaginați-vă dacă am putea ne inventăm propriile comenzi? Ei bine, putem, și este extrem de ușor. De fapt, majoritatea modulelor suplimentare pe care le puteți conecta la instalarea dvs. Python faceți exact acest lucru, adăugând comenzi pe care le puteți utiliza. O comandă personalizată în Python se numește o funcție și se face astfel:
{{Code|code=
{{Code|code=
def printsqm(myValue):
def printsqm(myValue):
Line 259: Line 261:
printsqm(45)
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.)
(O altă eroare de copy and paste, copiați numai prin sfârșitul secțiunii indentate, adică '''"metri pătrați"''' . Inserați în interpretor și apăsați <enter> până când promptul cu trei puncte dispare, apoi copiați și lipiți linia finală.)


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.
Extrem de simplu: comanda def () definește o nouă funcție. Dă-i un nume, iar în paranteză definiți argumente pe care le vom folosi în funcția noastră. Argumentele sunt date care vor fi transmise funcției. De exemplu, uitați-vă la comanda len (). Dacă scrieți len () singur, Python va spune că are nevoie de un argument. Asta este, vrei len () ceva, nu? Apoi, de exemplu, veți scrie len (myList) și veți obține lungimea myList. Ei bine, lista mea este un argument să-l treci la funcția len (). Funcția len () este definită astfel încât știe ce facă cu ceea ce este transmis acesteia. La fel cum am făcut aici.


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:
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:
Line 284: Line 286:
print sum(45,34)
print sum(45,34)
}}
}}
to have something printed. Read more about functions [http://www.diveintopython.net/getting_to_know_python/declaring_functions.html here].
pentru a avea ceva afișat, Citiți mai multe despre funcțiile [http://www.diveintopython.net/getting_to_know_python/declaring_functions.html here].


==Module==
==Module==


Acum că avem o idee completă de cum lucrează Python, vom avea nevoie de un ultim lucru: Cum să lucrăm cu fișiere și cu module.
Now that we have a good idea of how Python works, we'll need one last thing: How to work with files and modules.


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.
Până acum, am scris linii de instrucțiuni Python în linie în interpretor, nu-i așa? Dacă am putea scrie câteva rânduri împreună și le-am fi executat imediat? Cu siguranță ar fi mai ușor facem lucruri mai complexe. Și ne-am putea salva munca. Și asta este extrem de ușor. Pur și simplu deschideți un editor de text (cum ar fi notepad-ul din Windows, sub Linux: gedit, emacs sau vi) și scrieți toate liniile dvs. Python, la fel cum le scrieți în interpretor, cu indentări etc. , Apoi salvați fișierul undeva, de preferință cu o extensie .py. Asta e, aveți un program Python complet. Desigur, există editori mult mai buni decât notepad-ul, dar aceasta este doar arătăm un program Python nu este altceva decât un fișier text.


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:
Pentru a face Python execute acel program, există sute de moduri. În Windows, pur și simplu faceți clic dreapta pe fișierul dvs., deschideți-l cu Python și executați-l. Dar o puteți executa și din interpretorul Python. Pentru aceasta, interpretorul trebuie știe unde este programul dvs. .py. În FreeCAD, cel mai simplu mod este plasați programul într-un loc în care interpretul Python al FreeCAD îl cunoaște în mod implicit, ca de exemplu FreeCAD's bin folder, sau orice folder Mod. (In Linux, aveți probabil un director /home/<username>/.FreeCAD/Mod, haideți să-i adăugăm un subdirector to that called scripts unde vom pune fișierul text.) Presupunem scriem fișierul de maniera:
{{Code|code=
{{Code|code=
def sum(a,b):
def sum(a,b):

Revision as of 07:51, 15 August 2018

Acesta este un scurt tutorial pentru cei nou veniți în Python. Python is an open-source, multiplatform programming language. Python are mai multe caracteristici care o fac foarte diferită de alte limbaje și este foarte accesibil utilizatorilor noi ca tine:

  • A fost special conceput pentru a fi ușor de citit de ființe umane, și de aceea este foarte ușor de învățat și de înțeles.
  • Este un limbaj interpretat, este faptul că, spre deosebire de limbajele compilate cum ar fi C, programul nu trebuie să fie compilate înainte de a fi executat. Codul pe care îl scrieți, dacă doriți. Pentru că puteți merge încet, pas cu pas, este extrem de ușor de a învăța și de a găsi erori în cod.
  • Poate fi încorporat în alte programe pentru a fi folosit ca limbaj de scripting. FreeCAD are un interpretor Python încorporat; puteți scrie cod Python în freecad, Aceasta va Manipulează părți ale freecad, de exemplu, pentru a crea geometrie. Acest lucru este extrem de puternic, în loc de doar clic pe butonul închidere a Etichetat „creați sferă“ pe care unii ARE program de coduri; tu ai libertatea de a construi cu ușurință propriul instrument, care crează exact geometria dorită, într-o formă de și manieră pe care programatorul nu o putea prevedea.
  • Este extensibil, vă puteți conecta cu ușurință la funcționalitatea dvs. De exemplu,sunt modulele care permit Python-ului să citească și să scrie imagini jpg pentru a comunica cu Twitter, pentru a programa sarcinile care trebuie efectuate de sistemul de operare, etc.

Vă recomandăm cu tărie să introduceți fragmentele de cod de mai jos într-un interpret Python. Pentru multe dintre exemplele noastre, punctul important este linia după execuția codului, rezultatul. Și acum la muncă! Rețineți că următoarea este o introducere simplificată și, în nici un caz, un tutorial complet. Dar sperăm că după această lectură ați dobândit bazele necesare pentru a cunoaște și exploata mai profund mecanismele FreeCad.

Interpretorul

De obicei, când scrieți programe de calculator, deschideți pur și simplu un editor de text sau mediul de programare special (care este, de obicei, un editor de text cu mai multe instrumente suplimentare), scrieți programul, apoi compilați și executați. În mod obișnuit, au fost făcute una sau mai multe erori la intrare, astfel încât programul dvs. nu va funcționa. S-ar putea să primiți chiar și un mesaj de eroare care să vă spună ce sa întâmplat. Apoi, reveniți la editorul de text, corectați greșelile, executați din nou, repetând până când programul dvs. funcționează așa cum doriți.

Întregul proces, în Python, poate fi făcut transparent în interiorul interpretrului Python. Interpretorul este o fereastră Python cu un prompt de comandă, unde puteți introduce pur și simplu codul Python. Dacă instalați Python pe computerul dvs. (descărcați-l din Python website dacă sunteți pe Windows sau Mac, instalați-l din depozitul de pachete dacă sunteți pe GNU / Linux), veți avea un interpretor Python în meniul de pornire. Însă FreeCAD are și un interpretor Python în fereastra inferioară:

(Dacă nu o aveți, click pe View --> Panels --> Python console.)

Interpretorul arată versiune Python, apoi un simbol >>> , care este promptul comenzii, chiar așa, unde introduceți codul Python. Scrierea unui cod în interpretor este simplă: o linie este o instrucțiune. Când apăsați Enter, linia de cod va fi executată (după ce a fost compilată instant și netransparent pentru user). De exemplu, încercați să scrieți acest lucru:

print "hello"

print este un cuvânt cheie în Python care înseamnă ca, bineînțeles, că printezi ceva pe ecran. Când apeși Enter, operația este executată , și mesajul "hello" este afișat. Dacă faci o greșeală, să scriem de exemplu:

print hello

Python îți va spune că nu știe ce este hello . Ghilimelele " spun despre conținut că este un șir de caractere, care pur și simplu în jargonul informatic înseamnă o bucată de test. Fără ghilimele ", comanda de afișare a lui hello, acesta nu este recunoscut ca fiind un text , ci ca un cuvânt comandă special rezervat în Python.Important este că obțineți imediat o notificare de eroare. Apăsând săgeata sus (sau, în interpretorul FreeCAD CTRL+Săgeată sus), puteți merge înapoi la ultima comandă și să o scrieți corect.

Interpretorul Python dispune de asemenea de un sistem integrat de help. Încercați să tastați:

help

sau, de exemplu, sa spunem ca nu ințelegem ce a mers prost cu comanda de afișare a lui ”hello” de mai sus, dorim informații mai precise despre comanda "print":

help("print")

Veți obține o descriere lungă și completă a tot ceea ce poate face comanda ”print”.

Acum că stăpânim total interpretorul nostru , putem începe lucrurile serioase.

Varibile

Desigur, tipărirea lui "hello" nu este foarte interesantă. Mai interesant este să imprimați lucruri pe care nu le cunoșteați înainte sau să lăsați Python să le găsească pentru dvs. Aici vine conceptul de variabilă. O variabilă este pur și simplu o valoare pe care o stocați sub un nume. De exemplu, tastați:

a = "hello"
print a

Presupun că ați înțeles ce sa întâmplat, am "salvat" șirul "hello" într-o variabilă care poartă numele "a". Acum, "a" nu mai este un nume necunoscut! Putem să o folosim oriunde, de exemplu în comanda de afișare pe ecran. Putem folosi orice nume dorim, trebuie doar să urmați câteva reguli simple, cum ar fi nu folosiți spații sau punctuație. De exemplu, am putea scrie:

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

We changed the value of myVariable. We can also copy variables:

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.

Numere

Desigur, trebuie să știți că programarea este utilă pentru a trata toate tipurile de date, și mai ales numere, nu numai șiruri de text. Un lucru este important, Python trebuie să știe cu ce fel de date are de-a face. Am văzut în exemplul nostru de afișarea a lui ”hello”, că comanda de afișare a recunoscut șirul de caractere "hello". Acest lucru se datorează faptului că prin utilizarea ghilimelelor " ", am spus în mod specific că această comanda de afișare va trata un șir de caractere alfabetice (text).

Întotdeauna putem verifica tipul de date al unei variabile folosind cuvântul cheie special Python 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)

Int and Floats can be mixed together without problem:

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)

Now both are strings, the operation works! Note that we "stringified" varB at the time of printing, but we didn't change varB itself. If we wanted to turn varB permanently into a string, we would need to do this:

varB = str(varB)

We can also use int() and float() to convert to int and float if we want:

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

Notă asupra comenzilor Python

Probabil că ați observat că în această secțiune am folosit comanda de afișare în mai multe moduri. Am tipărit variabile, sume, mai multe lucruri separate prin virgule și chiar rezultatul altor comenzi Python, cum ar fi type(). Poate că ați văzut de asemenea că făcând aceste două comenzi,

type(varA)
print type(varA)

avem exact același rezultat. Asta pentru că suntem în interpretor și totul este afișat automat. Când scriem programe mai complexe care rulează în afara interpretorului, nu se vor imprima automat, deci va trebui să folosim comanda de afișare. De acum încolo, haideți să-l oprim aici, va merge mai repede. Deci putem scrie pur și simplu:

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/matrici

Un alt tip de date interesant este formată de către liste. O listă este pur și simplu o colecție de alte date. În același mod în care definim un șir de text folosind "", definim o listă folosind []:

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)

or retrieving one item of a list:

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.

Indentation

O mare utilizare rece a listelor este, de asemenea, navigarea prin ele și să facă ceva cu fiecare element. De exemplu, uitați-vă la acest lucru:

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

Am iterat(jargonul informatic) prin lista noastră cu comanda "for ... in ..." și am făcut ceva cu fiecare dintre ele. Rețineți sintaxa specială: comanda for se termină cu : indicând că următorul lucru va fi un bloc al uneia sau mai multor comenzi. În interpretor, imediat după ce ați introdus linia de comandă care se termină cu:, promptul de comandă se va schimba la ... Notați sintaxa particulară a buclei , comanda se termină cu un " : " ceea ce indică lui Python că urmarea va fi un bloc de una sau mai multe comenzi.

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

Or more complex things like this:

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

You see that the range() command also has that strange particularity that it begins with 0 (if you don't specify the starting number) and that its last number will be one less than the ending number you specify. That is, of course, so it works well with other Python commands. For example:

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

Another interesting use of indented blocks is with the if command. If executes a code block only if a certain condition is met, for example:

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

Of course this will always print the first sentence, but try replacing the second line by:

if "Lucky" in alldaltons:

Then nothing is printed. We can also specify an else: statement:

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

Funcții

Sunt câteva comenzi standard standard Python commands. În versiunea actuală a Python, există aproximativ 30, iar noi deja știm mai multe dintre ele. Dar imaginați-vă dacă am putea să ne inventăm propriile comenzi? Ei bine, putem, și este extrem de ușor. De fapt, majoritatea modulelor suplimentare pe care le puteți conecta la instalarea dvs. Python faceți exact acest lucru, adăugând comenzi pe care le puteți utiliza. O comandă personalizată în Python se numește o funcție și se face astfel:

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

(O altă eroare de copy and paste, copiați numai prin sfârșitul secțiunii indentate, adică "metri pătrați" . Inserați în interpretor și apăsați <enter> până când promptul cu trei puncte dispare, apoi copiați și lipiți linia finală.)

Extrem de simplu: comanda def () definește o nouă funcție. Dă-i un nume, iar în paranteză definiți argumente pe care le vom folosi în funcția noastră. Argumentele sunt date care vor fi transmise funcției. De exemplu, uitați-vă la comanda len (). Dacă scrieți len () singur, Python vă va spune că are nevoie de un argument. Asta este, vrei len () ceva, nu? Apoi, de exemplu, veți scrie len (myList) și veți obține lungimea myList. Ei bine, lista mea este un argument să-l treci la funcția len (). Funcția len () este definită astfel încât să știe ce să facă cu ceea ce este transmis acesteia. La fel cum am făcut aici.

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)

There will be an error. Our function was programmed to receive just one argument, but it received two, 45 and 34. We could instead do something like this:

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

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

We made a function that receives two arguments, sums them, and returns that value. Returning something is very useful, because we can do something with the result, such as store it in the myTotal variable. Of course, since we are in the interpreter and everything is printed, doing:

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)

pentru a avea ceva afișat, Citiți mai multe despre funcțiile here.

Module

Acum că avem o idee completă de cum lucrează Python, vom avea nevoie de un ultim lucru: Cum să lucrăm cu fișiere și cu module.

Până acum, am scris linii de instrucțiuni Python în linie în interpretor, nu-i așa? Dacă am putea scrie câteva rânduri împreună și le-am fi executat imediat? Cu siguranță ar fi mai ușor să facem lucruri mai complexe. Și ne-am putea salva munca. Și asta este extrem de ușor. Pur și simplu deschideți un editor de text (cum ar fi notepad-ul din Windows, sub Linux: gedit, emacs sau vi) și scrieți toate liniile dvs. Python, la fel cum le scrieți în interpretor, cu indentări etc. , Apoi salvați fișierul undeva, de preferință cu o extensie .py. Asta e, aveți un program Python complet. Desigur, există editori mult mai buni decât notepad-ul, dar aceasta este doar să vă arătăm că un program Python nu este altceva decât un fișier text.

Pentru a face Python să execute acel program, există sute de moduri. În Windows, pur și simplu faceți clic dreapta pe fișierul dvs., deschideți-l cu Python și executați-l. Dar o puteți executa și din interpretorul Python. Pentru aceasta, interpretorul trebuie să știe unde este programul dvs. .py. În FreeCAD, cel mai simplu mod este să plasați programul într-un loc în care interpretul Python al FreeCAD îl cunoaște în mod implicit, ca de exemplu FreeCAD's bin folder, sau orice folder Mod. (In Linux, aveți probabil un director /home/<username>/.FreeCAD/Mod, haideți să-i adăugăm un subdirector to that called scripts unde vom pune fișierul text.) Presupunem că scriem fișierul de maniera:

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

print "myTest.py succesfully loaded"

Și noi salvăm asta ca pe myTest.py în direcotrul nostru FreeCAD/bin directory (sau în Linux la /home/<username>/.FreeCAD/Mod/scripts.) Acum , hai să pornim FreeCAD, și în fereastra interpretorului, scrie :

import myTest

fără extensia .py . Aceasta va executa pur și simplu conținutul fișierului, linie cu linie, ca și cum l-am fi scris în interpret. Se va crea funcția sumă, iar mesajul va fi imprimat. Există o mare diferență: comanda de import este făcută nu numai pentru a executa programe scrise în fișiere, ca și pentru ale noastre, dar și pentru a încărca funcțiile din interior, astfel încât acestea să devină disponibile în interpretor. Fișierele care conțin funcții, precum cele ale noastre, sunt numite module.

În mod normal când scrii o funcție sum() in interpreter, noi o executăm simplu ca:

sum(14,45)

Like we did earlier. When we import a module containing our sum() function, the syntax is a bit different. We do:

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!

One last extremely useful thing. How do we know what modules we have, what functions are inside and how to use them (that is, what kind of arguments they need)? We saw already that Python has a help() function. Doing:

help()
modules

Ne va da o lista cu toate modulele disponibile. Acum putem introduce q pentru a ieși din ajutorul interactiv și pentru a importa oricare dintre ele. Putem chiar să răsfoim conținutul lor cu comanda dir()

import math
dir(math)

We'll see all the functions contained in the math module, as well as strange stuff named __doc__, __file__, __name__. The __doc__ is extremely useful, it is a documentation text. Every function of (well-made) modules has a __doc__ that explains how to use it. For example, we see that there is a sin function in side the math module. Want to know how to use it?

print math.sin.__doc__

(Este posibil să nu fie evident, dar din ambele părți ale docului există două caractere subliniate.)

Și în cele din urmă o bombonică: Când lucrăm la un modul nou sau existent, este mai bine să înlocuiți extensia de fișier cu py cum ar fi: myModule.FCMacro => myModule.py. Vrem adesea să o testeze astfel încât să o încărcăm ca mai sus.

import myModule
myModule.myTestFunction()

Dar dacă vedem că myTestFunction() nu funcționează corect? Ne întoarcem la editorul nostru și facem schimbări. Apoi, în loc să închidem și să redeschidem interpretul python, putem să actualizăm modulul astfel:

reload(myModule)

Acest redenumire de fișiere se datorează faptului că Python nu știe despre extensia FCMacro.

Cu toate acestea, există două alternative: în cadrul macro-ului se utilizează funcțiile exec sau execfile ale lui Python.

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

ori

execfile "myModule"

Pentru a partaja codul între macrocomenzi, puteți accesa modulul FreeCAD sau FreeCADGui (sau orice alt modul Python) și puteți seta orice atribut la acesta. Acest lucru ar trebui să supraviețuiască executării macrocomenzii.

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

Începeți cu FreeCAD

Ei bine, cred că acum aveți o idee bună despre modul în care funcționează Python și puteți începe să explorați ce oferă FreeCAD. Funcțiile Python ale FreeCAD sunt bine organizate în diferite module. Unele dintre ele sunt deja încărcate (importate) când porniți FreeCAD. Deci, pur și simplu

dir()

și citiți pe FreeCAD Scripting Basics...

Desigur, am văzut aici doar o mică parte a lumii Python. Există multe concepte importante pe care nu le-am menționat. Există trei documente de referință Python foarte importante pe net:

Be sure to bookmark them!


Macros
Python scripting tutorial