A variable is a name that refers to a value. You create one with an assignment statement.
name = "Ada"
age = 36
height = 1.68
is_engineer = TrueThe = sign is assignment, not mathematical equality. Read age = 36 as "age is assigned the value 36".
Dynamic typing#
Python is dynamically typed: a variable can refer to values of different types at different times.
value = 10
print(type(value).__name__) # int
value = "ten"
print(type(value).__name__) # strThe object has a type; the name simply points at the object. This flexibility is convenient, but clear names and small functions help prevent mistakes.
Core built-in types#
| Type | Purpose | Examples |
| --- | --- | --- |
| str | Text | "hello", 'ILoveCompiler' |
| int | Whole numbers | 0, 42, -7 |
| float | Decimal numbers | 3.14, -0.5, 2.0 |
| bool | Logical values | True, False |
| NoneType | Absence of a value | None |
type(value) returns the type object. . __name__ gives its readable name:
print(type(42))
print(type("Python"))
print(type(None))<class 'int'> <class 'str'> <class 'NoneType'>
The angle brackets are part of the representation printed by Python.
Naming variables#
Variable names may contain letters, digits, and underscores. They cannot start with a digit and cannot be a reserved keyword such as class or for.
Good names describe the value:
student_count = 28
is_submitted = False
total_price = 49.95Python style (PEP 8) uses snake_case for variables and functions, and CapWords for classes. Names are case-sensitive: total and Total are different variables.
Multiple assignment#
Assign several variables at once, or give them the same value:
x, y = 3, 8
a = b = 0
print(x, y, a, b)Tuple assignment is especially useful for swapping values without a temporary variable:
x, y = y, x
print(x, y)Constants by convention#
Python has no enforced constants. A name written in uppercase signals that it should not change:
MAX_ATTEMPTS = 3
SITE_NAME = "ILoveCompiler"Check your understanding#
What are the types of these values?
values = [12, "12", 12.0, True]
for value in values:
print(value, type(value).__name__)Run the program and check your answers in the output. Next, use numbers and operators to perform calculations.
