Skip to main content
eLearner.app
Module 4 · Lesson 4 of 416/36 in the course~10 min
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().

Python
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).

Python
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.

Python
float("3.14")      # 3.14
float("1e3")       # 1000.0
float("inf")       # inf
float("nan")       # nan

str(): 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.).

Python
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.

Python
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

Python
testo = input("età: ")
try:
    eta = int(testo)
except ValueError:
    print(f"non è un numero: {testo!r}")
    eta = None

Boolean 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

Exercise#python.m4.l4.e1
Attempts: 0Loading…

Given `a = '10'` and `b = '32'` (strings), compute `total` as their INTEGER sum. Evaluate `total`.

Loading editor…
Show hint

int(a) + int(b), otherwise you concatenate the strings.

Solution available after 3 attempts

Review exercise

Exercise#python.m4.l4.e2
Attempts: 0Loading…

Given the list `values = ['', 'x', 0, None, 1, []]`, build `truthy` with ONLY the truthy elements using bool(). Evaluate `truthy`.

Loading editor…
Show hint

List comprehension with filter bool(v) (or just 'if v').

Solution available after 3 attempts

Additional challenge

Exercise#python.m4.l4.e3
Attempts: 0Loading…

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.

Loading editor…
Show hint

Access elements by index, e.g. int(string_numbers[0]), and sum them.

Solution available after 3 attempts