Docsity
Docsity

Prepara i tuoi esami
Prepara i tuoi esami

Studia grazie alle numerose risorse presenti su Docsity


Ottieni i punti per scaricare
Ottieni i punti per scaricare

Guadagna punti aiutando altri studenti oppure acquistali con un piano Premium


Guide e consigli
Guide e consigli


Python Programming: An Expressive Guide for University Students, Appunti di Ingegneria del Software

This document serves as an expressive guide to python programming, tailored for university students. It covers fundamental concepts such as data types, control flow, and object-oriented programming. The guide includes practical examples and explanations of key python features, such as lists, loops, functions, and classes. It also introduces debugging techniques and basic algorithms, providing a solid foundation for learning python. This guide is designed to help students develop a strong understanding of python programming principles and practices, enhancing their ability to solve complex problems and build robust applications. It is structured into modules and chapters, making it easy to follow and understand. The guide also includes examples of how to use python in various fields, such as data science, web development, and ai.

Tipologia: Appunti

2025/2026

In vendita dal 25/09/2025

mumuksh-attri
mumuksh-attri 🇮🇹

3 documenti

1 / 18

Toggle sidebar

Questa pagina non è visibile nell’anteprima

Non perderti parti importanti!

bg1
Python Programming: An Expressive
Guide for the University of Milan
Module 1: The Foundations - Your First Steps with
Python
Chapter 1: Getting Started
1.1 The Pythonic Mindset: Why Python? Simple syntax, vast community, and its use in
data science, web development, and AI.
1.2 Setting Up Your Environment: Installing Python, choosing an IDE (like PyCharm or
VS Code), and the importance of virtual environments.
1.3 Hello, World! Your First Program: The print() function, comments, and the
fundamental structure of a Python script.
Chapter 2: Data, Types, and Variables
2.1 Storing Information: Introduction to variables and the concept of dynamic typing.
2.2 Primitive Data Types: Numbers (int, float), strings (str), and booleans (bool).
2.3 Operators: Arithmetic (+, -, *, /), comparison (==, !=, >, <), and logical (and, or, not)
operators.
Module 2: Control Flow & Logic
Chapter 3: Making Decisions
3.1 The if, elif, else Statements: How to make your program choose a path based on
conditions.
3.2 The Power of Indentation: A crucial concept in Python that defines code blocks.
Chapter 4: Repetitive Tasks
4.1 for Loops: Iterating over sequences like lists and strings. The range() function.
4.2 while Loops: Repeating a block of code as long as a condition is true.
4.3 Loop Control: The break and continue keywords.
Module 3: Organizing Data with Collections
Chapter 5: Lists & Tuples
5.1 The list Data Type: An ordered, changeable collection. Common methods: append(),
remove(), sort().
pf3
pf4
pf5
pf8
pf9
pfa
pfd
pfe
pff
pf12

Anteprima parziale del testo

Scarica Python Programming: An Expressive Guide for University Students e più Appunti in PDF di Ingegneria del Software solo su Docsity!

Python Programming: An Expressive

Guide for the University of Milan

Module 1: The Foundations - Your First Steps with

Python

Chapter 1: Getting Started

1.1 The Pythonic Mindset: Why Python? Simple syntax, vast community, and its use in data science, web development, and AI. ● 1.2 Setting Up Your Environment: Installing Python, choosing an IDE (like PyCharm or VS Code), and the importance of virtual environments. ● 1.3 Hello, World! Your First Program: The print() function, comments, and the fundamental structure of a Python script.

Chapter 2: Data, Types, and Variables

2.1 Storing Information: Introduction to variables and the concept of dynamic typing. ● 2.2 Primitive Data Types: Numbers (int, float), strings (str), and booleans (bool). ● 2.3 Operators: Arithmetic (+, -, *, /), comparison (==, !=, >, <), and logical (and, or, not) operators.

Module 2: Control Flow & Logic

Chapter 3: Making Decisions

3.1 The if, elif, else Statements: How to make your program choose a path based on conditions. ● 3.2 The Power of Indentation: A crucial concept in Python that defines code blocks.

Chapter 4: Repetitive Tasks

4.1 for Loops: Iterating over sequences like lists and strings. The range() function. ● 4.2 while Loops: Repeating a block of code as long as a condition is true. ● 4.3 Loop Control: The break and continue keywords.

