Coding from Zero
Data Structures & Algorithms · First Steps · Basics · 25 min
Write and read your very first Python: print, variables, numbers vs text, if/else, loops, a tiny function, and how to read an error message without panic.
Picture a recipe card next to a shelf of shoeboxes. Python reads the card one line at a time, top to bottom, and whenever it meets `name = value` it drops the value into a box and sticks a name label on the front.
The idea in everyday words
A program is like a note you leave for a friend who is feeding your cat: 'Open the cupboard. Take one scoop. If the bowl is empty, fill it.' Your friend does exactly what the note says, in order, and nothing more. A computer is that friend, only much faster and much more literal. If you misspell 'cupboard', it stops and tells you which line confused it. That message is not a telling-off. It is the computer asking you for help.
What is a program? Your first line of code
A program is a list of instructions. Python runs them from top to bottom, one line at a time, like reading a recipe.
The first instruction everyone learns is print. It shows something on the screen. Press Run on the code below:
print("Hello!")
print("I am learning Python.")
print(2 + 3)
print("2 + 3")
Look closely at the last two lines:
print(2 + 3)shows 5. Without quotes, Python works it out first.print("2 + 3")shows 2 + 3. Anything inside quotes is text, and text is printed exactly as you typed it.
A line that starts with # is a comment: a note for humans. Python skips it.
# This line is a note. Python ignores it.
print("Only this line does something.")
You cannot break your computer here. Everything runs safely in your browser. The worst that can happen is an error message, and by the end of this lesson you will know how to read one.
Variables: labelled boxes (numbers vs text)
A variable is a value with a name, so you can use it later. Think of a box with a label stuck on the front.
score = 10
print(score)
score = score + 5
print(score)
score = 10means: put 10 in a box and stick the labelscoreon it. Read=as "gets", not "equals": score gets 10.score = score + 5: Python works out the right side first (10 + 5 = 15), then moves the labelscoreonto the new value 15.
To be exact: a Python name is really a label stuck on a box, not the box itself. The box holds the value; the name is just the sticker you use to find it. That is why "changing" score really means moving the label onto a new value. You will use this idea again in the next lessons, where one label goes on a box of many values (a list) and, later, two labels end up stuck on the same box.
Good names say what is inside: total, age, count. Names can use letters, digits and _, but cannot start with a digit or contain spaces.
Numbers vs text
The two kinds of value you will use most:
| Kind | Python calls it | Looks like | What + does |
|---|---|---|---|
| whole number | int |
12, -3, 0 |
adds: 5 + 5 is 10 |
| decimal number | float |
2.5 |
adds |
| text | str (short for "string") |
"hi", "12" |
glues: "5" + "5" is "55" |
| yes / no | bool |
True, False |
(used in decisions) |
Quotes decide everything: 12 is a number, "12" is text that happens to contain the digits 1 and 2.
print(5 + 5)
print("5" + "5")
age = 12
print("I am", age) # a comma lets print mix text and numbers
print("I am " + str(age)) # str() turns a number into text
print(int("7") + 1) # int() turns text into a number
Decisions and repeats: if / else, for, while
if / else: choose a path
temp = 30
if temp > 25:
print("Hot! Wear shorts.")
else:
print("Bring a jacket.")
print("Have a nice day!")
temp > 25is a question with a True/False answer.- If it is
True, the indented lines underifrun. Otherwise the lines underelserun. Only one path ever runs. - The colon
:and the indent (4 spaces) matter. The colon says "a block starts here"; the indented lines are that block.
| Question | Means |
|---|---|
a == b |
is a equal to b? (two equals signs; one = puts a value in a box) |
a != b |
is a different from b? |
a > b, a < b |
bigger, smaller |
a >= b, a <= b |
bigger or equal, smaller or equal |
for: do something for each item
for n in [3, 5, 2]:
print("I see", n)
for i in range(3): # range(3) gives 0, 1, 2 (starts at 0, stops BEFORE 3)
print("round", i)
The label n moves onto each item in turn, and the indented lines run once per item.
while: repeat as long as something is True
n = 3
while n > 0:
print(n)
n = n - 1 # without this line, n stays 3 and it loops forever
print("Liftoff!")
A while loop must change something so that its question eventually becomes False.
The remainder trick: %
a % b is the remainder after dividing a by b. 7 % 2 is 1, 8 % 2 is 0. So a number n is even when n % 2 == 0. That includes 0 and negative numbers like -4.
Functions: a recipe with a name
A function packs some steps behind a name so you can use them again and again.
def double(x):
result = x * 2
return result
a = double(4)
print(a)
print(double(10))
def double(x):writes the recipe down. It does not run it yet.xis a parameter: the recipe's input box. When you calldouble(4), the 4 goes intox.return resulthands the answer back to whoever called the function, and the function stops right there.a = double(4)calls (runs) the recipe and puts its answer, 8, in a box labelleda.
print vs return
printshows a value on the screen, for a human to read.returngives a value back to the code, so it can be stored or used.
A function with no return gives back a special value, None ("nothing"). Coding challenges, on this site and in interviews, always ask you to return the answer.
def shout(word):
print(word + "!") # shows it, but returns nothing
x = shout("hi")
print(x) # None
How to read an error message without panic
Every programmer sees errors all day. An error message is Python saying: "I got stuck here, and this is why." It is a clue, not a grade.
Press Run on this one. It is supposed to fail:
score = 10
print(scroe)
Python prints something like this (the file name part may look a little different on this site):
Traceback (most recent call last):
File "main.py", line 2, in <module>
print(scroe)
^^^^^
NameError: name 'scroe' is not defined. Did you mean: 'score'?
The 3-step recipe
- Read the LAST line first. It tells you WHAT went wrong. The word before the colon is the error's name.
- Find "line N". It tells you WHERE. The line is copied underneath, and the
^marks point at the exact spot. - Look at that line and compare it with what you meant. Fix one thing, then run again.
The three errors you will meet first
| Last line starts with | In plain words | Usual cause | Fix |
|---|---|---|---|
NameError |
"I don't know this name." | a typo (scroe), a wrong capital letter (Score), or using a label before you made it |
spell it exactly as when you created it |
IndentationError |
"The spaces at the start of a line are wrong." | forgot to push the line in after a :, or pushed in a line that should not be |
after if, for, while, def, push the next lines in by 4 spaces |
TypeError |
"This kind of value can't be used this way." | mixing text and a number, like "I am " + 12 |
use str(12), or print("I am", 12) with a comma |
Here is the IndentationError. Notice that nothing runs at all: Python checks the shape of the whole program before starting.
for i in range(3):
print(i)
File "main.py", line 2
print(i)
^
IndentationError: expected an indented block after 'for' statement on line 1
And the TypeError. Line 1 ran fine; line 2 stopped the program:
age = 12
print("I am " + age)
TypeError: can only concatenate str (not "int") to str
Translation: str = text, int = whole number, concatenate = glue together. "I can only glue text to text."
Ignore the scary-looking middle at first. Last line, then line number. That is enough to fix most beginner errors.
Step by step
- The call:
We run count_even([4, 7, 10]). Inside the function, the label numbers goes on the list [4, 7, 10].
- Make the counter box:
count = 0. A box labelled count holding 0. Nothing is counted yet.
- Item 4:
The loop puts the label n on 4. Is 4 % 2 == 0? The remainder of 4 / 2 is 0, so yes: 4 is even. count becomes 0 + 1 = 1.
- Item 7:
n is now 7. 7 % 2 is 1, not 0, so the if question is False. Skip. count stays 1.
- Item 10:
n is now 10. 10 % 2 is 0, so 10 is even. count becomes 1 + 1 = 2.
- Loop ends:
No items left. Python moves to the first line after the loop: return count.
- Return:
return hands 2 back to whoever called count_even. The answer is 2.
Code example
# A tiny program that uses everything from this lesson
name = "Sam"
scores = [7, 4, 10]
print("Hi", name)
total = 0
for s in scores:
total = total + s
print("Total points:", total)
if total >= 20:
print("Great game!")
else:
print("Keep practising!")
def count_down(n):
while n > 0:
print(n)
n = n - 1
return "Liftoff!"
message = count_down(3)
print(message)Interview tips
Almost every interview question is 'write a function that takes X and returns Y'. Start by writing the def line and a return, then fill in the middle.
Talk while you code: 'I'll keep a counter that starts at 0, loop over the list, and add 1 when the number is even.' Interviewers want to hear your plan in plain words.
Before saying you're done, test the tiny cases out loud: an empty list, a list with one item, and a list where nothing matches.
If you hit an error, read the last line out loud and say what it means. Calmly fixing an error is a skill interviewers like to see.
Use names that say what is inside (count, total, numbers). Clear names make your code easier to explain.
Challenge: Count the Even Numbers
Write a function count_even(numbers) that is given a list of whole numbers and returns how many of them are even.
A number is even when dividing it by 2 leaves no remainder: in Python, n % 2 == 0. Remember that 0 and negative numbers like -4 are even too.
Examples:
count_even([1, 2, 3, 4])→2count_even([7, 9])→0count_even([])→0
Return the number, don't print it.
Solve it in the browser with tests, hints and an AI coach.
Practice problems
- Running Sum of 1d Array (Easy)
- Fizz Buzz (Easy)
- Number of Steps to Reduce a Number to Zero (Easy)
- Count Odd Numbers in an Interval Range (Easy)
More in First Steps
- Think Like a Programmer
- Python Crash Course for DSA
- Functions, Lists & Strings
- Classes & Objects
- Big-O: How Fast Is My Code?
- Recursion
Next: Think Like a Programmer