We have already worked with functions in Python. In fact, our first program already used a function. print() is actually a function. min(), max(), input(), sorted(), and all of the other commands with parentheses are all functions.
Functions execute several commands and in some cases return a result. min() computes the minimum of several values and returns that value. print(), on the other hand, prints a value in the output.
Functions are especially useful when eliminating repetitive code. We can define our custom functions as well. Imagine you would like to print a certain object 3 times and do something else in between:
To define a custom function one needs to use the keyword def followed by the name of the function (print_triangle in our case) which is followed by () and a : to mark the start of the function block. The list of commands the function should execute is placed in an indented block inside the function body.
Both of these programs perform exactly the same operations, but the second one defines the repetitive part in a function and makes sure the code is not copy-pasted.
On the other hand, the first one has a lot of copy-pasting, and in case we decide to change the * to % when printing a triangle, it would be required to make a lot of changes and go through every line and make the change. This can get really messy for larger codebases and is very error-prone.
Define a function that prints a rectangle and call it 3 times. The borders of the rectangle should be of # symbol, and the inner part should be empty.