Module 3: Organizing Data with Collections

Chapter 5: Lists & Tuples

5.1 The list Data Type: An ordered, changeable collection. Common methods: append(), remove(), sort().

5.2 The tuple Data Type: An ordered, unchangeable collection. When and why to use tuples over lists. ● 5.3 Slicing: A powerful technique for accessing parts of a sequence.

Chapter 6: Dictionaries & Sets

6.1 The dict Data Type: Key-value pairs. Introduction to fast lookups and efficient data storage. ● 6.2 The set Data Type: Unordered, unindexed collections of unique elements. Useful for membership testing and eliminating duplicates.

Module 4: Functions & Modularity

Chapter 7: Writing Your Own Functions

7.1 The def Keyword: Defining functions to encapsulate reusable code. ● 7.2 Parameters and Arguments: Passing information into a function. ● 7.3 return Values: Getting a result back from a function. ● 7.4 Scope: Understanding local and global variables.

Chapter 8: Modules & Libraries

8.1 The import Statement: How to use code from other Python files and libraries. ● 8.2 Popular Libraries: An overview of math, random, and os.

Module 5: Object-Oriented Programming (OOP)

Chapter 9: Objects & Classes

9.1 The class Keyword: Creating blueprints for objects. The init constructor. ● 9.2 Attributes and Methods: Data and functions within a class. ● 9.3 The self Keyword: A fundamental concept in Python OOP.

Chapter 10: Inheritance & Polymorphism

10.1 Inheritance: Creating new classes that inherit properties from existing ones. The concept of parent and child classes. ● 10.2 Polymorphism: Objects of different classes responding to the same method call in different ways.

Module 6: Advanced Topics & Application

Chapter 11: File Input/Output (I/O)

11.1 Reading from Files: The open() function, with statements, and reading text. ● 11.2 Writing to Files: Saving your program's output to a file.

print(fruits[2]) # Output: 'cherry'

You can also use negative indexing. -1 refers to the last item.

print(fruits[-1]) # Output: 'orange' print(fruits[-2]) # Output: 'cherry'

Modifying a List

Since lists are mutable, you can change them in place. ● Changing a specific item: fruits[1] = "strawberry" print(fruits) # Output: ['apple', 'strawberry', 'cherry', 'orange']

Adding an item to the end: fruits.append("grape") print(fruits) # Output: ['apple', 'strawberry', 'cherry', 'orange', 'grape']

Inserting an item at a specific position: fruits.insert(1, "mango") print(fruits) # Output: ['apple', 'mango', 'strawberry', 'cherry', 'orange', 'grape']

Removing an item: fruits.remove("apple") print(fruits) # Output: ['mango', 'strawberry', 'cherry', 'orange', 'grape']

Pro Tip: Loops and Lists

Lists and for loops are a perfect match. You can easily iterate through all the items in a list. for fruit in fruits: print(f"I have a {fruit}.")

Output:

I have a mango.

I have a strawberry.

... and so on.

Lists are the workhorses of Python, and mastering them is a crucial step in your programming journey. They will be used everywhere, from storing user data to building complex algorithms.

Python Programming: The Expressive

Guide

A Course for the University of Milan

Prologue: The Art of the Algorithm

Programming is not merely a technical skill; it is a form of thought. It is the art of translating a human idea—a logic, a process, a dream—into a language a machine can understand. It is the delicate act of taking a complex problem and, through a process of rigorous, creative deconstruction, reducing it to its simplest, most elegant components. Python is perhaps the finest tool for this intellectual craft. Its syntax, clean and uncluttered, feels less like a sterile command-line dialect and more like a form of prose. It is designed for human readability first, and machine execution second. This guide is your invitation to not just learn a language, but to embrace a mindset—the Pythonic mindset —one that values clarity, simplicity, and the beautiful logic of a well-crafted solution. This guide is designed for the curious mind, the one that asks "why?" as often as "how?". Together, we will not just write code; we will learn to think like a Python programmer, an artisan of the digital realm.

Module 1: The Foundations - First Movements

Chapter 1: The First Brushstrokes

1.1 Python and the Art of Clarity

