← Python

Python from zero · Part 1 of 6 · No experience needed

The full story · about 13 minutes

Python from zero, part 1: names, values and the two equals signs

1 · Observe

A line of code is one instruction

Words used in this lesson
WordWhat it means
ValueA piece of information: a number, some text, True or False.
NameA label you stick on a value, so you can use it again. Also called a variable.
AssignmentStoring a value under a name, written with one equals sign: price = 62.5.
ComparisonAsking a yes-or-no question, written with two equals signs: price == 62.5.
PrintShow something on the screen: print(price).
CommentA note to yourself. Python ignores everything after the # sign on a line.

Think of a house listing: 1,075 square feet, ₹62.5 lakh, in Pune. To work with it, a computer needs two things: the facts, and a way to refer to them. Python keeps facts as values and refers to them with names, the way you put a label on a jar.

A program is a list of instructions. Python reads them from the top, one line at a time, and does each before moving to the next. It never skips ahead or guesses what you meant. That is why small details such as one equals sign or two matter so much.

The same idea in English and in Python
In EnglishIn PythonWhat happens
Let the price be 62.5price = 62.5Stores 62.5 under the name price. Nothing is shown.
Is the price 62.5?price == 62.5Asks. The answer is True or False.
Show me the priceprint(price)Shows 62.5 on the screen.
A note to myself# check this laterIgnored by Python.

2 · Express

The two-equals rule

This is the single most important thing in this lesson. One equals sign stores. Two equals signs ask.

= stores a value under a name price = 62.5
== asks whether two things are equal price == 62.5
One is a command, the other is a question. The question always answers True or False.

The other questions you can ask all use symbols you know from school, with two small differences: 'not equal' is !=, and 'at most' is <=.

Comparison symbols, with price = 62.5
SymbolMeansExampleAnswer
==is equal toprice == 62.5True
!=is not equal toprice != 62.5False
<is less thanprice < 70True
>is greater thanprice > 70False
<=is less than or equal toprice <= 62.5True
>=is greater than or equal toprice >= 70False

Every value has a type. A whole number is an int (1075). A number with a decimal point is a float (62.5). Text is a str and must be wrapped in quotes ("Pune"). True and False are bool. The type decides what you can do: you can add 5 + 5 to get 10, but "5" + "5" glues text together to make "55".

The four types you meet first
TypeExampleUsed for
int1075Counts: bedrooms, rows, years
float62.5Measurements: price, area, rate
str"Pune"Text: city names, labels
boolTrueYes or no answers
Check yourself

What does the line count = 3 do?

3 · Visualize

Watch the names change, line by line

Programmers trace a program: write down, after each line, what every name points at. This is how you understand code you did not write, and how you find your own mistakes.

A trace of four lines
LineCodeWhat Python doesNames afterwards
1area = 1075Stores 1075 under areaarea → 1075
2price = 62.5Stores 62.5 under pricearea → 1075, price → 62.5
3price = price * 2Works out the right side first: 62.5 × 2 = 125.0. Then stores it under price, replacing the old value.area → 1075, price → 125.0
4price == 125.0Asks the question. Nothing is stored.Unchanged. The answer is True.

4 · Discover

Try it: store, ask and show

Run the cell below, then change a number and run it again. Predict each line before you look at the output.

Store, ask, show: the three things you will do all day
area_sqft = 1075          # store: the name area_sqft now points at 1075
price_lakh = 62.5         # store
print(area_sqft)          # show
print(area_sqft == 1075)  # ask: is it equal to 1075?
print(area_sqft == 900)   # ask again
area_sqft = 900           # store a new value: the name now points at 900
print(area_sqft)
print(type(area_sqft), type(price_lakh), type("Pune"), type(True))
1075
True
False
900
<class 'int'> <class 'float'> <class 'str'> <class 'bool'>
Edit and run this code in your browser

Live Python

Store, ask, show: the three things you will do all day

Runs in your browser on your device. Nothing you type is sent anywhere, and nothing here changes your saved progress.

Press Ctrl+Enter (⌘+Enter on Mac) to run. Tab moves focus to the next control, as usual; use spaces to indent.

Notice that the two lines that ask (==) printed True and False, while the lines that store (=) printed nothing. Storing is silent. After the second store, area_sqft points at 900 and the old 1075 is gone.

