← Semester 2

IT · Sem 2 · Chapter 2

IT · Semester 2 · Chapter 2 · Grade 8 (M.2)

Problem Solving with Python 🐍

การแก้ปัญหาด้วยไพทอน

Boolean operators, the while loop, if-elif-else and your own functions. Every example, activity and exercise from the IPST textbook (book pp. 24–49) is here, and you can step through each program one line at a time.

🕶️ with Guru Jazzy

🎯 Learning objectives จุดประสงค์ของบทเรียน

By the end of this chapter you can:

  • ✅ Write Python programs that use functions you create yourself.
  • ✅ Write Python programs that use Boolean operators (and, or, not).

In this chapter: 2.1 A bus-fare calculator · 2.2 Boolean operators · 2.3 Repeating with while · 2.4 Conditions with many choices · 2.5 Functions

The Chapter 2 mascot: a Python snake
The book’s chapter map, with Chapter 2 (Python) highlighted

🧥 Starting problem

“Every day we meet situations where we have to decide, depending on different conditions, to get the result we want. For example: choosing a phone promotion, choosing a route to school on a day when the streets are flooded, or choosing clothes to suit the weather before going shopping with friends at the weekend.”

A program has to make decisions too. Even a tiny guessing game asks a question, then decides what to say back:

A program that asks for input and prints a reply
Choosing what to wear for the weather means making a decision based on conditions

📖 Review before you start ทบทวนความรู้ก่อนเรียน

Tick (✓) every statement that is correct.

✏️ Try it ลองทำดู

1. Think about the steps of washing clothes you have worn, all the way to putting the clean clothes back in the wardrobe. What jobs are there?

  1. Sort the dirty clothes (whites, colours, delicate items).
  2. Wash: soak, add detergent, wash by hand or in the machine.
  3. Rinse until the soap is gone, then spin or wring.
  4. Hang the clothes to dry.
  5. Collect the dry clothes, then iron the ones that need it.
  6. Fold or hang them, and put them away in the wardrobe.

That is decomposition from Chapter 1: one big chore became six small jobs, and some of them (wash, rinse) repeat until a condition is met.

2. Use Python’s turtle module to draw a ring made of two overlapping circles.

 

💡 What this chapter adds

In Grade 7 you wrote Python programs that run in sequence, make a choice and repeat, using input, output, mathematical operators and variables.

In this chapter you will write programs that use functions and Boolean operators, so you can solve more complicated problems efficiently.

This chapter adds functions and Boolean operators to the Python you already know

🃏 Key-term flashcards Tap to flip

2.1 A bus-fare calculator ตัวอย่างระบบคำนวณค่าโดยสารรถประจำทาง

When a parent takes a kindergarten child to school by bus, the conductor has to work out how much each of them pays. That depends on conditions such as age or height. An automatic fare system has to make the same calculation by itself, using conditions that were decided in advance.

A city bus: the conductor works out each passenger’s fare
Example 2.1 · Bus fares ค่ารถโดยสาร

A public bus company in one district announces these fares:

  • Ordinary passengers pay 10 baht each, for any distance.
  • Children under 3 years old ride free.
  • Elders aged 60 or over pay half price.
  • A group of at most 30 people whose total fare is 200 baht or more gets a further 10% discount.
Example 2.1: the fare depends on each passenger’s age

You want to take people from your village on a field trip. How would you design an algorithm to work out the bus fare?

To solve it, consider these sub-problems:

1. How do you find how many passengers are children under 3, how many are elders, and how many are left?

Answer Count everyone, the children under 3 and the elders. The number paying full fare = all passengers − children under 3 − elders.

2. What do the elders pay altogether?

Answer Number of elders × 5 baht (half of 10 baht).

3. What do the full-fare passengers pay altogether?

Answer The number left over (from 1) × 10 baht.

4. What is the total before any discount?

Answer The elders’ total (from 2) + the full-fare total (from 3).

5. Do we get the 10% discount?

