0% found this document useful (0 votes)
3 views30 pages

Manual Ver 1-0 2022

This Python Programming Training Manual provides an introduction to Python, covering the use of Python IDLE, reserved words, important characteristics, variables, data types, and basic operations. It includes explanations of string manipulation, list creation, and built-in functions for handling data. The manual serves as a comprehensive guide for beginners to understand Python programming concepts and syntax.

Uploaded by

2024963861
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views30 pages

Manual Ver 1-0 2022

This Python Programming Training Manual provides an introduction to Python, covering the use of Python IDLE, reserved words, important characteristics, variables, data types, and basic operations. It includes explanations of string manipulation, list creation, and built-in functions for handling data. The manual serves as a comprehensive guide for beginners to understand Python programming concepts and syntax.

Uploaded by

2024963861
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 30

Python Programming

Training Manual

Prepared By

Abdul Rahman Mohamad Gobil


Python Programming Training Manual Version 1.0

AN INTRODUCTION TO PYTHON
• The entire course will use python IDLE as the platform to develop python script (program).
• Python IDLE can be downloaded from the following link:

https://www.python.org/

Python
Documentation
Online interpreter

Downloadable
interpreter

• Pyhton.org contain all python resources such as interpreter, documentation, online


interpreter etc,
• User can download the latest version of python IDLE from this website
• Python IDLE consist of two modes:
i) Interactive shell model

Interactive shell mode allows user to write python and get the output instantly.

ii) Editor mode

Editor mode allows user to write a set of statements and execute the statement as a
group of statement.

Interactive Shell Mode Editor Mode

2|Page
Python Programming Training Manual Version 1.0

RESERVED WORDS
The following table lists all reserved words in Python. Each of these words has special meaning in
python and cannot be used as the name of variables or any other identifier in your program.

All reserves words in python were written using lowercase letters only.

and exec not


assert finally or
break for pass
class from print
continue global raise
def if return
del import try
elif in while
else is with
except lambda yield

IMPORTANT CHARACTERISTICS OF PYTHON


• Python is case sensitive language

Python and python are two different object.

• Python uses indentation to create a block the program

Indented block of statement.

if score > 50:


print('Congratulation ')
print('You have passed ')
else
print('Sorry, try again’)
print('Failed ')

Unindented block of statement

if score > 50:


print('Congratulation ')
print('You have passed ')
else
print('Sorry, try again’)
print('Failed ')

3|Page
Python Programming Training Manual Version 1.0

VARIABLES
• In python a variable a name given by the user to point a specific value.
• For examples:

5
number = 5 number

20
score = 20 score

'Jebat'
name = 'Jebat' name

temperature = 39.6 39.6


temperature

• In python there is no specific variable declaration statement like other languages such as
C++ or Java. However, it is advisable to initialise the variable before using it and maintain
specific naming convention.
Comparison between C++ and Python

C++ Python

int number1 = 5, number = 8, sum; number2 = 8


sum = number1 + number2; sum = number1 + number2

4|Page
Python Programming Training Manual Version 1.0

DATA TYPES
• Basic data type in python
1. Integer (int)
2. Decimal (float)
3. String (str)
4. Boolean (bool)

• Extended Data Type (Container)


1. Tuple
2. List
3. Dictionary

• In python a variable is not associated with specific type of data permanently. A variable
can point to any type of data.
• The keyword type is used to check the current type of data pointed by a variable.

5
>>> number = 5 number
>>> type(number)
<class 'int'>

5
number = 3.4
number
>>> type(number)
<class 'float'> 3.4

number 3.4
number = 'five'
>>> type(number) 'five'
<class 'str'>

5|Page
Python Programming Training Manual Version 1.0

LINE CONTINUATION
• A long statement can be split across two or more lines by terminating each line
(except the last line) with a backslash character (\).

>>> lyric = "Negara Ku, Tanah Tumpahnya Darah ku" + \


"Rakyat Hidup, Bersatu dan Maju"

>>> lyric
'Negara Ku, Tanah Tumpahnya Darah kuRakyat Hidup, Bersatu dan
Maju'

PRINTING THE OUTPUT ON THE SCREEN


• print() function is used to print the output on the screen.
• Syntax:
print(output1, output2, …output)
• Examples:
>>> print('Hello')
Hello
>>> number = 5
>>> print(number)
5
>>> print(5 + 6)
11
>>> print(number + 2)
7
>>> print('The variable number contains ', number)
The variable number contains 5

6|Page
Python Programming Training Manual Version 1.0

GETTING INPUT FROM THE USER


• input() function is used to receive input from the user thru keyboard entry.

• input() function receives a string as input. Conversion is required if the program


requires the user to enter numeric or any other types of data.

number = int(input('Enter a number : '))

Enter a number : 5

Convert '5' to an
integer value using
int() function

5
number

7|Page
Python Programming Training Manual Version 1.0

CONVERTER FUNCTIONS
• There are three function that can be used to convert string input into numeric types as
follows:

i) int()

This function is used to convert the string input into an integer values as follows:

>>> num = int(input('Enter a number : '))


Enter a number : 45
>>> type(num)
<class 'int'>

This function will produce error message if user enters floating point value.

Enter a number : 4.5


Traceback (most recent call last):
File "<pyshell#0>", line 1, in <module>
num = int(input('Enter a number : '))
ValueError: invalid literal for int() with base 10: '4.5'

ii) float()

