Csc 201 Python Practical Manual22
Csc 201 Python Practical Manual22
PYTHON PROGRAMMING
LAB MANUAL
NAME …………………………………………………………………………………………
MATRIC NO: …………………………………………………………………………………
DEPARTMENT ……………………………………………………………………………….
SESSION ………………………………………………………………………………………
COURSE CODE………………………………………………………………………………
COURSE TITLE……………………………………………………………………………….
DEPARTMENT OF MATHEMATICAL AND
COMPUTING FACULTY OF APPLIED SCIENCES
INSTRUCTIONS
1. Students should report to the concerned labs as per the given timetable.
2. Students should make an entry in the log book whenever they enter the labs during practical
or for their own personal work.
3. When the experiment is completed, students should shut down the computers and make the
counter entry in the logbook.
4. Any damage to the lab computers will be viewed seriously.
5. Students should not leave the lab without concerned faculty’s permission.
6. Without Prior permission do not enter into the Laboratory
7. While entering into the LAB students should wear their ID cards.
8. Students should sign in the LOGIN REGISTER before entering into the laboratory
9. Students should maintain silence inside the laboratory
10. After completing the laboratory exercise, make sure to shut down the system properly
Week Topic Date of Date of Marks Remarks
Performance Checking (10)
Grand Total
UNIT 1
Prerequisites
• Python is Interpreted − Python is processed at runtime by the interpreter. You do not need to
compile your program before executing it. This is similar to PERL and PHP.
• Python is Interactive − You can actually sit at a Python prompt and interact with the interpreter
directly to write your programs.
History of Python
Python was developed by Guido van Rossum in the late eighties and early nineties at the
National Research Institute for Mathematics and Computer Science in the Netherlands. Python is
derived from many other languages, including ABC, Modula-3, C, C++, Algol-68, SmallTalk,
and Unix shell and other scripting languages.
Python is copyrighted. Like Perl, Python source code is now available under the GNU General
Public License (GPL).
Python is now maintained by a core development team at the institute, although Guido van
Rossum still holds a vital role in directing its progress.
Features of Python
• Easy-to-learn − Python has few keywords, simple structure, and a clearly defined syntax. This
allows the student to pick up the language quickly.
• Easy-to-read − Python code is more clearly defined and visible to the eyes. • Easy-to-maintain
− Python's source code is fairly easy-to-maintain.
• A broad standard library − Python's bulk of the library is very portable and cross-platform
compatible on UNIX, Windows, and Macintosh.
• Interactive Mode − Python has support for an interactive mode which allows interactive testing
and debugging of snippets of code.
• Portable − Python can run on a wide variety of hardware platforms and has the same interface
on all platforms.
• Extendable − You can add low-level modules to the Python interpreter. These modules enable
programmers to add to or customize their tools to be more efficient.
• GUI Programming − Python supports GUI applications that can be created and ported to many
system calls, libraries and windows systems, such as Windows MFC, Macintosh, and the X
Window system of Unix. • Scalable − Python provides a better structure and support for large
programs than shell scripting.
Apart from the above-mentioned features, Python has a big list of good features, few are listed
below
• It provides very high-level dynamic data types and supports dynamic type checking.
• It can be easily integrated with C, C++, COM, ActiveX, CORBA, and Java.
Example 1: Write a Python program to ask for user name, and display his/her name as
Output:
Hello, Kunle
Data Types
Python Data Types are used to define the type of a variable. It defines what type of data we are
going to store in a variable. The data stored in memory can be of many types. For example, a
person's age is stored as a numeric value and his or her address is stored as alphanumeric
characters.
Python has various built-in data types which we will discuss with in this class:
Numeric - int, float, complex
Examples
#This is integer data type (numeric)
x=3
type(x)
#This is float data type(numeric)
x=3
type(x+0.1)
#This is complex data type(numeric)
x=3
type(x+3j)
String – str
#This is string data type
x= str(input("Enter your name "))
type(x)
#This is multiline string data type
multiline="""
I've been to your house dear, "Can i visit you later"
"""
print(multiline)
print(multiline[:4])
Sequence - list, tuple, range
#This is sequence data type[list]. It can be modified
lists =[1,2,4,6,8,7]
lists1 =['banana','plaintain','guava','apple']
#nested list
lists2 =['banana','plaintain',3,['mango','orange'],'guava','apple',True]
#add to the list
lists2.append('cashew')
#change an index value
lists1[0]='pawpaw'
print(lists)
print(lists1[0])
print(lists2[3])
print(lists2[3][1])
#This is sequence data type[turple]. It cannot be changed
tuple1 =(1,2,4,6,8,7)
tuple2 =('banana','plaintain','guava','apple')
print(tuple1)
print(tuple2)
Binary - bytes, bytearray, memoryview
#Byte is a sequence of immutable single bytes
byte1 = 'Hello Class'
arr=bytes(byte1,'utf-8')#It converts the message to a sequence of bytes
arr
#byte object
bytes.fromhex('FFFF F21E')
#Byte is a sequence of mutable single bytes. It has the same objects as byte
arr=bytearray(byte1,'utf-8')#It converts the message to a sequence of bytes
arr
# Memoryview allow acces to object internal data
my=memoryview(arr)
#It returns the ascii value
my[1]
list(my[1:3])
#It returns the message
my[1]=65
arr
Mapping – dict
Example
#This is dictionary data type. It uses key not an index. We can update information with dictionary
#keyvalue pair
dict_list = {'name':'Adeyemi','level':200,'department':'computer science','favourite':['pounded yam','ice
cream','meat pie']}
#dict_list.values()
#dict_list.keys()
#dict_list.items()
#print(dict_list )
dict_list['name']='Israel'
dict_list['name']
#We can also use the update command
dict_list.update({'name':'Christian','level':200,'department':'software engineering','favourite':['pounded
yam','ice cream','meat pie']})
print(dict_list)
#we can also delete items
del dict_list['favourite']
print(dict_list)
Boolean – bool
Example
#This is boolean data type
x=3>5
#type(x)
print(x)
Set - set, frozenset
Example
#This is sequence data type[set]. It cannot have duplicate elements and cannot be acceseed with an index
set1 = {1,2,4,6,8,7,7 ,9,10,4,6}
set2 = {1,3,4,31,8,7,5 ,9,10,4,6}
print(set1)
print(set1|set2)
print(set1 & set2)
print(set1 - set2)
print(set1 ^ set2)
type(set1)
None - NoneType
1. Write a python program to request for the following information from student and display
the information as output. Name, Matric No, Age and Department
2. Write a python program to accept your name and matric number as input and print it out.
UNIT 2
PYTHON VARIABLES
Variables are containers for storing data values. A Python variable is a reserved memory
location to store values. In other words, a variable in a python program gives data to the
computer for processing.
Every value in Python has a datatype. Different data types in Python are Numbers, List, Tuple,
Strings, Dictionary, etc. Variables can be declared by any name or even alphabets like a, aa,
abc, etc.
a=100
print a
Variable names
There are just a couple of rules to follow when naming your variables.
• Variable names can contain letters, numbers, and the underscore.
• Variable names cannot contain spaces.
• Variable names cannot start with a number.
• Case Sensitive—for instance, temp and Temp are different.
Looking back at our first program, we see the use of a variable called temp. One of the major
purposes of a variable is to remember a value from one part of a program so that
it can be used in another part of the program. In the case above, the variable temp stores the
value that the user enters so that we can do a calculation with it in the next line.
Creating Variables
Python has no command for declaring a variable. A variable is created the moment you first
assign a value to it.
x = 5
y =
"John"
print(x)
print(y)
x, y, z = "Orange", "Banana",
"Cherry" print(x)
print(y
)
print(z
)
x = "Python is
awesome" print(x)
Global Variables
Variables that are created outside of a function (as in all of the examples above) are known as
global variables. Global variables can be used by everyone, both inside of functions and outside.
Example: Create a variable outside of a function, and use it inside the function
x =
"awesome"
def
myfunc():
print("Python is " + x)
myfunc()
Example
2:
Create a variable inside a function, with the same name as the global variable
x =
"awesome"
def
myfunc():
x = "fantastic"
print("Python is " +
x)
myfunc()
print("Python is " + x)
Comment
Comments can be used to explain Python code. Comments can be used to make the code more
readable. Comments can be used to prevent execution when testing code.
#This is a comment
print("Hello,
World!")
A comment does not have to be text that explains the code, it can also be used
to prevent Python from executing code.
Multiline Comment
#written in
#more than just one line
print("Hello, World!")
Assignment
1. Ask the user to enter a number. Print out the square of the number, but use the sep
optional argument to print it out in a full sentence that ends in a period. Sample output is shown
below.
Enter a number: 5
The square of 5 is 25.
2. Write a program that asks the user for a weight in kilograms and converts it to pounds.
There are 2.2 pounds in a kilogram.
3. A lot of cell phones have tip calculators. Write one. Ask the user for the price of the meal
and the percent tip they want to leave. Then print both the tip amount and the total bill
with the tip included.
Unit 3
ARITHMETIC OPERATORS
The arithmetic operations are the basic mathematical operators which are used in our daily life.
Mainly it consists of seven operators.
i. Addition operator --> '+'
ii. ii. Subtraction operator --> '-'
iii. iii. Multiplication operator --> '*'
iv. iv. Normal Division operator --> '/'
v. v. Modulo Division operator --> '%'
vi. vi. Floor Division operator --> '//' vii. Exponential operator (or) power operator --> '**'
i. Addition Operator: Generally, addition operator is used to perform the addition operation on
two operands. But in python we can use addition operator to perform the concatenation of
strings, lists and so on, but operands must of same datatype.
Example x
=2
y=3
print("ADDITION RESULT : ", x +
y) output : ADDITION RESULT : 5
Subtraction Operator
Generally, subtraction operator is used to perform the subtraction operation on two operands
a = 30
b = 10
print ("Subtraction result : ",a-b)
output: Subtraction result : 20
Multiplication operator
Generally, multiplication operator is used to perform the multiplication operation on two
operands.
But in python we can use multiplication operator to perform the repetition of strings, lists
and so on, but operands must belong to same datatype.
num1 = 23
num2 = 35
print ("MULTIPLICATION RESULT : “, num1 *num2)
Floor Division
Suppose 10.3 is there, what is the floor value of 10.3?
Answer is 10
What is the ceil value of 10.3?
Answer is 11
1. Sequential Statement
A sequential statement is composed of a sequence of statements which are executed one after
another. A code to print your name, address and phone number is an example of sequential
statement.
Example 1
#Program to print your name and address - example for sequential statement
print ("Hello! This is Seyi")
print ("km 18, Ibadan oyo express road, koladaisi university")
Output
Hello! This is Seyi
km 18, Ibadan oyo express road, koladaisi university
2. Alternative or Branching Statement
In our day-to-day life we need to take various decisions and choose an alternate path to achieve
our goal. Maybe we would have taken an alternate route to reach our destination when we find
the usual road by which we travel is blocked. This type of decision making is what we are to
learn through alternative or branching statement. Checking whether the given number is positive
or negative, even or odd can all be done using alternative or branching statement.
if..else statement thus provides two possibilities and the condition determines which BLOCK is
to be executed.
else:
statements-block n
‘elif’ clause combines if..else-if..else statements to one if..elif…else. ‘elif’ can be considered to
be abbreviation of ‘else if’. In an ‘if’ statement there is no limit of ‘elif’ clause that can be used,
but an ‘else’ clause if used should be placed at the end.
Example : #Program to illustrate the use of nested if
statement Average Grade
>=80 and above A
>=70 and <80 B
>=60 and <70 C
>=50 and <60 D
Otherwise E
m1=int(input("Enter your score: "))
if m1>=80:
print ("Grade : A")
elif m1>=70 and m1<80:
print ("Grade : B")
elif m1>=60 and m1<70:
print ("Grade : C")
elif m1>=50 and m1<60:
print ("Grade : D")
elif m1>=40 and m1<50:
print ("Grade : E")
else:
print ("Grade : F")
Output 1:
Enter mark in first subject : 34
Enter mark in second subject : 78
Grade : D
Output 2 :
Enter mark in first subject : 67
Example: #Program to illustrate the use of ‘in’ and ‘not in’ in if statement
ch=input (“Enter a character :”)
# to check if the letter is vowel
if ch in (‘a’, ‘A’, ‘e’, ‘E’, ‘i’, ‘I’, ‘o’, ‘O’, ‘u’, ‘U’):
print (ch,’ is a vowel’)
#to check if the letter typed is not ‘a’ or ‘b’ or ‘c’ if ch not in (‘a’, ’b’, ’c’):
print (ch,’ the letter is not a/b/c’)
Output 1:
Enter a character :e
e is a vowel
Output 2:
Enter a character :x
x the letter is not a/b/c
Iteration or loop are used in situation when the user need to execute a block of code several of
times or till the condition is satisfied. A loop statement allows to execute a statement or group of
statements multiple times.
Example: program to illustrate the use of while loop - to print all numbers from 10 to 15
Output:
10 11 12 13 14 15
Note: print can have end, sep as parameters. end parameter can be used when we need to give
any escape sequences like ‘\t’ for tab, ‘\n’ for new line and so on. sep as parameter can be used to
specify any special characters like, (comma) ; (semicolon) as separator between values (Recall
the concept which you have learnt in previous chapter about the formatting options in print()).
Example: program to illustrate the use of while loop - with else part
i=10 # intializing part of the control variable
while (i<=15): # test condition
print (i,end='\t') # statements - block 1
i=i+1 # Updation of the control variable
else:
print ("\nValue of i when the loop exit ",i)
Output: 1
10 11 12 13 14 15
(ii) for loop
for loop is the most comfortable loop. It is also an entry check loop. The condition is checked in
the beginning and the body of the loop(statements-block 1) is executed if it is only True
otherwise the loop is not executed.
Syntax:
statements-block 1
statements-block 2]
Example: #program to illustrate the use of for loop - to print single digit even number
for i in range (2,10,2):
print (i, end=' ')
Output:
2468
Example: #program to illustrate the use of for loop - to print single digit even number with
else part
for i in range(2,10,2):
print (i,end=' ')
else:
print ("\nEnd of the loop")
Output:
2468
End of the loop
#inn =6
i=1
while (i<=inn):
print (j,end='\t')
if (j==i):
break
print (end='\n')
i =i+1
4. Jump Statements in Python
The jump statement in Python, is used to unconditionally transfer the control from one part of the
program to another. There are three keywords to achieve jump statements in Python : break,
continue, pass. The following flowchart illustrates the use of break and continue.
The break statement terminates the loop containing it. Control of the program flows to the
statement immediately after the body of the loop.
A while or for loop will iterate till the condition is tested false, but one can even transfer the
control out of the loop (terminate) with help of break statement. When the break statement is
executed, the control flow of the program comes out of the loop and starts executing the segment
of code after the loop structure.
If break statement is inside a nested loop (loop inside another loop), break will terminate the
innermost loop.
Example
Assignment
1. Write a python program using a function to compute the sum of two numbers.
2. Write a python program using a function to compute the factorial of a positive
integer number
Assignment
Unit 6
Often times in problem solving we would want to store or process textual data containing
characters of the alphabets, numerals and special characters. Such data are called Strings.
Strings
These are collection of characters that are used to store and represent textual information. They
can be used to store anything data that will include letters or symbols such as your name,
address, department, course code etc.
Strings in python just like in many other programming languages are values placed in
between a pair of single or double quotes e.g. ‘Ola’, “CSC202” etc.
There are many operations that can be performed on strings, enumeration of string
characters, concatenation, sorting, deleting characters, replacing, pattern matching,
reversing etc.
In the memory, strings in python are actually stored as an ordered sequence of characters.
The figure below shows how the string “Science, Types” will be stored.
So it can be seen that characters of a strings are actually stored in consecutive memory
locations in memory where the first character occupies position or index 0 and the second
index 1 and to the last occupying index (N-1) where N is the length(total number of
characters) of the string. However from the rear, the indices is counted from -1, -2 to
–N!
Notice that even spaces are treated like a normal character.
String Literals
String literals can be written in two forms either using single or double quotes.
Single
Quote: Name =
‘KOLADAISI’
Double
Quote: Name =
“KOLADAISI”
Whichever you use, be assured python treats them equally and it allows you to be able to embed
one in the other.
Escape Sequence
These are special characters embedded inside string literals to give them a special meaning or
introduce special characters that cannot be found on the keyboard into the string.
The \ can be used to escape any given character in order to overall the default behaviour
of the character.
For instance putting another ‘ within a pair of ‘ and ‘ flags an error, to void the error, we can
escape the inner ‘ using the \ as shown below;
>>> place = ‘Senate\’s Underground’
Escape Sequence
They can also be used to introduce special characters such as the following in a body of
string.
String Methods
In memory, everything in python is actually treated as objects that can have methods, and properties. When
treated as objects, strings provide a set of methods (functions) that can be used to perform so many basic
operations with strings. See table below for some of these;
Method Use
Assignments