Answer Yes, if there are at most 30 passengers and the total is 200 baht or more.

6. If so, what is the final fare?

Answer The total (from 4) minus 10% of the total.

7. What should be shown?

Answer The number of passengers, how many pay full fare, how many are children under 3, how many are elders, the total before the discount, and the final fare after the discount.

Taking a group from the village on a field trip: how much will the bus cost?

Putting the sub-problems in order gives this pseudocode (รหัสลำลอง):

  1. all ← number of passengers
  2. children ← number of children under 3
  3. elders ← number of elders (aged 60 or over)
  4. regular ← (all − children − elders)
  5. fare_elders ← elders × (10/2)
  6. fare_regular ← regular × 10
  7. total ← fare_elders + fare_regular
  8. show all, children, elders, regular
  9. show total
  10. if all <= 30 and total >= 200
    1. total_discounted ← total − (total × 0.1)
    2. show total_discounted
An automatic fare system has to make these decisions by itself

Step 10 needs two conditions to be true at the same time. That is exactly what the Boolean operator and in 2.2 is for. (One small slip in the book: sub-problem 1 says elders are “over 60”, but the fare rule and the pseudocode both use “60 or over”. We use 60 or over.)

Guru Jazzy’s Python version of the pseudocode. The book stops at pseudocode; here it is as a program you can step through. (The variable is called people instead of all, because all is already the name of one of Python’s built-in functions.)

Practice: be the fare machine.

2.2 Boolean operators ตัวดำเนินการบูลีน

In Grade 7 you made Python choose between paths with if and if-else. Now you will learn more about comparison expressions (นิพจน์เปรียบเทียบ) and Boolean operators, so you can write the condition for an if much more precisely.

The comparisons you know so far are simple: they compare values with just a comparison operator.

OperatorMeaningExampleResult
==equal to5 == 5True
!=not equal to5 != 5False
<less than3 < 7True
<=less than or equal to120 <= 115False
>greater than60 > 60False
>=greater than or equal to60 >= 60True

For more complicated conditions, the Boolean operators and, or and not join simple comparisons together.

Joining two comparisons with and
height <= 115 and age <= 3
FalseTrue
↓ whole expression: False

Two comparisons joined by and are True only if both are True; in every other case the result is False. For example, if height holds 120 and age holds 3, then height <= 115 and age <= 3 is False.

⚠️ Scan gap: book pp. 30–31 are missing from our copy

The rest of 2.2 (with the book’s Examples 2.2 and 2.3) falls on two pages our scanned copy does not have. So that you are not left without or and not, here is the standard Python behaviour, written by Guru Jazzy (it is not the book’s wording):

  • A or B is True if at least one of A and B is True. It is False only when both are False.
  • not A flips the value: not True is False and not False is True.
  • Order: Python works out comparisons first, then not, then and, then or. Use brackets when in doubt: not (age <= 3).
ABA and BA or Bnot A
TrueTrueTrueTrueFalse
TrueFalseFalseTrueFalse
FalseTrueFalseTrueTrue
FalseFalseFalseFalseTrue
Boolean playground: change the values and watch every condition update.

2.3 Repeating with while การวนซ้ำด้วยคำสั่ง while

To repeat the same block of statements, Python has the while statement as well as for. while is the right choice when you do not know in advance how many times the loop will repeat. It looks like this:

 
How the while statement works

How while works: if the condition is True, the block runs once, then Python goes back and checks the condition again. This repeats until the condition is False; then the loop ends and the program carries on with the next statement.

while repeats the block for as long as the condition is True
Example 2.4 · Using while when you don’t know how many times to repeat

Write a program that reads a set of positive whole numbers (you do not know in advance how many there will be), then finds their sum and the largest value.

