
















































Studia grazie alle numerose risorse presenti su Docsity
Guadagna punti aiutando altri studenti oppure acquistali con un piano Premium
Prepara i tuoi esami
Studia grazie alle numerose risorse presenti su Docsity
Prepara i tuoi esami con i documenti condivisi da studenti come te su Docsity
Trova i documenti specifici per gli esami della tua università
Preparati con lezioni e prove svolte basate sui programmi universitari!
Rispondi a reali domande d’esame e scopri la tua preparazione
Riassumi i tuoi documenti, fagli domande, convertili in quiz e mappe concettuali
Studia con prove svolte, tesine e consigli utili
Togliti ogni dubbio leggendo le risposte alle domande fatte da altri studenti come te
Esplora i documenti più scaricati per gli argomenti di studio più popolari
Ottieni i punti per scaricare
Guadagna punti aiutando altri studenti oppure acquistali con un piano Premium
Documento scritto da me in inglese sul linguaggio Python. La dispensa spiega argomenti avanzati del linguaggio in maniera chiara e semplice per poterne utilizzare tutte le capacità. Si parte dalla gestione dei file fino alla programmazione di interfacce grafiche, Pandas e Numpy. Ogni argomento è corredato di esercizi svolti per comprendere meglio gli argomenti. Questo documento è adatto per chiunque indipendentemente dall'università/corso voglia approfondire la programmazione Python in maniera strutturata e completa.
Tipologia: Dispense
1 / 56
Questa pagina non è visibile nell’anteprima
Non perderti parti importanti!

















