>>> num = float(input('Enter a number : '))


Enter a number : 4.5
>>> type(num)
<class 'float'>

iii) eval()
This function will evaluate the expression to an integer value of floating-point value
as appropriate.
>>> num = eval(input('Enter a number : '))
Enter a number : 4
>>> type(num)
<class 'int'>
>>> num = eval(input('Enter a number : '))
Enter a number : 4.5
>>> type(num)
<class 'float'>

8|Page
Python Programming Training Manual Version 1.0

STRING
Overview and String Declaration

• Stiring are arrays of bytes representing Unicode character.


• A single character is considered as a string with a length of 1.
• Square bracket ([) and (]) can be used to access elements of the string.
• A string can be enclosed by single quotes (' ') or double quotes (" ").
• Examples of string declaration:

>>> str = 'Hello'

OR

>>> str = "Hello"


index

-5 -4 -3 -2 -1
str 0 1 2 3 4

' H' 'e' ' l' ' l' ' o'

• Square bracket ([) and (]) can be used to access elements of the string.

>>> str[0]
'H'
>>> str[-1]
'o'

• An attempt of accessing an index out of the range will cause an IndexError.

>>> str[5]
Traceback (most recent call last):
File "<pyshell#12>", line 1, in <module>
str[5]
IndexError: string index out of range

9|Page
Python Programming Training Manual Version 1.0

Manipulating a String Using the Built-in Functions

• Finding the length of a string

>>> str = "Malaysia"


>>> len(str)
8

• We can extract part of a string by slicing it using colon symbol (:).

Syntax:

stringName[x:y]

x is beginning index and y is the index after the last index to be sliced.

For example:

>>> str = "Malaysia"


>>> str[0:4]
'Mala'

The above statement slices the string start with index 0 until index 3.

• The following diagram shows several example of string slicing.

>>> str[-8:-5]
'Mal'

>>> str[0:3]
>>> str[:3]
'Mal'
'Mal'

-8 -7 -6 -5 -4 -3 -2 -1
0 1 2 3 4 5 6 7

'M' ' a' ' l' 'a' 'y' ' s' ' i' ' a'

>>> str[:5] >>> str[5:]

'Malay' 'sia'

10 | P a g e

>>> str[:]
'Malaysia'
r
Python Programming


Training Manual

Functions to manipulate a string are summirze in the following figures.


Version 1.0

Lowercase every alphabetical


>>> str.lower() character in the string
>>> str.startswith('M') 'malaysia'
True
True
>>> max(str)
'y'
'M' ' a' ' l' ' a' 'y' ' s' ' i' 'a'
>>> min(str)
>>> str.swapcase()
'M'
'mALAYSIA'
>>> str.startswith('m') Convert every alphabetical character to
with('M')
lowercase or vice versa
False
True
with('M')
True >>> len(str) Return the length of a string

