Module lessons (1/4)
Variables and types
In Python, a variable is simply a name we bind a value to.
You don't need to declare it with a keyword like in JavaScript: just
assign it something with the = symbol.
saluto = "Ciao, mondo!"
anni = 30
pi_greco = 3.14
attivo = TrueFrom that moment on, every time you write saluto Python replaces it
with the string "Ciao, mondo!".
Built-in types you'll always encounter
The five basic types you'll use in the first weeks are:
int— integers, with no size limit:42,-7,1_000_000.float— numbers with a decimal point:3.14,-0.5,2e10.str— text, in single or double quotes:"ciao",'mondo'.bool— truth values:TrueorFalse(capitalized!).NoneType— its only instance isNone, the equivalent of "no value".
You can always ask for the type of a value with the type(...) function:
type(42) # <class 'int'>
type(3.14) # <class 'float'>
type("ciao") # <class 'str'>
type(True) # <class 'bool'>
type(None) # <class 'NoneType'>Reassignment and dynamic types
Python is dynamically typed: the same variable can point over time to values of different types. It's not a good practice to abuse it, but it's legal:
x = 10 # ora x è int
x = "dieci" # ora x è strThe last expression is displayed
In our exercises (and in the Playground) the last expression of a block is captured as the "return value" and shown next to the output panel, REPL-style. So you can simply write the name of a variable as the last line to display its value.
Conventions and strong typing
Python is a strongly typed language: it does not perform implicit type conversions between incompatible types. For instance, summing a string and an integer ("Years: " + 30) will raise a TypeError. To achieve this, you must explicitly convert the number to a string using str(30).
Additionally, variables in Python are references to objects in memory: when you write a = 5 and then b = a, both variables point to the same integer in memory.
Try it yourself
Create a variable `greeting` with the value 'Ciao, mondo!' and then evaluate `greeting` as the last expression.
Show hint
In Python you don't need a keyword: just `name = value`.
Solution available after 3 attempts
Review exercise
Create a variable `age_type` that contains the type of the value 30 (hint: use the type function).
Show hint
type(30) returns <class 'int'>.
Solution available after 3 attempts
Additional challenge
Create a variable `height` with the float value `1.75`. Next, retrieve its type and assign it to the variable `height_type`. Finally, evaluate `height_type`.
Show hint
Use type(height) to retrieve the float's type and assign it to height_type.
Solution available after 3 attempts