0% found this document useful (0 votes)
13 views59 pages

Python Lab Manual IIUC CCE

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
13 views59 pages

Python Lab Manual IIUC CCE

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 59

“In the name of Allah, the Most Gracious, the Most Merciful"

International Islamic University Chittagong (IIUC)


Department of Computer and Communication Engineering (CCE)

Course Code: CCE-2406


Course Title: Python Programming Sessional

‘Lab Manual’

Prepared by:

Mohammad Nadib Hasan (MNH)


Lecturer, Department of CCE, IIUC.
Table of Contents

PART I: USER MANUAL Page No

1. COURSE DESCRIPTION i-ii


1.1 COURSE CONTENTS (SYLLABUS) i-ii
2. INTRODUCTION TO THE COURSE ii

3. OBJECTIVE(S) OF THIS COURSE ii

4. ASSESSMENT METHODS iii-v

5. GRADING POLICY vi

6. GENERAL GUIDELINES vi-vii

7. HOW TO WRITE A COMPLETE LAB REPORT? viii-x

PART II: LAB SESSIONS Page No

LAB 1# Introduction to Python Programming 1-13

LAB 2# Operators in Python 14-17

LAB 3# Strings in Python 18-21

LAB 4# Data Structures in Python 22-28

LAB 5# Loops, Conditional Statements and Function 29-36

LAB 6# File Handling in Python 37-40

LAB 7# Python OOPs Concepts 41-47


Course Title: Python Programming Sessional Course Code: CCE-2406

COURSE DESCRIPTION:
ISCED Code: 0613 Course Code: CCE-2406 Course Title: Python Programming Sessional
Credit Hours: 1.5 Contact Hours: 3 CH per Week Prerequisite Course: CCE-1208
Course CIE: Continuous Internal Evaluation 40 – 60 Marks
Assessments SEE: Semester End Examination 60 – 40 Marks

Contents CLOs Lecture Practical


Semester End Examination (SEE) = 60 – 40 Marks
Topic: Introduction to Python Programming
• Install and configure Python IDE 1 2
• Write a program that print your name with your student id and
your CGPA.
Topic: Operator
• Write a program to convert U.S. dollars to Indian rupees.
• Write a program to convert bits to Megabytes, Gigabytes and
Terabytes.
• Write a program to find the square root of a number. 2 2
• Write a program to find the area of Rectangle.
• Write a program to calculate area and perimeter of the square.
CLO – 1
• Write a program to calculate surface volume and area of a
cylinder.
Topic: Strings in Python
• Write a Python program to take a user input string, reverse it
using slicing, and display the reversed string in uppercase.
• Create a multiline string representing a short story. Use string
formatting to insert the name of the main character and age 2 2
within the story as a variable.
• Write a Python program to take user input and use positive and
negative indexing to display the first, last, and middle characters.
Calculate and print the length of the string.
Topic: Data Structures in Python
• Write a Python program to perform following operations on
Lists: Create, Access, Update and Delete items in a list.
• Write a Python program to perform following operations on CLO – 2 4 4
Tuples: Create Tuple, Access Tuple, Update Tuple, Delete Tuple.
• Write a Python program to represent and access an object inside
an object within a Python dictionary. (Use Countries Information).
Topic: Loops, Conditional Statements and Function
• Write a Python program using a loop to find the sum of all prime
numbers between 1 and 50.
• Implement a program that uses nested loops to create a pattern,
such as a triangle or a square, using asterisks. CLO – 1 4 5
• Create a function that takes a list of numbers as input and returns
the average of the positive numbers.
• Write a program to take user input and use a while loop to find
the factorial of a given number.

Dept. of CCE, IIUC. Page | i


Course Title: Python Programming Sessional Course Code: CCE-2406

Topic: File Handling in Python


• Write a function in Python that takes a filename and a string as
parameters and appends the string to the end of the file.
• Write a function that takes a directory path and deletes all text
CLO – 4 3 3
files in that directory.
• Write a Python program to merge data from "countries.txt" and
"populations.txt" into a new file named "details.txt". The new
data should be organized in a proper format.
Topic: Python OOPs Concepts
• Write a Python program to build a simple library system using
classes to represent books and library members. CLO – 3 4 4
• Write a Python program to create a bank account system with
classes representing accounts and transactions.
Total 20 22

*** A three-hour lab session has been reserved for administering impromptu programming tests.

INTRODUCTION TO THE COURSE:


This lab course provides a thorough introduction to the Python programming language. You will gain
essential coding skills, and hands-on experience, and develop a solid foundation in Python syntax and
structure for diverse programming scenarios. This course is designed to make Python accessible,
ensuring that by the end, you not only understand the language but can also apply it effectively in
your own projects.

OBJECTIVE(S) OF THIS COURSE:


✓ Interpret the use of procedural statements like assignments, conditional statements, loops
and function calls.
✓ Infer the supported data structures like lists, dictionaries and tuples in Python.
✓ Discover the use of external modules in creating excel files and navigating the file systems.
✓ Describe the need for Object-oriented programming concepts in Python.

Course Learning Outcomes (CLOs):


Course Learning Outcomes (CLOs): Upon the Bloom’s Program
CLOs successful completion of the course, Taxonomy Learning
students will be able to Domain/Level Outcomes (PLOs)
Describe the Python language syntax including
control statements, loops and functions to Cognitive (Design
CLO-1 PLO – 1
write programs for a wide variety problem in and Creation)
mathematics, science, and games.
Examine the core data structures like lists,
Cognitive
CLO-2 dictionaries, tuples and sets in Python to store, PLO – 2
(Evaluation)
process and sort the data.

Dept. of CCE, IIUC. Page | ii


Course Title: Python Programming Sessional Course Code: CCE-2406

Interpret the concepts of Object- oriented Cognitive


CLO-3 programming as used in Python using (Understand & PLO – 3
encapsulation, Evaluation)
Identify the external modules for creating and Cognitive
CLO-4 writing data to excel files and inspect the file (Understand & PLO – 9
operations to navigate the file systems. Evaluation)

ASSESSMENT METHODS:
Teaching Learning Strategy:
Face-to-Face Learning
➢ Lecture
➢ Experiment
Self-directed Learning
➢ Preparation for Lab Reports
➢ Preparation for Lab Test & Quiz
➢ Engagement in Project / Assignment

Student Assessment Methods:


Formative Assessment
➢ Continuous Assessment (Experiment Conduction, Lab Report and Lab Viva)
Summative Assessment
➢ Final Quiz / Final Lab Examination
➢ Lab Test / Lab Performance / Project Show

CLOs with Weighting of Assessments:

CLOs Assessment Method (%)


Attendance 10%
Experiment Conduction 10%
Continuous
Lab Report 20%
CLO-1, CLO-2, CLO-3 and Assessment
Lab Viva 10%
CLO-4
Final Lab Quiz / Final Lab Examination 30%
Final Lab Performance / Test & Viva 20%

Dept. of CCE, IIUC. Page | iii


Course Title: Python Programming Sessional Course Code: CCE-2406

Rubrics followed to Evaluate the Lab Courses:

Attendance:

Attendance Awarding marks


90% and above 10
85% to less than 90% 9
80% to less than 85% 8
75% to less than 80% 7
70% to less than 75% 6
65% to less than 70% 5
60% to less than 65% 4
less than 60% 0

Continuous Assessment (Experiment Conduction, Lab Viva and Lab Report):


