Introduction to Python/pl

To jest krótki tutorial dla osób które są całkowicie nowe w pythonie. Python jest wieloplatformowym językiem oprogramowania open source. Python posiada kilka cech, które sprawiają że jest on całkowicie odmienny od innych języków programowania i jest bardzo dostępny dla nowych użytkowników takich jak Ty:


 * Został zaprojektowany specjalnie jako łatwy do odczytania przez istoty ludzkie, i dlatego jest bardzo łatwy do nauczenia i zrozumienia.
 * Jest interpretowany, to znaczy, w przeciwieństwie do kompilowanych języków jak C, twój program nie wymaga kompilacji przed wykonaniem. Kod, który napiszesz może być wykonany natychmiastowo, linia po linii jeśli chcesz. Dzięki temu staje się ekstremalnie łatwy do nauczenia i wyszukiwania błędów - poruszasz się powoli, krok po kroku.
 * Może być wbudowany w inne programy jako język skryptujący. FreeCAD posiada wbudowany interpreter pythona, dlatego możesz wpisywać kod pythona we FreeCADzie by manipulować jego elementami, np. tworzyć geometrię. To daje wielkie możliwości, ponieważ zamiast klikać przycisk oznaczony "wstaw kulę", który programista umieścił tu dla ciebie, posiadasz wolność w tworzeniu własnych narzędzi do budowy geometrii jakiej dokładnie chcesz.
 * Jest elastyczny, możesz łatwo dołączać nowe moduły do twojej instalacji pythona i rozszerzać jego funkcjonalność. Np. masz moduły pozwalające pythonowi czytać i zapisywać obrazy jpg, komunikować się przez twittera, planować zadania twoim systemem operacyjnym itp.

Do dzieła! Bądź świadom, że jest to bardzo proste wprowadzenie, nie kompletny tutorial. Mam jednak nadzieję, że po nim będziesz miał wystarczające podstawy do głębszej eksploracji mechanizmów FreeCADa.

Interpreter
Zwykle, gdy piszesz programy komputerowe, po prostu otwierasz edytor tekstu i lub środowisko programistyczne, które w większości przypadków zawiera edytor tekstu z kilkoma dodatkowymi narzędziami, wpisujesz swój program, następnie kompilujesz go i wykonujesz. Przez większość czasu robisz błędy podczas pisania, więc twój program nie działa - otrzymujesz komunikat błędu mówiący co poszło źle. Potem wracasz do edytora tekstu, poprawiasz błędy, uruchamiasz ponownie, aż program zacznie działać prawidłowo.

Ten cały proces, w Pythonie może być dokonany transparentnie w środku interpretera Pythona. Interpreter znajduje się w środku okna Pythona z zgłoszeniem linii poleceń, gdzie możesz po prostu wpisać kod Pythona. Jeśli zainstalujesz Pythona na swoim komputerze (w przypadku Windows lub Mac OS X do pobrania ze strony Pythona, na Linuksie do zainstalowania z repozytorium pakietów), będziesz miał interpreter Pythona w menu start. Ale FreeCAD posiada także interpreter Pythona w dolnej części okna:



Interpreter pokazuje wersję Pythona, następnie symbol >>>, który jest zgłoszeniem linii poleceń, za nim wpisujesz kod Pythona. Wpisywanie kodu do interpretera jest proste: jedna linia jest jedną instrukcją. Kiedy wciśniesz Enter, linia kodu zostanie wykonana (po natychmiastowej i niewidzialnej kompilacji). Na przykład, spróbuj wpisać to:

print "hello"

print jest specjalnym słowem kluczowym Pythona oznaczającym, oczywiście, wydrukowanie czegoś na ekranie. Kiedy wciśniesz Enter, operacja zostanie wykonana i napis "hello" zostanie wydrukowany. Jeśli chcesz otrzymać błąd, np. spróbuj wpisać to:

print hello

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.

the python interpreter also has a built-in help system. Try typing:

