SlideShare a Scribd company logo
NURHANI BINTI MOHD SABRI
LIYANA BINTI MAT RANI
writers :
A Beginner Guide To Python Programming. Execute your first python program,all in simple steps
Basic Python
Programming
Basic Python
Programming
Character:
String
input()
[index:]
A
l
l
r
i
g
h
t
s
r
e
s
e
r
v
e
d
J
A
B
A
T
A
NT
E
KN
OL
OGI
MA
KL
U
MA
T&
KOMU
N
I
KA
S
I
(
J
T
MK)
P
OL
I
T
E
KN
I
KB
A
L
I
KP
U
L
A
U
©2
0
2
1P
o
l
i
t
e
k
n
i
kB
a
l
i
kP
u
l
a
u
A
U
T
HOR
S
:
L
i
y
a
n
aB
i
n
t
i
Ma
t
R
a
n
i
N
u
r
h
a
n
i
B
i
n
t
i
Mo
h
dS
a
b
r
i
E
D
I
T
OR
S
:
S
a
mi
h
a
hB
i
n
t
i
A
b
d
u
l
L
a
t
i
f
I
l
i
N
u
r
A
y
u
n
i
B
i
n
t
i
N
a
z
r
i
D
E
S
I
GN
E
R
S
:
Mu
h
a
mma
dS
h
u
k
r
i
B
i
nI
s
ma
i
l
E
d
d
y
z
u
l
h
a
m B
i
nA
b
uB
a
k
a
r
L
i
y
a
n
aB
i
n
t
i
Ma
t
R
a
n
i
T
h
i
s
b
o
o
k
o
r
a
n
y
p
o
r
t
i
o
n
t
h
e
r
e
o
f
m
a
y
n
o
t
b
e
r
e
p
r
o
d
u
c
e
d
o
r
u
s
e
d
i
n
a
n
y
m
a
n
n
e
r
w
h
a
t
s
o
e
v
e
r
w
i
t
h
o
u
t
t
h
e
e
x
p
r
e
s
s
w
r
i
t
t
e
n
p
e
r
m
i
s
s
i
o
n
o
f
t
h
e
p
u
b
l
i
s
h
e
r
e
x
c
e
p
t
f
o
r
t
h
e
u
s
e
o
f
b
r
i
e
f
a
u
t
a
t
i
o
n
s
i
n
a
b
o
o
k
r
e
v
i
e
w
.
F
i
r
s
t
a
n
df
o
r
e
mo
s
t
,
w
ew
o
u
l
dl
i
k
et
op
r
a
i
s
ea
n
dt
h
a
n
kA
l
l
a
h
S
.
W.
T
,
t
h
eA
l
mi
g
h
t
yf
o
r
g
i
v
i
n
gu
st
h
es
t
r
e
n
g
t
ha
n
db
e
c
a
u
s
e
o
f
H
i
sb
l
e
s
s
i
n
g
,
w
ea
r
ea
b
l
et
oc
o
mp
l
e
t
et
h
i
sP
y
t
h
o
n
e
-
B
o
o
k
.
T
h
es
u
c
c
e
s
sa
n
do
u
t
c
o
meo
f
t
h
i
sw
e
r
ep
o
s
s
i
b
l
eb
y
t
h
eg
u
i
d
a
n
c
ea
n
ds
u
p
p
o
r
t
f
r
o
mf
a
mi
l
ya
n
df
r
i
e
n
d
s
.
Wea
r
e
i
n
c
r
e
d
i
b
l
yp
r
i
v
i
l
e
g
e
dt
oh
a
v
eg
o
t
t
h
i
sa
l
l
a
l
o
n
gw
i
t
ht
h
e
a
c
h
i
e
v
e
me
n
t
o
f
o
u
r
e
B
o
o
kp
r
o
j
e
c
t
.
I
t
r
e
q
u
i
r
e
sal
o
t
o
f
e
f
f
o
r
t
f
r
o
me
a
c
hi
n
d
i
v
i
d
u
a
l
i
n
v
o
l
v
e
di
nt
h
i
sp
r
o
j
e
c
t
a
n
dw
ew
o
u
l
d
f
r
o
me
a
c
hi
n
d
i
v
i
d
u
a
l
i
n
v
o
l
v
e
di
nt
h
i
sp
r
o
j
e
c
t
a
n
dw
ew
o
u
l
d
l
i
k
et
ot
h
a
n
kt
h
e
m.
Wew
o
u
l
dl
i
k
et
oa
c
k
n
o
w
l
e
d
g
ew
i
t
h
t
h
a
n
k
st
oP
u
a
nWa
nN
u
r
Wa
h
i
d
a
hb
i
n
t
i
H
a
s
h
i
mf
o
r
g
r
a
n
t
i
n
g
u
sa
no
p
p
o
r
t
u
n
i
t
yt
od
ot
h
i
se
B
o
o
kp
r
o
j
e
c
t
a
n
dp
r
o
v
i
d
i
n
g
u
sw
i
t
ha
l
l
g
u
i
d
a
n
c
e
,
p
a
t
i
e
n
c
e
,
a
n
ds
u
p
p
o
r
t
,
w
h
i
c
hma
d
eu
s
c
o
mp
l
e
t
et
h
ee
B
o
o
kp
r
o
j
e
c
t
d
u
l
y
.
Wew
o
u
l
da
l
s
ol
i
k
et
o
t
h
a
n
kP
u
a
nS
a
mi
h
a
hb
i
n
t
i
A
b
d
u
l
L
a
t
i
f
f
o
r
p
r
e
s
e
n
t
i
n
g
e
n
d
l
e
s
ss
u
p
p
o
r
t
,
d
e
s
p
i
t
eh
a
v
i
n
gab
u
s
ys
c
h
e
d
u
l
e
.
e
n
d
l
e
s
ss
u
p
p
o
r
t
,
d
e
s
p
i
t
eh
a
v
i
n
gab
u
s
ys
c
h
e
d
u
l
e
.
Wea
r
e
t
h
a
n
k
f
u
l
f
o
r
t
h
ec
o
n
s
i
s
t
e
n
t
e
n
c
o
u
r
a
g
e
me
n
t
,
s
u
p
p
o
r
t
,
a
n
d
s
u
p
e
r
v
i
s
i
o
n
.
A
l
s
o
,
w
ew
o
u
l
dl
i
k
et
oc
o
n
t
i
n
u
eo
u
r
g
e
n
u
i
n
e
e
s
t
e
e
mst
oa
l
l
s
t
a
f
f
f
o
r
t
h
e
i
r
t
i
me
l
ys
u
p
p
o
r
t
.
A
c
k
n
o
w
l
e
d
g
e
me
n
t
“
“
e
B
o
o
ki
same
d
i
u
mt
oe
n
h
a
n
c
et
h
ed
i
g
i
t
a
l
l
i
b
r
a
r
yt
h
a
t
w
i
l
l
b
ee
n
a
b
l
eu
n
l
i
mi
t
e
da
c
c
e
s
sg
l
o
b
a
l
l
yf
o
r
2
4
h
o
u
r
sa
n
d7d
a
y
s
aw
e
e
kt
ot
h
er
e
q
u
i
r
e
di
n
f
o
r
ma
t
i
o
na
n
di
t
w
i
l
l
h
e
l
pu
s
e
r
st
o
q
u
i
c
k
l
yr
e
t
r
i
e
v
ea
n
da
c
c
e
s
ss
p
e
c
i
f
i
cr
e
s
e
a
r
c
hma
t
e
r
i
a
l
s
e
a
s
i
l
y
,
q
u
i
c
k
l
y
,
a
n
de
f
f
e
c
t
i
v
e
l
y
.
T
h
i
se
B
o
o
ki
sap
r
a
c
t
i
c
a
l
r
e
s
o
u
r
c
ef
o
r
a
c
a
d
e
mi
cd
e
p
a
r
t
me
n
t
a
n
ds
t
u
d
e
n
t
so
f
I
n
f
o
r
ma
t
i
o
nT
e
c
h
n
o
l
o
g
ya
n
dC
o
mmu
n
i
c
a
t
i
o
n
,
M
a
l
a
y
s
i
a
P
o
l
y
t
e
c
h
n
i
ct
h
a
t
o
f
f
e
r
sD
F
P
4
0
2
0
3P
y
t
h
o
nP
r
o
g
r
a
mmi
n
g
P
o
l
y
t
e
c
h
n
i
ct
h
a
t
o
f
f
e
r
sD
F
P
4
0
2
0
3P
y
t
h
o
nP
r
o
g
r
a
mmi
n
g
c
o
u
r
s
e
.
M
a
i
n
t
a
i
n
i
n
gap
r
a
c
t
i
c
a
l
p
e
r
s
p
e
c
t
i
v
e
,
B
a
s
i
cP
y
t
h
o
n
P
r
o
g
r
a
mmi
n
ga
c
q
u
a
i
n
t
sy
o
uw
i
t
ht
h
ew
o
n
d
e
r
f
u
l
w
o
r
l
do
f
p
r
o
g
r
a
mmi
n
g
.
T
h
i
se
B
o
o
ki
sas
t
a
r
t
i
n
gp
o
i
n
t
f
o
r
t
h
o
s
ew
h
o
j
u
s
t
s
t
a
r
t
e
dt
ol
e
a
r
nt
h
eB
a
s
i
cP
y
t
h
o
np
r
o
g
r
a
mmi
n
g
.
T
h
e
b
a
c
k
b
o
n
eo
f
a
n
yp
r
o
g
r
a
mmi
n
g
,
w
h
i
c
hi
st
h
ed
a
t
as
t
r
u
c
t
u
r
e
a
n
dc
o
mp
o
n
e
n
t
ss
u
c
ha
ss
t
r
i
n
g
s
,
l
i
s
t
,
e
t
c
.
,
h
a
v
eb
e
e
n
i
l
l
u
s
t
r
a
t
e
dw
i
t
hma
n
ye
x
a
mp
l
e
sa
n
de
n
o
u
g
hp
r
a
c
t
i
c
e
st
o
i
l
l
u
s
t
r
a
t
e
dw
i
t
hma
n
ye
x
a
mp
l
e
sa
n
de
n
o
u
g
hp
r
a
c
t
i
c
e
st
o
i
n
s
t
i
l
al
e
v
e
l
o
f
s
e
l
f
-
c
o
n
f
i
d
e
n
c
ei
nt
h
er
e
a
d
e
r
.
Y
o
uw
i
l
l
e
x
p
l
o
r
et
h
ef
o
u
n
d
a
t
i
o
no
f
P
y
t
h
o
np
r
o
g
r
a
mmi
n
ga
n
dl
e
a
r
n
h
o
wP
y
t
h
o
nc
a
nb
ema
n
i
p
u
l
a
t
e
dt
oa
c
h
i
e
v
ef
i
n
a
l
e
x
p
e
c
t
e
d
r
e
s
u
l
t
s
.
T
h
et
o
p
i
c
si
nt
h
i
se
B
o
o
kc
o
n
s
i
s
t
o
f
t
h
e
i
n
t
r
o
d
u
c
t
i
o
nt
op
y
t
h
o
n
,
b
a
s
i
cp
r
o
g
r
a
me
l
e
me
n
t
s
,
f
u
n
c
t
i
o
n
a
n
do
b
j
e
c
t
-
o
r
i
e
n
t
e
d
.
T
h
i
se
B
o
o
ka
l
s
op
r
o
v
i
d
eq
u
i
c
kr
e
v
i
e
w
t
ot
e
s
t
t
h
eu
n
d
e
r
s
t
a
n
d
i
n
g
,
t
h
e
o
r
ye
x
e
r
c
i
s
e
sa
n
de
x
a
mp
l
e
s
t
ot
e
s
t
t
h
eu
n
d
e
r
s
t
a
n
d
i
n
g
,
t
h
e
o
r
ye
x
e
r
c
i
s
e
sa
n
de
x
a
mp
l
e
s
o
f
p
r
o
g
r
a
mmi
n
ge
x
e
r
c
i
s
e
s
.
A
b
s
t
r
a
c
t
“
“
1
TABLE OF CONTENT
CHAPTER 1: INTRODUCTION TO PYTHON PROGRAMMING 3
DEFINE PYTHON PROGRAMMING 4
DESCRIBE BASIC PRINCIPLES OF PYTHON 5
INTERACTIVELY USING THE PYTHON INTERPRETER 6
RUNNING PYTHON FILE 6
USING PYTHON IN IDE 7
INSTALL AND SET UP PYTHON ENVIRONMENT 7
QUICK REVIEW 13
CHAPTER 2: PYTHON PROGRAM ELEMENTS 14
PYTHON SYNTAX 15
A QUICK LOOK AT PYTHON PROGRAM 15
VARIABLE AND DATA TYPES 17
TYPE CASTING 21
PYTHON NAMING VARIABLE 24
PYTHON COMMENT 25
SINGLE LINE COMMENT 25
MULTI-LINE COMMENT 25
STRING LITERALS FOR MULTI-LINE COMMENTS 26
OPERATORS AND OPERATOR PRECEDENCE 27
ARITHMETIC OPERATORS 27
ASSIGNMENT OPERATORS 29
COMPARISON OPERATORS 31
LOGICAL OPERATOR 33
OPERATOR PRECEDENCE 34
CONDITIONAL STATEMENT 35
THE IF STATEMENT 35
THE IF-ELSE STATEMENT 38
THE ELIF STATEMENT 40
THE NESTED IF STATEMENT 41
2
LOOPING STATEMENT 43
THE WHILE STATEMENTS 43
THE FOR STATEMENT 44
T BREAK STATEMENTS 46
THE CONTINUE STATEMENT 46
ORDERED AND UNORDERED DATA STRUCTURE 47
TUPLE 47
LIST 51
SET 53
DICTIONARY 56
QUICK REVIEW 59
PROGRAMMING EXERCISES 59
CHAPTER 3: FUNCTION AND OBJECT-ORIENTED 60
FUNCTION 61
BUILT-IN FUNCTION 62
DEFINE AND CALL FUNCTION 63
FUNCTION WITH PARAMETER(S) 64
RETURNING VALUES FROM FUNCTION 66
DEFAULT ARGUMENT 69
NAMED ARGUMENT 71
IMPORT AND USE MODULES 72
CREATE USER-DEFINED MODULE 73
BUILT-IN MODULE 75
OBJECT-ORIENTED AND ITS BASIC COMPONENT 76
DEFINE AND INSTANTIATE CLASS 78
DEFINING DEFAULT STRING REPRESENTATION 82
ADDING INSTANCE METHOD 82
ANOTHER EXAMPLE: CLASS PERSON 86
CLASS INHERITANCE 88
METHODS OVERRIDING 93
QUICK REVIEW 95
PROGRAMMING EXERCISES 96
REFERENCES 98
c
h
a
p
t
e
r1
:
i
n
t
r
o
d
u
c
t
i
o
nt
o
p
y
t
h
o
np
r
o
g
r
a
mmi
n
g
A
t
t
h
ee
n
do
f
t
h
i
sc
h
a
p
t
e
r
y
o
uw
i
l
l
a
b
l
et
o
:
•
D
e
f
i
n
eP
y
t
h
o
nP
r
o
g
r
a
mmi
n
g
•
D
e
s
c
r
i
b
eB
a
s
i
cP
r
i
n
c
i
p
l
e
so
f
P
y
t
h
o
n
•
I
n
s
t
a
l
l
i
n
gA
n
dP
y
t
h
o
nE
n
v
i
r
o
n
me
n
t
S
e
t
u
p
4
Define Python Programming
Python is an object-oriented and high-level programming language. Python is similar
to other programming language that you might have heard of such as C++, JavaScript,
Microsoft’s C#, and Oracle’s Java. Python has been around for a long time. It is created
by Guido van Rossum at the Centrum Wiskunde & Informatica (CWI) in the Netherlands
in the 1980s.
This increasing interest in Python is driven by several different factors:
• The language is flexible, simple which make it easy to learn
• Python supports modules and packages, which encourages program
modularity and code reuse.
• Can be run on (almost) any operating system.
• The availability of a wide range of libraries (modules) that can be used to
extend the basic features of the language.
• Its use by the Data Science community where it provides a more standard
programming language especially in the area of machine learning
• The ability of the language to connect existing components available nowadays
such as IoT devices, web pages, and machine learning easily.
• It is Free!
Currently, there are two main versions of Python called Python 2 and Python 3.
• Python 2 was launched in October 2000 and still is very widely used.
• Python 3 was launched in December 2008 and is a major revision to the
language that is not backward compatible.
The issue between the two versions can be highlighted by the simple print facility:
• In Python 2 this is written as print 'Hello World'
• In Python 3 this is written as print('Hello World')
It may not look much of a difference but the inclusion of the ‘ ( ) ‘ marks a major
change and means that any code written for one version of Python will probably not
run on the other version.
5
Describe Basic Principles of Python
Below are some principles of Python.
1. Hybrid programming language
o The code can be written in a procedural and object-oriented manner.
2. Interpreted language
o The source code of a Python is converted into bytecode that is then executed
by the Python virtual machine. There is no explicit compilation step in Python.
3. Dynamically Typed Language
o The data type checking is performed at runtime.It doesn’t know about the type
of the variable until the code is run.
o In Python, the variable is declared without the need to specify the data type.
4. Automatic memory management and garbage collection
o The garbage collector automatically frees up the memory which was allocated
by the program but is no longer referenced.
5. Can be used for many types of applications:
o Web Development
o Python for Scientific development
o Data Science and Analysis
6. Can be run using several ways:
o Interactively using the Python interpreter
o Stored in a file and run using the Python command
o From within a Python IDE (Integrated Development Environment) such as
PyCharm.
6
Interactively Using the Python Interpreter
Once Python has been installed, you can open a Command Prompt window (Windows)
or a Terminal window (Mac) and type Python into the prompt.
Below is the image shown for a Windows machine:
Running Python File
We can also save the Python commands into a file. For example, given a file containing
the following file (called hello.py) with the 4 commands in it:
To run the hello.py program on a PC using Windows, we can use Command Prompt :
• Navigate to the location of the file (hello.py) using the change directory (cd)
command
• Use python command followed by the name of the file:
7
Using Python in IDE
We can also use an IDE such as PyCharm to write and execute our Python program. The
same program is shown using PyCharm below:
The above figure shows a simple set of commands that are again listed in a file called
hello.py. The program has been run on within the IDE and the output is shown in an
output console at the bottom of the display.
Install and Set Up Python Environment
First, we will show you how to install Python Environment and then use the command
prompt to code the Python. The steps below used Windows platform to install and set
up Python.
Follow the following steps:
Step 1: Browse for https://www.python.org/. Go To Downloads Section and choose
Windows.
8
Step 2: Next from page Python Release For Windows, choose the latest Python 3
Release.
Step 3: On the page of the latest version of python, look for the Files section.
Step 4: Download Python installer either 32bits or 64bits depending on your
Operating System.
9
Step 5: Click on the Python Installer. By default the checkbox Add Python 3.9 to PATH
is unchecked. Make sure to check on Add Python 3.9 to PATH. Then click on Install
Now.
Step 6: On the computer open Command Prompt. Python is successfully installed if
symbol >>> appears on the Command Prompt.
Step 7: Type the following code:
print(‘Hello World’)
Step 8: Test the following code and observe the output.
print(5 + 10)
num1 = 100
num2 = 10
multiply = num1 * num2
print(multiply)
10
Next, we will install PyCharm, the Python IDE. Follow the following steps.
Step 1: Browse for https://www.jetbrains.com/pycharm/, then click on the Download
button.
Step 2: On the download page, choose the community download.
Step 3: Click on the PyCharm Installer. Use the default installation setting.
By now you have successfully installed the PyCharm IDE!
11
Step 3: Then, start the PyCharm IDE. Once started, you will be asked if you want to
import any settings you may have had for another version of PyCharm. At this point,
select ‘Do not import settings.
You should now be presented with the landing screen for PyCharm
Step 4: Click on the ‘Create New Project’ option in the landing dialog. Use default
location but change the name of the project to python_intro. Click Create.
12
Step 6: To create a New Python File, click on File -> New -> Python File. Put
helloWorld.py as the file name.
Step 7: Type the following code to the pyCharm editor.
print("hello World")
print("Politeknik Balik Pulau")
Step 8: To run the code, click on Run -> Run. Choose helloWorld
13
Quick Review
1. Python is an interpreted, object-oriented, high-level programming language with
dynamic semantics.
2. There are two main versions of Python called Python 2 and Python 3.
3. The basic principles of Python are :
• Hybrid programming language
• Interpreted language
• Dynamically Typed Language
• Includes all the features that one expects from a programming language
• Automatic memory management and garbage collection
4. There are several ways to run a Python program, including:
• Interactively using the Python interpreter
• Stored in a file and run using the Python command
• From within a Python IDE such as PyCharm.
c
h
a
p
t
e
r2
:
p
y
t
h
o
np
r
o
g
r
a
me
l
e
me
n
t
A
t
t
h
ee
n
do
f
t
h
i
sc
h
a
p
t
e
r
y
o
uw
i
l
l
a
b
l
et
o
:
•
E
x
p
l
a
i
nv
a
r
i
a
b
l
e
sa
n
dd
a
t
at
y
p
e
si
nP
y
t
h
o
n
•
A
p
p
l
yOp
e
r
a
t
o
r
sa
n
dOp
e
r
a
t
o
r
sP
r
e
c
e
d
e
n
c
e
•
D
e
f
i
n
ea
n
dw
r
i
t
eaC
o
n
d
i
t
i
o
n
a
l
a
n
dL
o
o
p
i
n
g
•
P
r
o
c
e
s
so
r
d
e
r
e
da
n
du
n
o
r
d
e
r
e
dd
a
t
as
t
r
u
c
t
u
r
e
15
Python Syntax
In this chapter, we will learn the basic elements and concepts of programming using
Python. There are two basic syntaxes in Python :
• It is not necessary to end a command with a semicolon.
• The indentation (refers to the space at the beginning of a code line) in Python
is very important. Python uses indentation to indicate a block of code.
A Quick Look At Python Program
Let's start with a quick look at a simple program to print out ‘Hello World’.
print('Hello World')
To execute the code above, you can use any text editor or IDE of your choice. The
example below use PyCharm to write and execute the code.
The print() statement will print everything that you pass inside the parenthesis.
Thus, when we run this program, the string ‘Hello World’ is printed on the screen.
16
Let us make our program a little more interesting. Let the program ask our name and
say hello to us. The program has two additional statements.
The first statement is:
This statement executes a function called input(). This function has an argument
which is a statement that is used to prompt for user’s input. In this case, it will print the
statement that you provide as a prompt to the user and wait until the user types
something. The value that the user typed is stored in a variable name.
The second statement is:
We will use the print() statement again, but this time the print() takes two data.
The data is separated by a comma. In this case, we passed a string ‘Hello’ and the value
referenced by the variable name.
17
Variable and Data Types
A variable is used to store value. A variable is stored in the computer’s memory and the
value can change depending on the program execution. A variable is created the
moment you first assign a value to it. Variables do not need to be declared with any
particular type.
The syntax to declare a varible is :
variable_name = value
Example: A program with two variables x and y.
Output :
5
Auni
The x and y are the variables with values “5” and “Auni” assign to the x and y,
respectively. The data type of a variable is automatically given to the variable based on
the values assigned to the variable. In this example, the x variable is a type of integer
and y is a type string.
The diagram below shows the data type in Python.
x = 5
y = "Auni"
print(x)
print(y)
18
Table below is the description of each data types in Python.
Name Class
Type
Description
Integer <int> Whole number such as 5, 23, 100, 300
Floating
Number
<float> Number with decimal points such as 10.1, 5.443, 0.3
Complex
Number
<complex> Complex numbers are comprised of a real part and an
imaginary part:
a = 8 + 5j
Boolean <bool> Has two values either TRUE or FALSE:
10>9 will return TRUE
10<9 will return FALSE
String <string> Sequence of character defined in sigle, double or triple
quote such as 'Hello', "525", '''xxx'''
Set <set> Unordered collection of unique object:
{"apple", "papaya", "durian"}
Dictionary <dict> Unordered collection of key->value pair:
{"alia" : 4.00, "aiman" : 3.87}
List <list> Ordered sequence of obeject :
["Aileen", 19.0, "aileen@gmail.com"]
Tuple <tuple> Ordered immutable sequence of object:
("Aileen", 19.0, "aileen@gmail.com")
19
The type of variable can dynamically change as the program being executed. This is
referred to as Dynamic Typing. To illustrate dynamic typing, refer to the illustration
below.
Initially, the x has the value ‘Sally’ which is a type of string. In the second line, the
program resets x = 10 which means the value in the variable x is replaced with 10.
Python automatically changes the type of x from string to integer. Then the program
again resets the x = 10.9 and the data type is changed to float.
In Python, we do not need to worry about what data type should we assign to the
variable. The data type will be assigned automatically by Python once the value is
assigned to the variable.
It is possible to find out what type of variable currently holds using the built-in
type() function. This function takes a variable name and will return the type of data
held by the variable.
Example: Use built-in function type() to get the type of variable
num1 = 10
print(type(num1))
num2 = 3.89
print(type(num2))
name = "Haniey"
print(type(name))
20
Output :
<class 'int'>
<class 'float'>
<class 'str'>
The type of item data (such as integer) determines what it is legal to do with the data
and what the effect of various actions will be.
For example, the effect of using a ‘+’ operator
• If the data type numbers are involved, then the plus operator will add the
numbers together.
• If strings are involved, then the string will be concatenated (combine) together.
Example: Use plus operator to data type number and string
Output :
30.5
Python Programming
Referring to the code above, str1,str2, and str3 is all type of string. A string is a sequence
of characters that is declared either in a single, double, or triple quotes. Single and
double quotes are the same. You can use single quotes for string literals like 'My Village'
but use double quotes for strings that are likely to contain single-quote characters as a
part of the string itself like the statement "You’ve got an error".
num1 = 10
num2 = 20.5
sum = num1 + num2
print(sum)
str1 = "Python "
str2 = 'Programming '
str3 = str1 + str2
print(str3)
21
However, Python's triple quotes are a bit different. Triple quotes allow the string
output to span multiple lines, including verbatim NEWLINEs, TABs, and any other
special characters.
Example: Use single, double and triple-quotes
Output :
My Cat
It’s mine
My lovely
Cat
Type Casting
As we mentioned previously, the data type of the variable is automatically assigned by
the Python environment when the value is assigned to the variable. However, there are
many times when we develop a program we may want to specify or change the data
type that we want.
Type Casting is the method to convert the variable data type into a certain data type to
the operation required to be performed by users.
str1 = 'My Cat'
str2 = "It’s mine"
str3 = ''' My lovely
Cat
'''
print(str1)
print(str2)
print(str3)
22
Casting in Python can be done using the following constructor functions:
• int ( ) :
o construct an integer number from an integer, float, or string.
• float ( )
o construct float number from an integer, a float, or a string literal
• str ( )
o constructs a string from a wide variety of data types, including strings,
integer, and float literals.
Example: Casting a variable
Output :
5.9
<class 'float'>
5
<class 'int'>
The above example shows the type of variable which is initially a floating number that
is changed into the integer data type using statement a = int(a). The value for the
variable changes from 5.9 to 5. You may be wondering why the value is not round up
to 6 since 5.9 is close to 6. Casting will just remove the decimal places in the float, it will
not round up or down to an integer value.
The most used typecasting in the program is when using the input() function to receive
input from a user. The variables received from the input() function is automatically data
type string.
Therefore, if you want your program to get the integer value from a user, you must cast
the variable into either integer or float.
a = 5.9
print(a)
print(type(a))
a = int(a)
print(a)
print(type(a))
23
Suppose you have the following program.
salary = input("Your salary : ")
bonus = 150
payment = salary + bonus
This program will generate a type error message because:
• salary is a string data type (all variables received from an input is automatically
assigned to a string)
• bonus is an integer data type
• The plus(+) operation is not legal between type string and integer, thus will
generate the following error.
To correct the code, we must cast the input to the integer data type. Refer to the
following example below.
Example: Casting variable receive from input()
Output :
Your salary : 1000
1150
After the variable salary has been cast to number (either integer or float), the plus
operation between salary and bonus produced the correct output.
salary = int(input("Your salary : "))
bonus = 150
payment = salary + bonus
print(payment)
24
Python Naming Variable
In naming the variable, the very widely used naming convention is:
• The first character of a variable must be an alphabetic letter (upper or lower
case) or the underscore. The remaining characters (if any) may be alphabetic
characters (upper or lower case), the underscore, or a digit
• No other characters (including spaces) are permitted.
• A reserved word cannot be used as an identifier
Some of the accepted and not accepted naming variables are represented in the table
below.
Variables Remarks
my_name, user_name,
account_name, count,
where_we_live,is_okay,
is_correct, status_flag
Accepted variables name
1_name Not Accepted. A Variable’s name cannot start
with a number.
user name Not Accepted. Variable’s name cannot have
space in between
where-we-live Not Accepted. Variable’s name cannot have
space and other characters than underscore (_)
The following reserved word cannot be used as a variable name.
25
Python Comment
Comments are descriptions that help programmers to understand better the
intention and functionality of the program.
Using comments in programs will make our code more understandable. It makes the
program more readable which helps us remember why certain blocks of code were
written.
Single Line Comment
Python used the # symbol to write a single-line comment. Comments can be placed at
the beginning or at the end of a line and Python will ignore the rest of the line.
Example: Python Single-line comment
Output :
Hello World
Hello World
Multi-line Comment
Python does not have syntax for multi-line comments. To add a multiline comment you
could insert a # for each line.
Example: Python Multi-line comment
Output :
Such a wonderful day!
# printing a string
print('Hello world')
print('Hello world')# printing a string
# it is a
# multiline
# comment
print("Such a wonderful day!")
26
String Literals for Multi-line Comments
Another thing that you need to know about string in Python is, the string literal will
ignore the statement that is not assigned to a variable.
Example: Use an unassigned string as a comment.
Output :
This also can be a comment.
Here, we can see that the first line of the program is a string but is not assigned to any
variable or function. So, the interpreter ignores the string.
Similarly, we can use multiline strings (triple quotes) to write multiline comments.
Example: Use an unassigned string as a multi-line comment.
Output :
Hello World
'this is an unassigned string as a comment '
print("This also can be a comment")
'''
I am a
multiline comment!
'''
print("Hello World")
27
Operators and Operator Precedence
Operators are used to perform operations on variables and values. In the previous
example, we use the plus(+) operator to add between two values.
Python divides the operators into the following groups:
i. Arithmetic operators
ii. Assignment operators
iii. Comparison operators
iv. Logical operators
v. Identity operators
vi. Membership operators
vii. Bitwise operators
Arithmetic Operators
Arithmetic operators are used to perform mathematical operations like addition,
subtraction, multiplication, etc.
Assume we have two variables:
a = 5
b = 2
The operation using the arithmetic operators is described in the table below.
Operator Expression Result Meaning
Addition (+) a + b 7 Add two values.
Subtract (-) a – b 3 Subtract one value from another
Multiplication
(*)
a * b 10 Multiply two numbers
Division (/) a / b 2.5 Divide left operand by the right operand
Modulus (%) a % b 1 The remainder from a division of left
operand by the right operand
Exponent (**) a ** b 25 Exponential value (a power of b)
Floor (//) a // b 2 Perform the division and only give the
integer quotient.
28
Example: Use arithmetic operators.
Output :
7 - 3 = 4
7 * 3 = 21
7 ^ 3 = 343
7 % 3 = 1
Example: Program to convert kilogram to grams
Output :
Enter value in kilograms : 1.5
1.5 kg = 1500.0 g
x = 7
y = 3
res = x - y
print( x , '-' , y ,'=' , res)
res = x * y
print( x , '*' , y ,'=' , res)
res = x ** y
print( x , '^' , y ,'=' , res)
res = x % y
print( x , '%' , y ,'=' , res)
val1 = float(input('Enter value in kilograms : '))
gram = val1 * 1000
print(val1, 'kg = ' , gram , 'g')
29
Example: Mathematical operation allowed on a string
Output :
*Politeknik*
*****
*****Politeknik*****
Assignment Operators
Assignment operators are used in Python to assign values to the variables.
a = 5 is a simple assignment operator that assigns the value 5 to the variable a. Python
as a compound operator like a+=5 that add 5 to the variable a. a+=5 is equivalent to a
= a + 5.
Assume we have:
x= 6
y = 3
The operation using the assignment operator is describe in the table below.
Operator Expression Result Meaning
Assignment (=) x = y + 2 5 x = 3 + 2
Addition Assignment (+=) x += y 9 x = x + y
Subtraction Assignment (-=) x -= y 3 x = x - y
Multiplication Assignment (*=) x *= b 18 x = x *y
Division Assignment (/=) x /= y 2 x = x / y
Modulus Assignment (/=) x %= y 0 x = x % y
Exponential Assignment (/=) x **= y 216 x = x** y
Floor Assignment (//=) x //= y 0 x = x // y
a = '*'
b = 'Politeknik'
c = a + b + a
print(c)
a = 5 * a
print(a)
c = a + b + a
print(c)
30
Example: Use the assignment operator on the integer values.
Output :
Initially value of z is 0
Current value of z is 25
Current value of z is 40
Current value of z is 600
The figure below shows how the values of the variable z change throughout the
program execution.
x = 15
y = 10
z = 0
print("Initially value of z is",z)
z = x + y
print("Current value of z is",z)
z += x
print("Current value of z is",z)
z *= x
print("Current value of z is", z)
31
Comparison Operators
Comparison operators or also known as the relational operator are used to compare
values between two operands and returns answer as True or False.
The table below shows the comparison operator, its expression, and the result.
Operator Expression Result
Less than (<) 5 < 2
5 < 5
False
False
Greater than (>) 5 > 2
5 > 5
True
False
Less than (<=) 5 <= 2
5 <= 5
False
True
Greater than (>=) 5 >= 2
5 >= 5
True
True
Equal to (==) 5 == 2
5 == 5
False
True
Not equal to (!=) 5 != 2
5 != 5
True
False
Example: Use comparison operator to compare between two number values.
Output :
False
True
False
print(10<4)
print(5>=5)
print(5!=5)
32
It is obvious when you use the comparison operator with the numbers. The following
example uses the comparison operator two strings:
Example: Use comparison operator to compare between two string values
Output :
True
True
False
The expression 'a' > 'b' returns True because the letter 'a' is before the letter 'z’. The
same goes to the expression 'apple' < 'banana' returns True because the letter a in
apple is before the letter b in banana. For the third statement, the first letter in durian
and dragon are the same, then it will compare with the second letter which is the letter
u and r. Since the letter 'u' comes after the letter r, the expression 'durian' < 'dragon'
returns False.
Example:
Output :
True
True
False
print('a'<'z')
print('apple'<'banana')
print('durian'<'dragon')
print('a'<'z')
print('apple'<'banana')
print('durian'<'dragon')
33
Logical Operator
Logical operators are used on conditional statements (either True or False). They
perform Logical AND, Logical OR, and Logical NOT operations.
The table below shows the description of the logical operator.
Operator Expression Result Meaning
and True and True
True and False
False and True
False and False
True
False
False
False
The result will be true if both the
operands are true, otherwise, it returns
false.
or True or True
True or False
False or True
False or False
True
True
True
False
The result will be true if both or either
of the operand is true, otherwise, it
returns false.
not not True
not False
False
True
Reverse the value of the operand. The
result will be true when the operand is
false and will return false if the operand
is true.
34
Operator Precedence
If an expression has more than one operator, for example, expression 5 + 7 * 2, to
determine which operation to perform first, the rules in operator precedence must be
used.
Figure below shows the execution of expression 10 + 7 * 2. This expression will be
calculated as 10 + (7 * 2) not as (10 + 7) * 2.
The operator precedence is listed in the following table.
Priority Operator Description Associativity
1 () Parenthesis left to right
2 ** Exponent left to right
3 *, /, % Multiplication, Division, Modulus left to right
4 +, - Addition, Subtraction left to right
5 < , <=
> , >=
Less than/less than or equal to
Greater than/greater than or equal
to
left to right
6 == , != Equal to, not equal to left to right
7 not Logical NOT left to right
8 and Logical AND left to right
9 Or Logical OR left to right
35
Example: Use operator precedence
Output :
220.0
40.0
Conditional Statement
You've now learned quite a bit of Python code from the previous section. Everything
you have seen so far has consisted of sequential execution, in which statements are
always performed one after the next, in exactly the order specified.
But the world is often more complicated than that. Frequently, a program needs to skip
over some statements or choose between alternate sets of statements to execute.
That is where the conditional statement comes in. The conditional statement is the if
statement used to perform decision making. It allows for the conditional execution of
a statement or group of statements based on the value of an expression.
Here is the type of conditional statement in Python.
• If
• If..Else
• Nested if
• elif
The if statement
The if statement is the most fundamental decision-making statement. It takes an
expression, for example, expression if (x > 3), and checks if the expression evaluates to
True then the block of code in if statement will be executed. If the expression evaluates
to False, then the block of code is skipped.
exp = 200 - 100 / 10 + 3 * 10
print(exp)
exp = (200 - 100) / 10 + 3 * 10
print(exp)
36
The syntax for the if statement is:
if expression:
statement_1
statement_2
………………….
statement_n
Example: Use if statement to check negative number
Output 1:
Enter a number: -4
-4 is negative
End of Program
The if statement checks if the input is less than zero. If the expression return True, it
will execute the block of if statement which prints the input as negative. If the
conditional statement returns False, it will execute the next line of code after the if
block.
num = int(input('Enter a number: '))
if (num < 0):
print(num, 'is negative')
print('End of Program')
bock of if
Output 2:
Enter a number: 10
End of Program
37
Example: Use more than one if statement
Output 1:
Enter Your Score : 100
Exceptional!
Output 4:
Enter Your Score : 12
Try again next time
The example used four(4) if statements to check the score and print the message. The
block of if statement is executed when the expression returns True.
Example: Use more than one if statement
score= int(input('Enter Your Score : '))
if (score == 100):
print('Exceptional!')
if (score < 100 and score >=80):
print('Excellent!')
if (score < 80 and score >=60):
print('Well Done!')
if (score < 60):
print('Try again next time')
Output 2:
Enter Your Score : 88
Excellent!
Output 3:
Enter Your Score : 79
Well Done!
score1= int(input('English Score : '))
score2= int(input('Mathematic Score : '))
print("You can choose: ")
if (score1 >= 80):
print('English course')
if (score2 >= 85):
print('Mathematic course')
if (score1 >= 90 and score2 >=95):
print('Science course')
38
Output 1:
English Score : 80
Mathematic Score : 70
You can choose:
English course
The if-else statement
From the name itself, we get the clue that the if-else statement checks the expression
and executes the if block when the expression is True otherwise it will execute the
else block of code. The else block should be right after if block and it is executed when
the expression is False.
The syntax for the if-else statement is:
if expression:
statement(s)
………………….
statement_n
else:
statement_1
………………….
statement_n
bock of if
bock of else
Output 2:
English Score : 98
Mathematic Score : 98
You can choose:
English course
Mathematic course
Science course
39
Example: Use an if-else statement.
Output :
Enter a number: 12
Number is non-negative
End of Program
Example: Use more than one if-else statement.
Output :
Enter a number: 20
20 is even number
the number is larger than 10
num = int(input('Enter a number: '))
if (num < 0):
print(num, 'is negative')
else:
print('Number is non-negative')
print('End of Program')
Output 2:
Enter a number: -10
-10 is negative
End of Program
num = int(input('Enter a number: '))
if (num % 2 == 0):
print(num, 'is even number')
else:
print(num, 'is odd number')
if (num>10):
print('the number is larger than 10')
else:
print('the number is less than 10')
Output 2:
Enter a number: 7
7 is odd number
the number is less
than 10
40
The elif statement
The elif keyword is used to chain multiple conditions one after another. With an elif
statement, we can make a complex decision-making statements. The elif statement
helps you to check multiple expressions and it executes the code as soon as one of the
conditions evaluates to True.
The syntax for the if-elif-else statement is:
If expression1 :
statement
elif expression2 :
statement
…
...
else:
statement
Example: Use an if-elif-else statement.
Output :
How much is your saving? :200
Well Done
saving = float(input('How much is your saving? :'))
if saving==0:
print('Sorry, no saving')
elif saving<500:
print('Well Done')
elif saving<=1000:
print('That is a tidy sum')
elif saving>1000:
print('Welcome Sir')
else:
print('Thank You')
41
The nested if statement
The nested if statement is an if statement inside another if statement. With nested if,
it allows us to stack any number of if statements inside the block of another if
statement. They are useful when we need to make a series of decisions.
Example: Use nested if statement.
Output 1:
Enter integer value in range 1-10 :2
2 is in range
Done
val = int(input('Enter integer value in range 1-10 :'))
if val >=0:
if val <=10:
print(val, 'is in range')
else:
print(val, 'is too large')
else:
print(val, 'is too small')
print('Done')
Output 2:
Enter integer value in range 1-10 :20
20 is too large
Done
42
Example: Use nested if statement.
Output 1:
Select your ride
******************
1. Bike
2. Car
Choice :1
You have selected Bike.
a. Road Bike
b. Mountain Bike
------------------
Choose your bike: a
Nice Choice!
print('Select your ride')
print(18 * '*')
print('1. Bike')
print('2. Car')
choice = int(input('Choice :'))
if( choice == 1 ):
print( 'You have selected Bike.' )
print('a. Road Bike')
print('b. Mountain Bike')
print(18 * '-')
bike = input('Choose your bike: ')
if bike == 'a':
print('Nice Choice!')
elif bike == 'b':
print('Train your stamina')
else:
print('Wrong choice!')
elif( choice == 2 ):
print( 'You have selected Car' )
else:
print('Wrong choice!')
Output 2:
Select your ride
******************
1. Bike
2. Car
Choice :2
You have selected Car
43
Looping Statement
Loops are one of the most powerful and basic concepts in programming. A loop can
contain a set of statements that keeps on executing until a specific condition is reached.
Python has two primitive loop commands which are:
• While Loop
• For Loop
Other statements that can be used in looping
• Break – stop the loop even if the while condition is true
• Continue – stop the current iteration and continue with the next
The while statements
The while loop executes a block of code until the
specified condition becomes False.
The syntax for the while loop is:
while test_expression:
Body of while
Example: Use a while statement.
Output :
Starting
0 1 2 3 4 5 6 7 8 9 10
Done
count = 0
print('Starting')
while count<=10:
print(count, ' ', end='')
count+=1
print()
print('Done')
44
Example: Use while to print multiplication of two
Output :
2 4 6 8 10 12 14 16 18 20
The for statement
A for loop is used for iterating over a sequence (that is either a list, a tuple, a
dictionary, a set, or a string).
The loop through a set code a specified number of times, we can use the range()
function.
The range() function returns a sequence of numbers, starting from 0 by default and
increments by 1 (by default), and ends at a specified number.
The syntax for loop is:
for val in sequence:
body of for loop
n = 2
i = 1
product= 1
while(i<=10):
product = i * n
i+=1
print(product, '', end='')
45
The range () function
When using for loops in Python, the range() function is pretty useful to specify the
number of times the loop is executed. It yields a sequence of numbers within a
specified range.
The syntax or range():
range(start, stop, step)
• The first argument is the starting value. It is zero by default.
• The second argument is the ending value of the range.
• The third argument is the number of steps to take after each yield.
Example: Use for loop to print 1 to 9
Output :
1 2 3 4 5 6 7 8 9
Example: Use for loop to print from 0 to 10 increment by 2
Output :
0 2 4 6 8
Example: Use for loop to print from 7 to 20 increment by 1
Output :
7 8 9 10 11 12 13 14 15 16 17 18 19
for i in range(10):
print(i, ' ', end='')
for i in range(0,10,2):
print(i, ' ', end='')
for i in range(7,20):
print(i, '',end='')
46
The break statements
The break statement inside a loop is used to exit out of the loop. Sometimes in a
program, we need to exit the loop when a certain condition is fulfilled.
Example: Use break statement in a loop
Output :
1
2
3
Loop ended
The Continue Statement
The continue statement is used to skip the next statements in the loop. When the
program reaches the continue statement, the program skips the statements after
continue and the flow reaches the next iteration of the loop.
Example: Use continue statement in a loop
Output :
1
3
4
5
Loop ended
num = 0
while( num <10 ):
num +=1
if(num==3): break
print( num )
print("Loop ended")
num = 0
while( num <5 ):
num +=1
if(num==2): continue
print(num)
print("Loop ended")
47
Ordered and Unordered Data Structure
Previously we have learned some Python built-in data structures such as string, int,
float, and as well bools. However, these are not the only built-in data structure in
Python Another group of built-in data structures is known as collection types.
A collection is a single object representing a group of objects. These collection classes
are often used as the basis for more complex or application-specific data structures and
data types.
The table below shows the group of ordered and unordered data structures in
Python.
Ordered Unordered
Tuple Set
List Dictionary
Tuple
Tuples are an immutable ordered collection of objects:
• Tuples can have a mixture of different types and they are not restricted to
hold all elements of the same types.
• Each element in a tuple has a specific position (positive and negative index)
and that position does not change over time.
• Index in tuple start with 0 (for positive index) and -1(for negative index).
• The index starts from zero and goes till the number of elements minus one.
• It is not possible to add or remove elements from the tuple once it has been
created.
The figure below shows the representation of the tuple.
48
Creating Tuples
Tuples are created by typing a sequence of items, separated by commas. Optionally,
you can put the comma-separated values in parenthesis.
Example: Create a tuple
Output :
(1, 2, 5, 6)
('a', 'b', 'c', 'd')
()
(5, 3, 1)
('Aileen', 'Auni', 'Asbir', 1986, 1640, 1948)
Accessing Elements of a Tuple
Tuple can be accessed using an index (positive or negative) in square brackets.
Example: Access element in a tuple using an index.
tuple1 = (1,2,5,6)
tuple2 = ('a', 'b', 'c', 'd')
tuple3 = () #empty tuple
tuple4 = 5,3,1
tuple5 = ('Aileen', 'Auni', 'Asbir', 1986,1640, 1948)
print(tuple1)
print(tuple2)
print(tuple3)
print(tuple4)
print(tuple5)
tuple1 = (1,3,5,7)
print('Element at index 0 =>' , tuple1[0])
print('Element at index 2 =>' ,tuple1[2])
print('Element at index -3 =>' ,tuple1[-3])
print('Element at index -1 =>' ,tuple1[-1])
49
Output :
Element at index 0 => 1
Element at index 2 => 5
Element at index -3 => 3
Element at index -1 => 7
Slicing a Tuple
We can slice a tuple using the ranges of indexes, by specifying where to start and where
to end the range. As we know, the index starts from zero and goes till the number of
elements minus one. The range of indexes in a tuple can be positive and negative.
The following diagrams illustrate how the slicing occurs in the tuple.
tuple = (1, 3, 5, 7, 8, 9, 12)
new_tuple1 = tuple[1:4]
tuple = (1, 3, 5, 7, 8, 9, 12)
new_tuple2 = tuple[ :3]
50
tuple = (1, 3, 5, 7, 8, 9, 12)
new_tuple3 = tuple[ :3]
Example: Slicing a tuple
Output :
(3, 5, 7)
(1, 3, 5, 7)
(3, 5, 7, 8)
(1, 3, 5, 7)
(8, 9, 12)
tuple = (1,3,5,7,8,9,12)
new_tuple1 = tuple[1:4]
new_tuple2 = tuple[:4]
new_tuple3 = tuple[-6:-2]
new_tuple4 = tuple[:-3]
new_tuple5 = tuple[-3:]
print(new_tuple1)
print(new_tuple2)
print(new_tuple3)
print(new_tuple4)
print(new_tuple5)
51
Iterating Over Tuples
Apply for loop to iterate over a tuple.
Example: Use for loop to iterate a tuple.
Output :
Kelantan Perak Kedah 1987 1999
List
The list is also an ordered collection of objects. It is similar to tuple but the difference
between them is that lists are mutable(can change) while tuples are immutable(cannot
change).
List support all the features of the Tuple but as they are mutable it is also possible to:
• Insert/modify elements in a list
• remove elements
Creating List
Lists are created using square brackets positioned around the elements.
Example: Create a list
Output :
('John', 'Jane', 'Ringo', 'Ahmad')
tuple = ('Kelantan', 'Perak', 'Kedah', 1987,1999)
for val in tuple:
print(val, end=' ')
list = ('John', 'Jane', 'Ringo', 'Ahmad')
print(list)
52
Accessing Elements from a List
Same as tuples, the element in the list is accessible via index.
Example: Access element in a list
Output :
Jane
Ahmad
Ringo
('John', 'Jane', 'Ringo')
Insert into a List
To insert an element into an existing list, use the insert() method.
Syntax:
<list>.insert(<index>, <object>)
The insert() method takes an index indicating where to insert the element and an
object to be inserted.
Example: Insert into a list
Output :
['Adele', 'Madonna', 'Jackson']
['Adele', 'Hillary', 'Madonna', 'Jackson']
We have inserted the string ‘Hillary’into the index position 1 pushing ‘Madonna’ and
‘Jackson’ up one in the index within the List.
list = ('John', 'Jane', 'Ringo', 'Ahmad')
print(list[1])
print(list[-1])
print(list[2])
print(list[-4:3])
actor = ['Adele', 'Madonna', 'Jackson']
print(actor)
actor.insert(1,'Hillary')
print(actor)
53
Remove from a List
We can remove elements from a List using the remove() method.
Syntax:
<list>.remove(<object>)
Example: Remove value from a list
Output :
['Aileen', 'Auni', 'Asbir', 'Jerry', 'Tan']
['Aileen', 'Asbir', 'Jerry', 'Tan']
Set
Set is an unordered (unindexed) collection of mutable objects that does not allow
duplicates. Unlike tuple and list, set are not accessible using the index. In set, any
duplicate items will be considered as one.
Create a Set
A Set is defined using curly brackets ‘{}’.
Example: Create a set.
Output :
{'orange', 'apple', 'banana'}
Even though the ‘apple’ and ‘banana’ appear two times in the set declaration, the value
will consider as one because the set treats any duplication as one item.
stud = ['Aileen', 'Auni', 'Asbir', 'Jerry','Tan']
print(stud)
stud.remove('Auni')
print(stud)
basket = {'apple', 'orange','apple','orange','banana'}
print(basket)
54
Accessing Elements in a Set
As mentioned earlier, a set is unordered, so it is not possible to refer to elements of the
set using an index. To access the elements in the set, for loop can be used.
Example: Access element in the set using for statement
Output :
apple banana pear orange
The order of the output is not the same as defined in the code. Set is unordered, so
when we display the element in the set it will come out in random order.
Adding Items to a Set
Element in the set can be accessed using add() method. This method can add an item
at one time.
Syntax :
<set>.add(<object>)
Example: Add an item to a set
Output :
{'pear', 'orange', 'durian', 'banana', 'apple'}
basket = {'banana', 'orange','apple','pear'}
for item in basket:
print(item, end=' ')
basket = {'banana', 'orange','apple','pear'}
basket.add('durian')
print(basket)
55
Remove an Item From Set
Element in the set can be accessed using the remove() method. This method removes
a single item from a set.
Syntax :
<set>.remove(<object>)
Example: Remove an item from a set.
Output :
{'apple', 'orange', 'pear'}
Set Operations
The Set container also supports set like operations such as:
• Union (|): Combination of all values in two or more sets.
• Intersection (&): Common values between two or more sets.
• Difference (−): The set of values in the first set that is not in the second set.
• Symmetric difference (^): All the unique values in two or more sets.
Example: Use set operations
basket = {'banana', 'orange','apple','pear'}
basket.remove('banana')
print(basket)
s1= {'a', 'b', 'c', 'd', 'e','f'}
s2= {'a', 'e', 'i', 'o', 'u'}
print("Union s1 | s2 :", s1|s2)
print("Intersection s1 | s2 :", s1&s2)
print("Difference s1 - s2 :", s1-s2)
print("Difference s2 - s1 :", s2-s1)
print("Symetric Difference s1 ^ s2 :", s1^s2)
56
Output :
Union s1 | s2 : {'d', 'a', 'o', 'i', 'b', 'u', 'e', 'f', 'c'}
Intersection s1 | s2 : {'a', 'e'}
Difference s1 - s2 : {'d', 'b', 'f', 'c'}
Difference s2 - s1 : {'o', 'u', 'i'}
Symmetric Difference s1 ^ s2 : {'d', 'b', 'u', 'o', 'i', 'f', 'c'}
The figure below illustrates how the set operation works.
We have:
s1= {'a', 'b', 'c', 'd', 'e','f'}
s2= {'a', 'e', 'i', 'o', 'u'}
Dictionary
A Dictionary is a set of associations between a key
and a value. A Dictionary is an unordered and
mutable collection. However, the dictionary has an
index, which is the key that is associated with the
value. The keys must be unique but the values do
not need to be unique
57
Creating a Dictionary
A Dictionary is created using curly brackets ('{}') where each entry in the dictionary is a
‘key:value’ pair.
Example: Create a dictionary.
Output :
{'Aileen': 2, 'Auni': 9, 'Sofea': 1, 'Ayra': 10}
Accessing Item via Keys
The value held in a Dictionary can be accessed using the associated key. The key
specified using square bracket (‘[]’)
Example: Access element in a Dictionary
Output :
2
1
Adding a New Entry and Changing the Keys Value
The element in the list can be added or changed simply by using the dictionary and
the key.
Example: Add and change the key-value in the dictionary.
Output :
{'Aileen': 3, 'Auni': 9, 'Sofea': 1, 'Ayra': 10, 'Ahmad': 7, 'Saiful': 6}
person = {'Aileen':2,'Auni':9,'Sofea':1,'Ayra':10}
print(person)
person = {'Aileen':2,'Auni':9,'Sofea':1,'Ayra':10}
print(person['Aileen'])
print(person['Sofea'])
person = {'Aileen':2,'Auni':9,'Sofea':1,'Ayra':10}
person['Ahmad'] = 7
person['Saiful'] = 6
person['Aileen'] = 3
print(person)
58
Removing an Entry
An entry into the dictionary can be removed using one of the pop() methods.
Syntax:
<dictionary>.pop(<key>)
Example: Remove an entry from the dictionary.
Output :
{'Aileen': 2, 'Sofea': 1, 'Ayra': 10}
Iterate over the dictionary
For loop can be used to iterate over a dictionary. The for loop processes each of the
keys in the dictionary. Then, the keys can be used to access each of the values
associated with the keys.
Example: Print key-value using for loop.
Output :
Aileen : 2
Auni : 9
Sofea : 1
Ayra : 10
person = {'Aileen':2,'Auni':9,'Sofea':1,'Ayra':10}
person.pop('Auni')
print(person)
person = {'Aileen':2,'Auni':9,'Sofea':1,'Ayra':10}
for item in person:
print(item , ':' , end=' ')
print(person[item])
59
Quick Review
1. It is not necessary to end the command in Python with a semicolon.
2. The indentation in Python is very important. Python uses indentation to indicate a
block of code.
3. A variable is created the moment you first assign a value to it. Variables do not
need to be declared with any particular type.
4. The categories of python data types are Numeric (Integer, Float, Complex
Number), Boolean, Set, Dictionary, Sequence(String, List, Tuple)
5. By default any variable created using input() statement is the type of string.
6. Type Casting is the method to convert the variable data type into a certain data
type to the operation required to be performed by users.
7. The conditional statement is used in the decision-making process
8. Looping is used to iterate for specified times
9. Tuple and List are ordered while Set and Dictionary are unordered
Programming Exercises
1. Create a variable and store a number's value to the variable.
a. Add print() function to display the value of the variable
b. Perform addition and multiplication with the variable, then print the
result to screen
2. Create a program to convert Kilometres to Miles.
3. Write a program to test if an integer is positive or negative. Your program should:
a. Prompt user to input a number.
b. Convert the string input to int()
c. Check whether the integer is positive or negative
d. Print the result.
c
h
a
p
t
e
r3
:
f
u
n
c
t
i
o
na
n
d
o
b
j
e
c
to
r
i
e
n
t
e
di
np
y
t
h
o
n
A
t
t
h
ee
n
do
f
t
h
i
sc
h
a
p
t
e
r
y
o
uw
i
l
l
a
b
l
et
o
:
•
D
e
f
i
n
ea
n
dc
a
l
l
F
u
n
c
t
i
o
n
•
D
e
f
i
n
eC
a
l
l
F
u
n
c
t
i
o
n
•
I
mp
o
r
t
a
n
dU
s
eMo
d
u
l
e
s
•
D
e
f
i
n
et
h
ec
o
mp
o
n
e
n
t
o
f
a
no
b
j
e
c
t
-
o
r
i
e
n
t
e
dP
y
t
h
o
n
•
D
e
f
i
n
ea
n
dI
n
s
t
a
n
t
i
a
t
e
sC
l
a
s
s
e
s
•
A
p
p
l
yC
l
a
s
sI
n
h
e
r
i
t
a
n
c
e
61
Function
In Chapter 2, all the programming instructions are written and executed line by line.
This technique is good only for short programs but not practical for large programs. You
must learn and practice to break the problem into manageable units. These units can
be work, tested, and maintain separately which makes the development process more
efficient.
A function is a group of related statements that perform a specific task. Functions are
like miniature programs that can be called together to form a large program.
The properties of function are:
• Functions may or may not take a set of parameters.
• Functions may or may not have a return value.
• Functions are only executed when it is called.
• Functions can be defined in one place and called in any place or any other
function.
Let us see the example of a program that is written using function and the other one
that is not. The programs below calculate the total from two integers. The set of values
that are used are:
• 10 and 20
• 20 and 5
Program 1: Not using function Program 2: Using Function
num1 = 10
num2 = 20
sum = num1 + num2
print(sum)
num1 = 10
num2 = 25
sum = num1 + num2
print(sum)
def sum(num1, num2):
sum = num1 + num2
print(sum)
sum(10, 20)
sum(20, 5)
62
In Program 1, to calculate two sets of values, the same codes are repeated twice.
However, in Program 2, there is no repetition. By using the function, we just need two
function calls which are sum(10,20) and sum(20,5). Every time we call the
function, the program searches for the function name and then executes the codes
defined inside the function.
Function gives many advantages which are:
• Code reusability.
• Reduce complexity.
• Easier to understand.
• Fewer errors because the function is not rewritten.
There are two types of functions:
1. Built-in Function
2. User-Defined Function
Built-in Function
Built-in functions are the predefined functions provided by Python that can be used
anywhere in the program. The print() which is used to display the output from a
program is one example of a built-in function that is frequently used.
Below are some of the built-in functions in python.
No Built-in Functions Description
1 max() Return the max from the list of items.
2 sum() Return the sum from the list of items.
3 open() Open file for reading or writing.
4 round() Return number rounded to by ndigits precision after the
decimal point.
5 sorted() Return the new sorted element from the list.
63
EXAMPLE: Use max() function to return the maximum value from the list.
Output : 100
EXAMPLE: Use round() function to return the floating number in 1 decimal place.
Output :
7.875
7.9
Define and Call Function
In this section, we will learn the second type of function which is user-defined function.
A user-defined function is a function that is written by the programmer. In many cases,
most of the programs are developed using user-defined functions.
The rules to define a function are:
1. A function is defined using the def keyword followed by the function name,
parentheses ( () ), and colon (:).
2. The block of statement in a function starts in a new line and is indented.
3. If the function has parameters, it should be placed within the parentheses (()).
max_num = max(10,20,40,100, 1)
print(max_num)
div = 9.45 / 1.2
print(div)
print(round(div,1))
64
The diagram below illustrates how to define and call a function.
The output generated is :
Welcome to learn Python
You will learn basic Python Programming"
Function with Parameter(s)
A parameter is a variable defined inside the parenthesis in the function header. The
parameter is used to receive data from the outside of the function and make the data
available within the function itself. You can use many parameters in the function, each
of them should be separated by a comma.
To call a function with parameters, it is a MUST to include the actual values to pass to
the function. The actual value that is provided in the function call is known as an
argument.
The argument must match with the parameters in terms of:
• the number of the parameters.
• position of the parameters.
65
The diagram below illustrates a function with parameters.
Example: A program to calculate bonus.
Output :
Bonus : RM 100
Bonus is RM 400
What program does are:
• The function has two parameters which are salary and percentage.
• Inside function:
o The bonus is calculated by a formula: bonus = salary *
percentage
o Then, print the output to the screen
• The function is called for two times : bonus(1000, 0.1) and
bonus(2000, 0.2)
def bonus (salary, percentage ) :
bonus = salary * percentage
print("Bonus : RM ", bonus)
bonus(1000, 0.1)
bonus(2000, 0.2)
66
EXAMPLE: A program prints the maximum from two numbers.
Output :
Number 1 : 10
Number 2 : 15
Higher number is 15
Returning Values From Function
The return keyword in a function is used to return any values to the caller. It means
that any values following the return keyword, are passed to the calling statement,
which is defined in the function call.
Both functions below display the same output which is "Hello". Function 1 is defined
without a return statement while Function 2 is defined with a return statement.
Function 1 Function 2
def greet():
print "Hello"
greet()
def greet():
return "Hello"
print(greet())
As can be seen, the code in Function 1 used print() statement inside the function
body while in Function 2 the print() statement is placed in the function call. When
a return statement is used, the function returns the value to the caller and it depends
on the caller, what operation to be done with the value.
def max_of_two(num1, num2):
if (num1> num2):
max = num1
else:
max = num2
print("Higher number is ",max)
a = int(input ("Number 1: "))
b= int(input ("Number 2: "))
max_of_two(a, b)
67
Besides printing the return value to the screen, we may want to assign the value to a
variable to do a different kind of operation.
EXAMPLE: A program calculates the average and takes the return values and performs
multiplication to the value.
Output :
6.0
In this program the value return by the function is assign to a variable
(x=avg()).The variable x is multiplied by 2 and the output is printed to the screen.
Is important to note that, we have to decide what operations we want to do with the
return value from the function. If we just call the function without any operation like
print(), nothing will be displayed on the screen.
You can try the following code, in which it just calls the function without any other
operation.
def greet():
return "Hello"
greet()
def avg(n1,n2,n3,n4):
avg = (n1+n2+n3+n4) / 4
return avg
x = avg(3,5,2,2)
bon = x * 2
print(bon)
68
EXAMPLE: A function to calculate the area of a triangle.
Output :
The area is 100 cm
EXAMPLE: A function to calculate Body Mass Index (BMI)
Output :
Enter weight in kilograms: 60
Enter height in meters: 158
The higher value is 24.03
def areaT(base, height):
return 0.5 * base * height
print("The area is ", areaT(10, 20) , "cm");
def get_bmi(weight, height):
height_in_meter = height/100
bmi = weight / (height_in_meter * height_in_meter )
return bmi
w = float(input ("Enter weight in kilograms: "))
h = float(input ("Enter height in centimeters: "))
bmi=round(get_bmi(w, h),2)
print("Your BMI is ", bmi)
69
EXAMPLE: A function with more than one return statement
Output :
Aileen
09-05-2019
A function can return more than one value. To do that, you just need to assign several
values after the return keyword, each is separated by a comma.
Default Argument
Default argument is the function that has the default value assigned to the parameter.
Default argument values will be used if no value is given in the call function. To declare
the default argument, use equal (=) followed by a value.
EXAMPLE: A function with a default parameter
Output :
Your country is Brunei
Your country is Malaysia
def name():
name = "Aileen"
date_of_birth = "09-05-2019"
return name, date_of_birth
get_name, dob = name()
print(get_name)
print(dob)
def country(name="Malaysia"):
print("Your country is ", name)
country("Brunei")
country()
70
Here is how the default argument works:
• Function country() has a default argument, name = "Malaysia".
• The first call function assigns the value = Brunei as the argument, so the
program prints "Your country is Brunei".
• The second function call has no value assigned to it, so the program takes the
default argument as the value and prints "Your country is Malaysia".
EXAMPLE: A function to get certification name.
Output :
Jerry
SPM Diploma Degree
John
SPM Diploma None
In this example, many parameters have been used. One of the parameters, cert3 is
the default argument. When you have many parameters and some of them are default
arguments, you should note that :
• Default argument should place at the rightmost of the parameter.
• Once the default argument has declared all remaining parameters to the right,
it will also be a default argument
• The following example shows the wrong way to declare the default argument:
def games(game1="Scrabble", game2)
def games(game1, game2="Scrabble", game3)
• The correct way is:
def games(game1, game2="Scrabble")
def games(game1, game2, game3="Scrabble")
def get_cert (name,cert1, cert2, cert3="None"):
print(name)
print(cert1, cert2, cert3)
get_cert("Jerry", "SPM", "Diploma", "Degree")
get_cert("John", "SPM", "Diploma")
71
Named Argument
In the previous section, we used the positional argument in the call function. Positional
arguments take into account the order of argument that should follow the order of the
parameters defined in the function header.
Named arguments allow us to ignore the position of the argument. To use a named
argument, we have to specify the name of the parameter and its value in the function
call. When the value is pass to the function, it will match the name of the parameter
with the specified name in the argument.
The following diagram illustrates how the named argument works
EXAMPLE: A function for a sender to send a message to the receiver.
Output :
To : Liyana
From : Aileen
Message : Wonderful
def get_msg(sender, receiver, msg):
print("To :", receiver)
print("From :", sender)
print("Message :", msg)
get_msg("Aileen",msg="Wondeful", sender="Aileen")
72
In the first argument, “Aileen” is matched with the first parameter, the sender. The
second and third are the named arguments.
When the named argument is used:
• The named argument should be placed at the rightmost of the call function.
• Wrong way to placed named argument:
get_msg(sender="Aileen", "Liyana", "Wonderful")
get_msg(Aileen", "Liyana", msg="Wonderful ")
• Correct way to placed named argument:
get_msg("Aileen", msg=" Wonderful ",receiver="Liyana")
get_msg("Aileen", msg=" Wonderful ", receiver="Liyana")
Import and Use Modules
A module is a python file that groups together related functions, classes, and code. The
module is used to organize large programs by breaking down the programs into small
and organize files.
Using modules helps with simplifying code, maintenance, comprehensibility because
the codes are grouped into smaller programs in different files.
There are two types of modules :
• User-defined module
• Built-in / Standard Module
73
Create user-defined module
A user-defined module is a module created by the programmer. To create a module,
simply save the code as usual, by using the .py extension. Any python file can be a
module.
To use a module in a program, use the import keyword followed by the module
name.
The following diagram illustrates two functions defined within a file called
example.py. Use import example (the file name without .py) to import all the
content of the file into my_app.py.
Once the definition of module example is visible, inside my_app.py, we can use them
as if they have been defined in the current file. To call the function in a module, we
have to include module name, dot operator(.), and function name.
example.add(10,20) )
When we run my_app.py, it will produce:
30
150
There are three methods on how to use modules in a program which are:
1. Import module (as shown previously)
2. Import with renaming
3. From module import list_of_function
74
EXAMPLE: Import module with renaming.
When we use the keyword as it creates an alias for the module. To call the function,
we just need to specify the alias instead of the module name.
EXAMPLE: Use from module import all.
Using this method, we can directly call any function inside the module without
specifying the module name.
EXAMPLE: Use from module import selected function
Using this method, we can select the function that we want to include in our program.
In this program, only function add() is included in the program.
import example as m
a = m.add(10, 20)
b = m.minus(100, 50)
print(a)
print(b)
from example import *
a = add(10, 20)
b = minus(100, 50)
print(a)
print(b)
from example import add
a = add(10, 20)
print(a)
75
Some important points to notes in naming the module:
• The only character allowed in naming the module are alphabets, numbers,
and underscore.
• For normal .py files, we can save files as act3a(iii).py but not for the module.
The bracket () is not allowed in naming the modules. The only special
character allowed is the underscore.
• Modules should have short, all-lowercase names. Underscores can be used in
the module name if it improves readability.
Built-in Module
There are a lot of built-in modules provided by Pythons such as sys, math, random, and
many more. To find the list of built-in modules, you can use command
help("module")
The diagram below shows the list of built-in modules provided by Python.
76
EXAMPLE: Use math and random built-in modules.
Output :
Square root of 9: 3.0
2 power of 3: 8.0
Random integer between 1-20: 9
Object-Oriented and Its Basic Component
Object-Oriented Programming (OOP) is a widely used concept to write powerful
applications. OOP provides an approach to structure the programs so that the data
held, and the operations performed on the data are bundled together in a class and can
be accessed via object. The paradigm of OOP mainly relies on the concept of classes
and objects which is illustrated in the diagram below.
Figure 1: Class and Object Relationship
from math import sqrt, pow
from random import *
print("Square root of 9: ", sqrt(9))
print("2 power of 3: ", pow(2,3))
print("Random integer between 1-20: ", randint(1,20))
77
The basic component of OOP are :
Component Description
Class • It is a template or blueprint for the object.
• It defines the attributes and methods shared by the same object
or class.
• A class represents broad categories like car, person, bird.
Object • The object is the real-world object that is represented by class
• An object is an instance of the class.
• You can think of it as a variable assigned to the class.
• Example: my_car1 and my_car2 are the objects that represent
class Car, each of them represents different values.
Attribute • A variable that holds data associated with a class and its objects.
• Example: color, type, name
Method • It is the function that is defined within the class
• It is a block of statement specify what objects can do.
• Example : calculate_price()
Inheritance • The ability of the child class to inherit the properties (attributes
and methods) defined in the parent class.
Other components of OOP include Encapsulation and Polymorphism. However, in this
e-book, we will cover the most basic component as listed in the table above.
78
Define and Instantiate Class
A class can be defined using the following format.
class name_of_class () :
__ init __
attributes
methods
About __init__():
• It is a special method that initializes the class (also known as a constructor)
• It indicates what data must be included when the class is instantiated.
• It also indicates how the data is stored inside the class.
• __init__() method is automatically called when the object is created
• self is the special variable that must be included when creating a method in
a class.
• The purpose of self is for the class to have the local variables as defined
which may be needed to operate class.
Therefore, to create an object you must refer to the __init__(), either it has
parameters or not. If it has parameters besides self, it means we must provide values
that match with the __init__()whenever we create the object.
The following figure shows a class with only a self variable declared as the parameter
inside the __init__() method.
The output generated from the code above is 1. The __init__() method has one
variable named val which has value 1.
79
While, in the following figure, the __init__() method has one more variable which
is score.
The output generated from the code above is 10 and 1.
Next, let create a class Car() which is represented by Figure 1 at the beginning of the
OOP section.
Define class and initialization method
class Car:
def __init__(self, manufacturer, color, price):
self.manufacturer = manufacturer
self.color = color
self.price = price
In Python, all the attributes(variable) or methods defined inside the class should be
accessed using self variable (for example self.color) as shown in the code above.
80
It is a good practice to define a class in a file named after the class. For example, the
code above would be stored in a file called Car.py. It makes it easier to find the code
associated with the class.
Instantiate Class (Create Object)
Instantiation refers to the creation of an object. The instance or object of class Car
can be created using the name of the class. The values, as defined in the __init__
method, shall be supplied to the class.
The following code creates three objects of the class Car.
my_car1 = Car(“Volkswagen”, “pink”, 187000)
my_car2 = Car(“Perodua”, “blue”, 63000)
my_car3 = Car(“Toyota”, “yellow”, 87000)
The figure below illustrates the value in objects my_car1, my_car2, and
mycar3 after the code above is executed.
Each object has the same set of methods and attributes because they are using the
same template which is class Car(). However, each object holds different data.
81
Accessing Object Attributes
We can access the attributes held by the object my_car1, my_car2, and my_car3
using the dot (.) operator followed by name of attribute:
Example : my_car1.manufacturer
The statement below print the value of the attributes:
print(my_car1.manufacturer, my_car1.color, my_car1.price)
print(my_car2.manufacturer, my_car2.color, my_car2.price)
print(my_car3.manufacturer, my_car3.color, my_car3.price)
The output generated is:
Volkswagen pink 187000
Perodua blue 63000
Toyota yellow 87000
It is important to note that we cannot print the class information directly using the
instance variables as in the following method:
print(my_car1)
print(my_car2)
print(my_car3)
The output generated from this method are :
<__main__.Car object at 0x000001DC8F142FD0>
<__main__.Car object at 0x000001DC8F142C70>
<__main__.Car object at 0x000001DC8F142BE0>
Which refers to the name of the class and the hexadecimal number indicates the
memory location of the object for class Car().
82
Defining Default String Representation
The default string representation is a special method used to convert an object into a
string for printing purposes. If we define the method in the class, we can directly print
the class information by using the instance variable.
This method can be defined using __str__().
The following code shows how to define the default string representation.
class Car:
def __init__(self, manufacturer, color, price):
self.manufacturer = manufacturer
self.color = color
self.price = price
def __str__(self):
return self.manufacturer + ' ' + self.color +' ' +
str(self.price)
Important note about __str__() :
• The method must return all the variables in string data type
• If the variable is a non-string type like variable price, it should convert to
string using the str() function.
Adding Instance Method
The behavior of the class is defined using a method. You can just think of a method as
the function we define in a class. We will define three methods, drive(), park()
and display().
Method Explanation
drive(self) Print out a statement "The car is moving"
park(self, hour) Calculate parking fees based on an hourly rate
display(self) Print out car information
As shown in the table above, each of the methods has a special variable self as the
required parameter in class.
83
Lets us now define the first method, drive(self)
class Car:
def __init__(self, manufacturer, color, price):
self.manufacturer = manufacturer
self.color = color
self.price = price
def drive(self):
print("The car is moving")
Create the instances of the class:
my_car1 = Car("Volkswagen", "pink", 187000)
my_car2 = Car("Perodua", "blue", 63000)
Then call the attributes name and method drive().
print(my_car1.name)
my_car1.drive()
print(my_car2.name)
my_car2.drive()
The output generated is :
Volkswagen
The car is moving
Perodua
The car is moving
84
Next is to define method park(). This method has a parameter, hour.
def park(self, hour):
if (hour <= 0.5):
pay = 0
if (hour > 0.5 and hour <= 2):
pay = hour * 2
if (hour > 2):
pay = hour * 1
print(self.manufacturer, "parking price for",
hour, "hours is RM", pay)
Method park() access instance variable as self.manufacturer. Remember, the
self variable is a MUST when we want to access any variables or methods defined
inside the class.
We will access method park(). This method needs an argument for parameter hour.
my_car1 .park(0.5)
my_car1 .park(1.5)
my_car1 .park(5)
The output generated is :
The payment for Volkswagen is 0
The payment for Volkswagen is 3.0
The payment for Volkswagen is 5
Then, let us define method display().
def display(self):
print("Car Manufacturer : ", self.manufacturer)
print("Car Color : ", self.color)
print("Car Price : ", self.price)
85
Create three objects and then access the methods.
my_car1 = Car("Volkswagen", "pink", 187000)
my_car2 = Car("Perodua", "blue", 63000)
my_car3 = Car("Toyota", "yellow", 87000)
print(my_car1.manufacturer)
my_car1 .display()
my_car1 .drive()
print()
print(my_car3.manufacturer)
my_car3.drive()
my_car3.park(5)
The output generated is :
Volkswagen
Car Manufacturer : Volkswagen
Car Color : pink
Car Price : 187000
The car is moving
Toyota
The car is moving
Toyota parking price for 5 hours is RM 5
86
Another Example: Class Person
Let us practice defining another example using class Person() which is illustrated
below:
The class Person() has:
• Attributes currentYear and age. The attributes are used to calculate the
age.
• The __init__() method has two instance attributes which are name and
yearborn. These two attributes shall be supplied when the class is
instantiated (created)
• calculate_age() is a method to calculate the age based on the year born
of a person.
• display() is a method to display the age of a person.
Define class, attributes, and __init__ method. Remember to be careful with
indentation.
class Person:
currentYear = 2021
age = 0
def __init__(self,name,yearborn):
self.name = name
self.yearborn=yearborn
87
Define method calculate_age().
def calculate_age(self):
self.age = self.currentYear - self.yearborn
return self.age
This method when it is called by the object will calculate the age and replace the initial
value of age=0 with the new value.
Define method display().
def display(self):
print("You are", self.age, "years old")
Create two objects for class Person()
p1 = Person("Aileen", 2019)
print("Hi", p1.name)
p1.calculate_age()
p1.display()
p2 = Person("Aydeen", 1998)
print("Hi", p2.name)
p2.calculate_age()
p2.display()
The output generated is :
Hi Aileen
You are 2 years old
Hi Aydeen
You are 23 years old
88
Class Inheritance
Inheritance is a core feature of OOP. Inheritance enables the subclass to inherits all the
attributes and methods from the superclass. The subclass can reuse all the attributes
and methods as its own, without the need to define the same attributes and methods
again.
The syntax to define the subclass is :
class SubClass (SuperClass):
""" body of class """
In this example, wewill use again the class Person() that we have defined previously.
Refer to the illustration below.
Here is the definition of class Person().
class Person:
currentYear = 2021
age = 0
def __init__(self,name,yearborn):
self.name = name
self.yearborn=yearborn
89
def calculate_age(self):
self.age = self.currentYear - self.yearborn
return self.age
Next, define the subclass Client()that inherits attributes and methods from the
class Person().
class Client(Person):
def __init__(self,name,yearborn,projectType):
super().__init__(name,yearborn)
self.projectType = projectType
def projectDetail(self):
if self.projectType == "A":
officer_incharge = "John Doe"
elif self.projectType == "B":
officer_incharge = "John Doe"
else:
officer_incharge = "Sally"
print("Name : ", self.name)
print("Age : ", self.age)
print("Officer Incharge : ", officer_incharge)
Here is what we do for class Client():
• The class Client() extends/inherit class Person(). The code to extend is
indicated by class Client(Person)
• Inside the __init__() method, we used super().__init__(name,
yearborn). It means that the attributes name and yearborn refer to the
__init__() method defined in superclass Person()
• We defined another attribute projectType inside the __init__(). It
means when the class Client() is created, it must supply three values for
name, yearborn, and ProjectType.
• class Client() has method projectDetail() which is programmed to
define the person in charge of the project.
90
Let us create the object for the class Client()
c1 = Client("Sofea", 1984, "A")
c1.calculate_age()
c1.projectDetail()
Class client() needs three values in the class instantiation as defined in the
__init__(). Once instantiated, it can use the method calculate_age() which
is inherited from the class Person().
The output generated is :
Name : Sofea
Age : 37
Officer Incharge : John Doe
Let us add class Employee() that also extends the class Person().
class Employee(Person):
def __init__(self, name, age, id):
super().__init__(name, age)
self.id = id
def calc_salary(self):
salary = 2000
if self.age>=35:
salary += 800
return salary
class Employee() is different with the class Client(). In Employee() we
defined attributes id instead of projectType. We create method
calc_salary() which is used to calculate the salary of the employee.
Even though Employee and Client are both types of Person, they are under different
sub-categories, so they have different attributes and behavior (methods). That is why
we separate them into two different classes.
91
We can go further and add a subclass Developer that extends class Employee. Refer to
the illustration below:
A developer is one of the employees. So, the developer will have all the attributes and
methods that the employee has by inherit the class. Class Developer() has a
unique method called bonus which depends on the number of projects they involve.
Let us define the subclass Developer().
class Developer(Employee):
def __init__(self,name, age, id, num_of_project):
super().__init__(name, age,id)
self.num_of_project = num_of_project
def bonus(self):
return self.num_of_project * 1000
Here is what we do for class Developer():
• Class Developer() extend class Employee()and class Empoyee()
extend class Person(). This enables the class Developer() to inherits
all the methods in both class Empoyee() and Person().
• In the __init__() method, we used super().__init__() to refer to
both attributes defined in class Empoyee() and Person().
• We add another attribute num_of_project inside the __init__()
method.
• class Developer() has method bonus() which is used to calculate the
bonus received by the developer.
92
Let us compile the code altogether and display the output to the screen.
print('Person')
p1 = Person("Fatimah", 1987)
print("Hi", p1.name, ".You are", p1.calculate_age())
print('-' * 25)
print('Client')
c1 = Client("Sofea", 1984, "A")
c1.calculate_age()
c1.projectDetail()
print('-' * 25)
print('Employee')
e1 = Employee("Adi", 1980,"P001")
e1.calculate_age()
print("Your Salary is", e1.calc_salary())
print('-' * 25)
print('Developer')
d1 = Developer("Irwan", 1980,"P001",5)
d1.calculate_age()
print("Your Salary is", d1.calc_salary() + d1.bonus())
The output generated is :
Person
Hi Fatimah. You are 34
-------------------------
Client
Name : Sofea
Age : 37
Officer Incharge : John Doe
-------------------------
Employee
Your Salary is 2800
-------------------------
Developer
Your Salary is 7800
93
Methods Overriding
Overriding occurs when a method is defined in a class (for example, Person) and also in
one of its subclasses (for example, Client). It means that for instance of Person and
Client both responded to the request for this method to be run but each has its own
implementation of the method.
For example, let us assume that we define the method __str__() in the class
Person() and Client().
The __str__() definition in class Person() is defined as :
While in the Client(), it is defined as :
94
The method in class Client() replace/override the version of __str__() in class
Person(). When we print the instance of class Employee() and Client(), the
output will differ because each class has its own method. For example:
p1 = Person("Fatimah", 1987)
p1.calculate_age()
c1 = Client("Sofea", 1984, "A")
c1.calculate_age()
print(p1)
print(c1)
The output generated is :
Fatimah is 34
Client Name is Sofea - Project Type A
As can be seen from this, the class Person() prints name and age while class
Client() prints name and project type.
Things that we should note is :
• If we ask an object to perform some operation, then, to determine which
version of the method is running, look in the class used to create the
instance. If the methods are not defined there, look into the class’s parents.
Keep doing that until we find a method that implements the operation
requested.
95
Quick Review
• Functions are like miniature programs which enable you to divide a program
into manageable tasks.
• The main advantage of function is because of the reusability.
• There are two types of functions which are built-in and user-defined functions.
• Function definition starts with keyword def, followed by the function name,
parenthesis, the parameter is declared inside parenthesis and a colon. The
block of statement in function starts in a new line and is indented.
• Functions can have more than one return value.
• The default argument is the value assigned to the parameter in the function
definition.
• Named argument is specifying the parameter name and value in the function
call.
• Module is a .py file that is used to organize a large program into smaller files.
• To use the module, use the import keyword.
• There are two types of modules which are built-in modules and user-defined
modules.
• Some of the basic components in OOP are: Class, Object, Attribute, Method
and Inheritance
• Attributes of a class refer to the variables and methods are the function
defined in the class.
• Instantiation is the creation of the object by assigning a variable to the class.
• Once the object is created, we can access the attributes and method using the
name of the object followed by dot(.) operator and attributes/method that we
want to call.
• Inheritance allows a class to use members of another class as a part of its own
definition.
96
Programming Exercises
1. Write a function that accepts the user's first and last name and prints them in
reverse order with a space between them.
2. Use the built-in module to get the Python version you are using (Hint import sys).
3. Write a function that accepts the radius of a circle from the user and compute the
area (Formule: Area of circle = πr2
).
4. Create a new class Item that represents Items in the library :
a. Define a new class Item
b. When the class is instantiated, you should provide the title, description,
quantity, and type of item (which can be a string representing ‘Book’,
‘DVD’, and ‘CD’. This means that there must be an __init__ method that
you will need to store the data within the object.
c. Define the default string representation.
d. Provide three instance method for the class Item : borrow_book(),
return_book() and get_balance. The behavior of these methods should be
as expected, borrow will decrease the book quantity, return book will
increase the book quantity, and balance returns the current book quantity.
e. A simpe test applicaton for the class Book is given below:
it1 = Item("Basic Python", "Book", 10)
it2 = Item("History of Malaysia", "DVD", 5)
it3 = Item("The Sound of Music", "CD", 5)
print(it1)
print(it2)
print(it3)
it1.borrow_book(3)
it1.return_book(1)
it1.current_quntity()
97
The following output illustrates the result of running this test application.
98
References
Scratch. M. &. Scratch. E. (2020). Coding Python: The Ultimate Tool to Progress Your
Python Programming from Good to Great While Making Coding in Scratch Look Easy
(Python Programming Language). Luca Pino. (ISBN: 1801326983)
Patricia. F. (2020). Python Programming for Beginners: A Kid's Guide to Coding
Fundamentals. Rockridge Press. (ISBN: 1646113888)
Hunt, J. (2020) A Beginners Guide to Python 3 Programming (ISBN: 978-3-030-20289-7)
Publisher
POLITEKNIK BALIK PULAU
Pinang Nirai, Mukim E,
11000 Balik Pulau,
Pulau Pinang.
Email:
polibalikpulau@pbu.edu.my
Website :
www.pbu.edu.my
Tel : 04-868 9000
Fax : 04-869 2061

More Related Content

Similar to Basic_Python_Programming.pdf

PYTHON TUTORIALS.pptx
PYTHON TUTORIALS.pptxPYTHON TUTORIALS.pptx
PYTHON TUTORIALS.pptx
EzatIlman1
 
Introduction to python
Introduction to pythonIntroduction to python
Introduction to python
AnirudhaGaikwad4
 
Migration of Applications to Python is the most prudent Decision
Migration of Applications to Python is the most prudent DecisionMigration of Applications to Python is the most prudent Decision
Migration of Applications to Python is the most prudent Decision
Mindfire LLC
 
Introduction to python updated
Introduction to python   updatedIntroduction to python   updated
Introduction to python updated
chakrib5
 
Python basic
Python basicPython basic
Python basic
radhikaadroja
 
Python for students step by step guidance
Python for students step by step guidancePython for students step by step guidance
Python for students step by step guidance
MantoshKumar79
 
Python quick guide1
Python quick guide1Python quick guide1
Python quick guide1Kanchilug
 
Introduction to Python
Introduction to PythonIntroduction to Python
Introduction to Python
DrMohammed Qassim
 
Python Programming Draft PPT.pptx
Python Programming Draft PPT.pptxPython Programming Draft PPT.pptx
Python Programming Draft PPT.pptx
LakshmiNarayanaReddy48
 
Basic Python Introduction Lecture 1.pptx
Basic Python Introduction Lecture 1.pptxBasic Python Introduction Lecture 1.pptx
Basic Python Introduction Lecture 1.pptx
Aditya Patel
 
Introduction to Python Programming - I
Introduction to Python Programming  - IIntroduction to Python Programming  - I
Introduction to Python Programming - I
Arnab Chakraborty
 
Ways To Become A Good Python Developer
Ways To Become A Good Python DeveloperWays To Become A Good Python Developer
Ways To Become A Good Python Developer
CodeMonk
 
Lecture 1.pptx
Lecture 1.pptxLecture 1.pptx
Lecture 1.pptx
hemantmohite6
 
Python final presentation kirti ppt1
Python final presentation kirti ppt1Python final presentation kirti ppt1
Python final presentation kirti ppt1
Kirti Verma
 
Chapter - 1.pptx
Chapter - 1.pptxChapter - 1.pptx
Chapter - 1.pptx
MikialeTesfamariam
 
1-ppt-python.ppt
1-ppt-python.ppt1-ppt-python.ppt
1-ppt-python.ppt
ssusera99a83
 
Learn Python Python Introduction for Beginners.pdf
Learn Python  Python Introduction for Beginners.pdfLearn Python  Python Introduction for Beginners.pdf
Learn Python Python Introduction for Beginners.pdf
SudhanshiBakre1
 
Python basics
Python basicsPython basics
Python basics
ssuser4e32df
 
python Certification Training in marthahalli
python Certification Training in marthahallipython Certification Training in marthahalli
python Certification Training in marthahalli
MUDDUKRISHNA14
 
Introduction to Python Unit -1 Part .pdf
Introduction to Python Unit -1 Part .pdfIntroduction to Python Unit -1 Part .pdf
Introduction to Python Unit -1 Part .pdf
VaibhavKumarSinghkal
 

Similar to Basic_Python_Programming.pdf (20)

PYTHON TUTORIALS.pptx
PYTHON TUTORIALS.pptxPYTHON TUTORIALS.pptx
PYTHON TUTORIALS.pptx
 
Introduction to python
Introduction to pythonIntroduction to python
Introduction to python
 
Migration of Applications to Python is the most prudent Decision
Migration of Applications to Python is the most prudent DecisionMigration of Applications to Python is the most prudent Decision
Migration of Applications to Python is the most prudent Decision
 
Introduction to python updated
Introduction to python   updatedIntroduction to python   updated
Introduction to python updated
 
Python basic
Python basicPython basic
Python basic
 
Python for students step by step guidance
Python for students step by step guidancePython for students step by step guidance
Python for students step by step guidance
 
Python quick guide1
Python quick guide1Python quick guide1
Python quick guide1
 
Introduction to Python
Introduction to PythonIntroduction to Python
Introduction to Python
 
Python Programming Draft PPT.pptx
Python Programming Draft PPT.pptxPython Programming Draft PPT.pptx
Python Programming Draft PPT.pptx
 
Basic Python Introduction Lecture 1.pptx
Basic Python Introduction Lecture 1.pptxBasic Python Introduction Lecture 1.pptx
Basic Python Introduction Lecture 1.pptx
 
Introduction to Python Programming - I
Introduction to Python Programming  - IIntroduction to Python Programming  - I
Introduction to Python Programming - I
 
Ways To Become A Good Python Developer
Ways To Become A Good Python DeveloperWays To Become A Good Python Developer
Ways To Become A Good Python Developer
 
Lecture 1.pptx
Lecture 1.pptxLecture 1.pptx
Lecture 1.pptx
 
Python final presentation kirti ppt1
Python final presentation kirti ppt1Python final presentation kirti ppt1
Python final presentation kirti ppt1
 
Chapter - 1.pptx
Chapter - 1.pptxChapter - 1.pptx
Chapter - 1.pptx
 
1-ppt-python.ppt
1-ppt-python.ppt1-ppt-python.ppt
1-ppt-python.ppt
 
Learn Python Python Introduction for Beginners.pdf
Learn Python  Python Introduction for Beginners.pdfLearn Python  Python Introduction for Beginners.pdf
Learn Python Python Introduction for Beginners.pdf
 
Python basics
Python basicsPython basics
Python basics
 
python Certification Training in marthahalli
python Certification Training in marthahallipython Certification Training in marthahalli
python Certification Training in marthahalli
 
Introduction to Python Unit -1 Part .pdf
Introduction to Python Unit -1 Part .pdfIntroduction to Python Unit -1 Part .pdf
Introduction to Python Unit -1 Part .pdf
 

Recently uploaded

Sha'Carri Richardson Presentation 202345
Sha'Carri Richardson Presentation 202345Sha'Carri Richardson Presentation 202345
Sha'Carri Richardson Presentation 202345
beazzy04
 
Additional Benefits for Employee Website.pdf
Additional Benefits for Employee Website.pdfAdditional Benefits for Employee Website.pdf
Additional Benefits for Employee Website.pdf
joachimlavalley1
 
The French Revolution Class 9 Study Material pdf free download
The French Revolution Class 9 Study Material pdf free downloadThe French Revolution Class 9 Study Material pdf free download
The French Revolution Class 9 Study Material pdf free download
Vivekanand Anglo Vedic Academy
 
Instructions for Submissions thorugh G- Classroom.pptx
Instructions for Submissions thorugh G- Classroom.pptxInstructions for Submissions thorugh G- Classroom.pptx
Instructions for Submissions thorugh G- Classroom.pptx
Jheel Barad
 
Language Across the Curriculm LAC B.Ed.
Language Across the  Curriculm LAC B.Ed.Language Across the  Curriculm LAC B.Ed.
Language Across the Curriculm LAC B.Ed.
Atul Kumar Singh
 
Synthetic Fiber Construction in lab .pptx
Synthetic Fiber Construction in lab .pptxSynthetic Fiber Construction in lab .pptx
Synthetic Fiber Construction in lab .pptx
Pavel ( NSTU)
 
Overview on Edible Vaccine: Pros & Cons with Mechanism
Overview on Edible Vaccine: Pros & Cons with MechanismOverview on Edible Vaccine: Pros & Cons with Mechanism
Overview on Edible Vaccine: Pros & Cons with Mechanism
DeeptiGupta154
 
How libraries can support authors with open access requirements for UKRI fund...
How libraries can support authors with open access requirements for UKRI fund...How libraries can support authors with open access requirements for UKRI fund...
How libraries can support authors with open access requirements for UKRI fund...
Jisc
 
The Accursed House by Émile Gaboriau.pptx
The Accursed House by Émile Gaboriau.pptxThe Accursed House by Émile Gaboriau.pptx
The Accursed House by Émile Gaboriau.pptx
DhatriParmar
 
Francesca Gottschalk - How can education support child empowerment.pptx
Francesca Gottschalk - How can education support child empowerment.pptxFrancesca Gottschalk - How can education support child empowerment.pptx
Francesca Gottschalk - How can education support child empowerment.pptx
EduSkills OECD
 
"Protectable subject matters, Protection in biotechnology, Protection of othe...
"Protectable subject matters, Protection in biotechnology, Protection of othe..."Protectable subject matters, Protection in biotechnology, Protection of othe...
"Protectable subject matters, Protection in biotechnology, Protection of othe...
SACHIN R KONDAGURI
 
Adversarial Attention Modeling for Multi-dimensional Emotion Regression.pdf
Adversarial Attention Modeling for Multi-dimensional Emotion Regression.pdfAdversarial Attention Modeling for Multi-dimensional Emotion Regression.pdf
Adversarial Attention Modeling for Multi-dimensional Emotion Regression.pdf
Po-Chuan Chen
 
Chapter 3 - Islamic Banking Products and Services.pptx
Chapter 3 - Islamic Banking Products and Services.pptxChapter 3 - Islamic Banking Products and Services.pptx
Chapter 3 - Islamic Banking Products and Services.pptx
Mohd Adib Abd Muin, Senior Lecturer at Universiti Utara Malaysia
 
Honest Reviews of Tim Han LMA Course Program.pptx
Honest Reviews of Tim Han LMA Course Program.pptxHonest Reviews of Tim Han LMA Course Program.pptx
Honest Reviews of Tim Han LMA Course Program.pptx
timhan337
 
The geography of Taylor Swift - some ideas
The geography of Taylor Swift - some ideasThe geography of Taylor Swift - some ideas
The geography of Taylor Swift - some ideas
GeoBlogs
 
Model Attribute Check Company Auto Property
Model Attribute  Check Company Auto PropertyModel Attribute  Check Company Auto Property
Model Attribute Check Company Auto Property
Celine George
 
678020731-Sumas-y-Restas-Para-Colorear.pdf
678020731-Sumas-y-Restas-Para-Colorear.pdf678020731-Sumas-y-Restas-Para-Colorear.pdf
678020731-Sumas-y-Restas-Para-Colorear.pdf
CarlosHernanMontoyab2
 
Biological Screening of Herbal Drugs in detailed.
Biological Screening of Herbal Drugs in detailed.Biological Screening of Herbal Drugs in detailed.
Biological Screening of Herbal Drugs in detailed.
Ashokrao Mane college of Pharmacy Peth-Vadgaon
 
Digital Tools and AI for Teaching Learning and Research
Digital Tools and AI for Teaching Learning and ResearchDigital Tools and AI for Teaching Learning and Research
Digital Tools and AI for Teaching Learning and Research
Vikramjit Singh
 
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
siemaillard
 

Recently uploaded (20)

Sha'Carri Richardson Presentation 202345
Sha'Carri Richardson Presentation 202345Sha'Carri Richardson Presentation 202345
Sha'Carri Richardson Presentation 202345
 
Additional Benefits for Employee Website.pdf
Additional Benefits for Employee Website.pdfAdditional Benefits for Employee Website.pdf
Additional Benefits for Employee Website.pdf
 
The French Revolution Class 9 Study Material pdf free download
The French Revolution Class 9 Study Material pdf free downloadThe French Revolution Class 9 Study Material pdf free download
The French Revolution Class 9 Study Material pdf free download
 
Instructions for Submissions thorugh G- Classroom.pptx
Instructions for Submissions thorugh G- Classroom.pptxInstructions for Submissions thorugh G- Classroom.pptx
Instructions for Submissions thorugh G- Classroom.pptx
 
Language Across the Curriculm LAC B.Ed.
Language Across the  Curriculm LAC B.Ed.Language Across the  Curriculm LAC B.Ed.
Language Across the Curriculm LAC B.Ed.
 
Synthetic Fiber Construction in lab .pptx
Synthetic Fiber Construction in lab .pptxSynthetic Fiber Construction in lab .pptx
Synthetic Fiber Construction in lab .pptx
 
Overview on Edible Vaccine: Pros & Cons with Mechanism
Overview on Edible Vaccine: Pros & Cons with MechanismOverview on Edible Vaccine: Pros & Cons with Mechanism
Overview on Edible Vaccine: Pros & Cons with Mechanism
 
How libraries can support authors with open access requirements for UKRI fund...
How libraries can support authors with open access requirements for UKRI fund...How libraries can support authors with open access requirements for UKRI fund...
How libraries can support authors with open access requirements for UKRI fund...
 
The Accursed House by Émile Gaboriau.pptx
The Accursed House by Émile Gaboriau.pptxThe Accursed House by Émile Gaboriau.pptx
The Accursed House by Émile Gaboriau.pptx
 
Francesca Gottschalk - How can education support child empowerment.pptx
Francesca Gottschalk - How can education support child empowerment.pptxFrancesca Gottschalk - How can education support child empowerment.pptx
Francesca Gottschalk - How can education support child empowerment.pptx
 
"Protectable subject matters, Protection in biotechnology, Protection of othe...
"Protectable subject matters, Protection in biotechnology, Protection of othe..."Protectable subject matters, Protection in biotechnology, Protection of othe...
"Protectable subject matters, Protection in biotechnology, Protection of othe...
 
Adversarial Attention Modeling for Multi-dimensional Emotion Regression.pdf
Adversarial Attention Modeling for Multi-dimensional Emotion Regression.pdfAdversarial Attention Modeling for Multi-dimensional Emotion Regression.pdf
Adversarial Attention Modeling for Multi-dimensional Emotion Regression.pdf
 
Chapter 3 - Islamic Banking Products and Services.pptx
Chapter 3 - Islamic Banking Products and Services.pptxChapter 3 - Islamic Banking Products and Services.pptx
Chapter 3 - Islamic Banking Products and Services.pptx
 
Honest Reviews of Tim Han LMA Course Program.pptx
Honest Reviews of Tim Han LMA Course Program.pptxHonest Reviews of Tim Han LMA Course Program.pptx
Honest Reviews of Tim Han LMA Course Program.pptx
 
The geography of Taylor Swift - some ideas
The geography of Taylor Swift - some ideasThe geography of Taylor Swift - some ideas
The geography of Taylor Swift - some ideas
 
Model Attribute Check Company Auto Property
Model Attribute  Check Company Auto PropertyModel Attribute  Check Company Auto Property
Model Attribute Check Company Auto Property
 
678020731-Sumas-y-Restas-Para-Colorear.pdf
678020731-Sumas-y-Restas-Para-Colorear.pdf678020731-Sumas-y-Restas-Para-Colorear.pdf
678020731-Sumas-y-Restas-Para-Colorear.pdf
 
Biological Screening of Herbal Drugs in detailed.
Biological Screening of Herbal Drugs in detailed.Biological Screening of Herbal Drugs in detailed.
Biological Screening of Herbal Drugs in detailed.
 
Digital Tools and AI for Teaching Learning and Research
Digital Tools and AI for Teaching Learning and ResearchDigital Tools and AI for Teaching Learning and Research
Digital Tools and AI for Teaching Learning and Research
 
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
 

Basic_Python_Programming.pdf

  • 1. NURHANI BINTI MOHD SABRI LIYANA BINTI MAT RANI writers : A Beginner Guide To Python Programming. Execute your first python program,all in simple steps Basic Python Programming Basic Python Programming Character: String input() [index:]
  • 2. A l l r i g h t s r e s e r v e d J A B A T A NT E KN OL OGI MA KL U MA T& KOMU N I KA S I ( J T MK) P OL I T E KN I KB A L I KP U L A U ©2 0 2 1P o l i t e k n i kB a l i kP u l a u A U T HOR S : L i y a n aB i n t i Ma t R a n i N u r h a n i B i n t i Mo h dS a b r i E D I T OR S : S a mi h a hB i n t i A b d u l L a t i f I l i N u r A y u n i B i n t i N a z r i D E S I GN E R S : Mu h a mma dS h u k r i B i nI s ma i l E d d y z u l h a m B i nA b uB a k a r L i y a n aB i n t i Ma t R a n i T h i s b o o k o r a n y p o r t i o n t h e r e o f m a y n o t b e r e p r o d u c e d o r u s e d i n a n y m a n n e r w h a t s o e v e r w i t h o u t t h e e x p r e s s w r i t t e n p e r m i s s i o n o f t h e p u b l i s h e r e x c e p t f o r t h e u s e o f b r i e f a u t a t i o n s i n a b o o k r e v i e w .
  • 3. F i r s t a n df o r e mo s t , w ew o u l dl i k et op r a i s ea n dt h a n kA l l a h S . W. T , t h eA l mi g h t yf o r g i v i n gu st h es t r e n g t ha n db e c a u s e o f H i sb l e s s i n g , w ea r ea b l et oc o mp l e t et h i sP y t h o n e - B o o k . T h es u c c e s sa n do u t c o meo f t h i sw e r ep o s s i b l eb y t h eg u i d a n c ea n ds u p p o r t f r o mf a mi l ya n df r i e n d s . Wea r e i n c r e d i b l yp r i v i l e g e dt oh a v eg o t t h i sa l l a l o n gw i t ht h e a c h i e v e me n t o f o u r e B o o kp r o j e c t . I t r e q u i r e sal o t o f e f f o r t f r o me a c hi n d i v i d u a l i n v o l v e di nt h i sp r o j e c t a n dw ew o u l d f r o me a c hi n d i v i d u a l i n v o l v e di nt h i sp r o j e c t a n dw ew o u l d l i k et ot h a n kt h e m. Wew o u l dl i k et oa c k n o w l e d g ew i t h t h a n k st oP u a nWa nN u r Wa h i d a hb i n t i H a s h i mf o r g r a n t i n g u sa no p p o r t u n i t yt od ot h i se B o o kp r o j e c t a n dp r o v i d i n g u sw i t ha l l g u i d a n c e , p a t i e n c e , a n ds u p p o r t , w h i c hma d eu s c o mp l e t et h ee B o o kp r o j e c t d u l y . Wew o u l da l s ol i k et o t h a n kP u a nS a mi h a hb i n t i A b d u l L a t i f f o r p r e s e n t i n g e n d l e s ss u p p o r t , d e s p i t eh a v i n gab u s ys c h e d u l e . e n d l e s ss u p p o r t , d e s p i t eh a v i n gab u s ys c h e d u l e . Wea r e t h a n k f u l f o r t h ec o n s i s t e n t e n c o u r a g e me n t , s u p p o r t , a n d s u p e r v i s i o n . A l s o , w ew o u l dl i k et oc o n t i n u eo u r g e n u i n e e s t e e mst oa l l s t a f f f o r t h e i r t i me l ys u p p o r t . A c k n o w l e d g e me n t “ “
  • 4. e B o o ki same d i u mt oe n h a n c et h ed i g i t a l l i b r a r yt h a t w i l l b ee n a b l eu n l i mi t e da c c e s sg l o b a l l yf o r 2 4 h o u r sa n d7d a y s aw e e kt ot h er e q u i r e di n f o r ma t i o na n di t w i l l h e l pu s e r st o q u i c k l yr e t r i e v ea n da c c e s ss p e c i f i cr e s e a r c hma t e r i a l s e a s i l y , q u i c k l y , a n de f f e c t i v e l y . T h i se B o o ki sap r a c t i c a l r e s o u r c ef o r a c a d e mi cd e p a r t me n t a n ds t u d e n t so f I n f o r ma t i o nT e c h n o l o g ya n dC o mmu n i c a t i o n , M a l a y s i a P o l y t e c h n i ct h a t o f f e r sD F P 4 0 2 0 3P y t h o nP r o g r a mmi n g P o l y t e c h n i ct h a t o f f e r sD F P 4 0 2 0 3P y t h o nP r o g r a mmi n g c o u r s e . M a i n t a i n i n gap r a c t i c a l p e r s p e c t i v e , B a s i cP y t h o n P r o g r a mmi n ga c q u a i n t sy o uw i t ht h ew o n d e r f u l w o r l do f p r o g r a mmi n g . T h i se B o o ki sas t a r t i n gp o i n t f o r t h o s ew h o j u s t s t a r t e dt ol e a r nt h eB a s i cP y t h o np r o g r a mmi n g . T h e b a c k b o n eo f a n yp r o g r a mmi n g , w h i c hi st h ed a t as t r u c t u r e a n dc o mp o n e n t ss u c ha ss t r i n g s , l i s t , e t c . , h a v eb e e n i l l u s t r a t e dw i t hma n ye x a mp l e sa n de n o u g hp r a c t i c e st o i l l u s t r a t e dw i t hma n ye x a mp l e sa n de n o u g hp r a c t i c e st o i n s t i l al e v e l o f s e l f - c o n f i d e n c ei nt h er e a d e r . Y o uw i l l e x p l o r et h ef o u n d a t i o no f P y t h o np r o g r a mmi n ga n dl e a r n h o wP y t h o nc a nb ema n i p u l a t e dt oa c h i e v ef i n a l e x p e c t e d r e s u l t s . T h et o p i c si nt h i se B o o kc o n s i s t o f t h e i n t r o d u c t i o nt op y t h o n , b a s i cp r o g r a me l e me n t s , f u n c t i o n a n do b j e c t - o r i e n t e d . T h i se B o o ka l s op r o v i d eq u i c kr e v i e w t ot e s t t h eu n d e r s t a n d i n g , t h e o r ye x e r c i s e sa n de x a mp l e s t ot e s t t h eu n d e r s t a n d i n g , t h e o r ye x e r c i s e sa n de x a mp l e s o f p r o g r a mmi n ge x e r c i s e s . A b s t r a c t “ “
  • 5. 1 TABLE OF CONTENT CHAPTER 1: INTRODUCTION TO PYTHON PROGRAMMING 3 DEFINE PYTHON PROGRAMMING 4 DESCRIBE BASIC PRINCIPLES OF PYTHON 5 INTERACTIVELY USING THE PYTHON INTERPRETER 6 RUNNING PYTHON FILE 6 USING PYTHON IN IDE 7 INSTALL AND SET UP PYTHON ENVIRONMENT 7 QUICK REVIEW 13 CHAPTER 2: PYTHON PROGRAM ELEMENTS 14 PYTHON SYNTAX 15 A QUICK LOOK AT PYTHON PROGRAM 15 VARIABLE AND DATA TYPES 17 TYPE CASTING 21 PYTHON NAMING VARIABLE 24 PYTHON COMMENT 25 SINGLE LINE COMMENT 25 MULTI-LINE COMMENT 25 STRING LITERALS FOR MULTI-LINE COMMENTS 26 OPERATORS AND OPERATOR PRECEDENCE 27 ARITHMETIC OPERATORS 27 ASSIGNMENT OPERATORS 29 COMPARISON OPERATORS 31 LOGICAL OPERATOR 33 OPERATOR PRECEDENCE 34 CONDITIONAL STATEMENT 35 THE IF STATEMENT 35 THE IF-ELSE STATEMENT 38 THE ELIF STATEMENT 40 THE NESTED IF STATEMENT 41
  • 6. 2 LOOPING STATEMENT 43 THE WHILE STATEMENTS 43 THE FOR STATEMENT 44 T BREAK STATEMENTS 46 THE CONTINUE STATEMENT 46 ORDERED AND UNORDERED DATA STRUCTURE 47 TUPLE 47 LIST 51 SET 53 DICTIONARY 56 QUICK REVIEW 59 PROGRAMMING EXERCISES 59 CHAPTER 3: FUNCTION AND OBJECT-ORIENTED 60 FUNCTION 61 BUILT-IN FUNCTION 62 DEFINE AND CALL FUNCTION 63 FUNCTION WITH PARAMETER(S) 64 RETURNING VALUES FROM FUNCTION 66 DEFAULT ARGUMENT 69 NAMED ARGUMENT 71 IMPORT AND USE MODULES 72 CREATE USER-DEFINED MODULE 73 BUILT-IN MODULE 75 OBJECT-ORIENTED AND ITS BASIC COMPONENT 76 DEFINE AND INSTANTIATE CLASS 78 DEFINING DEFAULT STRING REPRESENTATION 82 ADDING INSTANCE METHOD 82 ANOTHER EXAMPLE: CLASS PERSON 86 CLASS INHERITANCE 88 METHODS OVERRIDING 93 QUICK REVIEW 95 PROGRAMMING EXERCISES 96 REFERENCES 98
  • 8. 4 Define Python Programming Python is an object-oriented and high-level programming language. Python is similar to other programming language that you might have heard of such as C++, JavaScript, Microsoft’s C#, and Oracle’s Java. Python has been around for a long time. It is created by Guido van Rossum at the Centrum Wiskunde & Informatica (CWI) in the Netherlands in the 1980s. This increasing interest in Python is driven by several different factors: • The language is flexible, simple which make it easy to learn • Python supports modules and packages, which encourages program modularity and code reuse. • Can be run on (almost) any operating system. • The availability of a wide range of libraries (modules) that can be used to extend the basic features of the language. • Its use by the Data Science community where it provides a more standard programming language especially in the area of machine learning • The ability of the language to connect existing components available nowadays such as IoT devices, web pages, and machine learning easily. • It is Free! Currently, there are two main versions of Python called Python 2 and Python 3. • Python 2 was launched in October 2000 and still is very widely used. • Python 3 was launched in December 2008 and is a major revision to the language that is not backward compatible. The issue between the two versions can be highlighted by the simple print facility: • In Python 2 this is written as print 'Hello World' • In Python 3 this is written as print('Hello World') It may not look much of a difference but the inclusion of the ‘ ( ) ‘ marks a major change and means that any code written for one version of Python will probably not run on the other version.
  • 9. 5 Describe Basic Principles of Python Below are some principles of Python. 1. Hybrid programming language o The code can be written in a procedural and object-oriented manner. 2. Interpreted language o The source code of a Python is converted into bytecode that is then executed by the Python virtual machine. There is no explicit compilation step in Python. 3. Dynamically Typed Language o The data type checking is performed at runtime.It doesn’t know about the type of the variable until the code is run. o In Python, the variable is declared without the need to specify the data type. 4. Automatic memory management and garbage collection o The garbage collector automatically frees up the memory which was allocated by the program but is no longer referenced. 5. Can be used for many types of applications: o Web Development o Python for Scientific development o Data Science and Analysis 6. Can be run using several ways: o Interactively using the Python interpreter o Stored in a file and run using the Python command o From within a Python IDE (Integrated Development Environment) such as PyCharm.
  • 10. 6 Interactively Using the Python Interpreter Once Python has been installed, you can open a Command Prompt window (Windows) or a Terminal window (Mac) and type Python into the prompt. Below is the image shown for a Windows machine: Running Python File We can also save the Python commands into a file. For example, given a file containing the following file (called hello.py) with the 4 commands in it: To run the hello.py program on a PC using Windows, we can use Command Prompt : • Navigate to the location of the file (hello.py) using the change directory (cd) command • Use python command followed by the name of the file:
  • 11. 7 Using Python in IDE We can also use an IDE such as PyCharm to write and execute our Python program. The same program is shown using PyCharm below: The above figure shows a simple set of commands that are again listed in a file called hello.py. The program has been run on within the IDE and the output is shown in an output console at the bottom of the display. Install and Set Up Python Environment First, we will show you how to install Python Environment and then use the command prompt to code the Python. The steps below used Windows platform to install and set up Python. Follow the following steps: Step 1: Browse for https://www.python.org/. Go To Downloads Section and choose Windows.
  • 12. 8 Step 2: Next from page Python Release For Windows, choose the latest Python 3 Release. Step 3: On the page of the latest version of python, look for the Files section. Step 4: Download Python installer either 32bits or 64bits depending on your Operating System.
  • 13. 9 Step 5: Click on the Python Installer. By default the checkbox Add Python 3.9 to PATH is unchecked. Make sure to check on Add Python 3.9 to PATH. Then click on Install Now. Step 6: On the computer open Command Prompt. Python is successfully installed if symbol >>> appears on the Command Prompt. Step 7: Type the following code: print(‘Hello World’) Step 8: Test the following code and observe the output. print(5 + 10) num1 = 100 num2 = 10 multiply = num1 * num2 print(multiply)
  • 14. 10 Next, we will install PyCharm, the Python IDE. Follow the following steps. Step 1: Browse for https://www.jetbrains.com/pycharm/, then click on the Download button. Step 2: On the download page, choose the community download. Step 3: Click on the PyCharm Installer. Use the default installation setting. By now you have successfully installed the PyCharm IDE!
  • 15. 11 Step 3: Then, start the PyCharm IDE. Once started, you will be asked if you want to import any settings you may have had for another version of PyCharm. At this point, select ‘Do not import settings. You should now be presented with the landing screen for PyCharm Step 4: Click on the ‘Create New Project’ option in the landing dialog. Use default location but change the name of the project to python_intro. Click Create.
  • 16. 12 Step 6: To create a New Python File, click on File -> New -> Python File. Put helloWorld.py as the file name. Step 7: Type the following code to the pyCharm editor. print("hello World") print("Politeknik Balik Pulau") Step 8: To run the code, click on Run -> Run. Choose helloWorld
  • 17. 13 Quick Review 1. Python is an interpreted, object-oriented, high-level programming language with dynamic semantics. 2. There are two main versions of Python called Python 2 and Python 3. 3. The basic principles of Python are : • Hybrid programming language • Interpreted language • Dynamically Typed Language • Includes all the features that one expects from a programming language • Automatic memory management and garbage collection 4. There are several ways to run a Python program, including: • Interactively using the Python interpreter • Stored in a file and run using the Python command • From within a Python IDE such as PyCharm.
  • 19. 15 Python Syntax In this chapter, we will learn the basic elements and concepts of programming using Python. There are two basic syntaxes in Python : • It is not necessary to end a command with a semicolon. • The indentation (refers to the space at the beginning of a code line) in Python is very important. Python uses indentation to indicate a block of code. A Quick Look At Python Program Let's start with a quick look at a simple program to print out ‘Hello World’. print('Hello World') To execute the code above, you can use any text editor or IDE of your choice. The example below use PyCharm to write and execute the code. The print() statement will print everything that you pass inside the parenthesis. Thus, when we run this program, the string ‘Hello World’ is printed on the screen.
  • 20. 16 Let us make our program a little more interesting. Let the program ask our name and say hello to us. The program has two additional statements. The first statement is: This statement executes a function called input(). This function has an argument which is a statement that is used to prompt for user’s input. In this case, it will print the statement that you provide as a prompt to the user and wait until the user types something. The value that the user typed is stored in a variable name. The second statement is: We will use the print() statement again, but this time the print() takes two data. The data is separated by a comma. In this case, we passed a string ‘Hello’ and the value referenced by the variable name.
  • 21. 17 Variable and Data Types A variable is used to store value. A variable is stored in the computer’s memory and the value can change depending on the program execution. A variable is created the moment you first assign a value to it. Variables do not need to be declared with any particular type. The syntax to declare a varible is : variable_name = value Example: A program with two variables x and y. Output : 5 Auni The x and y are the variables with values “5” and “Auni” assign to the x and y, respectively. The data type of a variable is automatically given to the variable based on the values assigned to the variable. In this example, the x variable is a type of integer and y is a type string. The diagram below shows the data type in Python. x = 5 y = "Auni" print(x) print(y)
  • 22. 18 Table below is the description of each data types in Python. Name Class Type Description Integer <int> Whole number such as 5, 23, 100, 300 Floating Number <float> Number with decimal points such as 10.1, 5.443, 0.3 Complex Number <complex> Complex numbers are comprised of a real part and an imaginary part: a = 8 + 5j Boolean <bool> Has two values either TRUE or FALSE: 10>9 will return TRUE 10<9 will return FALSE String <string> Sequence of character defined in sigle, double or triple quote such as 'Hello', "525", '''xxx''' Set <set> Unordered collection of unique object: {"apple", "papaya", "durian"} Dictionary <dict> Unordered collection of key->value pair: {"alia" : 4.00, "aiman" : 3.87} List <list> Ordered sequence of obeject : ["Aileen", 19.0, "aileen@gmail.com"] Tuple <tuple> Ordered immutable sequence of object: ("Aileen", 19.0, "aileen@gmail.com")
  • 23. 19 The type of variable can dynamically change as the program being executed. This is referred to as Dynamic Typing. To illustrate dynamic typing, refer to the illustration below. Initially, the x has the value ‘Sally’ which is a type of string. In the second line, the program resets x = 10 which means the value in the variable x is replaced with 10. Python automatically changes the type of x from string to integer. Then the program again resets the x = 10.9 and the data type is changed to float. In Python, we do not need to worry about what data type should we assign to the variable. The data type will be assigned automatically by Python once the value is assigned to the variable. It is possible to find out what type of variable currently holds using the built-in type() function. This function takes a variable name and will return the type of data held by the variable. Example: Use built-in function type() to get the type of variable num1 = 10 print(type(num1)) num2 = 3.89 print(type(num2)) name = "Haniey" print(type(name))
  • 24. 20 Output : <class 'int'> <class 'float'> <class 'str'> The type of item data (such as integer) determines what it is legal to do with the data and what the effect of various actions will be. For example, the effect of using a ‘+’ operator • If the data type numbers are involved, then the plus operator will add the numbers together. • If strings are involved, then the string will be concatenated (combine) together. Example: Use plus operator to data type number and string Output : 30.5 Python Programming Referring to the code above, str1,str2, and str3 is all type of string. A string is a sequence of characters that is declared either in a single, double, or triple quotes. Single and double quotes are the same. You can use single quotes for string literals like 'My Village' but use double quotes for strings that are likely to contain single-quote characters as a part of the string itself like the statement "You’ve got an error". num1 = 10 num2 = 20.5 sum = num1 + num2 print(sum) str1 = "Python " str2 = 'Programming ' str3 = str1 + str2 print(str3)
  • 25. 21 However, Python's triple quotes are a bit different. Triple quotes allow the string output to span multiple lines, including verbatim NEWLINEs, TABs, and any other special characters. Example: Use single, double and triple-quotes Output : My Cat It’s mine My lovely Cat Type Casting As we mentioned previously, the data type of the variable is automatically assigned by the Python environment when the value is assigned to the variable. However, there are many times when we develop a program we may want to specify or change the data type that we want. Type Casting is the method to convert the variable data type into a certain data type to the operation required to be performed by users. str1 = 'My Cat' str2 = "It’s mine" str3 = ''' My lovely Cat ''' print(str1) print(str2) print(str3)
  • 26. 22 Casting in Python can be done using the following constructor functions: • int ( ) : o construct an integer number from an integer, float, or string. • float ( ) o construct float number from an integer, a float, or a string literal • str ( ) o constructs a string from a wide variety of data types, including strings, integer, and float literals. Example: Casting a variable Output : 5.9 <class 'float'> 5 <class 'int'> The above example shows the type of variable which is initially a floating number that is changed into the integer data type using statement a = int(a). The value for the variable changes from 5.9 to 5. You may be wondering why the value is not round up to 6 since 5.9 is close to 6. Casting will just remove the decimal places in the float, it will not round up or down to an integer value. The most used typecasting in the program is when using the input() function to receive input from a user. The variables received from the input() function is automatically data type string. Therefore, if you want your program to get the integer value from a user, you must cast the variable into either integer or float. a = 5.9 print(a) print(type(a)) a = int(a) print(a) print(type(a))
  • 27. 23 Suppose you have the following program. salary = input("Your salary : ") bonus = 150 payment = salary + bonus This program will generate a type error message because: • salary is a string data type (all variables received from an input is automatically assigned to a string) • bonus is an integer data type • The plus(+) operation is not legal between type string and integer, thus will generate the following error. To correct the code, we must cast the input to the integer data type. Refer to the following example below. Example: Casting variable receive from input() Output : Your salary : 1000 1150 After the variable salary has been cast to number (either integer or float), the plus operation between salary and bonus produced the correct output. salary = int(input("Your salary : ")) bonus = 150 payment = salary + bonus print(payment)
  • 28. 24 Python Naming Variable In naming the variable, the very widely used naming convention is: • The first character of a variable must be an alphabetic letter (upper or lower case) or the underscore. The remaining characters (if any) may be alphabetic characters (upper or lower case), the underscore, or a digit • No other characters (including spaces) are permitted. • A reserved word cannot be used as an identifier Some of the accepted and not accepted naming variables are represented in the table below. Variables Remarks my_name, user_name, account_name, count, where_we_live,is_okay, is_correct, status_flag Accepted variables name 1_name Not Accepted. A Variable’s name cannot start with a number. user name Not Accepted. Variable’s name cannot have space in between where-we-live Not Accepted. Variable’s name cannot have space and other characters than underscore (_) The following reserved word cannot be used as a variable name.
  • 29. 25 Python Comment Comments are descriptions that help programmers to understand better the intention and functionality of the program. Using comments in programs will make our code more understandable. It makes the program more readable which helps us remember why certain blocks of code were written. Single Line Comment Python used the # symbol to write a single-line comment. Comments can be placed at the beginning or at the end of a line and Python will ignore the rest of the line. Example: Python Single-line comment Output : Hello World Hello World Multi-line Comment Python does not have syntax for multi-line comments. To add a multiline comment you could insert a # for each line. Example: Python Multi-line comment Output : Such a wonderful day! # printing a string print('Hello world') print('Hello world')# printing a string # it is a # multiline # comment print("Such a wonderful day!")
  • 30. 26 String Literals for Multi-line Comments Another thing that you need to know about string in Python is, the string literal will ignore the statement that is not assigned to a variable. Example: Use an unassigned string as a comment. Output : This also can be a comment. Here, we can see that the first line of the program is a string but is not assigned to any variable or function. So, the interpreter ignores the string. Similarly, we can use multiline strings (triple quotes) to write multiline comments. Example: Use an unassigned string as a multi-line comment. Output : Hello World 'this is an unassigned string as a comment ' print("This also can be a comment") ''' I am a multiline comment! ''' print("Hello World")
  • 31. 27 Operators and Operator Precedence Operators are used to perform operations on variables and values. In the previous example, we use the plus(+) operator to add between two values. Python divides the operators into the following groups: i. Arithmetic operators ii. Assignment operators iii. Comparison operators iv. Logical operators v. Identity operators vi. Membership operators vii. Bitwise operators Arithmetic Operators Arithmetic operators are used to perform mathematical operations like addition, subtraction, multiplication, etc. Assume we have two variables: a = 5 b = 2 The operation using the arithmetic operators is described in the table below. Operator Expression Result Meaning Addition (+) a + b 7 Add two values. Subtract (-) a – b 3 Subtract one value from another Multiplication (*) a * b 10 Multiply two numbers Division (/) a / b 2.5 Divide left operand by the right operand Modulus (%) a % b 1 The remainder from a division of left operand by the right operand Exponent (**) a ** b 25 Exponential value (a power of b) Floor (//) a // b 2 Perform the division and only give the integer quotient.
  • 32. 28 Example: Use arithmetic operators. Output : 7 - 3 = 4 7 * 3 = 21 7 ^ 3 = 343 7 % 3 = 1 Example: Program to convert kilogram to grams Output : Enter value in kilograms : 1.5 1.5 kg = 1500.0 g x = 7 y = 3 res = x - y print( x , '-' , y ,'=' , res) res = x * y print( x , '*' , y ,'=' , res) res = x ** y print( x , '^' , y ,'=' , res) res = x % y print( x , '%' , y ,'=' , res) val1 = float(input('Enter value in kilograms : ')) gram = val1 * 1000 print(val1, 'kg = ' , gram , 'g')
  • 33. 29 Example: Mathematical operation allowed on a string Output : *Politeknik* ***** *****Politeknik***** Assignment Operators Assignment operators are used in Python to assign values to the variables. a = 5 is a simple assignment operator that assigns the value 5 to the variable a. Python as a compound operator like a+=5 that add 5 to the variable a. a+=5 is equivalent to a = a + 5. Assume we have: x= 6 y = 3 The operation using the assignment operator is describe in the table below. Operator Expression Result Meaning Assignment (=) x = y + 2 5 x = 3 + 2 Addition Assignment (+=) x += y 9 x = x + y Subtraction Assignment (-=) x -= y 3 x = x - y Multiplication Assignment (*=) x *= b 18 x = x *y Division Assignment (/=) x /= y 2 x = x / y Modulus Assignment (/=) x %= y 0 x = x % y Exponential Assignment (/=) x **= y 216 x = x** y Floor Assignment (//=) x //= y 0 x = x // y a = '*' b = 'Politeknik' c = a + b + a print(c) a = 5 * a print(a) c = a + b + a print(c)
  • 34. 30 Example: Use the assignment operator on the integer values. Output : Initially value of z is 0 Current value of z is 25 Current value of z is 40 Current value of z is 600 The figure below shows how the values of the variable z change throughout the program execution. x = 15 y = 10 z = 0 print("Initially value of z is",z) z = x + y print("Current value of z is",z) z += x print("Current value of z is",z) z *= x print("Current value of z is", z)
  • 35. 31 Comparison Operators Comparison operators or also known as the relational operator are used to compare values between two operands and returns answer as True or False. The table below shows the comparison operator, its expression, and the result. Operator Expression Result Less than (<) 5 < 2 5 < 5 False False Greater than (>) 5 > 2 5 > 5 True False Less than (<=) 5 <= 2 5 <= 5 False True Greater than (>=) 5 >= 2 5 >= 5 True True Equal to (==) 5 == 2 5 == 5 False True Not equal to (!=) 5 != 2 5 != 5 True False Example: Use comparison operator to compare between two number values. Output : False True False print(10<4) print(5>=5) print(5!=5)
  • 36. 32 It is obvious when you use the comparison operator with the numbers. The following example uses the comparison operator two strings: Example: Use comparison operator to compare between two string values Output : True True False The expression 'a' > 'b' returns True because the letter 'a' is before the letter 'z’. The same goes to the expression 'apple' < 'banana' returns True because the letter a in apple is before the letter b in banana. For the third statement, the first letter in durian and dragon are the same, then it will compare with the second letter which is the letter u and r. Since the letter 'u' comes after the letter r, the expression 'durian' < 'dragon' returns False. Example: Output : True True False print('a'<'z') print('apple'<'banana') print('durian'<'dragon') print('a'<'z') print('apple'<'banana') print('durian'<'dragon')
  • 37. 33 Logical Operator Logical operators are used on conditional statements (either True or False). They perform Logical AND, Logical OR, and Logical NOT operations. The table below shows the description of the logical operator. Operator Expression Result Meaning and True and True True and False False and True False and False True False False False The result will be true if both the operands are true, otherwise, it returns false. or True or True True or False False or True False or False True True True False The result will be true if both or either of the operand is true, otherwise, it returns false. not not True not False False True Reverse the value of the operand. The result will be true when the operand is false and will return false if the operand is true.
  • 38. 34 Operator Precedence If an expression has more than one operator, for example, expression 5 + 7 * 2, to determine which operation to perform first, the rules in operator precedence must be used. Figure below shows the execution of expression 10 + 7 * 2. This expression will be calculated as 10 + (7 * 2) not as (10 + 7) * 2. The operator precedence is listed in the following table. Priority Operator Description Associativity 1 () Parenthesis left to right 2 ** Exponent left to right 3 *, /, % Multiplication, Division, Modulus left to right 4 +, - Addition, Subtraction left to right 5 < , <= > , >= Less than/less than or equal to Greater than/greater than or equal to left to right 6 == , != Equal to, not equal to left to right 7 not Logical NOT left to right 8 and Logical AND left to right 9 Or Logical OR left to right
  • 39. 35 Example: Use operator precedence Output : 220.0 40.0 Conditional Statement You've now learned quite a bit of Python code from the previous section. Everything you have seen so far has consisted of sequential execution, in which statements are always performed one after the next, in exactly the order specified. But the world is often more complicated than that. Frequently, a program needs to skip over some statements or choose between alternate sets of statements to execute. That is where the conditional statement comes in. The conditional statement is the if statement used to perform decision making. It allows for the conditional execution of a statement or group of statements based on the value of an expression. Here is the type of conditional statement in Python. • If • If..Else • Nested if • elif The if statement The if statement is the most fundamental decision-making statement. It takes an expression, for example, expression if (x > 3), and checks if the expression evaluates to True then the block of code in if statement will be executed. If the expression evaluates to False, then the block of code is skipped. exp = 200 - 100 / 10 + 3 * 10 print(exp) exp = (200 - 100) / 10 + 3 * 10 print(exp)
  • 40. 36 The syntax for the if statement is: if expression: statement_1 statement_2 …………………. statement_n Example: Use if statement to check negative number Output 1: Enter a number: -4 -4 is negative End of Program The if statement checks if the input is less than zero. If the expression return True, it will execute the block of if statement which prints the input as negative. If the conditional statement returns False, it will execute the next line of code after the if block. num = int(input('Enter a number: ')) if (num < 0): print(num, 'is negative') print('End of Program') bock of if Output 2: Enter a number: 10 End of Program
  • 41. 37 Example: Use more than one if statement Output 1: Enter Your Score : 100 Exceptional! Output 4: Enter Your Score : 12 Try again next time The example used four(4) if statements to check the score and print the message. The block of if statement is executed when the expression returns True. Example: Use more than one if statement score= int(input('Enter Your Score : ')) if (score == 100): print('Exceptional!') if (score < 100 and score >=80): print('Excellent!') if (score < 80 and score >=60): print('Well Done!') if (score < 60): print('Try again next time') Output 2: Enter Your Score : 88 Excellent! Output 3: Enter Your Score : 79 Well Done! score1= int(input('English Score : ')) score2= int(input('Mathematic Score : ')) print("You can choose: ") if (score1 >= 80): print('English course') if (score2 >= 85): print('Mathematic course') if (score1 >= 90 and score2 >=95): print('Science course')
  • 42. 38 Output 1: English Score : 80 Mathematic Score : 70 You can choose: English course The if-else statement From the name itself, we get the clue that the if-else statement checks the expression and executes the if block when the expression is True otherwise it will execute the else block of code. The else block should be right after if block and it is executed when the expression is False. The syntax for the if-else statement is: if expression: statement(s) …………………. statement_n else: statement_1 …………………. statement_n bock of if bock of else Output 2: English Score : 98 Mathematic Score : 98 You can choose: English course Mathematic course Science course
  • 43. 39 Example: Use an if-else statement. Output : Enter a number: 12 Number is non-negative End of Program Example: Use more than one if-else statement. Output : Enter a number: 20 20 is even number the number is larger than 10 num = int(input('Enter a number: ')) if (num < 0): print(num, 'is negative') else: print('Number is non-negative') print('End of Program') Output 2: Enter a number: -10 -10 is negative End of Program num = int(input('Enter a number: ')) if (num % 2 == 0): print(num, 'is even number') else: print(num, 'is odd number') if (num>10): print('the number is larger than 10') else: print('the number is less than 10') Output 2: Enter a number: 7 7 is odd number the number is less than 10
  • 44. 40 The elif statement The elif keyword is used to chain multiple conditions one after another. With an elif statement, we can make a complex decision-making statements. The elif statement helps you to check multiple expressions and it executes the code as soon as one of the conditions evaluates to True. The syntax for the if-elif-else statement is: If expression1 : statement elif expression2 : statement … ... else: statement Example: Use an if-elif-else statement. Output : How much is your saving? :200 Well Done saving = float(input('How much is your saving? :')) if saving==0: print('Sorry, no saving') elif saving<500: print('Well Done') elif saving<=1000: print('That is a tidy sum') elif saving>1000: print('Welcome Sir') else: print('Thank You')
  • 45. 41 The nested if statement The nested if statement is an if statement inside another if statement. With nested if, it allows us to stack any number of if statements inside the block of another if statement. They are useful when we need to make a series of decisions. Example: Use nested if statement. Output 1: Enter integer value in range 1-10 :2 2 is in range Done val = int(input('Enter integer value in range 1-10 :')) if val >=0: if val <=10: print(val, 'is in range') else: print(val, 'is too large') else: print(val, 'is too small') print('Done') Output 2: Enter integer value in range 1-10 :20 20 is too large Done
  • 46. 42 Example: Use nested if statement. Output 1: Select your ride ****************** 1. Bike 2. Car Choice :1 You have selected Bike. a. Road Bike b. Mountain Bike ------------------ Choose your bike: a Nice Choice! print('Select your ride') print(18 * '*') print('1. Bike') print('2. Car') choice = int(input('Choice :')) if( choice == 1 ): print( 'You have selected Bike.' ) print('a. Road Bike') print('b. Mountain Bike') print(18 * '-') bike = input('Choose your bike: ') if bike == 'a': print('Nice Choice!') elif bike == 'b': print('Train your stamina') else: print('Wrong choice!') elif( choice == 2 ): print( 'You have selected Car' ) else: print('Wrong choice!') Output 2: Select your ride ****************** 1. Bike 2. Car Choice :2 You have selected Car
  • 47. 43 Looping Statement Loops are one of the most powerful and basic concepts in programming. A loop can contain a set of statements that keeps on executing until a specific condition is reached. Python has two primitive loop commands which are: • While Loop • For Loop Other statements that can be used in looping • Break – stop the loop even if the while condition is true • Continue – stop the current iteration and continue with the next The while statements The while loop executes a block of code until the specified condition becomes False. The syntax for the while loop is: while test_expression: Body of while Example: Use a while statement. Output : Starting 0 1 2 3 4 5 6 7 8 9 10 Done count = 0 print('Starting') while count<=10: print(count, ' ', end='') count+=1 print() print('Done')
  • 48. 44 Example: Use while to print multiplication of two Output : 2 4 6 8 10 12 14 16 18 20 The for statement A for loop is used for iterating over a sequence (that is either a list, a tuple, a dictionary, a set, or a string). The loop through a set code a specified number of times, we can use the range() function. The range() function returns a sequence of numbers, starting from 0 by default and increments by 1 (by default), and ends at a specified number. The syntax for loop is: for val in sequence: body of for loop n = 2 i = 1 product= 1 while(i<=10): product = i * n i+=1 print(product, '', end='')
  • 49. 45 The range () function When using for loops in Python, the range() function is pretty useful to specify the number of times the loop is executed. It yields a sequence of numbers within a specified range. The syntax or range(): range(start, stop, step) • The first argument is the starting value. It is zero by default. • The second argument is the ending value of the range. • The third argument is the number of steps to take after each yield. Example: Use for loop to print 1 to 9 Output : 1 2 3 4 5 6 7 8 9 Example: Use for loop to print from 0 to 10 increment by 2 Output : 0 2 4 6 8 Example: Use for loop to print from 7 to 20 increment by 1 Output : 7 8 9 10 11 12 13 14 15 16 17 18 19 for i in range(10): print(i, ' ', end='') for i in range(0,10,2): print(i, ' ', end='') for i in range(7,20): print(i, '',end='')
  • 50. 46 The break statements The break statement inside a loop is used to exit out of the loop. Sometimes in a program, we need to exit the loop when a certain condition is fulfilled. Example: Use break statement in a loop Output : 1 2 3 Loop ended The Continue Statement The continue statement is used to skip the next statements in the loop. When the program reaches the continue statement, the program skips the statements after continue and the flow reaches the next iteration of the loop. Example: Use continue statement in a loop Output : 1 3 4 5 Loop ended num = 0 while( num <10 ): num +=1 if(num==3): break print( num ) print("Loop ended") num = 0 while( num <5 ): num +=1 if(num==2): continue print(num) print("Loop ended")
  • 51. 47 Ordered and Unordered Data Structure Previously we have learned some Python built-in data structures such as string, int, float, and as well bools. However, these are not the only built-in data structure in Python Another group of built-in data structures is known as collection types. A collection is a single object representing a group of objects. These collection classes are often used as the basis for more complex or application-specific data structures and data types. The table below shows the group of ordered and unordered data structures in Python. Ordered Unordered Tuple Set List Dictionary Tuple Tuples are an immutable ordered collection of objects: • Tuples can have a mixture of different types and they are not restricted to hold all elements of the same types. • Each element in a tuple has a specific position (positive and negative index) and that position does not change over time. • Index in tuple start with 0 (for positive index) and -1(for negative index). • The index starts from zero and goes till the number of elements minus one. • It is not possible to add or remove elements from the tuple once it has been created. The figure below shows the representation of the tuple.
  • 52. 48 Creating Tuples Tuples are created by typing a sequence of items, separated by commas. Optionally, you can put the comma-separated values in parenthesis. Example: Create a tuple Output : (1, 2, 5, 6) ('a', 'b', 'c', 'd') () (5, 3, 1) ('Aileen', 'Auni', 'Asbir', 1986, 1640, 1948) Accessing Elements of a Tuple Tuple can be accessed using an index (positive or negative) in square brackets. Example: Access element in a tuple using an index. tuple1 = (1,2,5,6) tuple2 = ('a', 'b', 'c', 'd') tuple3 = () #empty tuple tuple4 = 5,3,1 tuple5 = ('Aileen', 'Auni', 'Asbir', 1986,1640, 1948) print(tuple1) print(tuple2) print(tuple3) print(tuple4) print(tuple5) tuple1 = (1,3,5,7) print('Element at index 0 =>' , tuple1[0]) print('Element at index 2 =>' ,tuple1[2]) print('Element at index -3 =>' ,tuple1[-3]) print('Element at index -1 =>' ,tuple1[-1])
  • 53. 49 Output : Element at index 0 => 1 Element at index 2 => 5 Element at index -3 => 3 Element at index -1 => 7 Slicing a Tuple We can slice a tuple using the ranges of indexes, by specifying where to start and where to end the range. As we know, the index starts from zero and goes till the number of elements minus one. The range of indexes in a tuple can be positive and negative. The following diagrams illustrate how the slicing occurs in the tuple. tuple = (1, 3, 5, 7, 8, 9, 12) new_tuple1 = tuple[1:4] tuple = (1, 3, 5, 7, 8, 9, 12) new_tuple2 = tuple[ :3]
  • 54. 50 tuple = (1, 3, 5, 7, 8, 9, 12) new_tuple3 = tuple[ :3] Example: Slicing a tuple Output : (3, 5, 7) (1, 3, 5, 7) (3, 5, 7, 8) (1, 3, 5, 7) (8, 9, 12) tuple = (1,3,5,7,8,9,12) new_tuple1 = tuple[1:4] new_tuple2 = tuple[:4] new_tuple3 = tuple[-6:-2] new_tuple4 = tuple[:-3] new_tuple5 = tuple[-3:] print(new_tuple1) print(new_tuple2) print(new_tuple3) print(new_tuple4) print(new_tuple5)
  • 55. 51 Iterating Over Tuples Apply for loop to iterate over a tuple. Example: Use for loop to iterate a tuple. Output : Kelantan Perak Kedah 1987 1999 List The list is also an ordered collection of objects. It is similar to tuple but the difference between them is that lists are mutable(can change) while tuples are immutable(cannot change). List support all the features of the Tuple but as they are mutable it is also possible to: • Insert/modify elements in a list • remove elements Creating List Lists are created using square brackets positioned around the elements. Example: Create a list Output : ('John', 'Jane', 'Ringo', 'Ahmad') tuple = ('Kelantan', 'Perak', 'Kedah', 1987,1999) for val in tuple: print(val, end=' ') list = ('John', 'Jane', 'Ringo', 'Ahmad') print(list)
  • 56. 52 Accessing Elements from a List Same as tuples, the element in the list is accessible via index. Example: Access element in a list Output : Jane Ahmad Ringo ('John', 'Jane', 'Ringo') Insert into a List To insert an element into an existing list, use the insert() method. Syntax: <list>.insert(<index>, <object>) The insert() method takes an index indicating where to insert the element and an object to be inserted. Example: Insert into a list Output : ['Adele', 'Madonna', 'Jackson'] ['Adele', 'Hillary', 'Madonna', 'Jackson'] We have inserted the string ‘Hillary’into the index position 1 pushing ‘Madonna’ and ‘Jackson’ up one in the index within the List. list = ('John', 'Jane', 'Ringo', 'Ahmad') print(list[1]) print(list[-1]) print(list[2]) print(list[-4:3]) actor = ['Adele', 'Madonna', 'Jackson'] print(actor) actor.insert(1,'Hillary') print(actor)
  • 57. 53 Remove from a List We can remove elements from a List using the remove() method. Syntax: <list>.remove(<object>) Example: Remove value from a list Output : ['Aileen', 'Auni', 'Asbir', 'Jerry', 'Tan'] ['Aileen', 'Asbir', 'Jerry', 'Tan'] Set Set is an unordered (unindexed) collection of mutable objects that does not allow duplicates. Unlike tuple and list, set are not accessible using the index. In set, any duplicate items will be considered as one. Create a Set A Set is defined using curly brackets ‘{}’. Example: Create a set. Output : {'orange', 'apple', 'banana'} Even though the ‘apple’ and ‘banana’ appear two times in the set declaration, the value will consider as one because the set treats any duplication as one item. stud = ['Aileen', 'Auni', 'Asbir', 'Jerry','Tan'] print(stud) stud.remove('Auni') print(stud) basket = {'apple', 'orange','apple','orange','banana'} print(basket)
  • 58. 54 Accessing Elements in a Set As mentioned earlier, a set is unordered, so it is not possible to refer to elements of the set using an index. To access the elements in the set, for loop can be used. Example: Access element in the set using for statement Output : apple banana pear orange The order of the output is not the same as defined in the code. Set is unordered, so when we display the element in the set it will come out in random order. Adding Items to a Set Element in the set can be accessed using add() method. This method can add an item at one time. Syntax : <set>.add(<object>) Example: Add an item to a set Output : {'pear', 'orange', 'durian', 'banana', 'apple'} basket = {'banana', 'orange','apple','pear'} for item in basket: print(item, end=' ') basket = {'banana', 'orange','apple','pear'} basket.add('durian') print(basket)
  • 59. 55 Remove an Item From Set Element in the set can be accessed using the remove() method. This method removes a single item from a set. Syntax : <set>.remove(<object>) Example: Remove an item from a set. Output : {'apple', 'orange', 'pear'} Set Operations The Set container also supports set like operations such as: • Union (|): Combination of all values in two or more sets. • Intersection (&): Common values between two or more sets. • Difference (−): The set of values in the first set that is not in the second set. • Symmetric difference (^): All the unique values in two or more sets. Example: Use set operations basket = {'banana', 'orange','apple','pear'} basket.remove('banana') print(basket) s1= {'a', 'b', 'c', 'd', 'e','f'} s2= {'a', 'e', 'i', 'o', 'u'} print("Union s1 | s2 :", s1|s2) print("Intersection s1 | s2 :", s1&s2) print("Difference s1 - s2 :", s1-s2) print("Difference s2 - s1 :", s2-s1) print("Symetric Difference s1 ^ s2 :", s1^s2)
  • 60. 56 Output : Union s1 | s2 : {'d', 'a', 'o', 'i', 'b', 'u', 'e', 'f', 'c'} Intersection s1 | s2 : {'a', 'e'} Difference s1 - s2 : {'d', 'b', 'f', 'c'} Difference s2 - s1 : {'o', 'u', 'i'} Symmetric Difference s1 ^ s2 : {'d', 'b', 'u', 'o', 'i', 'f', 'c'} The figure below illustrates how the set operation works. We have: s1= {'a', 'b', 'c', 'd', 'e','f'} s2= {'a', 'e', 'i', 'o', 'u'} Dictionary A Dictionary is a set of associations between a key and a value. A Dictionary is an unordered and mutable collection. However, the dictionary has an index, which is the key that is associated with the value. The keys must be unique but the values do not need to be unique
  • 61. 57 Creating a Dictionary A Dictionary is created using curly brackets ('{}') where each entry in the dictionary is a ‘key:value’ pair. Example: Create a dictionary. Output : {'Aileen': 2, 'Auni': 9, 'Sofea': 1, 'Ayra': 10} Accessing Item via Keys The value held in a Dictionary can be accessed using the associated key. The key specified using square bracket (‘[]’) Example: Access element in a Dictionary Output : 2 1 Adding a New Entry and Changing the Keys Value The element in the list can be added or changed simply by using the dictionary and the key. Example: Add and change the key-value in the dictionary. Output : {'Aileen': 3, 'Auni': 9, 'Sofea': 1, 'Ayra': 10, 'Ahmad': 7, 'Saiful': 6} person = {'Aileen':2,'Auni':9,'Sofea':1,'Ayra':10} print(person) person = {'Aileen':2,'Auni':9,'Sofea':1,'Ayra':10} print(person['Aileen']) print(person['Sofea']) person = {'Aileen':2,'Auni':9,'Sofea':1,'Ayra':10} person['Ahmad'] = 7 person['Saiful'] = 6 person['Aileen'] = 3 print(person)
  • 62. 58 Removing an Entry An entry into the dictionary can be removed using one of the pop() methods. Syntax: <dictionary>.pop(<key>) Example: Remove an entry from the dictionary. Output : {'Aileen': 2, 'Sofea': 1, 'Ayra': 10} Iterate over the dictionary For loop can be used to iterate over a dictionary. The for loop processes each of the keys in the dictionary. Then, the keys can be used to access each of the values associated with the keys. Example: Print key-value using for loop. Output : Aileen : 2 Auni : 9 Sofea : 1 Ayra : 10 person = {'Aileen':2,'Auni':9,'Sofea':1,'Ayra':10} person.pop('Auni') print(person) person = {'Aileen':2,'Auni':9,'Sofea':1,'Ayra':10} for item in person: print(item , ':' , end=' ') print(person[item])
  • 63. 59 Quick Review 1. It is not necessary to end the command in Python with a semicolon. 2. The indentation in Python is very important. Python uses indentation to indicate a block of code. 3. A variable is created the moment you first assign a value to it. Variables do not need to be declared with any particular type. 4. The categories of python data types are Numeric (Integer, Float, Complex Number), Boolean, Set, Dictionary, Sequence(String, List, Tuple) 5. By default any variable created using input() statement is the type of string. 6. Type Casting is the method to convert the variable data type into a certain data type to the operation required to be performed by users. 7. The conditional statement is used in the decision-making process 8. Looping is used to iterate for specified times 9. Tuple and List are ordered while Set and Dictionary are unordered Programming Exercises 1. Create a variable and store a number's value to the variable. a. Add print() function to display the value of the variable b. Perform addition and multiplication with the variable, then print the result to screen 2. Create a program to convert Kilometres to Miles. 3. Write a program to test if an integer is positive or negative. Your program should: a. Prompt user to input a number. b. Convert the string input to int() c. Check whether the integer is positive or negative d. Print the result.
  • 65. 61 Function In Chapter 2, all the programming instructions are written and executed line by line. This technique is good only for short programs but not practical for large programs. You must learn and practice to break the problem into manageable units. These units can be work, tested, and maintain separately which makes the development process more efficient. A function is a group of related statements that perform a specific task. Functions are like miniature programs that can be called together to form a large program. The properties of function are: • Functions may or may not take a set of parameters. • Functions may or may not have a return value. • Functions are only executed when it is called. • Functions can be defined in one place and called in any place or any other function. Let us see the example of a program that is written using function and the other one that is not. The programs below calculate the total from two integers. The set of values that are used are: • 10 and 20 • 20 and 5 Program 1: Not using function Program 2: Using Function num1 = 10 num2 = 20 sum = num1 + num2 print(sum) num1 = 10 num2 = 25 sum = num1 + num2 print(sum) def sum(num1, num2): sum = num1 + num2 print(sum) sum(10, 20) sum(20, 5)
  • 66. 62 In Program 1, to calculate two sets of values, the same codes are repeated twice. However, in Program 2, there is no repetition. By using the function, we just need two function calls which are sum(10,20) and sum(20,5). Every time we call the function, the program searches for the function name and then executes the codes defined inside the function. Function gives many advantages which are: • Code reusability. • Reduce complexity. • Easier to understand. • Fewer errors because the function is not rewritten. There are two types of functions: 1. Built-in Function 2. User-Defined Function Built-in Function Built-in functions are the predefined functions provided by Python that can be used anywhere in the program. The print() which is used to display the output from a program is one example of a built-in function that is frequently used. Below are some of the built-in functions in python. No Built-in Functions Description 1 max() Return the max from the list of items. 2 sum() Return the sum from the list of items. 3 open() Open file for reading or writing. 4 round() Return number rounded to by ndigits precision after the decimal point. 5 sorted() Return the new sorted element from the list.
  • 67. 63 EXAMPLE: Use max() function to return the maximum value from the list. Output : 100 EXAMPLE: Use round() function to return the floating number in 1 decimal place. Output : 7.875 7.9 Define and Call Function In this section, we will learn the second type of function which is user-defined function. A user-defined function is a function that is written by the programmer. In many cases, most of the programs are developed using user-defined functions. The rules to define a function are: 1. A function is defined using the def keyword followed by the function name, parentheses ( () ), and colon (:). 2. The block of statement in a function starts in a new line and is indented. 3. If the function has parameters, it should be placed within the parentheses (()). max_num = max(10,20,40,100, 1) print(max_num) div = 9.45 / 1.2 print(div) print(round(div,1))
  • 68. 64 The diagram below illustrates how to define and call a function. The output generated is : Welcome to learn Python You will learn basic Python Programming" Function with Parameter(s) A parameter is a variable defined inside the parenthesis in the function header. The parameter is used to receive data from the outside of the function and make the data available within the function itself. You can use many parameters in the function, each of them should be separated by a comma. To call a function with parameters, it is a MUST to include the actual values to pass to the function. The actual value that is provided in the function call is known as an argument. The argument must match with the parameters in terms of: • the number of the parameters. • position of the parameters.
  • 69. 65 The diagram below illustrates a function with parameters. Example: A program to calculate bonus. Output : Bonus : RM 100 Bonus is RM 400 What program does are: • The function has two parameters which are salary and percentage. • Inside function: o The bonus is calculated by a formula: bonus = salary * percentage o Then, print the output to the screen • The function is called for two times : bonus(1000, 0.1) and bonus(2000, 0.2) def bonus (salary, percentage ) : bonus = salary * percentage print("Bonus : RM ", bonus) bonus(1000, 0.1) bonus(2000, 0.2)
  • 70. 66 EXAMPLE: A program prints the maximum from two numbers. Output : Number 1 : 10 Number 2 : 15 Higher number is 15 Returning Values From Function The return keyword in a function is used to return any values to the caller. It means that any values following the return keyword, are passed to the calling statement, which is defined in the function call. Both functions below display the same output which is "Hello". Function 1 is defined without a return statement while Function 2 is defined with a return statement. Function 1 Function 2 def greet(): print "Hello" greet() def greet(): return "Hello" print(greet()) As can be seen, the code in Function 1 used print() statement inside the function body while in Function 2 the print() statement is placed in the function call. When a return statement is used, the function returns the value to the caller and it depends on the caller, what operation to be done with the value. def max_of_two(num1, num2): if (num1> num2): max = num1 else: max = num2 print("Higher number is ",max) a = int(input ("Number 1: ")) b= int(input ("Number 2: ")) max_of_two(a, b)
  • 71. 67 Besides printing the return value to the screen, we may want to assign the value to a variable to do a different kind of operation. EXAMPLE: A program calculates the average and takes the return values and performs multiplication to the value. Output : 6.0 In this program the value return by the function is assign to a variable (x=avg()).The variable x is multiplied by 2 and the output is printed to the screen. Is important to note that, we have to decide what operations we want to do with the return value from the function. If we just call the function without any operation like print(), nothing will be displayed on the screen. You can try the following code, in which it just calls the function without any other operation. def greet(): return "Hello" greet() def avg(n1,n2,n3,n4): avg = (n1+n2+n3+n4) / 4 return avg x = avg(3,5,2,2) bon = x * 2 print(bon)
  • 72. 68 EXAMPLE: A function to calculate the area of a triangle. Output : The area is 100 cm EXAMPLE: A function to calculate Body Mass Index (BMI) Output : Enter weight in kilograms: 60 Enter height in meters: 158 The higher value is 24.03 def areaT(base, height): return 0.5 * base * height print("The area is ", areaT(10, 20) , "cm"); def get_bmi(weight, height): height_in_meter = height/100 bmi = weight / (height_in_meter * height_in_meter ) return bmi w = float(input ("Enter weight in kilograms: ")) h = float(input ("Enter height in centimeters: ")) bmi=round(get_bmi(w, h),2) print("Your BMI is ", bmi)
  • 73. 69 EXAMPLE: A function with more than one return statement Output : Aileen 09-05-2019 A function can return more than one value. To do that, you just need to assign several values after the return keyword, each is separated by a comma. Default Argument Default argument is the function that has the default value assigned to the parameter. Default argument values will be used if no value is given in the call function. To declare the default argument, use equal (=) followed by a value. EXAMPLE: A function with a default parameter Output : Your country is Brunei Your country is Malaysia def name(): name = "Aileen" date_of_birth = "09-05-2019" return name, date_of_birth get_name, dob = name() print(get_name) print(dob) def country(name="Malaysia"): print("Your country is ", name) country("Brunei") country()
  • 74. 70 Here is how the default argument works: • Function country() has a default argument, name = "Malaysia". • The first call function assigns the value = Brunei as the argument, so the program prints "Your country is Brunei". • The second function call has no value assigned to it, so the program takes the default argument as the value and prints "Your country is Malaysia". EXAMPLE: A function to get certification name. Output : Jerry SPM Diploma Degree John SPM Diploma None In this example, many parameters have been used. One of the parameters, cert3 is the default argument. When you have many parameters and some of them are default arguments, you should note that : • Default argument should place at the rightmost of the parameter. • Once the default argument has declared all remaining parameters to the right, it will also be a default argument • The following example shows the wrong way to declare the default argument: def games(game1="Scrabble", game2) def games(game1, game2="Scrabble", game3) • The correct way is: def games(game1, game2="Scrabble") def games(game1, game2, game3="Scrabble") def get_cert (name,cert1, cert2, cert3="None"): print(name) print(cert1, cert2, cert3) get_cert("Jerry", "SPM", "Diploma", "Degree") get_cert("John", "SPM", "Diploma")
  • 75. 71 Named Argument In the previous section, we used the positional argument in the call function. Positional arguments take into account the order of argument that should follow the order of the parameters defined in the function header. Named arguments allow us to ignore the position of the argument. To use a named argument, we have to specify the name of the parameter and its value in the function call. When the value is pass to the function, it will match the name of the parameter with the specified name in the argument. The following diagram illustrates how the named argument works EXAMPLE: A function for a sender to send a message to the receiver. Output : To : Liyana From : Aileen Message : Wonderful def get_msg(sender, receiver, msg): print("To :", receiver) print("From :", sender) print("Message :", msg) get_msg("Aileen",msg="Wondeful", sender="Aileen")
  • 76. 72 In the first argument, “Aileen” is matched with the first parameter, the sender. The second and third are the named arguments. When the named argument is used: • The named argument should be placed at the rightmost of the call function. • Wrong way to placed named argument: get_msg(sender="Aileen", "Liyana", "Wonderful") get_msg(Aileen", "Liyana", msg="Wonderful ") • Correct way to placed named argument: get_msg("Aileen", msg=" Wonderful ",receiver="Liyana") get_msg("Aileen", msg=" Wonderful ", receiver="Liyana") Import and Use Modules A module is a python file that groups together related functions, classes, and code. The module is used to organize large programs by breaking down the programs into small and organize files. Using modules helps with simplifying code, maintenance, comprehensibility because the codes are grouped into smaller programs in different files. There are two types of modules : • User-defined module • Built-in / Standard Module
  • 77. 73 Create user-defined module A user-defined module is a module created by the programmer. To create a module, simply save the code as usual, by using the .py extension. Any python file can be a module. To use a module in a program, use the import keyword followed by the module name. The following diagram illustrates two functions defined within a file called example.py. Use import example (the file name without .py) to import all the content of the file into my_app.py. Once the definition of module example is visible, inside my_app.py, we can use them as if they have been defined in the current file. To call the function in a module, we have to include module name, dot operator(.), and function name. example.add(10,20) ) When we run my_app.py, it will produce: 30 150 There are three methods on how to use modules in a program which are: 1. Import module (as shown previously) 2. Import with renaming 3. From module import list_of_function
  • 78. 74 EXAMPLE: Import module with renaming. When we use the keyword as it creates an alias for the module. To call the function, we just need to specify the alias instead of the module name. EXAMPLE: Use from module import all. Using this method, we can directly call any function inside the module without specifying the module name. EXAMPLE: Use from module import selected function Using this method, we can select the function that we want to include in our program. In this program, only function add() is included in the program. import example as m a = m.add(10, 20) b = m.minus(100, 50) print(a) print(b) from example import * a = add(10, 20) b = minus(100, 50) print(a) print(b) from example import add a = add(10, 20) print(a)
  • 79. 75 Some important points to notes in naming the module: • The only character allowed in naming the module are alphabets, numbers, and underscore. • For normal .py files, we can save files as act3a(iii).py but not for the module. The bracket () is not allowed in naming the modules. The only special character allowed is the underscore. • Modules should have short, all-lowercase names. Underscores can be used in the module name if it improves readability. Built-in Module There are a lot of built-in modules provided by Pythons such as sys, math, random, and many more. To find the list of built-in modules, you can use command help("module") The diagram below shows the list of built-in modules provided by Python.
  • 80. 76 EXAMPLE: Use math and random built-in modules. Output : Square root of 9: 3.0 2 power of 3: 8.0 Random integer between 1-20: 9 Object-Oriented and Its Basic Component Object-Oriented Programming (OOP) is a widely used concept to write powerful applications. OOP provides an approach to structure the programs so that the data held, and the operations performed on the data are bundled together in a class and can be accessed via object. The paradigm of OOP mainly relies on the concept of classes and objects which is illustrated in the diagram below. Figure 1: Class and Object Relationship from math import sqrt, pow from random import * print("Square root of 9: ", sqrt(9)) print("2 power of 3: ", pow(2,3)) print("Random integer between 1-20: ", randint(1,20))
  • 81. 77 The basic component of OOP are : Component Description Class • It is a template or blueprint for the object. • It defines the attributes and methods shared by the same object or class. • A class represents broad categories like car, person, bird. Object • The object is the real-world object that is represented by class • An object is an instance of the class. • You can think of it as a variable assigned to the class. • Example: my_car1 and my_car2 are the objects that represent class Car, each of them represents different values. Attribute • A variable that holds data associated with a class and its objects. • Example: color, type, name Method • It is the function that is defined within the class • It is a block of statement specify what objects can do. • Example : calculate_price() Inheritance • The ability of the child class to inherit the properties (attributes and methods) defined in the parent class. Other components of OOP include Encapsulation and Polymorphism. However, in this e-book, we will cover the most basic component as listed in the table above.
  • 82. 78 Define and Instantiate Class A class can be defined using the following format. class name_of_class () : __ init __ attributes methods About __init__(): • It is a special method that initializes the class (also known as a constructor) • It indicates what data must be included when the class is instantiated. • It also indicates how the data is stored inside the class. • __init__() method is automatically called when the object is created • self is the special variable that must be included when creating a method in a class. • The purpose of self is for the class to have the local variables as defined which may be needed to operate class. Therefore, to create an object you must refer to the __init__(), either it has parameters or not. If it has parameters besides self, it means we must provide values that match with the __init__()whenever we create the object. The following figure shows a class with only a self variable declared as the parameter inside the __init__() method. The output generated from the code above is 1. The __init__() method has one variable named val which has value 1.
  • 83. 79 While, in the following figure, the __init__() method has one more variable which is score. The output generated from the code above is 10 and 1. Next, let create a class Car() which is represented by Figure 1 at the beginning of the OOP section. Define class and initialization method class Car: def __init__(self, manufacturer, color, price): self.manufacturer = manufacturer self.color = color self.price = price In Python, all the attributes(variable) or methods defined inside the class should be accessed using self variable (for example self.color) as shown in the code above.
  • 84. 80 It is a good practice to define a class in a file named after the class. For example, the code above would be stored in a file called Car.py. It makes it easier to find the code associated with the class. Instantiate Class (Create Object) Instantiation refers to the creation of an object. The instance or object of class Car can be created using the name of the class. The values, as defined in the __init__ method, shall be supplied to the class. The following code creates three objects of the class Car. my_car1 = Car(“Volkswagen”, “pink”, 187000) my_car2 = Car(“Perodua”, “blue”, 63000) my_car3 = Car(“Toyota”, “yellow”, 87000) The figure below illustrates the value in objects my_car1, my_car2, and mycar3 after the code above is executed. Each object has the same set of methods and attributes because they are using the same template which is class Car(). However, each object holds different data.
  • 85. 81 Accessing Object Attributes We can access the attributes held by the object my_car1, my_car2, and my_car3 using the dot (.) operator followed by name of attribute: Example : my_car1.manufacturer The statement below print the value of the attributes: print(my_car1.manufacturer, my_car1.color, my_car1.price) print(my_car2.manufacturer, my_car2.color, my_car2.price) print(my_car3.manufacturer, my_car3.color, my_car3.price) The output generated is: Volkswagen pink 187000 Perodua blue 63000 Toyota yellow 87000 It is important to note that we cannot print the class information directly using the instance variables as in the following method: print(my_car1) print(my_car2) print(my_car3) The output generated from this method are : <__main__.Car object at 0x000001DC8F142FD0> <__main__.Car object at 0x000001DC8F142C70> <__main__.Car object at 0x000001DC8F142BE0> Which refers to the name of the class and the hexadecimal number indicates the memory location of the object for class Car().
  • 86. 82 Defining Default String Representation The default string representation is a special method used to convert an object into a string for printing purposes. If we define the method in the class, we can directly print the class information by using the instance variable. This method can be defined using __str__(). The following code shows how to define the default string representation. class Car: def __init__(self, manufacturer, color, price): self.manufacturer = manufacturer self.color = color self.price = price def __str__(self): return self.manufacturer + ' ' + self.color +' ' + str(self.price) Important note about __str__() : • The method must return all the variables in string data type • If the variable is a non-string type like variable price, it should convert to string using the str() function. Adding Instance Method The behavior of the class is defined using a method. You can just think of a method as the function we define in a class. We will define three methods, drive(), park() and display(). Method Explanation drive(self) Print out a statement "The car is moving" park(self, hour) Calculate parking fees based on an hourly rate display(self) Print out car information As shown in the table above, each of the methods has a special variable self as the required parameter in class.
  • 87. 83 Lets us now define the first method, drive(self) class Car: def __init__(self, manufacturer, color, price): self.manufacturer = manufacturer self.color = color self.price = price def drive(self): print("The car is moving") Create the instances of the class: my_car1 = Car("Volkswagen", "pink", 187000) my_car2 = Car("Perodua", "blue", 63000) Then call the attributes name and method drive(). print(my_car1.name) my_car1.drive() print(my_car2.name) my_car2.drive() The output generated is : Volkswagen The car is moving Perodua The car is moving
  • 88. 84 Next is to define method park(). This method has a parameter, hour. def park(self, hour): if (hour <= 0.5): pay = 0 if (hour > 0.5 and hour <= 2): pay = hour * 2 if (hour > 2): pay = hour * 1 print(self.manufacturer, "parking price for", hour, "hours is RM", pay) Method park() access instance variable as self.manufacturer. Remember, the self variable is a MUST when we want to access any variables or methods defined inside the class. We will access method park(). This method needs an argument for parameter hour. my_car1 .park(0.5) my_car1 .park(1.5) my_car1 .park(5) The output generated is : The payment for Volkswagen is 0 The payment for Volkswagen is 3.0 The payment for Volkswagen is 5 Then, let us define method display(). def display(self): print("Car Manufacturer : ", self.manufacturer) print("Car Color : ", self.color) print("Car Price : ", self.price)
  • 89. 85 Create three objects and then access the methods. my_car1 = Car("Volkswagen", "pink", 187000) my_car2 = Car("Perodua", "blue", 63000) my_car3 = Car("Toyota", "yellow", 87000) print(my_car1.manufacturer) my_car1 .display() my_car1 .drive() print() print(my_car3.manufacturer) my_car3.drive() my_car3.park(5) The output generated is : Volkswagen Car Manufacturer : Volkswagen Car Color : pink Car Price : 187000 The car is moving Toyota The car is moving Toyota parking price for 5 hours is RM 5
  • 90. 86 Another Example: Class Person Let us practice defining another example using class Person() which is illustrated below: The class Person() has: • Attributes currentYear and age. The attributes are used to calculate the age. • The __init__() method has two instance attributes which are name and yearborn. These two attributes shall be supplied when the class is instantiated (created) • calculate_age() is a method to calculate the age based on the year born of a person. • display() is a method to display the age of a person. Define class, attributes, and __init__ method. Remember to be careful with indentation. class Person: currentYear = 2021 age = 0 def __init__(self,name,yearborn): self.name = name self.yearborn=yearborn
  • 91. 87 Define method calculate_age(). def calculate_age(self): self.age = self.currentYear - self.yearborn return self.age This method when it is called by the object will calculate the age and replace the initial value of age=0 with the new value. Define method display(). def display(self): print("You are", self.age, "years old") Create two objects for class Person() p1 = Person("Aileen", 2019) print("Hi", p1.name) p1.calculate_age() p1.display() p2 = Person("Aydeen", 1998) print("Hi", p2.name) p2.calculate_age() p2.display() The output generated is : Hi Aileen You are 2 years old Hi Aydeen You are 23 years old
  • 92. 88 Class Inheritance Inheritance is a core feature of OOP. Inheritance enables the subclass to inherits all the attributes and methods from the superclass. The subclass can reuse all the attributes and methods as its own, without the need to define the same attributes and methods again. The syntax to define the subclass is : class SubClass (SuperClass): """ body of class """ In this example, wewill use again the class Person() that we have defined previously. Refer to the illustration below. Here is the definition of class Person(). class Person: currentYear = 2021 age = 0 def __init__(self,name,yearborn): self.name = name self.yearborn=yearborn
  • 93. 89 def calculate_age(self): self.age = self.currentYear - self.yearborn return self.age Next, define the subclass Client()that inherits attributes and methods from the class Person(). class Client(Person): def __init__(self,name,yearborn,projectType): super().__init__(name,yearborn) self.projectType = projectType def projectDetail(self): if self.projectType == "A": officer_incharge = "John Doe" elif self.projectType == "B": officer_incharge = "John Doe" else: officer_incharge = "Sally" print("Name : ", self.name) print("Age : ", self.age) print("Officer Incharge : ", officer_incharge) Here is what we do for class Client(): • The class Client() extends/inherit class Person(). The code to extend is indicated by class Client(Person) • Inside the __init__() method, we used super().__init__(name, yearborn). It means that the attributes name and yearborn refer to the __init__() method defined in superclass Person() • We defined another attribute projectType inside the __init__(). It means when the class Client() is created, it must supply three values for name, yearborn, and ProjectType. • class Client() has method projectDetail() which is programmed to define the person in charge of the project.
  • 94. 90 Let us create the object for the class Client() c1 = Client("Sofea", 1984, "A") c1.calculate_age() c1.projectDetail() Class client() needs three values in the class instantiation as defined in the __init__(). Once instantiated, it can use the method calculate_age() which is inherited from the class Person(). The output generated is : Name : Sofea Age : 37 Officer Incharge : John Doe Let us add class Employee() that also extends the class Person(). class Employee(Person): def __init__(self, name, age, id): super().__init__(name, age) self.id = id def calc_salary(self): salary = 2000 if self.age>=35: salary += 800 return salary class Employee() is different with the class Client(). In Employee() we defined attributes id instead of projectType. We create method calc_salary() which is used to calculate the salary of the employee. Even though Employee and Client are both types of Person, they are under different sub-categories, so they have different attributes and behavior (methods). That is why we separate them into two different classes.
  • 95. 91 We can go further and add a subclass Developer that extends class Employee. Refer to the illustration below: A developer is one of the employees. So, the developer will have all the attributes and methods that the employee has by inherit the class. Class Developer() has a unique method called bonus which depends on the number of projects they involve. Let us define the subclass Developer(). class Developer(Employee): def __init__(self,name, age, id, num_of_project): super().__init__(name, age,id) self.num_of_project = num_of_project def bonus(self): return self.num_of_project * 1000 Here is what we do for class Developer(): • Class Developer() extend class Employee()and class Empoyee() extend class Person(). This enables the class Developer() to inherits all the methods in both class Empoyee() and Person(). • In the __init__() method, we used super().__init__() to refer to both attributes defined in class Empoyee() and Person(). • We add another attribute num_of_project inside the __init__() method. • class Developer() has method bonus() which is used to calculate the bonus received by the developer.
  • 96. 92 Let us compile the code altogether and display the output to the screen. print('Person') p1 = Person("Fatimah", 1987) print("Hi", p1.name, ".You are", p1.calculate_age()) print('-' * 25) print('Client') c1 = Client("Sofea", 1984, "A") c1.calculate_age() c1.projectDetail() print('-' * 25) print('Employee') e1 = Employee("Adi", 1980,"P001") e1.calculate_age() print("Your Salary is", e1.calc_salary()) print('-' * 25) print('Developer') d1 = Developer("Irwan", 1980,"P001",5) d1.calculate_age() print("Your Salary is", d1.calc_salary() + d1.bonus()) The output generated is : Person Hi Fatimah. You are 34 ------------------------- Client Name : Sofea Age : 37 Officer Incharge : John Doe ------------------------- Employee Your Salary is 2800 ------------------------- Developer Your Salary is 7800
  • 97. 93 Methods Overriding Overriding occurs when a method is defined in a class (for example, Person) and also in one of its subclasses (for example, Client). It means that for instance of Person and Client both responded to the request for this method to be run but each has its own implementation of the method. For example, let us assume that we define the method __str__() in the class Person() and Client(). The __str__() definition in class Person() is defined as : While in the Client(), it is defined as :
  • 98. 94 The method in class Client() replace/override the version of __str__() in class Person(). When we print the instance of class Employee() and Client(), the output will differ because each class has its own method. For example: p1 = Person("Fatimah", 1987) p1.calculate_age() c1 = Client("Sofea", 1984, "A") c1.calculate_age() print(p1) print(c1) The output generated is : Fatimah is 34 Client Name is Sofea - Project Type A As can be seen from this, the class Person() prints name and age while class Client() prints name and project type. Things that we should note is : • If we ask an object to perform some operation, then, to determine which version of the method is running, look in the class used to create the instance. If the methods are not defined there, look into the class’s parents. Keep doing that until we find a method that implements the operation requested.
  • 99. 95 Quick Review • Functions are like miniature programs which enable you to divide a program into manageable tasks. • The main advantage of function is because of the reusability. • There are two types of functions which are built-in and user-defined functions. • Function definition starts with keyword def, followed by the function name, parenthesis, the parameter is declared inside parenthesis and a colon. The block of statement in function starts in a new line and is indented. • Functions can have more than one return value. • The default argument is the value assigned to the parameter in the function definition. • Named argument is specifying the parameter name and value in the function call. • Module is a .py file that is used to organize a large program into smaller files. • To use the module, use the import keyword. • There are two types of modules which are built-in modules and user-defined modules. • Some of the basic components in OOP are: Class, Object, Attribute, Method and Inheritance • Attributes of a class refer to the variables and methods are the function defined in the class. • Instantiation is the creation of the object by assigning a variable to the class. • Once the object is created, we can access the attributes and method using the name of the object followed by dot(.) operator and attributes/method that we want to call. • Inheritance allows a class to use members of another class as a part of its own definition.
  • 100. 96 Programming Exercises 1. Write a function that accepts the user's first and last name and prints them in reverse order with a space between them. 2. Use the built-in module to get the Python version you are using (Hint import sys). 3. Write a function that accepts the radius of a circle from the user and compute the area (Formule: Area of circle = πr2 ). 4. Create a new class Item that represents Items in the library : a. Define a new class Item b. When the class is instantiated, you should provide the title, description, quantity, and type of item (which can be a string representing ‘Book’, ‘DVD’, and ‘CD’. This means that there must be an __init__ method that you will need to store the data within the object. c. Define the default string representation. d. Provide three instance method for the class Item : borrow_book(), return_book() and get_balance. The behavior of these methods should be as expected, borrow will decrease the book quantity, return book will increase the book quantity, and balance returns the current book quantity. e. A simpe test applicaton for the class Book is given below: it1 = Item("Basic Python", "Book", 10) it2 = Item("History of Malaysia", "DVD", 5) it3 = Item("The Sound of Music", "CD", 5) print(it1) print(it2) print(it3) it1.borrow_book(3) it1.return_book(1) it1.current_quntity()
  • 101. 97 The following output illustrates the result of running this test application.
  • 102. 98 References Scratch. M. &. Scratch. E. (2020). Coding Python: The Ultimate Tool to Progress Your Python Programming from Good to Great While Making Coding in Scratch Look Easy (Python Programming Language). Luca Pino. (ISBN: 1801326983) Patricia. F. (2020). Python Programming for Beginners: A Kid's Guide to Coding Fundamentals. Rockridge Press. (ISBN: 1646113888) Hunt, J. (2020) A Beginners Guide to Python 3 Programming (ISBN: 978-3-030-20289-7)
  • 103. Publisher POLITEKNIK BALIK PULAU Pinang Nirai, Mukim E, 11000 Balik Pulau, Pulau Pinang. Email: polibalikpulau@pbu.edu.my Website : www.pbu.edu.my Tel : 04-868 9000 Fax : 04-869 2061