Allocated
Parameter Low Medium High
Marks
The student has
The student has not The student has given excellent
performed anything given satisfactory performance or has
Experiment
10 during laboratory performance during completed all the
Conduction periods laboratory periods tasks given during
laboratory periods.
0 Mark 1 – 5 Marks 6 – 10 Marks
Low Medium High
The student was not The student was able The student was
able to answer to answer a few able to answer all
Lab Viva 10
anything during viva- questions during viva- the questions during
voce. voce viva voce.
0 Mark 1 – 5 Marks 6 – 10 Marks
The student was The student was
The student was not
partially able to able to perform the
able to perform the
Lab perform the job during job accurately
10 job, given during the
Performance the semester during the semester
semester laboratory
laboratory laboratory
examination.
examination. examination.
0 Mark 1 – 5 Marks 6 – 10 Marks

Dept. of CCE, IIUC. Page | iv


Course Title: Python Programming Sessional Course Code: CCE-2406

Lab Report Rubric:


Parameter Fail (0) Poor (2) Fair (4) Good (7) Excellent (10)
Lab report
submitted as
No Directions directed, and on
Report is
submission were not Report is well time.Directions
somewhat
Report / No effort followed organized and were followed.
organized
format and exhibited and cohesive but Report is well
with some
quality and No report contains minor organized and
spelling or
(5) attention to contains errors in format cohesive and
grammatical
detail many or procedures. contains no
errors.
evident errors. mechanical errors.
Presentation seems
polished.
Presents an
introduction
and
Provides a
background
sufficient Clearly articulates
Introductio information,
introduction the purpose,
n and but it lacks
and background significance, and
background clarity and
information but relevant
are relevance to
lacks some background
Lab Experiment insufficient the
No depth or clarity. information of the
Report Background, or missing experiment.
submission Presents mostly experiment.
Results & entirely. Presents
/ No effort accurate data Presents accurate,
Data Analysis Data is data with
exhibited. with some well-organized, and
(10) missing, several
organizational comprehensive
inaccurate, inaccuracies
issues. Analyses data. Analyses data
or not or significant
data adequately effectively using
analysed organization
but with minor appropriate
effectively. al problems.
errors or methods.
Data analysis
inconsistencies.
is limited or
contains
major errors.
Does not Attempts to Demonstrates a
Connects the
effectively connect clear understanding
results to the
connect results to of the results and
objectives objectives but connects them to
No results to
Discussion & but with lacks depth or the experiment's
submission objectives,
Conclusion significant thorough objectives. Offers
/ No effort and
(5) gaps or analysis. insightful
exhibited conclusions inaccuracies. interpretations and
Conclusions are
are absent Conclusions conclusions
drawn but lack
or are vague or supported by
insight or depth.
inaccurate. unsupported. evidence.

Dept. of CCE, IIUC. Page | v


Course Title: Python Programming Sessional Course Code: CCE-2406

GRADING POLICY:
Numerical grade Letter Grade Grade Point Remarks/
Marks% (LG) (GP/unit) Status
80-100 A+ (A plus) 4.00 Excellent
75 to less than 80 A (A regular) 3.75
70 to less than 75 A- (A minus) 3.50 Very good
65 to less than 70 B+ (B plus) 3.25
60 to less than 65 B (B regular) 3.00 Good
55 to less than 60 B- (B minus) 2.75
50 to less than 55 C+ (C plus) 2.50 Satisfactory
45 to less than 50 C (C regular) 2.25 Not
40 to less than 45 D (D regular) 2.00 Satisfactory
less than 40 F 0.00 Fail

GENERAL GUIDELINES:
Dear Students,
Welcome to Python Programming Lab.

• For the practical works of Python Programming Course, you have to


complete CCE-2406 lab (3 hours each) activities throughout the course. This
lab manual will guide you to prepare for making and submission of lab
reports. Further, it helps you to understand practically about the knowledge
of Python Programming. You can use this lab manual as the base reference
during your lab.
• You have to submit lab report of previous lab into corresponding next lab
during when your instructor shall take necessary lab performance for each
lab works. For your reference, “how to write a complete CCE-2406 lab
report?” is being prepared as sample lab report in this manual. For the rest
of your labs, please follow the reporting style as provided.
• Your lab report to be submitted should include at least the following topics.
1. Cover Page
2. Experiment No
3. Experiment Name
4. Objectives
5. Problem Statement/Theory
6. Algorithm/ Flowchart
7. Coding (Source Code)

Dept. of CCE, IIUC. Page | vi


Course Title: Python Programming Sessional Course Code: CCE-2406

8. Output (compilation, debugging & testing)


9. Discussion & Conclusion.

• You should attempt all Experiments given in the list lab wise.
• You may seek assistance in doing the lab Experiments from the concerned
lab instructor. Since the assignments have credits, the lab instructor is
obviously not expected to tell you how to solve these, but you may ask
questions concerning the Python Programming or a technical problem.
• For each program you should add comments [i.e., # for single line comment
and triple quotes (“”” “””) for multiline comment] above each function in
the code, including the main function.
• The comment block above the main code should describe the purpose of the
program. Proper comments are to be provide where and when necessary, in
the coding.
• The code should be interactive, general and properly documented with real
Input/ Output data.
• If two or more submissions from different students appear to be of the
same origin (i.e., are variants of essentially the same program), none of
them will be counted.
• You are strongly advised not to copy somebody else's work.
• It is your responsibility to create a separate directory to store all the
programs,so that nobody else can read or copy.
• As soon as you have finished a lab Experiment, contact one of the lab
instructors /in charge in order to get the Experiment evaluated and also get
the signature from him/her on the lab performance book.

Dept. of CCE, IIUC. Page | vii


Course Title: Python Programming Sessional Course Code: CCE-2406

1. HOW TO WRITE A COMPLETE LAB REPORT?

Page IX to X shows a sample of a complete lab report.

Dept. of CCE, IIUC. Page | viii


Course Title: Python Programming Sessional Course Code: CCE-2406

Department of Computer and Communication Engineering (CCE)

LAB REPORT-1
Topic: Data Structures in Python

Course Title : Python Programming Sessional


Course Code : CCE-2406

Experiment Name:

Submitted By
Name :
ID No :
Semester :
Section :

Date of Experiment:
Date of Submission:

Remarks
Submitted To
Engr. Mohammad Nadib Hasan
Lecturer, Dept. of CCE, IIUC.

Dept. of CCE, IIUC. Page | ix


Course Title: Python Programming Sessional Course Code: CCE-2406

Your lab report to be submitted should include at least the following topics.

1. Cover Page
2. Experiment No
3. Experiment Name
4. Objectives
5. Problem Statement/Theory
6. Algorithm/ Flowchart
7. Coding (Source Code)
8. Output (compilation, debugging & testing) and
9. Discussion & Conclusion.

Dept. of CCE, IIUC. Page | x


Course Title: Python Programming Sessional Course Code: CCE-2406

PART II: LAB SESSIONS


Lab #1: Introduction to Python Programming
Section A: Tutorial - Demonstrated by Instructor
(30-60 minutes prior to lab Experiments)

What is Python?
Python is a widely used high-level programming language for general-purpose
programming, created by Guido van Rossum and first released in 1991. Python is very
simple, yet incredibly powerful programming language. Like Perl, Python source code is also
available under the GNU General Public License (GPL). You can use it for writing web and
desktop applications, do scientific computations, create scripts, and more. You can use
Python for almost anything. In this course, you will learn the basics of Python syntax,
functions and creating console apps.
The whole process
Python code is executed using an interpreter, which is a program that reads one statement
from the source code, translates it to the machine code or virtual machine code, and then
executes it right away. Python is interpreted language, which means that Python code is
translated and executed by an interpreter, one statement at a time. At first, we write our
python source file, a file that has .py extension. Then we use the python interpreter to
interpret and run the program.
Python Editions
Python is now being developed and maintained by a large team of volunteers and is
available for free from the Python Software Foundation. Two versions of Python are
currently coexistent: Python 2 and Python 3. The programs written in Python 3 will not run
in Python 2. Python 3 is a newer version, but it isnot backward-compatible with Python 2.
This means that if you write a program using the Python 2 syntax,it may not work with a
Python 3 interpreter. Python provides a tool that automatically converts code written in
Python 2 into syntax Python 3 can use. We will use python 3 version for our lab experiment.
Installing Python
1. Go to Python's downloads page. https://www.python.org/downloads/
2. From the page, choose to download the second edition as illustrated in the figure below.

