Introduction to Python: Difference between revisions

From FreeCAD Documentation
(Revising...)
No edit summary
Line 620: Line 620:
* The [http://docs.python.org/3/tutorial/index.html official Python tutorial with way more information than this one]
* 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]
* The [http://docs.python.org/reference/ official Python reference]
Be sure to bookmark them!


<!--T:171-->
<!--T:171-->

Revision as of 10:59, 15 May 2020

This documentation is a work in progress. Please don't mark it as translatable since it will change in the next hours and days.


Introduction

This is a short tutorial for those new to Python. Python is an open-source, multiplatform programming language. It has several features that make it different from other programming languages, and very accessible to new users:

  • It has been designed to be to readable by human beings, making it relatively easy to learn and understand.
  • It is interpreted, this means that programs do not need to be compiled before they can be executed. Python code can be executed immediately, even line by line if you wish.
  • It can be embedded in other programs as a scripting language. FreeCAD has an embedded Python interpreter. You can write Python code in FreeCAD that will manipulate parts of FreeCAD, for example, to create geometry. This is very powerful, instead of just clicking a button labeled "create sphere" that some programmer has coded, you have the freedom to build your own tools.
  • It is extensible, you can easily plug new modules into your Python installation and extend its functionality. For example, there are modules that allow Python to read and write images, to communicate with Twitter, to schedule tasks to be performed by your operating system, etc.

The following is a very basic introduction, and by no means a complete tutorial. But our hope is that it will provide a good starting point for further exploration into FreeCAD and its mechanisms. We strongly encourage you to enter the code snippets below into a Python interpreter.

Python version information

FreeCAD was originally designed to work with Python 2. Since Python 2 reached the end of its life in 2020, future development of FreeCAD will be done exclusively with Python 3, and backwards compatibility will not be supported.

The interpreter

Usually, when writing computer programs, you open a text editor or your special programming environment (which is basically a text editor with several additional tools), write your program, then compile and execute. Often one or more errors were made during entry, so your program won't work. You may even get an error message telling you what went wrong. Then you go back to your text editor, correct the mistakes, run again, repeating until your program works as intended.

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

The FreeCAD Python console

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

The interpreter shows the Python version, then a >>> symbol which is the command prompt 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 Python command that, obviously, prints 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 you so. In this case it doesn't know what hello is. The " " characters specify that the content is a string, programming jargon for a piece of text. Without these the print() command doesn't recognize hello. The important thing is, you immediately get notified that you have made an error. By pressing the up arrow you can go back to the last line of code and correct it.

The Python interpreter also has a built-in help system. Let's say we don't understand what went wrong with our print hello command above and 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 that you understand the Python interpreter, we can continue with the more serious stuff.

Variables

Very often in programming you need to store a value under a name. That's where the concept of the variable comes in. For example, type this:

a = "hello"
print(a)

You probably understand what happened here, we saved the string "hello" under the name a. Now that a is known we can use it anywhere, for example in the print() command. We can use any name we want, we just need to follow some simple rules, like not using spaces or punctuation. For example, we can write:

hello = "my own version of hello"
print(hello)

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

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 important to give meaningful names to your variables. After a while you won't remember what your variable named a represents. But if you named it, for example, myWelcomeMessage you'll easily remember its purpose. Plus your code is a step closer to being self-documenting.

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

Numbers

Of course Python programs can deal with all kinds of data, 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. By using " " characters, we told specifically that what follows is a text string.

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

myVar = "hello"
type(myVar)

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

firstNumber = 10
secondNumber = 20
print(firstNumber + secondNumber)
type(firstNumber)

We now have a powerful calculator! Look at how well 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)

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

var1 = 13
var2 = 15.65
print("var1 is of type ", type(var1))
print("var2 is of type ", type(var2))

Integers and Floats can be mixed together without problems:

total = var1 + var2
print(total)
print(type(total))

Of course the total has decimals, and therefore Python automatically decides that the result must be a float. But there are also cases where Python does not knows what type to use. For example:

varA = "hello 123"
varB = 456
print(varA + varB)

This will give us an error, varA is a string and varB is an integer, and Python doesn't know what to do. However, we can force Python to convert between types:

varA = "hello"
varB = 123
print(varA + str(varB))

Now that 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))

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 another Python command. Maybe you also saw that these two commands:

type(varA)
print(type(varA))

have the same result. This is because we are in the interpreter, and everything is automatically printed. When we write more complex programs that run outside the interpreter, they won't print automatically, so we'll need to use the print() command. With that in mind let's stop using it here. From now on we will simply write:

myVar = "hello friends"
myVar

Lists

Another interesting data type is a list. A list is a collection of other data. The same way that we define a text string by using " ", we define a list by using [ ]:

myList = [1, 2, 3]
type(myList)
myOtherList = ["Bart", "Frank", "Bob"]
myMixedList = ["hello", 345, 34.567]

As you can see a list can contain any type of data. Lists are very useful because you can group values together. You can do many things with a list, for example, count its items:

len(myOtherList)

Or retrieving one item:

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

While the len() command returns the total number of items in a list, 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 with lists such as sorting contents and removing or adding elements.

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

myvar = "hello"
len(myvar)
myvar[2]

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

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

Indentation

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

alldaltons = ["Joe", "William", "Jack", "Averell"]
for dalton in alldaltons:
    print(dalton + " Dalton")

We iterated (programming jargon) 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 : indicating the following will be a block of one of more commands. In the interpreter, immediately after you enter the command line ending with :, the command prompt will change to ... which means Python knows that there is more to come.

How will Python know how many of the next lines will 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 everything 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 have finished, just write another line without indentation, or simply press Enter to come back from the for-in block

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

The for-in command 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)

If you have been running the code examples in an interpreter by copy-pasting, you will find the previous block of text will throw an error. Instead, copy to the end of the indented block, i.e. the end of the line "total = total + number" and then paste in the interpreter. In the interpreter issue an Enter until the three dot prompt disappears and the code runs. Then copy the final two lines followed by another Enter. The final answer should appear.

If you type into the interpreter help(range) you will see:

range(...)
    range(stop) -> list of integers
    range(start, stop[, step]) -> list of integers

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

number = 1000
for i in range(0, 180 * number, int(0.5 * number)):
    print(float(i) / number)

Another range() example:

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

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. This command 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 sentence, but try replacing the second line with:

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

There are very few standard Python commands. In the 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 quite easy. In fact, most of the additional modules that you can plug into your Python installation do just that, they add commands that you can use. A custom command in Python is called a function and is made like this:

def printsqm(myValue):
    print(str(myValue) + " square meters")

printsqm(45)

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

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

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

myTotal = sum(45, 34)

Here we made a function that receives two arguments, sums them, and returns that value. Returning something is very useful, because we can do something with the result, such as store it in the 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 print() command inside the function, nothing would appear on the screen. To have something printed you would need to use:

print(sum(45, 34))

Modules

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

Until now, we have written Python instructions line by line in the interpreter. But 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 quite easy. Simply open a text editor (such as Windows Notepad, Linux gedit, emacs, or vi), 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. And 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 more than a text file.

There are several of ways to execute a Python program. In Windows, simply right-click your file, open it with Python, and execute it. But you can also execute it from the Python interpreter itself. For this, the interpreter must know where your program is. In FreeCAD the easiest way is to place your program in a folder that FreeCAD's Python interpreter knows by default, such as FreeCAD's bin folder, or any of the Mod folders. (In Linux, you probably have a directory /home/<username>/.FreeCAD/Mod, let's add a subdirectory to that called scripts where we will put the text file.) Suppose we write a file like this:

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

print("myTest.py succesfully loaded")

and we save it as myTest.py in our FreeCAD/bin directory (or on Linux to /home/<username>/.FreeCAD/Mod/scripts.) Now, let's start FreeCAD, and in the interpreter window, write:

import myTest

without the .py extension. This will execute the contents of the file, line by line, just as if we had written it in the interpreter. The sum function will be created, and the message will be printed. Files containing functions, like ours, are called modules.

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

sum(14,45)

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

myTest.sum(14,45)

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

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

from myTest import *
sum(12,54)

Basically all modules behave like that. You import a module and then you can use its functions: 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 from importing other modules inside your module!

One last very 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 have already seen that Python has a help() function. Doing:

help("modules")

will give us a list of all available modules. We can import any of them and 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__. Every function in a well made module has a __doc__ that explains how to use it. For example, we see that there is a sin function inside the math module. Want to know how to use it?

print(math.sin.__doc__)

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

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

reload(myModule)

There is however an alternative:

exec(open("C:/PathToMyMacro/myMacro.FCMacro").read())

Starting with FreeCAD

Hopefully you now have a good idea of how Python works, and you can start exploring what FreeCAD has to offer. FreeCAD's Python functions are all well organized in different modules. Some of them are already loaded (imported) when you start FreeCAD. Just try:

dir()

Of course there are many important concepts that we haven't mention here. Much more information can be found in these Python resources: