Advanced Scientific Programming in 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 wish. Because you can go slowly, step-by-step, it is extremely easy to learn and to find errors in your code.
  • It can be embedded in other programs to be used as 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 extremely powerful, instead of just clicking a button labeled "create sphere", that some programmer has coded; you have the freedom to easily build your own tool, creating exactly the geometry you want, in a manner or shape that the programmer may not foresee.
  • 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.

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.

Usually, when writing computer programs, you simply open a text editor or your special programming environment, (which is usually a text editor with several additional tools) write your program, then compile and execute. Usually, 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.

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.

Researchers invest increasingly energy composing, keeping up, and investigating programming. While methods for doing this productively have advanced, just couple of researchers have been prepared to utilize them. Accordingly, rather than doing their examination, they invest immeasurably an excessive amount of energy composing insufficient code and reevaluating the wheel. In this course we will exhibit a choice of cutting edge programming strategies and best practices which are standard in the business, however particularly custom fitted to the necessities of a programming researcher. Addresses are formulated to be intuitive and to give the understudies enough time to obtain coordinate hands-on involvement with the materials. Understudies will work in sets all through the school and will collaborate to rehearse the recently learned abilities in a genuine programming venture — an engaging PC diversion.

We utilize the Python programming dialect for the whole course. Python functions as a basic programming dialect for novices, however more imperatively, it likewise works extraordinary in logical recreations and information investigation. We indicate how clean dialect configuration, simplicity of extensibility, and the colossal abundance of open source libraries for logical registering and information representation are driving Python to wind up a standard apparatus for the programming researcher.

This school is focused at Master or PhD understudies and Post-docs from all regions of science. Fitness in Python or in another dialect, for example, Java, C/C++, MATLAB, or Mathematica is totally required. Fundamental information of Python and of an adaptation control framework, for example, git, subversion, fluctuating, or bazaar is expected. Members with no related knowledge with Python and additionally git should work through the proposed early on material before the course.


  • Version control with git and how to contribute to open source projects with GitHub
  • Best practices in data visualization
  • Organizing, documenting, and distributing scientific code
  • Testing scientific code
  • Profiling scientific code
  • Advanced NumPy
  • Advanced scientific Python: decorators, context managers, generators, and elements of object oriented programming
  • Writing parallel applications in Python
  • Speeding up scientific code with Cython and numba
  • Memory-bound computations and the memory hierarchy
  • Programming in teams


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

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

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

Extremely simple: the def() command defines a new function. You give it a name, and inside the parenthesis you define arguments that we'll use in our function. Arguments are data that will be passed to the function. For example, look at the len() command. If you just write len() alone, Python will tell you it needs an argument. That is, you want len() of something, right? Then, for example, you'll write len(myList) and you'll get the length of myList. Well, myList is an argument that you pass to the len() function. The len() function is defined in such a way that it knows what to do with what is passed to it. Same as we did here.

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


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) 

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:


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:

print sum(45,34) 


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

Until now, we wrote Python instructions line by line in the interpreter, right? What if we could write several lines together, and have them executed all at once? It would certainly be handier for doing more complex things. And we could save our work too. Well, that too, is extremely easy. Simply open a text editor (such as the windows notepad, 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.

To make Python execute that program, there are hundreds of ways. In windows, simply right-click your file, open it with Python, and execute it. But you can also execute it from the Python interpreter itself. For this, the interpreter must know where your .py program is. In FreeCAD, the easiest way is to place your program in a place that FreeCAD's Python interpreter knows by default, such as FreeCAD's bin folder, or any of the Mod folders. (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 " succesfully loaded" 

and we save it as 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 simply execute the contents of the file, line by line, just as if we had written it in the interpreter. The sum function will be created, and the message will be printed. There is one big difference: the import command is made not only to execute programs written in files, like ours, but also to load the functions inside, so they become available in the interpreter. Files containing functions, like ours, are called modules.

Normally when we write a sum() function in the interpreter, we execute it simply like that:


Like we did earlier. When we import a module containing our sum() function, the syntax is a bit different. We do:


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

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

from myTest import *

Basically all modules behave like that. You import a module, 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 extremely useful thing. How do we know what modules we have, what functions are inside and how to use them (that is, what kind of arguments they need)? We saw already that Python has a help() function. Doing:


Will give us a list of all available modules. We can now type q to get out of the interactive help, and import any of them. We can even browse their content with the dir() command

import math

We'll see all the functions contained in the math module, as well as strange stuff named __doc__, __file__, __name__. The __doc__ is extremely useful, it is a documentation text. Every function of (well-made) modules has a __doc__ that explains how to use it. For example, we see that there is a sin function in side the math module. Want to know how to use it?

print math.sin.__doc__ 

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

And finally one last little goodie: When we work on a new or existing module, it's best to replace the file extension with py such as: myModule.FCMacro => We often want to test it so we will load it as above.

import myModule

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:


This file renaming is because Python doesn't know about the extension FCMacro.

However, there are two alternates: Inside the one macro use Python's exec or execfile functions.

f = open("myModule","r")
d =
exec d 


execfile "myModule" 

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.

import FreeCAD
if hasattr(FreeCAD,"macro2_executed"):
    FreeCAD.macro2_executed = True # you can assign any value because we only check for the existence of the attribute
    ... execute macro2 
Author's Score
Up Votes
Down Votes
Voted on
1 articles
For everything fun and local, you can find it on, #1 Social Classifieds
python, python, pythonprogramming, pythonprogramming, java, java, Programming in Python. Python functions, Programming in Python. Python functions, Python course, Python course,

Recent Articles

Perfumes for men and women are as different as men and women! It is better to know some basic rules before...
Hair is certainly The best aspect of your general character as it permits you to offer your character a flexible...
With the moving age and technology, more and more numbers of Indians are moving abroad to live and work. Increased...
The troubleshooting measures are essential for the users of Bigpond account who have trouble while accessing the...
If you start looking at your house you will notice you have a lot of things that work on electricity. Outlets,...

Copyrights © 2016 Voticle. All Rights Reserved.