Variables and types
A variable is a name that refers to a value. You create one with =:
There's no special keyword and no type declaration: Python works out the type from the value. You can also reassign a variable at any time:
Naming rules
- Letters, digits and
_, but not starting with a digit:total_2, ✅2total❌ - Case-sensitive:
nameandNameare different variables - Convention: snake_case for variables and functions (
first_name,max_speed) UPPER_CASEsignals a constant you don't intend to change:MAX_USERS = 100- Choose meaningful names:
price_with_tax, notp2
The basic types
| Type | Example | Meaning |
|---|---|---|
int |
42, -7, 1_000_000 |
Whole numbers (any size!) |
float |
3.14, 2.0, 1e6 |
Decimal numbers |
str |
"hello", 'Python' |
Text (a "string" of characters) |
bool |
True, False |
Yes/no values |
NoneType |
None |
"No value here" |
type() tells you what something is:
Floats are approximate
Computers store decimals in binary, so some can't be represented exactly. This surprises everyone once:
For money, use whole cents (int) or the decimal module.
Converting between types
Mixing text and numbers without converting is an error, because Python won't guess what you meant:
Fix it with str(age), or better, an f-string: f"I am {age} years old".
Truthy and falsy
Every value can be treated as True or False. These are falsy: False, None, 0, 0.0, "" (empty string), [], {}, (). Everything else is truthy:
Comparison and logic
Note that = assigns and == compares.
Multiple assignment
None: "nothing yet"
Practice
- Create variables for a product's name, price (float) and quantity (int).
- Calculate the total, and print it with an f-string, rounded to 2 decimals:
f"{total:.2f}". - Convert the string
"250"to a number, add 50, and print the result.
1.What is the type of 7 / 7?
2.Which of these is falsy?
3.How do you swap the values of a and b in Python?