8
>>> str = "the walking dead"
>>> str.title()
Capitalize the first letter of each word
'The Walking Dead' in the string

with('M')
True
't' 'h' 'e' '' 'w' 'a' 'l' 'k' 'i' 'n' 'g' 'd' 'e' 'a' 'd'

>>> str.istitle()
False

' H' 'e' ' l' ' l' ' o' ' H' 'e' ' l' ' l' 'o' ''
>>> str.upper() >>> str.rstrip()
'HELLO' 'Hello'

Removes spaces from the right side of the


Uppercase every alphabetical character string

11 | P a g e
Python Programming Training Manual Version 1.0

LIST
Overview and List Declaration

• A list is a sequence of data values called items or elements.


• An item can be any type of data and do not have to all be the same type.
• A list is written as a sequence of data values separated by commas and enclosed in
square brackets([ and ]).
• Examples of list declarations:

number = [34,56,87,25,1,689]
grade = ['A', 'B', 'A-', 'D']
countries = ['Malaysia', 1957, 'Singapore', 1965]

Accessing element in the list


Each element in the list has a unique index starting from 0 the length - 1 as per illustrated
the following figure:

indices

0 1 2 3 4 5
number
34 56 87 25 1 689
-6 -5 -4 -3 -2 -1

Negative indices

>>> number[0]
34
>>> number[4]
1

A list can be referenced from the end of the list starting from -1, -2 and so on as
follows:
>>> number[-1]
689
>>> number[-3]
25

12 | P a g e
Python Programming Training Manual Version 1.0

Creating a list

• A list can be created by using the range and list function as follows:
>>> series = list(range(1,5))
>>> series
[1, 2, 3, 4]

Manipulating a list using built-in functions

• The following examples demonstrate the use several functions to manipulate the list.

a) Determine the size of a list using len() function.

>>> number = [34,56,87,25,1,689]


>>> len(number)
6

b) Printing the contain of list using print() function

>>> print(number)
[34, 56, 87, 25, 1, 689]

c) Appending new element into a list list using append() function


>>> number.append(18)
>>> print(number)
[34, 56, 87, 25, 1, 689, 18]

d) Extending a list using another list by adding the new list at the end of current list.
This task is achievable by using extend() function
>>> number2 = [801, 91]
>>> number.extend(number2)
>>> print(number)
[34, 56, 87, 25, 1, 689, 18, 801, 91]

e) A list can be sorted by using sort() function as follows:

>>> number = [34,56,87,25,1,689]


>>> number.sort()
>>> print(number)
[1, 25, 34, 56, 87, 689]

13 | P a g e
Python Programming Training Manual Version 1.0

f) Inserting new elements at specific location (index) of the list using insert()
function
Syntax:
listname.insert(position, value)

Example: >>> lst = [34, 56, 78]


>>> lst.insert(1,68)
>>> print(lst)
[34, 68, 56, 78]

If the position is greater that the of the list, the value will placed at the end the
list as follows:

>>> lst.insert(9,13)
>>> print(lst)
[34, 68, 56, 78, 13]

g) Removing and returns the element at the end of the list using pop() function.
>>> print(lst)
[34, 68, 56, 78, 13]
>>> lst.pop()
13
>>> print(lst)
[34, 68, 56, 78]

You can remove the element at specific index by using lst.pop(index)

>>> lst.pop(1)
68
>>> print(lst)
[34, 56, 78]

h) A string can be split and assign the values into a list using split() function.
>>> str = "Tanah Tumpah Darah Ku"
>>> lst = str.split()
>>> lst
['Tanah', 'Tumpah', 'Darah', 'Ku']

>>> profile = "john/**&&^^%/12-01-2019/admin"


>>> profile.split("/")
['john', '**&&^^%', '12-01-2019', 'admin']

14 | P a g e
Python Programming Training Manual Version 1.0