Figure-1

Dept. of CCE, IIUC. Page 1 of 47


Course Title: Python Programming Sessional Course Code: CCE-2406

3. Run the installation wizard that you have just downloaded. At this screen, click "Next".

Figure-2

4. In this screen, you can specify the location where Python to be installed. Leave as default and click on
Next.
5. Click on "Add python.exe to Path" and choose "Will be installed on local hard drive", then click Next.
6. The installation process will start. At the end, you'll have Python installed on your machine and ready
to be used.

Check Python version

To check Python version installed on your machine follow the following steps.

1. To run the command prompt, press Win + R at the same time, then type cmd in the wizard. Or you
can search for cmd from the start menu.
2. In the command prompt print the following command to test python's version.

3. Press Enter. The following result will be displayed on the screen.


Python 3.10.6

Example 1: First Python Program


If you wanted to, you could develop python applications using any text editor, Notepad++, WordPad or
any other editor. By using any text editor, you can write down the source code, then you could use
command line tools to interpret and execute your program. Python programs must be written with a
particular structure. The syntax must be correct, or the interpreter will generate error messages and
won't execute the program.

The following steps show the whole process:

1. Open any text editor of your choice and type in the following code:
# This code prints Hello, World on the screen

print("Hello, World!")
Dept. of CCE, IIUC. Page 2 of 47
Course Title: Python Programming Sessional Course Code: CCE-2406

2. Save the file as test.py, then close it.


3. Open the command line and print the following command to interpret the source code and run
theapplication.

python test.py
4. You will notice Hello, World! printed out on the screen, WoW!

** print() is a function used to print output on the screen.

Installing PyCharm

As may you have noticed, that process is tedious and cumbersome. And we need a more productive model
than that. So, developers around the world use those things called Integrated Development Environments
(IDE) that allows us to type in our code, compile, debug and format it, everything in one place. PyCharm
Community Edition is the free version of PyCharm, a premier IDE for Python. In this lab, we are going to
use it.

The following steps show you how to install it:


1. Go to the download page and download the latest version of PyCharm Community Edition.
https://www.jetbrains.com/pycharm/download/
2. After download is complete, installation process is easy and straight forward. Do it yourself.
3. As a feature of being a student, you can get PyCharm Professional Edition, and all other JetBrains
products, for free as long as you are a student. Go to this link: https://www.jetbrains.com/student/

Creating First PyCharm Project


1. When you open the IDE, you will see the following screen. Click on Create New Project.

Figure-3

2. Choose the location and name of the project. When you open PyCharm for the first time, you
may need to assign them interpreter path in Interpreter field.

3. Click on Create button, and your amazing project will show up.

Dept. of CCE, IIUC. Page 3 of 47


Course Title: Python Programming Sessional Course Code: CCE-2406

Figure-4
Let’s print something in PyCharm!
1. Right click on project name, choose new -> Python File and write the name you want for that
file. You will notice a new python file is added.
2. Double click on the file name, and write down the code snippet from the previous section. Click
on Run menu from the menu bar and choose Run to run the program.

Figure-5

Congratulations! You have made a complete Python application. From now on, we will learn to
build useful and complex applications.

Dept. of CCE, IIUC. Page 4 of 47


Course Title: Python Programming Sessional Course Code: CCE-2406

Why to Learn Python?


Python is a high-level, interpreted, interactive and object-oriented scripting language.
Python is designedto be highly readable. It uses English keywords frequently where as other
languages use punctuation, andit has fewer syntactical constructions than other languages.
Python is a MUST for students and working professionals to become a great Software
Engineer specially when they are working in Web Development Domain.

Some of the key advantages of learning Python:

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.
Python is Object-Oriented− Python supports Object-Oriented style or technique of
programming that encapsulates code within objects.
Python is a Beginner’s Language− Python is a great language for the beginner-level
programmers and supports the development of a wide range of applications from simple
text processing to WWW browsersto games.

Characteristics of Python

Following are important characteristics of Python Programming −


➢ It supports functional and structured programming methods as well as OOP.
➢ It can be used as a scripting language or can be compiled to byte-code for building
largeapplications.
➢ It provides very high-level dynamic data types and supports dynamic type checking.
➢ It supports automatic garbage collection.
➢ It can be easily integrated with C, C++, COM, ActiveX, CORBA, and Java.

Applications of Python

As mentioned before, Python is one of the most widely used language over the web. I'm
going to list fewof them here:
➢ 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-maintained.
➢ 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.
➢ Databases − Python provides interfaces to all major commercial databases.
➢ GUI Programming − Python supports GUI applications that can be created and

Dept. of CCE, IIUC. Page 5 of 47


Course Title: Python Programming Sessional Course Code: CCE-2406

ported to many system calls, libraries and windows systems, such as Windows MFC,
Macintosh, and the X Windowsystem of Unix.
➢ Scalable − Python provides a better structure and support for large programs than shell
scripting.

Audience
This Python tutorial is designed for software programmers who need to learn Python
programminglanguage from scratch.

Prerequisites
You should have a basic understanding of Computer Programming terminologies. A basic
understandingof any of the programming languages is a plus.
The Python language has many similarities to Perl, C, and Java. However, there are
some definitedifferences between the languages.

Python Syntax

Execute Python Syntax


As we learned in the previous page, Python syntax can be executed by writing directly
in the CommandLine:
>>> print("Hello, Welcome to CCE!")
Hello, Welcome to CCE!

Or by creating a python file on the server, using the .py file extension, and running it in
the CommandLine:
C:\Users\Your Name>python filename.py

Python Indentation

Indentation refers to the spaces at the beginning of a code line. Where in other programming
languages the indentation in code is for readability only, the indentation in Python is very
important.

Python uses indentation to indicate a block of code:

1. Example

Python will give you an error if you skip the indentation:

2. Example (Syntax Error)

The number of spaces is up to you as a programmer, the most common use is four, but it has
to be at leastone.

Dept. of CCE, IIUC. Page 6 of 47


Course Title: Python Programming Sessional Course Code: CCE-2406

3. Example

You have to use the same number of spaces in the same block of code, otherwise Python
will give you anerror:

4. Example (Syntax Error):

Python Variables
In Python, variables are created when you assign a value to it, Python has no specific command for
declaring a variable.

1. Example: (Variables in Python)

Comments

Python has commenting capability for the purpose of in-code documentation. Comments
start with a #,and Python will render the rest of the line as a comment:

1. Example: (Comments in Python)

Multi Line Comments


Python does not really have a syntax for multi-line comments. To add a multiline comment,
you could insert a # for each line:

2. Example

Or, not quite as intended, you can use a multiline string.

Dept. of CCE, IIUC. Page 7 of 47


Course Title: Python Programming Sessional Course Code: CCE-2406

Since Python will ignore string literals that are not assigned to a variable, you can add a
multiline string(triple quotes) in your code, and place your comment inside it:

3. Example

Python Variables
Variables: Variables are containers for storing data values.

Creating Variables: Python has no command for declaring a variable. A variable is created the moment
you first assign avalue to it.

1. Example

Casting
If you want to specify the data type of a variable, this can be done with casting.

1. Example

Get the Type