Example 2.4 explained

  1. Line 1 reads the first positive integer into x. The user types 0 when there is no more data. Because we only want positive numbers, 0 can be the signal that the data has run out.
  2. Lines 2–4 set starting values for the variables that keep the sum (sum), the largest value (max) and the number of values (n).
  3. Line 5 is the while statement. Its condition is that x must be a positive number.
  4. Lines 6–10 are the block inside the loop: line 6 counts the values in n, line 7 adds to sum, lines 8–9 keep the largest value so far, and line 10 reads the next value.
  5. Lines 11–12: if at least one value was entered, print the results.

Teacher’s note: the book names two variables sum and max. That works, but those are also Python’s built-in sum() and max() functions, which you then can’t use in that program. In your own code, names like total and biggest are safer.

💭 Think about it ชวนคิด

In everyday life, what situations repeat in a way that is like a while loop?

  • While the sugar has not dissolved, keep stirring.
  • While nobody answers the door, knock again.
  • While the tyre is still soft, keep pumping.
  • While there are still dirty plates in the sink, wash the next one.

In each case you cannot say beforehand how many times it will happen, only the condition for stopping. That is when while beats for.

2.4 Conditions with many choices เงื่อนไขทางเลือก

if-else lets a Python program choose which block to run from the result of a condition, with two choices. For more choices you could combine if-else statements or nest them inside each other, but Python has an easier statement for many choices: if-elif-else.

 
How if-elif-else works

Python checks the conditions from the top down. The first condition that is True has its block run, and then the whole statement ends; the remaining conditions are not checked at all. If none are True, the else block runs.

You can add as many elif conditions (with their blocks) as you need, and the else part is optional.

With if-elif-else, Python can choose between more than two paths
Example 2.5 · if-elif-else for more than 2 choices

Write a Python program that tells a passenger the bus fare. The normal fare is 6.50 baht, elders pay half, and children no more than 3 years old ride free.

Example 2.5 explained

  1. Line 1 stores the fare 6.50 in fare.
  2. Line 2 reads the age into age.
  3. Line 3 checks the condition: if the age is 60 or over, the fare is halved and stored in fare, so it becomes fare/2 baht.
  4. Line 5 is the case of someone under 60 who is no more than 3 years old. elif creates this choice.
  5. Line 7 covers every other case: an ordinary passenger. if-elif-else keeps the program short and easy to check.
💭 Think about it

Which lines of Example 2.5 could you delete, and the program would still give the same results?

Lines 7 and 8 (else: and fare=6.50). Line 1 has already put 6.50 into fare, so if neither condition is True, fare is still 6.50. Try it: in the tracer above, an age of 30 never changes fare in line 8, because it sets it to the value it already has.

Example 2.6 · The area of a circle, triangle or rectangle

Write a Python program where the user chooses whether to find the area of a circle, a triangle or a rectangle.

Example 2.6 explained

  1. Line 3 reads a letter from the user into shape, to say which shape’s area is wanted.
  2. Lines 4, 7 and 11 compare that letter, to choose the circle, triangle or rectangle formula.

Try typing x as the shape: the program still asks for a width and length, because everything that is not c or t falls into else. Activity 2.1 asks you to fix that.

🅰 Activity 2.1 กิจกรรมที่ 2.1

1. Improve Example 2.6:

  • If the user types any letter that is not 'c', 't' or 'r', the program should show an error message.
  • Change line 15 from “The area of the shape is” to “The circle has area”, “The triangle has area” or “The rectangle has area”, matching the letter typed in line 3.

2. Write a Python program that:

  • asks whether to draw a circle or a square;
  • asks for the circle’s radius or the square’s side length;
  • uses the turtle to draw the shape at the size typed in.
 

3. Challenge: write a Python program that analyses a test score from 0 to 100 using the table below. But if the student still has work not handed in, the result is “ร” (incomplete), whatever the score.

Im the robot marks a challenge question
ScoreResult
0 up to (not including) 50, and no work outstandingFail (ไม่ผ่าน)
50 up to (not including) 70, and no work outstandingPass (ผ่าน)
70 up to (not including) 90, and no work outstandingGood (ดี)
90 to 100, and no work outstandingExcellent (เยี่ยม)
Work outstandingร
Be the program:
 

