PART 1 · PYTHON FROM ZERO · LESSON 2
Variables and names
FreeLesson 4 of 78
A variable is a label you stick on a value so you can use it later. Most programs are just values, labels and steps.
Writing orders = 15 means "remember 15, and call it orders". The = sign is not "equals" from maths; read it as "becomes". You can change what a label points at any time, and Python always uses the latest value.
orders = 15 # orders becomes 15
city = "Bengaluru" # text goes in quotes
price = 799.0 # numbers with a dot are decimals
is_delivered = True # True / False, capital first letter
print(orders, city, price, is_delivered)
orders = orders + 1 # use the old value to make a new one
print("now:", orders)
print(type(orders), type(city), type(price), type(is_delivered))Output
15 Bengaluru 799.0 True now: 16 <class 'int'> <class 'str'> <class 'float'> <class 'bool'>
a, b = 10, 20 # two at once
a, b = b, a # swap without a third variable
print(a, b)
x = y = 0 # same value, two names
GST_RATE = 0.18 # CAPITALS: a value you never change
total = 1000 * (1 + GST_RATE)
print(x, y, total)Output
20 10 0 0 1180.0
Python does not lock constants. Writing them in capitals is a promise to the reader that the value never changes.
Naming rules
| Allowed | Not allowed | Why |
|---|---|---|
order_total | order total | No spaces. Use _ between words (this style is called snake_case) |
order2 | 2order | Cannot start with a digit |
total_amount | class, for, if | Words Python already uses (keywords) are reserved |
customer_city | cc, x1, data2 | Allowed, but meaningless names make code hard to read in interviews |
Amount = 100
amount = 200
print(Amount, amount) # two different variablesOutput
100 200
print(total_orders) # used before it was createdOutput
NameError: name 'total_orders' is not defined
Create a variable on an earlier line than the one that uses it. Python reads top to bottom.
Try it yourself before moving on
- Store a product name, its price and a quantity, then print the total cost.
- Swap the values of two variables without a third one.
- Print type(10), type(10.0) and type("10"). Why are they different?