Introduction
As we saw, good practices for coding and scientific computing include avoiding duplication of code blocks. Functions encapsulate instructions which can be run by invoking only one command, the function's name. It therefore facilitate automation and on the other hand makes it easier to maintain, update or correct our code.
Define a function
Parameters of a function
Upon definition, we can specify the parameters that the function admits. This will allow the user to give his or her own values (which are then called arguments of the function) to these parameters and modify accordingly the function's behaviour
Documenting my function
Another good practice is to document the code you write. This is kind to other users that may be reading your code at some point, but also very kind to your future you, who may need to dive into the code some time after you finished your project. You will be very grateful then to have properly documented your functions, indicating their purpose and how they globally work.
Further reading:
In case you are interested, a rather complete tutorial on documenting Python code: https://realpython.com/documenting-python-code/
The docstring specification for Python is described in PEP257
Modules and libraries
Modules are .py files containing definitions and statements. They allow to organize the code and share it with others. A library refers to a collection of modules. Python has an extremely rich ecosystem of built-in and contributed modules that perform a huge range of tasks.
Methods and attributes of objects
Modules introduce rich classes, which are templates of objects relevant to the problem at hand.
To manipulate those objects, for example a file, or a dataset, the module defines methods and attributes associated to an object's instance.
Challenges
Challenge 1
In a file called challenges-functions.py, write a function that takes an integer n as argument and returns True if n is a prime number and False otherwise.
Challenge 2
Add to the file challenges-functions.py a block of code that requests an integer n from the user and prints out all the prime numbers less than n.