Functions and dictionaries

The third part of the “Python from scratch” course: your own commands and data you find by name. Lessons 8–9 and two mini-projects, a shopping cart and a quiz.

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 8. Functions: your own command

    Why. The same action is often needed in different places: calculating a discounted price, greeting a user. To avoid copying code, you give it a name and call it by that name.

    What a function is. A function is your own command. You have already used ready-made ones: print, len, round. Now let's learn to make our own.

    How to define one. The word def starts the definition. Then come the function name, brackets and a colon: def greet(name):. The function's lines are indented, as in conditions and loops.

    Parameters are the empty places in the brackets. When the function is called, they are filled with values: greet("Anya") puts "Anya" into name.

    Defining is not running. The code inside def works only when the function is called: the name and brackets, greet("Anya").

    return hands back the result. A function is like a coffee machine: you give it beans, it gives back coffee. return means “here is the finished result, take it”. You can save it in a variable or use it further: total = price_with_discount(1000, 10).

    print and return are different things. print only shows a value on the screen. return hands it back to the program so you can keep working with it.

    A default value. def greet(name="guest"): — if no name is passed, it will be “guest”.

    Try it: call greet with your own name. In the second example change the discount and see how the total changes.

    Common mistake: print instead of return

    If a function prints the result instead of returning it, you can't keep working with it: the function returns the empty value None. Trying to add a number to it ends like this: TypeError: unsupported operand type(s) for +: 'NoneType' and 'int' Write return inside the function, and print the result outside: print(f(3)).

    Common mistake: forgetting the brackets when calling

    print(greet) without brackets doesn't call the function, it prints something like <function greet at 0x…>. For the function to work you need brackets: greet() or greet("Anya").

    In short:

    • def name(parameters): defines a function, and it runs when called: name(...);
    • return hands back the result, print only shows it;
    • a parameter can have a default value: name="guest".
    Example 1. A greeting
    def greet(name="guest"):
        return f"Hello, {name}!"
    
    print(greet("Anya"))
    print(greet("Marat"))
    print(greet())
    Example 2. A discounted price
    def price_with_discount(price, percent):
        return price - price * percent / 100
    
    phone = price_with_discount(120000, 10)
    cover = price_with_discount(5000, 20)
    
    print("Phone:", phone)
    print("Case:", cover)
    print("Together:", phone + cover)

    Exercise: the square of a number

    Level: Easy

    Finish the function square(n): it must return the number multiplied by itself. For example, square(3) returns 9.

    Show the solution
    def square(n):
        return n * n

    A harder exercise: a ticket price

    Level: Medium

    At the cinema children under 7 get in free, schoolchildren under 18 pay 500 tenge, everyone else pays 1000. Write a function ticket_price(age) that returns the price. For example, ticket_price(10) returns 500.

    Show the solution
    def ticket_price(age):
        if age < 7:
            return 0
        elif age < 18:
            return 500
        else:
            return 1000
  2. Mini-project 2. A shopping cart

    What we'll build. Three functions for an online shop cart. The cart holds the prices of the items, and the functions calculate the total, find expensive items and apply a discount. On a real website the same functions would be called every time the cart is opened.

    You'll need: lists (lesson 6), loops (lesson 7), conditions (lesson 5) and functions (lesson 8).

    Three functions:

    • total(cart) returns the sum of all prices. For an empty cart — 0;
    • count_expensive(cart, limit) returns how many items cost more than limit;
    • apply_discount(cart, percent) returns a new list of discounted prices, each rounded to a whole number.

    Step-by-step plan:

    1. total: create s = 0, add each price in a loop, return s. Yes, there is a ready sum(), but this way you'll understand how it works;
    2. count_expensive: the same counter, only add 1 and only under the condition if price > limit;
    3. apply_discount: create an empty list new = [], in a loop add the discounted price to it with .append(), return new.

    Why a new list. If you change the original one, the old prices are lost, and websites often show them crossed out next to the new ones.

    What you can add: a function cheapest(cart) that returns the lowest price, or average(cart) with the average price.

    How it should look
    cart = [200, 450, 1500]
    total(cart)                  → 2150
    count_expensive(cart, 400)   → 2
    apply_discount(cart, 10)     → [180, 405, 1350]

    Project: cart functions

    Level: Medium

    Finish the three functions. The check will call them with different carts, including an empty one.

    Show the solution
    def total(cart):
        s = 0
        for price in cart:
            s += price
        return s
    
    
    def count_expensive(cart, limit):
        n = 0
        for price in cart:
            if price > limit:
                n += 1
        return n
    
    
    def apply_discount(cart, percent):
        new = []
        for price in cart:
            new.append(round(price - price * percent / 100))
        return new
  3. Lesson 9. Dictionaries: find a value by its name

    Why. A website user has a name, an age, a city. It is convenient to store them not by number, as in a list, but by name: “name — Aruzhan”, “city — Almaty”. That is what dictionaries are for.

    What a dictionary is. A dictionary stores “key — value” pairs in curly braces: {"bread": 200, "milk": 450}. It is like the contacts in a phone: you find the number by the name. Or like a price list: the price by the product name.

    To get a value use its key in square brackets: prices["bread"] gives 200.

    To add or change: prices["cheese"] = 1500. If the key wasn't there, it appears, and if it was, the value is replaced. To delete a pair: del prices["bread"].

    To get safely. prices.get("coffee", 0) returns the price of coffee, and if it isn't in the dictionary, returns 0 instead of an error. You can check whether a key exists with the familiar word in: "bread" in prices.

    To go through a dictionary. for name, price in prices.items(): takes the pairs in turn: the key goes into name, the value into price.

    A list of dictionaries is the usual way to store many similar records: products, students, messages. This is exactly the form in which websites pass data to each other, it is called JSON.

    Try it: add your own product with a price, change the price of milk. In the second example add one more student.

    Common mistake: there is no such key

    If you ask for a key that isn't in the dictionary, the program stops: KeyError: 'coffee' Check the spelling: "Bread" and "bread" are different keys. If the key may be missing, use .get().

    Common mistake: a number instead of a key

    A dictionary has no numbers like a list: prices[0] looks for the key 0 and won't find it. Use the name: prices["bread"].

    In short:

    • a dictionary is “key: value” pairs in curly braces, a value is found by its key;
    • d[key] = value adds or changes, .get(key, fallback) doesn't fail if the key is missing;
    • for k, v in d.items(): goes through the pairs, and a list of dictionaries stores many records.
    Example 1. A price list
    prices = {"bread": 200, "milk": 450}
    
    print("Bread costs", prices["bread"], "tenge")
    
    prices["cheese"] = 1500
    prices["milk"] = 500
    print(prices)
    
    print("Coffee:", prices.get("coffee", "not on sale"))
    
    for name, price in prices.items():
        print(f"{name}: {price} tenge")
    Example 2. Students of a class
    students = [
        {"name": "Aruzhan", "city": "Almaty", "score": 92},
        {"name": "Yerlan", "city": "Astana", "score": 78},
        {"name": "Dana", "city": "Shymkent", "score": 85},
    ]
    
    for student in students:
        print(f"{student['name']} from {student['city']}: {student['score']} points")
    
    best = 0
    for student in students:
        if student["score"] > best:
            best = student["score"]
    print("Best result:", best)

    Exercise: the cost of a purchase

    Level: Easy

    The prices are in the prices dictionary. Print how much two loaves of bread and one milk cost. Take the prices from the dictionary, don't write the numbers yourself.

    Show the solution
    prices = {"bread": 200, "milk": 450, "cheese": 1500}
    print(2 * prices["bread"] + prices["milk"])

    A harder exercise: counting votes

    Level: Medium

    A class was choosing a pet for the nature corner. The votes are in the votes list. Fill the counts dictionary: the key is the animal, the value is how many votes it got.

    Show the solution
    votes = ["cat", "dog", "cat", "parrot", "cat", "dog"]
    counts = {}
    for vote in votes:
        counts[vote] = counts.get(vote, 0) + 1
    print(counts)
  4. Mini-project 3. A quiz

    What we'll build. A quiz checker: the questions with correct answers are in one dictionary, the student's answers in another. The program counts the correct answers and gives a grade. Tests on any learning website work like this, including the final test on this site.

    You'll need: strings (lesson 4), conditions (lesson 5), loops (lesson 7), functions (lesson 8) and dictionaries (lesson 9).

    Two functions:

    • check_quiz(questions, answers) returns how many answers are correct. An answer counts even if the student wrote it in small letters or with spaces at the edges. If a question wasn't answered, it simply doesn't count;
    • grade(score, total) turns the result into a word: from 90% — excellent, from 70% — good, from 50% — not bad, otherwise try again.

    Step-by-step plan:

    1. in check_quiz create a counter and go through the questions: for question, right in questions.items():;
    2. get the student's answer safely: answers.get(question, ""). If there is no answer, you get an empty string, and the program won't fail;
    3. compare the answers after bringing both to the same form: .strip().lower();
    4. in grade calculate the percent: score * 100 // total, then if and elif, as in the lesson on conditions.

    What you can add: a list of the questions the student got wrong, to show them the correct answers.

    Quiz data
    questions = {
        "Capital of Kazakhstan?": "Astana",
        "What is 7 * 8?": "56",
        "Language of this course?": "Python",
    }
    answers = {
        "Capital of Kazakhstan?": " astana ",
        "What is 7 * 8?": "54",
        "Language of this course?": "python",
    }
    print("Questions:", len(questions))
    print("Answer to the first:", answers["Capital of Kazakhstan?"])

    Project: checking a quiz

    Level: Medium

    Finish the two functions. With the data from the example, check_quiz must return 2, and grade(2, 3) must return not bad.

    Show the solution
    def check_quiz(questions, answers):
        score = 0
        for question, right in questions.items():
            given = answers.get(question, "")
            if given.strip().lower() == right.lower():
                score += 1
        return score
    
    
    def grade(score, total):
        percent = score * 100 // total
        if percent >= 90:
            return "excellent"
        elif percent >= 70:
            return "good"
        elif percent >= 50:
            return "not bad"
        else:
            return "try again"

Next: part 4

Errors, modules and websites: how to read error messages, where to get ready-made tools and how all of this connects to websites.