help

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:

help("print")

You'll get a long and complete description of everything the print command can do.

Now we dominate totally our interpreter, we can begin with serious stuff.

Variables
Of course, printing "hello" is not very interesting. More interesting is printing stuff you don't know before, or let python find for you. That's where the concept of 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 anymore! We can use it anywhere, for example in the print command. We can use any name we want, just respecting simple rules, like not using spaces or punctuation. For example, we could very well write:

hello = "my own version of hello" print hello

See? now hello is not an undefined word anymore. What if, by terrible bad luck, we choosed 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 own variables can be modified anytime, that's exactly 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 interesting to give good names to your variables, because when you'll write long programs, after a while you won't remember what your variable named "a" is for. But if you named it for example myWelcomeMessage, you'll remember easily what it is used for when you'll see it.

Numbers
Of course you must know that programming is useful to treat all kind 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 that what it would come next is a text string.

we can always check what data type is the contents of a variable with the special python keyword type:

myVar = "hello" type(myVar)

It will tell us the contents of myVar is 'str', or 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 already much more interesting, isn't it? Now we already have a powerful calculator! Look well at how 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 foat 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 give to something. 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. But 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)

Note on python commands

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 on screen. When we'll write more complex programs that run outside the interpreter, they won't print automatically everything on screen, so we'll need to use the print command. But from now on, let's stop using it here, it'll go faster. so we can simply write:

myVar = "hello friends" myVar

You must also have seen that most of the python commands (or keywords) we already know have parenthesis used to tell them on what contents the command must work: type, int, str, etc. Only exception is the print command, which in fact is not an exception, it also works normally like this: print("hello"), but, since it is used often, the python programmers made a simplified version.

Lists
Another interesting data type is lists. A list is simply a list of other data. The same way as we define a text string by using " ", we define lists 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 kind of things within that groups, 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 stuff with lists such as you can read here, such as sorting contents, removing or adding elements.

A funny and interesting thing for you: a text string is, in reality, a list of characters! Try doing this:

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

Usually all you can do with lists can also be done with strings.

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

Indentation
One big cool use of lists is also browsing through them and do something with each item. For example look at this:

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

We iterated (programming jargon again!) 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 : which indicates that what will comes after will be a block of one of more commands. Immediately after you enter the command line ending with :, the command prompt will change to ... which means python knows that a :-ended line has happened and that what will come next will be part of it.

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 everythin 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 if you make big ones (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 many other commands 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

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!"

Functions
The standard python commands are not many. In 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)

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 so the function knows 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 more print command inside the function, nothing would appear on the screen. You would need to do:

print sum(45,34)

to have something printed. Read more about functions here.

Modules
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), 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. Suppose we write a file like this:

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

print "test.py succesfully loaded"

and we save it as test.py in our FreeCAD/bin directory. Now, let's start FreeCAD, and in the interpreter window, write:

import test

without the .py extension. This will simply execute the contents of the file, line by line, just as if we had written it in the interpreter. The sum function will be created, and the message will be printed. There is one big difference: the import command is made not only to execute programs written in files, like ours, but also to load the functions inside, so they become available in the interpreter. Files containing functions, like ours, are called modules.

Normally when we write a sum function in the interpreter, we execute it simply like that:

sum(14,45)

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

test.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 inbetween, that means somethingElse is inside something.

We can also throw out the test part, and import our sum function directly into the main interpreter space, like this:

from test import * sum(12,54)

Basically all modules behave like that. You import a module, then you can use its functions like that: 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 to import 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

Will give us a list of all available modules. We can now type q to get out of the interactive help, and import any of them. We can even browse their content with the dir command

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__

Starting with FreeCAD
Well, I think you must know 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

and read on to FreeCAD Scripting Basics...

Of course, we saw here only a very small part of the python world. There are many important concepts that we didn't mention here. There are two very important python reference documents on the net: Be sure to bookmark them!
 * the official Python reference
 * the Dive into Python wikibook