Python is known for readable code, which makes it a friendly first language for data work, automation, scripting and general programming. This course starts from zero and covers the building blocks you will use in every Python program.

Install Python or use any online editor, and run every example as you go. Programming is a skill you build by doing, so treat the examples as exercises to modify rather than text to memorise.

1. What is Python? (start here)

A friendly, readable programming language.

Python is a programming language. A programming language is a way of giving a computer precise instructions in text. The computer follows your instructions exactly, one by one, very quickly.

Python was designed to be easy to read. Its code looks a lot like plain English, which is why it is one of the most popular first languages in the world.

What Python is used for

  • Data and AI: analysing data, machine learning, chatbots.
  • Websites and servers: the back end of many apps.
  • Automation: scripts that rename 1,000 files, send reports, or collect information.
  • Science, finance, games, teaching, and much more.

What a program is

A program is a list of instructions, like a recipe: "boil water, add pasta, wait 10 minutes". The computer reads the program from top to bottom, one line at a time.

print("Step 1")
print("Step 2")
print("Step 3")

A tiny program: three instructions, run in order

If you swap the lines, the output swaps too.

Why people like Python

  • Short, clear code: there are few symbols to remember.
  • Works almost everywhere.
  • A huge community and lots of free tools.

What you will learn here

Printing, variables, types, functions, decisions, loops, lists, dictionaries and string tools. That is the core of the language, and everything else in Python builds on it.

Recap
  • Python is a readable, general-purpose programming language.
  • A program is a list of instructions run from top to bottom.
  • It is used for data, AI, websites, automation and more.

2. How Python runs your code

Writing, running, and reading the result.

In this club you write Python in the Playground. You type code, press Run, and the result appears in the Output box. Nothing to install.

What happens when you press Run

Python reads your code from top to bottom, one line at a time, and does what each line says. Python is an interpreted language: it reads and runs your text directly, with no separate "compile" step.

Indentation is part of the language

Many languages use brackets to group code. Python uses indentation: spaces at the start of a line. Lines that are indented the same amount belong together.

def say_hi():
    print("Hi!")

say_hi()

The indented line belongs to the function

Rules: use 4 spaces for each level (never mix tabs and spaces), and keep every line in a group at the same indentation. If you indent wrongly, Python stops with an IndentationError.

Case matters, spelling matters

print works. Print and prnt do not. Variable names are also case-sensitive: score and Score are different.

Errors

When something is wrong, Python stops and shows an error message that says the kind of error and the line number.

NameError: name 'nme' is not defined

A typical error

NameError is the kind of problem; the rest says that Python has never heard of a name nme. Maybe you meant name. Read error messages carefully: they tell you what and where.

Recap
  • Python reads your code top to bottom and runs each line.
  • Indentation (4 spaces) groups code together.
  • Python is case-sensitive. Error messages tell you what went wrong and where.

3. Your first program: print()

Saying hello to the computer.

The first thing every programmer learns is how to show something on the screen. In Python that is print().

print("Hello, club!")

Show a message

Piece by piece

  • print is a built-in function: a ready-made tool that shows a value.
  • The parentheses ( ) hold what you want to show, called the argument.
  • "Hello, club!" is a string: text between quotes. You can use single '...' or double "..." quotes.

Printing different things

print("Score:", 42)
print(1 + 2)
print("Ha" * 3)

Text, numbers and calculations

Several values can be printed together, separated by commas; Python puts a space between them. Anything not in quotes is treated as code and calculated first, so 1 + 2 prints 3.

Comments

Anything after a # is a comment. Python ignores it. Use comments to explain your thinking.

# This line says hello
print("Hello!")  # this part is also a comment

Comments help humans

Common beginner mistakes

  • Forgetting the quotes: print(Hello) looks for something called Hello.
  • Mismatched quotes: "Hello'.
  • Wrong capitals: Print("hi") fails. Python is case-sensitive.
  • Forgetting a closing parenthesis ).

Try it

Print anything at all and the first challenge is done.

Recap
  • print(value) shows a value on the screen.
  • Text goes inside quotes. # starts a comment.
  • Spelling and capital letters matter.

