PythonTrading – 2 – Learning basic functions

Now let’s have a look at Python functions.


A function is an indented block of code that is defined (using def) and a function can be executed by calling its name.


Behind the function name there are round braces that can pass parameters to the function.


For example in the example below, we are using the default parameter for myprint_function2.


If we don’t provide any other value, this default parameter is used by the function. If we override it with another value, the new value is used.



With triple quotes I can create a docstring text that comes up whenever somebody calls my function – the cursor needs to be in the round braces.

Once a function is defined, we can use the return value to return an outcome.


For example we could create a function to multiply a parameter with its value and return the result.


That result can also be stored in a variable.

If a function is only needed once, we can use so called lambda functions. Lambda functions are basically an unnamed and short version where we return the calculated value behind a colon.

There is also a filter function available, that can be used to filter the items in a list. In our case we use it to find even numbers.

Working with text strings is possible in many ways. For example we can convert them to upper or lower cases and split them wherever we find special characters that we can define in the split function.

It is even possible to get the splitted parts by appending an index, in our example for the first part (index 0) and for the second part (index 1).

Lists can be changed, append would add an item at the end, pop would remove an item at the end, pop with an index number would remove the item at the specified index.


We can use the expression “in” to find out, if an item is part of a list.