price = price * 2 is not an equation
price = 62.5
price = price * 2     # work out the right side first (125.0), then store it back into price
print(price)
print(price == 125.0)  # asking: no storing happens here
125.0
True
Edit and run this code in your browser

Live Python

price = price * 2 is not an equation

Runs in your browser on your device. Nothing you type is sent anywhere, and nothing here changes your saved progress.

Press Ctrl+Enter (⌘+Enter on Mac) to run. Tab moves focus to the next control, as usual; use spaces to indent.

5 · Apply

Two worked examples

Example 1: a listing. Store the facts, work out the price per square foot, ask whether it is above ₹6,000, and show a sentence. The f before the quote marks lets you place a name inside curly brackets and have its value dropped into the text.

A listing, line by line
area_sqft = 1075
price_lakh = 62.5
rate = price_lakh * 100000 / area_sqft        # rupees per square foot
print("price per sq ft:", round(rate, 1))
is_expensive = rate > 6000                    # a comparison gives True or False
print("above 6000 a sq ft?", is_expensive)
city = "Pune"
print(f"{city}: {area_sqft} sq ft for {price_lakh} lakh")   # f"..." drops values into text
print(city == "pune", city == "Pune")         # capital letters matter
price per sq ft: 5814.0
above 6000 a sq ft? False
Pune: 1075 sq ft for 62.5 lakh
False True
Edit and run this code in your browser

Live Python

A listing, line by line

Runs in your browser on your device. Nothing you type is sent anywhere, and nothing here changes your saved progress.

Press Ctrl+Enter (⌘+Enter on Mac) to run. Tab moves focus to the next control, as usual; use spaces to indent.

The rate comes out at about ₹5,814 per square foot, so the answer to 'above 6000?' is False. Example 2 is the last line: "Pune" is not the same as "pune", because Python treats capital letters as different characters.

Check yourself

After x = 4 and then x = x + 1 what does x point at?

6 · Where it goes wrong

Four mistakes everyone makes

Mixing them up, and what Python says
x = 5
try:
    compile("if x = 5:\n    pass", "<cell>", "exec")   # = where == was meant
except SyntaxError as e:
    print("SyntaxError:", e.msg)
try:
    print(Price)             # the name was price (small p)
except NameError as e:
    print("NameError:", e)
try:
    print("5" + 5)           # text plus a number
except TypeError as e:
    print("TypeError:", e)
SyntaxError: invalid syntax. Maybe you meant '==' or ':=' instead of '='?
NameError: name 'Price' is not defined
TypeError: can only concatenate str (not "int") to str
Edit and run this code in your browser

Live Python

Mixing them up, and what Python says

Runs in your browser on your device. Nothing you type is sent anywhere, and nothing here changes your saved progress.

Press Ctrl+Enter (⌘+Enter on Mac) to run. Tab moves focus to the next control, as usual; use spaces to indent.

Read the last line of any error first. It names the kind of mistake and usually says what Python could not understand.

7 · In Python

Your first complete program

A program usually has four parts: store the facts, work something out, ask a question, show the answer. Here they are in order.

Your first complete program
# 1. Store what we know
area_sqft = 1075
price_lakh = 62.5
budget_lakh = 70

# 2. Work something out
rate = price_lakh * 100000 / area_sqft

# 3. Ask a question
affordable = price_lakh <= budget_lakh

# 4. Show the answer
print("rate per sq ft:", round(rate, 1))
print("within budget?", affordable)
print("type of the answer:", type(affordable).__name__)
rate per sq ft: 5814.0
within budget? True
type of the answer: bool
Edit and run this code in your browser

Live Python

Your first complete program

Runs in your browser on your device. Nothing you type is sent anywhere, and nothing here changes your saved progress.

Press Ctrl+Enter (⌘+Enter on Mac) to run. Tab moves focus to the next control, as usual; use spaces to indent.

  1. Change budget_lakh to 60 and run it. The answer to the question should flip to False.
  2. Change price_lakh to 58 and run it again. What changed in the rate?
  3. Add a line print(price_lakh == 62.5) and predict the answer before you run it. Then change it to print(price_lakh == 62) and predict again.

Stuck on a symbol? Keep the Python cheat sheet open in another tab.