4. Variables: giving names to values

Labelled boxes that remember things.

Programs need to remember things: a name, a score, a total. A variable is a name that refers to a value. You choose the name, store a value in it, and use the name later.

name = "Sam"
score = 0
score = score + 10
print(name, score)

Creating and using variables

The = sign

In Python, = is assignment. It does not mean "equal to" like in maths. It means: "work out the right side, then store the result under the name on the left."

So score = score + 10 means: take the current value of score (0), add 10, and store 10 back into score. The last line prints Sam 10.

Naming rules

  • Letters, digits and underscores only. A name cannot start with a digit.
  • Case-sensitive: score and Score are different.
  • Write names in snake_case: player_score, total_price. Lowercase words joined with underscores.
  • Choose clear names. price is better than p.
  • Do not use Python's own words (like print, if, for) as names.

Variables are not stuck with one type

Unlike some languages, Python lets the same name hold a number first and text later. Avoid doing that: it confuses people.

Shortcuts

score += 5 means score = score + 5. Likewise -=, *=, /=.

Recap
  • A variable is a name for a value, created with =.
  • = stores a value; it is not "equals".
  • Use snake_case names that say what the value is.

5. Types of values

Whole numbers, decimals, text and True or False.

Every value has a type: what kind of thing it is and what you can do with it. Python has four basic types you meet first.

  • int: whole numbers like 42, -7, 0.
  • float: decimal numbers like 3.14 or 9.5.
  • str: text (a string), like "club".
  • bool: a Boolean, either True or False (capital first letter!).
age = 20
price = 9.5
name = "club"
ok = True
print(type(age))
print(type(price))
print(type(name))
print(type(ok))

One value of each type

type(value) tells you the type. The output looks like <class 'int'>; the word inside the quotes is the type name.

Why types matter

The same symbol can do different things depending on the type.

print(2 + 3)
print("2" + "3")

Numbers add, strings join

The first prints 5. The second prints 23: with strings, + glues text together. A number in quotes is not a number: it is text that looks like one.

Converting between types

print(int("42") + 1)
print(str(42) + " apples")
print(float("3.5"))

Convert with int(), float() and str()

Booleans come from comparisons

5 > 3 is True. 5 == 4 is False. Booleans power decisions, which you will learn in the if lesson.

Your challenge

Print the type of a whole number, a decimal, a string and a boolean, so that int, float, str and bool all appear.

Recap
  • Four basic types: int, float, str, bool.
  • type(x) shows the type. Quotes make a string, even around digits.
  • int(), float() and str() convert values.

6. Operators: calculating and comparing

The symbols that do the work.

An operator is a symbol that does something with values.

Arithmetic

