Errors, modules and websites

The fourth and last part of the “Python from scratch” course: how to read errors, where to get ready-made tools and how all of this connects to websites. Lessons 10–12 and the “Guess the number” mini-project.

On the first run the browser loads Python, which takes a few seconds. Unfamiliar words are in the glossary (in Russian for now).

0 of 17 lessons and projects done

  1. Lesson 10. Errors: how to read and catch them

    Why. Everyone makes errors, even experienced programmers. A user types letters instead of a number, a record is missing, the internet goes down. A good program doesn't “crash” in such cases, it calmly explains what is wrong.

    How to read an error message. Python writes several lines, and the most important is the last one. It has the error type and a short explanation, for example ValueError: invalid literal for int(). The line with line 3 shows where to look. On this site a “What it means” hint also appears under the error.

    Errors you have already met:

    • SyntaxError — the code is written incorrectly: a missing quote, bracket, colon;
    • NameError — there is no such name, often a typo;
    • TypeError — the operation doesn't fit the type, for example text plus a number;
    • IndexError and KeyError — there is no element with such a number or key;
    • ValueError — the value doesn't fit: int("abc").

    To catch an error use try and except. It means: “try to do this, and if such an error happens, do that”. The program won't stop.

    Catch a specific error: except ValueError:, not everything at once. Otherwise except will hide a real typo too, and you'll spend a long time figuring out why the program misbehaves.

    Try it: in the first example add your own answer to the list, for example "twenty". In the second divide by zero and see what the function answers.

    Common mistake: catching absolutely everything

    An empty except: without an error name catches anything, even a typo in a variable name. The program “silently” does the wrong thing, and the cause will be hard to find. Always write which error you expect: except ValueError:.

    Common mistake: reading the message from the top

    Beginners are often scared by a long message and read its first line. Start from the last one: it says what happened, for example ValueError: invalid literal for int() with base 10: 'abc' This means “'abc' can't be turned into a whole number”.

    In short:

    • in an error message the main thing is the last line: the error type and the explanation;
    • try: — try, except Type: — what to do if such an error happened;
    • catch specific errors, not all of them at once.
    Example 1. Answers from a form
    answers = ["16", "abc", "20", ""]
    
    for text in answers:
        try:
            age = int(text)
            print("Age:", age)
        except ValueError:
            print(f"“{text}” is not a number, skipping")
    Example 2. Safe division
    def divide(a, b):
        try:
            return a / b
        except ZeroDivisionError:
            return "you can't divide by zero"
    
    print(divide(10, 4))
    print(divide(10, 0))

    Exercise: is it a number?

    Level: Easy

    The text variable holds what the user typed. Try to turn it into a number and print it. If that doesn't work, print This is not a number.

    Show the solution
    text = "12a"
    try:
        print(int(text))
    except ValueError:
        print("This is not a number")

    A harder exercise: a reliable conversion to a number

    Level: Medium

    Write a function safe_int(text, default=0). It returns the number from the text, and if the text is not a number, returns default. For example, safe_int("42") gives 42, and safe_int("abc") gives 0.

    Show the solution
    def safe_int(text, default=0):
        try:
            return int(text)
        except ValueError:
            return default
  2. Lesson 11. Modules: ready-made tools

    Why. You don't have to write everything yourself. Python comes with a whole library of ready-made tools: random numbers, maths, dates. These sets are called modules.

    How to connect one. A module is connected with the import command at the start of the program: import random. After that its tools are available after a dot: random.randint(1, 6).

    To take one thing write: from datetime import date. Then you just write date, without the module name.

    Three useful modules:

    • random — chance: randint(1, 6) rolls a die, choice(list) picks a random element;
    • math — maths: sqrt(16) is a square root, pi is the number π;
    • datetime — dates: date.today() is today's date, and the difference of two dates shows how many days are between them.

    Modules from the internet. Besides the built-in ones, there are thousands of modules by other people, called packages. They are installed with the pip install command. This is how Flask and Django are installed, we'll cover it in the first project.

    Try it: run the first example several times: the answers will differ. In the second change the event date to your birthday.

    Common mistake: forgetting import

    If you write random.randint(1, 6) right away without connecting the module, Python doesn't know it and even tells you what's wrong: NameError: name 'random' is not defined. Did you forget to import 'random'? Add import random at the start of the program.

    Common mistake: a typo in the module name

    The module name must be exact. import randon ends with an error: ModuleNotFoundError: No module named 'randon'

    In short:

    • a module is a set of ready-made tools, connected with import;
    • import random and random.randint(), or from datetime import date and just date;
    • built-in modules come with Python, the rest are installed with pip install.
    Example 1. A die and a draw
    import random
    import math
    
    print("The die shows:", random.randint(1, 6))
    
    students = ["Aruzhan", "Yerlan", "Dana", "Marat"]
    print("Next to answer:", random.choice(students))
    
    print("Square root of 144:", math.sqrt(144))
    print("Pi:", round(math.pi, 4))
    Example 2. How many days are left
    from datetime import date
    
    today = date.today()
    new_year = date(today.year + 1, 1, 1)
    
    print("Today:", today)
    print("Days until New Year:", (new_year - today).days)

    Exercise: a square root

    Level: Easy

    Connect the math module and print the square root of 144 with math.sqrt.

    Show the solution
    import math
    print(math.sqrt(144))

    A harder exercise: school days

    Level: Medium

    The school year starts on 1 September 2026 and ends on 25 May 2027. Print how many days there are between these dates.

    Show the solution
    from datetime import date
    
    start = date(2026, 9, 1)
    end = date(2027, 5, 25)
    print((end - start).days)
  3. Mini-project 4. Guess the number

    What we'll build. The computer picks a number from 1 to 100 and then guesses it itself. The trick is that it will guess in 7 tries or fewer, whatever number was picked. This is a real algorithm, called halving or binary search. This is how searching in databases works, and even the “hot and cold” game.

    You'll need: conditions (lesson 5), the while loop (lesson 7), functions (lesson 8) and the random module (lesson 11).

    How to guess. The number is somewhere between low = 1 and high = 100. We name the middle: (low + high) // 2. If we guessed it, we're done. If the secret is bigger, everything below the middle can be thrown away: low = middle + 1. If it is smaller, we throw away the upper half: high = middle - 1. Each try halves the range, so 100 numbers run out very quickly.

    Step-by-step plan:

    1. in the function guess_number(secret, low=1, high=100) create a try counter tries = 0;
    2. make a while True: loop — “repeat until we say stop”;
    3. in the loop add a try and name the middle;
    4. if you guessed it, return the number of tries at once: return ends both the loop and the function. Otherwise move low or high.

    What you can add: printing each try (“trying 50 — higher”), and also a check that 7 tries really are enough for 100 numbers: go through all the numbers from 1 to 100 with a loop and find the largest number of tries.

    How it looks step by step
    import random
    
    secret = random.randint(1, 100)
    low = 1
    high = 100
    tries = 0
    
    while True:
        tries += 1
        guess = (low + high) // 2
        if guess == secret:
            print(f"Try {tries}: {guess} — got it!")
            break
        elif guess < secret:
            print(f"Try {tries}: {guess} — higher")
            low = guess + 1
        else:
            print(f"Try {tries}: {guess} — lower")
            high = guess - 1

    Project: a guessing function

    Level: Hard

    Write a function guess_number(secret, low=1, high=100) that guesses secret by halving and returns how many tries it took. For example, guess_number(50) guesses on the first try and returns 1.

    Show the solution
    def guess_number(secret, low=1, high=100):
        tries = 0
        while True:
            tries += 1
            guess = (low + high) // 2
            if guess == secret:
                return tries
            elif guess < secret:
                low = guess + 1
            else:
                high = guess - 1
  4. Lesson 12. How this connects to websites

    Why. You have learned the basics of Python. Now let's put them together and see how a website is built from these bricks.

    How a website works. You type an address in the browser, and the browser sends a request to a server. A server is a computer running a program, for example in Python. It looks at the address, picks the right function, and that function returns a response: the text of the page. More on the “How a website works” page.

    Where your lessons are here:

    • functions — each page of the site: a function receives a request and returns a page;
    • a dictionary — “address → function”: this is how the site chooses what to show;
    • f-strings — put data into the page: “Hello, {name}!”;
    • lists and loops — a feed of posts, a task list, products in a catalogue;
    • conditions — whether the user is logged in, whether the password is correct;
    • errors — a “404: not found” page instead of the site crashing;
    • modules — Flask and Django, ready-made tools for websites.

    Flask. The second example is the same site on Flask. The line @app.route("/") says: “this address opens this function”. It is really the same dictionary of addresses, only Flask creates it for you.

    Try it: in the first example change the address to "/", then to "/tasks", then to one that doesn't exist. Add your own task to the list.

    Common mistake: there is no such page

    If you open an address that isn't in the dictionary, pages[address] fails with KeyError. A real site doesn't do that: it shows a “404: not found” page. In the example pages.get(address, not_found) does this.

    In short:

    • a website is a program: it receives an address and returns a page;
    • pages are functions, addresses are dictionary keys, data is put in with f-strings;
    • Flask and Django do the same thing, only more conveniently; next you'll build your first project on them.
    Example 1. A website from functions and a dictionary
    tasks = ["buy bread", "do homework"]
    
    def home():
        return "Home page"
    
    def task_list():
        lines = ""
        for task in tasks:
            lines += f"- {task}\n"
        return f"My tasks ({len(tasks)}):\n{lines}"
    
    def not_found():
        return "404: page not found"
    
    pages = {"/": home, "/tasks": task_list}
    
    address = "/tasks"
    print("You opened:", address)
    print(pages.get(address, not_found)())
    The same with Flask
    from flask import Flask
    
    app = Flask(__name__)
    
    @app.route("/")
    def home():
        return "Home page"
    
    print("The site answered:", app.test_client().get("/").text)

    Exercise: a new page

    Level: Easy

    Add an “About us” page to the site. Write a function about() that returns About us, and add it to the pages dictionary at the address "/about".

    Show the solution
    def home():
        return "Home page"
    
    def about():
        return "About us"
    
    pages = {"/": home}
    pages["/about"] = about

    A harder exercise: the server's response

    Level: Medium

    Write a function handle(address), like a real server's. If the address is in the pages dictionary, it calls the right function and returns its response. If the address isn't there, it returns 404: page not found.

    Show the solution
    def home():
        return "Home page"
    
    def contacts():
        return "Our contacts"
    
    pages = {"/": home, "/contacts": contacts}
    
    def handle(address):
        if address in pages:
            return pages[address]()
        return "404: page not found"

What's next

Now you understand the basics of Python. Next you'll learn what a website page is made of: HTML and CSS. And then you'll build your first site.