Checking the outstanding work first is the trick: once it is True, none of the score conditions are looked at. Because elif stops at the first True condition, score < 70 already means “50 up to 70”: there is no need to write score >= 50 and score < 70.

Activity 2.1

2.5 Functions ฟังก์ชัน

A function is a small program written to do one specific job. You can call it whenever you need it, without writing the same statements again. That makes big programs quicker to write and easier to check.

Python has many ready-made functions, and you have already used several: input(), print(), int(), float() and type(). To use a function you call it by name and pass it the values it needs inside the brackets ( ) after the name. If you pass more than one value, separate them with commas. How many values, and of what type, depends on how each function was designed. For example:

  • print('area =', area) calls print() with the string 'area =' and the value of the variable area. print() shows them on screen from left to right.
  • int('20') calls int() with one value, the string '20'.

A function can also return a value (คืนค่า) when it finishes. int('20') sends the string '20' to int(), which converts it and returns the integer 20. So you can use int('20') exactly like the number 20.

Example 2.7 · Passing values to functions and getting values back (from Example 2.5)
 

Watch line 1 being worked out, innermost function first. Type an age, then press Next.

Example 2.7 explained

  1. Line 1 calls int() and input(), one inside the other. When functions are nested, Python works out the innermost one first. So input() is called first: Python passes it the string "Your age: ", and input() shows that on screen and waits. When the user types something and presses Enter, input() returns what was typed as a string. If the user types 20, then int(input("Your age: ")) becomes int('20').
  2. Next Python works out int('20'): it sends '20' to int(), which converts the string to the integer 20 and returns it. So age=int(input("Your age: ")) becomes age=int('20'), which is age=20.
  3. Line 8 calls print() with 2 values, the string "Your fare is" and the variable fare, and print() shows them in order.

📝 Fun fact · Functions and abstraction เกร็ดน่ารู้

Using a function is a kind of hiding detail from Chapter 1’s abstraction. When you call print() or input() you do not need to know how they work inside. You only need to know what they do.

📝 Fun fact · Arguments

The values you pass to a function when you call it are called arguments (อาร์กิวเมนต์). An argument can be a value, a variable, an expression, text or even another function call. How many arguments there are depends on the function; separate them with commas ,.

🛠️ Writing your own functions

As well as Python’s ready-made functions, you can create your own. A function has 3 parts: (1) the function’s name, (2) its parameters (พารามิเตอร์) in brackets, followed by a colon :, and (3) its block of statements. Example 2.8 creates a function that does not return a value yet.

Example 2.8 · The function hello1()

Type this into a cell:

 

Result:

Hello Prawit
Defining your own function with def

Example 2.8 explained

  1. Line 1 creates a new function. The Python keyword def starts the definition. The function is named hello1 and has 1 parameter, the variable name, written inside the brackets after the name, then a colon : after the closing bracket. When the function is called, the statements inside it can use the value passed in through name.
  2. Line 2 is the function’s block. It has only one statement, print('Hello', name), which prints Hello followed by the value of name.
  3. Line 4 calls hello1() with the single string argument 'Prawit'. The statements of hello1() defined in lines 1–2 run, and the result is “Hello Prawit”.

The book’s program prints the Thai greeting สวัสดี (“sawasdee”) and the name ประวิทย์; we use English here.

The general form of a function definition:

 

A function is named by the same rules as a variable. It must have an opening and closing bracket after the name. Inside the brackets list the parameter variables; if there are none, leave the brackets empty, and if there is more than one, separate them with commas. End with a colon :. The block must be indented further than def, and if there is more than one statement they must all be indented by the same amount.

📝 Fun fact · Blocks

A group of statements called a block starts on the line after the colon :, uses indentation (การย่อหน้า), and ends where the indentation stops. In Python, the usual indent is 4 spaces.

💭 Think about it

In the program of Example 2.5, which lines are the blocks under if, elif and else?

Python marks a block by indenting it