In a world filled with complexity, Python offers a sanctuary of simplicity. When you encounter a problem, your first thought is often to map out a solution in plain language. Python is the rare language that allows you to do exactly that. The phrase "there should be one—and preferably only one—obvious way to do it" from The Zen of Python is not just a motto; it is a guiding principle. ● Why Python?Readability: The syntax is designed to be read like English, which means less time deciphering cryptic symbols and more time focused on the logic itself. ○ Versatility: From analyzing vast datasets for a new scientific discovery to building the backend of a sleek web application, Python is a universal language. It is the intellectual polymath of programming. ○ Community: An immense global community of developers, libraries, and frameworks means you are never alone. Whatever challenge you face, someone has likely already solved it, and their solution is waiting for you in a library.

1.2 Your Digital Workshop: Setting Up the Environment

Before an artist can paint, they must prepare their canvas and organize their pigments. In the

allowing you to focus on the logic, not the syntax.

2.2 The Universe of Data: Primitive Types

All complex things are built from simple ones. In Python, our simple building blocks are the primitive data types. ● Numbers:int (Integers): The whole numbers. They are concrete and indivisible. Your age, the number of steps you've taken, the floor you are on. ○ float (Floating-point numbers): The numbers with a decimal point. They represent a spectrum, a measure that can be in between. Your height, the temperature, your grade point average. ● Text (str - Strings): A string is a sequence of characters enclosed in quotes. It is the very fabric of language in programming. A name, a sentence, a poem—all are strings. Strings are immutable , which means once they are created, they cannot be changed in place. You can create a new string with modifications, but the original remains as it was, a testament to its original form. ● Truth (bool - Booleans): The simplest and most powerful type, representing a binary state: True or False. It is the foundation of all decision-making in a program. Is the light on? True. Is the door locked? False.

2.3 The Conversation of Logic: Operators

Operators are the verbs of our programming language. They describe the actions and relationships between our data. ● Arithmetic Operators: These are the familiar actions of mathematics. + (addition), - (subtraction), * (multiplication), / (division). ● Comparison Operators: These ask questions and return a bool answer. Is this value equal to that one? (==). Is it greater than? (>). ● Logical Operators: These combine our boolean truths to form more complex ideas. and requires both conditions to be true. or requires at least one. not inverts the truth. This chapter has given you the raw materials of programming: data and the means to manipulate it. In the next chapter, we will learn how to make our program think and choose.

Module 2: Building Structures - The Art of Collections

Chapter 5: The Mutable Scroll: Lists

A list is a container, a vessel that can hold a collection of items. But it is not a rigid box; it is a flexible, dynamic, and ever-changing scroll. ● Ordered: The items within a list have a specific sequence, and that sequence is maintained. This allows us to access elements by their position, a numerical address called an index. The first item is always at index 0. ● Mutable: The most defining characteristic of a list. You can add items to it, remove items from it, and change any item within it, all after the list has been created. It is the living, breathing journal of your program's data.

5.1 Creating and Populating a List

Lists are created with square brackets [].

A simple shopping list

shopping_list = ["bread", "milk", "eggs"]

A list can hold mixed data types

diverse_list = ["Giulia", 22, True, 1.70]

It can also be created from an existing sequence

letters = list("Python") # Output: ['P', 'y', 't', 'h', 'o', 'n']

5.2 Navigating the Scroll: Indexing and Slicing

To access an item, we use its index. print(shopping_list[0]) # Output: 'bread' print(shopping_list[2]) # Output: 'eggs'

Negative indexing: a powerful shortcut.

-1 refers to the last item.

print(shopping_list[-1]) # Output: 'eggs'

Slicing is a beautiful concept in Python. It's the ability to take a part of the list, a segment of the scroll, by specifying a start and end index. numbers = [1, 2, 3, 4, 5, 6, 7]

Get items from index 2 up to (but not including) index 5

subset = numbers[2:5] # Output: [3, 4, 5]

Get all items from the beginning up to index 4

start_slice = numbers[:4] # Output: [1, 2, 3, 4]

Get all items from index 3 to the end

end_slice = numbers[3:] # Output: [4, 5, 6, 7]

This is not just a technical operation; it is a way of selectively focusing on a part of your data, a fundamental skill for any programmer.

5.3 The Mutability of the Scroll

