Pattara Python 01204111
Pattara Python 01204111
Outline:
1.1 Introduction to computer programming.
1.2 A quick look at the Python programming language and common constructs
1.3 Exercise
Machine instruction is a machine language that only a computer can understand because it is written in
binary numbers including 0 and 1. Assembly language is a low-level programming language that is used in the
past and still quite difficult to understand by general people. It is designed for a specific type of processor,
and its code can be converted to a machine language by using an assembler. The computer program that
To understand how computer works, let’s try to make an analogy with how people solve a problem.
Problem: It’s the first day of school. You want to go to school from your home. What do you have to do?
Assume that your home is close to the school enough to walk to.
Solution: If you know the way to the school, you can just walk. But if you don’t, you may need to look at
the map and use it to plan your route to the school. Note that if you can plan your walking route with a
map, you can solve this kind of problems not just for going from your home to the school, but from any
place to any other place.
In a way, you are a “computer”. If you want to know the route from your home to the school, you need the
location of your home, the location of the school, and the map as “inputs”. Then you figure out the route
from your home to the school as an “output”.
Inputs
Location of
your home
Output
Location of
school
Route from
home to school
A computer that
Map solves the route-
finding problem
Central
Processing
Unit
Input
(CPU)
&
Output
Memory
• Central Processing Unit (CPU): Performs calculation and makes a decision based on instructions and
data in the memory
• Input and output: Provide means (method) for the CPU to interact with the outside world through
various devices
• Memory: Stores data and instructions
Memory
0 1
Two bits
0 1 0 1 1 1 0 0
One byte
• 1 kB = 1,000 bytes
• 1 MB = 1,000,000 bytes
• 1 GB = 1,000,000,000 bytes
Memory
0001 1001
1001 1110
1000 1011
1100 1011
1110 0010
1001 0111
1100 1011
1110 0010
1001 0111
1100 1011
These instructions are in the format that the CPU can easily understand, referred to as “machine
instructions”. When writing a program, we rarely write in machine instructions. Instead of working directly with
machine instructions, people usually develop software with higher-level programming languages. But the
program must be translated into a form that the computer can understand. This process is called “program
translation”.
0001 1001
1001 1110
1000 1011
1100 1011
sum = 0 1110 0010
for i in range(1,101): 1001 0111
sum = sum + i 1100 1011
1110 0010
1001 0111
1100 1011
A program in Translation
high-level Machine
language instructions
We will focus more on learning how to program and how to write good codes, skills that can be applied with
any popular computer programming languages.
print("Hello, Python")
The output:
Hello, Python
a = int(input())
b = int(input())
result = a + b
print(f"{a} + {b} = {result}")
The output:
11
27
11 + 27 = 38
If this is the first time you see computer programs, you may feel that these lines of code may look fairly
difficult. But as you continue to see and write more programs, it will be much easier to understand.
import math
r = float(input())
print(math.pi*r*r)
The output:
10
314.15926538979
The above program reads a number and outputs pi times that number squared. Actually, the goal of this
program is to compute the area of the circle with radius r. Thus, we can write a better program as follows
which performs the same task but easier to understand because it states its intention fairly clearly.
import math
return length*width
Main program
# ask user to input length and width of a rectangle
area = rectangle_area(length,width)
print(f"Rectangle area is {area}")
First of all, each line of code is executed one by one from top to bottom. Apart from the “main program”
which is the main part every program must have, there may be “function definition”, “docstrings” and
“comments”.
Function Definition
A function is a group of organized, reusable code that is used to perform a single, related action. Functions
provide better modularity and a high degree of code reusing. You can define your own functions to provide
the required functionality. We may call “function”, a subroutine which has exactly the same meaning.
import math
def rectangle_area(length,width):
return length*width
RUN
EDIT TEST
Debugging
When programmers try to fix mistakes in their codes, they usually refer to the activity as “debugging” (killing
the bugs). In the early days of computing, there was actually a bug in the machine. Therefore, problems with
computers are often referred to as bugs.
turtle.forward(100)
turtle.left(90)
turtle.forward(100)
turtle.left(90)
turtle.forward(100)
turtle.left(90)
turtle.forward(100)
turtle.left(90)
turtle.forward(100)
turtle.left(90)
turtle.forward(100)
turtle.left(90)
turtle.forward(100)
turtle.left(90)
turtle.forward(100)
turtle.left(90)
turtle.left(45)
turtle.forward(100)
turtle.left(90)
turtle.forward(100)
turtle.left(90)
turtle.forward(100)
turtle.left(90)
import turtle
def draw_square():
turtle.forward(100)
turtle.left(90)
turtle.forward(100)
turtle.left(90) Define a subroutine "draw_square"
turtle.forward(100)
turtle.left(90)
turtle.forward(100)
turtle.left(90)
draw_square()
turtle.left(45) Call the subroutine "draw_square"
draw_square()
Please note that the above program gives the same output as the previous program which has lengthy code.
import turtle
for _ in range(4):
turtle.forward(size)
turtle.left(90)
draw_square(100)
turtle.left(45)
draw_square(-50) This call gives no result
turtle.left(90)
draw_square(80)
Thus, the turtle draws only two squares with having the size of 100 and 80 as follows.
1.3 Exercise
2) From the sentences below, answer True or False into the blanks.
___(A)___ The smallest unit of information that can be processed by digital is a single binary (a
bit).
___(B)___ The computer memory only keeps the data to be processed with CPU.
___(C)___ People rarely write a program in machine language instructions.
4) Write the program that orders turtle to draw a movement path like a house as follows.
Note:
- The width and height of each grid square side are 100.
- The turtle can repeat the same path.
- Each side of the triangle on the roof of the house is 70.
Outline:
2.1 Simple Sequential programs
2.2 Operator Precedence
2.3 Variable
2.4 Values and Types
2.5 Input Statement
2.6 Output Formatting
2.7 Exercise
Salad 82
Soup 64
Steak 90
Wine 75
Orange Juice 33
Ideas and Steps - We simply want to know the summation of all the five numbers. Somehow, we need to
tell the order to the computer to show the result of all these numbers added up.
The above line is equivalent to giving a command, “Hey! Please print the value of the expression
82+64+90+75+33.”
After this part gets evaluated by the computer, it is evaluated to a numerical value of 344.
Another example, the following part;
10+(2*A)
After this part gets evaluated by the computer, it is evaluated to a value of 20, in the case that variable A is 5.
Ideas: Start with the same summation expression. Then, with a 20% discount, the final cost will be 80% of
the original. Therefore, we just multiply the original expression by 0.8. Please note that, in most programming
languages, star symbol (*) means multiply
print('Total cost is ')
print(82+64+90+75+33 * 0.8)
Operators Precedence
( ) Highest
** :
* / // % :
+ - Lowest
Expression Equivalent to
2*3+4*5 (2*3)+(4*5)
1+2+3+4 ((1+2)+3)+4
(2+3)/5*4 ((2+3)/5)*4
3-2-5-(7+6) ((3-2)-5)-(7+6)
10+9%2+30 (10+(9%2))+30
10/2*5%3 ((10/2)*5)%3
Item Price
Salad 82
Soup 64
Steak 90
Wine 75
Orange Juice 33
Ideas:
• Just compute the total and divide it by 5
• The result should be the amount each person has to pay
print('Total amount: ')
print( 82+64+90+75+33 )
print('Each has to pay: ')
print( (82+64+90+75+33) / 5.0 )
total = 82+64+90+75+33
print('Total amount: ')
print(total)
print('Each has to pay: ')
print(total/5)
• Any values such as 85, 23+8, "Hello" are objects that get stored inside a computer's memory.
• A variable is like a name tag given to such an object
Reassigning Variables
Binding can be changed with a new assignment statement. Previous objects may still reside in memory, but
will be removed later on like this example.
>>> my_int = 82
>>> my_int = 64
>>> my_int
64
You don’t have to memorize this list. In most development environments, keywords will be displayed in a
different color right after you type them into the code.
>>> x = 5
>>> x = 20
>>> x
20
>>> y = x*2
>>> x = 8
>>> x = x+1
>>> x
9
>>> y
40
Sometimes you need to store something other than an integer in a variable. Python provides several data
types (or classes) for different purposes. Some important types are listed here
Type Value Usage Example
first = 'A'
string a sequence of zero or more character(s) name = 'John'
What is the most appropriate variable data type to store each of the following items?
1. The number of students in a class ==> int
2. The height of a person in meters ==> float
The reason is the second appearance of the quote (') indicates the end of the string 'He said,'
or
print('He said, "Goodbye."')
Examples:
>>> s1 = "String with ' inside"
>>> s2 = 'String with " inside'
>>> s3 = """String with both ' and " inside"""
>>> s4 = '''Another string with both ' and " inside'''
>>> s5 = """This form also supports multiple lines.
Like this."""
>>> print(s1)
String with ' inside
>>> print(s2)
String with " inside
>>> print(s3)
String with both ' and " inside
>>> print(s4)
Another string with both ' and " inside
>>> print(s5)
This form also supports multiple lines.
Like this.
>>>
Similar to a long division taught in primary school. Also, the fraction part is discarded.
• / is floating point division.
• % is division remainder.
Examples:
10/4 = 2.5
10//4 = 2 (not 2.5)
10//5 = 2 (not 2.0)
10/5 = 2.0
10%3 =1
10.0%3 = 1.0
This is equivalent to giving a command 'Hey! Please ask input from the user and refer to it with the variable
celsius'. This will wait for the user to enter a value from the keyboard.
- Print a string, then immediately prompt the user to enter a value (the cursor will be on the same line
after the string)
variable_name = input(string)
- For example, suppose we run input() and the user enters 25.
>>> celcius = input('Enter temp: ')
Enter temp: 25
it’s a string, NOT a number. So, it cannot be added to a number. Therefore, we must convert a string
to a number before using + operator. Besides, to use + operator, data must have the same type.
Let’s break it down. Suppose that the user enters 42.1 via keyboard. The Type of celsius_str is string. After
that, the data is converted to float by float(celsius_str) function and assigned to the variable name
celsius.
Output:
The circle's area is 211.24.
Note: Please use :.2f to specify that you want to display the float number with 2 decimal places.
However, very complex expressions should be avoided. Keep in mind that readability counts, so it’s better to
re-write the above codes as follows.
import math
radius = 8.2
area = radius*radius*math.pi
print(f"The circle's area is {area:.2f}.")
An expression inside {} may be followed by a formatting specification that controls the length, precision
(decimal places), and alignment of the expression's displayed value. The following program prints the value
of 200/3 with different numbers of decimal places and alignments.
x = 200/3
print(f"Value of x is [{x}]") # default formatting
print(f"Value of x is [{x:<10.3f}]") # left-aligned, 10-letter wide, 3 decimal places
print(f"Value of x is [{x:^10.3f}]") # center-aligned, 10-letter wide, 3 decimal places
print(f"Value of x is [{x:>10.3f}]") # right-aligned, 10-letter wide, 3 decimal places
print(f"Value of x is [{x:>10.6f}]") # right-aligned, 10-letter wide, 6 decimal places
print(f"Value of x is [{x:>5.1f}]") # right-aligned, 5-letter wide, 1 decimal place
Output:
Value of x is [66.66666666666667]
Value of x is [66.667 ]
Value of x is [ 66.667 ]
Value of x is [ 66.667]
Value of x is [ 66.666667]
Value of x is [ 66.7]
1) Complete the following variable assignment in the blank (A) so that it gives the output as shown.
>>> text1 = ____(A)______
>>> print(text1)
"print" is a function.
2) Complete the following variable assignment in the blank (A) so that it gives the output as shown.
>>> text2 = ____(A)______
>>> print(text2)
"That's good," he said.
3) Compute the number of whole minutes and remaining seconds from the specified total number of
seconds defined in the variable total_seconds by entering expressions with appropriate division
operators in the blanks (A) and (B). (Your expression MUST work with any value of total_seconds.)
>>> total_seconds = 381
>>> minutes = _____(A)_____
>>> seconds = _____(B)_____
>>> print(minutes)
6
>>> print(seconds)
21
4) Write a program that takes the number of seconds passed and displays the same amount of time in
hours, minutes, and seconds.
Output Example 1:
How many seconds? 378
That equals 0 hour(s) 6 minute(s) and 18 second(s).
Output Example 2:
How many seconds? 8000
That equals 2 hour(s) 13 minute(s) and 20 second(s).
Hint: Use the operators // (integer division) and % (remainder after division).
A subroutine is a sequence of one or more actions grouped into a single task. The task won't be performed
until the subroutine itself is used. E.g.
• The smart television which has the function to watch YouTube, will not show any YouTube video
clip until you click or push the “YouTube” button on the remote control.
Subroutines are also known by other names like subroutines, functions, method, or procedures.
print(82+64+90+75+33)
print('Hello')
val = input()
These are parts of the Python’s built-in functions, they are readily available to use. Functions are always
followed by parentheses. Within parentheses, It may contain argument(s) of the function. Note that, a
function may have no argument or 1 or more argument. From the above Python program, 82+64+90+75+33
and 'Hello' are arguments of print function, but input function (input()) does not have any argument.
No need to remember all of these now. We will eventually learn how to use them later. For each function,
you need to learn how to use it, i.e. what argument(s) to send.
3.2.2 Function
Function usually has input(s) and/or output(s). For example, in math, suppose you have a math function
(not Python) f(x) defined as follows;
f(x) = 2x + 1.
This means x is an input to the function f(x), and the function produces a result (output) of the expression 2x
+ 1.
Ideas: At first, the problem looks like a typical division problem. However, the fraction of the result must not
be discarded this time but will be rounded up to the nearest integer. E.g., 3 is rounded up to 3, while 3.1 is
rounded up to 4. From the problem, let x represent the call length in minutes. This mean, we want to know
the smallest integer that is larger or equal to x. Mathematically, we are computing the ceiling of x.
⌈𝑥𝑥⌉
END
Program:
1: import math
2: minutes_str = input('Enter call length in minutes: ')
3: minutes = float(minutes_str)
4: rounded_minutes = math.ceil(minutes)
5: charge = 2*rounded_minutes
6: print(f'Charge is {charge:.2f} Baht.')
import math imports the math module that contains additional mathematical functions. Line 3, the
expression math.ceil(minutes) is evaluated to ⌈𝑚𝑚𝑚𝑚𝑚𝑚𝑚𝑚𝑚𝑚𝑚𝑚𝑚𝑚⌉ .
Examples:
>>> import math
>>> math.fabs(-12.34)
12.34
>>> math.ceil(3.29)
4
>>> math.floor(3.29)
3
>>> math.cos(math.pi/4)
0.7071067811865476
>>> math.pow(5,3)
125.0
>>> math.sqrt(2)
1.4142135623730951
>>> math.exp(1)
2.718281828459045
>>> math.log(4)
1.3862943611198906
>>> math.log10(100)
2.0
>>> math.log(8,2)
3.0
>>> math.pi
3.141592653589793
>>> math.e
2.718281828459045
• Importing only specified names inside a module. These imported names can be used directly.
from math import cos, pi
value = cos(pi/2)
Ideas:
We need to analyze the relationship among all the variables to solve the two unknowns.
From Pythagorean theorem (x,y)
𝑑𝑑𝑑𝑑𝑑𝑑𝑑𝑑𝑑𝑑𝑑𝑑𝑑𝑑𝑒𝑒 2 = 𝑥𝑥 2 + 𝑦𝑦 2
𝑦𝑦
𝑡𝑡𝑡𝑡𝑡𝑡 𝜃𝜃 =
𝑥𝑥
θ
Therefore,
(0,0) x
𝑦𝑦
𝑑𝑑𝑑𝑑𝑑𝑑𝑑𝑑𝑑𝑑𝑑𝑑𝑑𝑑𝑑𝑑 = �𝑥𝑥 2 + 𝑦𝑦 2 and 𝜃𝜃 = arctan
𝑥𝑥
>>> math.degrees(math.asin(1))
90.0
3.3 Composition
Some functions return a value, which can be used as part of an expression. Also is an argument of another
function.
As part of an expression of the following program:
rounded_minutes = math.ceil(minutes)
charge = 2*rounded_minutes
From the above program, the variable rounded_minutes contains the rounded-up value of minutes. After
that, it is multiplied by 2. Therefore, we can revise/shorten the above program as follows:
charge = 2*math.ceil(minutes)
Function that has a value can also be part of an argument of another function:
minutes_str = input('Enter call length in minutes: ')
minutes = float(minutes_str)
From now on, we will write the input statement this way when reading a number.
0 𝑝𝑝
𝑟𝑟
1 𝑝𝑝 �1 +
100
�
𝑟𝑟 𝑟𝑟 𝑟𝑟 2
2 𝑝𝑝 �1 + � �1 + � = 𝑝𝑝 �1 + �
100 100 100
𝑟𝑟 2 𝑟𝑟 𝑟𝑟 3
3 𝑝𝑝 �1 + � �1 + � = 𝑝𝑝 �1 + �
100 100 100
: :
𝑟𝑟 𝑛𝑛
It follows that on nth year, the amount will be 𝑝𝑝 �1 + 100�
Steps:
BEGIN
𝑦𝑦𝑦𝑦𝑦𝑦𝑦𝑦𝑦𝑦
Compute amount = 𝑝𝑝𝑝𝑝𝑝𝑝𝑝𝑝𝑝𝑝𝑝𝑝𝑝𝑝𝑝𝑝𝑝𝑝 �1 + 𝑟𝑟𝑟𝑟𝑟𝑟𝑟𝑟
100
�
END
Program:
import math
principal = float(input('Principal (Baht): '))
rate = float(input('Rate (% per year): '))
years = int(input('Time (years): '))
amount = principal * math.pow(1 + rate/100, years)
print(f'Amount: {amount:.2f}')
Note: expression math.pow(1 + rate/100, years) has the same meaning as (1 + rate/100)**years
• def (in line 1) is the Python keyword that means, I am defining a function.
• The name of your defined function (e.g. my_hello in line 1) follows the naming rules.
• You can define parameters (e.g. parameter_name in line 1) of your defined function as many as
you need.
• The statement my_hello('Jon Snow') (in line 3) calls your defined function.
• Note that, functions must be defined before use.
Program 1:
1: radius = float(input('Enter a radius: '))
2: area = math.pi*radius**2
3: print('Area of a circle with radius
{radius} is {area:.2f}')
Start
Enter a radius:
radius = …
2
area = π × radius
Print result
End
Program 1 is the program that computes the circle’s area without any defining functions. The flowchart of the
program is shown above.
Program 2 is the program that has the original new defining function compute_circle_area() without
parameter (shown in line 1 to line 4). Then, in line 4, the statement compute_circle_area() calls the
defined function. The flowchart of the program is shown as follows.
Enter a radius:
Start
radius = …
Call the function compute_circle_area
2
area = π × radius
End
Print result
Examples:
def compute_circle_area(...):
...
...
statements
...
def compute_circle_area() :
radius = float(input('Enter a radius: '))
1 3 area = math.pi*radius**2
print(f'Area of a circle with radius {radius} is {area:.2f}')
2 compute_circle_area()
In the above statement, the argument '35' (type String) is sent to a built-in function float(). After that,
function float() returns a float value that equal to 35.0. Finally, 35.0 is stored in a variable celsius. In
other words, the term float('35') is equal to 35.0. You can write your own function that returns a value by
using return keyword.
Program 3:
1: def compute_circle_area(radius):
2: circle_area = math.pi*radius**2
3: return circle_area
4:
5: r = float(input('Enter a radius: '))
6: area = compute_circle_area(r)
7: print(f'Area of a circle with radius {r} is {area:.2f}')
In program 3, a value in circle_area (in line 3) is returned to the main program and then stored in the
variable area (in line 6). The flowchart of the program is shown as follows.
2
Call the function compute_circle_area area = π × radius
Print result
End
Program 4:
1: def compute_circle_area(radius):
2: return math.pi*radius**2
3:
4: r = float(input('Enter a radius: '))
5: area = compute_circle_area(r)
6: print(f'Area of a circle with radius {r} is {area:.2f}')
In program 4, you will see a little change in the content of function compute_circle_area(radius). The
statement circle_area = math.pi*radius**2 in program 3 is disappear. This means the result of expression
math.pi*radius**2 (in line 2) is returned to the main program and then stored in the variable area (in line
5).
def compute_circle_area(radius):
... parameter
}
argument
The built-in help() function can be used in the shell to provide more details about any object as shown in
the following pictures:
def compute_circle_area(radius):
"""
Compute and return the area of a circle docstring
with the specified radius
"""
return math.pi*radius**2
2) Complete the following program in the blank (A) so that it computes the value of �𝑥𝑥 2 + 𝑦𝑦 2 +𝑧𝑧 2 and
stores the result in the variable distance, then prints it out. The variables x, y, and z are already
defined.
import math
x,y,z = 8,4,3
_____(A)______
print(distance)
Output Example 1:
Enter circle radius: 10
The circumference of the circle is 62.83
The area of this circle is 314.16
Output Example 2:
Enter circle radius: 38.1
The circumference of the circle is 239.39
The area of this circle is 4560.37
Hints
1. The circumference of a circle of radius r is 2𝜋𝜋𝜋𝜋.
2. The area of a circle of radius r is 𝜋𝜋𝑟𝑟 2 .
Outline:
4.1 Local and global variables
4.2 Multiple returned values
4.3 Calling functions with positional and named arguments
4.4 Exercises
Let’ try to add the statement print(circle_area) to the above program (into line 11 in the following
program).
1: import math
2:
3: def compute_circle_area(radius):
4: circle_area = math.pi*radius**2
5: return circle_area
6:
7: r = float(input("Enter a radius: "))
8: area = compute_circle_area(r)
9: print(f"Area of the circle is {area:.2f}")
10:
11: print(circle_area)
1: def function1():
2: x = 300
3: print(f"Inside function1(): x = {x}")
4:
5: x = 50
6: function1()
7: print(f"Outside function1(): x = {x}")
These two x's are different variables. x in function1() can only be used inside its function and has a value of
300. Thus, the output of the above program shown as follows.
Note that, a variable that is referenced, but not defined inside a function is considered a global variable
(variable x in line 2 in the following program). However, these variables are read-only by default.
Reason: after function1() is called at line 5, variable x in line 2 is then referenced, but at this moment x is
not defined inside function1() yet. Thus, x is considered a global variable which has a value of 50 (which
has already been assigned at line 4). Therefore, a statement “print(f"Inside function1(): x = {x}") in
line 2, then outputs “Inside function1(): x = 50”.
Ideas:
A flat washer resembles a small donut (see the figure). To compute the weight of a single flat washer, you
need to know its rim area, thickness, and density of the material. Here, we can reuse compute_circle_area()
function.
Requirements:
- The radius of the flat washer (outer radius) and
the radius of the hole (inner raduis)
- Thickness
- Density
- Quantity
We will assume that the material used is aluminum, whose density is well-known.
Steps:
1. Get the flat washer’s outer radius, inner radius, thickness, and quantity.
2. Compute the weight of one flat washer
unit_weight = rim_area × thickness × density
Print result
End
Program:
1: import math
2:
3: MATERIAL_DENSITY = 2.70
4:
5: def compute_circle_area(radius):
6: return math.pi*radius**2;
7:
8: def flat_washer_weight(outer_r,inner_r,thickness):
9: rim_area=compute_circle_area(outer_r)-compute_circle_area(inner_r)
10: return rim_area*thickness*MATERIAL_DENSITY
11:
12: outer_radius = float(input('Enter the outer radius (cm.): '))
13: inner_radius = float(input('Enter inner radius (cm.): '))
14: thickness = float(input('Enter thickness (cm.): '))
15: quantity = int(input('Enter the quantity (pieces): '))
16: unit_weight = flat_washer_weight(outer_radius,inner_radius,thickness)
17: total_weight = unit_weight * quantity
18: print(f'Weight of the batch is {total_weight:.2f} grams')
Note: The variable MATERIAL_DENSITY (in line 3) is defined and used as a global variable.
Output Example:
Ideas:
Need to know the three integer values, i.e. val1, val2, val3
Compute the average.
average = (val1 + val2 + val3)/3
Steps:
1. Get input three input integer values from the user.
2. Calculate the average.
average = (val1 + val2 + val3)/3
Print result
End
Output Example:
def Read3Integers():
...
return x, y, z
send to
Program #2:
1: def read_3integers():
2: # read three integers
3: a1 = int(input("1st value: "))
4: a2 = int(input("2nd value: "))
5: a3 = int(input("3rd value: "))
6: return a1, a2, a3
7:
8: def average3(x, y, z):
9: return (x+y+z)/3
10:
11: val1, val2, val3 = read_3integers()
12: # compute and output their average
13: print(f"average is {average3(val1, val2, val3):.4f}")
Task: Trapezoid
In Euclidean geometry, a convex quadrilateral with at least one pair of parallel sides is referred to as a
trapezoid. (ref: https://en.wikipedia.org/wiki/Trapezoid)
a
h a+b
𝑎𝑎𝑎𝑎𝑎𝑎𝑎𝑎 = ℎ
2
b
Steps:
1. Get three double values from the user:
- (parallel) side1
- (parallel) side2
- height
2. Calculate the trapezoid area.
area = ((side1 + side2)/2) × height
3. Finally, Print the resulting area.
Start
Print result
End
Output Example:
Heron's formula states that the area of a triangle whose sides have lengths a, b, and c is
Program:
1: import math
2:
3: def line_length(x1, y1, x2, y2):
4: """
5: Given X-Y coordinates of 2 points, compute the line length that
6: joins them
7: """
8: return math.sqrt((x1-x2)**2+(y1-y2)**2);
9:
10: def triangle_area(x1, y1, x2, y2, x3, y3):
11: """
12: Given the 3 vertices, compute triangle area using Heron's Formula
13: """
14: a = line_length(x1, y1, x2, y2)
15: b = line_length(x2, y2, x3, y3)
16: c = line_length(x3, y3, x1, y1)
17: s = (a+b+c)/2
18: return math.sqrt(s*(s-a)*(s-b)*(s-c))
19:
20: def read_coordinates():
21: x = float(input("x? "))
22: y = float(input("y? "))
23: return x,y
24:
25: def read_triangle():
26: """
27: Read X-Y co-ordinates of 3 vertices of a triangle
28: """
29: print("Enter X-Y coordinates of the three vertices of triangle:")
30: print("1st vertex:")
31: x1,y1 = read_coordinates()
32: print("2nd vertex:")
33: x2,y2 = read_coordinates()
34: print("3rd vertex:")
35: x3,y3 = read_coordinates()
36: return x1,y1,x2,y2,x3,y3
37:
38: # main program
39: x1,y1,x2,y2,x3,y3 = read_triangle()
40: area = triangle_area(x1,y1,x2,y2,x3,y3)
41: print(f"area of the triangle is {area:.2f}")
by using Heron’s formula. In this function, function line_length() (from line 3 to line 8) is called to
compute line length between each two x-y coordinates, then by using those line length, the triangle area is
calculated and returned back to the variable area. Finally, the result is output on the screen.
Output Example:
So far, when we call a function, arguments are arranged in the order according to the parameters called
“positional arguments”
def trapezoid_area(a, b, h):
return 0.5*(a+b)*h;
4.4 Exercises
1) Complete the following program by filing code in the blank (A), so that it can correctly compute the
amount of Thai Baht corresponding to the given USD amount based on the current exchange rate in
the global variable EXCHANGE_RATE.
def usd_to_thb(usd):
_______(A)________
EXCHANGE_RATE = 34.09
print(f"The current exchange rate is {EXCHANGE_RATE} THB per USD")
print(f"You get {usd_to_thb(100):.2f} Thai Baht for 100 USD")
EXCHANGE_RATE = 33.15
print(f"The current exchange rate is {EXCHANGE_RATE} THB per USD")
print(f"You get {usd_to_thb(100):.2f} Thai Baht for 100 USD")
EXCHANGE_RATE = 35.26
print(f"The current exchange rate is {EXCHANGE_RATE} THB per USD")
print(f"You get {usd_to_thb(100):.2f} Thai Baht for 100 USD")
Output:
The current exchange rate is 34.09 THB per USD
You get 3409.00 Thai Baht for 100 USD
The current exchange rate is 33.15 THB per USD
You get 3315.00 Thai Baht for 100 USD
The current exchange rate is 35.26 THB per USD
You get 3526.00 Thai Baht for 100 USD
def read_rectangle():
length = float(input("Enter rectangle length: "))
width = float(input("Enter rectangle width: "))
return length,width
side1,side2 = read_rectangle()
area,peri = rectangle_area_and_perimeter(side1,side2)
print(f"The area of the rectangle is {area:.2f}")
print(f"The perimeter of the rectangle is {peri:.2f}")
Then, the function to calculate BMI can be defined as follows, where weight is in kilograms,
and height is in meters.
def bmi(weight,height):
return weight/(height**2)
Call the function bmi() by filling blank (A), using named arguments with 63 kg for weight and 1.71
meters for height.
>>> bmi(____(A)______)
21.545090797168363
Outline:
5.1 Boolean Expressions
5.2 Operator Precedence in Python
5.3 Fundamental Flow Controls
5.4 Flowcharts
5.5 Basic Selections
5.6 Programming Examples
5.7 Exercises
True and False are values. So, these values can be assigned to variable as follows:
>>> x = True
>>> y = False
>>> print(x)
True
>>> print(y)
False
Also, you can check their types as the following output examples:
>>> type(True)
<class 'bool'>
>>> type(False)
<class 'bool'>
>>> type(x)
<class 'bool'>
Importance: Python is case-sensitive, so False and false are not the same. Python’s bool constants are
written precisely as:
• True
• False
Meaning Operator
Equal ==
Not equal !=
Logical operators: they are used to combine two or more Boolean expressions:
Meaning Operator
Boolean AND and
Boolean OR or
p q p and q p or q
True True True True
True False False True
False True False True
False False False False
p not p
True False
False True
Subroutine Selection
5.4 Flowcharts
Terminator
Process
Input/output
Condition
Connector
Flow line
START
nOdd, nEven = 0, 0
True
End of input ? write nOdd, nEven
False
read k END
True False
k%2 == 0
Figure out what kind of task this flowchart trying to do. Then try to run this flowchart with the input
sequence: 5, 1, 4, 9, 8
x = int(input())
y = int(input())
print(x+y)
print("Hello",x)
z = x * y + 10
print(z)
False
1: price = 40
2: if height <= 140:
3: print('Hello kids!')
4: price = 0
5: print('price =', price)
From the above program, when height is 160, the result of the condition height <= 140 is False. Then, after
line 1 is executed, the program executes like the orange line which skips line 3 and line 4, and executes line
5. On the other hand, when height is 120, the result of the condition height <= 140 is True. Then, the
program executes like the green line which executes all lines in the program.
If Statement:
if statement is used to decide whether a code block is to be executed or not, depending on a condition.
The statements in the code block will be executed only if the condition is True.
if condition:
True
statement1 statement
statement2 1
...
...
statementn
a code block statement
2
statement
n
price = 40
Code Blocks:
In Python, a line that ends with : (colon) indicates that the next line starts a new “code block”. A code
block consists of one or more statements that are indented equally deeply from the left. In the example
below, the first code block which has 3 statements is written inside the dotted line square and its indentation
level shown by the dotted line arrow. Then, the second code block which has 2 statements is written inside
the solid line square and its indentation level shown by the solid line arrow.
def mrt_fee(height) :
price = 40
print('Hello kids!')
price = 0
Be careful, Python uses the concept of blocks extensively. Thus, you must be very careful about indentation.
fddslfldskf fddslfldskf
fdsfkdsfdsfd fdsfkdsfdsfd
fdkfddfdfd fdkfddfdfd
fdkfdlf fdkfdlf
fdkfddfdfd fdsfkdsfdsfd
fdkfdlf fdkfddfdf
Pass-statement:
In Python, we cannot have an empty block.
If you want a block that does nothing, use the pass statement.
If-else statement:
If-else statement is used to decide whether a code block is to be executed or not, depending on a
condition. In the following phyton syntax code and flowchart semantics, the statements in the code block1
will be executed only if the condition is True, and the statements in the code block2 will be executed only if
the condition is False.
Program Pattern 1:
max = a max = b
def max_of_two(a, b):
if a > b:
max = a
else:
max = b
return max
return max
Output example ( pattern 1 and pattern 2 of the program have the same output):
>>> print(max_of_two(3,2))
3
>>> max_of_two(3, 2)
3
>>> max_of_two(2, 3)
3
>>> x = 5
>>> max_of_two(3*x, x**2)
25
Output Example:
>>> payment(10, 3)
You got 5% discount.
Total payment is 28.5 baht.
>>> payment(itemprice=5, nitems=20)
You got 10% discount.
You also got 6 stamps.
Total payment is 90.0 baht.
>>>
Ideas: The roots of a quadratic equation ax2 + bx + c = 0 can be calculated by the formula:
The term b2 − 4ac in the formula is called the discriminant (D) of the equation because it can discriminate
between the possible types of roots. The discriminant D = b2 − 4ac of the equation determines the type of
roots as follows:
−𝑏𝑏+ √𝐷𝐷 −𝑏𝑏 − √𝐷𝐷
• If D > 0, there are two real roots: 2𝑎𝑎
and 2𝑎𝑎
−𝑏𝑏
• If D = 0, there is only one real root: 2𝑎𝑎
−𝑏𝑏 −𝑏𝑏
• If D < 0, there are two complex roots: 2𝑎𝑎 + 𝑖𝑖 √−𝐷𝐷
2𝑎𝑎
and 2𝑎𝑎 − 𝑖𝑖 √−𝐷𝐷
2𝑎𝑎
Now we've got enough information to write the program. Next, we are going to demonstrate a useful,
effective development technique called Incremental Development together with Incremental test.
The main routine has been tested and it works correctly. Next, we are going to create function
read_coefficients() and solve_and_output() to complete the program.
Insert the newly created function compute_real_roots() into the previous program, then execute a test run
again.
1: import sys
2: from math import sqrt
3:
4: def read_coefficients():
5: a = float(input('Enter 1st coefficient: '))
6: b = float(input('Enter 2nd coefficient: '))
7: c = float(input('Enter 3rd coefficient: '))
8: return a, b, c
9:
10: def solve_and_output(a, b, c):
11: disc = b*b - 4*a*c
12: if disc >= 0: # has real roots
13: compute_real_roots(a, b, disc)
14: else: # has complex roots
15: compute_complex_roots(a, b, disc)
16:
17: def compute_real_roots(a, b, disc):
18: if disc == 0:
19: root = -b / (2*a)
20: print(f'Only one real root: {root}')
21: else:
22: root1 = (-b + sqrt(disc)) / (2*a)
23: root2 = (-b - sqrt(disc)) / (2*a)
24: print(f'Two real roots: {root1} and {root2}')
25:
26: def compute_complex_roots(a, b, disc):
27: print("In compute_complex_roots:", a, b, disc) # dummy code
28:
29: # ----- main ----- #
30: a, b, c = read_coefficients()
31: if a == 0:
32: print("1st coefficient can't be zero. Program exits.")
33: sys.exit() # exit this running program immediately
34: solve_and_output(a, b, c)
def divisible_by_7(num):
return num%7 == 0
def too_fast(speed):
return speed > 120
What is the result of each following Boolean expression when run in shell mode?
• x%2 != 1
• is_odd
• divisible_by_7(x)
• divisible_by_7(x+12)
• too_fast(80)
• too_fast(180)
2) A mobile phone company gives you a special discount rate of 1 baht/min for any call of 30 minutes
or longer. Otherwise, when the call duration is less than 30 minutes, the normal rate of 2 baht/min is
applied. Complete the function below by filling blank (A) (B) (C) so that it can correctly compute the
charge of a call of the duration which is given in minutes.
def calling_charge(duration):
if _____(A)_____ :
rate = _____(B)_____
else:
rate = _____(C)_____
return duration*rate
Output Example:
>>> calling_charge(5)
10
>>> calling_charge(20)
40
>>> calling_charge(30)
30
>>> calling_charge(40)
40
The store offers a 12% discount to the customer who purchases more than 10000 baht in total.
Write a program that reads the number of each product purchased, then calculates and prints total
payment (with possible 12% discount) in 2 decimal points.
Example Output 1:
How many TVs do you want? 1
How many DVD players do you want? 0
How many audio systems do you want? 1
Your total amount is 4500.00 baht.
Your payment is 4500.00 baht. Thank you.
Example Output 2:
How many TVs do you want? 0
How many DVD players do you want? 2
How many audio systems do you want? 3
Your total amount is 6000.00 baht.
Your payment is 6000.00 baht. Thank you.
Example Output 3:
How many TVs do you want? 2
How many DVD players do you want? 3
How many audio systems do you want? 2
Your total amount is 11250.00 baht.
You got a discount of 1350.00 baht.
Your payment is 9900.00 baht. Thank you.
T F
x > y
m = x m = y
F
z = x-y
z > m
m = 1
r = x+z-m
Each box above is actually a single statement. Thus, each can be put into any statement (statement ~
1
if condition:
statement
1
statement
2
else:
statement
3
statement
4
statement
5
Example in Python
When an if or if-else statement is put within another if or if-else statement, we call it a nested
conditional construct. Note that indentation is very important as shown in the following example.
In the above diagram, you can see that nested conditionals start as just a single statement of if-else. Then,
the other statements are nested(put) into code block1 and code block2. Subsequently, the statements other
if x > 0:
T F
i = 2 x > 0
if y > 1:
F
k = 2 i = 2 Z < 10
else:
if z < 10: T
F
k = 5 y > 1 k = 5
if y > 5:
T
k = x+y
T F
else: k = 2 y > 5
k = x-y
k=x+y k=x-y
From above, the flowchart on the right side shows the execution flow of the program on the left. According
to the flowchart, there are 5 possible paths that the program can execute.
Example Output 1:
Enter 1st number: 25.5
Enter 2nd number: 30
Enter 3rd number: 20.2
The max is 30
Example Output 3:
Enter 1st number: 50
Enter 2nd number: 5
Enter 3rd number: 50
The max is 50
Ideas:
The maximum of 3 numeric values is the value that is not less than the other two. Therefore, to find the
maximum is to look for a value that is not less than the other two. It’s OK if some of them are equal, or even
all of them are equal. Thus, the following is the topmost level in the main routine.
• Reads three numbers.
• Computes the max by calling function max_of_three()
• Prints the max.
Function max_of_three()
Now it’s time to write the function max_of_three(). There are many ways to write it. We’ll show a few
different ways to demonstrate the use of nested conditionals.
Algorithm:
if (a is not less than the other two)
a is the max
else # a is not the max
Compete b with c for the max
Algorithm:
if (a > b) # so a may be the max
Compete a with c for the max
else # so b may be the max
Compete b with c for the max
Algorithm:
• Let max be the value of a
• if (b > max) then
Let max be the value of b
• if (c > max) then
Let max be the value of c
Note that this 3rd version is actually a sequence of two if statements, not a nested if construct. Besides, this
version can be easily extended to 4 or more numbers.
In Python, actually, we have a built-in function max(). Thus, you can use this function, instead of creating
your own program to compute max value.
Example
Try to select a planned activity on Monday, Tuesday, Wednesday, or Thursday by using the following
flowchart.
F Today is T
Saturday Play_Football
F Today is T Go_Swimming
Sunday
Play_Basketbal
Go_Jogging
From the above flowchart, we use 3 conditions (written in the rhombus/diamond shape) to select only one
out of the four sets of planned activity. As you can see from the flow of the execution, when either condition
becomes true, one of the three related actions (Play_Football, Go_Swimming, Play_Basketball) will be
selected. And when all the conditions are false, the fourth action (Go_Jogging) is selected.
F T
cond
1
F T
cond
2
code block
1
F T
cond
3
code block
2
code block code block
4 3
if cond1: if cond1:
code_block1 code_block1
else: elif cond2:
if cond2: code_block2
code_block2 elif cond3:
else: code_block3
if cond3: else:
code_block3 code_block4
else:
code_block4
Firstly, the program on the right-side above works exactly the same as the left one. The difference is else:
followed by if has been replaced to Python keyword elif, and that re-indent has been done. We call the
T
cond code block
1 1
F
T
cond 3 code block
2 2
F
T
cond code block
3 3
code block
4
The flow charts of both implementations of if- elseif -else statement and if- elif -else statement show that
these two Python program construction work exactly the same too.
Output Example:
>>> divfive(50)
50 is divisible by 5
>>> divfive(54)
54 is not divisible by 5
the remainder is 4
>>> divfive(53)
53 is not divisible by 5
the remainder is 3
>>> divfive(52)
52 is not divisible by 5
the remainder is 2
>>> divfive(51)
51 is not divisible by 5
the remainder is 1
Version 1 shows that you can have as many elif-clauses as you need. Besides, note that the last choice is
written in the code block after else:.
Version 2 shows that you can have no else-clause at all if you don't need it.
Version 3 shows that you can have no elif-clauses at all if you don't need them.
Please understand that all these three versions produce exactly the same result.
Idea:
Given the weight (in kilograms) and the height (in meters) of a person, the Body-Mass Index (BMI) of the
person can be computed by the following formula:
weight
BMI =
height × height
Compute BMI
T
BMI < 18.5 wstatus = "underweight"
F
T
BMI < 25.0 wstatus = "normal"
F
T
BMI < 30.0 wstatus = "overweight"
F
wstatus = "obese"
T
BMI >= 30.0 wstatus = "underweight"
F
T
BMI >= 25.0 wstatus = "normal"
F
T
BMI >= 18.5 wstatus = "overweight"
F
wstatus = "obese"
Please compare both algorithm and program of version 1 and version2 to understand what is different.
Note that both versions produce exactly the same result.
After that, test the program thoroughly by inputting values that yield all possible outputs, and also Also try
some inputs that hit all the three boundary cases which are 18.5, 25.0, 30.0.
1) Given the following group() function, put appropriate values in the blanks (A) to (D) to get the output as
shown below.
def group(x):
if x>0:
if x%3 == 0 and x%7 == 0:
print("Group A")
else:
print("Group B")
else:
if x%2 == 0 or x%5 == 0:
print("Group C")
else:
print("Group D")
Example output:
>>> group(_____(A)_____)
Group A
>>> group(_____(B)_____)
Group B
>>> group(_____(C)_____)
Group C
>>> group(_____(D)_____)
Group D
2) The following function returns a grade letter (A,B,C,F) based on a given score.
def letter_grade(score):
if score >= 80:
return "A"
elif score >= 70:
return "B"
elif score >= 60:
return "C"
elif score >= 50:
return "D"
else:
return "F"
Example output:
>>> letter_grade(90)
'A'
>>> letter_grade(75)
'B'
>>> letter_grade(36)
'F'
def letter_grade(score):
if _____(A)_____:
return "F"
elif _____(B)_____:
return "D"
elif _____(C)_____:
return "C"
elif _____(D)_____:
return "B"
else:
return "A"
3) Write a Python program to get input from the user and check whether that input is odd or even
number.
Example output 1:
Enter number: 105
105 more than 100
Example output 2:
Enter number: 91
91 is even
Example output 3:
Enter number: 80
80 is odd
Outline:
7.1 Repetition Control Flow
7.2 Programming Examples
7.3 More About Strings
7.4 A Numerical Example
7.5 Exercises
Sequence
Repetition
Subroutine Selection
So far, we have already learned about the flow control of Sequence, Subroutine, and Selection
(branching). In this chapter, we will newly learn about the flow control of Repetition.
Computers are often used to do repetitive tasks because humans don’t like to do the same thing over and
over again. In computer programs, repetition flow control is used to execute a group of instructions
repeatedly. Repetition flow control is also called iteration or loop. In Python, repetition flow control can be
expressed by a for-statement or a while-statement that allows us to execute a code block repeatedly.
Syntax:
for variable in sequence :
code_block
The variable after for is called the “loop index”. It takes on each successive value in “sequence” in the
order they appear in the sequence. The sequence can be one of the Python sequence objects such as a
string, a list, a tuple, or a range of integers from the built-in function range() (we will explain about function
range() in the next subsection). In the following flowchart, the number of times the code_block is executed
False
more items in sequence ?
True
variable = next item
code_block
k = k + 1
print(f'round {k} : c is {c}')
round 1 : c is p
round 2 : c is y
round 3 : c is t
round 4 : c is h
round 5 : c is o
round 6 : c is n
>>> k = 0
>>> for i in range(4):
k = k + 1
print(f'round {k} : i is {i}')
round 1 : i is 0
round 2 : i is 1
round 3 : i is 2
round 4 : i is 3
In its most general form, the range() function takes three integer arguments: start, stop, and step.
range(start, stop, step) produces the sequence of integers:
- If step is positive, the last element is the largest integer less than stop.
When step
is positive
+step +step +step +step +step
...
start stop
- If step is negative, the last element is the smallest integer greater than stop.
When step
is negative
+step +step +step +step +step
...
stop start
Produces the empty sequence because step is positive and start is not less than stop.
>>> list(range(5,3,1))
[]
Produces the empty sequence because step is negative and start is not greater than stop.
>>> list(range(3,5,-1))
[]
Note: the stop value will never appear in the generated sequence.
>>> list(range(3,8,1))
[3, 4, 5, 6, 7]
Step:
A simple step of function hello().
hello(n):
• receive n as its parameter.
• repeat n times:
o write 'Hello World!'
• write 'Goodbye!'
Program:
1: def hello(n):
2: for i in range(n):
3: print('Hello World!')
4: print('Goodbye!')
We’ll write a function fah_to_cel() to do the task. We’ll use a for-loop in which the loop index holds the
Fahrenheit values. The for-loop will iterate over a sequence from 212 down to 32 generated by range().
First, let's experiment with the range of Fahrenheit values:
>>> list(range(212,32,-20))
[212, 192, 172, 152, 132, 112, 92, 72, 52]
>>>
From the above example, the result shows that 32 is missing. We should use one less than 32 so that 32 can
be included in the sequence. Now, we've got a correct sequence running from 212 down to 32 as follows.
1: def test_print():
2: print('12345678901234567890')
3: print(f"{'python':>10}{'idle':>10}")
4: print(f"{'python':<10}{'idle':<10}")
5: print(f"{'python':^10}{'idle':^10}")
6: cel = 32/3
7: print('12345678901234567890')
8: print(f"{cel:>10.1f}{cel:>10.3f}")
9: print(f"{cel:<10.1f}{cel:<10.3f}")
10: print(f"{cel:^10.1f}{cel:^10.3f}")
11: print('12345678901234567890')
>>> fah_to_cel(32,100,20)
Fahrenheit Celcius
---------- -------
32 0.0
52 11.1
72 22.2
92 33.3
---------- -------
>>> fah_to_cel(100,32,-20)
Fahrenheit Celcius
---------- -------
100 37.8
80 26.7
60 15.6
40 4.4
---------- -------
>>> fah_to_cel(step=-20,start=100,end=0)
Fahrenheit Celcius
---------- -------
100 37.8
80 26.7
60 15.6
40 4.4
20 -6.7
---------- -------
>>>
Run each of these following examples to see how the default values, 32, 213, and 20, works.
>>> fah_to_cel()
Fahrenheit Celcius
---------- -------
32 0.0
52 11.1
72 22.2
92 33.3
112 44.4
132 55.6
152 66.7
172 77.8
192 88.9
212 100.0
---------- -------
>>> fah_to_cel(100)
Fahrenheit Celcius
---------- -------
100 37.8
120 48.9
140 60.0
160 71.1
180 82.2
200 93.3
---------- -------
>>> fah_to_cel(50,100)
Fahrenheit Celcius
---------- -------
50 10.0
70 21.1
90 32.2
---------- -------
>>>
Let's write a Python function factorial(n) to compute and return the value of n!
>>> factorial(5)
120
>>> factorial(3)
6
>>> factorial(1)
1
>>> factorial(0)
1
>>> factorial(10)
3628800
>>>
An Accumulating Algorithm:
The calculate of 3! and 5! are performed as follows.
3! = 3*2*1 = 6
5! = 5*4*3*2*1 = 120
Since the function factorial(n) must work for every value of n, so we'll devise an accumulating algorithm
that works for every value of n. We can compute 4! by accumulating results as follows. Let's use a variable
result to hold the accumulating result.
• Start at 1
• Take that 1, then 1*4 = 4
• Take that 4, then 4*3 = 12
• Take that 12, then 12*2 = 24
• Done!
Then, translate our above algorithm into Python statements
result = 1
result = result*4
result = result*3
result = result*2
return result
Notice that for 4! the multiplication calculation is repeated 3 times through the sequence 4, 3, 2.
Therefore, for n! the multiplication calculation is repeated n-1 times through the sequence n, n-1, n-2 …, 3, 2
01204111 Computers and Programming, 108
Asst.Prof.Dr.Pattara Leelaprute, Department of Computer Engineering, Faculty of Engineering, Kasetsart University. All Right Reserved
result = 1
result = result*n
result = result*(n-1)
result = result*(n-2)
...
result = result*2
return result
1: def factorial(n):
2: result = 1
3: for i in range(n,1,-1):
4: result = result*i
5: return result
Next, let’s check if our function can work properly when n=0 or n=1.
From our function factorial(n), when n = 0 or 1, the range() in the for-statement becomes range(0,1,-
1) or range(1,1,-1) respectively. Then, use the built-in function list() to show the output sequence (list)
As a result, the output are both empty sequence (empty list). Thus, If we use an empty sequence in for-
statement, nothing will be generated as an output because statement(s) inside the loop doesn't get executed
at all, as shown as follows.
>>> for i in []:
print("Yappadapadoo")
>>>
1: def factorial(n):
2: result = 1
3: for i in range(n,1,-1):
4: result = result*i
5: return result
By the explanation given above, when n=0 or n=1, the range() in the for-statement becomes range(0,1,-1)
or range(1,1,-1) and both of them generate empty sequence (empty list). Thus, the statement result=
The indexes of characters in a string are numbered from the left, starting with 0.
greet
H e l l o D a n
index 0 1 2 3 4 5 6 7 8
The built-in function len() returns the length of its string argument.
>>> greet = 'Hello Dan'
>>> len(greet)
9
>>> len("I'm happy.")
10
>>> greet + 'ny!'
'Hello Danny!'
>>> len(greet + 'ny!')
12
greet
H e l l o D a n
You can use negative indexes to index backward from the end of the string.
>>> greet = 'Hello Dan'
Last character:
>>> greet[-1]
'n'
First character:
>>> greet[-9]
'H'
>>> greet[-len(greet)]
'H'
Notice the positive indexes that refer to the same positions as their negative counterparts.
>>> length = len(greet)
Last character:
>>> greet[length-1]
'n'
Second-last character:
>>> greet[length-2]
'a'
First character:
>>> greet[0]
'H'
>>> greet[length-len(greet)]
'H'
A new string object 'Hello Dan' is created and then assigned to the variable greet. Then, we expect to
change Dan to Jan
>>> greet[6] = 'J'
TypeError: 'str' object does not support item assignment
>>> 'Hello Dan'[6] = 'J'
TypeError: 'str' object does not support item assignment
>>> greet
'Hello Dan'
>>> greet = greet + 'ny'
>>> greet
'Hello Danny'
The above examples show that in Python we cannot change any character in the string, but we can append
character(s) to the string. Note that the variable greet has been changed twice by assignment, but the two
string objects, 'Hello Dan' and 'Hello Danny', can never be changed.
This pattern of processing is called a traversal. In Python, one way to implement a string traversal is by using
a for-loop.
Traversal Example:
We want to write a program that prints each character in a string, one per line, enclosed in / /. Without using
a loop, we may write a Python program to traverse the string assigned to a variable text like this:
text = 'a dog'
c = text[0]; print(f'/{c}/')
c = text[1]; print(f'/{c}/')
c = text[2]; print(f'/{c}/')
c = text[3]; print(f'/{c}/')
c = text[4]; print(f'/{c}/')
Both examples work effectively the same and the test run result shown as follows:
>>> text = 'a dog'
>>> for c in text:
print(f'/{c}/')
/a/
/ /
/d/
/o/
/g/
Test it again.
>>> spread_str('a')
/a/
>>> spread_str('')
>>> spread_str("T'Rex")
/T/
/'/
/R/
/e/
/x/
Besides, following is also the alternative version of function spread_str(text) which can work the same.
def spread_str(text):
"""print text, one char per line within / /"""
for c in text:
print(f'/{c}/')
Counting a Character:
We want to write a program that counts the number of times a character appears in a string. Suppose we
want to count the number of 'e' in a string 'pete', we may write a program like this:
1: text = 'pete'
2: count = 0
3: c=text[0]; if c=='e': count = count+1
4: c=text[1]; if c=='e': count = count+1
5: c=text[2]; if c=='e': count = count+1
6: c=text[3]; if c=='e': count = count+1
7: print(count)
Each statement in line 3 until line 6 traverses the string from left to right, and If the current character is 'e',
the variable count will be incremented by 1. This repetition is exactly the for-loop as follows:
for c in text:
if c == 'e':
count = count+1
Alternatively, we may loop over string indexes with still have the same result.
def count_char(char, text): #version 2
"""counts the no. of times 'char' appears in 'text'"""
count = 0
for i in range(len(text)):
if text[i] == char:
count = count+1
return count
Example Output 1:
How many numbers? 4
Enter number #1: 12
Enter number #2: 11.5
Enter number #3: 13
Enter number #4: 10.5
The average of 4 number(s) is 11.75
Topmost Steps:
Algorithm of the Main Routine
1) Read the value of n, making sure that n > 0
2) Read each of the n numbers and calculate the average.
3) Output the average.
Then, translate it into Python program.
1: import sys
2: # ---- main ---- #
3: n = int(input('How many numbers? '))
4: if n <= 0:
5: print('Nothing to do. Bye!')
6: sys.exit()
7: avg = average(n)
8: print(f'The average of {n} number(s) is {avg}')
From the above program, step 1) in the algorithm is translated to the code in line 3 to line 6. It receives the
value of n from the user, and uses “if statement” written in line 4 to line 6 to make sure whether received n
is greater than 0 or not. If n is less than or equal to 0, the program will stop by sys.exit() statement (in line
6). We'll write the function average() to do the read/calculate task.
The above accumulating algorithm shows repeated statements that read the number and add that number
with sum. Thus, we can convert to for-loop using n as the loop iterations as follows.
• sum = 0
• Repeat n times:
- Read a new number into the variable number
- sum = sum + number
Then translate it into Python code.
sum = 0
for i in range(n):
number = float(input(f'Enter number #{i+1}: '))
sum = sum + number
Complete Program:
1: import sys
2: def average(n):
3: sum = 0
4: for i in range(n):
5: number = float(input(f'Enter number #{i+1}: '))
6: sum = sum + number
7: return sum/n
8:
9: # ---- main ---- #
10: n = int(input('How many numbers? '))
11: if n <= 0:
12: print('Nothing to do. Bye!')
13: sys.exit()
14: avg = average(n)
15: print(f'The average of {n} number(s) is {avg}')
1) Complete the program below (in the blank (A)) so that it prints out a message many times as the
user specifies, as shown.
msg = input("What do you want me to say? ")
num = int(input("How many times you want me to say it? "))
_____________
_____(A)_____
_____________
Example output:
What do you want me to say? Thank you
How many times you want me to say it? 3
Thank you #1
Thank you #2
Thank you #3
2) Complete the code in the blanks (A) and (B) so that it creates a simple bar graph of the function g(x) =
x2, where x = 1,2,3,4,5.
def g(x):
return _____(A)_____
print(" x | g(x)")
print("---+---------------------------------")
for _____(B)_____:
bars = "#" * round(g(x+1))
print(f" {x+1} | {bars} ({g(x+1)})")
Example output:
x | g(x)
---+---------------------------------
1 | # (1)
2 | #### (4)
3 | ######### (9)
4 | ################ (16)
5 | ######################### (25)
3) Write a Python program print the words “Programming” backward as the following output. Note that
each character must be in the same line.
Output:
gnimmargorP
Example output 2:
What is the block size? 5
Enter the character to use: *
*****
*****
*****
*****
*****
5) Write a Python program that takes a message from the user, then prints the message out diagonally.
Example output 1:
Input a message: Hello
H
e
l
l
o
Example output 2:
Input a message: Good bye
G
o
o
d
b
y
e
Outline:
We've already learned that the Python for-statement provides a simple kind of loops that iterate through a
sequence of values.
The result is a run-time error because the range() function requires only integer arguments, but 0.5 is not an
integer. Thus, we need another kind of loop that is more flexible than the for-loop, which is “while-loop”.
While-loop is also called the condition loops.
while condition :
code_block
False
condition
True
code_block
1: def countdown(n):
2: False
3: while n > 0: n > 0
4: print(n)
5: n = n-1 True
6:
7: print("Go!") print(n)
>>> countdown(4)
4
3
2
1
Go! print("Go!")
>>> countdown(0)
Go!
From the test run output of countdown(0), the result shows that the code block of the loop body written in
line 4 and line 5 of the program didn’t get executed at all. It is because the condition of while statement (n>
0) is False, so that the execution of statements in the code block (written in line 4 and line 5) are bypassed as
We then devise a conditional-loop algorithm for the new version of function fah_to_cel() as follows.
fah = start
False
fah < end
True
cel = (5/9)*(fah-32)
print fah,cel
fah = fah+step
Algorithm:
• Set fah to the value of start before the first iteration.
• The condition fah < end is used to decide whether to execute another iteration or exit the loop.
• Computation to be done for each iteration: calculate cel from fah, then print a line of the table.
• Increment fah by step, to ready fah for the next iteration.
fah = start
Finally, the new version of the function fah_to_cel() (# version 2) can be defined as follows.
1: def fah_to_cel(start, end, step): # version 2
2: print(f"{'Fahrenheit':>12}{'Celcius':>12}")
3: print(f"{'----------':>12}{'-------':>12}")
4:
5: fah = start
6: while fah < end:
7: cel = (5/9)*(fah-32)
8: print(f"{fah:12.2f}{cel:12.2f}")
9: fah = fah + step
10:
11: print(f"{'----------':>12}{'-------':>12}")
Output Example 1:
For the input of the function fah_to_cel(), gives 50 as start, 40 as stop, and increment step by 2.5.
>>> fah_to_cel(50, 40, 2.5)
Fahrenheit Celcius
---------- -------
---------- -------
The above output which produced an empty table is really sensible, so it should be considered as normal,
because the step is positive and the start 50 already exceeds the stop 40.
Output Example 2:
For the input of the function fah_to_cel(), gives 50 as start, 40 as stop, and decrement step by 0.5.
>>> fah_to_cel(50, 40, -0.5)
Fahrenheit Celcius
---------- -------
---------- -------
The above output is not sensible, because the step is negative so we'd rather see a table running from 50
down to 40. Thus, this should be considered as a bug.
Output Example 3:
For the input of the function fah_to_cel(), gives 30 as start, 40 as stop, and decremented by 2.5. Since
start is already less than stop, you'd expect to see an empty table. But what you see is;
>>> fah_to_cel(30, 40, -2.5)
Fahrenheit Celcius
---------- -------
30.00 -1.11
27.50 -2.50
25.00 -3.89
22.50 -5.28
20.00 -6.67
17.50 -8.06
15.00 -9.44
12.50 -10.83
10.00 -12.22
7.50 -13.61
5.00 -15.00
2.50 -16.39
0.00 -17.78
-2.50 -19.17
The program is still running indefinitely, so you decide to hit <Ctrl+C> to stop the program.
fah = start
False
fah < end
True
cel = (5/9)*(fah-32)
print fah,cel
fah = fah+step
counter False
is within the
limit?
True
The flow chart of the counting loops can be translated into a while-loop algorithm as follows:
Note that, from the above while-loop algorithm, counter is a variable. And, “some computation statements”
may or may not use the counter variable in the computations.
Again, let’s look at the python code of function fah_to_cel() #version2, which actually uses the counting
loop.
Then, we will compare in sequence which line of the python code corresponds to which part of the
algorithm.
• Initialize the counter: Variable start is initialized to fah (line 5). Here, fah is our counter.
• while counter is within the limit: Check the condition fah<end (line 6). If the condition is True,
then executes the following statements (line 7 and line 8), in each iteration.
cel = (5/9)*(fah-32)
print(f"{fah:12.2f}{cel:12.2f}")
• Update the counter: fah is decremented by step before ending of each loop (line 9), in each
iteration.
We have once used a for-loop to implement an accumulating algorithm that computes the factorial of n as
follows:
result = 1
result = result*n
result = result*(n-1)
result = result*(n-2)
...
result = result*2
return result
This accumulating algorithm can also be easily implemented by using a counting loop (while-loop) by the
following ideas.
In fact, since the value of n is not used again elsewhere, n can be the counter itself. Thus, another slimmer
counting-loop version shown as follows:
1: def factorial(n): #version 2.1
2: result= 1
3: while n >= 2:
4: result = result*n
5: n = n-1
6: return result
One last thing before we leave factorial(n), Make sure you understand why all these versions work
correctly when n = 0 or n = 1.
The program we wrote uses a for-loop so it needs to know in advance how many input numbers there are.
This is because the for-loop is a definite loop, meaning that the number of iterations is determined when the
loop starts. Thus, we have to count the input numbers before running. Therefore, the program can be
inconvenient especially when we have too many input numbers to count.
Thus, let's write another version of this program that counts the input numbers automatically.
The program will be only interested in the first character of these responses (y). Each iteration of the loop
does the following steps:
False
more_data is 'yes' ?
True
Interactive loops allow the user to repeat a certain portion of the program on-demand, by interactive control.
The flow chart of the Interactive loops can be translated into a while-loop algorithm as follows:
Python code of the interactive loop While-loop algorithm of the interactive loop
1: def average():
2: sum = 0
3: count = 0
4: more_data = 'yes' Set more_data to 'yes'
5: while more_data[0] == 'y': while more_data is 'yes':
6: number = float(input('Enter a number:')) Read the next data item
7: sum = sum + number
8: count = count + 1
} Process the data item
9: more_data = input('Another number? (y or n):') Ask if there is more_data
10: return count, sum/count
11:
12: # ---- main ---- #
13: n, avg = average()
14: print(f'The average of {n} number(s) is {avg}')
The main routine is then added (line 13 and 14) to call the function average() and print the results. Test run
result is shown as follows:
To make the input process easier, we may employ another loop pattern, “the sentinel loop”.
• Sentinel loops (also called sentinel-controlled loops) is a leaner kind of the interactive loops.
• Sentinel loops continue to read and process data until reaching a special value that signals the
end of data.
• This special value is called the sentinel.
• The sentinel must be distinguishable from the data since it is not processed as part of the data.
False
item is not the sentinel
True
A negative input number serves as the sentinel that signals the end of data. The average() function #version
3 can be defined as follows. Then, we will compare in sequence which line of the python code corresponds
to which part of the algorithm.
Python code of the sentinel loop While-loop algorithm of the sentinel loop
1: def average(): # version 3 : sentinel loop
2: sum = 0
3: count = 0
4: number = float(input('Enter a number Read the first data item
(negative to quit): '))
5: while number >= 0: while item is not the sentinel :
6: sum = sum + number
7: count = count + 1
} Process the data item
8: number = float(input('Enter a number
(negative to quit): ')) } Read the next data item
9:
10: return count, sum/count
11:
12: # ---- main ---- #
13: n, avg = average()
14: print(f'The average of {n} number(s) is {avg}')
exits immediately, which means count remains to be 0. That renders sum/count a division by zero, which will
crash the program. A test run proves our prediction.
Handling an empty data set by a run-time error is rather disgraceful. Let's modify our function average()
version 3 to print this more poetic message for empty data set as follows:
Enter a number (negative to quit): -3
The average of 0 number(s) is nothingness
>>>
Just add an if-statement as follows before return statement. This will solve the problem.
if count == 0:
return 0, 'nothingness'
But even this nice version 3.1 still has a serious shortcoming. It cannot average a data set that contains both
positive and negative numbers because negative numbers have been used as the sentinel.
Hint: If this shortcoming is to be resolved, the sentinel can no longer be a number. Look at the statement in
line 4, the function input() actually returns a string, so we may use a character-based sentinel instead of a
numeric one. In fact, using the empty string ('') as the sentinel is very convenient.
The better version 4.0 of function average() uses the empty string as the sentinel. We want it to run like this:
Enter a number (or just <Enter> to quit): 30
Enter a number (or just <Enter> to quit): 0
Enter a number (or just <Enter> to quit): 25
Enter a number (or just <Enter> to quit): -10
Enter a number (or just <Enter> to quit): -30.5
Enter a number (or just <Enter> to quit): 15.8
Enter a number (or just <Enter> to quit): ↵
The average of 6 number(s) is 5.05
Note that, the symbol ↵ in the above output example means that the user hits <Enter> as an input. As a
result, the empty string ('') then will be given to the program as an input.
Let this version 4.0 be your programming exercise.
We've got to convert such input string to a numeric type (float or int) to be processed as a number.
>>> x = float(s)
>>> x
31.55
>>> type(x)
<class 'float'>
>>> x+3
34.55
>>>
If the user just hit <Enter> here, then input() returns the empty string.
>>> s = input('Enter a number: ')
Enter a number: ↵
>>> s
''
>>> type(s)
<class 'str'>
Now, can you figure out how to use the empty string as the sentinel for a data set.
Algorithm design:
Suppose we have three input numbers 20, 25, and 10, a simple procedure to find the maximum could be like
this.
read 20
assign 20 to max
20 >= 0, so do the following:
if 20 > max:
assign 20 to max
read 25
25 >= 0, so do the following:
if 25 > max:
assign 25 to max
read 10
10 >= 0, so do the following:
if 10 > max:
assign 10 to max
read -1
-1 < 0, so the data ends.
print max
Let's use a variable number to hold each input number. This suggests a sentinel-loop algorithm with the loop
condition number>=0. Each iteration in the dotted line squares does the following steps:
Before printing max, we ought to add a check here for the case when the very first number is the sentinel
itself, meaning an empty data set. Thus, the complete function can be defined as follows.
1: def maximum():
2: number = float(input('Enter a number (negative to quit): '))
3: max = number
4: while number >= 0:
5: if number > max:
6: max = number
7: number = float(input('Enter a number (negative to quit): '))
8: if max < 0:
9: print('Nothing to do.')
10: else:
11: print(f'The maximum is {max}')
8.6 Exercise
1) Fill the blanks (A), (B), (C) to convert the following for-loop into a while-loop.
for i in range(10,22,3):
print(i)
_____(A)_____
while ____(B)____ :
print(i)
____(C)____
>>> fah_to_cel(15,20,1)
Fahrenheit Celcius
---------- -------
15.00 -9.44
16.00 -8.89
17.00 -8.33
18.00 -7.78
19.00 -7.22
---------- -------
>>> fah_to_cel(20,15,-1)
Fahrenheit Celcius
---------- -------
20.00 -6.67
19.00 -7.22
18.00 -7.78
17.00 -8.33
16.00 -8.89
---------- -------
>>> fah_to_cel(15,20,-1)
Fahrenheit Celcius
---------- -------
---------- -------
>>> fah_to_cel(20,15,1)
Fahrenheit Celcius
---------- -------
---------- -------
>>>
3) Write a Python program that reads a sequence of numbers from the user, and prints out the
maximum, minimum, and the average of those numbers with two decimal places. The program stops
reading input when the user simply presses <Enter> without entering any number. (I.e., the sentinel is
an empty input.)
Examples Output 1:
Enter a number (just [Enter] to quit): 10
Enter a number (just [Enter] to quit): ↵
The maximum value is 10.00
The minimum value is 10.00
The average value is 10.00
Examples Output 3:
Enter a number (just [Enter] to quit): ↵
Nothing to do.
4) Write a Python program print the words “Programming” backward as the following output using
while-loop. Note that each character must be in the same line.
Output:
gnimmargorP
Outline:
9.1 Loop and a Half
9.2 Forever Loops with break
9.3 Nested Loops
9.4 Exercises
The loop and a half is a loop that may exit (on a special condition) somewhere in the middle of the loop
body. Such a premature loop exit could be done by the return statement, or the break statement, or the
continue statement. We will not cover continue in this course, though. It’s quite handy in simple programs
but can make more complex programs harder to comprehend, so some purist programmers tend to avoid
using it.
False
loop condition
True
early loop body
Algorithm:
Let’s try to figure out what find() should do for this call.
>>> find('Que sera, sera', 'e', 3)
Algorithm:
1: The three parameters:
2: text is 'Que sera, sera'
3: char is 'e'
4: index is 3
5:
6: index is 3 and text[index] != char, so increment index by 1 to become 4
7: index is 4 and text[index] != char, so increment index by 1 to become 5
8: index is 5 and text[index] == char, so char has been found, return index
From the above algorithm, you can see repeated actions from line 6 to line 8. Thus, these repeated actions
suggest a loop algorithm. The loop is to scan text searching for char, so it should iterate over the indexes of
text. Whenever char is found within text, the loop immediately exits via return with the current index (line
8). Therefore, text[index] == char is the special exit condition. Thus, we can convert from the algorithm to
the code as follows:
1: def find(text, char, index=0):
2: textlength = len(text)
3: while index < textlength:
4: if text[index] == char:
5: return index
6: index = index + 1
7:
8: return -1
you can see in line 4. When char has been found in text, the condition text[index]==char which is the
special exit condition becomes true, and then return statement in line 5 will get executed, causing an
immediate return of index to the caller. Note that, line 8 is a normal exit of the loop means char is not
found in text.
The test run result is shown as follows:
As you can see in the above program, a for loop containing a return statement is also “a loop and a half”.
Pre-loop statements
loop False
condition
True
break
Back to the function find(), we are going to create the alternative version using break. The previous version
of function find() is as follows:
return -1
Instead of the immediate return the value of index inside the dashed line square, it can break out of the
loop first and then return the result after the loop. Thus, the function find() version 2 can be modified as
follows:
return result
First, it initializes the result to the not found status by assigning -1 to result. In the dashed line square,
whenever char is found in text, the current index is the result, then break out of the loop. Finally, notice
Let’s create the alternative version of the function has_char() using break. The previous version of the
function has_char() is as follows:
for c in text:
if c == char:
return True
return False
Instead of the immediate return in a dashed line square, it can break out of the loop first and then return the
result after the loop. Thus, the function has_char() version 2 can be modified as follows.
for c in text:
if c == char:
result = True
break
return result
First, it initializes the result to False (the not found status). Whenever char is found, set result to True (the
found status), then break out of the loop. Notice that if char is never found in text, the loop will exit
normally and result remains to be False.
Pre-loop statements
exit False
condition
Ture
break
pre-loop statements
while True:
early loop body
if exit_condition == True
break
the rest of loop body
This break upon exit_condition makes it possible for the loop to terminate eventually.
A Simple Example:
1: print('Hi there.')
2: while True:
3: s = input('Enter something: ')
4: if s == 'quit':
5: break
6: print(f'You entered {len(s)} characters')
7: print('Bye now.')
The program is asking the user to input something (in line 3). Then, it checks the condition if the inputted
string is 'quit' or not. If the condition is true, it immediately breaks out of the loop and goes to execute the
first statement following the loop in line 7. Otherwise, the program continues asking for the input. The test
run example is shown as follows.
Hi there.
Enter something: python
You entered 6 characters
Enter something: Time flies.
You entered 11 characters An empty line is entered.
Enter something:
You entered 0 characters
Enter something: quit This word hits the exit condition.
Bye now.
>>>
False
item is not the sentinel
True
The flow chart of the sentinel loop can be translated into a while-loop algorithm as follows:
Sentinel-loop pattern requires two of the same read statements, one before the loop, and the other within
the loop. A forever loop with break can reduce to only one read. Now, rewrite it as a forever loop having
only one read call “The Sentinel Loop via the Forever Loop” as follows. Note that, both patterns work
effectively the same.
while True :
Read next data item
if item is the sentinel:
break
Process the data item
The function read_positive() by a forever loop with break can be defined as follows:
1: def read_positive():
2: """reads and returns only a positive number.
3: Invalid input will prompt the user to re-enter.
4: """
5: while True:
6: n = float(input('Enter a positive number: '))
7: if n > 0: # valid input
8: break
9: print(f'{n} is not positive. Please retry.')
10: return n
while i <= k:
for _ in range(i):
print('$', end='')
print()
i = i+1
Each box above is actually a single statement. Thus, each can put into any statement (statement ~
1
Nested Loops happen naturally on demand. Suppose we want to write a line of n dollar-signs ($) where n is a
given positive integer. A single call of print() can do the task.
>>> n = 5
>>> print(n*'$')
$$$$$
We can use a counting while-loop that repeats the above for-loop with the counter n running from 1 to k.
Suppose k is 5. Thus, the program can be defined as follows:
k = 5 # prints a right triangle with the base of length k
n = 1
while n <= k:
for i in range(n):
print('$', end='')
print()
n = n+1
Note that, the empty print() is added to make the next print() start at a new line.
Now, let’s convert from right triangles to a saw. Here, as shown above, we have already got a program that
writes a right triangle with the base of k dollar-signs, where k is a given positive integer.
Next, we want to write m right triangles, each with the base of k dollar signs so they look like a saw of m teeth,
where m is a given positive integer. Thus, the output when m is 3 and k is 5 shown as follows:
Again, from the code that prints a right triangle with the base of length k as shown above, we can use a
simple for-loop that repeats the above code m times. Suppose m is 4, so now we've got a program that writes
a saw of m teeth, where m is a given positive integer as follows.
1: m = 4
2: for j in range(m):
3: k = 5 # prints a right triangle with the base of length k
4: n = 1
5: while n <= k:
6: for i in range(n):
7: print('$', end='')
8: print()
9: n = n+1
Now, let’s encapsulate our saw's code into a function saw() that has three parameters:
• nteeth – the number of saw teeth.
• baselength – the number of symbols at the base of each tooth.
• symbol – the symbol used to build the saw.
In the program m is renamed to nteeth, k is renamed to baselength, '$' is replaced by symbol. Thus, the
complete code is modified as follows:
n = 1
while n <= baselength:
for i in range(n):
print(symbol, end='')
print()
n = n + 1
The counting while-loop inside the dashed line square in the version 1 of function saw() can be replaced by
a for-loop to become the version 2 of function saw() as follows.
for i in range(n):
print(symbol, end='')
print()
s
The innermost for-loop and a print() inside the dotted line square that prints a line can be replaced by a
single print() to become the version 3 of function saw() as follows.
print(n*symbol)
The inner for-loop inside the dashed line square in the version 3 of function saw() that prints a saw tooth
can be factored out to become a function print_a_tooth(). Thus, the function saw() in this new version 4
has only a single loop that is much easier to understand than the nested-loop versions.
print_a_tooth(baselength, symbol)
This process of replacing part of a program by a subroutine call is called "refactoring", which may produce a
better program.
while True:
Read n
if n is negative:
break
Convert n to binary and print the result
print 'Bye!'
The function dec_to_bin() will do the conversion from the decimal number into its binary equivalent.
Algorithm of dec_to_bin():
Let’s convert 13 to binary. These are the expressions for the conversion, step by step.
Loop design:
Now, we are going to convert 6 in decimal to binary.
iteration n
quotient remainder binary updated next iteration?
n//2 n%2 n
Pre-loop 6 ""
3rd 1 0 1 "110" 0 No
From the table, n is the given decimal number. In this example, 6 is given as an input. At the 1st iteration, 6 is
divided by 2 gives 3 as the answer(“quotient”) and 0 as the remainder, then we put that answer (3) into the
column “updated n”. After that, put that remainder (0) into the column “binary” as a string ("0"). Then,
check if “updated n” is 0 or not, and put the answer of “Yes” or “No” into the column of “next iteration?”
For the 2nd iteration, we start with n = 3 and do the same things as in the 1st iteration. At the 3rd iteration,
because “next iteration?” is “No”, so we end our calculation here. Finally, we can obtain “110” which is
written in the column of “binary” as our answer.
Note that, we can combine the string using the plus operator (+). For example, "1"+"0" is “10”. Then, we can
translate the mentioned steps to python code as follows:
1: # n is given as a parameter
2: binary = ''
3: while True:
4:
5: quotient = n // 2
6: remainder = n % 2
7: binary = str(remainder) + binary
8: n = quotient
9:
10: if n == 0 :
11: break
1: # n is given as a parameter
2: binary = ''
3: while True:
4:
5: binary = str(n % 2) + binary
6: n = n // 2;
7:
8: if n == 0 :
9: break
Once the loop exits, the variable binary (in line 10) is the result of the conversion. The main program added
to finish the program as follows:
1: def dec_to_bin(n):
2: """returns the binary representation of integer n
3: """
4: binary = ''
5: while True:
6: binary = str(n % 2) + binary
7: n = n // 2
8: if n == 0:
9: break
10: return binary
11:
12: # ---- main ---- #
13: while True:
14: n = int(input('Enter a nonnegative integer (or negative to quit): '))
15: if n < 0:
16: break
17: print('Binary number is', dec_to_bin(n))
18: print('Bye!')
9.4 Exercises
1) Fill in the blank (A) to complete the following program so that the loop stops when it has found
the smallest positive integer greater than 1000 that is divisible by both 33 and 273.
n = 1001
while True:
_____________
_____(A)_____
Output:
The value of n is 3003
2) Fill in the blank (A) and (B) to complete the code so that it gives the output as shown.
for i in _____(A)_____ :
print(f"i = {i}")
for j in _____(B)_____ :
print(f" j = {j}")
Output:
i = 5
j = 1
j = 2
i = 6
j = 1
j = 2
i = 7
j = 1
j = 2
i = 8
j = 1
3) Fill in the blank (A) (B) (B) to complete the code so that it gives the output as shown.
for i in range(3):
for j in _____(A)_____ :
nspaces = _____(B)_____
nstars = _____(C)_____
print((' ' * nspaces) + ('*' * nstars))
Output:
*
***
*****
*******
*
***
*****
*******
*
***
*****
*******
4) Write a Python program to show the multiplication table of N from N x 1 to N x 12. The program
will continue to ask for another value N until the user presses ENTER without giving any value.
Example Output:
Input value of N (or just ENTER to quit): 12↵
12 x 1 = 12
12 x 2 = 24
12 x 3 = 36
12 x 4 = 48
12 x 5 = 60
12 x 6 = 72
12 x 7 = 84
12 x 8 = 96
12 x 9 = 108
12 x 10 = 120
12 x 11 = 132
12 x 12 = 144
Input value of N (or just ENTER to quit): ↵
*********
Note: Import the random function as follows to generate a random number (in this exercise use
integer number).
>>> import random
>>> number = random.randint(0,99)
>>> number
67
Example Output 1:
Round [1] >> Enter the number (0-99): 20
too LOW
Round [2] >> Enter the number (0-99): 50
too HIGHT
Round [3] >> Enter the number (0-99): 30
too LOW
Round [4] >> Enter the number (0-99): 40
too HIGHT
Round [5] >> Enter the number (0-99): 35
CORRECT
Example Output 2:
Round [1] >> Enter the number (0-99): 99
too HIGHT
Round [2] >> Enter the number (0-99): 1
too LOW
Round [3] >> Enter the number (0-99): 60
too LOW
Round [4] >> Enter the number (0-99): 80
too HIGHT
Round [5] >> Enter the number (0-99): 62
too LOW
Round [6] >> Enter the number (0-99): 68
too LOW
Round [7] >> Maximum attempts exceeded.
Outline:
From the program, while loop is used to receive numbers from user. After the user inputs a number in each
iteration (line 4), the program checks the condition if that input (ans) is empty string or not (line 5). If the
condition is true, loop will stop by break (line 6). Otherwise, that input (ans) is converted to float and
assigned to a variable score, then accumulated into a variable sum. Variable count is used to count a number
of the input. Finally, the average(avg) is calculated (line 10).
Ideas: We need to keep track of every single score. Thus, writing a program by declaring one variable for one
score is very inflexible. We cannot even control how many times to read scores.
s1 = float(input("Enter student score: "))
s2 = float(input("Enter student score: "))
s3 = float(input("Enter student score: "))
:
Line 1 is the statement that creates an empty list. Then a new element is appended to that list at line 7.
A new element can be added by using the list.append() method (a method is a function bound to an
object).
>>> lst
[8, 3, 38, 5, 3, 1, 6]
>>> lst.append(72)
>>> lst
[8, 3, 38, 5, 3, 1, 6, 72]
8
3
2
5
3
1
6
START
display average
END
False
more score?
True
return scores
average total/count
return average
False
more item in scores? return
True
False
score less than value?
True
print score
1: def compute_average(scores):
2: sum = 0
3: for s in scores:
4: sum = sum + s
5: return sum/len(scores)
>>> sum([1,2,3,4])
10
>>> sum([10,50,21,27])
108
>>> sum(range(101))
5050
Testing:
Once we have defined all subroutines, let us test them one by one
• Testing read_scores()
• Testing compute_average()
Once we have tested all subroutines, let us write the main program as follows:
1: scores = read_scores()
2: avg = compute_average(scores)
3: print(f"Average score is {avg}")
4: print("Scores below average:")
5: print_below(scores,avg)
Ideas:
Most subroutines from the previous example can be reused (read_scores, compute_average). Min and max
can be computed using the built-in functions. The only challenge is the summary table part which is defined
as show_score_summary(scores) (in line 2) in the following code.
1: scores = read_scores()
2: show_score_summary(scores)
3: avg_score = compute_average(scores)
4: min_score = min(scores)
5: max_score = max(scores)
6: print(f"Average score is {avg_score}")
7: print(f"Minimum score is {min_score}")
8: print(f"Maximum score is {max_score}")
The summary needs to display the order of each student's score as shown in the test run result in the
following dotted line square. Thus, a for loop with a combination of len() and range() can help.
From the above example, instead of 4, a new value of 8 was assigned to the place of Index number 3.
From the above example, it shows that we cannot change any character in the string.
From the above example, after creating a list of numbers (in the first line), nums1 is then assigned to nums2 by
equal (=) operator (in the second line). That means both variables nums1 and nums2 are associated/assigned
with the same list of numbers. Thus, when some member in one variable has been changed ( nums2[2]=20
in the example), the member at the same index number of the other variable (nums1[2]) will be also
changed accordingly. To prevent this behavior, making a copy of a list by using list() function instead is
recommended.
>>> nums1 = [1,2,4,8]
>>> nums2 = list(nums1)
>>> nums2[2] = 20 nums1 1 2 4 8
>>> nums1
[1, 2, 4, 8]
>>> nums2 nums2 1 2 20 8
[1, 2, 20, 8]
they are independent of each other. Therefore, even a member of one variable is changed (nums2[2]=20 in
the example), the member of the other variable are not affected at all.
Membership Test
Using the in operator to check if a specified value exists in a sequence (list or string) or not.
>>> numbers = [5,1,8,2,7]
>>> 5 in numbers
True
>>> 9 in numbers
False
The following code slices a list of month names into four quarters.
1: months = [
2: 'Jan','Feb','Mar','Apr','May','Jun',
3: 'Jul','Aug','Sep','Oct','Nov','Dec'
4: ]
5:
6: q1 = months[0:3]
7: q2 = months[3:6]
8: q3 = months[6:9]
9: q4 = months[9:12]
10: print("Quarter 1:", q1)
11: print("Quarter 2:", q2)
12: print("Quarter 3:", q3)
13: print("Quarter 4:", q4)
1) Fill in the blank (A) so that it gives the output in the shell as shown.
>>> nums = _____(A)_____
>>> len(nums)
5
>>> min(nums)
3
>>> max(nums)
10
>>> sum(nums)
34
2) Fill the blank (A) to complete the code so that it prints out every third member of the list seq in the
order from first to last, starting from the second member. Your code must also work with any
contents of seq.
seq = [2,3,5,7,11,13,17,19]
for i in _____(A)_____:
print(seq[i])
Output:
3
11
19
3) Fill in the blank (A) to complete the code so that it prints out all members of the list seq in the
order from last to first. Your code must also work with any contents of seq.
seq = [2,3,5,7,11,13,17,19]
for i in _____(A)_____:
print(seq[i])
Output:
19
17
13
11
4) Write a Python program that asks user to enter a sequence of scores with an empty input to indicate
the end of the score sequence. The program then prints out all the scores ranked from the highest
to the lowest.
Example Output 1:
Enter student score (or ENTER to finish): 13↵
Enter student score (or ENTER to finish): 19↵
Enter student score (or ENTER to finish): 10↵
Enter student score (or ENTER to finish): ↵
Rank #1: 19
Rank #2: 13
Rank #3: 10
Example Output 2:
Enter student score (or ENTER to finish): 87↵
Enter student score (or ENTER to finish): 56↵
Enter student score (or ENTER to finish): 73↵
Enter student score (or ENTER to finish): 59↵
Enter student score (or ENTER to finish): 90↵
Enter student score (or ENTER to finish): 72↵
Enter student score (or ENTER to finish): ↵
Rank #1: 90
Rank #2: 87
Rank #3: 73
Rank #4: 72
Rank #5: 59
Rank #6: 56
Outline:
data.txt
Hello
Good morning
>>> s = open("data.txt").read()
>>> s
'Hello\nGood morning\n'
Reading file's contents as a list of strings, one per line can be done as follows. Note that method
str.splitlines() returns a list.
open(filename).read().splitlines()
Methods are called with their names and objects they are bound to (e.g., str.split(), where str is replaced
by a string)
>>> s = "Hello, World"
>>> s.split
<built-in method split of str object at 0x109665e70>
>>> s.split(",")
['Hello', ' World']
Text file
data.txt
Hello
Good morning
Program:
filename = input("Enter file name: ")
lines = open(filename).read().splitlines()
for i in range(len(lines)):
print(f"Line {i+1}: {lines[i]}")
For Windows:
• Click a file icon in Explorer
• Press <Ctrl-C> to copy the entire path name of the file.
• Back to IDLE shell and press <Ctrl-V> to paste the entire path name of the file as follows:
• The close() method. A file is closed manually when this statement is executed.
f = open("file.txt")
for line in f.readlines():
# process the lines
f.close()
Text file
scores.txt
87.3
75.6
63.0
97.5
37.6
Ideas:
Scores must be read as a list of numbers, not strings. Thus, each string member must get converted into a
number (float).
lines
“87.3” “75.6” “63.0” “97.5” “37.6”
float()
First, we read the file's contents as a list of strings, one per line, and name that list as lines. Then we create
an empty list named scores and use for loop to convert each member in the list lines from string to float
number and append the converted number to list scores.
list2 = []
for item in list1:
list2.append(expression)
list1 x0 x1 x2 x3 x4
expression
list2 y0 y1 y2 y3 y4
Examples:
Create a new list with all values doubled from another list.
>>> L1 = [5,1,2,8,9,12,16]
>>> L2 = [2*x for x in L1]
>>> L2
[10, 2, 4, 16, 18, 24, 32]
Create a list of squares of n, where n = 1,2,…,10. Note that, a range object can be used directly inside a list
comprehension.
>>> [i**2 for i in range(1,11)]
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
From the above program, note that line 4 is the statement that sorts the scores from highest to lowest.
scores.txt
87.3
75.6
63.0
97.5
37.6
scores.txt
87.3
75.6
63.0
97.5
37.6
Thus, we must filter out those empty line(s) before converting them to floats.
list2 = []
for item in list1:
if condition:
list2.append(expression)
Create a list of positive integers less than 100 that are divisible by 8 but not divisible by 6.
>>> [x for x in range(1,100) if x%8 == 0 and x%6 != 0]
[8, 16, 32, 40, 56, 64, 80, 88]
01175112,1,B+
01204111,3,A
row 01417167,3,B
columns
grades.txt
01175112,1,B+
01204111,3,A
01355112,3,C+
01417167,3,B
table
1 2 3
4 5 6
Step 1: Read grade table data from the file as a nested list.
We will define read_table() function as follows:
def read_table(filename):
lines = open(filename).read().splitlines()
table = [x.split(",") for x in lines if x != ""]
return table
input file
Let's test it. grades.txt
As you can see from the above output, the resulting table is not complete yet.
• The credits column (in a dotted line square) should store integers, not strings, for later calculation.
• The point column (in a dashed line square) is still missing.
We will traverse the table list to perform an adjustment on each row. Thus, we have to also define the
grade_point() function to map grades to points.
Line 26 is a calling of function grade_point() by sending a grade as an argument. Then the function
grade_point() converts the grade to the corresponding grade point and returns. Finally, the returned grade
point is appended to row as a last column. The test run result of the function read_table() is shown as
follows:
>>> table = read_table("grades.txt")
>>> table
[['01175112', 1, 'B+', 3.5], ['01204111', 3, 'A', 4.0],
['01355112', 3, 'C+', 2.5], ['01417167', 3, 'B', 3.0]]
GPA is computed from the summation of credits*point of all subjects, divided by the total credits. Note
that, credits is in column#1 and point is in column#3.
sum_credits_point = sum([row[1]*row[3] for row in table])
gpa = sum_credits_point/total_credits
The program starts the execution form this main method. Line 37 is the statement that gets the file name
from the user. The next line is a calling of function read_table() to process data as explained in step 1. Line
39 is a calling of function print_table() to display the grade table as explained in step 2. Then lines 40, 41
and 42 are for the calculation of total credit and GPA as explained in step3. Finally, the last two lines are
showing the outputs of total credit and GPA. Test run result then shown as follows.
planets.txt
Mercury
Venus
Earth
Mars
Jupiter
Saturn
Uranus
Neptune
Fill in the blank (A) to complete the code below so that it opens planets.txt in the same folder
and reads out all of its lines into a list, including empty lines.
>>> lines = _____(A)_____
>>> lines
['Mercury', 'Venus', '', 'Earth', '', 'Mars', 'Jupiter', 'Saturn', 'Uranus',
'Neptune']
4) Given a nested list representing a table, fill in the blank (A) to write a list comprehension that creates
a list of only the rows whose last columns are even numbers.
>>> table = [[1,2,3],[4,5,6],[7,8,9],[10,11,12]]
>>> new_table = _____(A)_____
>>> new_table
[[4, 5, 6], [10, 11, 12]]
5) Write a Python program that reads a CSV file containing a list of people and their ages. The program
then reports the name(s) of the oldest person(s) in the list.
Notes: if there is more than one person with the same oldest age, the program must print out these
names in the same order as listed in the input file.
age1.txt
Somchai,58
Somying,50
Somsak,62
Examples 2: In case there is more than one person with the oldest age, the program must report all
those people's names. Suppose the file age2.txt contains the following:
age2.txt
Sophia,95
Jackson,56
Emma,95
Aiden,42
Olivia,68
Lucas,75
Ava,86
Liam,92
Outline:
Using NumPy
NumPy library is named numpy and can be imported using the import keyword, e.g.,
import numpy
a = numpy.array([1,2,3])
By convention, the name numpy is renamed to np for convenience using the as keyword, e.g.,
import numpy as np
a = np.array([1,2,3])
• Arrays can be two-dimensional, similar to nested lists. Examples are shown as follows.
>>> import numpy as np
>>> table = np.array([[1,2,3],[4,5,6]])
>>> table
array([[1, 2, 3],
[4, 5, 6]])
>>> table[0] # one-index access gives a single row
array([1, 2, 3])
>>> table[1]
array([4, 5, 6])
>>> table[0][1] # two-index access gives a single element
2
>>> table[1][2]
6
In the above example, an error occurred because math.sqrt only works with scalars.
>>> np.sqrt(a)
array([ 1. , 1.41421356, 1.73205081, 2. , 2.23606798])
Thus, instead of math.sqrt, we have to use a vectorized version of sqrt which is provided by NumPy as
shown in the above example.
0
10
37
50
68
100
Ideas:
Although techniques from previous chapters could be used, we will solve this problem using arrays by these
steps.
Step 1: Read all values in the input file into an array.
Step 2: Apply the conversion formula directly to the array.
9
F= C + 32
5
Program:
1: import numpy as np
2:
3: filename = input("Enter file name: ")
4: c_array = np.loadtxt(filename)
5: f_array = 9/5*c_array + 32
6: for fah in f_array:
7: print(f"{fah:.1f}")
After received the file name from the user (in line 3), the program uses function loadtxt() to read numbers
in that text file and converts to an array of float numbers (in line 4). Then the program converts each number
in that array (which is degree Celsius) to Fahrenheit (in line 5). Finally, the program shows the output by using
for loop (in line 6-7). Note that :.1f inside print() (in line 7) is to specify to display 1 decimal points.
The test run result shown as follows.
68.70
31.53
16.94
9.95
52.55
29.65
64.01
69.52
30.08
21.77
Ideas:
From statistics, the mean of the data set (x1, x2,…, xn) is
n
1
x� = � xi
n
i=1
That’s mean:
stdev = np.sqrt(
sum((X-mean)**2) / (n-1)
)
After receive file name from the user (in line 3), the program uses function loadtxt() to read numbers in that
text file and converts to array X (in line 4). Then, the program calculates mean and assign to variable mean (in
line 6). After that, it calculates standard deviation as explained in the Ideas above (in line 7). Finally, the
program shows the output of mean and standard deviation (in line 8-9). The test run result is shown as
follows.
1row.txt
75,34,64,82
Initially, import module numpy and use function loadtxt() to create array, named table as follows.
>>> import numpy as np
>>> table = np.loadtxt("1row.txt",delimiter=",")
>>> table
array([ 75., 34., 64., 82.])
Try to use properties ndim and shape to find array dimension and lengths in all dimensions, respectively.
>>> table.ndim
1
>>> table.shape
(4,)
As you can see from the output result, array table has 1 dimension with 4 members (has length of 4).
Again, try to use properties ndim and shape to find array dimension(s) and length(s) in all dimension(s),
respectively. Now, you can confirm that array table has 2 dimensions, and each dimension has length of 1
and 4, respectively.
>>> table.ndim
2
>>> table.shape
(1, 4)
Back to Task Score Query. The program of Task Score Query can be defined as follows.
After import a module numpy (in line 1), the program gets data from a file named scores.txt, and creates
array named table (lines 3-5). Then, it gets a table size and displays as the number of students and the
number of subjects (in line 6-7), respectively. Then, it asks the user to input which number of the student
(student_no) and also which number of the subject (subject_no) to be displayed (in line 8-9). Note that, to
specify the correct index number to array table, we have to subtract 1 from both student_no and
subject_no because the index number of array starts from 0 (in line 10). Finally, the output is shown (in line
scores.txt
75,34,64,82
67,79,45,71
58,74,79,63
Ideas:
Find the student who fails the exam (score < 50). Scan through all scores and check one by one.
Steps:
For each student (each row), go from the first to the last subject (columns). Check whether the score is below
50 or not. If so, print out the student number, subject number, and the score.
Program:
1: import numpy as np
2:
3: FILENAME = "scores.txt"
4: print(f"Reading data from {FILENAME}")
5: table = np.loadtxt(FILENAME, delimiter=",", ndmin=2)
6: nrows,ncols = table.shape
7: print(f"Found scores of {nrows} student(s) on {ncols} subject(s)")
8:
9: for r in range(nrows):
10: for c in range(ncols):
11: score = table[r][c]
12: if score < 50:
13: print(f"Student #{r+1} fails subject #{c+1} with score {score}")
However, how to traverse all the columns (i.e., subjects) by for loop?
Array Transpose
NumPy's arrays have the array.T property for viewing the transposed version of the arrays. This allows 2D
array traversal by columns. The transpose provides a different view to an array, not a copy of it. See an
example using the same table from the above.
>>> table
array([[ 75., 34., 64., 82.], Row 0
[ 67., 79., 45., 71.], Row 1
[ 58., 74., 79., 63.]]) Row 2
>>> table.T
array([[ 75., 67., 58.], Column 0
[ 34., 79., 74.], Column 1
[ 64., 45., 79.], Column 2
[ 82., 71., 63.]]) Column 3
>>> table.T[0]
array([ 75., 67., 58.])
Thus, by using array.T property, the program of the task Score Sheet Summary can be defined as follows.
This program also modified from the previous task. The first for loop in line 11-12 accesses each row of table
and calculates the summation of each rows. Then, it shows total score of each student in line 12. The second
for loop in line 16-18 calculates average score of each subject (average score of each column) by using the
transpose of table. Concretely, the average of each subject is calculated by dividing the summation of
transposed row (which is scores of students) by the length of that transposed row (which is the number of
students). Then, it shows the average score for each subject in line 18. The test run result is shown as
follows.
• Matrix-style multiplication
>>> import numpy as np
>>> a = np.matrix([[1,2],[3,4]])
>>> b = np.matrix([[5,6],[7,8]])
>>> a
matrix([[1, 2],
[3, 4]])
>>> b
matrix([[5, 6],
[7, 8]])
>>> a*b
matrix([[19, 22],
[43, 50]])
>>> b*a
matrix([[23, 34],
[31, 46]])
Matplotlib provides a rich set of data visualization tools like NumPy. Matplotlib is not part of standard Python.
Anaconda and other scientific Python distributions come with it.
Matplotlib library has many submodules, but the most commonly used submodule is pyplot. It provides
functions similar to that of MATLAB. Pyplot can be imported using the import keyword, e.g.,
import matplotlib.pyplot
matplotlib.pyplot.plot([1,2,3],[4,5,6])
matplotlib.pyplot.show()
Ideas:
• Create an array for the values of x, 0 ≤ 𝑥𝑥 ≤ 5
• Compute two other arrays for y1 and y2
The program imports numpy and matplotlib module (in line 1 and 2). Line 3 creates an array that contains
the values of x which are [0,1,2,3,4,5], and line 4-5 create an array for y1 and y2. Then, the program
plots a graph by using plot() function for x vs. y1 and x vs. y2, in line 6-7. Finally, show() function is used to
show the graph. The output result is shown as follows.
• linspace(start,stop,length) makes an array of length values from start to stop (including stop
itself)
>>> np.linspace(0,5,11)
array([ 0. , 0.5, 1. , 1.5, 2. , 2.5, 3. , 3.5, 4. , 4.5, 5. ])
In the task Function Grapher, we will use the linspace() function to create a finer sequence of x. Create 100
points from 0 to 5 to make smoother curves. We can modify line 3 as follows:
1: import numpy as np
2: import matplotlib.pyplot as plt
3: x = np.linspace(0,5,100) # 100 points from 0 to 5
4: y1 = np.sin(np.pi*x/2)
5: y2 = 1/2*np.cos(np.pi*x/3)
6: plt.plot(x,y1)
7: plt.plot(x,y2)
8: plt.show()
y label
x label
Ideas:
We simply use the projectile-motion formulas from high-school physics:
𝑥𝑥(𝑡𝑡) = 𝑢𝑢 cos(𝜃𝜃) × 𝑡𝑡,
1
𝑦𝑦(𝑡𝑡) = 𝑢𝑢 sin(𝜃𝜃) × 𝑡𝑡 − 𝑔𝑔𝑡𝑡 2
2
where u is the initial speed (in m/s) and g is the Earth's gravitational acceleration, which is 9.81 m/s2
Steps:
The program will roughly work in the following steps.
Program:
1: import numpy as np
2: import matplotlib.pyplot as plt
3:
4: g = 9.81 # Earth's gravity in m/s^2
5: u = 100 # initial speed in m/s
6: t = np.linspace(0,10,100)
7: angles = [30,45,60,75]
8: for theta in angles:
9: x = u*np.cos(np.radians(theta))*t
10: y = u*np.sin(np.radians(theta))*t - 1/2*g*(t**2)
11: plt.plot(x,y,label=f"angle = {theta}")
12:
13: # decorate the figure
14: plt.xlabel("distance (m)")
15: plt.ylabel("height (m)")
16: plt.legend()
17: plt.grid(True)
18: plt.show()
Please note that for loop is used because we need to calculate x and y then plot the graph for each angle.
The output result is shown as follows.
body.txt
65.6,174.0
71.8,175.3
80.7,193.5
72.6,186.5
:
The output result when using scatter plot function with three variables is shown as follows.
The output result when using scatter plot function adding a color bar is shown as follows.
The output result when using scatter plot function adding a color bar that changed the color map to “jet” is
shown as follows.
Ideas:
We will create a scatter plot with three variables:
weights as x values
heights as y values
BMI as color codes
BMI is computed from weights and heights using the formula:
weight kg
BMI =
(height m )2
Program:
Please download the full body.txt file from https://elab.cpe.ku.ac.th/data/body.txt
body.txt
65.6,174.0
71.8,175.3
80.7,193.5
72.6,186.5
:
Note that, according to the file body.txt, weight and height are separated into 2 columns in each row.
Therefore, we need to transpose them (as shown in line 5 and 6), to get the row of weight and the row of
height, respectively. The output of the program then shown as follows.
temperature.txt
18,18,18,19,20,...
19,19,19,20,21,...
19,19,19,21,21,...
: : : : :
import numpy as np
import matplotlib.pyplot as plt
data = np.loadtxt("temperature.txt",delimiter=",")
plt.imshow(data)
plt.show()
1) Fill in the blanks (A) and (B) to get the output as shown.
>>> import numpy as np
>>> x = _____(A)_____
>>> x*2
array([ 4, 6, 10, 14, 22, 26])
>>> y = _____(B)_____
>>> x*2 + y
array([ 5, 6, 11, 14, 23, 26])
2) Enter an expression in the blank (A) so that it correctly computes the root mean square (RMS) of the
values in the array x. The RMS of (x1,x2,…,xn) is defined as:
1
𝑥𝑥𝑟𝑟𝑟𝑟𝑟𝑟 = � (𝑥𝑥12 + 𝑥𝑥22 +. . . +𝑥𝑥𝑛𝑛2 )
𝑛𝑛
The expression must work with any sequence, not only the one in the example.
>>> import numpy as np
>>> x = np.array([2,3,5,7,11,13])
>>> x_rms = _____(A)_____
>>> print(f"{x_rms:.2f}")
7.93
table.txt
3,5,0,5,9,1
4,2,6,5,1,8
7,10,9,4,6,5
5) Write a Python program that reads a list of values from the file specified. The program then reports
the following:
• The number of values (i.e., the data size) in the file
• The minimum value, with two decimal places
• The maximum value, with two decimal places
• The mean of the values, with two decimal places
• The standard deviation of the values, with two decimal places
Note that the mean of the data set X = (x1,x2,…,xn) is:
𝑁𝑁
1
𝑥𝑥̅ = � 𝑥𝑥𝑖𝑖
𝑛𝑛
𝑖𝑖=1
𝑁𝑁
1
𝜎𝜎 = � �(𝑥𝑥𝑖𝑖 − 𝑥𝑥̅ )2
𝑁𝑁 − 1
𝑖𝑖=1
Example 1:
Suppose the file values1.txt contains the following:
values1.txt
10
13
19
Example 2:
Suppose the file values2.txt contains the following:
values2.txt
68.70
31.53
16.94
9.95
52.55
29.65
64.01
69.52
30.08
21.77