Cohort 4Register

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.

CREATE, CHANGE, CHECK THE TYPEPYTHON 3.12
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'>
HANDY SHORTCUTSPYTHON 3.12
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

AllowedNot allowedWhy
order_totalorder totalNo spaces. Use _ between words (this style is called snake_case)
order22orderCannot start with a digit
total_amountclass, for, ifWords Python already uses (keywords) are reserved
customer_citycc, x1, data2Allowed, but meaningless names make code hard to read in interviews
NAMES ARE CASE-SENSITIVEPYTHON 3.12
Amount = 100
amount = 200
print(Amount, amount)        # two different variables

Output

100 200
USE BEFORE CREATEPYTHON 3.12
print(total_orders)          # used before it was created

Output

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

  1. Store a product name, its price and a quantity, then print the total cost.
  2. Swap the values of two variables without a third one.
  3. Print type(10), type(10.0) and type("10"). Why are they different?