The living nature of lists means we can change them with ease. ● append(): Adds an item to the end of the list. Like adding a new entry to the end of a journal. shopping_list.append("cheese") print(shopping_list) # Output: ['bread', 'milk', 'eggs', 'cheese']

Python Programming: The Expressive

Guide

A Course for the University of Milan

Module 2: The Logic of Action - Control Flow & Decision

Chapter 3: The Crossroads of Logic: Making Decisions

A program that simply executes a list of instructions from top to bottom is a rigid, unthinking automaton. The true power of code lies in its ability to adapt, to respond to different situations, and to choose its path. This is the art of control flow , and the fundamental tool for this is the if statement.

3.1 The if Statement: A Fork in the Road

The if statement is a simple question posed to the computer: "Is this condition true?" If the answer is "yes," a specific block of code is executed. If the answer is "no," that block is skipped. It is the very essence of a logical choice. The structure is simple and elegant:

A simple example

temperature = 25

if temperature > 30: print("It's a hot day! Stay hydrated.")

print("The program continues here.")

Notice the colon : at the end of the if line. This is Python's way of signaling the start of a new, indented block of code. The indentation itself is crucial; it is not just for style, but for defining the scope of the if statement.

3.2 Extending the Choice: else and elif

What if the first condition is false? What if we want to provide an alternative path? That's where else and elif come in. ● else: The "otherwise" clause. It provides a default block of code to run if all preceding conditions are False. weather = "rainy"

if weather == "sunny": print("Time for a picnic!") else: print("Grab an umbrella.")

elif (short for "else if"): The chain of thought. This allows you to check for multiple, mutually exclusive conditions in a single sequence. grade = 85

if grade >= 90: print("Excellent!") elif grade >= 80: print("Very good.") elif grade >= 70: print("Good.") else: print("Keep working hard.")

The interpreter will check these conditions one by one, from top to bottom. As soon as it finds a condition that is True, it executes that block and ignores the rest. This ensures that only one path is ever taken.

Chapter 4: The Rhythm of Repetition: Loops

Many tasks in programming are repetitive. You might need to process every item in a list, or continue an action until a certain condition is met. Loops are the tools that allow your program to perform these rhythmic, repetitive tasks with efficiency and grace.

4.1 The for Loop: Iteration Through a Sequence

The for loop is your master conductor for sequences. It iterates over each item in a collection—be it a list, a string, a tuple, or a range of numbers—and performs an action for each one. The syntax reflects its purpose: "for each item in this collection, do this."

Iterating over a list of names

students = ["Alice", "Bob", "Charlie"] for student in students: print(f"Hello, {student}!")

Iterating over the characters in a string

for char in "Python": print(char)

Iterating a specific number of times using range()

The range(5) function generates a sequence of numbers from 0 to 4.

for i in range(5): print(f"Looping for the {i+1}th time.")

4.2 The while Loop: Repeating Until a Condition

The while loop is a different kind of repetition. It continues to execute its block of code as long

Python Programming: The Expressive

Guide

A Course for the University of Milan

Module 5: The Object-Oriented Universe

Chapter 7: Blueprints and Living Things: Objects and Classes

Up to this point, our programs have operated on a flat plane. We've worked with data and functions, but they've been separate entities. Object-Oriented Programming, or OOP, changes this. It is a paradigm shift in how we think about code. It’s a way of modeling the world by combining data and the functions that operate on that data into a single, cohesive unit called an object. Think of a car: it has data (color, model, speed) and it has functions that act on that data (accelerate, brake, turn).

7.1 The class Keyword: The Blueprint

A class is the blueprint for an object. It defines the structure and behavior that all objects of that type will have. It's a template, a recipe, a set of instructions for creating a "thing." We define a class using the class keyword.

A simple blueprint for a 'Dog'

class Dog:

A class attribute, shared by all instances of this class

species = "Canis familiaris"

The constructor method: init

It initializes the object's data when it's created

def init(self, name, age):

These are instance attributes, unique to each object

self.name = name self.age = age

A method (a function defined inside a class)

def bark(self): return f"{self.name} says 'Woof!'"

Creating a new Dog object (an instance of the class)

my_dog = Dog("Fido", 3)

The init method is special; it is the constructor. It's automatically called whenever you create a new object. The self parameter is a crucial concept. It's a reference to the specific object that is being created or is calling the method. It allows you to access and modify the

