Introduction to Python/sv: Difference between revisions

From FreeCAD Documentation
(N)
 
(Updating to match new version of source page)
Line 1: Line 1:
Detta är en kort övning gjord för den som aldrig har använt python tidigare. [http://sv.wikipedia.org/wiki/Python_%28programspråk%29 Python] är en öppen-källkod, multiplattform [http://sv.wikipedia.org/wiki/Programspråk programmeringsspråk]. Python har flera egenskaper som gör att det skiljer sig mycket från andra vanliga programmeringsspråk, och väldigt åtkomligt för nya användare som du själv:
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.
*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.
*Det har designats speciellt för att vara lätt att läsas av människor, så det är mycket lätt att lära sig och förstå.


==The interpreter==
*Det är ett interpreterande språk, vilket är, till skillnad från ett kompilerat som C, att ditt program inte behöver kompileras innan det körs. Den kod som du skriver kan köras omedelbart, rad för rad om du så vill. Detta gör det extremt lätt att lära sig och att hitta fel i din kod, eftersom du går långsamt, steg-för-steg.


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.
*Det kan bäddas in i andra program och användas som ett skriptspråk. FreeCAD har en inbäddad python tolk, så du kan skriva python kod i FreeCAD, som kan manipulera delar av FreeCAD, till exempel för att skapa geometri. Detta är mycket kraftfullt, därför att istället för att bara klicka på en knapp benämnd "skapa sfär", som en programmerare har placerat där för dig, så har du friheten att lätt skapa ditt eget verktyg för att skapa exakt den geometri du vill.

*Det är utbyggbart, du kan lätt plugga in nya moduler i din python installation och utöka dess funktionalitet. Till exempel, så finns det moduler som tillåter python att läsa och skriva jpg bilder, för att kommunicera med twitter, att schemalägga uppgifter för att utföras av ditt operativsystem, etc.


Så, sätt igång! Tänk på att det som kommer nu är en mycket enkel introduktion, och inte en komplett övning. Men mitt hopp är att efter detta så har du tillräckliga baskunskaper för att göra djupare utforskningar i FreeCAD's mekanismer.


===Tolken===
Vanligtvis när man skriver datorprogram, så startar man helt enkelt en textredigerare eller din speciella programmeringsmiljö som i de flesta fall är en textredigerare med flera verktyg runt den, skriver ditt program, kompilerar det och kör det. För det mesta har du gjort något fel när du skrev, så ditt program fungerar inte, och du får ett felmeddelande som talar om vad som gick snett. Sedan går du tillbaka till din textredigerare, korrigerar misstagen, kör igen, och så vidare ända tills ditt program fungerar bra.


Hela denna process, kan i python, göras transparent inne in pythontolken. Tolken är ett python fönster med en kommandoprompt, där du kan skriva python kod. Om du installerar python på din dator (ladda ned den från [http://www.python.org python webbplatsen] om du är på Windows eller Mac, installera den från din pakethanterare om du är på linux), så kommer du att ha en python i din startmeny. Men FreeCAD har också en python tolk i dess nedre del:


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


Tolken visar python's version, sedan en >>> symbol, vilken är kommandoprompten, där du skriver in python kod. Skriva kod i tolken är enkelt: en rad är en instruktion. När du trycker på Enter, kommer din kodrad att köras (efter att omedelbart och osynligt ha kompilerats). Försök till exempel att skriva detta:
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:
<syntaxhighlight>

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

<syntaxhighlight>
''print'' är ett speciellt python nyckelord som innebär att skriva något på skärmen. När du trycker på Enter, så utförs operationen, och meddelandet "hello" skrivs ut. Om du gör ett fel, låt oss till exempel skriva:

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

<syntaxhighlight>
så kommer python att tala om för oss att den inte vet vad hello är. " tecknen specificerar att innehållet är en sträng, vilket på programmeringsspråk betyder att det är en bit text. Utan ", så trodde inte print kommandot att hello var en bit text utan ett speciellt python nyckelord. Det viktiga är att du omedelbart meddelas att du har gjort ett fel. Genom att trycka på tangentbordets upp-pil (eller, i FreeCAD tolken, CTRL+upp-pil), så kan du få tillbaka det sist skrivna kommandot och korrigera det.


python tolken har även ett inbyggt hjälpsystem. Prova genom att skriva:

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:

<syntaxhighlight>
eller, till exempel, låt oss säga att vi inte förstod vad som gick fel med vårt print hello kommando ovan så vi vill ha specifik information om "print" kommandot:

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.


==Variables==
Så får du en lång och komplett beskrivning av allt som print kommandot kan göra.

Nu när vi dominerar vår tolk fullständigt, så kan vi börja med seriösa saker.


===Variabler===
Det är förstås inte speciellt intressant att skriva "hello" . Mer intressant är att skriva saker som du inte visste innan, eller låta python leta åt dig. Det är där konceptet med variabler kommer in. En variabel är helt enkelt ett värde som du lagrar under ett namn. Skriv till exempel detta:


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>
a = "hello"
a = "hello"
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:

<syntaxhighlight>
Jag gissar att du förstod vad som hände, vi "sparade" strängen "hello" under namnet a. Nu är a inte något okänt namn längre! Vi kan använda det var som helst, till exempel i print kommandot. Vi kan använda vilket namn vi vill, så länge man respekterar några enkla regler, som att inte använda mellanslag eller punktuationer. Vi skulle till exempel mycket väl kunna skriva:

hello = "my own version of hello"
hello = "my own version of hello"
print hello
print hello
</syntaxhighlight>

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>
Se? nu är hello inte ett odefinierat ord längre. Vad händer om vi skulle ha oturen att välja ett namn som redan finns i python? Låt oss säga att vi vill spara vår sträng under namnet "print":

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

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>
Python är mycket intelligent och kommer att tala om för oss att detta inte är möjligt. Den har några "reserverade" nyckelord som inte kan ändras. Men våra egna variabler kan ändras när som helst, det är precis därför som de kallas variabler, innehållet kan variera. Till exempel:

myVariable = "hello"
myVariable = "hello"
print myVariable
print myVariable
myVariable = "good bye"
myVariable = "good bye"
print myVariable
print myVariable
</syntaxhighlight>

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

<syntaxhighlight>
Vi ändrade värdet på myVariable. Vi kan också kopiera variabler:

var1 = "hello"
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==


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.
Notera att det är en bra ide att ge bra namn till dina variabler, därför att när du skriver långa program, så glömmer du efter ett tag vad variabeln benämnd "a" är till. Men om du döpte den till till exempel myWelcomeMessage, så är det mycket lättare att komma ihåg vad den används till när du ser den.


===Tal===
Du vet säkert att programmering är användbart till att behandla all möjlig data, och speciellt tal, inte bara textsträngar. En sak som är viktigt, python måste veta villken sorts data den jobbar med. Vi såg i vårt print hello exempel, att print kommandot kände igen vår "hello" sträng. Det gjorde den för att när vi använde ", så talade vi om för print kommandot att det som kommer efter är en textsträng.


vi kan alltid kontrollera vilken datatyp som en variabel innehåller med det speciella python nyckelordet type:


We can always check what data type is the contents of a variable with the special Python keyword type:
<syntaxhighlight>
myVar = "hello"
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:

<syntaxhighlight>
Den kommer att tala om för oss att innehållet i myVar är 'str', vilket betyder sträng på pythonspråk. Vi har även andra typer av data som hel- och flyttal:

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>
Detta är redan mycket intressantare, eller hur? Nu har vi redan en kraftfull miniräknare! Titta på hur den fungerade, python vet att 10 och 20 är heltal. så de lagras som "int", och python kan göra allt med dem som man kan göra med heltal. Titta på resultatet av detta:

firstNumber = "10"
firstNumber = "10"
secondNumber = "20"
secondNumber = "20"
print firstNumber + secondNumber
print firstNumber + secondNumber
</syntaxhighlight>

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>
Se? Vi tvingade python att anse att våra två tal inte var tal utan textbitar. Python kan lägga ihop två textbitar, men den kommer inte at försöka räkna ut någon summa. Men vi talade om heltal. Det finns också flyttal. Skillnaden är att heltal inte har någon decimaldel, medan flyttal kan ha en decimaldel:

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 Floats can be mixed together without problem:

<syntaxhighlight>
Int och Floats kan blandas ihop utan problem:

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>
Eftersom total har decimaler så beslöt python automatiskt att resultatet är ett flyttal. I flera fall som detta , så beslutar python automatiskt vilken typ den ska ge till något. I andra fall så gör den inte det. Till exempel:

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

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>
Detta kommer att ge ett fel, varA är en string och varB är en int, och python vet inte vad den ska göra. Men vi kan tvinga python att konvertera mellan typer:

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

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>
Nu är båda strings, operationen fungerar! Notera att vi "strängifierade" varB när den skrevs, men vi ändrade inte själva varB. Om vi ville förändra varB till en sträng permanent, så skulle vi behöva göra detta:

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

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

<syntaxhighlight>
Vi kan också använda int() och float() för att konvertera till int och float om vi vill:

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:

<syntaxhighlight>
'''Notering om python kommandon'''
Du har säkert noterat att vi i detta avsnittet har använt print kommandot på flera sätt. Vi skrev ut variabler, summor, flera saker separerade av komman, och även resultatet av ett annat python kommando som type(). Du kanske även såg att om man kör dessa två kommandon:

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:

<syntaxhighlight>
så ger de exakt samma resultat. Det beror på att vi är i tolken, och allt skrivs automatiskt ut på skärmen. När vi skriver mer komplexa program som körs utanför tolken, så kommer inte allt att skrivas ut automatiskt på skärmen, så då behöver vi använda print kommandot. Men låt oss från och med nu sluta med att använda det här, så går det snabbare. Så vi kan skriva:

myVar = "hello friends"
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==


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 [ ]:
Du måste också ha sett att de flesta python kommandona (eller nyckelorden) som vi redan känner till har parenteser som används till att tala om för dem på vilket innehåll som kommandot måste arbeta med: type(), int(), str(), etc. Det enda undantaget är print kommandot, vilket faktiskt inte är ett undantag, det fungerar också normalt så här: print("hello"), men eftersom det används ofta, så har python programmerarna gjort en förenklad version.
<syntaxhighlight>


===Listor===
En annan intressant datatyp är listor. En lista är helt enkelt en lista med annan data. På samma sätt som vi definierar en text sträng genom att använda " ", så definierar vi listor genom att använda [ ]:

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:

<syntaxhighlight>
Du ser att de kan innehålla vilken data som helst. Listor är väldigt användbara därför att du kan samla ihop variabler i grupper. Du kan sedan göra allt möjligt i dessa grupper, till exempel räkna dem:

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

or retrieving one item of a list:

<syntaxhighlight>
eller hämta en punkt i listan:

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:

<syntaxhighlight>
Du ser att medan len() kommandot returnerar det totala antalet punkter i en lista, så börjar deras "position" i listan med 0. Den första punkten i en lista är alltid i position 0, så i vår myOtherList, så kommer "Bob" att vara i position 2. Vi kan göra mycket mer saker med listor som du kan läsa [http://diveintopython.org/native_data_types/lists.html här], som att sortera innehåll, ta bort eller lägga till element.


En rolig och intressant sak för dig: en textsträng är i själva verket en lista med tecken! Försök att göra detta:

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


==Indentation==
Vanligtvis så kan allt som kan göras med listor, även göras med strängar.


Förutom strängar, heltal, flyttal och listor, så finns det mer inbyggda datatyper, som [http://www.diveintopython.org/getting_to_know_python/dictionaries.html ordböcker], eller så kan du skapa dina egna datatyper med[http://www.freenetpages.co.uk/hp/alan.gauld/tutclass.htm klasser].


===Indrag===
En annan sak man kan göra med listor är att köra igenom dem och göra något med varje punkt. Titta till exempel på detta:


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.
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.
Vi itererade (programmeringsslang igen!) genom vår lista med "for ... in ..." kommandot och gjorde något med varje punkt. Notera den speciella syntaxen: for kommandot avslutas med : vilket indikerar att det som kommer efter är ett block av ett eller fler kommandon. Omedelbart efter att du har skrivit en kommandorad som slutar med :, så kommer kommandoprompten att ändras till ... vilket betyder att python vet att en :-avslutad rad har skrivits och att det som kommer efter kommer att vara en del av det.


Hur ska python veta hur många rader som ska utföras innanför for...in operationen? För det, så använder python indrag. Det innebär att de efterkommande raderna inte kommer börja längst till vänster. Du påbörjar dem med ett eller flera mellanslag, eller en eller flera tabbar. Andra programmeringsspråk använder andra metoder, som att skriva allt innanför parenteser, etc.

Så länge som du skriver dina nästa rader med '''samma''' indrag, så anses de vara en del av for-in blocket. Om du börjar en rad med 2 mellanslag och nästa med 4, så kommer du att få ett fel.

När du är klar med blocket, skriv bara en annan rad utan indrag, eller tryck på enter för att komma tillbaka från for-in blocket


Indrag är bra därför om du gör stora (till exempel använder tabbar istället för mellanslag), så syns det lättare vad som utförs inuti vad, när du skriver större program. Vi kommeer att se att många andra kommandon än for-in kan ha indragna kodblock.


For-in kommandon kan användas till många saker som måster göras mer än en gång. Det kan till exempel kombineras med range() ¨kommandot:


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 237: Line 198:
print "----"
print "----"
print total
print total
</syntaxhighlight>

Or more complex things like this:

<syntaxhighlight>
Eller mer komplexa saker som detta:

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:

<syntaxhighlight>
Du ser att range() kommandot också har den egenskapen att den börjar med 0 (om du inte specificerar startnumret) och att dess sista nummer kommer bli en mindre än det slutnummer du specificerar. Detta är så för att det ska fungera bra ihop med andra python kommandon. Till exempel:

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:

<syntaxhighlight>
Ett annat intressant bruk av indragna block är med if kommandot. If utför endast ett kodblock om ett visst villkor är uppfyllt, till exempel:

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>
Detta kommer förstås alltid skriva ut det första ordet, men försök genom att byta ut den andra raden med:

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

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

<syntaxhighlight>
Då skrivs inget ut. Vi kan också specificera ett else: kommando:

alldaltons = ["Joe", "William", "Jack", "Averell"]
alldaltons = ["Joe", "William", "Jack", "Averell"]
if "Lucky" in alldaltons:
if "Lucky" in alldaltons:
Line 273: 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:

<syntaxhighlight>
===Funktioner===
[http://docs.python.org/reference/lexical_analysis.html#identifiers standard python kommandon] är inte så många. I nuvarande python version finns det omkring 30, och vi känner redan till flera av dem. Men tänk dig om vi kunde uppfinna våra egna kommandon? Det kan vi, och det är mycket lätt. Faktum är att de flesta av de extra moduler som du kan plugga in i din python installation gör just det, de lägger till kommandon som du kan använda. Ett hemmagjort kommando i python kallas för en funktion och görs så här:

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:

<syntaxhighlight>
Väldigt enkelt: def() kommandot definierar en ny funktion. du ger den ett namn, och inuti parenteserna så definieras de argument som vi ska använda i vår funktion. Argument är data som ska skickas till funktionen. Till exempel, titta på len() kommandot. Om du bara skriver len() , så kommer python att tala om för dig att det behöver ett argument. För du vill ha len() av något, eller hur? Sedan skriver du till exempel len(myList) och du får längden av myList. så, myList är ett argument som du skickar till funktionen len(). len() funktionen är definierad på ett sådant sätt att den vet vad den ska göra med det som skickas till den. Samma som vi gjorde här.


"myValue" namnet kan vara vad som helst, och kommer bara att användas inuti funktionen. det är bara ett namn som du ger till argumentet så att du kan göra något med det men den ser också till så att funktionen vet hur många argument den ska färvänta sig. Om du till exempel gör detta:

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>
Så kommer det bli fel. Vår funktion var programmerad till att ta emot endast ett argument, men det tog emot två, 45 och 34. vi skulle istället gjort som detta:

def sum(val1,val2):
def sum(val1,val2):
total = val1 + val2
total = val1 + val2
Line 300: 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:

<syntaxhighlight>
Vi gjorde en funktion som tar emot två argument, summerar dem, och returnerar det värdet. Att returnera något är mycket användbart, eftersom vi kan göra något med resultatet, som att lagra den i variabeln myTotal. Eftersom vi är i tolken och allt skrivs ut, så kommer följande:

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:

<syntaxhighlight>
att skriva ut resultatet på skärmen, men utanför tolken, eftersom det inte finns något print kommando inuti funktionen, så kommer inget fram på skärmen. Du skulle behöva göra:

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


Now that we have a good idea of how Python works, we'll need one last thing: How to work with files and modules.
för att få något utskrivet. Läs mer om funktioner [http://www.penzilla.net/tutorials/python/functions/ här].


===Moduler===
Nu när vi har en god uppfattning om hur python fungerar så behöver vi en sak till: Hur man arbetar med filer och moduler.


Tills nu så har vi skrivit python instruktioner rad för rad i tolkaren. Men om vi kunde skriva flera rader, och köra dem allihop på en gång? Det skulle vara smidigare för att göra mer komplexa saker. Och vi skulle kunna spara vårt arbete också. Även det är väldigt lätt. Öppna en textredigerare (som till exempel windows anteckningar), och skriv alla dina python rader, på samma sätt som du skriver dem i tolken, med indrag, etc. Spara sedan den filen någonstans, föredragsvis med filtypen .py . Sådär, nu har du ett komplett pythonprogram. Det finns förstås mycket bättre redigerare än anteckningar, men det är bara för att visa dig att ett pythonprogram inte är något annat än en textfil.



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.
Det finns hundratals sätt att få python att köra det programmet. I windows, högerklicka på din fil, öppna den med python, och kör den. Men du kan också köra den från pythontolken. För att kunna göra detta, så måste tolken veta var ditt .py program är. I FreeCAD, så är den bästa platsen att placera dina program på ett ställe som FreeCAD's pythontolk redan känner till, som till exempel FreeCAD's bin mapp, eller någon av Mod mapparna. Anta att vi skriver en fil som denna:


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):
<syntaxhighlight>
def sum(a,b):
return a + b
return a + b


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


och vi sparar den som test.py i vår FreeCAD/bin katalog. Låt oss nu starta FreeCAD, och i tolkfönstret skriva:


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:

<syntaxhighlight>
utan filtypen .py . Detta kommer att köra filens innehåll, rad för rad, precis som om vi hade skrivit den i tolken. Sum funktionen kommer att skapas, och meddelandet kommer att skrivas ut. Det finns en stor skillnad: import kommandot finns inte bara för att köra program som är skrivna i en fil, som vår, utan även för att ladda funktioner, så de finns tillgängliga för tolken. Filer som innehåller funktioner, som vår, kallas för moduler.


Normalt, när vi skriver en sum() funktion i tolken, så kör vi den så här:

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:

<syntaxhighlight>
Som vi gjorde tidigare. När vi importerar en modul som innehåller vår sum() funktion, så skiljer sig syntaxen lite. Vi gör:

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>
Vilket innebär att modulen importeras som en "behållare", och alla dess funktioner är inuti. Detta är väldigt användbart, eftersom vi kan importera många moduler, och hålla allt välorganiserat. Så överallt där du ser Något.NågotAnnat, med en punkt emellan, innebär att NågotAnnat är inuti Något.


Vi kan också strunta i test delen, och importera vår sum() funktion direkt i tolkens huvudutrymme, som så här:

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:

<syntaxhighlight>
I enkelhet så beter sig alla moduler så. Du importerar en modul, sedan kan du använda dess funktioner så här: modul.funktion(argument). Nästan alla moduler gör så: de definierar funktioner, nya datatyper och klasser som du kan använda i tolken eller i dina egna pythonmoduler, för det är inget som hindrar dig från att importera moduler inuti din modul!


En sista mycket användbar sak. Hur vet vi vilka moduler vi har, vilka funktioner är inne i dem och hur ska man använda dem (vilken sorts argument behöver de)? Vi har redan sett att python har en help() funktion. Genom att göra:

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

<syntaxhighlight>
Kommer att ge oss en lista på alla tillgängliga moduler. Vi kan nu skriva q för att komma ut från den interaktiva hjälpen, och importera någon av dem. Vi kan även lista deras innehåll med dir() kommandot

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

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>
Vi kommer att se alla funktioner som math modulen innehåller, såvär som konstiga saker med namnen __doc__, __file__, __name__. __doc__ är väldigt användbart, det är en dokumentationstext. Varje funktion i (välgjorda) moduler har en __doc__ som förklarar hur man använder den. Till exempel så ser vi att det finns en sin funktion inuti math modulen. Vill du veta hur du använder den?

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:
<syntaxhighlight>
import myModule
myModule.myTestFunction()
</syntaxhighlight>
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)
</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

<syntaxhighlight>
===Starta med FreeCAD===
Nu bör du ha en god ide om hur python fungerar, och du kan börja utforska vad FreeCAD har att erbjuda. FreeCAD's python funktioner är välorganiserade i olika moduler. En del av dem är redan laddade (importerade) när du startar FreeCAD. Så gör bara

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:

* the [http://docs.python.org/3/tutorial/index.html official Python tutorial with way more information than this one]
and fortsätt läsa [[FreeCAD Scripting Basics/sv|FreeCAD Skript grunder]]...
* the [http://docs.python.org/reference/ official Python reference]

* the [http://www.diveintopython.net Dive into Python] wikibook/ book.

Be sure to bookmark them!
Vi såg förstås här bara en mycket liten del av python världen. Det finns många viktiga koncept som vi inte har nämnt här. Det finns två mycket viktiga python referensdokument på nätet:

* [http://docs.python.org/reference/ officiell Python referens]
* [http://www.diveintopython.org/toc/index.html Dive into Python] wikibook

Bokmärk dem!




{{docnav/sv|Macros/sv|FreeCAD Scripting Basics/sv}}
{{docnav|Macros|Python scripting tutorial}}


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


{{clear}}
[[Category:Poweruser Documentation/sv]]
<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