print(7 + 2)    # 9    addition
print(7 - 2)    # 5    subtraction
print(7 * 2)    # 14   multiplication
print(7 / 2)    # 3.5  division (always a float)
print(7 // 2)   # 3    floor division
print(7 % 2)    # 1    remainder
print(2 ** 3)   # 8    power

Maths in Python

% is the remainder operator: 7 % 2 is 1 because 2 goes into 7 three times with 1 left over. A number is even when n % 2 == 0.

Comparison

These give back a Boolean.

print(5 > 3)    # True
print(5 < 3)    # False
print(5 >= 5)   # True
print(5 == 5)   # True  equal
print(5 != 4)   # True  not equal

Comparisons

Careful: = stores a value, == compares two values. Mixing them up is one of the most common beginner mistakes.

Logical operators

They combine Booleans, and they are written as plain words.

age = 20
print(age >= 18 and age < 65)
print(not age > 30)

and, or, not

Order of operations

As in maths: ** first, then *, /, //, %, then + and -. Use parentheses to be clear: (2 + 3) * 4 is 20.

Recap
  • + - * / // % ** do maths.
  • == != < > <= >= compare and give True or False.
  • and, or, not combine Booleans. == compares; = stores.

7. Functions: reusable instructions

Write once, use many times.

A function is a named, reusable block of code. Instead of repeating the same steps, you put them in a function and call it whenever you need them.

Think of a blender. You put things in (the inputs), press a button, and get something out (the output).

def double(n):
    return n * 2

print(double(21))
print(double(5))

Define a function, then call it

The parts

  • def starts a function definition ("define").
  • double is the name you choose.
  • (n) lists the parameters: names for the inputs. n stands for whatever value is passed in.
  • The : at the end, then the indented lines, form the body.
  • return sends a value back to the caller and ends the function.

Calling a function

double(21) calls the function. The value 21 is the argument and becomes n. The call turns into the returned value 42, which print shows.

Defining is not running

Writing def does nothing by itself. The code inside only runs when you call the function.

Return vs print

print shows something to a person. return hands a value back to the code that called the function, so you can keep using it.

def add(a, b):
    return a + b

print(add(2, 3) * 10)

The result can be used in more maths

Watch outIf you forget return, the function gives back None (Python's "nothing"). In the challenges, always return the answer instead of just printing it. Also remember to indent the body by 4 spaces.
Recap
  • def name(parameters): and an indented body.
  • Calling a function runs it. return gives a value back.
  • print shows; return hands back.

8. Strings and f-strings

Putting values inside text.

A string is a sequence of characters, written in quotes. You often need to build sentences with values inside them. Python has a very friendly tool for that: the f-string.

name = "club"
print(f"Hello, {name}!")

An f-string

Put the letter f right before the opening quote, and write { } where a value should go. Python replaces {name} with the value of name.

You can put expressions in the braces

price = 4
count = 3
print(f"Total: {price * count} dollars")

Calculations inside text

The older way: joining with +

You can also glue strings together with +, but you must add spaces yourself, and numbers must be converted with str().

name = "club"
print("Hello, " + name + "!")

Joining with +

F-strings are easier to read, so prefer them.

A function that builds a greeting

def greet(name):
    return f"Hello, {name}!"

print(greet("Sam"))

Return a finished sentence

Your challenge

Write greet(name) that returns Hello, followed by the name and !. Return it; do not print it.

Recap
  • f"...{value}..." puts values into text.
  • Expressions work inside the braces.
  • Prefer f-strings over joining with +.

9. Making decisions with if

Code that chooses what to do.

Real programs need to choose: "if it is raining, take an umbrella". In Python that is if.

n = 5
if n > 0:
    print("positive")
elif n < 0:
    print("negative")
else:
    print("zero")

if, elif and else

How it reads

  • if is followed by a condition: something that is True or False, then a colon :.
  • The indented lines under it run only when the condition is true.
  • elif ("else if") adds another check. Python tests from the top and runs the first one that is true.
  • else catches everything left. It is optional.

Conditions

Anything that is True or False works: age >= 18, name == "Sam", is_logged_in, or combinations with and / or / not.

Functions can decide too

return ends a function immediately, so it works nicely with if.

def sign(n):
    if n > 0:
        return 1
    if n < 0:
        return -1
    return 0

print(sign(5), sign(-3), sign(0))

A function with three outcomes

Your challenge

sign(n) returns 1 for positive numbers, -1 for negative numbers and 0 for zero. Walk through the three cases above, and you are done.

Watch outTwo classic slips: writing = instead of == in the condition, and forgetting the colon or the indentation.
Recap
  • if / elif / else choose a path; the first true branch runs.
  • The colon and the indentation are required.
  • Use == to compare, not =.

10. Lists: collections of values

Keeping many values together.

So far a variable has held one value. A list holds many values, in order. Write it with square brackets, separating items with commas.

langs = ["HTML", "CSS", "Python"]
print(langs)
print(len(langs))

Create a list

Reading items: indexes

Each item has a position called an index, and indexes start at 0.

langs = ["HTML", "CSS", "Python"]
print(langs[0])
print(langs[1])
print(langs[-1])

The first item is at index 0

langs[-1] is a Python special: negative numbers count from the end, so -1 is the last item.

Changing lists

langs = ["HTML", "CSS"]
langs.append("Python")       # add to the end
print(len(langs))            # how many items
print("CSS" in langs)        # is it in the list?
langs[0] = "HTML5"           # replace an item
print(langs)

List tools

  • append(item) adds to the end.
  • len(list) counts items.
  • item in list is True if the item is there.
  • list[i] = value replaces an item.

Lists can hold anything

Numbers, strings, even other lists: [1, "two", True, [3, 4]].

Recap
  • A list is an ordered collection in square brackets.
  • Indexes start at 0; -1 is the last item.
  • append, len and in are everyday tools.

11. Loops: doing something many times

Repeat without repeating yourself.

Imagine adding up 1,000 numbers by typing + 1,000 times. A loop repeats code for you.

for

A for loop runs once for each item of a list.

for n in [1, 2, 3]:
    print(n)

Print every item

On each round, n becomes the next item: first 1, then 2, then 3. When the items run out, the loop ends. Remember the colon and the indented body.

range

range(n) makes the numbers 0 up to n - 1. Use it to repeat something a set number of times.

for i in range(5):
    print(i)

Count from 0 to 4

range(1, 6) gives 1 to 5, and range(0, 10, 2) gives 0, 2, 4, 6, 8.

Loop over text

A string is a sequence of letters, so you can loop over it too.

for letter in "club":
    print(letter)

One letter at a time

while

while repeats as long as a condition is True. Make sure something inside makes it false, or it will never stop.

n = 3
while n > 0:
    print(n)
    n = n - 1

Count down

Loop over a list of things, with a variable

When you loop, you often keep a variable that changes each time (a counter or a total). That is the next idea, and you will use it in the challenges.

Recap
  • for item in list: runs the body once per item.
  • range(n) gives 0 to n - 1.
  • Strings can be looped over, letter by letter.

12. Looping over text and checking letters

Counting things in a string.

You now know loops and strings. Together they can answer questions about text, like "how many vowels are in this word?"

Is it in there?

The in operator asks whether one string appears inside another.

print("a" in "apple")
print("z" in "apple")
print("e" in "aeiou")

The in operator

Changing case

Computers see "A" and "a" as different characters. To compare fairly, change everything to the same case first with .lower().

print("PYTHON".lower())
print("A" in "aeiou")
print("A".lower() in "aeiou")

lower() makes comparison fair

Counting with a loop

A counter is a variable that starts at 0, and goes up by 1 each time you find what you want.

count = 0
for letter in "banana":
    if letter == "a":
        count += 1
print(count)

Count the letter "a"

Trace: the loop visits b, a, n, a, n, a. Each time the letter is a, count goes up. At the end it is 3.

Putting it in a function

def count_a(text):
    count = 0
    for letter in text.lower():
        if letter == "a":
            count += 1
    return count

print(count_a("Banana"))

A reusable function

Your challenge

Write count_vowels(text), which counts the letters a, e, i, o, u, in upper or lower case. Instead of checking letter == "a", check whether letter in "aeiou".

Recap
  • "x" in text checks whether a letter is inside.
  • .lower() makes comparisons case-insensitive.
  • A counter that starts at 0 and goes up inside a loop counts things.

13. Totals and filters

Adding up only the items you want.

Two patterns appear in almost every program. You have just seen the first.

The counter

Start at 0, add 1 when something is true.

The accumulator (running total)

Start at 0, add each value as you loop.

total = 0
for n in [1, 2, 3, 4]:
    total += n
print(total)

Add up a list

Trace: total is 0; after 1 it is 1; after 2 it is 3; after 3 it is 6; after 4 it is 10.

Add a filter

Put an if inside the loop to add only the items you want. The condition n % 2 == 0 is true for even numbers.

total = 0
for n in [1, 2, 3, 4]:
    if n % 2 == 0:
        total += n
print(total)

Add up only the even numbers

The odd numbers 1 and 3 are skipped. The total is 2 + 4 = 6.

In a function

def sum_even(numbers):
    total = 0
    for n in numbers:
        if n % 2 == 0:
            total += n
    return total

print(sum_even([1, 2, 3, 4]))
print(sum_even([]))

The pattern as a function

Details that matter

  • Create total = 0 before the loop, not inside it. Otherwise it resets on every round.
  • return total goes after the loop, at the same indentation as for. If you put it inside the loop, the function stops after the first item.
  • For an empty list the loop never runs, so the function returns 0. That is the right answer.
Recap
  • Counter: +1 each time something is true. Accumulator: add each value.
  • An if inside the loop filters which items count.
  • Start the total before the loop; return it after the loop.

14. More with lists: biggest value and empty lists

Looking for the best item.

Python has built-in tools for common list questions:

nums = [3, 1, 4, 1, 5]
print(len(nums))
print(max(nums))
print(min(nums))
print(sum(nums))
print(sorted(nums))

Built-in list tools

  • max() and min() give the biggest and smallest items.
  • sum() adds all the items.
  • sorted() returns a new sorted list.

The empty list problem

max([]) causes an error, because there is no biggest item in an empty list. A careful function checks for that first.

print(max([]))

This crashes with ValueError

None: "nothing here"

Python has a special value, None, that means "no value". A good function returns None when there is no sensible answer.

def largest(numbers):
    if len(numbers) == 0:
        return None
    return max(numbers)

print(largest([3, 9, 2]))
print(largest([]))

Check for empty first

You can also write the check as if not numbers:: an empty list counts as false.

Doing it by hand

Without max, you remember the best so far, and update it in a loop. This is a good exercise: it is the same accumulator idea.

def largest(numbers):
    if not numbers:
        return None
    best = numbers[0]
    for n in numbers:
        if n > best:
            best = n
    return best

print(largest([3, 9, 2]))

Track the biggest value in a loop

Recap
  • max, min, sum, sorted and len answer common questions about lists.
  • max([]) is an error. Check for an empty list first.
  • None means "no value". Return it when there is no answer.

15. Dictionaries: labelled values

Look things up by name.

A list stores values by position. A dictionary (dict) stores values by name (called a key). Use it when you describe one thing with several details, like a person or a product.

person = {"name": "Sam", "age": 20}
print(person["name"])
print(person["age"])

A dictionary

Parts

  • Curly braces { } wrap the dictionary.
  • Each entry is key: value.
  • Entries are separated by commas.
  • Read a value with its key in square brackets: person["name"].

Changing and adding

person = {"name": "Sam", "age": 20}
person["age"] = 21
person["city"] = "Dhaka"
print(person)
print("city" in person)

Update, add and check

Missing keys

Reading a key that does not exist is an error. .get(key) is the safe way: it returns None (or a default you choose).

person = {"name": "Sam"}
print(person.get("age"))
print(person.get("age", 0))

A safe lookup

Looping over a dictionary

person = {"name": "Sam", "age": 20}
for key, value in person.items():
    print(key, "=", value)

Keys and values together

A function that builds a dictionary

def describe(name, age):
    return {"name": name, "age": age}

print(describe("Sam", 20))

Return a dictionary from a function

Recap
  • A dict maps keys to values: {"key": value}.
  • Read with d[key]; add or change by assigning.
  • .get(key) is the safe lookup; .items() loops over pairs.

16. List comprehensions

Build a list in one line.

A very common job is "make a new list from an old one, keeping only some items". You could write a loop:

nums = [1, 2, 3, 4]
evens = []
for n in nums:
    if n % 2 == 0:
        evens.append(n)
print(evens)

The loop way

Python lets you write the same thing in one line. This is a list comprehension.

nums = [1, 2, 3, 4]
evens = [n for n in nums if n % 2 == 0]
print(evens)

The comprehension way

How to read it

[ n for n in nums if n % 2 == 0 ] reads as: "a list of n, for each n in nums, if n is even." The three parts:

  1. What to put in the new list (n).
  2. Where it comes from (for n in nums).
  3. An optional filter (if ...).

Transforming

Change the first part to change each item.

nums = [1, 2, 3]
print([n * 2 for n in nums])
print([n ** 2 for n in nums])

Doubling and squaring

In a function

def even_numbers(numbers):
    return [n for n in numbers if n % 2 == 0]

print(even_numbers([1, 2, 3, 4, 5, 6]))

Even numbers only

TipIf a comprehension gets hard to read, use a normal loop. Clarity beats cleverness.
Recap
  • [expression for item in list if condition] builds a new list.
  • It replaces a loop that appends to a new list.
  • The original list is not changed.

17. String methods

Powerful text tools.

A method is a function that belongs to a value, called with a dot: text.upper(). Strings have many handy ones.

text = "  hello world  "
print(text.strip())
print(text.upper())
print(text.replace("world", "club"))
print("hello world".title())
print("hello world".split())

A tour of string methods

  • .strip() removes spaces from both ends.
  • .upper() and .lower() change case.
  • .replace(a, b) swaps text.
  • .title() capitalises each word.
  • .split() cuts a string into a list of words. .split(",") cuts at commas.
  • " ".join(list) is the opposite: it glues a list of strings into one string, with the text before the dot placed between them.

Strings are never changed in place

Methods return a new string. The original stays as it was. Store the result if you want to keep it.

name = "club"
name.upper()
print(name)
name = name.upper()
print(name)

The original does not change

Building your own title case

Combine the tools: split into words, capitalise each, join with spaces.

def title_case(text):
    words = text.split()
    result = []
    for word in words:
        result.append(word.capitalize())
    return " ".join(result)

print(title_case("hello world"))

Capitalise every word

Your challenge

Write title_case(text) so title_case('hello world') gives 'Hello World'. A one-liner works too: text.title(), or a comprehension with .capitalize().

Recap
  • Methods are called with a dot: text.method().
  • split() makes a list; " ".join(list) makes a string.
  • Methods return new strings and do not change the original.

18. Reading errors and fixing bugs

What to do when your code does not work.

A bug is a mistake in code. Finding and fixing bugs is called debugging, and it is a big part of every programmer's day.

Step 1: read the error

Python's messages say the type and the line.

  • SyntaxError: the code is written wrongly (missing colon, bracket or quote).
  • IndentationError: the spacing at the start of a line is wrong.
  • NameError: you used a name that does not exist (typo, or you did not create it yet).
  • TypeError: a value of the wrong type was used, such as adding a number to text.
  • IndexError: you asked for a list position that is not there.
  • KeyError: you asked for a dictionary key that is missing.
  • ZeroDivisionError: you divided by zero.
print("Total: " + 5)
# TypeError: can only concatenate str (not "int") to str

An example

The fix is print("Total:", 5) or print(f"Total: {5}").

Step 2: no error but a wrong answer?

Print the values to see what is happening.

def add(a, b):
    print("a is", a, "b is", b)
    return a + b

print(add(2, 3))

Peek inside your function

Step 3: shrink the problem

Cut away everything unrelated until the bug is tiny, then fix it.

Mistake checklist

  • = instead of == in a condition.
  • Missing colon : after if, for, def.
  • Forgetting return in a function.
  • Indentation off by a space or two.
  • Capital letters (True, not true).
TipIf you are stuck for 15 minutes, explain the problem out loud, or post it in the community. Saying it often reveals the answer.
Recap
  • Read the error type and line number.
  • Use print to inspect values.
  • Shrink the problem and check the usual mistakes.

19. What you can do next

From the basics to real projects.

You have learned the foundations of Python: values and types, variables, operators, functions, decisions, loops, lists, dictionaries, comprehensions and string tools. Almost every Python program, from tiny scripts to big AI systems, is built from these parts.

Going further

  • Modules: ready-made toolkits you load with import, such as math and random.
  • Files: reading and writing text files.
  • Classes: your own custom kinds of objects.
  • Libraries: tools for data (pandas), websites (Flask, Django), and AI (PyTorch).
import math
import random

print(math.sqrt(16))
print(random.randint(1, 6))

A taste of modules (on your own computer)

How to keep learning

  • Build tiny projects: a number guessing game, a to-do list, a quiz.
  • Redo the challenges without looking at the hints.
  • Read other people's code and ask what each line does.
  • Share your projects on CodelyTeam and ask for feedback.
Recap
  • You know the core of Python.
  • Next: modules, files, classes and libraries.
  • Practice with small projects.