Nested Lists

• A list can be a multidimensional or contains several lists as follows:


population = [['Mambau',34000],['Rantau',43000],['Rembau',94000]]

0 1
0 'Mambau' 34000
1 'Rantau' 43000
2 'Rembau' 94000

• The following syntax is used to access element(s) of a list”

Identifier[column][row]
>>> population[0]
['Mambau', 34000]

>>> population[0][0]
'Mambau'

>>> population[1][1]
34000

>>> population[:2]
[['Mambau', 34000], ['Rantau', 43000]]

>>> population[1:]
[['Rantau', 43000], ['Rembau', 94000]]

• A list can contain tuples as the list’s elements

>>> voters = [('Mambau',20000),('Rantau',18000),('Rembau',45000)]


>>> voters
[('Mambau', 20000), ('Rantau', 18000), ('Rembau', 45000)]
>>> voters[1]
('Rantau', 18000)
>>> voters[1:]
[('Rantau', 18000), ('Rembau', 45000)]
>>> voters[1][0]
'Rantau'
>>> totalVoters = voters[0][1] + voters[1][1] + voters[2][1]
>>> >>> totalVoters
83000

15 | P a g e
Python Programming Training Manual Version 1.0

Copying Lists

• A list identifier is a pointer to the location of the list. Therefore, an assignment


operator (=) cannot be used to copy a list to another as follows:

>>> lst1 = [34,56,78]


>>> lst2 = lst1

lst1 34 56 78

Lst2

Update any element in the list will reflect both identifiers as follows:

>>> lst1[2] = 56
>>> lst1
34 56 78 56
[34, 56, 56]
>>> lst2
[34, 56, 56]

The appropriate method to copy a list to another list is as follows:

>>> lst2 = lst1[:]

lst1
34 56 78

Lst2 34 56 78

>>> lst1[2] = 56
>>> lst1
[34, 56, 56]
>>> lst2
[34, 56, 78]

16 | P a g e
Python Programming Training Manual Version 1.0

List of functions to manipulate the list

Given the following list declarations:


words = ['book', 'cook', 'look']
nums = [87, -45, 98, 12, 43, 87]
animals = ['tiger', 'lion', 'snake']
vowels = ['a', 'e', 'i', 'o']
scores = [45,67,80]

The following table contains all functions to manipulate the list:

Function Example Result Description


Returns the number of
len Len(words) 3
items in the list

Returns the greatest value


max max(nums) 98 (items must have the same
type)

Returns the least value


min min(nums) -45 (items must have the same
type)

Returns the total of all


sum sum(nums) 282 items in the list (The items
must be the same type)

Returns the number of


count nums.count(87) 2
occurrences of an object

Returns the index of the


index nums.index(87) 0 first occurrence of the
object

>>> words Reverse the order of items


reverse words.reverse()
['look', 'cook', 'book'] in the list
>>> animals
clear animal.clear() Empty the list
[]
>>> vowels Insert the object at the end
append vowels.append('u')
['a', 'e', 'i', 'o', 'u'] of the list
>>> scores Insert new list’s items at
extend scores.extend([34,67])
[45,67,80,34,67] the end of the list
>>> words Remove items with stated
del del words[-1]
['look', 'cook'] index
>>> nums Removes the first
remove nums.remove(87)
[-45, 98, 12, 43, 87] occurrence of an object
>>> words Insert new item before the
insert words.insert(1,'hook')
['book', 'hook', 'cook', 'look'] item of given index
Concatenation. Same as
+ [1,'x'] + [2,'y'] [1,'x', 2,'y']
[1,'x'].extend([2,'y'])
* [0] * 3 [0, 0, 0] List repetition

17 | P a g e
Python Programming Training Manual Version 1.0

Tuples
1. A tuple is a type of sequence that resembles a list however unlike l list, a tuple is
immutable.
2. A tuple is indicated by using parenthesis ().

Syntax:
identifier = (list of elements in the tuple separated by comas)
Example:
>>> vowel = ('a','e','i','o','u')
>>> vowel
('a', 'e', 'i', 'o', 'u')

