Introduction to Python/es

Este es un pequeño tutorial hecho para quien sea nuevo en Python. Python es un lenguaje de programación de código abierto y multiplataforma. Python tiene varias características que lo hacen muy diferente de otros lenguajes de programación comunes, y es muy accesible para usuarios nuevos como tu:


 * It has been designed specially to be easy to read by human beings, and so it is very easy to learn and understand.
 * It is interpreted, that is, unlike compiled languages like C, your program doesn't need to be compiled before it is executed. The code you write can be immediately executed, line by line if you want so. This makes it extremely easy to learn and to find errors in your code, because you go slowly, step-by-step.
 * It can be embedded in other programs to be used as scripting language. FreeCAD has an embedded Python interpreter, so you can write Python code in FreeCAD, that will manipulate parts of FreeCAD, for example to create geometry. This is extremely powerful, because instead of just clicking a button labeled "create sphere", that a programmer has placed there for you, you have the freedom to create easily your own tool to create exactly the geometry you want.
 * It is extensible, you can easily plug new modules in your Python installation and extend its functionality. For example, you have modules that allow Python to read and write jpg images, to communicate with twitter, to schedule tasks to be performed by your operating system, etc.

Así que, ¡manos a la obra! Ten en cuenta que lo que viene ahora es una introducción muy simple, de ningún modo un completo tutorial. Pero espero que después, tengas la base suficiente para explorar más profundamente en las interioridades de FreeCAD.

El intérprete
Por lo general, cuando escribes programas de ordenador, abres un editor de texto o tu entorno de programación favorito (que en la mayoría de los casos constará de un editor de texto con varias herramientas a su alrededor), escribes tu programa, a continuación, lo compilas y lo ejecutarás. La mayoría de las veces habrás cometido errores al escribir, así que tu programa no funcionará, y recibirás un mensaje de error diciendo lo que salió mal. Entonces regresarás a tu editor de texto, corregirás los errores, ejecutarás de nuevo, y así sucesivamente hasta que el programa funcione bien.

Todo este proceso se puede hacer, en Python, de forma transparente dentro del intérprete de Python. El intérprete es una ventana de Python con un símbolo del sistema, donde puedes simplemente escribir código Python. Si instalas en su ordenador Python (descargarlo desde su website si estás en Windows o Mac, o instalar desde el repositorio de paquetes si estás en linux), tendrás un intérprete Python en el menú de inicio. Pero FreeCAD también tiene un intérprete de Python en su parte inferior:



(If you don't have it, click on View ? Views ? Python console.)

El intérprete muestra la versión de Python, y luego el símbolo >>>, que es el símbolo del sistema, es decir, donde se introduce el código Python. Escribir código en el intérprete es simple: una línea es una instrucción. Al pulsar Intro, tu línea de código se ejecutará (después de ser compilado de modo instantáneo e invisible). Por ejemplo, trata de escribir esto:

print es una palabra clave especial de Python que significa, obviamente, imprimir algo en la pantalla. Al pulsar Intro, la operación se ejecuta, y el mensaje "hola" se imprime. Si cometes un error, por ejemplo vamos a escribir:

Python nos dirá que no sabe lo que es hola. El caracter " especifica que el contenido es una cadena, que es simplemente, en la jerga de programación, un pedazo de texto. Sin el signo ", el comando de impresión cree que hola no era un trozo de texto, sino una palabra clave especial de Python. Lo importante es, que inmediatamente se notifica que has cometido un error. Al pulsar la flecha hacia arriba (o, en el intérprete FreeCAD, CTRL + flecha hacia arriba), puedes volver a la última orden que has escrito y corregirlo.

El intérprete de Python también incoEpora un sistema de ayuda. Prueba a escribir:

o, por ejemplo, supongamos que no entendemos lo que salió mal con nuestro comando anterior: print hola. queremos obtener información específica sobre el comando "print":

Entonces obtendrás una descripción más larga y completa de todo lo que el comando print puede hacer.

Ahora dominamos por completo nuestro intérprete, y podemos empezar con cosas serias.

Variables
Por supuesto, imprimir "hola" no es muy interesante. Más interesante es la impresión de cosas que no conocía antes, o dejar que Python las busque para ti. Ahí es donde el concepto de variable entra en juego. Una variable es simplemente un valor que se almacenan bajo un nombre. Por ejemplo, escribe lo siguiente:

Supongo que entiendes lo que ocurrió, "guardaste" la cadena "hola" con el nombre a. Ahora, a ya no es un nombre desconocido más! Podemos utilizarlo en cualquier lugar, por ejemplo, en el comando de impresión. Podemos usar cualquier nombre que desees, respetando unas simples normas, como no usar espacios ni puntuación. Por ejemplo, podríamos escribir:

¿Ves? ahora hola no es una palabra indefinida más. ¿Qué pasa si, por una mala suerte terrible, elegiste un nombre que ya existe en Python? Supongamos que queremos almacenar nuestra cadena con el nombre de "print":

Python es muy inteligente y nos dirá que esto no es posible. Tiene algunas palabras clave "reservadas" que no se pueden modificar. Pero nuestras propias variables pueden ser modificadas en cualquier momento, eso es exactamente por lo qué se llaman variables, los contenidos pueden variar. Por ejemplo:

Hemos cambiado el valor de miVariable. También podemos copiar variables:

Ten en cuenta que es interesante dar buenos nombres para las variables, ya que cuando vayas a escribir programas largos, después de un tiempo no te acordarás de para que era su variable llamada "a". Pero si la llamas, por ejemplo miMensajeBienvenida, cuando vuelvas a verlo recordarás fácilmente para que se utiliza.

Números
Por supuesto, debes saber que la programación es útil para tratar todo tipo de datos, y los números en especial, no sólo cadenas de texto. Una cosa es importante, Python debe saber con que tipo de datos está tratando. Vimos en nuestro ejemplo print hola, que el comando de impresión print reconoció nuestro cadena "hola". Eso se debe a que mediante el caracter ", le dijimos específicamente al comando de impresión print que lo que vendría después era una cadena de texto.

Siempre se puede comprobar que tipo de datos contiene una variable con la palabra clave especial de python: Type

Nos dirá el contenido de myVar es "str", o una cadena en la jerga de python. Tenemos también otros tipos de datos, como números enteros y números en coma flotante:

Esto ya es mucho más interesante, ¿no? Ahora ya tenemos una potente calculadora! Mira bien cómo funciona, Python sabe que el 10 y 20 son números enteros. Así que se almacenan como "int", y Python puede hacer con ellos todo lo que puede hacer con números enteros. Mira los resultados de este:

¿Ves? Estamos obligando a Python a considerar que nuestras dos variables no son números sino simples piezas de texto. Python puede unir dos fragmentos de texto en conjunto, pero no va a tratar de calcular el resultado de la suma. Pero estábamos hablando de números enteros. También hay números en coma flotante. La diferencia es que los números enteros no tienen parte decimal, mientras que los números en coma flotante pueden tener una parte decimal:

Int and Float pueden mezclarse sin problemas:

Por supuesto que 'total' tiene decimales, ¿verdad? Por eso Python automáticamente decidió que el resultado es un float. En varios casos como éste, python decide automáticamente qué tipo dar al resultado. En otros casos no es así. Por ejemplo:

Esto nos dará un error, varA es un string y varB es un int, y Python no sabe que hacer. Pero podemos obligar a Python a convertir entre tipos:

Ahora los dos son strings, la operación se puede hacer! Fíjate que convertimos en "string" a varB en el momento de implimir, peo no cambiamos VarB. Si quisieramos cambiar varB permanentemente en un string, necesitariamos hacer así:

Tambien podemos usar int y float para convertir en int y float si queremos:

Nota sobre comandos en Python

Habrás visto que en esta sección hemos usado el comando print de varias formas. Hemos impreso variables, sumas, varias cosas separadas por comas e incluso el resultado de otro comando Python como es type. Tambien habrás notado que estos dos comandos:

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:

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 [ ]:

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:

or retrieving one item of a list:

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 very similar to a list of characters! Try doing this:

Usually all 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 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:

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:

Or more complex things like this:

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:

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:

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

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

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:

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:

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:

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:

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:

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:

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

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:

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

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 throw out the test part, and import our sum function directly into the main interpreter space, like this:

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:

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

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?

And finally one last little goodie: When we work on programming a new module, we often want to test it. So once we wrote a little piece of module, in a python interpreter, we do something like this, to test our new code:

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

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

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 three very important Python reference documents on the net: Be sure to bookmark them!
 * the official Python tutorial with way more information than this one
 * the official Python reference
 * the Dive into Python wikibook/ book.