Module lessons (4/4)
Type conversions
Python is strongly typed: it never adds a string to a number unless you
say so. To go from one type to another you use the constructor functions:
int(), float(), str(), bool(), list(), tuple(), set().
int("42") # 42
float("3.14") # 3.14
str(42) # '42'
list("abc") # ['a', 'b', 'c']
tuple([1, 2]) # (1, 2)
set([1, 1, 2]) # {1, 2}int() with strings
int("42") works; int("42.5") raises ValueError. For decimal strings,
go through float first: int(float("42.5")) → 42 (truncates, does not
round).
int("42") # 42
int(" 42 ") # 42 (strip automatico degli spazi)
int("42.5") # ValueError
int(float("42.5")) # 42
int("ff", 16) # 255 (base esplicita)float() with strings
Accepts decimal and scientific notation.
float("3.14") # 3.14
float("1e3") # 1000.0
float("inf") # inf
float("nan") # nanstr(): the "friendly" conversion
str(x) internally calls x.__str__() to get the "human" representation.
There is also repr(x) for the "debugger" representation, often more
explicit (with quotes for strings, etc.).
str(3.14) # '3.14'
str([1, 2]) # '[1, 2]'
str(True) # 'True'bool() and truthiness
bool(x) returns False only for Python's falsy values:
False,None- zero numbers:
0,0.0 - empty containers:
"",[],(),{},set()
Everything else is truthy.
bool(0) # False
bool("") # False
bool([]) # False
bool("0") # True ! (stringa non vuota)
bool([0]) # True ! (lista non vuota, anche se contiene 0)Pattern: safe input parsing
testo = input("età: ")
try:
eta = int(testo)
except ValueError:
print(f"non è un numero: {testo!r}")
eta = NoneBoolean evaluation (Truthiness)
In Python, every object has an implicit truth value. You can check the boolean value of any object using the bool(...) function. Empty collections (e.g. "", [], {}, set()) and zero values (0, 0.0) always evaluate to False. All other objects evaluate to True.
Try it
Given `a = '10'` and `b = '32'` (strings), compute `total` as their INTEGER sum. Evaluate `total`.
Show hint
int(a) + int(b), otherwise you concatenate the strings.
Solution available after 3 attempts
Review exercise
Given the list `values = ['', 'x', 0, None, 1, []]`, build `truthy` with ONLY the truthy elements using bool(). Evaluate `truthy`.
Show hint
List comprehension with filter bool(v) (or just 'if v').
Solution available after 3 attempts
Additional challenge
Given the list of strings `string_numbers = ["1", "2", "3"]`, convert each element to an integer using `int()` and sum them together to obtain the value `6`. Store the sum in `sum_val` and evaluate it.
Show hint
Access elements by index, e.g. int(string_numbers[0]), and sum them.
Solution available after 3 attempts