3. A new tuple can be created by merging another tuples as follows:

>>> meats = ('fish', 'poultry')


>>> fruits = ('apple', 'banana')
>>> food = meats + fruits
>>> food
('fish', 'poultry', 'apple', 'banana')

4. A new tuple can also be created from a list as follows:

18 | P a g e
Python Programming Training Manual Version 1.0

EXERCISES
1. Determine the output of the following program.

a = 2
b = 3
print((a + b,))
print((a + b))
print(())

2. Determine the output of the following program.

companies = [("Apple", "Cupertino", "CA"), ("Amazon.com", "Seattle", "WA"),


("Google", "Mountain View", "CA")]
(name, city, state) = (companies[1][0], companies[1][1],companies[1][2])
print(name, " is located in ", city, ", ", state, ".", sep = "")

Answer:
Amazon.com is located in Seattle, WA.

19 | P a g e
Python Programming Training Manual Version 1.0

Program Control
Statements

20 | P a g e
Python Programming Training Manual Version 1.0

Selection Statement
1. If statement

Syntax:

if condition:
indented block of true_statements

Example:

a)
if score > 50:
print('Congratulation!')
print('You have passed the examnination')

b)
var = 'Congratulation!'
if isinstance(var,str)
print('This is a string\n')

c)
var = 123
if var.isdigit()
print('This is a number\n')

21 | P a g e
Python Programming Training Manual Version 1.0

2. If..else statement

Syntax:

if condition:
indented block of true_statements
else:
indented block of false_statements
Example:

if score > 50:


print('Congratulation!')
print('You have passed the examnination')
else:
print('Sorry!')
print('You have falied the examnination')

3. If..elif statement

Syntax:

22 | P a g e
Python Programming Training Manual Version 1.0

if condition:
indented block of true_statements
elif condition:
indented block of true_statements
elif condition:
indented block of true_statements
elif condition:
indented block of true_statements
else:
indented block of default_statements

Example:
score = int(input('Enter a score : '))

if score >= 90:


grade = 'A'
elif score >= 70:
grade = 'B'
elif score >= 50:
grade = 'C'
elif score >= 30:
grade = 'D'
elif score >= 10:
grade = 'E'
else:
grade = 'F'

print('Your grade is ', grade)

23 | P a g e
Python Programming Training Manual Version 1.0

Loops Statement
1. For statement

24 | P a g e
Python Programming Training Manual Version 1.0

2. While statement

25 | P a g e
Python Programming Training Manual Version 1.0

Graphical User Interface

26 | P a g e
Python Programming Training Manual Version 1.0

Graphical User Interface (GUI)


1. GUI based program opens a window and wait for the user to manipulate window objects
with the mouse which is also known as user-generated events.
2. Examples of user-generated events are mouse clicks, trigger operations in the program
to respond by pulling in inputs, processing them, and displaying results.
3. This type of programming called event-driven programming.
4. Event-driven programming used Model-View-Controller (MVC) architecture.
5. The MVC consists of three components as illustrated in the following diagram:

View

Controller

Model

6. Steps in event-driven programming:


STEP 1 : Define a new class to represent the main application window
STEP 2 : Instantiate the class of window objects needed for this application, such as
labels, fields, and command buttons.
STEP 3 : Position these components in the window
STEP 4 : Instantiate the data model and provide for the display of any default data in the
window objects.
STEP 5 : Register controller methods with each window object in which an event
relevant to the application might occur.
STEP 6 : Define these controller methods.
STEP 7 : Define a main function that instantiates the window class and run the
appropriate method to launch the GUI.

27 | P a g e
Python Programming Training Manual Version 1.0

7. The GUI interface is created using several types of widgets as follow:

28 | P a g e
Python Programming Training Manual Version 1.0

Graphical User Interface Using tkinter


Sample 1: Circle Area Calculator

29 | P a g e
Python Programming Training Manual Version 1.0

Graphical User Interface Using tkinter


Sample : Rectangle Area Calculator

30 | P a g e

You might also like