Introduction to Python/pt-br

Introdução
Este é um pequeno tutorial para aqueles que ainda não conhecem Python. Python é uma linguagem de programação multiplataforma de código aberto que possui vários recursos que o diferenciam de outras linguagens, tornado seu aprendizado muito acessível aos novos usuários:


 * Ele foi projetado para ser legível por seres humanos, tornando-o relativamente fácil de aprender e entender.
 * É interpretado, isso significa que os programas não precisam ser compilados antes que possam ser executados. O código Python pode ser executado imediatamente, mesmo linha por linha, se desejar.
 * Pode ser incorporado em outros programas como uma linguagem de script. O FreeCAD possui um interpretador Python embutido. Você pode escrever código em Python para manipular partes do FreeCAD. Isso é muito poderoso, significa que você pode criar suas próprias ferramentas.
 * É extensível, você pode facilmente conectar novos módulos à sua instalação do Python e estender sua funcionalidade. Por exemplo, existem módulos que permitem que o Python leia e escreva imagens, se comunique com o Twitter, agende tarefas a serem executadas pelo seu sistema operacional etc.

Esse texto é uma introdução muito básica e não um tutorial completo. Mas esperamos que seja um ponto de partida e ajude a aprofundar seus conhecimento do FreeCAD e seus mecanismos. Recomendamos que você experimente os trechos de código abaixo em um interpretador Python.

O interpretador
Geralmente, quando se escreve programas de computador, você ira abrir um editor de texto ou editor de código para desenvolvimentos (que basicamente é um editor de texto com algumas ferramentas adicionais), escreve seu código, compila e executa. É comum acontecer um ou mais erros que impedem seu programa de funcionar, provavelmente um erro de digitação ou sintaxe, então seu programa não funcionará. Na maioria dos casos irá receber uma mensagem de erro dizendo o que deu errado. Então você volta ao seu editor de texto, corrige os erros, executa novamente, repetindo até que seu programa funcione como pretendido.

In Python that whole process can be done transparently inside the Python interpreter. The interpreter is a Python window with a command prompt, where you can simply type Python code. If you have installed Python on your computer (download it from the Python website if you are on Windows or Mac, install it from your package repository if you are on GNU/Linux), you will have a Python interpreter in your start menu. But, as already mentioned, FreeCAD also has a built-in Python interpreter: the Python console.



If you don't see it, click on. The Python console can be resized and also undocked.

The interpreter shows the Python version, then a symbol which is the command prompt. Writing code in the interpreter is simple: one line is one instruction. When you press, your line of code will be executed (after being instantly and invisibly compiled). For example, try writing this:

is a Python command that, obviously, prints something on the screen. When you press, the operation is executed, and the message is printed. If you make an error, for example let's write:

Python will immediately tell you so. In this case Python doesn't know what is. The characters specify that the content is a string, programming jargon for a piece of text. Without these the command doesn't recognize. By pressing the up arrow you can go back to the last line of code and correct it.

The Python interpreter also has a built-in help system. Let's say we don't understand what went wrong with and we want specific information about the command:

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

Now that you understand the Python interpreter, we can continue with the more serious stuff.

Variables
Very often in programming you need to store a value under a name. That's where variables come in. For example, type this:

You probably understand what happened here, we saved the string under the name. Now that is known we can use it anywhere, for example in the  command. We can use any name we want, we just need to follow some simple rules, such as not using spaces or punctuation and not using Python keywords. For example, we can write:

Now is not an undefined any more. Variables can be modified at any time, that's why they are called variables, their content can vary. For example:

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

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

Case is very important, is not the same as. If you were to enter it would come back with an error as not defined.

Numbers
Of course Python programs can deal with all kinds of data, not just 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 command recognized our  string. By using characters, we specified that what follows is a text string.

We can always check the data type of a variable with the command:

It will tell us the content of is a, which is short for string. We also have other basic data types such as integer and float numbers:

Python knows that 10 and 20 are integer numbers, so they are stored as, and Python can do with them everything it can do with integers. Look at the results of this:

Here we forced Python to consider that our two variables are not numbers but pieces of text. Python can add two pieces of text together, although in that case, of course, it won't perform any arithmetic. But we were talking about integer numbers. There are also float numbers. The difference is float numbers can have a decimal part and integer numbers do not:

Integers and floats can be mixed together without problems:

Because is a float Python automatically decides that the result must also be a float. But there are cases where Python does not knows what type to use. For example:

