Python Lab Manual IIUC CCE
Python Lab Manual IIUC CCE
‘Lab Manual’
Prepared by:
5. GRADING POLICY vi
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
*** A three-hour lab session has been reserved for administering impromptu programming tests.
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
Attendance:
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.
• 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.
LAB REPORT-1
Topic: Data Structures in Python
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.
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.
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
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.
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.
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
python test.py
4. You will notice Hello, World! printed out on the screen, WoW!
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.
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.
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.
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
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
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
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.
1. Example
The number of spaces is up to you as a programmer, the most common use is four, but it has
to be at leastone.
3. Example
You have to use the same number of spaces in the same block of code, otherwise Python
will give you anerror:
Python Variables
In Python, variables are created when you assign a value to it, Python has no specific command for
declaring a variable.
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:
2. Example
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
You can get the data type of a variable with the type() function.
2. Example
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.
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:
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:
5. Example
Floats:
6. Example
Strings:
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
Output:
Experiment-1
a) Install and configure Python IDE
b) Write a program that print your name with your student id and your CGPA.
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
In the example below, we use the + operator to add together two values:
1. Example
Assignment Operator
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
Experiment-2
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
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.
3. Example:
Get the character at position 1 (remember that the first character has the position 0):
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):
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)
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:
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!']
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.
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.
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.
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)
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.
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)
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:
➢ Example
Create a new tuple with the value "orange", and add that tuple:
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:
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:
➢ 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:
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)
➢ Write syntax to copy specific elements existing tuple into new tuple.
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.
This for loop will go through each item of the list and print them in a sequence separately.
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.
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.
This loop prints numbers 0 through 4 while the condition count < 5 is true.
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.
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.
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.
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
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.
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.
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.
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.
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.
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.
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)
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.
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 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.
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 6: Write a Python program that reads a text file and counts the number of words in it. Display
the result.
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.
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.
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.
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.
To understand the state, behavior, and identity let us take the example of the class dog (explained
above).
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.
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:
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.
Polymorphism may be used in Python in various ways. Polymorphism can be defined using numerous
functions, class methods, and objects.
➢ 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.
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.
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.
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.