The block under if is line 4 (fare=fare/2), under elif it is line 6 (fare=0) and under else it is line 8 (fare=6.50). Each block is one indented line. Line 9 is not indented, so it is not part of any block and always runs.

Example 2.9 · A function with more than one parameter

In Example 2.9, lines 1–2 create a new function. After the keyword def comes the name hello2, with 2 parameters, the variables fname and lname, inside the brackets. The arguments are matched to the parameters in order: the first argument goes to fname, the second to lname.

Example 2.10 · A function that draws a house

The house-drawing program from Example 1.1 in Chapter 1 can be written with functions in Python. Type this in script mode, then run the program to check the result.

Example 2.10: turn Chapter 1’s house drawing into functions

Example 2.10 explained

  1. Line 1 loads the turtle module, so you can call its drawing functions.
  2. Lines 3–8 create a function that draws a square, with 1 parameter, size, for the length of a side.
  3. Lines 10–15 create a function that draws an equilateral triangle, with 1 parameter, size, for the length of a side.
  4. Lines 17–22 create a function that draws a house, by calling the square function and the triangle function.
  5. Lines 24–29 are the main program. Line 24 makes the pen look like a turtle, line 25 sets how thick the line is, line 26 sets how fast the turtle moves, line 27 calls the function that draws a house of size 50, line 28 hides the turtle when the drawing is finished, and line 29 keeps the drawing window open until the user clicks anywhere in it.
Python and its turtle

Returning a value from a function การคืนค่าจากฟังก์ชัน

To make a function you wrote send a value back to the main program when it finishes, use the return statement followed by the expression or value to send back. If nothing needs to be returned you do not need return, as in Examples 2.8, 2.9 and 2.10.

Example 2.11 · Returning a value from a function

This program uses a function that takes the radius of a sphere and returns the sphere’s volume. Type it in script mode and run it to check.

Example 2.11 explained

  1. Line 3 starts defining sphere_volume(), with 1 parameter, the sphere’s radius, stored in r.
  2. Lines 4 and 5 are the function’s block. Line 4 calculates the volume into vol, and line 5 returns that volume to whichever program called the function.
  3. From line 7 on is the main program, which calls sphere_volume(). Line 7 reads the radius typed by the user into radius.
  4. Line 8 calls sphere_volume() with radius as its argument. When sphere_volume() finishes and returns a value, the string 'Volume is' and the returned value are passed as arguments to print().

📝 Fun fact · Returning an expression

sphere_volume() in Example 2.11 can be written more briefly, because return can send back an expression directly. So sphere_volume() could be:

 
🅰 Activity 2.2 กิจกรรมที่ 2.2

1. Use the Python turtle to draw the Olympic symbol, five overlapping coloured circles as in the picture. Create a function myCircle() to draw a circle.

Activity 2.2: the Olympic symbol, five overlapping circles
 

circle(50) draws a circle of radius 50 to the turtle’s left, so a turtle at (x, y) facing right draws a ring whose centre is (x, y + 50). Giving myCircle() parameters for the position and the colour means one function draws all five rings.

2. Write a program that prints stars with the Python turtle. Create a function star(x) that takes one parameter, x, the size of the star. Then write a program that calls this function to draw a group of big and small stars.

 

Why 144°? To draw a 5-pointed star in one stroke, the turtle turns 5 times and spins round twice in total: 2 × 360° ÷ 5 = 144°.

📋 Chapter summary สรุปท้ายบท

Python has if and if-else for programs that choose between paths. For several conditions there is nested if and if-elif-else, and the Boolean operators and, or and not build more complicated conditions out of comparisons. For repeating, for is used when you know how many times to repeat, and while when you do not know exactly how many times.

Programmers can also create functions, small programs that each do one particular job, so they can be called whenever needed without writing the same statements again. That makes big programs quicker to build and easier to check.

Chapter summary

💻 End-of-chapter activity กิจกรรมท้ายบท

