Before analyzing the functions in Python let’s talk about another important aspect of the language, namely the List Comprehensions, the Dict Comprehensions and the Set Comprehensions.
LIST COMPREHENSION
It is a mechanism that starting from a list or any iterable object produces another in a single instruction by performing sophisticated processing starting from the source list. The central part of this statement should be familiar, it is a for in loop that iterates through the collection placed in iterable and each extracted element places it in the variable item. To the right appears a conditional structure if condition. This means that at each iteration this condition is evaluated and only if True the current element is put in item, otherwise it is discarded. The condition is optional. Expression processes item, it is a more or less complex rule that is applied to item so that it produces a value which then enters the destination list.
EXAMPLE LIST COMPREHENSION
Here is an example to clarify the above concepts.
DICT COMPREHENSION
It is a mechanism used to produce a dictionary from any iterable object. The keys and values of the dictionary are obtained by processing the iterable object of origin.
EXAMPLE DICT COMPREHENSION
The instruction pow (n, 1/2) calculates the square root of n.
SET COMPREHENSION
Constructs a set from any iterable object (List, String, Dictionary, etc.). The expression must produce a new element of the whole as long as it is not duplicated. If an element is duplicated, Python automatically discards it.
EXAMPLE SET COMPREHENSION
Here is a simple example.
FUNCTIONS
A function is made up of a set of instructions, we assign a name to it and call it in other parts of the program. Even a function is an object, remember that everything in Python is an object.
The first step in using functions is to define them. To define a function, it is necessary to indicate the parameters if required, write the instructions in the body and assign it a name. Once defined by following the above steps, it can be recalled. The keyword in the header is def which means defined function. Function name is the identifier, the name we are assigning to the function. Parameters are an optional list of names enclosed in round brackets. They will be assigned at the time we call the function and pass the arguments. If the function has no parameters, the pair of round brackets must in any case be indicated.
PARAMETERS
Parameters, sometimes even by default, name the values that are passed when calling functions in Python.
POSITIONAL PARAMETERS
Whenever we call a function with positional parameters we must necessarily supply the values.
EXAMPLE OF POSITIONAL PARAMETERS
KEYWORD PARAMETERS
In this case, Python manages to recompose the order. The advantage of doing this is that we can specify the parameters we supply also in a different order, Python manages to define the right order because in the call we are defining the names of the parameters. If you call a function while supplying positional parameters and keyword parameters at the same time, the positional parameters must always precede the keyword parameters.
EXAMPLE OF KEYWORD PARAMETERS
OPTIONAL PARAMETERS
Mandatory parameters, if any, can be followed by optional parameters. Having directly assigned a default value at the time of the declaration, the callers of the function will replace the default ones if they specify the optional parameters. Conversely, if they are not specified, the default parameters already provided are used.
EXAMPLE OF OPTIONAL PARAMETERS
PARAMETERS *ARGS
They are defined with the asterisk symbol followed by a name, usually args. An arbitrary number of positional parameters can be specified with this definition. In args a tuple is created and correctly printed.
EXAMPLE OF PARAMETERS *ARGS
Here is an example.
Python in this case creates a dictionary with the keys supplied by the parameter names and as values those supplied.
THE STATEMENT RETURN
All functions in Python always return a value either implicitly but also explicitly. The return statement can only be indicated in the suite of instructions that precisely contain the code body of the function itself. In this example, return is followed by an expression that calculates the sum of a and b. If we do not indicate a value in the return statement Python returns to the caller however a value which in this case is None which means lack of a value. The caller of the function can test through a conditional test whether the function returns None.
Even if there is no return statement, if the function body terminates, Python also returns None.
CALL A FUNCTION
Once a function has been defined, we can call it from one or more parts of the code.
function_name (arguments)
The passing of the parameters is done by reference. A distinction must be made: whether the object passed as a value to the parameter is of a mutable or immutable type.
IMMUTABLE OBJECTS
An int passed to the function is an immutable object, when we return from the function by printing the value of y we realize that its value has remained unchanged, this is because y is an immutable object and is not modified by the function.
MUTABLE OBJECTS
Being a dictionary by its nature mutable, this time the passage by reference has a different behavior. The past value d is also added to the dictionary to the ‘func‘ key with value 10.
#DEFINIRE UNA FUNZIONE CHE SELEZIONA I DISTINTI ELEMENTI #DI DUE LISTE. LA SECONDA HA DEI PARAMETRI DI DEFAULT [6,7,8,9,10]. #COLCOLARE SOMMA E RADICE QUADRATA DEGLI ELEMENTI SELEZIONATI. import math def funcliste(l1,l2=[6,7,8,9,10]): lresult=[] somma=0 for x in l2: if not x in l1: lresult.append(x) somma+=x for x in l1: if not x in l2: lresult.append(x) somma+=x print(f'Risultato: {lresult}') print(f'Somma: {somma}') print(f'Radice Quadrata: {math.sqrt(somma)}') return lresult funcliste([1,2,3,4,5],[2,4,8])
DEEPENING
In Python, functions are reusable blocks of code that perform a specific operation. Functions can accept input in the form of parameters and return output. Function parameters in Python can be of various types, each with specific characteristics. Here is a detailed overview:
1. Functions in Python
– Definition: Functions in Python are defined using the keyword def, followed by the function name and a pair of brackets (), which may contain parameters. The function code block is indented.
– Basic syntax:
def nome_funzione(parametri):
# Blocco di codice
return valore # (opzionale)
• Esempio:
def saluta(nome):
return f”Ciao, {nome}!”
messaggio = saluta(“Alice“)
print(messaggio) # Output: Ciao, Alice!
2. Types of Parameters.
Python supports several types of parameters in functions, each with a particular behavior:
2.1 Positional Parameters (Positional Arguments).
– Description: These are the most common parameters. They are passed to the function in the order in which they are defined. The order is crucial: the first argument passed to the function is assigned to the first parameter, the second to the second parameter, and so on.
– Example:
def moltiplica(a, b):
return a * b
risultato = moltiplica(2, 3) # 2 viene assegnato ad a, 3 a b
print(risultato) # Output: 6
2.2 Nominal Parameters (Keyword Arguments)
– Description: They allow passing values to parameters by specifying their names, regardless of their location. They are useful to improve code readability and when you want to specify only some of the parameters.
– Example:
def saluta(nome, messaggio=”Ciao“):
return f”{messaggio}, {nome}!”
print(saluta(nome=”Alice“, messaggio=”Buongiorno“)) # Output: Buongiorno, Alice!
print(saluta(nome=”Bob“)) # Output: Ciao, Bob!
2.3 Default Parameters (Default Arguments)
– Description: These are parameters that are assigned a default value. If the corresponding argument is not passed to the function, the parameter uses the default value.
– Example:
def saluta(nome, messaggio=”Ciao“):
return f”{messaggio}, {nome}!”
print(saluta(“Alice“)) # Output: Ciao, Alice! (messaggio usa il valore predefinito)
print(saluta(“Bob“, “Buongiorno“)) # Output: Buongiorno, Bob!
2.4 Arbitrary Positional Arguments (Arbitrary Positional Arguments)
– Description: By using an asterisk * before the parameter name, a variable number of positional arguments can be passed to the function. These arguments are collected in a tuple within the function.
– Example:
def somma(*numeri):
return sum(numeri)
print(somma(1, 2, 3, 4)) # Output: 10
print(somma(5, 10)) # Output: 15
2.5 Nominal Arbitrary Parameters (Arbitrary Keyword Arguments)
– Description: By using two asterisks ** before the parameter name, a variable number of nominal arguments (keyword arguments) can be passed to the function. These arguments are collected in a dictionary.
– Example:
def descrizione(**info):
return info
print(descrizione(nome=”Alice“, età=25, lavoro=”Ingegnere“))
# Output: {‘nome’: ‘Alice’, ‘età’: 25, ‘lavoro’: ‘Ingegnere’}
3. Use of Functions
Functions are used to avoid code duplication, modularize programs, and improve readability. It is important to choose the appropriate parameters based on the intended use of the function and the flexibility required.
4. Anonymous Functions (Lambda Functions).
–Description: Lambda functions are anonymous, lightweight functions defined with the lambda keyword. They are mainly used for simple operations that require an ad hoc function.
–Example:
sum = lambda x, y: x + y
print(sum(3, 5)) # Output: 8
This overview covers the various types of parameters in Python functions, helping to understand when and how to use them effectively.
Leave A Comment