Functions can take a variable number of parameters using *args and **kwargs. They
are particularly useful when you want to create flexible functions that can handle
any number of input arguments.
which are stored in a tuple:
>>> def print_args(*args):
>>> for arg in args:
>>> print(arg)
>>> print_args(1, 2, 3)
output: 1 2 3
which are stored in a dictionary:
>>> def print_kwargs(**kwargs):
>>> for key, value in kwargs.items():
>>> print(f"{key}: {value}")
>>> print_kwargs(name="Alice", age=30, city="New York")
output: name: Alice age: 30 city: New York
This can be particularly useful in situations where the number of inputs is not
predetermined. A lot of pre-built Python functions use *args or **kwargs. For
example the function .format() used with the strings:
>>> template = "Hello, {name}! You have {count} new messages."
>>> formatted = template.format(name="Alice", count=5)
>>> print(formatted)
output: Hello, Alice! You have 5 new messages.
This because the number of placeholders inside the string can vary.
Furthermore, the behavior of a function can be controlled using the Python
decorators. They act as wrappers around functions, enabling you to add
functionality before or after the function is executed, or even alter its input and
output. The general syntax for a decorator is:
def decorator_name(func):
def wrapper():
result = func() # Call the original function
return wrapper
@decorator_name
def function_name(parameters):
The general syntax involves defining a decorator function, which takes another
function as an argument. This decorator function then defines a nested wrapper
function that adds additional behavior before and/or after calling the original
function. The decorator function returns this wrapper function, effectively
replacing the original function with the enhanced version. The @decorator_name
syntax is used to apply the decorator to a function, making the original function
execute with the extra functionality provided by the wrapper.
This approach allows for clean and reusable code modifications without altering the
original function's code.
>>> def my_decorator(func):
>>> def wrapper():
>>> print("Before the function.")
>>> func()
>>> print("After the function.")
>>> return wrapper
>>> @my_decorator
>>> def my_function():
>>> print("Inside the function.")
>>> # Calling the decorated function
>>> my_function()
output: Before the function.
Inside the function.
After the function.
add_expenses(("Food", 20 ), ("Entertainment", 50 ), ("Utilities", 75 ), ("Food", 15 ))
total = calculate_total(*expenses)
print(f"Total Expenses: ${total}")
summary = generate_summary(*expenses)
print("Expense Summary:")
for expense_type, amount in summary.items():
print(f"{expense_type}: ${amount}")
def generate_report(**sections):
report = {}
for title, content in sections.items():
if isinstance(content, str):
report[title] = content
else:
print(f"Invalid content for section '{title}': {content}")
return report
def print_summary(**sections):
for title, content in sections.items():
first_line = content.split('\n')[ 0 ] # Extract the first line of content
print(f"Title: {title}")
print(f"Content Preview: {first_line}")
print()
def filter_sections(keyword, **sections):
filtered = {title: content for title, content in sections.items() if
keyword.lower() in content.lower()}
return filtered
report = generate_report(
Introduction="This is the introduction section of the report. It covers the
background.",
Results="The results section includes the main findings of the research.",
Conclusion="The conclusion summarizes the main points and suggests future
work.",
Appendix="Additional materials and data can be found in the appendix section."
print("Report Summary:")
print_summary(**report)
filtered_report = filter_sections("summary", **report)
print("Filtered Sections:")
print_summary(**filtered_report)
import time
def timing_decorator(func):
def wrapper(*args, **kwargs):
start_time = time.time() # Record the start time
result = func(*args, **kwargs) # Call the original function
end_time = time.time() # Record the end time
execution_time = end_time - start_time # Calculate execution time
print(f"Execution time: {execution_time:.4f} seconds")
return result
return wrapper
@timing_decorator
def compute_sum(n):
total = 0
for i in range(n):
total += i
return total
print("Result:", compute_sum( 1000000 ))
opened in write mode.
>>> file = open( "PATH_TO_FILE" , mode='w')
>>> file.write("Hello")
pass the list as content to write. Each element in the list will be written
inside a separate line.
>>> lines = ["First line\n", "Second line\n", "Third line\n"]
>>> file = open("path/to/my/file", mode='w')
>>> file.writelines(lines)
The write mode have to be used carefully because, based on where is placed the file
cursor, the writing process will insert the text after the file cursor.
Ultimately, we can be sure of writing new content at the end of the file by
specifying the append mode:
>>> file = open( "PATH_TO_FILE" , mode='a')
>>> file.write("Hello")
The new content will be placed at the end of the file.
We can move the file cursor using:
>>> seek(0) # rewind the file position to zero
Finally, the file have to be closed:
>>> file = open( "PATH_TO_FILE" , mode='w')
>>> file.close()
In order to manage easily the files, we can use the with statement, that allow to
refere to a specific expression using a defined variable:
with EXPRESSION as VARIABLE :
The with statement allows to manage resources in an easy way by accessing it using
a single variable name:
>>> with open( "PATH_TO_FILE" , "r") as file:
>>> content = file.read()
This makes easy to manage different files without any confusion.
CSV files:
Python is very suitable for CSV (Comma Separated Values) files. It is a simple file
format used to store tabular data, such as a spreadsheet or database. A CSV file
stores tabular data (numbers and text) in plain text. Each line of the file is a
data record. Each record consists of one or more fields, separated by commas.
Header (column names) of the file
The file is seen as:
The 'csv' module is used to handle this type of files.
iterable list where the element will be a string.
>>> import csv
>>> with open( "PATH_TO_FILE" , mode='r') as file:
>>> reader = csv.reader(file)
>>> for row in reader:
>>> print(row) # each row is a list of strings
output: ['NAME', 'AGE', 'JOB']
['John', '28', 'Teacher']
['Bob', '32', 'Mechanic']
['Giulia', '19', 'Waiter']
CSV files can be red with different delimiters (for example, the CSV files in Excel
have a colon as delimiter instead of commas). The csv.reader function has a commas
default delimiter. We can change it when we call the function in any character we
want to consider a delimiter for our CSV file:
>>> import csv
>>> with open( "PATH_TO_FILE" , mode='r') as file:
>>> reader = csv.reader(file, delimiter=':')
In any case, the header of the CSV can be extracted as the first row of content of
the file.
JSON files:
JSON (JavaScript Object Notation) is a widely used format for exchanging data
between a server and a client, or for storing structured data in a readable text
format. They follow a specific notation very similar to the Python dictionaries:
Python's json module provides built-in support for parsing JSON data and converting
Python objects to JSON format.
follows the file structure.
>>> import json
>>> with open( "PATH_TO_FILE" ) as file:
>>> data = json.load(file)
>>> print(data)
output: {'employee': {'name': 'John', 'age': '28', 'job': 'Teacher'}}
control the indentation using whitespaces.
>>> import json
>>> person = {'name': 'Jane', 'age': 25, 'city': 'Los Angeles'}
>>> with open( "PATH_TO_FILE" , "w") as file:
>>> json.dump(person, file, indent=4)
This makes possible to manage this complex file type using dictionaries.
server_log.txt
INFO: Server started successfully.
WARNING: Disk space running low.
ERROR: Failed to connect to database.
INFO: User login successful.
ERROR: Unable to open file.
WARNING: High memory usage detected.
INFO: Server shutdown initiated.
def analyze_log_file(input_file, output_file):
error_count = 0
warning_count = 0
with open(input_file, 'r') as file:
for line in file:
if 'ERROR' in line:
error_count += 1
elif 'WARNING' in line:
warning_count += 1
with open(output_file, 'w') as file:
file.write(f"Error Count: {error_count}\n")
file.write(f"Warning Count: {warning_count}\n")
input_filename = 'server_log.txt'
output_filename = 'log_summary.txt'
analyze_log_file(input_filename, output_filename)
sales_data.csv
Product,Amount
Apple,
Banana,
Apple,
Orange,
Banana,
Apple,
import json
def process_json_data(input_file, output_file):
with open(input_file, 'r') as file:
data = json.load(file) # Load JSON data into a Python list
total_salary = 0
employee_count = len(data)
for employee in data:
total_salary += employee['salary']
average_salary = total_salary / employee_count if employee_count > 0 else 0
summary = {
'average_salary': average_salary
with open(output_file, 'w') as file:
json.dump(summary, file, indent= 4 ) # Write JSON data with indentation
input_filename = 'employees.json'
output_filename = 'salary_summary.json'
process_json_data(input_filename, output_filename)
Exceptions
🔀
Exceptions in Python are events that disrupt the normal flow of a program's
execution. They are used to handle errors and unusual situations gracefully,
allowing the program to continue running or to fail with a meaningful error message.
The general syntax is:
try:
except EXCEPTION_TYPE as ERROR :
finally:
You try to execute a code. If it raise an error, instead of blocking the program,
you can write a specific code that can handle the situation in order to do not stop
the code flow. In the finally section we excecute the code no matter what happened.
This is usefulll when we need to do something at the end of our code.
Any error is identified by a name. These situations are categorized in Python (and
also in any other language program) in order to be solved easly by the programmers.
For example:
>>> try:
>>> result = 10 / 0
>>> except ZeroDivisionError:
>>> print("You tried to divide by zero!")
This structure is very useful to do several checks in our code, based on what we
have to do. For example while managing the files:
>>> try:
>>> # Attempt to open and read from a file
>>> file = open( "PATH_TO_FILE" , mode='r')
>>> content = file.read()
>>> print(content) # Print the content of the file
>>> except FileNotFoundError:
>>> # Handle the case where the file does not exist
>>> print("The file does not exist. Please check the file path.")
>>> except IOError:
>>> # Handle other I/O related errors
>>> print("An I/O error occurred while trying to read the file.")
>>> finally:
>>> # Ensure the file is closed no matter what
>>> try:
>>> file.close()
>>> print("File has been closed.")
>>> except NameError:
>>> # Handle the case where 'file' was never defined
>>> print("No file was opened, so there is nothing to close.")
def process_numbers(numbers):
try:
if not isinstance(numbers, list):
raise TypeError("Input must be a list.")
if len(numbers) == 0 :
raise ValueError("The list is empty.")
if not all(isinstance(num, (int, float)) for num in numbers):
raise ValueError("All elements in the list must be numbers.")
average = sum(numbers) / len(numbers)
largest = max(numbers)
smallest = min(numbers)
return {
'average': average,
'largest': largest,
'smallest': smallest
except TypeError as e:
print(f"TypeError: {e}")
except ValueError as e:
print(f"ValueError: {e}")
except ZeroDivisionError:
print("Error: Division by zero while computing the average.")
except Exception as e:
print(f"An unexpected error occurred: {e}")
numbers = [ 10 , 20 , 30 , 40 , 50 ]
result = process_numbers(numbers)
if result:
print("Results:", result)
process_numbers("10, 20, 30")
process_numbers([ 10 , "twenty", 30 ])
process_numbers([])
Pandas
Pandas is a powerful and flexible Python library used for data manipulation and
analysis. It provides two primary data structures: DataFrame and Series. These
structures are designed to handle and analyze structured data efficiently.
DataFrame:
A DataFrame is a two-dimensional, size-mutable, and heterogeneous tabular data
structure with labeled axes. Rows are labeled with indexes, while columns are
labeled using names.
DataFrames can be created using dictionaries where using the pandas.DataFrame()
casting. We convert a dictionary into a DataFrame: the keys become the column
names, while the values become the column values.
>>> import pandas as pd
>>> # Create a DataFrame from a dictionary
>>> data = {
>>> 'Name': ['Alice', 'Bob', 'Charlie'],
>>> 'Age': [25, 30, 35],
>>> 'City': ['New York', 'Los Angeles', 'Chicago']
>>> df = pd.DataFrame(data)
>>> print(df)
output: index Name Age City
0 Alice 25 New York
1 Bob 30 Los Angeles
2 Charlie 35 Chicago
Now, the DataFrame is a table with columns named and row labeled using indexes.
The row index, if no list is specified, is assigned automatically with integers
starting from 0, otherwise the attribute "index" can be assigned to the desired
list values.
A very useful usecase for DataFrame is to store the data coming from a CSV. Pandas
provide a powerful function in order to do that: pandas.read_csv() create a
DataFrame using the column names of the CSV as column names into the DataFrame,
and fill the column values with the items stored inside the CSV.
>>> import pandas as pd
>>> # Create a DataFrame from a CSV file
>>> df = pd.read_csv( "PATH_TO_FILE"
>>> print(df)
output: index Name Age City
0 Alice 25 New York
1 Bob 30 Los Angeles
2 Charlie 35 Chicago