You can get the data type of a variable with the type() function.

2. Example

Dept. of CCE, IIUC. Page 8 of 47


Course Title: Python Programming Sessional Course Code: CCE-2406

Built-in Data Types


In programming, data type is an important concept. Variables can store data of
different types, and different types can do different things.

Python has the following data types built-in by default, in these categories:
There are three numeric types in Python:
• int
• float
• complex

Variables of numeric types are created when you assign a value to them:

2. Example

To verify the type of any object in Python, use the type() function:

3. Example

int: int, or integer, is a whole number, positive or negative, without decimals, of unlimited
length.

Dept. of CCE, IIUC. Page 9 of 47


Course Title: Python Programming Sessional Course Code: CCE-2406

Float: Float, or "floating point number" is a number, positive or negative, containing one or
more decimals.

Float can also be scientific numbers with an "e" to indicate the power of 10.
4. Example (Floats):

Complex: Complex numbers are written with a "j" as the imaginary part:

5. Example

Type Conversion: You can convert from one type to another with the int(), float(), and complex()
methods:

Example
** Convert from one type to another:

Dept. of CCE, IIUC. Page 10 of 47


Course Title: Python Programming Sessional Course Code: CCE-2406

Output:

1.0
2 (1+0j)
<class 'float'>
<class 'int'>
<class 'complex'>

Python Casting
Specify a Variable Type
There may be times when you want to specify a type on to a variable. This can be done with
casting. Python is an object-orientated language, and as such it uses classes to define data
types, including its primitive types.
Casting in python is therefore done using constructor functions:
• int() - constructs an integer number from an integer literal, a float literal (by
removing alldecimals), or a string literal (providing the string represents a whole
number)
• float() - constructs a float number from an integer literal, a float literal or a string
literal (providingthe string represents a float or an integer)
• str() - constructs a string from a wide variety of data types, including strings,
integer literals and float literals.

4. Example
Integers:

Dept. of CCE, IIUC. Page 11 of 47


Course Title: Python Programming Sessional Course Code: CCE-2406

5. Example
Floats:

6. Example
Strings:

Problem 1. Write a program to demonstrate different number datatypes in python.

Source code:

I=7
c=24+8j
f=701
s='HELLO EVERYONE!!\nThis is john\'s python programming...'
# NOTE: boolean has truth values that are case sensitive Ex: True (T is caps!) b= True

print("the value of c is:",i,'\nits type is:',type(i))


print("the value of c is:",f,'\nits type is:',type(f))
print("the value of c is:",c,'\nits type is:',type(c))
print("the value of c is:",s,'\nits type is:',type(s))
print("the value of c is:",b,'\nits type is:',type(b))
print('NOTE: boolean has truth values that are case sensitive Ex: True (T is caps!)')

Output:

the value of c is: 7


its type is: <class 'int'> the value of c is: 701 its type is: <class 'int'>
the value of c is: (24+8j)
its type is: <class 'complex'>
the value of c is: HELLO EVERYONE!! This is john's python programming.. its type is: <class 'str'>
the value of c is: True its type is: <class 'bool'>
NOTE: boolean has truth values that are case sensitive Ex: True (T is caps!)

** Process exited – Return


Code: 0 ** Press Enter to exit
terminal

Dept. of CCE, IIUC. Page 12 of 47


Course Title: Python Programming Sessional Course Code: CCE-2406

Section B: Lab Experiments - Demonstrated by students


(Please Code yourself and show the output to instructor)

Experiment-1
a) Install and configure Python IDE
b) Write a program that print your name with your student id and your CGPA.

Some Viva questions:


➢ What are the supported data types in Python?
➢ How to represent complex numbers in python?
➢ Write a print statement to truncate the number 12.34567 to 2 decimal places?
➢ What is command line argument?
➢ In which module command line arguments are present in Python?
➢ What is the importance of type conversion?
➢ How to determine the type of a variable in Python?
➢ What is indentation error with an example?

Dept. of CCE, IIUC. Page 13 of 47


Course Title: Python Programming Sessional Course Code: CCE-2406

Lab #2: Operator


Section A: Tutorial - Demonstrated by Instructor
(30-60 minutes prior to lab Experiments)

Operators are used to perform operations on values and variables. Operators can manipulate
individual items and returns a result. The data items are referred as operands or arguments. Operators
are either represented by keywords or special characters. Here are the types of operators supported
by Python:
➢ Arithmetic Operators
➢ Assignment Operators
➢ Relational or Comparison Operators
➢ Logical Operators
➢ Bitwise Operators
➢ Identity Operators
➢ Membership Operators

Operators are used to perform operations on variables and values.

In the example below, we use the + operator to add together two values:

1. Example

Python Arithmetic Operators


Arithmetic operators are used with numeric values to perform common mathematical operations:

Dept. of CCE, IIUC. Page 14 of 47


Course Title: Python Programming Sessional Course Code: CCE-2406

Assignment Operator

Assignment operators are used to assign values to variables:

Python Comparison Operators

Comparison operators are used to compare two values

Dept. of CCE, IIUC. Page 15 of 47


Course Title: Python Programming Sessional Course Code: CCE-2406

Python Logical Operators


Logical operators are used to combine conditional statements:

Python Identity Operators


Identity operators are used to compare the objects, not if they are equal, but if they are
actually thesame object, with the same memory location:

Python Membership Operators

Membership operators are used to test if a sequence is presented in an object:

Python Bitwise Operators


Bitwise operators are used to compare (binary) numbers:

Dept. of CCE, IIUC. Page 16 of 47


Course Title: Python Programming Sessional Course Code: CCE-2406

Problem 01: Write a program to perform different arithmetic operations on numbers in python.
Source code:

a=10; b=3
print("addition of a:",a,"&b:",b,"is:",a+b)
print("substraction of a:",a,"&b:",b,"is:",a-b)
print("multiplication of a:",a,"&b:",b,"is:",a*b)
print("division of a:",a,"&b:",b,"is:",a/b)
print("floor divison of a:",a,"&b:",b,"is:",a//b)
print("moduli of a:",a,"&b:",b,"is:",a%b)
print("exponent of a:",a,"&b:",b,"is:",a**b)

Output:
addition of a: 10 &b: 3 is: 13
substraction of a: 10 &b: 3 is: 7
multiplication of a: 10 &b: 3 is: 30
division of a: 10 &b: 3 is: 3.3333333333333335
floor divison of a: 10 &b: 3 is: 3
moduli of a: 10 &b: 3 is: 1
exponent of a: 10 &b: 3 is: 1000

** Process exited - Return Code: 0 **Press Enter to exit terminal

Section B: Lab Experiments - Demonstrated by students


(Please Code yourself and show the output to instructor)

Experiment-2

a) Write a program to convert U.S. dollars to Indian rupees.


b) Write a program to convert bits to Megabytes, Gigabytes and Terabytes.
c) Write a program to find the square root of a number.
d) Write a program to find the area of Rectangle.
e) Write a program to calculate area and perimeter of the square.
f) Write a program to calculate surface volume and area of a cylinder.

Some Viva Questions:

➢ Mention the use of //, **, % operator in Python


➢ Describe ternary operator in Python.
➢ Describe about different Logical operators in Python with appropriate examples.
➢ Describe about different Arithmetic operators in Python with appropriate examples.
➢ Describe about different Bitwise operators in Python with appropriate examples.

Dept. of CCE, IIUC. Page 17 of 47


Course Title: Python Programming Sessional Course Code: CCE-2406

Lab #3: Strings in Python


Section A: Tutorial - Demonstrated by Instructor
(30-60 minutes prior to lab Experiments)

