Conditions, lists and loops

The second part of the “Python from scratch” course: your program learns to choose and to repeat. Lessons 5–7 and the first mini-project, a discount calculator.

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 5. Conditions: if this, then that

    Why. A website keeps choosing: whether to let a user in, whether to accept an answer, whether there is enough money for a purchase. Conditions are for choosing.

    The word if means “if”. After it come the condition and a colon. The lines below it, indented by four spaces, run only if the condition is true.

    The word else means “otherwise”. Its lines run if the condition is false. And elif means “and if not, check this”. You can write as many such checks as you like, Python goes through them from top to bottom and stops at the first true one.

    Indentation shows which lines belong to the condition. It is not decoration: without it Python won't understand what to run.

    Comparisons. > greater, < less, >= and <= — greater than or equal and less than or equal. Equality is checked with two signs: ==. Not equal — !=. Text can be compared too: password == "qwerty".

    True and false. The answer to a comparison is True or False. Check it yourself: print(5 > 3) prints True.

    Several conditions. and is true when both are true. or needs just one. not flips the answer.

    Try it: in the first example set the temperature to 10, then 30. In the second change the age and the parents' permission.

    Common mistake: one = sign instead of two

    One = sign puts a value into a variable, and comparison uses two: ==. If you write if x = 5:, Python will tell you right away: SyntaxError: invalid syntax. Maybe you meant '==' or ':=' instead of '='?

    Common mistake: a missing indent or colon

    After a condition you need a colon, and the lines inside need an indent of four spaces. Otherwise Python stops: IndentationError: expected an indented block after 'if' statement on line 2 Put the colon and move the line to the right with Tab or four spaces.

    In short:

    • if — if, elif — else if, else — otherwise; after the condition a colon and an indent;
    • equality is checked with ==, and one = puts a value into a variable;
    • and — both conditions, or — at least one, not — the opposite.
    Example 1. What to wear
    temperature = -5
    
    if temperature < 0:
        print("It's freezing outside, wear a hat")
    elif temperature < 15:
        print("It's cool, take a jacket")
    else:
        print("It's warm, a T-shirt will do")
    
    print(temperature < 0)
    Example 2. Can I go hiking
    age = 15
    parents_allow = True
    
    if age >= 16 or parents_allow:
        print("You can go hiking")
    else:
        print("Not yet")
    
    if age >= 14 and age <= 17:
        print("You are in the teenagers' group")

    Exercise: even or odd

    Level: Easy

    A number is stored in the number variable. Print even if it divides by 2 with no remainder, and odd if not.

    Show the solution
    number = 7
    if number % 2 == 0:
        print("even")
    else:
        print("odd")

    A harder exercise: a grade from points

    Level: Medium

    A test gives up to 100 points. From 90 — excellent, from 70 — good, from 50 — satisfactory, below 50 — try again. Print the grade for score.

    Show the solution
    score = 78
    if score >= 90:
        print("excellent")
    elif score >= 70:
        print("good")
    elif score >= 50:
        print("satisfactory")
    else:
        print("try again")
  2. Mini-project 1. A discount calculator

    What we'll build. A program for a shop till: it calculates the discount and prints a receipt. This is how the cart of any online shop works, only there the server does the same thing.

    You'll need: numbers (lesson 2), variables (lesson 3), f-strings (lesson 4) and conditions (lesson 5).

    The shop's rules:

    • if the purchase is 5000 tenge or more, the discount is 10%;
    • students get another 5% on top;
    • discounts add up: a student buying for 6000 gets 15%.

    Step-by-step plan:

    1. create a variable discount = 0 — the discount in percent;
    2. with two separate ifs add 10 and 5 to it if the conditions are true;
    3. calculate the amount to pay and round it to a whole number: round(...);
    4. print a three-line receipt as in the “How it should look” example.

    Why two separate ifs and not elif. elif only fires if the previous condition is false. Here the discounts must add up, so each condition is checked on its own.

    What you can add: free delivery from 10 000 tenge, a 20% birthday discount, a line “You saved: … tenge”.

    How it should look
    Total: 6000 tenge
    Discount: 15%
    To pay: 5100 tenge

    Project: a receipt with a discount

    Level: Medium

    A purchase of 6000 tenge, the customer is a student. Calculate the discount by the shop's rules and print the receipt exactly as in the example.

    Show the solution
    price = 6000
    is_student = True
    discount = 0
    
    if price >= 5000:
        discount += 10
    if is_student:
        discount += 5
    
    to_pay = round(price - price * discount / 100)
    
    print(f"Total: {price} tenge")
    print(f"Discount: {discount}%")
    print(f"To pay: {to_pay} tenge")
  3. Lesson 6. Lists: many values in one variable

    Why. On websites almost everything is a list: a news feed, the students of a class, items in a cart. Keeping each value in its own variable is awkward, so they are collected in a list.

    What a list is. A list is a row of values in square brackets separated by commas: ["apple", "pear", "plum"]. Imagine a train: each value rides in its own carriage.

    Carriage numbers start from zero, like the letters in a string. fruits[0] is the first element, fruits[1] is the second. From the end you count with negative numbers: fruits[-1] is the last.

    How many elements there are is shown by the familiar len(fruits).

    A list can change. fruits[1] = "kiwi" replaces the second element. .append("banana") adds to the end, .remove("pear") removes by value.

    Is it in the list? The word in checks this: "plum" in fruits gives True or False. Handy in conditions.

    Lists of numbers. sum() adds up all the numbers, min() and max() find the smallest and largest, sorted() returns them in order.

    Try it: add your own product to the first list and remove another one. In the second example add one more grade.

    Common mistake: numbers start from zero

    In a list of three elements the numbers are 0, 1 and 2. There is no element number 3: IndexError: list index out of range The number of the last element is one less than the length. Or just write [-1].

    Common mistake: the wrong method

    You add to a list with the .append() method. If you write .add(), Python answers that a list has no such thing: AttributeError: 'list' object has no attribute 'add'

    In short:

    • a list is values in square brackets: ["a", "b"], numbers start from zero;
    • .append() adds, .remove() removes, in checks whether a value is there;
    • len(), sum(), min(), max() and sorted() work with the whole list at once.
    Example 1. A shopping list
    shopping = ["bread", "milk", "apples"]
    
    print(shopping[0])
    print(shopping[-1])
    
    shopping.append("cheese")
    shopping.remove("milk")
    print(shopping)
    print("Items in total:", len(shopping))
    print("Is there bread?", "bread" in shopping)
    Example 2. Grades for the term
    grades = [5, 4, 5, 3, 5, 4]
    
    print("Number of grades:", len(grades))
    print("Sum:", sum(grades))
    print("Best:", max(grades), "worst:", min(grades))
    print("Average:", round(sum(grades) / len(grades), 2))
    print("In order:", sorted(grades))

    Exercise: a guest list

    Level: Easy

    Two people have already been invited to a birthday party. Add a guest named Dana to the guests list and print how many guests there are now.

    Show the solution
    guests = ["Aruzhan", "Yerlan"]
    guests.append("Dana")
    print(len(guests))

    A harder exercise: the average grade

    Level: Medium

    The scores list holds a student's grades. Print the average grade rounded to one digit after the dot. You should get 4.4.

    Show the solution
    scores = [5, 4, 5, 3, 5]
    print(round(sum(scores) / len(scores), 1))
  4. Lesson 7. Loops: one action many times

    Why. A website shows a feed of a hundred posts, but the code for one post is written once. A loop repeats it for each one.

    The for loop means “for each”. for fruit in fruits: reads: “for each fruit in the list of fruits do…”. Python takes the elements one by one, puts the current one into the fruit variable and runs the indented lines.

    Repeating several times is done with range. range(5) gives the numbers 0, 1, 2, 3, 4 — five of them, starting from zero. range(1, 6) gives the numbers from 1 to 5: the last number is not included.

    Accumulating. A common trick: create a variable before the loop and change it inside. For example, total = 0, and in the loop total += price. After the loop total holds the sum.

    The while loop means “while”. It repeats lines while the condition is true. It is needed when you don't know in advance how many repeats there will be: for example, saving until you have the amount you need.

    To leave early use the break command: the loop ends at once.

    Try it: in the first example add your own fruit and change range(1, 4) to range(1, 11). In the second change the amount you save each week.

    Common mistake: an endless loop

    If nothing changes inside while, the condition is always true and the loop never ends. The program “hangs”. Check that the variable from the condition changes in the loop: for example, there is money += 150.

    Common mistake: one number short

    range(1, 10) gives the numbers from 1 to 9, not to 10. Python won't show an error, the last number just won't be in the answer. To reach 10, write range(1, 11).

    In short:

    • for x in list: repeats the indented lines for each element;
    • range(1, 6) is the numbers from 1 to 5, the last one is not included;
    • while condition: repeats while the condition is true, and something must change inside.
    Example 1. For each
    fruits = ["apple", "pear", "plum"]
    
    for fruit in fruits:
        print("I love", fruit)
    
    for number in range(1, 4):
        print("Repeat number", number)
    
    total = 0
    for price in [450, 200, 1200]:
        total += price
    print("Total:", total)
    Example 2. Saving up for headphones
    money = 0
    weeks = 0
    
    while money < 1000:
        money += 150
        weeks += 1
    
    print("Weeks needed:", weeks)
    print("Saved:", money)

    Exercise: the 7 times table

    Level: Easy

    Print five lines of the 7 times table, from 7 x 1 = 7 to 7 x 5 = 35. Use a loop, not five separate prints.

    Show the solution
    for n in range(1, 6):
        print(f"7 x {n} = {7 * n}")

    A harder exercise: the sum of even numbers

    Level: Medium

    Add up all the even numbers from 1 to 20 inclusive and print the sum. A hint from the lesson on conditions will help.

    Show the solution
    total = 0
    for n in range(1, 21):
        if n % 2 == 0:
            total += n
    print(total)

Next: part 3

Functions and dictionaries: your own commands and data you find by name. Plus two mini-projects, a shopping cart and a quiz.