Introduction to Python/es: Difference between revisions

From FreeCAD Documentation
mNo edit summary
(Updating to match new version of source page)
Line 1: Line 1:
Este es un pequeño tutorial hecho para quien sea nuevo en Python. [http://es.wikipedia.org/wiki/Python Python] es un [http://es.wikipedia.org/wiki/Lenguaje_de_programaci%C3%B3n 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:
This is a short tutorial made for who is totally new to Python. [http://en.wikipedia.org/wiki/Python_%28programming_language%29 Python] is an open-source, multiplatform [http://en.wikipedia.org/wiki/Programming_language programming language]. Python has several features that make it very different than other common programming languages, and very accessible to new users like yourself:


*It has been designed specially to be easy to read by human beings, and so it is very easy to learn and understand.
* Se ha diseñado especialmente para ser fácil de leer por los seres humanos, por lo que es muy fácil de aprender y comprender.
*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.
* Se interpreta, es decir, a diferencia de lenguajes compilados como C, tu programa no necesitan ser compilado antes de ser ejecutado. El código que escribas podrá ser ejecutado, línea por línea si así lo deseas. Esto hace que sea muy fácil de aprender y de encontrar errores en su código, ya que va despacio, paso a paso.
*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.
* Puede ser integrado en otros programas para ser utilizado como lenguaje de archivos de guión. FreeCAD tiene un intérprete de Python integrado, por lo que se puede escribir código Python en FreeCAD, que manipulará partes de FreeCAD, por ejemplo para crear la geometría. Esto es extremadamente potente, porque en lugar de simplemente pulsar un botón "crear esfera", que un programador ha puesto allí para ti, tienes la libertad de crear fácilmente tu propia herramienta para crear exactamente la geometría que desees.
* Es extensible, puedes conectar fácilmente nuevos módulos en tu instalación de Python y extender su funcionalidad. Por ejemplo, tiene módulos que permiten a Python leer y escribir imágenes jpg, comunicarse con Twitter, programar las tareas a realizar por el sistema operativo, etc.
*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.


So, hands on! Be aware that what will come next is a very simple introduction, by no means a complete tutorial. But my hope is that after that you'll get enough basics to explore deeper into the FreeCAD mechanisms.


==The interpreter==


Usually, when writing computer programs, you simply open a text editor or your special programming environment which is in most case a text editor with several tools around it, write your program, then compile it and execute it. Most of the time you made errors while writing, so your program won't work, and you will get an error message telling you what went wrong. Then you go back to your text editor, correct the mistakes, run again, and so on until your program works fine.
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 [http://www.python.org 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:


That whole process, in Python, 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 install Python on your computer (download it from the [http://www.python.org 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 FreeCAD also has a Python interpreter in its bottom part:


[[Image:Screenshot_pythoninterpreter.jpg]]
[[Image:Screenshot_pythoninterpreter.jpg]]


(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:


The interpreter shows the Python version, then a >>> symbol, which is the command prompt, that is, where you enter Python code. 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:
print "hola"
<syntaxhighlight>

print "hello"
''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:
</syntaxhighlight>

<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:
print hola
<syntaxhighlight>

print hello

</syntaxhighlight>
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.
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.

el intérprete de Python también incorpora un sistema de ayuda. Prueba a escribir:


The Python interpreter also has a built-in help system. Try typing:
<syntaxhighlight>
help
help
</syntaxhighlight>

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:
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":
<syntaxhighlight>


help("print")
help("print")
</syntaxhighlight>
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.
Entonces obtendrás una descripción más larga y completa de todo lo que el comando print puede hacer.


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


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:

<syntaxhighlight>
===Variables===
a = "hello"

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:

a = "hola"
print a
print a
</syntaxhighlight>

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:
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:
<syntaxhighlight>

hola = "mi propia versión de hola"
hello = "my own version of hello"
print hola
print hello
</syntaxhighlight>

¿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":
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":
<syntaxhighlight>

print = "hola"
print = "hello"
</syntaxhighlight>

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:
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:
<syntaxhighlight>

miVariable = "hola"
myVariable = "hello"
print miVariable
print myVariable
miVariable = "adios"
myVariable = "good bye"
print miVariable
print myVariable
</syntaxhighlight>

Hemos cambiado el valor de miVariable. También podemos copiar variables:
We changed the value of myVariable. We can also copy variables:
<syntaxhighlight>

var1 = "hola"
var1 = "hello"
var2 = var1
var2 = var1
print var2
print var2
</syntaxhighlight>
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==
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()''


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 = "hola"
<syntaxhighlight>
myVar = "hello"
type(myVar)
type(myVar)
</syntaxhighlight>

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:
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:
<syntaxhighlight>


firstNumber = 10
firstNumber = 10
secondNumber = 20
secondNumber = 20
print firstNumber + secondNumber
print firstNumber + secondNumber
type(firstNumber)
type(firstNumber)
</syntaxhighlight>

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:

<syntaxhighlight>
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:
firstNumber = "10"

primerNumero = "10"
secondNumber = "20"
print firstNumber + secondNumber
secondNumber = "20"
</syntaxhighlight>
print primerNumero + 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:

<syntaxhighlight>
¿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:

var1 = 13
var1 = 13
var2 = 15.65
var2 = 15.65
print "var1 is of type ", type(var1)
print "var1 is of type ", type(var1)
print "var2 is of type ", type(var2)
print "var2 is of type ", type(var2)
</syntaxhighlight>

Int and Float pueden mezclarse sin problemas:
Int and Floats can be mixed together without problem:
<syntaxhighlight>

total = var1 + var2
total = var1 + var2
print total
print total
print type(total)
print type(total)
</syntaxhighlight>

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:

<syntaxhighlight>
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:
varA = "hello 123"


varA = "hola 123"
varB = 456
varB = 456
print varA + varB
print varA + varB
</syntaxhighlight>

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:
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:
<syntaxhighlight>

varA = "hola"
varA = "hello"
varB = 123
varB = 123
print varA + str(varB)
print varA + str(varB)
</syntaxhighlight>

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í:
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:
<syntaxhighlight>

varB = str(varB)
varB = str(varB)
</syntaxhighlight>

Tambien podemos usar int() y float() para convertir en int y float si queremos:
We can also use int() and float() to convert to int and float if we want:
<syntaxhighlight>

varA = "123"
varA = "123"
print int(varA)
print int(varA)
print float(varA)
print float(varA)
</syntaxhighlight>
'''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:
'''Nota sobre comandos en Python'''
<syntaxhighlight>

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:

type(varA)
type(varA)
print type(varA)
print type(varA)
</syntaxhighlight>

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:
dan exactamente el mismo resultado. Eso es porque estamos en un interprete, y todo es automáticamente impreso en la pantalla. Cuando escribamos programas mayores que corran fuera del interprete, no imprimirán automaticaemnte todo en la pantalla, por eso tendremos que usar el comando print. Pero desde ahora y hasta entonces, dejaremos de usar print aqui (iremos más rápido), de modo que escribiremos simplemente:
<syntaxhighlight>

myVar = "hola amigos"
myVar = "hello friends"
myVar
myVar
</syntaxhighlight>
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==
Tambien habrás visto que muchos de los comandos (o palabras clave) de Python que hemos conocido, tiene paréntesis que le indican sobre que tienen que operar: type(), int(), str(), etc. La única excepción es el comando print, que de hecho no es una excepcion. Tambien funciona normalmente así: print("hola"), pero, como suele ocurrir, los programadores de Python hicieron una versión simplificada.

===Listas===

Otro tipo de dato interesante son las listas. Las listas son, simplemente, listas de otros datos. Del mismo modo que definimos una cadena de texto, string, usando " ", definimos listas usando [ ]:


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 [ ]:
<syntaxhighlight>
myList = [1,2,3]
myList = [1,2,3]
type(myList)
type(myList)
myOtherList = ["Bart", "Frank", "Bob"]
myOtherList = ["Bart", "Frank", "Bob"]
myMixedList = ["hello", 345, 34.567]
myMixedList = ["hello", 345, 34.567]
</syntaxhighlight>

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:
Verás que pueden contener cualquier tipo de datos. Las listas son muy útiles porque pueden agrupar datos. Despues puede hacer muchas cosas con ellos, por ejemplo contarlos:
<syntaxhighlight>

len(myOtherList)
len(myOtherList)
</syntaxhighlight>

or retrieving one item of a list:
u obtener un elemento de una lista:
<syntaxhighlight>

myName = myOtherList[0]
myName = myOtherList[0]
myFriendsName = myOtherList[1]
myFriendsName = myOtherList[1]
</syntaxhighlight>
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 [http://www.diveintopython.net/native_data_types/lists.html 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:
Como vés, mientras el comando len() devuelve el número total de elementos en una lista, sus posiciones en la lista empiezan en 0. El primer elemento en una lista está simepre en la posición 0. Así, en myOtherList, "Bob" estará en la posición 2. Se pueden hacer muchas cosas con listas, como se muestra en [http://diveintopython.org/native_data_types/lists.html aquí], como es ordenar sus contenidos, añadir o quitar elementos.
<syntaxhighlight>

Una cosa interesante y divertida para ti: Un string es, en realidad, una lista de caracteres! Intenta hacer esto:

myvar = "hello"
myvar = "hello"
len(myvar)
len(myvar)
myvar[2]
myvar[2]
</syntaxhighlight>
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 [http://www.diveintopython.net/native_data_types/index.html#d0e5174 dictionnaries], or you can even create your own data types with [http://www.freenetpages.co.uk/hp/alan.gauld/tutclass.htm classes].
Normalmente, todo lo que puedes hacer con listas, también puede hacerse con strings.


==Indentation==
Además de strings, ints, floats y lists, hay más tipos de datos incorporados, como son [http://www.diveintopython.org/getting_to_know_python/dictionaries.html diccionarios], o puedes incluso crear tus propios tipos con [http://www.freenetpages.co.uk/hp/alan.gauld/tutclass.htm clases].

===Indentación===

Un uso típico de las listas es el de ojearlas y hacer algo con cada elemento. Por ejemplo, mira esto:


One big cool use of lists is also browsing through them and do something with each item. For example look at this:
<syntaxhighlight>
alldaltons = ["Joe", "William", "Jack", "Averell"]
alldaltons = ["Joe", "William", "Jack", "Averell"]
for dalton in alldaltons:
for dalton in alldaltons:
print dalton + " Dalton"
print dalton + " Dalton"
</syntaxhighlight>
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.
Aquí ''iteramos'' (es jerga de programación!) en nuestra lista con el comando "for ... in ..." y hacemos algo con cada uno de los elementos. Observa la especial sintaxis: el comando for termina con : lo que indica que lo que siga será un bloque de uno o más comandos.
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
Inmediatamente después de que metas la línea de comando terminada en : el cursor donde se meten los comandos cambia a ... lo que indica que Python ha visto la línea terminada en : y que lo que siga será parte de ella.


Cómo sabe Python cuantas de las siguientes líneas deben ser ejecutadas dentro del bucle for ... in ...?. Para eso, Python usa la indentación o indentado. Eso es que las siguientes líneas no empiezan inmediatamente al inicio del renglón. Se escibirán empezando con uno o varios espacios en blanco, o tabuladores. Otros leguajes de programación usan otros medios, como poner el bloque entre paréntesis, etc.

Mientras empieces las siguientes líneas con la misma indentación, serán consideradas como parte del mismo bloque for...in.
Si empiezas una línea con dos espacios y la siguiente con 4, habrá un error.
Para terminar, escribe otra línea, pero sin sangría, o simplemente pulsa Intro para salir del bloque for...in.

El indentado es estupendo, porque si los haces grandes (por ejemplo usando tabulador en lugar de espacios, porque es más grande), cuando se escribe un gran programa tendrás una visión clara de lo que se ejecuta dentro de cada cosa.

Veremos que muchos comandos distintos de los bloques for-in también puede tener sangría de código.


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.
Los comandos for-in se pueden utilizar para muchas cosas que hay que hacer más de una vez. Por ejemplo se puede combinar con el comando range():


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:
<syntaxhighlight>
serie = range(1,11)
serie = range(1,11)
total = 0
total = 0
Line 214: Line 198:
print "----"
print "----"
print total
print total
</syntaxhighlight>

Or more complex things like this:
O cosas mas complejas como esto:
<syntaxhighlight>

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

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:
El comando range() tambien tiene la extraña particularidad de que comienza con 0 (si no se especifica el número de inicio) y que su último número será uno menos del número final que le indique. Esto es, por supuesto, para que trabaje bien con otros comandos Python. Por ejemplo:
<syntaxhighlight>

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

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:
Otro interesante uso de los bloques indentados es con el comando if. If ejecuta el bloque de código solo si se cumple una determianda condición. Por ejemplo:
<syntaxhighlight>

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

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

<syntaxhighlight>
Por supuesto, esto siempre imprimirá la primera frase. Pero trata de sustituir la segunda línea por:

if "Lucky" in alldaltons:
if "Lucky" in alldaltons:
</syntaxhighlight>

Then nothing is printed. We can also specify an else: statement:
Entonces no se imprime nada. También podemos especificar una clausula else:
<syntaxhighlight>

alldaltons = ["Joe", "William", "Jack", "Averell"]
alldaltons = ["Joe", "William", "Jack", "Averell"]
if "Lucky" in alldaltons:
if "Lucky" in alldaltons:
Line 246: Line 229:
else:
else:
print "Such Dalton doesn't exist!"
print "Such Dalton doesn't exist!"
</syntaxhighlight>
==Functions==


The [http://docs.python.org/reference/lexical_analysis.html#identifiers 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:
===Funciones===
<syntaxhighlight>

Los [http://docs.python.org/reference/lexical_analysis.html#identifiers comandos estandard de Python] no son tantos. En la actual version de Python hay unos 30, y ya conocemos algunos de ellos. ¿Pero, imagina que pudieramos inventar nuestros propios comandos? Pues podemos, y es sumamente fácil. De hecho, la mayoría de los módulos adicionales que puedes cargar en su instalación hacen eso. Añaden comandos que puedes usar. Un comando de usuario en Python se llama función y se crean así:

def printsqm(myValue):
def printsqm(myValue):
print str(myValue)+" square meters"
print str(myValue)+" square meters"
printsqm(45)
printsqm(45)
</syntaxhighlight>
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:
Muy simple: el comando def() define una nueva función. Le da un nombre, y dentro del paréntesis define argumentos que usará en su función. Los Argumentos son datos que le pasará a la función.
<syntaxhighlight>

Por ejemplo, mira el comando len(). Si escribes solo len(), Python te dirá que falta un argumento. Es decir, desea len () de algo, ¿no? Entonces, por ejemplo, si escribes len (myList) obtendrás la longitud de myList. myList es un argumento que se pasa a la función len (). la función len () está definida de tal manera que sepa qué hacer con lo que se le pasa. Lo mismo que hicimos aquí.

El nombre "myValue" puede ser cualquier cosa, y sólo será utilizado dentro de la función. Es sólo un nombre que se le asigna al argumento para que puedas hacer algo con él, pero también sirve para que la función sepa cuantos argumentos debe esperar. Por ejemplo, si haces esto:

printsqm(45,34)
printsqm(45,34)
</syntaxhighlight>

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:

<syntaxhighlight>
Habrá un error. Nuestra función fue programada para recibir un solo argumento, pero recibió dos, 45 y 34. En su lugar, podríamos hacer algo como esto:
def sum(val1,val2):
def sum(val1,val2):
total = val1 + val2
total = val1 + val2
Line 273: Line 253:
sum(45,34)
sum(45,34)
myTotal = sum(45,34)
myTotal = sum(45,34)
</syntaxhighlight>

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:
Hicimos una función que recibe dos argumentos, los suma, y devuelve ese valor. Devolver algo es muy útil, porque podemos hacer algo con el resultado, como almacenarlo en la variable myTotal. Por supuesto, ya que estamos en el intérprete y todo lo que hacemos se imprime, haciendo:
<syntaxhighlight>

sum(45,34)
sum(45,34)
</syntaxhighlight>

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:
se imprimirá el resultado en la pantalla, pero fuera del intérprete nada aparece en la pantalla (ya que no hay comando de impresión dentro de la función). Tendrías que hacer:
<syntaxhighlight>

print sum(45,34)
print sum(45,34)
</syntaxhighlight>
to have something printed. Read more about functions [http://www.diveintopython.net/getting_to_know_python/declaring_functions.html here].


==Modules==
para que se imprima algo. Lee más sobre funciones [http://www.penzilla.net/tutorials/python/functions/ aquí].


Now that we have a good idea of how Python works, we'll need one last thing: How to work with files and modules.
===Módulos===


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.
Ahora que tenemos una buena idea de cómo funciona Python, necesitamos una última cosa: Cómo trabajar con archivos y módulos.


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:
Hasta ahora, hemos escrito las instrucciones Python línea por línea en el intérprete. ¿Y si pudiéramos escribir varias líneas juntas, y ejecutarlas a la vez? Sin duda, sería más práctico para hacer cosas más complejas. Y también así podríamos salvar nuestro trabajo. Bueno, eso también es extremadamente fácil. Basta con abrir un editor de textos (como el Bloc de notas de Windows), y escribir tus líneas de Python, de la misma manera como las escribes en el intérprete, con indentación, etc. A continuación, guarda el archivo en alguna parte, preferentemente con una extensión .Py. Eso es todo, ya tienes un programa Python completo. Por supuesto, hay editores mucho mejores que el bloc de notas, pero esto es sólo para mostrar que un programa de Python no es más que un archivo de texto.
<syntaxhighlight>

def sum(a,b):
Para hacer a Python ejecutar ese programa, hay cientos de maneras. En Windows, simplemente haz clic derecho en el archivo, abrirlo con Python, y ejecutarlo. Pero también se puede ejecutar desde el intérprete de Python en sí. Para ello, el intérprete debe saber dónde está tu programa .Py. En FreeCAD, la forma más fácil es colocar su programa en un lugar que el intérprete de Python de FreeCAD sabe por defecto, como la carpeta bin de FreeCAD, o cualquiera de las carpetas Mod. Supongamos que escribes un archivo así:


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


print "test.py succesfully loaded"
print "test.py succesfully loaded"
</syntaxhighlight>

y lo guardas como test.py en el directorio /bin de FreeCAD. Ahora, vamos a iniciar FreeCAD, y en la ventana del intérprete, escribe:


and we save it as test.py in our FreeCAD/bin directory. Now, let's start FreeCAD, and in the interpreter window, write:
<syntaxhighlight>
import test
import test
</syntaxhighlight>
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:
sin la extensión. py. Esto simplemente ejecuta el contenido del archivo, línea por línea, como si se hubiera escrito en el intérprete. La función suma se creará, y el mensaje se imprimirá. Pero hay una gran diferencia: el comando de importación sirve no sólo para ejecutar programas escritos en los archivos, como el nuestro, sino también para cargar las funciones que tienen en el interior, de modo que estén disponibles para el intérprete. Los archivos que contienen funciones, como la nuestra, se llaman módulos.
<syntaxhighlight>

Normalmente cuando escribimos una función sum() en el intérprete, simplemente se ejecuta, así:

sum(14,45)
sum(14,45)
</syntaxhighlight>

Like we did earlier. When we import a module containing our sum() function, the syntax is a bit different. We do:
como hicimos antes. Al importar un módulo que contiene nuestra función sum(), la sintaxis es un poco diferente. Hacemos:
<syntaxhighlight>

test.sum(14,45)
test.sum(14,45)
</syntaxhighlight>
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:

<syntaxhighlight>
Es decir, el módulo se importa como un "contenedor", y todas sus funciones se encuentran dentro. Esto es muy útil, ya que puedes importar una gran cantidad de módulos, y mantener todo bien organizado. Así que, básicamente, Allá donde veas ''algo.algoMas'', con un punto intermedio, lo que significa es que ''algoMas'' está dentro de ''algo''.

También podemos sacar la parte ''test'', e importar nuestra función sum() directamente en el espacio principal del intérprete, así:

from test import *
from test import *
sum(12,54)
sum(12,54)
</syntaxhighlight>
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:
Básicamente todos los módulos se comportan así. Importa un módulo, y ya puedes utilizar sus funciones así: module.function(argumento). Casi todos los módulos hacen eso: definen funciones, nuevos tipos de datos y clases que se pueden usar en el intérprete o en sus propios módulos de Python, porque nada impide que importes módulos dentro de tu módulo!
<syntaxhighlight>

Una última cosa muy útil. ¿Cómo sabemos los módulos que tenemos, qué funciones se encuentran dentro y cómo utilizarlos (es decir, qué tipo de argumentos necesitan)? Vimos ya que Python tiene una función ayuda(). Si haces:

help()
help()
modules
modules
</syntaxhighlight>

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
Nos dará una lista de todos los módulos disponibles. Podemos ahora escribir ''q'' (de quit) para salir de la ayuda interactiva, e importar cualquiera de ellos. Incluso puedes navegar por su contenido con el comando dir()
<syntaxhighlight>

import math
import math
dir(math)
dir(math)
</syntaxhighlight>

Vamos a ver todas las funciones contenidas en el módulo de matemáticas, así como material extraño llamado __doc__, __file__, __name__. The __doc__ es extremadamente útil, es un texto de documentación. Cada función de un módulo (bien hecho) tiene un __doc__ que explica cómo usarlo. Por ejemplo, vemos que existe una función seno en el módulo de matemáticas. ¿Quieres saber cómo usarlo?
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?
<syntaxhighlight>

print math.sin.__doc__
print math.sin.__doc__
</syntaxhighlight>

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:
Y por último una pequeña golosina más: Cuando trabajamos en la programación de un módulo, frecuentemente querremos probarlo. De modo que una vez que escribimos una pequeña parte del módulo, en un interprete de Python, hacemos algo parecido a esto, para probar nuestro nuevo código:
<syntaxhighlight>

import myModule
import myModule
myModule.myTestFunction()
myModule.myTestFunction()
</syntaxhighlight>

Pero que pasa si vemos que myTestFunction() no funciona correctamente? Volvemos a nuestro editor y lo modificamos. Luego, en lugar de cerrar y volver a abrir el interprete de Python, podemos simplemente actualizar el módulo así:
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:
<syntaxhighlight>

reload(myModule)
reload(myModule)
</syntaxhighlight>
==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
===Empezando con FreeCAD===
<syntaxhighlight>

Bien, creo que debes tener una buena idea de cómo funciona Python, y puedes empezar a explorar lo que FreeCAD puede ofrecer. Las funciones Python de FreeCAD están todas bien organizadas en diferentes módulos. Algunos de ellos están ya cargados (importados) cuando inicias FreeCAD. Así, que simplemente haz


dir()
dir()
</syntaxhighlight>
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:
y sigue leyendo en [[FreeCAD Scripting Basics/es|Archivos de guión básicos en FreeCAD]]...
* the [http://docs.python.org/3/tutorial/index.html official Python tutorial with way more information than this one]

* the [http://docs.python.org/reference/ official Python reference]
Por supuesto, aquí sólo hemos visto una pequeña parte del mundo de Python. Hay muchos conceptos relevantes que no hemos mencionado. En la red hay dos documentos muy importantes como referencia sobre Python:
* the [http://www.diveintopython.net Dive into Python] wikibook/ book.

Be sure to bookmark them!
* La [http://docs.python.org/reference/ referencia oficial de Python]
* La wiki [http://www.diveintopython.org/toc/index.html Zambullirse en Python]


Asegúrate de tener a mano estos enlaces!


{{docnav/es|Macros/es|Python scripting tutorial/es}}
{{docnav|Macros|Python scripting tutorial}}


[[Category:Poweruser Documentation]]
{{languages/es | {{en|Introduction to Python}} {{de|Introduction to Python/de}} {{fr|Introduction to Python/fr}} {{pl|Introduction to Python/pl}} {{ru|Introduction to Python/ru}} {{se|Introduction to Python/se}} }}


{{clear}}
[[Category:Poweruser Documentation/es]]
<languages/>

Revision as of 19:45, 8 October 2014

This is a short tutorial made for who is totally new to Python. Python is an open-source, multiplatform programming language. Python has several features that make it very different than other common programming languages, and very accessible to new users like yourself:

  • 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.

So, hands on! Be aware that what will come next is a very simple introduction, by no means a complete tutorial. But my hope is that after that you'll get enough basics to explore deeper into the FreeCAD mechanisms.

The interpreter

Usually, when writing computer programs, you simply open a text editor or your special programming environment which is in most case a text editor with several tools around it, write your program, then compile it and execute it. Most of the time you made errors while writing, so your program won't work, and you will get an error message telling you what went wrong. Then you go back to your text editor, correct the mistakes, run again, and so on until your program works fine.

That whole process, in Python, 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 install 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 FreeCAD also has a Python interpreter in its bottom part:

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

The interpreter shows the Python version, then a >>> symbol, which is the command prompt, that is, where you enter Python code. 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:

 print "hello"

print 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:

 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 very similar to 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. 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:

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

 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__

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:

 import myModule
 myModule.myTestFunction()

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:

 reload(myModule)

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 three very important Python reference documents on the net:

Be sure to bookmark them!


Macros
Python scripting tutorial