Python has a built-in string class named "str" with many handy features (there is an older module
named "string" which you should not use). String literals can be enclosed by either double or single
quotes, although single quotes are more commonly used. Backslash escapes work the usual way
within both single and double quoted literals -- e.g., \n \' \". A double quoted string literal can contain
single quotes without any fuss (e.g., "I didn't do it") and likewise single quoted string can contain
double quotes.

Python strings are "immutable" which means they cannot be changed after they are created (Java
strings also use this immutable style).
So, for example the expression ('hello' + 'there') takes in the 2 strings 'hello' and 'there' and builds a
new string 'hellothere'.

Multiline Strings

You can assign a multiline string to a variable by using three quotes:

1. Example (You can use three double quotes):

Or three single quotes:


2. Example:

Strings are Arrays

Like many other popular programming languages, strings in Python are arrays of bytes representing
unicode characters.
However, Python does not have a character data type, a single character is simply a string with a length
of 1. Square brackets can be used to access elements of the string.

Dept. of CCE, IIUC. Page 18 of 47


Course Title: Python Programming Sessional Course Code: CCE-2406

3. Example:
Get the character at position 1 (remember that the first character has the position 0):

Looping Through a String

Since strings are arrays, we can loop through the characters in a string, with a for loop.
4. Example
Loop through the letters in the word "banana":

Slicing Strings

You can return a range of characters by using the slice syntax. Specify the start index and the end
index, separated by a colon, to return a part of the string.

5. Example
Get the characters from position 2 to position 5 (not included):

Note: The first character has index 0

Slice From the Start: By leaving out the start index, the range will start at the first character:

6. Example
Get the characters from the start to position 5 (not included):

By leaving out the end index, the range will go to the end:

7. Example

Get the characters from position 2, and all the way to the end:

Negative Indexing
Use negative indexes to start the slice from the end of the string:
Get the characters:
From: "o" in "World!" (position -5)

Dept. of CCE, IIUC. Page 19 of 47


Course Title: Python Programming Sessional Course Code: CCE-2406

To, but not included: "d" in "World!" (position -2):

Modify Strings

Python has a set of built-in methods that you can use on strings.
Upper Case
➢ Example
The upper() method returns the string in upper case:
a = "Hello, World!"
print(a.upper())

Lower Case
➢ Example
The lower() method returns the string in lower case:

a = "Hello, World!"
print(a.lower())

Remove Whitespace
Whitespace is the space before and/or after the actual text, and very often you
want to remove this space.
➢ Example
The strip() method removes any whitespace from the beginning or the end:

a = " Hello, World! "


print(a.strip()) # returns "Hello, World!"

Replace String
➢ Example
The replace() method replaces a string with another string:

a = "Hello, World!"
print(a.replace("H", "J"))

Split String
The split() method returns a list where the text between the specified separator becomes the list items.
➢ Example
The split() method splits the string into substrings if it finds instances of the separator:

a = "Hello, World!"
print(a.split(",")) # returns ['Hello', ' World!']

Dept. of CCE, IIUC. Page 20 of 47


Course Title: Python Programming Sessional Course Code: CCE-2406

Section B: Lab Experiments - Demonstrated by students


(Please Code yourself and show the output to instructor)

Experiment-3
a) Write a Python program to take a user input string, reverse it using slicing, and display the
reversed string in uppercase.
b) Create a multiline string representing a short story. Use string formatting to insert the name
of the main character and age within the story as a variable.
c) Write a Python program to take user input and use positive and negative indexing to display
the first, last, and middle characters. Calculate and print the length of the string.

Some Viva Questions:


➢ What is a string in Python, and how is it defined?
➢ Explain the difference between single and double-quoted strings in Python.
➢ How do you reverse a string in Python using slicing?
➢ What is string interpolation, and how is it achieved in Python?
➢ How can you find the length of a string in Python?
➢ What is the purpose of the strip() method in string manipulation?
➢ Describe the difference between split() and join() methods in Python strings.
➢ How can you convert a string to uppercase and lowercase in Python?
➢ Explain the concept of string immutability in Python.
➢ How would you check if a substring exists in a given string in Python?

Dept. of CCE, IIUC. Page 21 of 47


Course Title: Python Programming Sessional Course Code: CCE-2406

Lab #4: Data Structures in Python


Section A: Tutorial - Demonstrated by Instructor
(30-60 minutes prior to lab Experiments)

Data Structures are a way of organizing data so that it can be accessed more efficiently depending on
the situation. Data Structures are fundamentals of any programming language around which a
program is built. Python helps to learn the fundamentals of these data structures in a simpler way as
compared to other programming languages. Organizing, managing and storing data is important as it
enables easier access and efficient modifications. Data Structures allows to organize data in such a
way that help us to store collections of data, relate them and perform operations on them accordingly.

Python has implicit support for Data Structures be default which aim to store and access data. These
structures are called List, Dictionary, Tuple and Set.

Python Lists
Lists are used to store data of different data types sequentially. There are addresses assigned to every
element of the list, which is called an Index. The index value starts from 0 and goes on until the last
element called the positive index. There is also negative indexing which starts from -1 enabling you to
access elements from the last to the first.

Creating a List: Lists are created using square brackets:


empty_list = []
fruits = ['apple', 'banana', 'orange', 'blackberry', 'lemon']
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
items = ['chair', 2, 'table', 'light', 'bed', '200']
List is a collection which is ordered and changeable. Allows duplicate members.

Change Item Value: To change the value of a specific item, refer to the index number.
fruits = ['apple', 'banana', 'orange', 'blackberry', 'lemon']
fruits[2] = 'avocados'
print(fruits)
** The len() function returns to us the length of the list.

Dept. of CCE, IIUC. Page 22 of 47


Course Title: Python Programming Sessional Course Code: CCE-2406

Change a Range of Item Values: To change the value of items within a specific range
define a list with the new values, and refer to the range of index numbers where we
want to insert the new values.
fruits = ['apple', 'banana', 'orange', 'blackberry', 'lemon']
fruits[1:4] = ['grapes', 'kiwi', 'blueberry']
print(fruits)

Append Items: To add an item to the end of the list, use the append() method.
fruits = ['apple', 'banana', 'orange', 'blackberry', 'lemon']
fruits.append("Pineapple")
print(fruits)

Insert Items: To insert a list item at a specified index, use the insert() method. The
insert() method inserts an item at the specified index:
fruits = ['apple', 'banana', 'orange', 'blackberry', 'lemon']
fruits.insert(2, 'mango')
print(fruits)

Remove List Item: The remove() method removes the specified item.
fruits = ['apple', 'banana', 'orange', 'blackberry', 'lemon']
fruits.remove("orange")
print(fruits)

The del keyword also removes the specified index:


Clear the List: The clear() method empties the list. The list will still remains, but without any items.
fruits = ['apple', 'banana', 'orange', 'blackberry', 'lemon']
fruits.clear()
print(fruits)

Join Lists: There are several ways to join, or concatenate, two or more lists in Python. One of the easiest
ways are by using the ‘ + ‘ operator.

fruits1 = ['apple', 'banana', 'orange', 'pineapple']

fruits2 = ['blackberry', 'lemon']

fruits = fruits1 + fruits2


print(fruits)

Sorting Lists: There are several ways to sort items in a lists in Python. One of the easiest ways are using
sorted() function.
fruits = ['apple', 'banana', 'orange', 'blackberry', 'lemon']

sorted_list = sorted(fruits)

print(sorted_list)

For descending sorting,


desc_list = sorted(fruits, reverse=True)

Dept. of CCE, IIUC. Page 23 of 47


Course Title: Python Programming Sessional Course Code: CCE-2406

Python Tuples
Tuple is one of the built-in data types in Python. Tuples are used to store multiple items in a single
variable. A Python tuple is a sequence of comma separated items, enclosed in brackets (). The items
in a Python tuple need not be of same data type.

