Introduction to Python: Difference between revisions
m ([[ | ]]) |
Marc-Medley (talk | contribs) m (updated: Mac OSX…/Preferences/… to macOS …/Application Support/…) |
||
(102 intermediate revisions by 3 users not shown) | |||
Line 1: | Line 1: | ||
<languages/> |
<languages/> |
||
<translate> |
<translate> |
||
<!--T:183--> |
<!--T:183--> |
||
{{Docnav |
|||
{{docnav|Macros|Python scripting tutorial}} |
|||
|[[Scripts|Scripts]] |
|||
|[[Python_scripting_tutorial|Python scripting tutorial]] |
|||
}} |
|||
</translate> |
|||
{{TOCright}} |
|||
<translate> |
|||
<!--T: |
==Introduction== <!--T:187--> |
||
{{VeryImportantMessage|(November 2018) FreeCAD was originally designed to work with Python 2. Many features work with Python 3, but some do not. Making FreeCAD fully support Python 3 is a work in process. |
|||
The information here describes Python 2, but most of the code should work the same with Python 3. In particular, the {{incode|print()}} function is preferred over the old {{incode|print}} statement.}} |
|||
<!--T:87--> |
<!--T:87--> |
||
This is a short tutorial for those new to |
This is a short tutorial for those new to [https://en.wikipedia.org/wiki/Python_%28programming_language%29 Python]. Python is an open-source, multiplatform [https://en.wikipedia.org/wiki/Programming_language programming language]. It has several features that make it different from other programming languages, and very accessible to new users: |
||
<!--T:88--> |
<!--T:88--> |
||
*It has been designed |
*It has been designed to be to readable by human beings, making it relatively easy to learn and understand. |
||
*It is interpreted, |
*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 |
*It can be embedded in other programs as a scripting language. FreeCAD has an embedded Python interpreter. You can write Python code to manipulate parts of FreeCAD. This is very powerful, it means you can build your very own tools. |
||
*It is extensible, you can easily plug new modules |
*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. |
||
<!--T:89--> |
<!--T:89--> |
||
The following is a very basic introduction, and by no means a complete tutorial. But hopefully 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. |
|||
We strongly encourage you to enter the code snippets below into a Python interpreter. For many of our discussions, the important point is the line after the snippet is run, the reveal. Not running the code would be all build up, without a punch line. So, hands on! The following is a very simple introduction, and by no means a complete tutorial. But our hope is that this will provide enough basics to explore deeper into the FreeCAD mechanisms. |
|||
==The interpreter== <!--T:90--> |
==The interpreter== <!--T:90--> |
||
<!--T:91--> |
<!--T:91--> |
||
Usually |
Usually when writing computer programs, you open a text editor or your special programming environment (which is basically a text editor with some 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. |
||
<!--T:92--> |
<!--T:92--> |
||
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 [https://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, as already mentioned, FreeCAD also has a built-in Python interpreter: the [[Python_console|Python console]]. |
|||
</translate> |
|||
[[Image:FreeCAD_Python_console.png]] |
|||
<translate> |
|||
<!--T:93--> |
<!--T:93--> |
||
{{Caption|The FreeCAD Python console}} |
|||
[[Image:Screenshot_pythoninterpreter.jpg]] |
|||
<!--T:94--> |
<!--T:94--> |
||
If you don't see it, click on {{MenuCommand|View → Panels → Python console}}. The Python console can be resized and also undocked. |
|||
<!--T:95--> |
<!--T:95--> |
||
The interpreter shows the Python version, then a >>> symbol |
The interpreter shows the Python version, then a {{incode|>>>}} symbol which is the command prompt. Writing code in the interpreter is simple: one line is one instruction. When you press {{KEY|Enter}}, your line of code will be executed (after being instantly and invisibly compiled). For example, try writing this: |
||
</translate> |
</translate> |
||
{{Code|code= |
{{Code|code= |
||
print |
print("hello") |
||
}} |
}} |
||
<translate> |
<translate> |
||
<!--T:96--> |
<!--T:96--> |
||
{{incode|print()}} is a Python command that, obviously, prints something on the screen. When you press {{KEY|Enter}}, the operation is executed, and the message {{incode|"hello"}} is printed. If you make an error, for example let's write: |
|||
</translate> |
</translate> |
||
{{Code|code= |
{{Code|code= |
||
print |
print(hello) |
||
}} |
}} |
||
<translate> |
<translate> |
||
<!--T:97--> |
<!--T:97--> |
||
Python will tell |
Python will immediately tell you so. In this case Python doesn't know what {{incode|hello}} is. The {{incode|" "}} characters specify that the content is a string, programming jargon for a piece of text. Without these the {{incode|print()}} command doesn't recognize {{incode|hello}}. By pressing the up arrow you can go back to the last line of code and correct it. |
||
<!--T:98--> |
<!--T:98--> |
||
The Python interpreter also has a built-in help system. |
The Python interpreter also has a built-in help system. Let's say we don't understand what went wrong with {{incode|print(hello)}} and we want specific information about the command: |
||
</translate> |
|||
{{Code|code= |
|||
help |
|||
}} |
|||
<translate> |
|||
<!--T:99--> |
|||
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: |
|||
</translate> |
</translate> |
||
{{Code|code= |
{{Code|code= |
||
Line 65: | Line 72: | ||
}} |
}} |
||
<translate> |
<translate> |
||
<!--T:100--> |
<!--T:100--> |
||
You'll get a long and complete description of everything the print command can do. |
You'll get a long and complete description of everything the {{incode|print()}} command can do. |
||
<!--T:101--> |
<!--T:101--> |
||
Now that |
Now that you understand the Python interpreter, we can continue with the more serious stuff. |
||
</translate>{{Top}}<translate> |
|||
==Variables== <!--T:102--> |
==Variables== <!--T:102--> |
||
<!--T:103--> |
<!--T:103--> |
||
Very often in programming you need to store a value under a name. That's where variables come in. For example, type this: |
|||
</translate> |
</translate> |
||
{{Code|code= |
{{Code|code= |
||
a = "hello" |
a = "hello" |
||
print |
print(a) |
||
}} |
}} |
||
<translate> |
<translate> |
||
<!--T:104--> |
<!--T:104--> |
||
You probably understand what happened here, we saved the string {{incode|"hello"}} under the name {{incode|a}}. Now that {{incode|a}} is known we can use it anywhere, for example in the {{incode|print()}} command. We can use any name we want, we just need to follow some simple rules, such as not using spaces or punctuation and not using Python keywords. For example, we can write: |
|||
</translate> |
</translate> |
||
{{Code|code= |
{{Code|code= |
||
hello = "my own version of hello" |
hello = "my own version of hello" |
||
print |
print(hello) |
||
}} |
}} |
||
<translate> |
<translate> |
||
<!--T:105--> |
<!--T:105--> |
||
Now {{incode|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: |
|||
</translate> |
|||
{{Code|code= |
|||
print = "hello" |
|||
}} |
|||
<translate> |
|||
<!--T:106--> |
|||
Python is very intelligent and will tell us that this is not possible. It has some "reserved" keywords that cannot be modified. But our variables can be modified any time, that's why they are called variables, the contents can vary. For example: |
|||
</translate> |
</translate> |
||
{{Code|code= |
{{Code|code= |
||
myVariable = "hello" |
myVariable = "hello" |
||
print |
print(myVariable) |
||
myVariable = "good bye" |
myVariable = "good bye" |
||
print |
print(myVariable) |
||
}} |
}} |
||
<translate> |
<translate> |
||
<!--T:107--> |
<!--T:107--> |
||
We changed the value of myVariable. We can also copy variables: |
We changed the value of {{incode|myVariable}}. We can also copy variables: |
||
</translate> |
</translate> |
||
{{Code|code= |
{{Code|code= |
||
var1 = "hello" |
var1 = "hello" |
||
var2 = var1 |
var2 = var1 |
||
print |
print(var2) |
||
}} |
}} |
||
<translate> |
<translate> |
||
<!--T:108--> |
<!--T:108--> |
||
It is advisable to give meaningful names to your variables. After a while you won't remember what your variable named {{incode|a}} represents. But if you named it, for example, {{incode|myWelcomeMessage}} you'll easily remember its purpose. Plus your code is a step closer to being self-documenting. |
|||
<!--T:179--> |
<!--T:179--> |
||
Case is very important |
Case is very important, {{incode|myVariable}} is not the same as {{incode|myvariable}}. If you were to enter {{incode|print(myvariable)}} it would come back with an error as not defined. |
||
</translate>{{Top}}<translate> |
|||
==Numbers== <!--T:109--> |
==Numbers== <!--T:109--> |
||
<!--T:110--> |
<!--T:110--> |
||
Of course |
Of course Python programs can deal with all kinds of data, not just 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 {{incode|print()}} command recognized our {{incode|"hello"}} string. By using {{incode|" "}} characters, we specified that what follows is a text string. |
||
<!--T:111--> |
<!--T:111--> |
||
We can always check the data type of a variable with the |
We can always check the data type of a variable with the {{incode|type()}} command: |
||
</translate> |
</translate> |
||
{{Code|code= |
{{Code|code= |
||
Line 134: | Line 148: | ||
}} |
}} |
||
<translate> |
<translate> |
||
<!--T:112--> |
<!--T:112--> |
||
It will tell us the |
It will tell us the content of {{incode|myVar}} is a {{incode|'str'}}, which is short for string. We also have other basic data types such as integer and float numbers: |
||
</translate> |
</translate> |
||
{{Code|code= |
{{Code|code= |
||
firstNumber = 10 |
firstNumber = 10 |
||
secondNumber = 20 |
secondNumber = 20 |
||
print |
print(firstNumber + secondNumber) |
||
type(firstNumber) |
type(firstNumber) |
||
}} |
}} |
||
<translate> |
<translate> |
||
<!--T:113--> |
<!--T:113--> |
||
Python knows that 10 and 20 are integer numbers, so they are stored as {{incode|'int'}}, and Python can do with them everything it can do with integers. Look at the results of this: |
|||
</translate> |
</translate> |
||
{{Code|code= |
{{Code|code= |
||
firstNumber = "10" |
firstNumber = "10" |
||
secondNumber = "20" |
secondNumber = "20" |
||
print |
print(firstNumber + secondNumber) |
||
}} |
}} |
||
<translate> |
<translate> |
||
<!--T:114--> |
<!--T:114--> |
||
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 perform any arithmetic. 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: |
|||
</translate> |
</translate> |
||
{{Code|code= |
{{Code|code= |
||
var1 = 13 |
var1 = 13 |
||
var2 = 15.65 |
var2 = 15.65 |
||
print |
print("var1 is of type ", type(var1)) |
||
print |
print("var2 is of type ", type(var2)) |
||
}} |
}} |
||
<translate> |
<translate> |
||
<!--T:115--> |
<!--T:115--> |
||
Integers and floats can be mixed together without problems: |
|||
</translate> |
</translate> |
||
{{Code|code= |
{{Code|code= |
||
total = var1 + var2 |
total = var1 + var2 |
||
print |
print(total) |
||
print |
print(type(total)) |
||
}} |
}} |
||
<translate> |
<translate> |
||
<!--T:116--> |
<!--T:116--> |
||
Because {{incode|var2}} is a float Python automatically decides that the result must also be a float. But there are cases where Python does not knows what type to use. For example: |
|||
</translate> |
</translate> |
||
{{Code|code= |
{{Code|code= |
||
varA = "hello 123" |
varA = "hello 123" |
||
varB = 456 |
varB = 456 |
||
print |
print(varA + varB) |
||
}} |
}} |
||
<translate> |
<translate> |
||
<!--T:117--> |
<!--T:117--> |
||
This |
This results in an error, {{incode|varA}} is a string and {{incode|varB}} is an integer, and Python doesn't know what to do. However, we can force Python to convert between types: |
||
</translate> |
</translate> |
||
{{Code|code= |
{{Code|code= |
||
varA = "hello" |
varA = "hello" |
||
varB = 123 |
varB = 123 |
||
print |
print(varA + str(varB)) |
||
}} |
}} |
||
<translate> |
<translate> |
||
<!--T:118--> |
<!--T:118--> |
||
Now both are strings |
Now that both variables are strings the operation works. Note that we "stringified" {{incode|varB}} at the time of printing, but we didn't change {{incode|varB}} itself. If we wanted to turn {{incode|varB}} permanently into a string, we would need to do this: |
||
</translate> |
</translate> |
||
{{Code|code= |
{{Code|code= |
||
Line 197: | Line 225: | ||
}} |
}} |
||
<translate> |
<translate> |
||
<!--T:119--> |
<!--T:119--> |
||
We can also use int() and float() to convert to |
We can also use {{incode|int()}} and {{incode|float()}} to convert to integer and float if we want: |
||
</translate> |
</translate> |
||
{{Code|code= |
{{Code|code= |
||
varA = "123" |
varA = "123" |
||
print |
print(int(varA)) |
||
print |
print(float(varA)) |
||
}} |
}} |
||
<translate> |
<translate> |
||
<!--T:120--> |
|||
'''Note on Python commands''' |
|||
<!--T:121--> |
<!--T:121--> |
||
You must have noticed that |
You must have noticed that we have used the {{incode|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: |
||
</translate> |
</translate> |
||
{{Code|code= |
{{Code|code= |
||
type(varA) |
type(varA) |
||
print |
print(type(varA)) |
||
}} |
}} |
||
<translate> |
<translate> |
||
<!--T:122--> |
<!--T:122--> |
||
have |
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 {{incode|print()}} command. With that in mind let's stop using it here. From now on we will simply write: |
||
</translate> |
</translate> |
||
{{Code|code= |
{{Code|code= |
||
Line 225: | Line 256: | ||
}} |
}} |
||
<translate> |
<translate> |
||
<!--T:123--> |
|||
</translate>{{Top}}<translate> |
|||
You must have seen that most of the Python commands (or keywords) type(), int(), str(), etc. have parenthesis to limit the command contents. The only exception is the print command, which in fact is not really an exception, as it also works normally: print("hello"). However, since it is used often, the Python designers allowed a simpler version. |
|||
==Lists== <!--T:124--> |
==Lists== <!--T:124--> |
||
<!--T:125--> |
<!--T:125--> |
||
Another |
Another useful data type is a list. A list is a collection of other data. To define a list we use {{incode|[ ]}}: |
||
</translate> |
</translate> |
||
{{Code|code= |
{{Code|code= |
||
myList = [1,2,3] |
myList = [1, 2, 3] |
||
type(myList) |
type(myList) |
||
myOtherList = ["Bart", "Frank", "Bob"] |
myOtherList = ["Bart", "Frank", "Bob"] |
||
Line 240: | Line 272: | ||
}} |
}} |
||
<translate> |
<translate> |
||
<!--T:126--> |
<!--T:126--> |
||
As you can see a list can contain any type of data. You can do many things with a list. For example, count its items: |
|||
</translate> |
</translate> |
||
{{Code|code= |
{{Code|code= |
||
Line 247: | Line 281: | ||
}} |
}} |
||
<translate> |
<translate> |
||
<!--T:127--> |
<!--T:127--> |
||
Or retrieve one item: |
|||
</translate> |
</translate> |
||
{{Code|code= |
{{Code|code= |
||
Line 255: | Line 291: | ||
}} |
}} |
||
<translate> |
<translate> |
||
<!--T:128--> |
<!--T:128--> |
||
While the {{incode|len()}} command returns the total number of items in a list, the first item in a list is always at position {{incode|0}}, so in our {{incode|myOtherList}} {{incode|"Bob"}} will be at position {{incode|2}}. We can do much more with lists such as sorting items and removing or adding items. |
|||
<!--T:129--> |
<!--T:129--> |
||
Interestingly a text string is very similar to a list of characters in Python. Try doing this: |
|||
</translate> |
</translate> |
||
{{Code|code= |
{{Code|code= |
||
Line 267: | Line 305: | ||
}} |
}} |
||
<translate> |
<translate> |
||
<!--T:130--> |
<!--T:130--> |
||
Usually |
Usually what you can do with lists can also be done with strings. In fact both lists and strings are sequences. |
||
<!--T:131--> |
<!--T:131--> |
||
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. |
|||
</translate>{{Top}}<translate> |
|||
==Indentation== <!--T:132--> |
==Indentation== <!--T:132--> |
||
<!--T:133--> |
<!--T:133--> |
||
One |
One important use of lists is the ability to "browse" through them and do something with each item. For example look at this: |
||
</translate> |
</translate> |
||
{{Code|code= |
{{Code|code= |
||
alldaltons = ["Joe", "William", "Jack", "Averell"] |
alldaltons = ["Joe", "William", "Jack", "Averell"] |
||
for dalton in alldaltons: |
for dalton in alldaltons: |
||
print(dalton + " Dalton") |
|||
}} |
}} |
||
<translate> |
<translate> |
||
<!--T:134--> |
<!--T:134--> |
||
We iterated (programming jargon) through our list with the |
We iterated (programming jargon) through our list with the {{incode|for in}} command and did something with each of the items. Note the special syntax: the {{incode|for}} command terminates with {{incode|:}} indicating the following will be a block of one of more commands. In the interpreter, immediately after you enter the command line ending with {{incode|:}}, the command prompt will change to {{incode|...}} which means Python knows that there is more to come. |
||
<!--T:135--> |
<!--T:135--> |
||
How will Python know how many of the next lines will |
How will Python know how many of the next lines will need to be executed inside the {{incode|for in}} operation? For that, Python relies on indentation. The next lines must begin with a blank space, or several blank spaces, or a tab, or several tabs. And as long as the indentation stays the same the lines will be considered part of the {{incode|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 press {{KEY|Enter}} to come back from the {{incode|for in}} block |
||
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 |
|||
<!--T:136--> |
<!--T:136--> |
||
Indentation |
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 other commands use indented blocks of code as well. |
||
<!--T:137--> |
<!--T:137--> |
||
The {{incode|for in}} command can be used for many things that must be done more than once. It can, for example, be combined with the {{incode|range()}} command: |
|||
</translate> |
</translate> |
||
{{Code|code= |
{{Code|code= |
||
serie = range(1,11) |
serie = range(1, 11) |
||
total = 0 |
total = 0 |
||
print |
print("sum") |
||
for number in serie: |
for number in serie: |
||
print(number) |
|||
total = total + number |
total = total + number |
||
print |
print("----") |
||
print |
print(total) |
||
}} |
}} |
||
<translate> |
<translate> |
||
<!--T:173--> |
<!--T:173--> |
||
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 {{incode|total <nowiki>=</nowiki> total + number}} and then paste in the interpreter. In the interpreter press {{KEY|Enter}} until the three dot prompt disappears and the code runs. Then copy the final two lines followed by another {{KEY|Enter}}. The final answer should appear. |
|||
<!--T:180--> |
<!--T:180--> |
||
If you |
If you type into the interpreter {{incode|help(range)}} you will see: |
||
</translate> |
|||
{{Code|code= |
{{Code|code= |
||
range(...) |
range(...) |
||
Line 319: | Line 364: | ||
range(start, stop[, step]) -> list of integers |
range(start, stop[, step]) -> list of integers |
||
}} |
}} |
||
<translate> |
|||
Here the square brackets denote an optional parameter. However all are expected to be integers. Below we will force the range parameters to be an integer using int() |
|||
<!--T:192--> |
|||
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 {{incode|int()}}: |
|||
</translate> |
</translate> |
||
{{Code|code= |
{{Code|code= |
||
number = 1000 |
|||
decimales = 1000 # for 3 decimales |
|||
for i in range(0, 180 * number, int(0.5 * number)): |
|||
#decimales = 10000 # for 4 decimales ... |
|||
print(float(i) / number) |
|||
for i in range(int(0 * decimales),int(180 * decimales),int(0.5 * decimales)): |
|||
print float(i) / decimales |
|||
}} |
}} |
||
<translate> |
<translate> |
||
<!--T:138--> |
<!--T:138--> |
||
Another {{incode|range()}} example: |
|||
Or more complex things like this: |
|||
</translate> |
</translate> |
||
{{Code|code= |
{{Code|code= |
||
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) |
|||
}} |
}} |
||
<translate> |
<translate> |
||
<!--T:139--> |
<!--T:139--> |
||
The {{incode|range()}} command also has that strange particularity that it begins with {{incode|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: |
|||
</translate> |
</translate> |
||
{{Code|code= |
{{Code|code= |
||
Line 344: | Line 396: | ||
total = len(alldaltons) |
total = len(alldaltons) |
||
for n in range(total): |
for n in range(total): |
||
print(alldaltons[n]) |
|||
}} |
}} |
||
<translate> |
<translate> |
||
<!--T:140--> |
<!--T:140--> |
||
Another interesting use of indented blocks is with the if command. |
Another interesting use of indented blocks is with the {{incode|if}} command. This command executes a code block only if a certain condition is met, for example: |
||
</translate> |
</translate> |
||
{{Code|code= |
{{Code|code= |
||
alldaltons = ["Joe", "William", "Jack", "Averell"] |
alldaltons = ["Joe", "William", "Jack", "Averell"] |
||
if "Joe" in alldaltons: |
if "Joe" in alldaltons: |
||
print("We found that Dalton!!!") |
|||
}} |
}} |
||
<translate> |
<translate> |
||
<!--T:141--> |
<!--T:141--> |
||
Of course this will always print the |
Of course this will always print the sentence, but try replacing the second line with: |
||
</translate> |
</translate> |
||
{{Code|code= |
{{Code|code= |
||
Line 363: | Line 419: | ||
}} |
}} |
||
<translate> |
<translate> |
||
<!--T:142--> |
<!--T:142--> |
||
Then nothing is printed. We can also specify an else |
Then nothing is printed. We can also specify an {{incode|else}} statement: |
||
</translate> |
</translate> |
||
{{Code|code= |
{{Code|code= |
||
alldaltons = ["Joe", "William", "Jack", "Averell"] |
alldaltons = ["Joe", "William", "Jack", "Averell"] |
||
if "Lucky" in alldaltons: |
if "Lucky" in alldaltons: |
||
print("We found that Dalton!!!") |
|||
else: |
else: |
||
print("Such Dalton doesn't exist!") |
|||
}} |
}} |
||
<translate> |
<translate> |
||
</translate>{{Top}}<translate> |
|||
==Functions== <!--T:143--> |
==Functions== <!--T:143--> |
||
<!--T:144--> |
<!--T:144--> |
||
There are few [ |
There are very few [https://docs.python.org/3/reference/lexical_analysis.html#identifiers standard Python commands] and we already know several of them. But you can create your own commands. 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: |
||
</translate> |
</translate> |
||
{{Code|code= |
{{Code|code= |
||
def printsqm(myValue): |
def printsqm(myValue): |
||
print(str(myValue) + " square meters") |
|||
printsqm(45) |
printsqm(45) |
||
}} |
}} |
||
<translate> |
<translate> |
||
<!--T:145--> |
|||
(Another copy and paste error, only copy through the end of the indented section i.e. '''" square meters"''' Paste to the interpreter, and issue <enter> until the three dot prompt goes a way, then copy and paste the final line.) |
|||
<!--T:181--> |
<!--T:181--> |
||
The {{incode|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 {{incode|len()}} command. If you just write {{incode|len()}}, Python will tell you it needs an argument. Which is obvious: you want to know the length of something. If you write {{incode|len(myList)}} then {{incode|myList}} is the argument that you pass to the {{incode|len()}} function. And the {{incode|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 {{incode|printsqm}} function. |
|||
<!--T:146--> |
<!--T:146--> |
||
The |
The {{incode|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: |
||
</translate> |
</translate> |
||
{{Code|code= |
{{Code|code= |
||
printsqm(45,34) |
printsqm(45, 34) |
||
}} |
}} |
||
<translate> |
<translate> |
||
<!--T:147--> |
<!--T:147--> |
||
there will be an error. Our function was programmed to receive just one argument, but it received two, {{incode|45}} and {{incode|34}}. Let's try another example: |
|||
</translate> |
</translate> |
||
{{Code|code= |
{{Code|code= |
||
def sum(val1,val2): |
def sum(val1, val2): |
||
total = val1 + val2 |
total = val1 + val2 |
||
return total |
return total |
||
sum(45,34) |
myTotal = sum(45, 34) |
||
myTotal = sum(45,34) |
|||
}} |
}} |
||
<translate> |
<translate> |
||
<!--T:148--> |
<!--T:148--> |
||
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 {{incode|myTotal}} variable. |
|||
</translate> |
|||
</translate>{{Top}}<translate> |
|||
{{Code|code= |
|||
sum(45,34) |
|||
}} |
|||
<translate> |
|||
<!--T:149--> |
|||
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. You would need to: |
|||
</translate> |
|||
{{Code|code= |
|||
print sum(45,34) |
|||
}} |
|||
<translate> |
|||
<!--T:150--> |
|||
to have something printed. Read more about functions [http://www.diveintopython.net/getting_to_know_python/declaring_functions.html here]. |
|||
==Modules== <!--T:151--> |
==Modules== <!--T:151--> |
||
<!--T:152--> |
<!--T:152--> |
||
Now that |
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. |
||
<!--T:153--> |
<!--T:153--> |
||
Until now, we have written Python instructions line by line in the interpreter. This method is obviously not suitable for larger programs. Normally the code for Python programs is stored in files with the {{FileName|.py}} extension. Which are just plain text files and any text editor (Linux gedit, emacs, vi or even Windows Notepad) can be used to create and edit them. |
|||
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, 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. 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. |
|||
<!--T:154--> |
<!--T:154--> |
||
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 user {{FileName|Mod}} folder: |
|||
* On Linux it is usually {{FileName|/home/<username>/.local/share/FreeCAD/Mod/}} ({{VersionPlus|0.20}}) or {{FileName|/home/<username>/.FreeCAD/Mod/}} ({{VersionMinus|0.19}}). |
|||
* On Windows it is {{FileName|%APPDATA%\FreeCAD\Mod\}}, which is usually {{FileName|C:\Users\<username>\Appdata\Roaming\FreeCAD\Mod\}}. |
|||
* On macOS it is usually {{FileName|/Users/<username>/Library/Application Support/FreeCAD/Mod/}}. |
|||
Let's add a subfolder there called {{FileName|scripts}} and then write a file like this: |
|||
</translate> |
</translate> |
||
{{Code|code= |
{{Code|code= |
||
Line 444: | Line 499: | ||
return a + b |
return a + b |
||
print |
print("myTest.py succesfully loaded") |
||
}} |
}} |
||
<translate> |
<translate> |
||
<!--T:155--> |
<!--T:155--> |
||
Save the file as {{FileName|myTest.py}} in the {{FileName|scripts}} folder, and in the interpreter window write: |
|||
</translate> |
</translate> |
||
{{Code|code= |
{{Code|code= |
||
Line 455: | Line 511: | ||
}} |
}} |
||
<translate> |
<translate> |
||
<!--T:156--> |
<!--T:156--> |
||
without the .py extension. This will |
without the {{FileName|.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. |
||
<!--T:157--> |
<!--T:157--> |
||
When we write a {{incode|sum()}} function in the interpreter, we execute it like this: |
|||
</translate> |
</translate> |
||
{{Code|code= |
{{Code|code= |
||
sum(14,45) |
sum(14, 45) |
||
}} |
}} |
||
<translate> |
<translate> |
||
<!--T:158--> |
<!--T:158--> |
||
But when we import a module containing a {{incode|sum()}} function the syntax is a bit different: |
|||
</translate> |
</translate> |
||
{{Code|code= |
{{Code|code= |
||
myTest.sum(14,45) |
myTest.sum(14, 45) |
||
}} |
}} |
||
<translate> |
<translate> |
||
<!--T:159--> |
<!--T:159--> |
||
That is, the module is imported as a "container", and all its functions are inside. This is |
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 {{incode|something.somethingElse}}, with a dot in between, then this means {{incode|somethingElse}} is inside {{incode|something}}. |
||
<!--T:160--> |
<!--T:160--> |
||
We can also import our sum() function directly into the main interpreter space |
We can also import our sum() function directly into the main interpreter space: |
||
</translate> |
</translate> |
||
{{Code|code= |
{{Code|code= |
||
from myTest import * |
from myTest import * |
||
sum(12,54) |
sum(12, 54) |
||
}} |
}} |
||
<translate> |
<translate> |
||
<!--T:161--> |
<!--T:161--> |
||
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! |
|||
<!--T:162--> |
<!--T:162--> |
||
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 {{incode|help()}} function. Doing: |
|||
</translate> |
</translate> |
||
{{Code|code= |
{{Code|code= |
||
help() |
help("modules") |
||
modules |
|||
}} |
}} |
||
<translate> |
<translate> |
||
<!--T:163--> |
<!--T:163--> |
||
will give us a list of all available modules. We can import any of them and browse their content with the {{incode|dir()}} command: |
|||
</translate> |
</translate> |
||
{{Code|code= |
{{Code|code= |
||
Line 502: | Line 567: | ||
}} |
}} |
||
<translate> |
<translate> |
||
<!--T:164--> |
<!--T:164--> |
||
We'll see all the functions contained in the math module, as well as strange stuff named __doc__, __file__, __name__. |
We'll see all the functions contained in the {{incode|math}} module, as well as strange stuff named {{incode|__doc__}}, {{incode|__file__}}, {{incode|__name__}}. Every function in a well made module has a {{incode|__doc__}} that explains how to use it. For example, we see that there is a {{incode|sin()}} function inside the math module. Want to know how to use it? |
||
</translate> |
</translate> |
||
{{Code|code= |
{{Code|code= |
||
print |
print(math.sin.__doc__) |
||
}} |
}} |
||
<translate> |
<translate> |
||
<!--T:165--> |
<!--T:165--> |
||
It may not be evident, but on either side of {{incode|doc}} are two underscore characters. |
|||
<!--T:174--> |
<!--T:174--> |
||
And finally one last |
And finally one last tip: When working on new or existing code, it is better to not use the FreeCAD macro file extension, {{FileName|.FCMacro}}, but instead use the standard {{FileName|.py}} extension. This is because Python doesn't recognize the {{FileName|.FCMacro}} extension. If you use {{FileName|.py}} your code can be easily loaded with {{incode|import}}, as we have already seen, and also reloaded with {{incode|importlib.reload()}}: |
||
</translate> |
</translate> |
||
{{Code|code= |
{{Code|code= |
||
import |
import importlib |
||
importlib.reload(myTest) |
|||
myModule.myTestFunction() |
|||
}} |
}} |
||
<translate> |
<translate> |
||
<!--T:166--> |
|||
But what if we see that myTestFunction() doesn't work correctly? We go back to our editor and make changes. Then, instead of closing and reopening the python interpreter, we can simply update the module like this: |
|||
</translate> |
|||
{{Code|code= |
|||
reload(myModule) |
|||
}} |
|||
<translate> |
|||
<!--T:175--> |
|||
This file renaming is because Python doesn't know about the extension FCMacro. |
|||
<!--T:176--> |
<!--T:176--> |
||
There is however an alternative: |
|||
However, there are two alternates: Inside the one macro use Python's exec or execfile functions. |
|||
</translate> |
|||
{{Code|code= |
|||
f = open("myModule","r") |
|||
d = f.read() |
|||
exec d |
|||
}} |
|||
<translate> |
|||
<!--T:177--> |
|||
or |
|||
</translate> |
|||
{{Code|code= |
|||
execfile "myModule" |
|||
}} |
|||
<translate> |
|||
<!--T:178--> |
|||
To share code across macros, you can access the FreeCAD or FreeCADGui module (or any other Python module) and set any attribute to it. This should survive the execution of the macro. |
|||
</translate> |
</translate> |
||
{{Code|code= |
{{Code|code= |
||
exec(open("C:/PathToMyMacro/myMacro.FCMacro").read()) |
|||
import FreeCAD |
|||
if hasattr(FreeCAD,"macro2_executed"): |
|||
... |
|||
else: |
|||
FreeCAD.macro2_executed = True # you can assign any value because we only check for the existence of the attribute |
|||
... execute macro2 |
|||
}} |
}} |
||
<translate> |
<translate> |
||
</translate>{{Top}}<translate> |
|||
==Starting with FreeCAD== <!--T:167--> |
==Starting with FreeCAD== <!--T:167--> |
||
<!--T:168--> |
<!--T:168--> |
||
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: |
|||
</translate> |
</translate> |
||
{{Code|code= |
{{Code|code= |
||
Line 569: | Line 610: | ||
}} |
}} |
||
<translate> |
<translate> |
||
<!--T:169--> |
|||
and read on to [[FreeCAD Scripting Basics]]. |
|||
</translate>{{Top}}<translate> |
|||
<!--T:170--> |
|||
Of course, we saw here only a very small part of the Python world. There are many important concepts that we didn't mention. 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] |
|||
* the [http://docs.python.org/reference/ official Python reference] |
|||
* the [http://www.diveinto.org/python3/ Dive into Python] wikibook/ book. |
|||
Be sure to bookmark them! |
|||
==Notes== <!--T:197--> |
|||
<!--T: |
<!--T:198--> |
||
* 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. |
|||
{{docnav|[[Macros|Macros]]|[[Python scripting tutorial|Python scripting tutorial]]}} |
|||
* Much more information about Python can be found in the [https://docs.python.org/3/tutorial/index.html official Python tutorial] and the [https://docs.python.org/3/reference/ official Python reference]. |
|||
</translate>{{Top}}<translate> |
|||
<!--T:184--> |
|||
{{Userdocnavi}} |
|||
<!--T:172--> |
|||
[[Category:Poweruser Documentation]] |
|||
<!--T:171--> |
|||
[[Category:Python_Code]] |
|||
{{Docnav |
|||
|[[Scripts|Scripts]] |
|||
|[[Python_scripting_tutorial|Python scripting tutorial]] |
|||
}} |
|||
</translate> |
</translate> |
||
{{Powerdocnavi{{#translation:}}}} |
|||
{{clear}} |
|||
[[Category:Developer Documentation{{#translation:}}]] |
|||
[[Category:Python Code{{#translation:}}]] |
Latest revision as of 17:12, 16 February 2023
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 to manipulate parts of FreeCAD. This is very powerful, it means you can build your very 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 hopefully 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.
The interpreter
Usually when writing computer programs, you open a text editor or your special programming environment (which is basically a text editor with some 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. 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 immediately tell you so. In this case Python 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
. 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 print(hello)
and we want specific information about the 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 variables come 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, such as not using spaces or punctuation and not using Python keywords. 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)
It is advisable 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 just 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 specified 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)
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 perform any arithmetic. 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))
Because var2
is a float Python automatically decides that the result must also be a float. But there are cases where Python does not knows what type to use. For example:
varA = "hello 123"
varB = 456
print(varA + varB)
This results in 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 variables 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 integer and float if we want:
varA = "123"
print(int(varA))
print(float(varA))
You must have noticed that we have 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 useful data type is a list. A list is a collection of other data. To define a list we use [ ]
:
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. You can do many things with a list. For example, count its items:
len(myOtherList)
Or retrieve 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 items and removing or adding items.
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 need to be executed inside the for in
operation? For that, Python relies on indentation. The next lines must begin with a blank space, or several blank spaces, or a tab, or several tabs. And as long as the indentation stays the same the lines 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 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 other commands use indented blocks of code as well.
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 press 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 and we already know several of them. But you can create your own commands. 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
. Let's try another example:
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.
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. This method is obviously not suitable for larger programs. Normally the code for Python programs is stored in files with the .py extension. Which are just plain text files and any text editor (Linux gedit, emacs, vi or even Windows Notepad) can be used to create and edit them.
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 user Mod folder:
- On Linux it is usually /home/<username>/.local/share/FreeCAD/Mod/ (version 0.20 and above) or /home/<username>/.FreeCAD/Mod/ (version 0.19 and below).
- On Windows it is %APPDATA%\FreeCAD\Mod\, which is usually C:\Users\<username>\Appdata\Roaming\FreeCAD\Mod\.
- On macOS it is usually /Users/<username>/Library/Application Support/FreeCAD/Mod/.
Let's add a subfolder there called scripts and then write a file like this:
def sum(a,b):
return a + b
print("myTest.py succesfully loaded")
Save the file as myTest.py in the scripts folder, 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, then 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)
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!
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 is better to not use the FreeCAD macro file extension, .FCMacro, but instead use the standard .py extension. 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 also reloaded with importlib.reload()
:
import importlib
importlib.reload(myTest)
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()
Notes
- 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.
- Much more information about Python can be found in the official Python tutorial and the official Python reference.
- FreeCAD scripting: Python, Introduction to Python, Python scripting tutorial, FreeCAD Scripting Basics
- Modules: Builtin modules, Units, Quantity
- Workbenches: Workbench creation, Gui Commands, Commands, Installing more workbenches
- Meshes and Parts: Mesh Scripting, Topological data scripting, Mesh to Part, PythonOCC
- Parametric objects: Scripted objects, Viewproviders (Custom icon in tree view)
- Scenegraph: Coin (Inventor) scenegraph, Pivy
- Graphical interface: Interface creation, Interface creation completely in Python (1, 2, 3, 4, 5), PySide, PySide examples beginner, intermediate, advanced
- Macros: Macros, How to install macros
- Embedding: Embedding FreeCAD, Embedding FreeCADGui
- Other: Expressions, Code snippets, Line drawing function, FreeCAD vector math library (deprecated)
- Hubs: User hub, Power users hub, Developer hub