Salta al contenuto
Note per Studenti Python - Control Flow, Lists, Functions and Files Report

Python - Control Flow, Lists, Functions and Files

In questa pagina 7

Continues Python - BasicsPython 3 is a high-level, general-purpose, interpreted language. A program is a sequence of statements run by the interpreter, either interactively at the prompt or from a file with the edit/run loop. Variables are names bound to values by assignment; the basic types are int, float, str and bool, with explicit conversions (int, float, str, bool) and input always returning a string. Arithmetic uses the operators plus, minus, star, slash, double slash, percent and double star with precedence rules, relational operators produce booleans, and and, or, not combine them (precedence not, and, or; De Morgan's laws).Python - Basics → (variables, types, operators, boolean logic). Python is the language of the course; the number and text codings underneath are in Representation of InformationEverything in a computer is a sequence of bits, so each kind of information needs a coding. Natural numbers use positional notation in base 2 (conversion by repeated division by 2); signed integers use two's complement (range from minus 2 to the n minus 1 up to 2 to the n minus 1, minus 1), where negation is invert-all-bits-and-add-1, sums are plain binary sums and overflow is detected on the two top carries; hexadecimal groups bits in fours; fractions use fixed point or IEEE 754 floating point (sign, exponent in excess 127, 23-bit fraction) and are only approximate; characters are unsigned integers in a code table (ASCII, Unicode); images, video and sound are stored as numbers too (pixels, frame differences, samples).Representation of Information →.

1. Making decisions: if, else, elif

A program can make decisions, executing different statements depending on the circumstances. if makes the execution of a group of statements depend on a condition.

Syntax: the keyword if, followed by a condition (always either True or False), by the colon :, and, in the following lines, the block of statements to execute, indented relative to the if.

python
age = int(input("How old are you? "))

if age >= 18:
    print("You are of legal age.")

If the condition is True the indented block is executed; if it is False the block is skipped and the program continues. The condition does not have to be a comparison: any expression that gives a boolean value is acceptable, including those built with and, or, not.

else

To perform one action when the condition is true and another when it is false, add an else clause ("otherwise") after the if block, at the same indentation level; it introduces its own indented block.

python
grade = int(input("What grade did you get? "))
if grade >= 18:
    print("Pass")
else:
    print("Fail")
What grade did you get? 25
Pass

The two blocks are alternative and mutually exclusive: exactly one runs, never both and never neither; then the program continues after the whole structure.

elif

With more than two alternatives, insert elif clauses (else if) between the initial if and the optional final else, each with its own condition and block.

python
grade = int(input("What grade did you get? "))

if grade < 18:
    print("Fail.")
elif grade < 24:
    print("Pass.")
elif grade < 28:
    print("Good.")
else:
    print("Excellent.")
  • Conditions are evaluated from top to bottom.
  • As soon as one is true, its block is executed and all subsequent clauses are ignored.
  • If no condition is true the else block is executed, if present (otherwise nothing runs).
  • Order matters: grade < 24 is examined only after grade < 18 was false, so it already implies grade is at least 18; this is why grade < 24 suffices instead of grade >= 18 and grade < 24.

2. Indentation

  • Indentation is an integral part of Python syntax: it is the mechanism by which the language recognizes which statements form a block.
  • Statements in the same block must have the same indentation. The block starts with the first indented line after the colon and ends with the first line that returns to the previous indentation level.
  • The universal convention: indent each level with four spaces.
  • Consistency: mixing spaces and tabs, or using a different number of spaces from line to line within the same block, causes an IndentationError.
python
age = int(input("How old are you? "))
if age >= 18:
    print("You are of legal age.")
    print("You can vote.")
print("End of program.")

The two indented print calls form the if block and run only if the condition is true; the last print is outside the if and always runs. The incorrect version, with the print lines not indented, gives:

IndentationError: expected an indented block after 'if' statement on line 2

Another error from the notes: a wrongly indented extra line (print("hello") followed by an indented print(...)) gives IndentationError: unexpected indent. Nesting is shown by one more level of indentation (an if inside the block of another if, with its own else). The colon : always announces the start of an indented block, with the same meaning in loops and functions.

3. Loops

  • Many programs repeat the same statements (sum a sequence of grades, ask for a password until it is correct). A group of repeated statements is a loop; each single execution of the loop body is an iteration.
  • Python has two main loops: while repeats as long as a condition remains true; for repeats by iterating over a sequence of values.
  • The notes stress the difference from if: if executes its block at most once, while executes it as many times as the condition stays true (possibly none).

The while loop

Syntax like if: keyword while, condition, colon, indented block. After the block, execution goes back to the condition and evaluates it again.

python
n = 1
while n <= 5:
    print(n)
    n = n + 1
print("Done.")

Output: 1, 2, 3, 4, 5 (one per line), then Done.. Trace: n starts at 1, the condition is true, 1 is printed and n becomes 2, and so on until n is 6, when n <= 5 is false and the loop ends.

A loop with a counter has three fundamental parts:

python
n = 1           # initialization
while n <= 5:   # condition
    n = n + 1   # update
  • The update allows the condition to become false. Short form: n += 1 (the notes add -=, *= and similar forms).
  • An infinite loopa loop whose condition remains true forever, so it never stops occurs when the condition stays true forever. It is a logical error, not a syntactic one: Python does not report it automatically (a stuck program can be interrupted with Ctrl-C). Incorrect code, missing the update:
python
n = 1
while n <= 5:
    print(n)

Sentinel loops

A while loop is especially useful when the user must decide when to stop. Example: sum numbers until the user enters 0; the value 0 is the sentinel that signals the end of input.

python
total = 0
number = int(input("Enter a number (0 to stop): "))
while number != 0:
    total = total + number
    number = int(input("Enter a number (0 to stop): "))
print("The total is", total)
Enter a number (0 to stop): 10
Enter a number (0 to stop): 5
Enter a number (0 to stop): 7
Enter a number (0 to stop): 0
The total is 22

Structure: a first read before the while gives the condition a value to examine; an identical read at the end of the block prepares the value for the next check. If the user types 0 at once, the block never runs and the total stays 0.

Validating input

The same pattern repeats the request until the data is acceptable:

python
age = int(input("How old are you? "))
while age < 0:
    print("Age cannot be negative, please try again.")
    age = int(input("How old are you? "))
print("You are", age, "years old.")

The for loop and range

The for loop is suitable when we know how many times to repeat. It does not use a condition: it iterates over the elements of a sequence, executing the block once for each. range(5) produces the numbers from 0 inclusive to 5 exclusive (0 1 2 3 4); the variable i automatically takes a different value on each iteration, with no counter to initialize or increment by hand.

python
for i in range(5):
    print(i)

Output: 0, 1, 2, 3, 4. range has one, two or three arguments:

call produces
range(5) 0, 1, 2, 3, 4
range(2, 6) 2, 3, 4, 5
range(0, 10, 2) 0, 2, 4, 6, 8
range(5, 0, -1) 5, 4, 3, 2, 1

The first endpoint is included, the second is excluded (range(a, b, p) has step p, which can be negative).

Accumulating values in a variable during a loop, sum of the numbers from 1 to 100 (the second argument is 101 because it is excluded):

python
total = 0
for i in range(1, 101):
    total = total + i
print("The sum of the numbers from 1 to 100 is", total)

Output: The sum of the numbers from 1 to 100 is 5050.

Choosing between for and while

  • Use for when you know in advance how many times to repeat, when iterating over a sequence (list, range, string), or when you need a simple way to count. Example: for i in range(1, 6): print(i) runs exactly 5 times.
  • Use while when you do not know in advance how many iterations (the repetition depends on a condition: user input, a variable, the result of a computation). Example: keep asking for a number until the user enters 0.
  • In short: use for when you count, while when you check a condition.

4. Lists

A list is an ordered container of values, used when a program must manage multiple pieces of data under a single name. Elements are written inside square brackets separated by commas. A list can contain numbers, strings, booleans or elements of different types, but it is often better to use homogeneous lists (grades, names, prices). Order matters: [1, 2, 3] == [3, 2, 1] is False.

>>> grades = [24, 27, 30, 21]
>>> grades
[24, 27, 30, 21]
>>> type(grades)
<class 'list'>
python
numbers = [10, 20, 30, 40]
names = ["Ann", "Luke", "Sarah"]
mixed = [10, "hello", True, 3.5]
empty = []

An empty list is useful to start with an empty container and fill it during execution.

Indices and length

  • Elements are accessed via an index; in Python the first element has index 0, not 1. With three elements the valid indices are 0, 1, 2.
  • names[3] on a three-element list gives IndexError: list index out of range.
>>> names = ["Ann", "Luke", "Sarah"]
>>> names[0]
'Ann'
>>> names[1]
'Luke'
>>> names[2]
'Sarah'
  • len returns the number of elements; if a list has n elements the indices go from 0 to n - 1. Last element: numbers[len(numbers)-1]; second to last: numbers[len(numbers)-2].
  • Negative indices also work: -1 is the last element, -2 the second-to-last (grades[-1], grades[-2]).
>>> numbers = [10, 20, 30, 40]
>>> numbers[len(numbers)-1]
40
>>> numbers[len(numbers)-2]
30

Mutability

Lists are mutablean object whose contents can be changed after it is created: the value of any element can be changed. Strings are immutable: a character cannot be changed directly.

>>> grades = [24, 27, 18, 21]
>>> grades[2] = 30
>>> grades
[24, 27, 30, 21]
>>> word = "dog"
>>> word[0] = "l"
TypeError: 'str' object does not support item assignment

Adding and removing elements

  • append(x) adds an element at the end; useful when data is collected little by little (with input). names.append(name) uses the dot notation (a ready-made operation associated with lists).
python
names = []

name = input("First name: ")
names.append(name)

name = input("Second name: ")
names.append(name)

name = input("Third name: ")
names.append(name)

print("Names entered:", names)

Typical output: Names entered: ['Ann', 'Luke', 'Sarah'].

  • insert(index, element) (from the notes) inserts at a given position and shifts the following elements one place forward, unlike overwriting:
python
values = ["Ann", "Luke", "Sarah"]
values.insert(1, "Carl")
print(values)

Output: ['Ann', 'Carl', 'Luke', 'Sarah'].

  • pop() without arguments removes the last element and, if needed, saves it in a variable; pop(index) removes a specific element.
>>> grades = [1, 2, 3, 4]
>>> n = grades.pop()
>>> n
4
>>> names = ["Ann", "Luke", "Sarah"]
>>> removed = names.pop(1)
>>> removed
'Luke'
>>> names
['Ann', 'Sarah']
  • remove(value) (from the notes) removes by value; if the value is absent: ValueError: list.remove(x): x not in list.
>>> names = ["Ann", "Luke", "Sarah"]
>>> names.remove("Luke")
>>> names
['Ann', 'Sarah']

Iterating and processing

The most natural way to process a list is a for loop: the variable takes, one by one, all the values of the list. This allows sums, averages, maxima, minima, or printing only some elements.

python
grades = [24, 27, 30, 21]

total = 0

for grade in grades:
    total = total + grade

average = total / len(grades)

print("Average:", average)

Output: Average: 25.5 (the sum alone is 102). Instead of four separate variables, all the grades sit in one structure processed by a loop.

Complete example, grades at or above the average: the list stores the data, the loop visits them one at a time, the condition decides which to print.

python
grades = [24, 27, 30, 21, 18]

total = 0

for grade in grades:
    total = total + grade

average = total / len(grades)

print("Average:", average)
print("Grades greater than or equal to the average:")

for grade in grades:
    if grade >= average:
        print(grade)
Average: 24.0
Grades greater than or equal to the average:
24
27
30

Building a list of numbers (from the notes): read how many numbers, collect them with append, then sum them.

python
how_many = int(input("How many numbers do you want to enter? "))

numbers = []

for i in range(how_many):
    n = int(input("Number: "))
    numbers.append(n)

total = 0

for n in numbers:
    total = total + n

print("Numbers entered:", numbers)
print("Sum:", total)

With 4 numbers 10, 5, 8, 7 the output is Numbers entered: [10, 5, 8, 7] and Sum: 30.

Searching: the in operator

in checks whether an element is present; the result is a boolean (the code reads like an English sentence).

>>> names = ["Ann", "Luke", "Sarah"]
>>> "Luke" in names
True
>>> "Marco" in names
False
python
names = ["Ann", "Luke", "Sarah"]

search = input("Name to search for: ")

if search in names:
    print("Name found")
else:
    print("Name not found")

Slicing

Extracts part of a list: the left bound is included, the right bound excluded. Omit the first bound to start from the beginning, omit the second to go to the end.

>>> numbers = [10, 20, 30, 40, 50]
>>> numbers[1:4]
[20, 30, 40]
>>> numbers[:3]
[10, 20, 30]
>>> numbers[2:]
[30, 40, 50]

numbers[1:4] takes the indices 1, 2, 3.

Sorting: sorted versus sort

sorted(numbers) numbers.sort()
what it is built-in function list method
list passed as an argument prefix before the dot, no argument
effect returns a new sorted list, the original is unchanged sorts in place and returns None
>>> numbers = [30, 10, 40, 20]
>>> sorted_numbers = sorted(numbers)
>>> sorted_numbers
[10, 20, 30, 40]
>>> numbers
[30, 10, 40, 20]
>>> numbers.sort()
>>> numbers
[10, 20, 30, 40]

Strings are sorted in lexicographic order, similar to alphabetical: sorted(["Luke", "Ann", "Sarah"]) gives ['Ann', 'Luke', 'Sarah'].

Lists and strings

Both are ordered sequences: indices, len, slicing and the for loop work on both (word = "hello": word[0] is 'h', len(word) is 5, word[1:3] is 'el'). The main difference for now: a list is mutable, a string is immutable.

Practical rules for lists

  • A list is written between square brackets; elements are ordered and accessed by index; indices start from 0.
  • len gives the number of elements; lists are mutable (change, add, remove).
  • for is the most natural way to iterate; in checks presence; slicing extracts a portion.
  • sorted and sort sort lists.

5. Functions

A function is a block of statements to which we give a name. It is used to avoid rewriting the same code, to give a clear name to an operation and to break a large problem into smaller parts. Once defined, it is called whenever needed without rewriting its instructions. Already used: print, input, int, str, len, sorted.

Defining and calling

A function is defined with def, then name, round brackets and colon; the body is indented.

python
def greet():
    print("Hello!")
    print("Welcome to the program")

greet()
Hello!
Welcome to the program

The def line does not execute the function: it only tells Python that it exists. The code runs only when the function is called by writing the name followed by parentheses, needed even when the function receives no data (greet alone does not call it).

The notes' example of reuse:

python
def print_header():
    print("======================")
    print(" TOTAL CALCULATION")
    print("======================")

print_header()
price = 12
quantity = 3
total = price * quantity
print("Total:", total)
print_header()
price = 5
quantity = 8
total = price * quantity
print("Total:", total)

Parameters and arguments

The names between the parentheses in the definition are parameters; the actual values passed in the call are arguments.

python
def greet_person(name):
    print("Hello,", name)

greet_person("Ann")
greet_person("Luke")

Output: Hello, Ann and Hello, Luke (name is the parameter, "Ann" and "Luke" are the arguments). A function can have several parameters; the order of the arguments matters (positional: first argument to the first parameter, and so on).

python
def print_product(price, quantity):
    total = price * quantity
    print("Price:", price)
    print("Quantity:", quantity)
    print("Total:", total)

print_product(10, 3)
print_product(4, 7)

Output: Price 10, Quantity 3, Total 30; then Price 4, Quantity 7, Total 28.

From the slide on argument passing: arguments can also be passed by keyword, naming the parameter (greet(message="Hello", name="Alice")), which makes the call clearer and independent of the order; the number of arguments must match the number of parameters. Python passes arguments by assignment ("pass by object reference"): a function that receives a mutable object such as a list can modify it, and the change is visible outside; with an immutable object (number, string, tuple) the original value cannot be modified.

python
def add_item(lst, item):
    lst.append(item)

my_list = [1, 2, 3]
add_item(my_list, 4)
print(my_list)   # Output: [1, 2, 3, 4]

return

A function does not always print: often it must compute a value and return it to the point of the program where it was called. return lets the result be used inside other expressions.

python
def rectangle_area(base, height):
    area = base * height
    return area

result = rectangle_area(8, 5)
print("Area:", result)

Output: Area: 40. The function does not print the area; it computes and returns it, and the value is saved in result. The same function can be used in a larger expression:

python
def rectangle_area(base, height):
    return base * height

area1 = rectangle_area(8, 5)
area2 = rectangle_area(10, 2)

print("Sum of areas:", area1 + area2)

Output: Sum of areas: 60.

print shows a value on the screen; return gives a value back to the program. A function can print, return a value, do both, or neither. Common beginner error:

python
def wrong_double(x):
    print(x * 2)

result = wrong_double(5)
print("Result:", result)

Output: 10 then Result: None: the function prints 10 but returns nothing, so the result is None ("no useful value"; Python returns it automatically when there is no return). Correct version:

python
def double(x):
    return x * 2

result = double(5)
print("Result:", result)

Output: Result: 10.

Returning different values

A function can return any type of value and different values depending on the case. If it returns a boolean it can be used directly in a condition.

python
def is_even(number):
    if number % 2 == 0:
        return True
    else:
        return False

print(is_even(10))
print(is_even(7))

n = 12

if is_even(n):
    print("The number is even")
else:
    print("The number is odd")

Output: True, False, The number is even. Shorter form, because number % 2 == 0 already produces True or False:

python
def is_even(number):
    return number % 2 == 0

After return the function ends

When Python meets return, the function ends immediately; the subsequent instructions are not executed.

python
def absolute_value(x):
    if x >= 0:
        return x
    return -x

print(absolute_value(5))
print(absolute_value(-8))

Output: 5 and 8 (for a negative x the first return is not reached).

Local variables

Variables created inside a function are local: they exist only during the execution of the function and are not visible outside it.

python
def calculate_total(price, quantity):
    total = price * quantity
    return total

result = calculate_total(6, 4)
print("Result:", result)

Output: Result: 24. The variable total belongs to the function; outside, what matters is the value returned. Rule of thumb from the notes: a function should communicate with the rest of the program through its parameters and return value.

Define before calling

A function must be defined before the point at which it is called.

python
def greet():
    print("Hello!")

greet()

works; calling greet() first and defining it afterwards gives NameError: name 'greet' is not defined, because when Python reads greet() the function does not exist yet. In well-organised programs the definitions are at the start of the file and the main code that uses them comes later.

Further examples from the notes:

python
def apply_discount(price, percentage):
    discount = price * percentage / 100
    final_price = price - discount
    return final_price

price = float(input("Initial price: "))
percentage = float(input("Percentage discount: "))
final = apply_discount(price, percentage)
print("Final price:", final)

With 80 and 25 the output is Final price: 60.0. A function can receive a list:

python
def average(values):
    total = 0
    for value in values:
        total = total + value
    return total / len(values)

grades = [24, 27, 30, 21]
m = average(grades)
print("Average:", m)

Output: Average: 25.5.

Functions in separate files (modules)

For small programs everything fits in one file; when the code grows, put functions in a separate file and import them. geometry.py:

python
def rectangle_area(base, height):
    return base * height

def rectangle_perimeter(base, height):
    return 2 * (base + height)

program.py:

python
import geometry

a = geometry.rectangle_area(8, 5)
p = geometry.rectangle_perimeter(8, 5)

print("Area:", a)
print("Perimeter:", p)

Output: Area: 40, Perimeter: 26. Single functions can be imported with from:

python
from geometry import rectangle_area

a = rectangle_area(8, 5)
print("Area:", a)

There is also from geometry import *, which imports every name of the module; the notes advise avoiding it in well-organised programs because it hides where a function comes from (import geometry is more explicit).

Practical rules for functions

Choose clear names (calculate_average, not ca); use parameters for the data the function needs; use return to produce a result; do not confuse print with return; define before calling; keep functions short, one specific task each.

6. Files

Programs seen so far read from the terminal and print to the screen. A file is a container of data stored on mass storage (SSD, hard disk, USB drive) and preserves data even after the program ends. Only text files are used (files with readable characters, such as .txt and the .py files themselves).

  • When only the file name is used, Python looks for it in the current directory, the folder from which the program is run. At first it is best to put program and file in the same folder.
  • Three ideas are enough: open it with open, read or write, and let it close automatically with with.
mode meaning
"r" read (default)
"w" write: creates the file or overwrites an existing one (old content deleted)
"a" append: adds text at the end without deleting what was there
"r+" read and write (from the slide summary)

Always use with, so Python closes the file automatically, and specify encoding="utf-8" to avoid problems with accents and special characters. \n denotes a new line.

Writing (w)

python
with open("message.txt", "w", encoding="utf-8") as file:
    file.write("Hello, file!\n")
    file.write("This is the second line.\n")

print("File written successfully.")

message.txt then contains the two lines. Without \n the text is joined on the same line.

Appending (a)

python
with open("message.txt", "a", encoding="utf-8") as file:
    file.write("This line was added later.\n")

print("Line added.")

The file now has three lines (the third is "This line was added later.").

Reading (r)

read() reads the entire content and returns it as a string:

python
with open("message.txt", "r", encoding="utf-8") as file:
    content = file.read()

print("File content:")
print(content)

A file can also be read with a for loop, one line at a time. Each line already contains \n and print adds another newline, so empty lines appear between the output lines:

python
with open("message.txt", "r", encoding="utf-8") as file:
    for line in file:
        print("LINE:", line)

strip() removes the leading and trailing whitespace (including the \n):

python
with open("message.txt", "r", encoding="utf-8") as file:
    for line in file:
        line = line.strip()
        print("LINE:", line)

Output: LINE: Hello, file!, LINE: This is the second line., LINE: This line was added later. with no blank lines.

Processing numbers from a file

What is read from a file is text: numbers must be converted with int() or float(). With grades.txt containing 24, 27, 30, 18 on separate lines:

python
total = 0
count = 0

with open("grades.txt", "r", encoding="utf-8") as file:
    for line in file:
        grade = int(line.strip())
        total = total + grade
        count = count + 1

average = total / count
print("Average:", average)

Output: Average: 24.75.

More examples from the notes

Saving a list of lines (creates students.txt with one name per line), counting lines, copying a file:

python
names = ["Ann", "Luke", "Martha", "Paul"]
with open("students.txt", "w", encoding="utf-8") as file:
    for name in names:
        file.write(name + "\n")

print("List saved.")
python
count = 0
with open("students.txt", "r", encoding="utf-8") as file:
    for line in file:
        count = count + 1

print("Number of lines:", count)

Output: Number of lines: 4.

python
with open("message.txt", "r", encoding="utf-8") as source:
    content = source.read()

with open("message_copy.txt", "w", encoding="utf-8") as destination:
    destination.write(content)

print("Copy completed.")

Handling a missing file

Reading a file that does not exist raises an error. A simple form of error handling uses try and except: try to read, and if the file does not exist print a clear message.

python
try:
    with open("does_not_exist.txt", "r", encoding="utf-8") as file:
        content = file.read()
    print(content)

except FileNotFoundError:
    print("The requested file does not exist.")

Output: The requested file does not exist.

Practical rules for files

Use "w" to create or overwrite, "a" to append at the end, "r" to read; always use with; add encoding="utf-8"; remember that what is read from a file is text, so convert it before calculating.

7. Self-check questions (from the slides)

Syntactic structure of an if; the role of else and elif; why indentation is mandatory; what a block of statements is; loops versus conditional statements; when to use while; what an infinite loop is and why it is a serious error; what for does and why it is useful with range; how range(5), range(1, 6) and range(1, 10, 2) work; why accumulate values in a variable during a loop; what a text file is versus a binary file; the modes "w", "r", "a"; why use with open(...); read() versus reading line by line; why int or float are needed for numbers read from a file; what happens when reading a file that does not exist and how to handle it.

Versione ripasso

Decisions. if condition: followed by an indented block (four spaces; wrong indentation gives IndentationError). else: is the alternative block; elif adds further tests, checked top to bottom: the first true one runs and the rest are skipped.

python
if grade < 18:
    print("Fail.")
elif grade < 24:      # already implies grade >= 18
    print("Pass.")
else:
    print("Excellent.")

Loops.

  • while checks the condition before each pass (zero or more iterations); if runs at most once.
  • Counter loop: initialization, condition, update (n += 1). A missing update gives an infinite loopa loop whose condition remains true forever, so it never stops, a logical error.
  • Sentinel loop: read once before the while and again at the end of the block; 0 stops the sum.
  • Validation: repeat the request while the input is invalid.
  • for i in range(...): range(5) gives 0 to 4; range(2, 6), range(0, 10, 2), range(5, 0, -1). Start included, stop excluded.
  • Use for when the count is known or when iterating a sequence; while when it depends on a condition.
  • Accumulator: total = total + value inside the loop.

Lists. Ordered, mutable, written in square brackets, zero-based indices, len(); -1 is the last element. A bad index raises IndexError.

  • append(x) adds at the end; insert(i, x) shifts the following elements; pop() or pop(i) removes and returns; remove(value) raises ValueError if absent.
  • for item in lst; in gives a boolean; slicing lst[start:stop] excludes stop, omitted bounds go to the ends.
  • sorted(lst) returns a new list; lst.sort() sorts in place and returns None.
  • Strings are immutable (word[0] = "l" gives TypeError); lists are mutable.

Functions.

  • def name(params): defines the function; name(args) calls it. The def line alone runs nothing.
  • Parameters are in the definition, arguments in the call; positional or by keyword.
  • return gives a value back and ends the function; print only displays. No return gives None.
  • Variables created inside are local.
  • A function receiving a list can change it (object passed by reference); numbers and strings cannot be changed.
  • Define before calling (otherwise NameError). Modules: import geometry then geometry.rectangle_area(8, 5); or from geometry import rectangle_area; avoid import *.
python
def is_even(number):
    return number % 2 == 0

Files.

  • Modes: "r" read (default), "w" write (overwrites), "a" append, "r+" read and write.
  • Always with open(name, mode, encoding="utf-8") as file: so the file is closed automatically; \n ends a line.
  • read() returns the whole text; for line in file reads line by line; line.strip() removes spaces and \n.
  • File content is text: convert numbers with int() or float().
  • A missing file raises an error: try / except FileNotFoundError.

Common mistakes: no update in a while loop; forgetting that range excludes its stop and that indices start from 0; print used instead of return (result None); calling a function before defining it; "w" erasing an existing file; using file text in arithmetic without conversion.

Teoria collegata