Tuples are identical to lists in all respects, except for the following properties:
• Tuples are defined by enclosing the elements in brackets () instead of square brackets [ ].
• Tuples are immutable.

Create a Tuple:

Update Tuples

Tuples are unchangeable, meaning that you cannot change, add, or remove items once the tuple
is created.
But there are some workarounds.

Change Tuple Values: Once a tuple is created, you cannot change its values. Tuples are
unchangeable, or immutable as it also is called.

But there is a workaround. You can convert the tuple into a list, change the list, and
convert the list back into a tuple.
➢ Example
Convert the tuple into a list to be able to change it:

Add Items: Since tuples are immutable, they do not have a build-in append() method,
but there are other ways to add items to a tuple.

• Convert into a list: Just like the workaround for changing a tuple, you can convert it
into a list, add your item(s), and convert it back into a tuple.

➢ Example

Convert the tuple into a list, add "orange", and convert it back into a tuple:

• Add tuple to a tuple. You are allowed to add tuples to tuples, so if you want to add one item,
(or many), create a new tuple with the item(s), and add it to the existing tuple:

Dept. of CCE, IIUC. Page 24 of 47


Course Title: Python Programming Sessional Course Code: CCE-2406

➢ Example
Create a new tuple with the value "orange", and add that tuple:

Join Two Tuples:


To join two or more tuples, you can use the + operator:
➢ Example
Join two tuples:

Multiply Tuples:
If you want to multiply the content of a tuple a given number of times, you can use the * operator:
➢ Example
Multiply the fruits tuple by 2:

Python Dictionary

Dictionaries are used to store data values in key:value pairs. A dictionary is a collection which is
ordered*, changeable and do not allow duplicates. As of Python version 3.7, dictionaries are ordered.
In Python 3.6 and earlier, dictionaries are unordered. Dictionaries are written with curlyy brackets,
and have keys and values:

➢ Example
Create and print a dictionary:

Dept. of CCE, IIUC. Page 25 of 47


Course Title: Python Programming Sessional Course Code: CCE-2406

Dictionary Items: Dictionary items are ordered, changeable, and does not allow
duplicates. Dictionary items are presented in key:value pairs, and can be referred to by
using the key name.
➢ Example
Print the "brand" value of the dictionary:

Change Values: We can change the value of a specific item by referring to its key name:
➢ Example (Change the "year" to 2018)

Update Dictionary: The update() method will update the dictionary with the items from the
given argument. The argument must be a dictionary, or an iterable object with key:value pairs.
➢ Example
Update the "year" of the car by using the update() method:

Removing Items: There are several methods to remove items from a dictionary:

➢ Example
The pop() method removes the item with the specified key name:

Dept. of CCE, IIUC. Page 26 of 47


Course Title: Python Programming Sessional Course Code: CCE-2406

➢ Example
The del keyword removes the item with the specified key name:

➢ Example
The del keyword can also delete the dictionary completely:

➢ Example
The clear() method empties the dictionary:

Dept. of CCE, IIUC. Page 27 of 47


Course Title: Python Programming Sessional Course Code: CCE-2406

Section B: Lab Experiments - Demonstrated by students


(Please Code yourself and show the output to instructor)

Experiment-4
a) Write a Python program to perform following operations on Lists: Create, Access, Update and
Delete items in a list.

b) Write a Python program to perform following operations on Tuples: Create Tuple, Access
Tuple, Update Tuple, Delete Tuple.

c) Write a Python program to represent and access an object inside an object within a Python
dictionary. (Use Countries Information)

Some Viva Questions:


➢ When to used list?

➢ Describe various list functions.

➢ Write syntax for a method to sort a list.

➢ Write syntax for a method to count occurrences of a list item in Python.

➢ How to concatenate list?

➢ Define empty tuple. Write syntax to create empty tuple.

➢ Write syntax to copy specific elements existing tuple into new tuple.

➢ Compare tuple with list (Any 4 points).

Dept. of CCE, IIUC. Page 28 of 47


Course Title: Python Programming Sessional Course Code: CCE-2406

Lab #5: Loops, Conditional Statements and


Function
Section A: Tutorial - Demonstrated by Instructor
(30-60 minutes prior to lab Experiments)

Loop In Python: Looping means repeating something over and over until a particular condition is
satisfied. A for loop in Python is a control flow statement that is used to repeatedly execute a group
of statements as long as the condition is satisfied. Such a type of statement is also known as an
iterative statement.
Python programming language provides following types of loops to handle looping requirements.

Loop Control Statements: Loop control statements change execution from its normal sequence.
When execution leaves a scope, all automatic objects that were created in that scope are destroyed.
Python supports the following control statements.

For Loop in Python: for loops are used when we have a block of code which we want to repeat a fixed
number of times. The for-loop is always used in combination with an iterable object, like a list or a
range. The Python for statement iterates over the members of a sequence in order, executing the
block each time.

Basic Syntax:
word = "Python"
for letter in word:
print (letter)

This simple for loop will go through each letters and print them in a sequence separately.

Dept. of CCE, IIUC. Page 29 of 47


Course Title: Python Programming Sessional Course Code: CCE-2406

Iterating Over Lists:

This for loop will go through each item of the list and print them in a sequence separately.

Using range function:

This loop prints numbers 1 through 5 using the range function.

Looping Through Strings:

This loop iterates over each character in the string and prints it.

Nested Loops:

This example demonstrates a nested for loop, useful for working with 2D data.

Looping Through a Dictionary:

This loop iterates over key-value pairs in a dictionary and later we can use the key and value pairs as
we need.

While Loop in Python: A while loop is a control flow statement which repeatedly executes a block of
code until the condition is satisfied. It stops executing the block only if the condition fails. One should
use a 'while' loop when one needs to perform a repeated operation, but doesn't know in advance how
many iterations would be needed.

Dept. of CCE, IIUC. Page 30 of 47


Course Title: Python Programming Sessional Course Code: CCE-2406

Basic While Loop:

This loop prints numbers 0 through 4 while the condition count < 5 is true.

Using else with While Loop:

The else block is executed when the condition becomes false.

While Loop with continue:

The while loop continues, skipping the iteration when count is 3.

Using break to Exit Loop:

This loop prints numbers 0 through 4 and then breaks out of the loop.

Conditional Statements in Python: Like every other programming language, Python also has some
predefined conditional statements. A conditional statement as the name suggests itself, is used to
handle conditions in a program. These statements guide the program while making decisions based
on the conditions encountered by the program.
Conditional statements (if, else, and elif) are fundamental programming constructs that allows us to
control the flow of a program based on conditions that we specify. They provide a way to make
decisions in our program and execute different code based on those decisions.

Dept. of CCE, IIUC. Page 31 of 47


Course Title: Python Programming Sessional Course Code: CCE-2406

Python supports the usual logical conditions from mathematics:

The If Statement in Python: The if statement is used to test a condition. If the condition is true, the
code inside the if block is executed.

Figure 01: Flowchart of ‘if’ statement

Example:

In this example, we use the > operator to compare the value of x to 5. If x is greater than 5, the
mentioned print statement will be executed, otherwise not.

Python If-Else Statement: The if statement alone tells us that if a condition is true, it will execute a
block of statements and if the condition is false, it won’t. But if we want to do something else if the
condition is false, we can use the else statement with the if statement to execute a block of code when
the if condition is false.

Dept. of CCE, IIUC. Page 32 of 47


Course Title: Python Programming Sessional Course Code: CCE-2406

Figure 02: Flowchart of If-Else Statement

Basic Syntax of if-else statement:

Example 01: Determine if a person is eligible to vote:

