BCA III Year Major-II Python
BCA III Year Major-II Python
Python Programming
(Major)
Page 1
BCA IIInd Year Subject – Python Programming
Page 2
BCA IIInd Year Subject – Python Programming
Page 3
BCA IIInd Year Subject – Python Programming
Unit I
➢ What is python
➢ History of Python
➢ Features of Python
➢ Installation of Python
➢ Python Real Time IDEs
➢ Variables
➢ Datatypes
➢ Operator
➢ Comment
➢ Input Output Operation
Page 4
BCA IIInd Year Subject – Python Programming
What is Python?
Python is an interpreted, object-oriented, high-level programming language with dynamic
semantics. Its high-level built in data structures, combined with dynamic typing and dynamic
binding, make it very attractive for Rapid Application Development, as well as for use as a
scripting or glue language to connect existing components together. Python's simple, easy to
learn syntax emphasizes readability and therefore reduces the cost of program maintenance.
Python supports modules and packages, which encourages program modularity and code reuse.
The Python interpreter and the extensive standard library are available in source or binary form
without charge for all major platforms, and can be freely distributed.
History of Python
• The implementation of Python was started in December 1989 by Guido Van Rossum at
CWI in Netherland.
• In February 1991, Guido Van Rossum published the code (labeled version 0.9.0) to
alt.sources.
• In 1994, Python 1.0 was released with new features like lambda, map, filter, and reduce.
• Python 2.0 added new features such as list comprehensions, garbage collection systems.
• On December 3, 2008, Python 3.0 (also called "Py3K") was released. It was designed to
rectify the fundamental flaw of the language.
▪ ABC language.
▪ Modula-3
Page 5
BCA IIInd Year Subject – Python Programming
Features in Python
Python provides many useful features which make it popular and valuable from the other
programming languages.
Expressive Language
Python can perform complex tasks using a few lines of code. A simple example, the hello world
program you simply type print("Hello World"). It will take only one line to execute, while Java
or C takes multiple lines.
Interpreted Language
Python is an interpreted language; it means the Python program is executed one line at a time.
The advantage of being interpreted language, it makes debugging easy and portable.
Cross-platform Language
Python can run equally on different platforms such as Windows, Linux, UNIX, and Macintosh,
etc. So, we can say that Python is a portable language.
Object-Oriented Language
Python supports object-oriented language and concepts of classes and objects come into
existence. It supports inheritance, polymorphism, and encapsulation, etc. The object-oriented
procedure helps to programmer to write reusable code and develop applications in less code.
Page 6
BCA IIInd Year Subject – Python Programming
GUI Support
Graphical User Interface is used for the developing Desktop application. PyQT5, Tkinter, Kivy
are the libraries which are used for developing the web application.
Once you have downloaded the installer, open the .exe file, such as python-3.10.11-amd64.exe,
by double-clicking it to launch the Python installer
After Clicking the Install Now Button the setup will start installing Python on your Windows
system. You will see a window like this.
Page 7
BCA IIInd Year Subject – Python Programming
After completing the setup. Python will be installed on your Windows system. You will see a
successful message.
Page 8
BCA IIInd Year Subject – Python Programming
Close the window after successful installation of Python. You can check if the installation of
Python was successful by using either the command line or the Integrated Development
Environment (IDLE), which you may have installed. To access the command line, click on the
Start menu and type “cmd” in the search bar. Then click on Command Prompt.
IDLE
IDLE is a cross-platform open-source IDE that comes by default with Python so you don’t need
to worry about the installation or setup. IDLE is written in Python and this IDE is suitable for
beginner-level developers who want to practice python development. IDLE is lightweight and
simple to use so you can build simple projects such as web browser game automation, basic web
scraping applications, and office automation. This IDE is not good for larger projects so move to
some advanced IDEs after learning the basics from IDLE.
• A multi-window code editor that allows features like smart indentation, autocomplete, etc
• It has an interactive interpreter with colorizing of input, output, and error messages.
• Text/Code Editor: Code editors are the lightweight tool that allows you to write and edit
the code with some features such as syntax highlighting and code formatting. It provided
fewer features than IDE.
PyCharm
In industries most professional developers use PyCharm and it has been considered the best
IDE for python developers. It was developed by the Czech company JetBrains and it’s a cross-
platform IDE.
some other features of this IDE.
• It is considered an intelligent code editor, fast and safe refactoring, and smart code.
• Features for debugging, profiling, remote development, testing the code, auto code
completion, quick fixing, error detection, and tools of the database.
• Support for Popular web technologies, web frameworks, scientific libraries, and version
control.
Spyder
Spyder is another good open-source and cross-platform IDE written in Python. It is also called
Scientific Python Development IDE and it is the most lightweight IDE for Python. It is mainly
used by data scientists who can integrate with Matplotlib, SciPy, NumPy, Pandas, Cython,
IPython, SymPy, and other open-source software. It comes with the Anaconda package manager
distribution and it has some good advanced features such as edit, debug, and data exploration.
Below are some other features of this IDE.
Page 10
BCA IIInd Year Subject – Python Programming
• Ability to search and edit the variables from the graphical user interface itself.
• It is very efficient in tracing each step of the script execution by a powerful debugger.
Visual Studio Code (VS Code) is a free and open-source code editor created by Microsoft that
can be used for Python development. You can add the extension to create a Python development
environment. It provides support for debugging, embedded Git control, syntax highlighting,
IntelliSense code completion, snippets, and code refactoring. Some of its best features are given
below.
• Powerful debugger by which the user can debug code from the editor itself.
• Easily customizable.
Atom
Page 11
BCA IIInd Year Subject – Python Programming
Variable Names:
A variable is the name given to a memory location. A value-holding Python variable is also
known as an identifier.
A variable can have a short name (like x and y) or a more descriptive name (age, carname,
total_volume). Rules for Python variables:
Pascal Case
Each word starts with a capital letter:
MyVariableName = "John"
Snake Case
Each word is separated by an underscore character:
my_variable_name = "John"
Example
Page 12
BCA IIInd Year Subject – Python Programming
And you can assign the same value to multiple variables in one line:
Example
x = y = z = "Orange"
print(x)
print(y)
print(z)
Data Types
A variable can contain a variety of values. On the other hand, a person's id must be stored
as an integer, while their name must be stored as a string.
The storage method for each of the standard data types that Python provides is specified by
Python. The following is a list of the Python-defined data types.
1. Numbers
2. Sequence Type
3. Boolean
4. Set
5. Dictionary
Page 13
BCA IIInd Year Subject – Python Programming
Python Numbers
• int
• float
• complex
x = 1 # int
y = 2.8 # float
z = 1j # complex
To verify the type of any object in Python, use the type() function:
Example
print(type(x))
print(type(y))
print(type(z))
Type Conversion
You can convert from one type to another with the int(), float(), and complex() methods:
Page 14
BCA IIInd Year Subject – Python Programming
x = 1 # int
y = 2.8 # float
z = 1j # complex
print(a)
print(b)
print(c)
print(type(a))
print(type(b))
print(type(c))
Comments
Comments in Python are the lines in the code that are ignored by the interpreter during the
execution of the program.
Page 15
BCA IIInd Year Subject – Python Programming
Single-Line Comments:
A single-line comment of Python is the one that has a hashtag # at the beginning of
it and continues until the finish of the line. If the comment continues to the next
line, add a hashtag to the subsequent line and resume the conversation.
Code
# This code is to show an example of a single-line comment
print( 'This statement does not have a hashtag before it' )
Multi-Line Comments
Code
# it is a
# comment
# extending to multiple lines
operators
The operator is a symbol that performs a specific operation between two operands
Python also has some operators, and these are given below -
o Arithmetic operators
o Comparison operators
o Assignment Operators
o Logical Operators
Page 16
BCA IIInd Year Subject – Python Programming
o Bitwise Operators
o Membership Operators
o Identity Operators
Arithmetic Operators
Arithmetic operators used between two operands for a particular operation.
% Modulus b%a=0
Comparison operator
Page 17
BCA IIInd Year Subject – Python Programming
Assignment Operators
= a = 10 a = 10
+= a += 30 a = a + 30
-= a -= 15 a = a - 15
*= a *= 10 a = a * 10
/= a /= 5 a=a/5
%= a %= 5 a=a%5
**= a **= 4 a = a ** 4
Logical Operators
or OR a or b
Identity Operators
Identity operators are used to compare the objects, not if they are equal, but if they
are actually the same object, with the same memory location:
is Returns True if both variables are the same object and false a is b
Page 18
BCA IIInd Year Subject – Python Programming
otherwise.
is not Returns True if both variables are not the same object and a is not b
false otherwise.
Membership Operators
Bitwise Operators
| OR a|b
^ XOR a^b
~ NOT ~a
Page 19
BCA IIInd Year Subject – Python Programming
The input function is used in all latest version of the Python. It takes the input from
the user and then evaluates the expression.
Example 1:
Example 2:
Page 20
BCA IIInd Year Subject – Python Programming
Suggested Question:
Page 21
BCA IIInd Year Subject – Python Programming
Unit II
➢ Conditional Statement
➢ Loops
➢ Dictionary , Set and Tuples
➢ Function
➢ Filter
➢ Lamda
➢ Map
Page 22
BCA IIInd Year Subject – Python Programming
Conditional Statement:
Conditional Statements are statements in Python that provide a choice for the control flow based
on a condition. It means that the control flow of the Python program will be decided based on the
outcome of the condition.
Indentation in Python:
For the ease of programming and to achieve simplicity, python doesn't allow the use of
parentheses for the block level code. In Python, indentation is used to declare a block. If two
statements are at the same indentation level, then they are the part of the same block.
if statement
The if statement is used to test a particular condition and if the condition is true, it executes a
block of code known as if-block.
if expression:
statement
Example:
num = int(input("enter the number:"))
if num%2 == 0:
print("The Given number is an even number")
if-else statement
The if-else statement provides an else block combined with the if statement which is executed in
the false case of the condition.
if condition:
#block of statements
else:
#another block of statements (else-block)
Example:
age = int (input("Enter your age: "))
if age>=18:
print("You are eligible to vote !!");
else:
Page 23
BCA IIInd Year Subject – Python Programming
elif statement
The elif statement enables us to check multiple conditions and execute the specific block of
statements depending upon the true condition among them. We can have any number of elif
statements in our program depending upon our need. However, using elif is optional.
if expression 1:
# block of statements
elif expression 2:
# block of statements
elif expression 3:
# block of statements
else:
# block of statements
Example:
number = int(input("Enter the number?"))
if number==10:
print("The given number is equals to 10")
elif number==50:
print("The given number is equal to 50");
elif number==100:
print("The given number is equal to 100");
else:
print("The given number is not equal to 10, 50 or 100");
Loop in python
In Python, a while loop is used to execute a block of statements repeatedly until a given
condition is satisfied. When the condition becomes false, the line immediately after the loop in
the program is executed.
while expression:
statement(s)
Page 24
BCA IIInd Year Subject – Python Programming
Example
count = 0
count = count + 1
print("Hello ")
For Loop
Python's for loop is designed to repeatedly execute a code block while iterating through a list,
tuple, dictionary, or other iterable objects of Python. The process of traversing a sequence is
known as iteration.
Example:
n=4
for i in range(0, n):
print(i)
Break statement
This command terminates the loop's execution and transfers the program's control to the
statement next to the loop.
for x in fruits:
print(x)
if x == "banana":
break
Output:
apple
banana
Continue statement
This command skips the current iteration of the loop. The statements following the continue
statement are not executed once the Python interpreter reaches the continue statement.
Example:
fruits = ["apple", "banana", "cherry"]
for x in fruits:
if x == "banana":
continue
print(x)
Output:
apple
cherry
Pass statement
The pass statement is used when a statement is syntactically necessary, but no code is to be
executed.
List:
In Python, the sequence of various data types is stored in a list. A list is a collection of different
kinds of values or items. Since Python lists are mutable, we can change their elements after
forming. The comma (,) and the square brackets [enclose the List's items] serve as separators.
print(list1)
print(list2)
Page 26
BCA IIInd Year Subject – Python Programming
print(type(list1))
print(type(list2))
# Creating a List
List1 = []
print(len(List1))
# Creating a List of numbers
List2 = [10, 20, 14]
print(len(List2))
output
1
3
In order to access the list items refer to the index number. Use the index operator [ ] to access an
item in a list. The index must be an integer. Nested lists are accessed using nested indexing.
Output
Ram
Ramesh
Negative indexing
In Python, negative sequence indexes represent positions from the end of the List. Instead of
having to compute the offset as in List[len(List)-3], it is enough to just write List[-3]. Negative
Page 27
BCA IIInd Year Subject – Python Programming
indexing means beginning from the end, -1 refers to the last item, -2 refers to the second-last
item, etc.
Ram
Sita
Append Items
To add an item to the end of the list, use the append() method:
thislist = ["apple", "banana", "cherry"]
thislist.append("orange")
print(thislist)
Output:
['apple', 'banana', 'cherry', 'orange']
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:
Output:
['apple', 'orange', 'banana', 'cherry']
Page 28
BCA IIInd Year Subject – Python Programming
Output:
['apple', 'cherry']
Output:
['banana', 'kiwi', 'mango', 'orange', 'pineapple']
Sort Descending
Output:
['pineapple', 'orange', 'mango', 'kiwi', 'banana']
Tupple
Python Tuple is a collection of objects separated by commas. In some ways, a tuple is similar to
a Python list in terms of indexing, nested objects, and repetition but the main difference between
both is Python tuple is immutable, unlike the Python list which is mutable.
Page 29
BCA IIInd Year Subject – Python Programming
Output:
('apple', 'banana', 'cherry')
Range of Indexes
You can specify a range of indexes by specifying where to start and where to end the range.
Add Items
Since tuples are immutable, they do not have a built-in append() method, but there are other
ways to add items to a tuple.
1. 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.
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:
Remove Items
Convert the tuple into a list, remove "apple", and convert it back into a tuple:
Page 30
BCA IIInd Year Subject – Python Programming
Python Set
A Python set is the collection of the unordered items. Each element in the set must be unique,
immutable, and the sets remove the duplicate elements. Sets are mutable which means we can
modify it after its creation.
Creating a set
The set can be created by enclosing the comma-separated immutable items with the curly braces
{}.
print(type(Days))
for i in Days:
print(i)
print(Days)
print(type(Days))
Page 31
BCA IIInd Year Subject – Python Programming
for i in Days:
print(i)
Python provides the add() method and update() method which can be used to add some
particular item to the set. The add() method is used to add a single element whereas the update()
method is used to add multiple elements to the set. Consider the following example.
Remove Item
Page 32
BCA IIInd Year Subject – Python Programming
Clear Method
Example
The clear() method empties the set:
thisset = {"apple", "banana", "cherry"}
thisset.clear()
print(thisset)
Example:
Output
<class 'dict'>
printing Employee data ....
Name : Dev
Age : 20
Salary : 45000
Page 33
BCA IIInd Year Subject – Python Programming
Company : WIPRO
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
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
thisdict.update({"year": 2020})
Removing Items
Example
The pop() method removes the item with the specified key name:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
thisdict.pop("model")
print(thisdict)
Output:
Page 34
BCA IIInd Year Subject – Python Programming
Items in list can be Items in set cannot be changed or replaced Items in tuple cannot be
replaced or changed but you can remove and add new items. changed or replaced
Python Functions
Python Functions is a block of statements that return the specific task. The idea is to put some
commonly or repeatedly done tasks together and make a function so that instead of writing the
same code again and again for different inputs, we can do the function calls to reuse code
contained in it over and over again.
Page 35
BCA IIInd Year Subject – Python Programming
return num3
# Driver code
num1, num2 = 5, 15
ans = add(num1, num2)
print(f"The addition of {num1} and {num2} results {ans}.")
Function Arguments
The following are the types of arguments that we can use to call a function:
1. Default arguments
2. Keyword arguments
3. Positional arguments
4. Variable-length arguments
Page 36
BCA IIInd Year Subject – Python Programming
Default Argument
A default argument is a parameter that assumes a default value if a value is not provided in the
function call for that argument. The following example illustrates Default arguments to write
functions in Python.
Keyword Arguments
The idea is to allow the caller to specify the argument name with values so that the caller
does not need to remember the order of parameters.
Positional Arguments
We used the Position argument during the function call so that the first argument (or value) is
assigned to name and the second argument (or value) is assigned to age. By changing the
position, or if you forget the order of the positions, the values can be used in the wrong places, as
shown in the Case-2 example below, where 27 is assigned to the name and Suraj is assigned to
the age.
Page 37
BCA IIInd Year Subject – Python Programming
Example:
Filter function
The filter() method filters the given sequence with the help of a function that tests each element
in the sequence to be true or not.
Python filter() Syntax
The filter() method in Python has the following syntax:
Syntax: filter(function, sequence)
Parameters:
• function: function that tests if each element of a sequence is true or not.
• sequence: sequence which needs to be filtered, it can be sets, lists, tuples, or containers
of any iterators.
Returns: an iterator that is already filtered.
Suggested Question:
Page 38
BCA IIInd Year Subject – Python Programming
Unit III
Importance of modular programming. What is module? Types of Modules - Pre defined, User
defined. User defines module creation, OS, Date-time, math modules, organizing python project
into packages, Types of packages - pre defined, user defined. Package v/s Folder, File and
Directory handling in Python
What is module?
A document with definitions of functions and various statements written in Python is called a
Python module.
Built-in Modules
There are several built-in modules in Python, which you can import whenever you like.
import platform
x = platform.system()
print(x)
output:
Windows
The math module is a built-in module in Python that is used for performing mathematical
operations. This module provides various built-in methods for performing different mathematical
tasks.
Factorial()
Page 39
BCA IIInd Year Subject – Python Programming
The Python math.factorial() method is used to calculate the factorial of a non-negative integer.
Example
import math
result = math.factorial(5)
print("The result obtained is:",result)
OutPut:
120
Remainder()
The Python math.remainder() method is used to calculate the remainder of dividing one
number by another. Mathematically it is denoted as –
Example 1:
import math
result = math.remainder(10, 3)
print("The result obtained is:",result)
Output:
1.0
Example2:
import math
result = math.remainder(-10, 3)
print("The result obtained is:",result)
output:
-1.0
Isqrt()
The Python math.isqrt() method is used to calculate the integer square root of a non-negative
integer.
Example 1:
import math
result = math.isqrt(25)
print("The result obtained is:",result)
Output:
5
LCM():
The Python math.lcm() method is used to calculate the least common multiple (LCM) of two or
more integers.
import math
result = math.lcm(12, 15)
print("The result obtained is:",result)
Output: 60
Page 40
BCA IIInd Year Subject – Python Programming
Python Dates
A date in Python is not a data type of its own, but we can import a module named datetime to
work with dates as date objects.
Example:
import datetime
x = datetime.datetime.now()
print(x)
Output:
2024-11-05 09:27:23.553350
Example:
import datetime
x = datetime.datetime(2020, 5, 17)
print(x)
Output:
2020-05-17 00:00:00
Python os Module
Python has a built-in os module with methods for interacting with the operating system, like
creating files and directories, management of files and directories, input, output, environment
variables, process management, etc.
Page 41
BCA IIInd Year Subject – Python Programming
OS Methods
os.name()
This function provides the name of the operating system module that it imports.
Currently, it registers 'posix', 'nt', 'os2', 'ce', 'java' and 'riscos'.
Example:
import os
print(os.name)
Output:
Posix
os.mkdir()
The os.mkdir() function is used to create new directory. Consider the following example.
Example:
import os
os.mkdir("d:\\newdir")
Output:
os.getcwd()
It returns the current working directory(CWD) of the file.
Example
import os
print(os.getcwd())
Output:
/home/PwqNte
os.chdir()
The os module provides the chdir() function to change the current working directory.
Example:
import os
os.chdir("d:\\")
Output:
d:\\
Page 42
BCA IIInd Year Subject – Python Programming
# module1.py
def greet(name):
print(f"Hello, {name}!")
# module2.py
def add(a, b):
return a + b
Example 1:
file = open('geek.txt','w')
file.write("This is the write command")
file.write("It allows us to write in a particular file")
file.close()
Example 2:
with open("file.txt", "w") as f:
f.write("Hello World!!!")
Example 3:
# Python code to illustrate read() mode
file = open("geeks.txt", "r")
print (file.read())
Example 4:
# Python code to illustrate read() mode character wise
file = open("geeks.txt", "r")
print (file.read(5))
Suggested Question:
Page 44
BCA IIInd Year Subject – Python Programming
Unit-IV
Adding new data and functions is not Adding new data and function is easy.
easy.
Page 45
BCA IIInd Year Subject – Python Programming
Class
The class can be defined as a collection of objects. It is a logical entity that has
some specific attributes and methods. For example: if you have an employee class,
then it should contain an attribute and method, i.e. an email id, name, age, salary,
etc.
Object
The object is an entity that has state and behavior. It may be any real-world object
like the mouse, keyboard, chair, table, pen, etc.
Everything in Python is an object, and almost everything has attributes and
methods. All functions have a built-in attribute __doc__, which returns the
docstring defined in the function source code.
Method
Page 46
BCA IIInd Year Subject – Python Programming
Polymorphism
Polymorphism contains two words "poly" and "morphs". Poly means many, and
morph means shape. By polymorphism, we understand that one task can be
performed in different ways. For example - you have a class animal, and all
animals speak. But they speak differently. Here, the "speak" behavior is
polymorphic in a sense and depends on the animal. So, the abstract "animal"
concept does not actually "speak", but specific animals (like dogs and cats) have a
concrete implementation of the action "speak".
Encapsulation
Encapsulation is also an essential aspect of object-oriented programming. It is used
to restrict access to methods and variables. In encapsulation, code and data are
wrapped together within a single unit from being modified by accident.
Data Abstraction
Data abstraction and encapsulation both are often used as synonyms. Both are
nearly synonyms because data abstraction is achieved through encapsulation.
Abstraction is used to hide internal details and show only functionalities.
Abstracting something means to give names to things so that the name captures the
core of what a function or a whole program does.
Classes in Python:
In Python, a class is a user-defined data type that contains both the data itself and
the methods that may be used to manipulate it.
Creating Classes in Python
In Python, a class can be created by using the keyword class, followed by the class
name. The syntax to create a class is given below.
Syntax
class ClassName:
#statement_suite
Objects in Python:
Page 47
BCA IIInd Year Subject – Python Programming
# Create a new instance of the Person class and assign it to the variable person1
person1 = Person("Ayan", 25)
person1.greet()
Example 2:
class Addition:
def add(self,a,b):
self.a=a
self.b=b
self.c=a+b
def display(self):
print(self.c)
x = int(input("Enter first number: "))
y = int(input("Enter second number: "))
Ad=Addition()
Ad.add(x,y)
Ad.display()
The self-parameter
The self-parameter refers to the current instance of the class and accesses the class
variables. We can use anything instead of self, but it must be the first parameter of
any function which belongs to the class.
Python Constructor
A constructor is a special type of method (function) which is used to initialize the
instance members of the class.
In C++ or Java, the constructor has the same name as its class, but it treats
constructor differently in Python. It is used to create an object.
Constructors can be of two types.
1. Parameterized Constructor
2. Non-parameterized Constructor
Constructor definition is executed when we create the object of this class.
Page 48
BCA IIInd Year Subject – Python Programming
class Student:
# Constructor - non parameterized
def __init__(self):
print("This is non parametrized constructor")
def show(self,name):
print("Hello",name)
student = Student()
student.show("John")
Example 2:
class stock:
def __init__(self,stid):
self.stid=stid
def show(self):
print(self.stid)
st=stock(101)
st.show()
Page 49
BCA IIInd Year Subject – Python Programming
Example:
class Employee:
__count = 0;
def __init__(self):
Employee.__count = Employee.__count+1
def display(self):
print("The number of employees",Employee.__count)
emp = Employee()
emp2 = Employee()
try:
print(emp.__count)
finally:
emp.display()
Inheritance:
Inheritance is the capacity of a particular class to obtain or inherit properties from
another class and then use them when required.
In inheritance, the child class acquires the properties and can access all the data
members and functions defined in the parent class. A child class can also provide
its specific implementation to the functions of the parent class.
Syntax
class derived-class(base class):
<class-suite>
Example:
class Animal:
def speak(self):
print("Animal Speaking")
class Dog(Animal): #child class Dog inherits the base class Animal
def bark(self):
Page 50
BCA IIInd Year Subject – Python Programming
print("dog barking")
d = Dog()
d.bark()
d.speak()
Example
class Animal:
def speak(self):
print("Animal Speaking")
#The child class Dog inherits the base class Animal
class Dog(Animal):
def bark(self):
print("dog barking")
#The child class Dogchild inherits another child class Dog
class DogChild(Dog):
def eat(self):
print("Eating bread...")
d = DogChild()
d.bark()
d.speak()
d.eat()
Multiple inheritance
Python provides us the flexibility to inherit multiple base classes in the child class.
Page 51
BCA IIInd Year Subject – Python Programming
Syntax
class Base1:
<class-suite>
class Base2:
<class-suite>
.
.
.
class BaseN:
<class-suite>
Example
class Calculation1:
def Summation(self,a,b):
return a+b;
class Calculation2:
def Multiplication(self,a,b):
return a*b;
class Derived(Calculation1,Calculation2):
def Divide(self,a,b):
return a/b;
d = Derived()
print(d.Summation(10,20))
print(d.Multiplication(10,20))
print(d.Divide(10,20))
What is module?
Page 52
BCA IIInd Year Subject – Python Programming
import platform
x = platform.system()
print(x)
output:
Windows
sys
• The python sys module provides functions and variables which are used to
manipulate different parts of the Python Runtime Environment. It lets us
access system-specific parameters and functions.
• Example: sys.argv, sys.exit(), sys.version
import sys
First, we have to import the sys module in our program before running any
functions.
sys.modules
This function provides the name of the existing python modules which have been
imported.
Example:
import sys
print(sys.modules)
sys.path
This function shows the PYTHONPATH set in the current system. It is an
environment variable that is a search path for all the python modules.
Example:
Page 53
BCA IIInd Year Subject – Python Programming
import sys
print(sys.path)
sys.exit
This function is used to exit from either the Python console or command prompt,
and also used to exit from the program in case of an exception.
Example:
import sys print("Program is running...")
sys.exit(0) # Exit with status code 0, indicating success
print("This will not be printed.")
sys.argv
This function returns a list of command line arguments passed to a Python script.
The name of the script is always the item at index 0, and the rest of the arguments
are stored at subsequent indices.
Example:
import sys
print("Script name:", sys.argv[0]) print("Arguments:", sys.argv[1:])
random
• The random() method returns a random floating number between 0 and 1.
• Example: random.randint(), random.choice(), random.shuffle()
Syntax
random.random()
Example:
import random
print(random.random())
choice()
The choice() method returns a randomly selected element from the specified
sequence.
The sequence can be a string, a range, a list, a tuple or any other kind of sequence.
Example:
import random
mylist = ["apple", "banana", "cherry"]
print(random.choice(mylist))
When we import a module with the help of the Python import module it searches
for the module initially in the local scope by calling __import__() function. The
value returned by the function is then reflected in the output of the initial code.
Example
import math
pie = math.pi
print("The value of pi is : ", pie)
Example:
from math import pi
print(pi)
Example:
from math import *
print(pi)
print(factorial(6))
class Color:
# constructor method
Page 55
BCA IIInd Year Subject – Python Programming
def __init__(self):
# object attributes
self.name = 'Green'
self.lg = self.Lightgreen()
def show(self):
print('Name:', self.name)
Page 56
BCA IIInd Year Subject – Python Programming
Exception Handling: Python Exception Handling handles errors that occur during
the execution of a program. Exception handling allows to respond to the error,
instead of crashing the running program. It enables you to catch and manage errors,
making your code more robust and user-friendly.
Syntax
try:
# Code that might raise an exception
except SomeException:
# Code to handle the exception
else:
# Code to run if no exception occurs
finally:
# Code to run regardless of whether an exception occurs
Example:
try:
n=0
res = 100 / n
except ZeroDivisionError:
print("You can't divide by zero!")
Page 57
BCA IIInd Year Subject – Python Programming
except ValueError:
print("Enter a valid number!")
else:
print("Result is", res)
finally:
print("Execution complete.")
Suggested question:
Ques 1. Explain class and Object in Python.
Ques 2. What is constructor? Explain different types of constructor.
Ques 3. What do you mean by inheritance? Explain different types of inheritance.
Ques 4. What is modules? Explain different types of modules.
Ques 5. What do you mean by exception handling?
Page 58
BCA IIInd Year Subject – Python Programming
Unit V
In Python, both multithreading and multiprocessing are techniques used to run
tasks concurrently or in parallel, which can help improve performance, especially
for tasks that are I/O-bound or CPU-bound. Here's an overview of each:
1. Multithreading
Multithreading allows you to run multiple threads (smaller units of a process)
within a single process. Each thread runs concurrently, but they share the same
memory space.
Use case: Ideal for I/O-bound tasks, such as reading/writing files, making network
requests, or database queries.
Limitations: Python’s Global Interpreter Lock (GIL) restricts true parallel
execution of threads in a single process. This means that even though you have
multiple threads, only one thread can execute Python bytecode at a time in a
process.
Key concepts:
Thread: A lightweight, independent unit of execution.
Global Interpreter Lock (GIL): A mechanism in Python (the most widely used
Python implementation) that ensures only one thread executes Python bytecode at
a time.
2. Multiprocessing
Multiprocessing, unlike multithreading, runs separate processes in parallel, each
with its own memory space. This avoids the GIL issue and is particularly useful for
CPU-bound tasks that require significant computation, such as image processing,
numerical calculations, or machine learning.
• Use case: Ideal for CPU-bound tasks, such as heavy computations or
processing large datasets.
• Advantages: Multiple processes can run on different CPU cores, allowing
true parallelism.
Key concepts:
• Process: A complete, independent unit of execution with its own memory.
• Inter-Process Communication (IPC): Mechanisms to allow processes to
share data or communicate with each other (e.g., queues, pipes).
Creating thread-inheriting thread class in python
we will extend the thread class from the threading module. This approach of
creating a thread is also known as Object-Oriented Way.
Page 59
BCA IIInd Year Subject – Python Programming
# Driver Code
Creating a Thread − To create a new thread in Python, you typically use the
Thread class from the threading module.
Page 60
BCA IIInd Year Subject – Python Programming
Threading Modules
The threading module is a high-level implementation of multithreading used to
deploy an application in Python. To use multithreading, we need to import the
threading module in Python Program.
3. Start a new thread: To start a thread in Python multithreading, call the thread
class's object. The start() method can be called once for each thread object;
otherwise, it throws an exception error.
Syntax:
1. t1.start()
2. t2.start()
Page 61
BCA IIInd Year Subject – Python Programming
Join method: It is a join() method used in the thread class to halt the main thread's
execution and waits till the complete execution of the thread object. When the
thread object is completed, it starts the execution of the main thread in Python.
Syntax:
import threading
def print_hello(n):
Print("Hello, how old are you? ", n)
T1 = threading.Thread( target = print_hello, args = (20, ))
T1.start()
T1.join()
Print("Thank you")
Page 62
BCA IIInd Year Subject – Python Programming
#cal_cube(ar)
#cal_sqre(ar)
th1 = threading.Thread(target=cal_sqre, args=(ar, ))
th2 = threading.Thread(target=cal_cube, args=(ar, ))
th1.start()
th2.start()
th1.join()
th2.join()
print(" Total time taking by threads is :", time.time() - t) # print the total time
print(" Again executing the main thread")
print(" Thread 1 and Thread 2 have finished their execution.")
Garbage Collection:
In Python, garbage collection refers to the automatic process of freeing up memory
by removing objects that are no longer in use or reachable. Python uses a
combination of reference counting and a cyclic garbage collector to manage
memory.
1. Reference Counting
Python keeps track of how many references there are to each object. When the
reference count drops to zero (i.e., no variable or object is pointing to it), the
memory occupied by that object can be released.
Features of NumPy
NumPy has various features which make them popular over lists.
Page 63
BCA IIInd Year Subject – Python Programming
Introduction of Pandas:
Pandas is a powerful and open-source Python library. The Pandas library is used
for data manipulation and analysis. Pandas consist of data structures and functions
to perform efficient operations on data.
Suggested Question:
Ques 1: What is Multithreading in python? Explain Threading module.
Ques 2: Explain life cycle of thread in python.
Ques 3: Explain Garbage collection.
Ques 4: Introduction of Numpy and pandas
Page 64
BCA IIInd Year Subject – Python Programming
Page 65
BCA IIInd Year Subject – Python Programming
Page 66