object's unique data (its attributes ).

7.2 Attributes and Methods: The Inner Life of an Object

Attributes: These are the data associated with an object. In the Dog class, name and age are instance attributes because each dog object has its own unique name and age. species is a class attribute , a piece of data shared across all dogs. ● Methods: These are the functions defined inside a class. They are the behaviors of the object. The bark() method is an action that our dog object can perform. To call a method, you use the object's name followed by a dot and the method name: my_dog.bark().

7.3 Encapsulation: The Shell and the Core

Encapsulation is the principle of bundling an object's data and methods into a single unit. It's like putting all the controls for a machine inside a single panel, hiding the complex inner workings from the user. This simplifies our code and prevents us from accidentally changing an object's state in an unpredictable way.

Chapter 8: Building on Giants: Inheritance

A key pillar of OOP is inheritance. It is a powerful mechanism that allows a new class ( the child class ) to inherit the attributes and methods of an existing class ( the parent class ). This is a way of creating a "is a" relationship. For example, a GoldenRetriever is a Dog.

8.1 Extending a Class

To create a child class, you simply include the parent class's name in parentheses after the child class's name.

The parent class

class Animal: def init(self, name): self.name = name

def speak(self):

A generic method to be overridden by child classes

raise NotImplementedError("Subclass must implement abstract method")

The child class inherits from Animal

class Dog(Animal): def speak(self): return f"{self.name} barks."

Another child class

class Cat(Animal): def speak(self): return f"{self.name} meows."

Python Programming: The Expressive

Guide

A Course for the University of Milan

Module 2: The Logic of Action - Control Flow & Decision

Chapter 3: The Crossroads of Logic: Making Decisions

A program that simply executes a list of instructions from top to bottom is a rigid, unthinking automaton. The true power of code lies in its ability to adapt, to respond to different situations, and to choose its path. This is the art of control flow , and the fundamental tool for this is the if statement.

3.1 The if Statement: A Fork in the Road

The if statement is a simple question posed to the computer: "Is this condition true?" If the answer is "yes," a specific block of code is executed. If the answer is "no," that block is skipped. It is the very essence of a logical choice. The structure is simple and elegant:

A simple example

temperature = 25

if temperature > 30: print("It's a hot day! Stay hydrated.")

print("The program continues here.")

Notice the colon : at the end of the if line. This is Python's way of signaling the start of a new, indented block of code. The indentation itself is crucial; it is not just for style, but for defining the scope of the if statement.

3.2 Extending the Choice: else and elif

What if the first condition is false? What if we want to provide an alternative path? That's where else and elif come in. ● else: The "otherwise" clause. It provides a default block of code to run if all preceding conditions are False. weather = "rainy"

if weather == "sunny": print("Time for a picnic!") else: print("Grab an umbrella.")

elif (short for "else if"): The chain of thought. This allows you to check for multiple, mutually exclusive conditions in a single sequence. grade = 85

if grade >= 90: print("Excellent!") elif grade >= 80: print("Very good.") elif grade >= 70: print("Good.") else: print("Keep working hard.")

The interpreter will check these conditions one by one, from top to bottom. As soon as it finds a condition that is True, it executes that block and ignores the rest. This ensures that only one path is ever taken.

Chapter 4: The Rhythm of Repetition: Loops

Many tasks in programming are repetitive. You might need to process every item in a list, or continue an action until a certain condition is met. Loops are the tools that allow your program to perform these rhythmic, repetitive tasks with efficiency and grace.

4.1 The for Loop: Iteration Through a Sequence

The for loop is your master conductor for sequences. It iterates over each item in a collection—be it a list, a string, a tuple, or a range of numbers—and performs an action for each one. The syntax reflects its purpose: "for each item in this collection, do this."

Iterating over a list of names

students = ["Alice", "Bob", "Charlie"] for student in students: print(f"Hello, {student}!")

Iterating over the characters in a string

for char in "Python": print(char)

Iterating a specific number of times using range()

The range(5) function generates a sequence of numbers from 0 to 4.

for i in range(5): print(f"Looping for the {i+1}th time.")

4.2 The while Loop: Repeating Until a Condition

The while loop is a different kind of repetition. It continues to execute its block of code as long