Example 02: Write a program to check if a year is a leap year or not:

Python Else-If Statement: The elif statement allows you to check multiple expressions for TRUE and
execute a block of code as soon as one of the conditions evaluates to TRUE. Similar to the else
statement, the elif statement is optional. However, unlike else, for which there can be at the most one

Dept. of CCE, IIUC. Page 33 of 47


Course Title: Python Programming Sessional Course Code: CCE-2406

statement; there can be an arbitrary number of elif statements following an if.


The syntax of the elif statement is given below:

Example 01: Write a program to print grade based on exam score:

Here, the program takes the exam score as input from the user, and then it uses if-else and elif
statements to determine the corresponding grade.

Example 02: Classify a number as positive, negative, or zero

The program checks three conditions in sequence using if, elif, and else. Depending on the user's input,
it prints whether the number is positive, negative, or zero.

Dept. of CCE, IIUC. Page 34 of 47


Course Title: Python Programming Sessional Course Code: CCE-2406

User Defined Function: In Python, a user-defined function is a block of reusable code designed to
perform a specific task. Functions provide a way to organize code into modular and reusable
components, making the code more readable, maintainable, and efficient.

Advantages of user-defined functions:


• User-defined functions help to decompose a large program into small segments which makes
program easy to understand, maintain and debug.
• If repeated code occurs in a program. Function can be used to include those codes and execute
when needed by calling that function.
• Programmers working on large project can divide the workload by making different functions.

Basic syntax of user-defined function in Python programming:

Creating a Function: It includes the def keyword, which is used to define the function in Python.
Let's create a simple function that adds two numbers:

Here, we have defined the function add_numbers() which take two parameters as an input, adds them
and returns the result. The way of calling a function is function_name(), and we can use this as much
we need in our program to avoid the repeated coding scenarios.

Conditional statements, loops inside a user-defined function: A user-defined function in


Python can contain conditional statements, loops, and various programming constructs. We
can use if, elif, and else statements to implement conditions based on which different parts
of your function can execute. Yet, we also can us loops to iterate over sequences or execute
a block of code repeatedly.

Dept. of CCE, IIUC. Page 35 of 47


Course Title: Python Programming Sessional Course Code: CCE-2406

Example: Write a user-defined function to Check if a Number is Prime

Section B: Lab Experiments - Demonstrated by students


(Please Code yourself and show the output to instructor)

Experiment-5
a) Write a Python program using a loop to find the sum of all prime numbers between 1 and 50.
b) Implement a program that uses nested loops to create a pattern, such as a triangle or a square,
using asterisks.
c) Create a function that takes a list of numbers as input and returns the average of the positive
numbers.
d) Write a program to take user input and use a while loop to find the factorial of a given number.

Some Viva Questions:


➢ Explain the difference between a for loop and a while loop.
➢ What is the break and continue statements used for within loops? Provide examples.
➢ What is the if, elif, and else keywords used for?
➢ What does it mean for a code block to be "indented" in Python, and why is it important
with conditional statements?
➢ How to declare a user-defined function in Python?
➢ Why are functions important in programming? What advantages do they offer?
➢ What's the difference between function parameters and arguments?

Dept. of CCE, IIUC. Page 36 of 47


Course Title: Python Programming Sessional Course Code: CCE-2406

Lab #6: File Handling in Python


Section A: Tutorial - Demonstrated by Instructor
(30-60 minutes prior to lab Experiments)

File handling in Python is a powerful and versatile tool that can be used to perform a wide range of
operations. However, it is important to carefully consider the advantages and disadvantages of file
handling when writing Python programs, to ensure that the code is secure, reliable, and performs well.
In shorts, File operations and file handling in Python refer to the various ways in which you can work
with files, such as reading from and writing to files. Python provides built-in functions and modules
that allow us to perform these operations efficiently.

Advantages of File Handling in Python:


✓ Versatility: File handling in Python allows you to perform a wide range of operations, such as
creating, reading, writing, appending, renaming, and deleting files.
✓ Flexibility: File handling in Python is highly flexible, as it allows you to work with different file
types (e.g., text files, binary files, CSV files, etc.), and to perform different operations on files
(e.g., read, write, append, etc.).
✓ User–Friendly: Python provides a user-friendly interface for file handling, making it easy to
create, read, and manipulate files.
✓ Cross-Platform: Python file-handling functions work across different platforms (e.g.,
Windows, Mac, Linux), allowing for seamless integration and compatibility.

Opening a File: Before performing any operation on the file like reading or writing, first, we have to
open that file. For this, we should use Python’s inbuilt function open() but at the time of opening, we
have to specify the mode, which represents the purpose of the opening file.

f = open(filename, mode)

The following mode is supported: Filename structure according to the system:

File Methods: Once a file is opened, we have various methods at our disposal.
➢ read(): Reads the entire file as a single string.
➢ readline(): Reads a single line from the file.
➢ readlines(): Reads all lines into a list of strings.

Dept. of CCE, IIUC. Page 37 of 47


Course Title: Python Programming Sessional Course Code: CCE-2406

➢ write(): Writes a string to the file.


➢ close(): Closes the file, saving changes and releasing system resources.

Example 1: Opening a file ‘example.txt’ with ‘read’ mode

Example 2: The open command will open the Python file in the read mode and the for loop will print
each line present in the file.

Example 3: In this example, we will see how we can read a file using the with statement in Python.

Example 4: We can also split lines while reading files in Python. The split() function splits the variable
when space is encountered.

Creating a File: Just like reading a file in Python, there are a number of ways to Writing to file in Python.

Example 1: Opening a file ‘example.txt’ with ‘write’ mode

Example 2: In this example, we will see how the write mode and the write() function is used to write
in a file. The close() command terminates all the resources in use and frees the system of this particular
program.

If a file already exists, it truncates the existing content and places the filehandle at the beginning of
the file. A new file is created if the mentioned file doesn’t exist.

Dept. of CCE, IIUC. Page 38 of 47


Course Title: Python Programming Sessional Course Code: CCE-2406

Example 3: We can also use the written statement along with the with() function.

Appending to a File: If we need to add content at the end of the existing file, we can use the access
mode ‘a’ to open a file in append mode.

** the with() function can also be utilized here to append a new line.

Example 4: By importing OS module, we can check if a file is exist or not

Example 5: Implementing the OS module, we can also delete a file:

Example 6: Write a Python program that reads a text file and counts the number of words in it. Display
the result.

Dept. of CCE, IIUC. Page 39 of 47


Course Title: Python Programming Sessional Course Code: CCE-2406

Section B: Lab Experiments - Demonstrated by students


(Please Code yourself and show the output to instructor)

Experiment-6
a) Write a function in Python that takes a filename and a string as parameters and appends the
string to the end of the file.
b) Write a function that takes a directory path and deletes all text files in that directory.
c) Write a Python program to merge data from "countries.txt" and "populations.txt" into a new
file named "details.txt". The new data should be organized in a proper format.

Important Viva Questions:


➢ Why is it important to close a file after performing operations on it?
➢ How can you read the entire contents of a file in Python?
➢ How can you list all files in a directory using Python?
➢ Explain the difference between the read(), readline(), and readlines() methods.
➢ How do you open a file in Python? Explain the various modes.

Dept. of CCE, IIUC. Page 40 of 47


Course Title: Python Programming Sessional Course Code: CCE-2406

Lab #7: Python OOPs Concepts


Section A: Tutorial - Demonstrated by Instructor
(30-60 minutes prior to lab Experiments)

In Python, object-oriented Programming (OOPs) is a programming paradigm that uses objects and
classes in programming. It aims to implement real-world entities like inheritance, polymorphisms,
encapsulation, etc. in the programming. The main concept of OOPs is to bind the data and the
functions that work on that together as a single unit so that no other part of the code can access this
data.

