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.
🎯 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
🧥 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:
📖 Review before you start ทบทวนความรู้ก่อนเรียน
Tick (✓) every statement that is correct.
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?
- Sort the dirty clothes (whites, colours, delicate items).
- Wash: soak, add detergent, wash by hand or in the machine.
- Rinse until the soap is gone, then spin or wring.
- Hang the clothes to dry.
- Collect the dry clothes, then iron the ones that need it.
- 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.
🃏 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 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.
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.
Putting the sub-problems in order gives this pseudocode (รหัสลำลอง):
- all ← number of passengers
- children ← number of children under 3
- elders ← number of elders (aged 60 or over)
- regular ← (all − children − elders)
- fare_elders ← elders × (10/2)
- fare_regular ← regular × 10
- total ← fare_elders + fare_regular
- show all, children, elders, regular
- show total
- if all <= 30 and total >= 200
- total_discounted ← total − (total × 0.1)
- show total_discounted
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.)
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.
| Operator | Meaning | Example | Result |
|---|---|---|---|
| == | equal to | 5 == 5 | True |
| != | not equal to | 5 != 5 | False |
| < | less than | 3 < 7 | True |
| <= | less than or equal to | 120 <= 115 | False |
| > | greater than | 60 > 60 | False |
| >= | greater than or equal to | 60 >= 60 | True |
For more complicated conditions, the Boolean operators and, or and not join simple comparisons together.
andTwo 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.
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 Bis True if at least one of A and B is True. It is False only when both are False.not Aflips the value:not Trueis False andnot Falseis True.- Order: Python works out comparisons first, then
not, thenand, thenor. Use brackets when in doubt:not (age <= 3).
| A | B | A and B | A or B | not A |
|---|---|---|---|---|
| True | True | True | True | False |
| True | False | False | True | False |
| False | True | False | True | True |
| False | False | False | False | True |
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 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 when you don’t know how many times to repeatWrite 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
- 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. - Lines 2–4 set starting values for the variables that keep the sum (
sum), the largest value (max) and the number of values (n). - Line 5 is the
whilestatement. Its condition is thatxmust be a positive number. - Lines 6–10 are the block inside the loop: line 6 counts the values in
n, line 7 adds tosum, lines 8–9 keep the largest value so far, and line 10 reads the next value. - 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.
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.
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.
if-elif-else for more than 2 choicesWrite 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
- Line 1 stores the fare 6.50 in
fare. - Line 2 reads the age into
age. - Line 3 checks the condition: if the age is 60 or over, the fare is halved and stored in
fare, so it becomesfare/2baht. - Line 5 is the case of someone under 60 who is no more than 3 years old.
elifcreates this choice. - Line 7 covers every other case: an ordinary passenger.
if-elif-elsekeeps the program short and easy to check.
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.
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
- Line 3 reads a letter from the user into
shape, to say which shape’s area is wanted. - 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.
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.
| Score | Result |
|---|---|
| 0 up to (not including) 50, and no work outstanding | Fail (ไม่ผ่าน) |
| 50 up to (not including) 70, and no work outstanding | Pass (ผ่าน) |
| 70 up to (not including) 90, and no work outstanding | Good (ดี) |
| 90 to 100, and no work outstanding | Excellent (เยี่ยม) |
| Work outstanding | ร |
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.
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)callsprint()with the string'area ='and the value of the variablearea.print()shows them on screen from left to right.int('20')callsint()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.
Watch line 1 being worked out, innermost function first. Type an age, then press Next.
Example 2.7 explained
- Line 1 calls
int()andinput(), one inside the other. When functions are nested, Python works out the innermost one first. Soinput()is called first: Python passes it the string"Your age: ", andinput()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 types20, thenint(input("Your age: "))becomesint('20'). - Next Python works out
int('20'): it sends'20'toint(), which converts the string to the integer 20 and returns it. Soage=int(input("Your age: "))becomesage=int('20'), which isage=20. - Line 8 calls
print()with 2 values, the string"Your fare is"and the variablefare, andprint()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.
hello1()Type this into a cell:
Result:
Example 2.8 explained
- Line 1 creates a new function. The Python keyword
defstarts the definition. The function is namedhello1and has 1 parameter, the variablename, 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 throughname. - Line 2 is the function’s block. It has only one statement,
print('Hello', name), which prints Hello followed by the value ofname. - Line 4 calls
hello1()with the single string argument'Prawit'. The statements ofhello1()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.
In the program of Example 2.5, which lines are the blocks under if, elif and else?
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.
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.
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 explained
- Line 1 loads the
turtlemodule, so you can call its drawing functions. - Lines 3–8 create a function that draws a square, with 1 parameter,
size, for the length of a side. - Lines 10–15 create a function that draws an equilateral triangle, with 1 parameter,
size, for the length of a side. - Lines 17–22 create a function that draws a house, by calling the square function and the triangle function.
- 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.
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.
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
- Line 3 starts defining
sphere_volume(), with 1 parameter, the sphere’s radius, stored inr. - 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. - From line 7 on is the main program, which calls
sphere_volume(). Line 7 reads the radius typed by the user intoradius. - Line 8 calls
sphere_volume()withradiusas its argument. Whensphere_volume()finishes and returns a value, the string'Volume is'and the returned value are passed as arguments toprint().
📝 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:
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.
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.
💻 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.
- 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.
📝 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:
| Item | Price per unit (baht) | Share per unit (baht) | Extra share |
|---|---|---|---|
| Cake | 10 | 2 | More than 20 pieces: share goes up to 3 baht a piece |
| Chicken sticky rice | 20 | 5 | More than 30 packs: share goes up to 7 baht a pack |
| Orange juice | 15 | 3 | More 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.
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?
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.
| Name | Sex (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.
15 boxes of basil-chicken rice use:
| Ingredient | Price |
|---|---|
| Jasmine rice 2 kg | 38 baht/kg |
| Chicken 1 kg | 70 baht/kg |
| Holy basil 200 g | 20 baht/kg |
| Chillies 200 g | 45 baht/kg |
| Garlic 20 g | 80 baht/kg |
| Eggs 15 | 3.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.