Functions in Python
A function is a reusable block of instructions that performs a specific
task and is grouped under a name. Up until now, we've been using
Python's predefined functions without realizing it. For example, print()
and input() are functions that receive values and perform tasks with
them.
A function is like a black box: from the outside, we can only see its inputs
and outputs. The process is hidden inside, but it works perfectly!
MODULES
Python Modules
Many Python functions are stored in files called modules. This is the
case for functions related to random numbers, which are grouped in the
random module.
To use functions from a module, we need to import it at the beginning of
our program using the import statement.
Syntax:
import random
Once imported, we can access all the random functions to generate
unpredictable values, select random elements, and more.
RANDOM FUNCTIONS
Working with Random Numbers
randint Function choice Function
Generates a random integer in the range [min, max] Selects a random element from a list
Syntax: Syntax:
variable = [Link](min, max) variable = [Link](list_name)
These functions are essential for creating games, simulations, and programs that require unpredictable behavior. Remember to import the random module first!
Creating Your Own
Functions
In addition to all of Python's predefined functions, we can create our own
custom functions. This helps us avoid duplicating code and makes it
easier to solve problems by breaking them into smaller subproblems,
with a function for each one.
Basic Syntax:
def function_name(input):
statement
statement
etc.
Anatomy of a Function
01 02
Function Name Input Parameters
A descriptive identifier that tells us Data the function receives to work
what the function does with (optional)
03
Function Body
The indented block of instructions that performs the task
Functions are created at the beginning of the program
A function ends when another function starts or when non-
indented code is found
Calling a Function
When we define a function, it gets "registered" so we can use it later.
However, if we don't call it by its name, its code block will never execute. The
function definition is just a blueprint4we need to invoke it to make it work.
Example:
Function Call
This is where the magic happens!
When we write the function name
followed by parentheses (with or
without arguments), Python
executes all the instructions inside
the function body.
Local Scope: What Happens in the Function Stays in
the Function
Local Variables Parameter Modifications Return Statement
Variables created inside a function are If we modify input parameters The only way a function communicates
local and don't exist outside of it. They are (arguments), this only affects the local results back to the main program is
born when the function is called and die copy inside the function. The original through the return statement. This is the
when it finishes. values outside remain unchanged. function's output channel.
Functions That Return Results
A function that includes the return statement not only performs its designated task but also sends back
a result. This returned value can be stored in a variable, displayed with print(), or used in expressions for
calculations or comparisons.
Example: Understanding the truncar_dec Function
Function Call
1
truncar_dec(3.1415, 2)
Calculate Power
2
potencia10 = 100
Truncate
3 num = int(3.1415*100)/100
num = 314/100
Result
4
num = 3.14
What does this function do? It truncates a decimal number to a specified number of decimal places by
multiplying by a power of 10, converting to integer, then dividing back.
Using the Function's Result
In this example, our truncar_dec function returns a number "trimmed" to the specified number of decimal places. Both the number and decimal count are sent as input parameters. We make two
function calls: in the first, we store the result in a variable, while in the second, we display it directly.
Code Example: Output:
Notice how the same function can be used in different ways: storing its result for later use or immediately displaying it. This flexibility makes functions incredibly powerful!
Function Termination with Return
When Python encounters the return statement, it immediately exits the function and continues execution at the line that called it. This is how functions
send their results back to the main program.
1 2 3
Return Execution Code After Return Continuation Point
The function stops immediately when return Any instructions after return will be ignored Execution resumes at the line following the
is reached and never executed function call
Example:
Understanding return is crucial for writing effective functions. It's both the function's end point and its way of delivering results back to the calling code!