OOPs Concepts in Python


➢ Class
➢ Objects
➢ Polymorphism
➢ Encapsulation
➢ Inheritance
➢ Data Abstraction

Figure 01: Python OOPs Concepts

Python Class: A class is a collection of objects. A class contains the blueprints or the prototype from
which the objects are being created. It is a logical entity that contains some attributes and methods.
To understand the need for creating a class let’s consider an example, let’s say we wanted to track the
number of dogs that may have different attributes like breed, and age. If a list is used, the first element
could be the dog’s breed while the second element could represent its age. Let’s suppose there are
100 different dogs, then how would we know: Which element is supposed to be which and what if
you wanted to add other properties to these dogs?

This lacks organization and it’s the exact need for classes.

Dept. of CCE, IIUC. Page 41 of 47


Course Title: Python Programming Sessional Course Code: CCE-2406

Some points on Python class:


✓ Classes are created by keyword class.
✓ Attributes are the variables that belong to a class.
✓ Attributes are always public and can be accessed using the dot (.) operator.

Class Definition Syntax:

Python Objects: The object is an entity that has a state and behavior associated with it. It may be
any real-world object like a mouse, keyboard, chair, table, pen, etc. Integers, strings, floating-point
numbers, even arrays, and dictionaries, are all objects. More specifically, any single integer or any
single string is an object. The number 12 is an object, the string “Hello, world” is an object, a list is an
object that can hold other objects, and so on.

An object consists of:


➢ State: It is represented by the attributes of an object. It also reflects the properties of an
object.
➢ Behavior: It is represented by the methods of an object. It also reflects the response of an
object to other objects.
➢ Identity: It gives a unique name to an object and enables one object to interact with other
objects.

To understand the state, behavior, and identity let us take the example of the class dog (explained
above).

• The identity can be considered as the name of the dog.


• State or Attributes can be considered as the breed, age, or color of the dog.
• The behavior can be considered as to whether the dog is eating or sleeping.

Creating an Object:
This will create an object named obj of the class Dog defined above. Before diving deep into objects
and classes it's essentials to understand some basic keywords that will we used while working with
objects and classes.

an_object = Dog()

➢ Class methods must have an extra first parameter in the method definition. We do not give a
value for this parameter when we call the method, Python provides it.
➢ If we have a method that takes no arguments, then we still have to have one argument.
➢ This is similar to this pointer in C++ and this reference in Java.

Dept. of CCE, IIUC. Page 42 of 47


Course Title: Python Programming Sessional Course Code: CCE-2406

Note: An object is any entity that has attributes and behaviors. For example, a parrot is an object. It
has attributes - name, age, color and behavior - dancing, singing, etc.

The Python __init__ Method: The __init__ method is similar to constructors in C++ and Java. It is run
as soon as an object of a class is instantiated. The method is useful to do any initialization you want to
do with your object. Now let us define a class and create some objects using the self and __init__
method.

Example 01: Creating a class and object with class and instance attributes:

Example 02: The __init__ method is called for each instance to initialize their name attributes with
the provided names. The speak method is called in both instances (Rodger.speak() and
Tommy.speak()), causing each dog to print a statement with its name.

Python Inheritance: Inheritance is the capability of one class to derive or inherit the properties from
another class. The class that derives properties is called the derived class or child class and the class
from which the properties are being derived is called the base class or parent class. The benefits of
inheritance are:

➢ It represents real-world relationships well.


➢ It provides the reusability of a code. We don’t have to write the same code again and again.
Also, it allows us to add more features to a class without modifying it.
➢ It is transitive in nature, which means that if class B inherits from another class A, then all the
subclasses of B would automatically inherit from class A.

Dept. of CCE, IIUC. Page 43 of 47


Course Title: Python Programming Sessional Course Code: CCE-2406

Let's assume, we have created two classes i.e., Person (parent class) and Employee (Child Class). The
Employee class inherits from the Person class. We can use the methods of the person class through
the employee class as seen in the display function in the above code.

Example 03: A child class can also modify the behavior of the parent class as seen through the details()
method.

Python Polymorphism: In Python, polymorphisms refer to the occurrence of something in multiple


forms. As part of polymorphism, a Python child class has methods with the same name as a parent
class method. This is an essential part of programming. A single type of entity is used to represent a
variety of types in different contexts (methods, operators, objects, etc.)

Polymorphism may be used in Python in various ways. Polymorphism can be defined using numerous
functions, class methods, and objects.

Why Use Polymorphism?

➢ Code Reusability: Methods with the same name can perform different actions. You don't need
separate function names for each class.
➢ Extensibility: New classes can seamlessly integrate into existing code that uses polymorphic
behavior.
➢ Reduced Complexity: It simplifies how you use objects, allowing you to think more in terms of
general actions rather than specific implementations.

Dept. of CCE, IIUC. Page 44 of 47


Course Title: Python Programming Sessional Course Code: CCE-2406

Example 04: This code demonstrates the concept of inheritance and method overriding in Python
classes. It shows how subclasses can override methods defined in their parent class to provide specific
behavior while still inheriting other methods from the parent class.

Example 05: We have created a superclass: Polygon and two subclasses: Square and Circle. Notice the
use of the render() method. The main purpose of the render() method is to render the shape.
However, the process of rendering a square is different from the process of rendering a circle.

Hence, the render() method behaves differently in different classes. Or, we can say render() is
polymorphic.

Python Encapsulation: Encapsulation is one of the fundamental concepts in object-oriented


programming (OOP). It describes the idea of wrapping data and the methods that work on data within
one unit. This puts restrictions on accessing variables and methods directly and can prevent the
accidental modification of data. To prevent accidental change, an object’s variable can only be
changed by an object’s method. Those types of variables are known as private variables.

Dept. of CCE, IIUC. Page 45 of 47


Course Title: Python Programming Sessional Course Code: CCE-2406

A class is an example of encapsulation as it encapsulates all the data that is member functions,
variables, etc.

Encapsulation prevents outer classes from accessing and changing attributes and methods of a class.
This also helps to achieve data hiding. In Python, we denote private attributes using underscore as the
prefix i.e. single _ or double __.

Example 06: We have created the c variable as the private attribute. We cannot even access this
attribute directly and can’t even change its value.

Example 07: Here, we have tried to modify the value of __maxprice outside of the class. However,
since __maxprice is a private variable, this modification is not seen on the output. We have to use a
setter function i.e setMaxPrice() which takes price as a parameter.

Dept. of CCE, IIUC. Page 46 of 47


Course Title: Python Programming Sessional Course Code: CCE-2406

Key Points to Remember:


➢ Object-Oriented Programming makes the program easy to understand as well as efficient.
➢ Since the class is sharable, the code can be reused.
➢ Data is safe and secure with data abstraction.
➢ Polymorphism allows the same interface for different objects, so programmers can write
efficient code.

Section B: Lab Experiments - Demonstrated by students


(Please Code yourself and show the output to instructor)

Experiment-07
a) Write a Python program to build a simple library system using classes to represent books and
library members.
b) Write a Python program to create a bank account system with classes representing accounts
and transactions.

Some Viva Questions:


➢ Define OOP and explain its core principles.
➢ Describe the terms 'Encapsulation,' 'Inheritance,' and 'Polymorphism.'
➢ Differentiate between public, private, and protected attributes/methods in Python.
➢ What is a class, and how is it different from an object?
➢ What is the purpose of the ‘self’ parameter in Python classes?
➢ Explain the purpose of the __init__ method in Python classes.

Dept. of CCE, IIUC. Page 47 of 47

You might also like