INTRO TO PYTHON
NORZILA ISHAK
NURHIDAYAH MOKHTAR
JABATAN TEKNOLOGI MAKLUMATDAN KOMUNIKASI
POLITEKNIK SEBERANG PERAI
INTRO to PYTHON
Norzila Bt Ishak
Nurhidayah Bt Mokhtar
2022
Jabatan Teknologi Maklumat & Komunikasi
©All rights reserved for electronic, mechanical, recording, or otherwise, without prior permission
in writing from Politeknik Seberang Perai.
ii eBook PSP
All rights reserved
No part of this publication may be translated or reproduced in any retrieval system, or
transmitted in any form or by any means, electronic, mechanical, recording, or otherwise, without
prior permission in writing from Politeknik Seberang Perai.
Published by
Politeknik Seberang Perai
Jalan Permatang Pauh, 13500 Permatang Pauh
Pulau Pinang
Editor
Norzila bt Ishak
Nurhidayah bt Mokhtar
Content Reviewer
Muna bt Ishak
Cover Designer
Azilah bt Abd Rahim
Tel : 04-538 3322 Fax : 04-538 9266
Email : [email protected] Website : www.psp.edu.my
FB : politeknikseberangperai Ig : politeknikseberangperai
Perpustakaan Negara Malaysia Cataloguing-in-Publication Data
Norzila Ishak
INTRO to PYTHON / Norzila Bt Ishak, Nurhidayah Bt Mokhtar.
Mode of access: Internet
eISBN 978-967-2774-18-1
1. Python (Computer program language).
2. Scripting languages (Computer science).
3. Government publications--Malaysia.
4. Electronic books.
I. Nurhidayah Mokhtar. II. Title.
005.133
eBook PSP | 2022 iii
Acknowledgement
Assalammualaikum..
Bismillahhirahmannirrahim..
We would like to thank everyone who aided us with this book, including those who read,
wrote, commented on it, and allowed us to cite them, as well as those who assisted in
the editing, proofreading, and designing.
Above all, we want to thank our partner and family for their support and encouragement
despite the time we spent away from them. Thank you very much for your patience.
A special thanks to our Head of Department, without whose assistance this book would
never have been produced and could not be utilised as a reference for our students. Not
to mention our superiors and co-worker’s for their assistance and support in producing
this book, as well as improving the content and topics from time to time.
Last but not least, we apologise for failing to acknowledge those who have assisted us
directly or indirectly. We hope that this book will be helpful to students in achieving good
grades.
Norzila Bt Ishak
Nurhidayah Bt Mokhtar
iv eBook PSP
Preface
This book is designed as a reference book for anyone who are interested in learning
Python. It covers the basics of python.
This book is divided into several chapters. The first chapter is Variable, where it will
covers variable, data types and operators. The second chapter is Conditional and looping
statement and will covers conditional statements and looping statement. The third
chapter is Functions. This chapter will covers functions creation, function overloading
and magic method. The fourth chapter is Class, that will cover the creations of class,
instantiation of class, creation of objects and construction of inheritance. Finally the last
chapter is Modules that covers on how to create modules and import modules.
This book also provides code example to help readers better understand the topic being
convey. This book uses Sublime as code editor and the latest version of python that can
be downloaded at python.org.
eBook PSP | 2022 v
Table of Content
01 Variable and Data Types
Variable
Data Types
Operators and Operators Precedence
Casting
Conditional and Looping Statement
02 if
elif
else
while
for
03 Function
Define Function
Define Call Function
Function Overloading
Magic Method
04Classes
Define Classes
Instantiates Classes
Objects
Construct Inheritance
05 Modules
Import Modules
from import *
from import item name
eBook PSP | Intro to Python 1
01
VARIABLE AND
DATA TYPE
Chapter one description
The emphasis in this chapter is on fundamental Python programming concepts such as variables,
data types, operators and operator precedence, casting.
2 eBook PSP | Topic 1: Variable and Data Type
About Python
Python is a programming language that emphasizes productivity and readability in the
code. Python uses coding that resembles written English. Additionally, rather than using
characters, the coding is done in words and sentences. Guido van Rossum created Python,
which was first released on February 20, 1991. Python is a popular, interpreted, object-
oriented, high-level, and dynamically semantic programming language used for general-
purpose programming. Whether they realize it or not, people use numerous Python-
powered devices on a daily basis. There are a few other factors that make Python an
excellent learning tool:
• It is simple to learn because the time required to learn Python is less than that
required to learn many other languages, allowing you to begin programming sooner.
• It is simple to use for developing new software, and it is often possible to write code
faster when using Python.
• Python is free, open, and multiplatform, which not all languages can claim.
As a general-purpose programming language, Python can be used to create a wide range
of applications. Examples of the various application categories created in Python include:
• Web apps
• Video games
• Audio/video apps
• Mobile apps
• Networking apps
• Database access
• Scientific/mathematical apps
• Security utilities
• Education apps
A Python environment is required to run the Python scripts. A Python standard library
interpreter and pre-installed packages make up an environment. Python programs can be
run in an IDE (integrated development environment) such as PyCharm, Visual Studio Code,
Sublime Text 3, Atom, Jupyter, Spyder, PyDev, Wing, Thonny and etc.
eBook PSP | Intro to Python 3
Variable and Data Types
Variables
Usually, in a programming language, each variable needs to be declared first with a data
type. In Python, variables do not need to be declared but they exist when a programmer
assigns a value to them. Variables can be stored in a variety of data types. Rules for
variables names:
• Must begin with a letter and underscore character.
• Cannot start with number.
• Cannot use reserved words.
• Case sensitive.
• Can only contain alpha-numeric character (A-Z, 0-9) and underscore (_).
Figure 1.1: Example of variables code and the output
Data type
Data types are classes, and variables are instances (objects) of these classes. In code, the
function type () can be used to get the data type of an object. The basic data types in
Python are like:
4 eBook PSP | Topic 1: Variable and Data Type
Figure 1.2: Data Types
a. Numeric (int, float, complex)
int – used to store integer values.
Figure 1.3: Example of integer code and the output
float – used to store decimal points number.
Figure 1.4: Example of float code and the output
complex – used to store the combination of two real number. It contents a real part and
imaginary part (real + (imag)j).
eBook PSP | Intro to Python 5
Figure 1.5: Example of complex code and the output
b. Boolean (bool)
bool – used to determine the truth value of any expression, either True or False.
Figure 1.6: Example of boolean code and the output
c. Sequence (string, list, tuple)
String - A string is a grouping of a few characters enclosed in single (‘ ’) or double (“ ”)
quotation marks. It can be category as an order sequence. It has few methods can
implement using string. str keyword is used to convert others values to string value.
6 eBook PSP | Topic 1: Variable and Data Type
Figure 1.7: Example of string code and the output
List – It's similar to an array and using index number to access the value. It is used to store
several values in a single variable name follow by square bracket symbol like [ ]. It can be
category as an order sequence, it value enables to change, add, access, remove and allow
the duplicate values in the list.
eBook PSP | Intro to Python 7
Figure 1.8: Example of list code and the output
Tuple – It's similar to an array and using index number to access the value. It is used to
store several values in a single variable name follow by round bracket symbol (). It can be
category as an order sequence, it value allow to duplicate but unchangeable. To perform
an activity such as updating a value in a tuple, first convert the variable into a list, then
perform all of the activities in the list, and finally convert back to tuple type.
8 eBook PSP | Topic 1: Variable and Data Type
Figure 1.9: Example of tuple code and the output
d. Set
Set – It's similar to an array and not using index number to access the value. It is used to
store several values in a single variable name follow by curly bracket symbol { }. It can be
eBook PSP | Intro to Python 9
category as an unordered sequence, it unchangeable value and not allow the duplicate
value. Use the provided method shown in table 1.1 to perform an activity such as access,
add and remove value.
Table 1.1: List of some of Python Set Methods
METHODS NAME DESCRIPTION
add() Adds a given element to a set
clear() Removes all elements from the set
copy() Returns a shallow copy of the set
difference() Returns a set that is the difference between two sets
discard() Removes the element from the set
pop() Returns and removes a random element from the set
remove() Removes the element from the set
10 eBook PSP | Topic 1: Variable and Data Type
Figure 1.10: Example of set code and the output
eBook PSP | Intro to Python 11
e. Dictionary
Dictionary – It's similar to an array. It is used to store several values in a single variable
name follow by curly bracket symbol { } and have key and value. It can be category as an
ordered sequence, it value is changeable and not allow the duplicate value. Use the
provided method to perform an activity such as access, add and remove value.
METHOD Table 1.2: List of some of Python Dictionary Methods
clear() DESCRIPTION
copy()
fromkeys() Removes all the elements from the dictionary
get()
items() Returns a copy of the dictionary
keys()
pop() Returns a dictionary with the specified keys and value
popitem()
Returns the value of the specified key
setdefault()
Returns a list containing a tuple for each key value pair
update()
values() Returns a list containing the dictionary's keys
Removes the element with the specified key
Removes the last inserted key-value pair
Returns the value of the specified key. If the key does not exist:
insert the key, with the specified value
Updates the dictionary with the specified key-value pairs
Returns a list of all the values in the dictionary
12 eBook PSP | Topic 1: Variable and Data Type
eBook PSP | Intro to Python 13
Figure 1.11: Example of dictionary code and the output
Casting
It used to assign a data type to a variable and convert a variable's data type to another
data type.
Table 1.3 Example of casting
Code Description
a = int (10) a value is 10
b = int (“10”) b value is 10
c = int (10.10) c value is 10
e = float (10.10) e value is 10.10
f = float (“10.10”) f value is 10.10
g = float (10) g value is 10.0
h = str (“10”) h value is ‘10’
i = str (10) i value is ‘10’
j = str (10.10) j value is ’10.10’
14 eBook PSP | Topic 1: Variable and Data Type
Figure 1.12: Example of casting code and the output
Operators and Operators Precedence
Operator
Operations on variables and values carried out using operators. Type of operator are:
• Arithmetic operators
• Assignment operators
• Comparison operators
• Logical operators
• Identity operators
• Membership operators
• Bitwise operators
eBook PSP | Intro to Python 15
Example code with operators:
Figure 1.13: Example of arithmetic operator code and the output
16 eBook PSP | Topic 1: Variable and Data Type
Figure 1.14: Example of comparison and Logical operator code and the output
eBook PSP | Intro to Python 17
Operators Precedence
When expressions are used, operator precedence refers to the order of priority of operators
in python. Variables, functions, values, and operators are combined to form the
expressions. Below is operator precedence from highest to lowest:
Table 1.4 Operator precedence Meaning
Operators Parentheses
()
** Exponent
+x, -x, ~x Unary plus, Unary minus, Bitwise NOT
*, /, //, % Multiplication, Division, Floor division, Modulus
+, -
<<, >> Addition, Subtraction
& Bitwise shift operators
^
| Bitwise AND
Bitwise XOR
==, !=, >, >=, <, <=, is, is not, in, not in Bitwise OR
not Comparisons, Identity, Membership operators
and Logical NOT
or Logical AND
Logical OR
18 eBook PSP | Topic 2: Conditional and Looping Statement
02
CONDITIONAL AND
LOOPING STATEMENT
Chapter two description
The emphasis in this chapter is on conditional - if, elif and else, looping statement – while and
for.
eBook PSP | Intro to Python 19
Conditional and Looping Statement
Conditional statement
In real life, we face situations in which we must make decisions and then decide what to
do next. Similar situations arise in programming where we must make decisions and then
execute the next block of code based on those decisions. In programming languages,
decision-making statements determine the flow of programme execution.
In Python, the if-else elif statement is used to make decisions.
if – a keyword is used to generate a decision, it contains a body of code to test that will
produce the result when the condition is true. Below is the if syntax.
If (condition):
Statement
Example of code:
Figure 2.1: Example of if code and output
Indentation
Python uses indentation (whitespace at the start of a line) to define scope in code. Curly-brackets
are frequently used for this purpose in other programming languages.
20 eBook PSP | Topic 2: Conditional and Looping Statement
Figure 2.2: Example error without indentation in if block
elif – a keyword is used when the code has multiple conditions, it generates another
decision if the previous conditions are false. It also contains a body of code to test that will
produce the result when the condition is true. Below is the elif syntax.
If (condition):
Statement
elif(condition):
Statement
Example of code:
Figure 2.3: Example of elif code and output
else – a keyword is used to captures anything not caught by the previous conditions. It
also contains a body of code to produce the result. n Python, else can also be used in
looping statements. Below is the else syntax.
If (condition):
eBook PSP | Intro to Python 21
else: Statement
Statement
Example of code:
Figure 2.4: Example of else code and output
Example code conditional statement:
Figure 2.5: Example selection code and output
Nested if – when in if code statement has another if code statement. Below is the nested
if syntax.
22 eBook PSP | Topic 2: Conditional and Looping Statement
If (condition):
If (condition):
Statement
Example of code:
Figure 2.6: Example of nested if code and output
Looping statements
Python The for loop is used for sequential traversal, that is, iterating over an iterable such
as a String, Tuple, List, Set, or Dictionary.
There is no C-style for loop in Python, i.e. for (i=0; in; i++). The "for" loop is similar to the
"each" loop in other languages.
For loops in Python only support collection-based iteration.
eBook PSP | Intro to Python 23
while – a keyword is used to loop through a set of statements when the condition is true.
The loop is terminated when the condition is false. To control the looping process, three
components should be in the loop statement: initialization, condition, and
increment/decrement. The initialization must have an assigned value. When no value is
specified, the initialization is set to the default value of 0. Below is the while syntax.
initialization
while (condition):
Statement
increment/decrement
Example of code:
Figure 2.7: Example of while code and output
Example code while statement:
Figure 2.8: Example while code and output
24 eBook PSP | Topic 2: Conditional and Looping Statement
for – a keyword is used to loop through a set of statements when the condition is true. The
loop is terminated when the condition is false. To control the looping process, three
components should be in the loop statement: initialization, condition, and
increment/decrement. When no value is specified, the initialization is set to the default
value of 0. Below is the for syntax.
for (initialization, condition, increment/decrement):
Statement
Example of code:
Figure 2.9: Example of for code and output
Example code for statement:
eBook PSP | Intro to Python 25
Figure 2.10: Example for code and output
break – keyword is used to terminate a loop through a set of statements when the
condition is true.
Figure 2.11: Example of break code and output
continue – a keyword is used to skip a loop through a set of statements when the condition
is true then continue the loop process.
Figure 2.12: Example of continue code and output
26 eBook PSP | Topic 2: Conditional and Looping Statement
Nested loop when in loop code statement has another loop code statement.
Figure 2.13: Example of nested loop code and output
Example code conditional and looping statement:
eBook PSP | Intro to Python 27
Figure 2.14: Example of conditional and looping code and output
28 eBook PSP | Topic 3: Function
03
FUNCTION
Chapter three description
The emphasis in this chapter is on using function, function overloading and magic method.
eBook PSP | Intro to Python 29
Function
A function is a concept in which a block of code is only executed once it is called. Data can
be passed into functions known as parameters. A function also could return data as a
result.
def a keyword is used to declare a function. In function declaration also have parameters.
If the function does not know the argument number to receive, use the asterisk symbol (*)
before the parameter name. Below is the function declaration syntax.
def function_name (parameters):
Statement
return
Arguments are values that may be placed inside the call function brackets to pass them
to that function.
return statements is a statement inside the function definition that will return or pass any
result of the function back to call function. If the function not have any return statement,
the none value will pass back to call function.
Call function means wanting to use any function that already exists. The trick is to write
the name of that function to be used and enclose it with brackets (). Below is the call
function syntax.
function_name (arguments)
30 eBook PSP | Topic 3: Function
Figure 3.1: Example of function code and output
Figure 3.2: Example of function code and output
eBook PSP | Intro to Python 31
Function Overloading
Function overloading is the process of calling the same method with different arguments.
However, Python does not support this procedure. Because Python only uses the most
recent define method. If a user overloads the method, Python will give a TypeError.
However, this problem can be solved by defining functions and setting the default values
of parameters to one in the class or can create different class for each function.
Figure 3.3: Example of function overloading code and output
Code at Figure 3.4 is a solution for the function overloading code at Figure 3.3.
32 eBook PSP | Topic 3: Function
Figure 3.4: Solution function overloading code and output
Code at Figure 3.5 is a solution for the function overloading code at Figure 3.3 using
class code.
eBook PSP | Intro to Python 33
Figure 3.5: Solution function overloading using class code and output
Magic Method
Magic methods are special methods provided by the built-in class. Use a double
underscore symbol to start and end this method. The invocation magic method in the
program is internal only and not directly involved. It means when a user does the + operator
in code, the magic method __add__ is called.
Figure 3.6: Example of magic method code and output
34 eBook PSP | Topic 4: Classes
04
CLASSES
Chapter four description
The emphasis in this chapter is on creating classes, instantiation of class, use of objects and
construction of inheritance.
eBook PSP | Intro to Python 35
Object-oriented Programming (OOP)
Object-oriented Programming (OOP) is a concept of programming using classes and
objects in code. It makes the program look simply, with reusable blocks of code, specific
behaviour blocks of code, and easy to debug. The OOP code block consists of classes,
objects, methods, and attributes.
Class is a blueprint block of code that has a collection of instance variable and related
methods that define a particular object. To create a class in code, use the syntax below. It
starts with the class keyword, followed by the class name, and then the start blocks of
class code.
class Class_Name:
statements
Object is an instance class. Its role is to represent the memory allocation required for
storing variable data as a copy of the class with actual values. Each object in a class has
a copy of the class's data members. Because when a user creates a class object, a copy
of each data variable defined in that class is created. To create an object of class, use the
syntax below. It starts with the object name followed equal symbol and then class name.
object_name = class_name()
__init__() method is constructor in python class. It is also known as instance attributes.
This method holds that all of the class's attributes are declared. It will also be the first thing
to run after the object is created.
Instance method is a function that will act as the behaviour of a class. It will be defined in
the class code. One class may have multiple instance methods depending on the class
history.
pass keyword is used when the class is created but does not have any other properties or
methods in the class.
36 eBook PSP | Topic 4: Classes
Figure 4.1: Example of class and object code and output
Figure 4.2: Example on how to use pass keyword
eBook PSP | Intro to Python 37
Figure 4.3: Example of class and object code and output
38 eBook PSP | Topic 5: Modules
05
MODULES
Chapter five description
The emphasis in this chapter is on creating modules and implementing modules.
eBook PSP | Intro to Python 39
Import and Use Modules
Module is a set of codes that are stored in one file name. It can also be called a library of
code. In a module, you can have variables, functions, classes, etc. A module can be created
by saving a file of code or program under a.py file, and to use a module can be called using
import statements.
Import is a keyword that allows code in any module to be available used in other code. To
use an import module, start by typing the import keyword, then the module name. It will
search for the module name and then bind the results to a name in the module's local
scope of code. This concept will make the code reusable.
import module_name
There are steps to use the import module. First, create a module with a few lines of code,
then save the file as any module named.py. After that, create a new file that contains an
import module in this file. An import file can access all or a few of the contents of a module
file.
Figure 5.1: Example code of file module - areaModule.py
Line 1 at Figure 5.2 is a way of writing import code to use module areaModule.py in code
file main.py. By using module name, all item in module code can be access by dot (.)
operator. For the example to use function area of rectangle, write the module name follow
by dot operator then function name. Below is syntax and example of code.
Example: Module_Name.variabe / function name () / etc
areaModule.area_rectangle(2,2)
40 eBook PSP | Topic 5: Modules
Figure 5.2: Example of code and output for file import module main.py
From…import * is a keyword that allows a user to use all the items found in the module
code without limits and without using the dot operator. Below is the syntax to write code
and line 1 at Figure 5.3 is the example.
from moduleName import *
Code at Figure 5.3 is a way of writing import code to use module areaModule.py using
from…import*. Directly use all item name in module code can be access without dot (.)
operator like line 3, 6 and 9.
Figure 5.3: Example of code and output for file from import module main.py
eBook PSP | Intro to Python 41
From…import itemName is a keyword that allows a user to use the specific items in the
module code without using the dot operator. Below is the syntax to write code and line 1
at code Figure 5.4 is the example.
from moduleName import itemModule1, itemModule2…
Code at Figure 5.4 is a way of writing import code to use module areaModule.py using
from…import itemName. Directly use the specific item name in module code and can be
access without dot (.) operator like line 3 and 6. If an item module is not declared in the
import code but it has in the body of code to access the item, a debugging error will be
produced.
Figure 5.4: Example of code and output for file from import module main.py
42 eBook PSP | Topic 5: Modules
REFERENCE
Campbell, S. (2022, October 8). Python tutorial for beginners: Learn programming basics [pdf].
Guru99. Retrieved October 28, 2022, from https://www.guru99.com/python-tutorials.html
Learn Python - Free Interactive Python tutorial. Learn Python - Free Interactive Python Tutorial.
(n.d.). Retrieved October 28, 2022, from https://www.learnpython.org/
Learn Python programming. Programiz. (n.d.). Retrieved October 28, 2022, from
https://www.programiz.com/python-programming
Learn python tutorial - javatpoint. www.javatpoint.com. (n.d.). Retrieved October 28, 2022, from
https://www.javatpoint.com/python-tutorial
Python programming language. GeeksforGeeks. (n.d.). Retrieved October 28, 2022, from
https://www.geeksforgeeks.org/python-programming-language/?ref=lbp
Python tutorial. Python Tutorial - Master Python Programming For Beginners from Scratch. (2022,
October 26). Retrieved October 28, 2022, from https://www.pythontutorial.net/
W3schools. (n.d.). Python Tutorial. Python tutorial. Retrieved October 28, 2022, from
https://www.w3schools.com/python/
POLITEKNIK SEBERANG PERAI E ISBN 978-967-2774-18-1
JALAN PERMATANG PAUH INTRO TO PYTHON
13500 PERMATANG PAUH
PULAU PINANG
http://www.psp.edu.my