Skip to content

Python Course – 5. Functions

Learn Python functions: arguments and parameters, scope, documenting your code and lambda functions, with theory, videos and a hands-on ATM exercise.

Group lines of code so you can reuse them several times, or document them as specific pieces of functionality whose name sums up what the code does without having to read it all.

Theory

Skip to PDF content

5.1- Function

Write non-sequential code, that is, write pieces of code that will run at a later time using functional programming.

Note

To learn more, check out the following posts:

5.2- Function – Arguments and Parameters

A function can behave like a black box, with some inputs and some outputs; a bit like an engine, which needs a certain amount of gasoline going in and gives movement coming out. Arguments and parameters are the data input of the function.

Note

To learn more, check out the following posts:

5.3- Function – Scope

The scope of a function is a bit peculiar, because the code doesn’t run sequentially: where it’s written it won’t run right away, but later. This means the values of variables at one point won’t be the same as when the function is called.

5.4- Documenting Functions

A function is already a way of documenting code in itself, but you can go further; in other words, we’ll be able to document our code professionally.

5.5- Lambda Function

Functions have a name and can be run multiple times. However, especially in event-driven programming, we’ll want the function to run only once, and we won’t even care about giving it a name; we achieve this with Lambda.

Exercises

Exercise 5.1-cajero_automatico.py

Let’s create a logging system for an ATM.

We’ll create a method to print each line, with “fecha” (date) and “concepto” (description) as required parameters, and “cantidad” (amount) as optional: if it isn’t passed, it will be 0, and “movimiento” (transaction type) will be “Domiciliación” if nothing is passed. Also, if the “cantidad” is negative, you have to mark that line somehow (for example, by adding the word “Déficit” at the end).

The data input has to be done by calling the method directly and passing it different values, with the different combinations for the arguments that are optional.

Console capture of three dated bank transactions; the -50€ concert payment is flagged as Deficit

“Python Course – 5. Functions” by Ramón Invarato at jarroba.com, licensed under Creative Commons Attribution-NonCommercial-ShareAlike 3.0. Registered at Safe Creative.

Ramón Invarato

I design and build data platforms and intelligent systems, and I enjoy sharing that experience here.

You may also like

Comments

Leave a comment


This site uses Akismet to reduce spam. Learn how your comment data is processed.