Your village is holding a New Year party, and you have been asked to work out how many boxes are needed for the washed plates. Each box holds 3 stacks of 10 plates. Follow the problem-solving steps to work out the smallest number of boxes that will hold all the plates exactly, with no empty box left over.

End-of-chapter activity: boxing up the clean plates
  • What do we know? The number of plates. One box = 3 × 10 = 30 plates.
  • Sub-problems: how many boxes are completely full? Are any plates left over? If so, they need one more box.
 

// divides and throws away the remainder, and % gives the remainder. 95 plates: 95 // 30 = 3 full boxes and 95 % 30 = 5 plates left, so 4 boxes.

Practice:

📝 End-of-chapter exercises แบบฝึกหัดท้ายบท

Follow the problem-solving steps to write a Python program for each situation.

1 · Earning money selling food

You earn extra money by selling food for a shop. The shop owner pays you a share of the sales like this:

ItemPrice per unit (baht)Share per unit (baht)Extra share
Cake102More than 20 pieces: share goes up to 3 baht a piece
Chicken sticky rice205More than 30 packs: share goes up to 7 baht a pack
Orange juice153More than 30 bottles: share goes up to 5 baht a bottle

If your total sales are more than 500 baht, you get an extra 10% of the sales as well. Write a program that adds up your total sales and the share you receive.

Exercise 1: selling food for a share of the sales
 

We read “more than 20 pieces: 3 baht a piece” as the higher rate applying to every piece sold that day. If your teacher means only the pieces beyond 20, change e.g. share = cake*3 to share = 20*2 + (cake-20)*3.

2 · Which ride is cheaper?

  • An air-conditioned bus costs 5 baht per kilometre per person; under 1 km costs 5 baht.
  • A taxi starts at 35 baht for the first 3 km; after that it costs 2 baht more per kilometre. One taxi takes at most 4 people.

You and a group of friends want to travel to a station. Which ride should you choose to pay the least?

Exercise 2: which ride is the cheapest?

3 · Class height-and-weight report

Your form teacher asks you to record your classmates’ height, weight and sex and write a summary report containing:

  • each person’s name, surname, sex, height and weight;
  • the average height and weight of the whole class, and separately by sex.
Exercise 3: a class height-and-weight report
Try the report on some data (edit any cell):
NameSex (m/f)Height (cm)Weight (kg)
 
 

This uses only what this chapter teaches: a while loop that stops when the name is left blank (we don’t know how many students there are), if-else to sort by sex, and running totals.

4 · Basil-chicken rice for the school

The teacher hires a cook to make x boxes of basil-chicken rice with a fried egg for the school; the cook buys the ingredients herself. Work out how much the ingredients cost altogether, and how much she should charge per box to make a 30% profit.

Exercise 4: basil-chicken rice with a fried egg (chicken, eggs, jasmine rice, basil and chillies)

15 boxes of basil-chicken rice use:

IngredientPrice
Jasmine rice 2 kg38 baht/kg
Chicken 1 kg70 baht/kg
Holy basil 200 g20 baht/kg
Chillies 200 g45 baht/kg
Garlic 20 g80 baht/kg
Eggs 153.50 baht each

Note: seasonings (sauce, soy sauce, sugar), the stove, water, electricity and containers are provided by the school kitchen and are not counted.

 

Watch the units: 200 g = 0.2 kg and 20 g = 0.02 kg. 15 boxes cost 76 + 70 + 4 + 9 + 1.60 + 52.50 = 213.10 baht, so one box costs about 14.21 baht, and with 30% profit the price is about 18.47 baht (in practice, round up to 19 baht).

🧠 Mini-quiz

Source: IPST (สสวท.) Basic Science and Technology textbook, Technology (Computing Science), Grade 8 (M.2), Chapter 2. Figures are from the textbook; text translated and adapted by Guru Jazzy. Book pp. 30–31 are missing from our scan.

Guru Jazzy 🕶️ · Sem 2 · Chapter 2 · Problem Solving with Python