BATTARAMULLA
UNIT 08
PYTHON PROGRAMMING
8.1 - INTRODUCTION
Monday, April 15, 2024 ESOFT METRO COLLEGE - BATTARAMULLA 2
INTRODUCTION
• A general-purpose programming language.
• Created in 1991 by Guido Van Rossum.
• Python is:
• INTEPRETED.
• INTERACTIVE.
• OBJECT-ORIENTED.
• BEGINNER'S LANGUAGE.
Monday, April 15, 2024 ESOFT METRO COLLEGE - BATTARAMULLA 3
8.1.1 – FEATURES OF PYTHON
Monday, April 15, 2024 ESOFT METRO COLLEGE - BATTARAMULLA 4
8.1.1 – FEATURES OF PYTHON
• Easy-to-Learn. • GUI Programming.
• Easy-to-Read. • Scalable.
• Easy-to-Maintain.
• A broad standard library.
• Interactive mode.
• Portable.
• Extendable.
• Databases.
Monday, April 15, 2024 ESOFT METRO COLLEGE - BATTARAMULLA 5
8.1.2 – FIRST SIMPLE PROGRAM
Monday, April 15, 2024 ESOFT METRO COLLEGE - BATTARAMULLA 6
8.1.2 – FIRST SIMPLE PROGRAM
• Please refer to Python™ 3 Installation Guide to make your computer ready to run Python™
programs.
Monday, April 15, 2024 ESOFT METRO COLLEGE - BATTARAMULLA 7
8.2 – USING VARIABLES IN PYTHON™
Monday, April 15, 2024 ESOFT METRO COLLEGE - BATTARAMULLA 8
8.2 – VARIABLES
• Reserved memory locations to store data.
• Created in the main memory (RAM).
• Once the program is finished, the variables it created will be lost.
Monday, April 15, 2024 ESOFT METRO COLLEGE - BATTARAMULLA 9
8.2.1 – ASSIGNING VALUES TO VARIABLES
Monday, April 15, 2024 ESOFT METRO COLLEGE - BATTARAMULLA 10
8.2.1 – ASSIGNING VALUES TO VARIABLES
• No explicit declaration is needed.
• Just give a name and assign a value. Then you can use it until the end at any point.
• Example: Assignment
Operator
Name of Value to be saved inside the
the variable
variable
Monday, April 15, 2024 ESOFT METRO COLLEGE - BATTARAMULLA 11
PROGRAM NO 1
#Numeric Data
mark01 = 85 #Non-Decimal Values
Go to Python Numbers Again
mark02 = 85.64 #Decimal Values
#Non-Numeric Values
name = ‘Dilan’
address = “No 57, Main Street, Battaramulla”
Monday, April 15, 2024 ESOFT METRO COLLEGE - BATTARAMULLA 12
8.2.2 – STANDARD DATA TYPES
Monday, April 15, 2024 ESOFT METRO COLLEGE - BATTARAMULLA 13
8.2.2 – STANDARD DATA TYPES
• Will be covered in 8.6 - SPECIAL DATA TYPES lesson.
Monday, April 15, 2024 ESOFT METRO COLLEGE - BATTARAMULLA 14
8.3 – PYTHON™ OPERATORS
Monday, April 15, 2024 ESOFT METRO COLLEGE - BATTARAMULLA 15
8.3.1 – WHAT IS AN OPERATOR?
Monday, April 15, 2024 ESOFT METRO COLLEGE - BATTARAMULLA 16
8.3.1 – WHAT IS AN OPERATOR?
• Special symbols that can perform arithmetic computations, logical comparisons or value
assignments.
• Typical Operation:
OPERATOR
LEFT OPERAND RIGHT OPERAND
Monday, April 15, 2024 ESOFT METRO COLLEGE - BATTARAMULLA 17
8.3.2 – PYTHON™ ARITHMETIC OPERATORS
Monday, April 15, 2024 ESOFT METRO COLLEGE - BATTARAMULLA 18
8.3.2 – PYTHON™ ARITHMETIC OPERATORS
If A = 10 and B = 3
VALUE INSIDE
OPERATOR NAME EXAMPLE VARIABLE ‘C’
+ Addition C=A+B 13
- Subtraction C=A–B 7
* Multiplication C=A*B 30
/ Division C=A/B 3.33
% Modulus C=A%B 1
** Exponent C = A ** B 1000
// Floor Division C = A // B 3
Monday, April 15, 2024 ESOFT METRO COLLEGE - BATTARAMULLA 19
8.3.3 – PYTHON™ COMPARISON OPERATORS
Monday, April 15, 2024 ESOFT METRO COLLEGE - BATTARAMULLA 20
8.3.3 – PYTHON™ COMPARISON OPERATORS
If A = 10, B = 10 and C = 3
VALUE INSIDE
OPERATOR NAME EXAMPLE VARIABLE ‘C’
== Equals C = (A == B) True
!= C = (A != B) False
Not Equals
<> C = (A <> C) True
> Greater Than C = (A > C) True
>= Greater Than or Equals C = (A >= C) True
< Lesser Than C = (A < B) False
<= Lesser Than or Equals C = (A <= B) True
Monday, April 15, 2024 ESOFT METRO COLLEGE - BATTARAMULLA 21
8.3.4 – PYTHON™ ASSIGNMENT OPERATORS
Monday, April 15, 2024 ESOFT METRO COLLEGE - BATTARAMULLA 22
8.3.4 – PYTHON™ ASSIGNMENT OPERATORS
If A = 10 and B = 4
VALUE INSIDE
OPERATOR EXAMPLE VARIABLE ‘A’
= A=B 4
+= A += B 14
-= A -= B 6
*= A *= B 40
/= A /= B 2.5
%= A %= B 2
**= A **= B 10000
//= A //= B 2
Monday, April 15, 2024 ESOFT METRO COLLEGE - BATTARAMULLA 23
8.3.5 – OPERATOR PRECEDENCE
(Textbook – Page 34)
Monday, April 15, 2024 ESOFT METRO COLLEGE - BATTARAMULLA 24
8.4 – CONDITIONAL STATEMENTS
Monday, April 15, 2024 ESOFT METRO COLLEGE - BATTARAMULLA 25
IF STATEMENTS
• Syntax: • Example:
if(condition): Mark = 85
statement(s)
if(Mark > 50):
print(“Passed”)
Reading Keyboard
Input
Monday, April 15, 2024 ESOFT METRO COLLEGE - BATTARAMULLA 26
IF-ELSE STATEMENTS
• Syntax: • Example:
Mark = 85
if (condition):
if (Mark > 50):
statement(s) print(“Passed”)
else:
else:
print(“Failed”)
statement(s)
Monday, April 15, 2024 ESOFT METRO COLLEGE - BATTARAMULLA 27
IF-ELIF-ELSE STATEMENTS
• Syntax: • Example:
Mark = 85
if (condition_01): if (Mark > 75):
statement(s) print(“A”)
elif (condition_02): elif (Mark > 50):
statement(s) print(“B”)
…………………………………………………… elif (Mark > 35):
else: print(“C”)
statement(s) else:
print(“Failed”)
Monday, April 15, 2024 ESOFT METRO COLLEGE - BATTARAMULLA 28
8.5 – LOOPS IN PYTHON™
Monday, April 15, 2024 ESOFT METRO COLLEGE - BATTARAMULLA 29
8.5.1 - WHILE LOOP
• Syntax:
X = 0
while (condition): while (X < 5):
statement(s) print(X)
X += 1
• Example:
Monday, April 15, 2024 ESOFT METRO COLLEGE - BATTARAMULLA 30
8.5.2 - FOR LOOP
• Syntax:
for X in range(5):
for(variable in sequence): print(X)
statement(s)
• Example:
Monday, April 15, 2024 ESOFT METRO COLLEGE - BATTARAMULLA 31
8.6 – SPECIAL DATA TYPES
Monday, April 15, 2024 ESOFT METRO COLLEGE - BATTARAMULLA 32
PYTHON NUMERICS
Monday, April 15, 2024 ESOFT METRO COLLEGE - BATTARAMULLA 33
8.6.1 – PYTHON STRINGS
Monday, April 15, 2024 ESOFT METRO COLLEGE - BATTARAMULLA 34
8.6.1 – PYTHON STRINGS
• We can store any character value as string data in Python.
• We can store any number of characters (even a single character) in a string.
• Examples:
• grade01 = “A” or grade = ‘A’
• name01 = “Gihan Samaranayake”
• Address01 = ‘78, Main Street, Colombo-01’
Monday, April 15, 2024 ESOFT METRO COLLEGE - BATTARAMULLA 35
8.6.1 – PYTHON STRINGS
• Following illustration shows how Python string values are saved in main memory.
• Example:
• name01 = “Gihan Samaranayaka”
name01 Values
(Name of the variable)
G i h a n S a m a r a n a y a k a
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
Index Numbers
Monday, April 15, 2024 ESOFT METRO COLLEGE - BATTARAMULLA 36
8.6.1 – PYTHON STRINGS
• We can use index numbers (indices) to access a value(s) of a string.
• To access a single value (place) of a string:
Name of the string variable
A[X]
Index number of the place that you need to access
Monday, April 15, 2024 ESOFT METRO COLLEGE - BATTARAMULLA 37
8.6.1 – PYTHON STRINGS
• Example 01: • Output:
print(name01[8]) m
• However, if you try to access an index number, that do not exist in the specified variable,
following error will occur:
• Example 02: • Output:
print(name01[18]) IndexError: string index out of
range
Monday, April 15, 2024 ESOFT METRO COLLEGE - BATTARAMULLA 38
8.6.1 – PYTHON STRINGS
• To access one or more values (substring) of a string:
Name of the string variable
A[Y:Z]
Y – starting index number
Z – (ending index number + 1)
Monday, April 15, 2024 ESOFT METRO COLLEGE - BATTARAMULLA 39
8.6.1 – PYTHON STRINGS
• Example 01: • Output:
print(name01[8:11]) mar
• However, if you try to access an index number, that do not exist in the specified variable,
there will not be an error:
• Example 02: • Output:
print(name01[8:20]) maranayaka
Monday, April 15, 2024 ESOFT METRO COLLEGE - BATTARAMULLA 40
8.6.1 – PYTHON STRINGS – EXAMPLE PROGRAMS
• Example:
Examples\PythonStrings01.py
Click Here
Monday, April 15, 2024 ESOFT METRO COLLEGE - BATTARAMULLA 41
8.6.2 – PYTHON LISTS
Monday, April 15, 2024 ESOFT METRO COLLEGE - BATTARAMULLA 42
8.6.2 – PYTHON LISTS
• We can store a collection of items as a list in Python.
• Those items can be of multiple types.
• Syntax:
• List_Name = [item01, item02, item03,……,itemX]
• Examples:
• names01 = [“Sahan”, “Amith”, “Jehan”]
• list01 = ['ABC', 35, 7.25, "Item 04", 658]
Monday, April 15, 2024 ESOFT METRO COLLEGE - BATTARAMULLA 43
8.6.2 – PYTHON LISTS
• Following illustration shows how Python list items are saved in main memory.
• Example:
• names01 = [“Sahan”, “Amith”, “Jehan”]
names01 Values
(Name of the list)
Sahan Amith Jehan
0 1 2
Index Numbers
Monday, April 15, 2024 ESOFT METRO COLLEGE - BATTARAMULLA 44
8.6.2 – PYTHON LISTS
• We can use index numbers (indices) to access a value(s) of a list.
• To access a single item (place) of a list:
Name of the list
A[X]
Index number of the item that you need to access
Monday, April 15, 2024 ESOFT METRO COLLEGE - BATTARAMULLA 45
8.6.2 – PYTHON LISTS
• Example 01: • Output:
print(names01[1]) Amith
• However, if you try to access an index number that do not exist in the specified variable,
following error will occur:
• Example 02: • Output:
print(names01[3]) IndexError: list index out of
range
Monday, April 15, 2024 ESOFT METRO COLLEGE - BATTARAMULLA 46
8.6.2 – PYTHON LISTS
• To access a subset of a list:
Name of the list
A[Y:Z]
Y – starting index number
Z – (ending index number + 1)
Monday, April 15, 2024 ESOFT METRO COLLEGE - BATTARAMULLA 47
8.6.2 – PYTHON LISTS
• Example 01: • Output:
print(names01[0:2]) [‘Sahan’, ‘Amith’]
• However, if you try to access an index number that do not exist in the specified variable,
there will not be an error:
• Example 02: • Output:
print(names01[-1:2]) []
Monday, April 15, 2024 ESOFT METRO COLLEGE - BATTARAMULLA 48
8.6.2 – PYTHON LISTS
• Example:
Examples\PythonLists01.py
Click Here
Monday, April 15, 2024 ESOFT METRO COLLEGE - BATTARAMULLA 49
8.6.3 – PYTHON TUPLES
Monday, April 15, 2024 ESOFT METRO COLLEGE - BATTARAMULLA 50
8.6.3 – PYTHON TUPLES
• We can store a collection of items as a tuples in Python.
• Those items can be of multiple types.
• Syntax:
• Tuple_Name = (item01, item02, item03,……,itemX)
• Examples:
• student01 = (“Sahan”, “Saparamadu”, “DIT-111”, “Battaramulla”)
• batch01 = (“DIT-111”, 2018, “01-09-2018”)
Monday, April 15, 2024 ESOFT METRO COLLEGE - BATTARAMULLA 51
8.6.3 – PYTHON TUPLES
• Following illustration shows how Python tuple items are saved in main memory.
• Example:
• student01 = (“Sahan”, “Saparamadu”, “DIT-111”, “Battaramulla”)
student01 Values
(Name of the tuple)
Sahan Saparamadu DIT-111 Battaramulla
0 1 2 3
Index Numbers
Monday, April 15, 2024 ESOFT METRO COLLEGE - BATTARAMULLA 52
8.6.3 – PYTHON TUPLES
• We can use index numbers (indices) to access a value(s) of a tuple.
• To access a single item (place) of a tuple:
Name of the tuple
A[X]
Index number of the item that you need to access
Monday, April 15, 2024 ESOFT METRO COLLEGE - BATTARAMULLA 53
8.6.3 – PYTHON TUPLES
• Example 01: • Output:
print(student01[2]) DIT-111
• However, if you try to access an index number that do not exist in the specified variable,
following error will occur:
• Example 02: • Output:
print(student01[5]) IndexError: tuple index out of
range
Monday, April 15, 2024 ESOFT METRO COLLEGE - BATTARAMULLA 54
8.6.3 – PYTHON TUPLES
• To access a subset of a list:
Name of the tuple
A[Y:Z]
Y – starting index number
Z – (ending index number + 1)
Monday, April 15, 2024 ESOFT METRO COLLEGE - BATTARAMULLA 55
8.6.3 – PYTHON TUPLES
• Example 01: • Output:
print(names01[0:2]) (‘Sahan’, ‘Saparamadu’)
• However, if you try to access an index number that do not exist in the specified variable,
there will not be an error:
• Example 02: • Output:
print(names01[-1:2]) ()
Monday, April 15, 2024 ESOFT METRO COLLEGE - BATTARAMULLA 56
8.6.3 – PYTHON TUPLES
• Example:
Examples\PythonTuples01.py
Click Here
Monday, April 15, 2024 ESOFT METRO COLLEGE - BATTARAMULLA 57
8.6.4 – PYTHON DICTIONARY
Monday, April 15, 2024 ESOFT METRO COLLEGE - BATTARAMULLA 58
8.6.4 – PYTHON DICTIONARY
• Also known as associative arrays or Hash Tables.
• We can store a collection of key-value pairs as a dictionary in Python.
• Those items can be of multiple types.
• Syntax: Key Value
• Dictionary_Name = {item01:value01,……,itemX:valueX}
• Examples: Key-Value Pair
• studentDict1 = {'FirstName':'Saman' , 'Age':35 , 'Hometown':'Nugegoda'}
• studentDict2 = {'FirstName':'Dilan' , 'Age':34 , 'Hometown':'Matara'}
Monday, April 15, 2024 ESOFT METRO COLLEGE - BATTARAMULLA 59
8.6.4 – PYTHON DICTIONARY
• Following illustration shows how Python dictionary items are saved in main memory.
• Example:
• studentDict1 = {'FirstName':'Saman' , 'Age':35 , 'Hometown':'Nugegoda'}
studentDict01
(Name of the dictionary)
FirstName Saman Age 35 Hometown Nugegoda
Monday, April 15, 2024 ESOFT METRO COLLEGE - BATTARAMULLA 60
8.6.4 – PYTHON DICTIONARY
• To access a value of a Dictionary:
Name of the Dictionary
A[X]
X - Key
Monday, April 15, 2024 ESOFT METRO COLLEGE - BATTARAMULLA 61
8.6.4 – PYTHON DICTIONARY
• Example 01: • Output:
print(studentDict01['Hometown']) Nugegoda
• However, if you try to access a key that do not exist in the specified dictionary, following error
will occur:
• Example 02: • Output:
print(studentDict01['LastName']) KeyError: ‘LastName’
Monday, April 15, 2024 ESOFT METRO COLLEGE - BATTARAMULLA 62
8.6.4 – PYTHON DICTIONARY
• Example:
Examples\PythonDictionaries01.py
Click Here
Monday, April 15, 2024 ESOFT METRO COLLEGE - BATTARAMULLA 63
8.6.5 – PYTHON FUNCTIONS
Monday, April 15, 2024 ESOFT METRO COLLEGE - BATTARAMULLA 64
8.6.5 – PYTHON FUNCTIONS
• A function is a grouped set of statements written to achieve a specific task inside a program.
• Rules of creating a function in Python:
• Function should begin with the keyword def. Then you should provide a name for the
function.
• Arguments (input parameters) should be declared if any.
• docstring (Document String) should be the first line in a function. But it is optional.
• Function declaration should end with a : symbol.
• Set of statements should be indented after the : symbol.
• return statement should be the last statement of a function.
Monday, April 15, 2024 ESOFT METRO COLLEGE - BATTARAMULLA 65
8.6.5 – PYTHON FUNCTIONS
• Example: Docstring
Arguments (Optional)
Name
def addNumbers(X, Y):
“This function adds two numbers and returns the result”
Sum = X + Y Statement(s)
return Sum Return Statement
Monday, April 15, 2024 ESOFT METRO COLLEGE - BATTARAMULLA 66
8.6.5 – PYTHON FUNCTIONS
• Another Example:
Examples\PythonFunctions01.py
Click Here
Monday, April 15, 2024 ESOFT METRO COLLEGE - BATTARAMULLA 67
8.7 – PYTHON FILES I/O
Monday, April 15, 2024 ESOFT METRO COLLEGE - BATTARAMULLA 68
8.7.1 – READING KEYBOARD INPUT
• We can use the in-built input() function of Python to read keyboard input from the user.
• By default, the value taken by the input() is of type string.
• If we need to convert that string value into a numeric value (for calculations), we can use in-
built int() and float() functions.
Monday, April 15, 2024 ESOFT METRO COLLEGE - BATTARAMULLA 69
8.7.1 – READING KEYBOARD INPUT
• Example:
#Taking a string input and saving in a variable as a string
Name = input(“Please insert your name: ”)
#Taking a string input and saving it as an integer value
Age = int(input(“Please insert your Age: ”))
#Taking a string input and saving it as a floating-point value
GPA = float(input(“Please insert your GPA: ”))
Go again to IF STATEMENTS
Monday, April 15, 2024 ESOFT METRO COLLEGE - BATTARAMULLA 70
PYTHON EXERCISES
Monday, April 15, 2024 ESOFT METRO COLLEGE - BATTARAMULLA 71
PYTHON EXERCISES
• Find the Exercises file in following folder:
Exercises\Python 3 Exercises.pdf
Click Here
Monday, April 15, 2024 ESOFT METRO COLLEGE - BATTARAMULLA 72