This results in an error, is a string and  is an integer, and Python doesn't know what to do. However, we can force Python to convert between types:

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

We can also use and  to convert to integer and float if we want:

You must have noticed that we have used the command in several ways. We printed variables, sums, several things separated by commas, and even the result of another Python command. Maybe you also saw that these two commands:

have the same result. This 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 command. With that in mind let's stop using it here. From now on we will simply write:

Lists
Another useful data type is a list. A list is a collection of other data. To define a list we use :

As you can see a list can contain any type of data. You can do many things with a list. For example, count its items:

Or retrieve one item:

While the command returns the total number of items in a list, the first item in a list is always at position, so in our   will be at position. We can do much more with lists such as sorting items and removing or adding items.

Interestingly a text string is very similar to a list of characters in Python. Try doing this:

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

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

Indentation
One important use of lists is the ability to "browse" through them and do something with each item. For example look at this:

We iterated (programming jargon) through our list with the command and did something with each of the items. Note the special syntax: the 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 there is more to come.

How will Python know how many of the next lines will need to be executed inside the operation? For that, Python relies on indentation. The next lines must begin with a blank space, or several blank spaces, or a tab, or several tabs. And as long as the indentation stays the same the lines will be considered part of the block. If you begin one line with 2 spaces and the next one with 4, there will be an error. When you have finished, just write another line without indentation, or press to come back from the  block

Indentation also aids in program readability. If you use large indentations (for example use tabs instead of spaces) when you write a big program, you'll have a clear view of what is executed inside what. We'll see that other commands use indented blocks of code as well.

The command can be used for many things that must be done more than once. It can, for example, be combined with the command:

If you have been running the code examples in an interpreter by copy-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 and then paste in the interpreter. In the interpreter press until the three dot prompt disappears and the code runs. Then copy the final two lines followed by another. The final answer should appear.

If you type into the interpreter you will see:

Here the square brackets denote an optional parameter. However all are expected to be integers. Below we will force the step parameter to be an integer using :

Another example:

The command also has that strange particularity that it begins with  (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:

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

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

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

Functions
There are very few standard Python commands and we already know several of them. But you can create your own commands. In fact, most of 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:

The command defines a new function, you give it a name, and inside the parenthesis you define the arguments that the function will use. Arguments are data that will be passed to the function. For example, look at the command. If you just write, Python will tell you it needs an argument. Which is obvious: you want to know the length of something. If you write then  is the argument that you pass to the  function. And the function is defined in such a way that it knows what to do with this argument. We have done the same thing with our function.

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

there will be an error. Our function was programmed to receive just one argument, but it received two, and. Let's try another example:

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

Modules
Now that you have a good idea of how Python works, you will need to know one more thing: How to work with files and modules.

Until now, we have written Python instructions line by line in the interpreter. This method is obviously not suitable for larger programs. Normally the code for Python programs is stored in files with the extension. Which are just plain text files and any text editor (Linux gedit, emacs, vi or even Windows Notepad) can be used to create and edit them.

There are several of ways to execute a Python program. 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 program is. In FreeCAD the easiest way is to place your program in a folder that FreeCAD's Python interpreter knows by default, such as FreeCAD's user folder: Let's add a subfolder there called and then write a file like this:
 * On Linux it is usually  or.
 * On Windows it is, which is usually.
 * On Mac OSX it is usually.

Save the file as in the  folder, and in the interpreter window write:

without the extension. This will 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. Files containing functions, like ours, are called modules.

When we write a function in the interpreter, we execute it like this:

But when we import a module containing a function the syntax is a bit different:

That is, the module is imported as a "container", and all its functions are inside that container. This is very useful, because we can import a lot of modules, and keep everything well organized. Basically when you see, with a dot in between, then this means is inside.

We can also import our sum function directly into the main interpreter space:

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!

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 have already seen that Python has a function. Doing:

will give us a list of all available modules. We can import any of them and browse their content with the command:

We'll see all the functions contained in the module, as well as strange stuff named, ,. Every function in a well made module has a that explains how to use it. For example, we see that there is a function inside the math module. Want to know how to use it?

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

And finally one last tip: When working on new or existing code, it is better to not use the FreeCAD macro file extension,, but instead use the standard extension. This is because Python doesn't recognize the extension. If you use your code can be easily loaded with, as we have already seen, and also reloaded with :

There is however an alternative:

Starting with FreeCAD
Hopefully 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. Just try: