Introduction to Python

From FreeCAD Documentation
Revision as of 15:44, 10 September 2009 by Yorik (talk | contribs) (Created page with 'This is a short tutorial made for who is totally new to python. [ Python] is an open-source, multiplatform [http://e…')
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to navigation Jump to search

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.

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 linux), you will have a python interpreter in your start menu. But FreeCAD also has a python interpreter in its bottom part:

Screenshot pythoninterpreter.jpg

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:


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:


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.


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.


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"

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

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:

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"

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.


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


or retrieving one item of a list:

myName = myOtherList[0]
myFriendsName = myOtherList[1]

You see that while the len() command returns the total number of items in a list, their "position" in the list begins with 0. The first item in a list is always at position 0, so in our myOtherList, "Bob" will be at position 2. We can do much more stuff with lists such as you can read here, such as sorting contents, removing or adding elements.

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

myvar = "hello"

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


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