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 content5.1- Function
Write non-sequential code, that is, write pieces of code that will run at a later time using functional programming.
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.
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.

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

You may also like
Advanced Dockerfile: Multi-Stage Builds, Registries, and Tricks
Free Docker course. Expert Docker tricks: multi-stage builds, optimizing images, faster build times, and distributing images through Docker registries.
Dockerfile: Directives and Dockerizing Projects
Free Docker course. A Dockerfile is a file of directives for building and deploying custom applications with Docker. Learn how to Dockerize your projects.



Leave a comment