0% found this document useful (0 votes)
20 views

BCA III Year Major-II Python

The document outlines the curriculum for a Python Programming course for BCA III Year students, covering topics such as the history, features, installation, and data types of Python. It provides detailed information on Python's syntax, variable naming conventions, operators, and the installation process on different operating systems. Additionally, it discusses various Integrated Development Environments (IDEs) suitable for Python development.

Uploaded by

utkarshsahu2005
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
20 views

BCA III Year Major-II Python

The document outlines the curriculum for a Python Programming course for BCA III Year students, covering topics such as the history, features, installation, and data types of Python. It provides detailed information on Python's syntax, variable naming conventions, operators, and the installation process on different operating systems. Additionally, it discusses various Integrated Development Environments (IDEs) suitable for Python development.

Uploaded by

utkarshsahu2005
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 66

BCA IIInd Year Subject – Python Programming

BCA III Year

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

Python laid its foundation in the late 1980s.

• 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 programming language is said to be the predecessor of Python language, which


was capable of Exception Handling and interfacing with the Amoeba Operating System.

• The following programming languages influence Python:

▪ 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.

Easy to Learn and Use


Python is easy to learn as compared to other programming languages. Its syntax is
straightforward and much the same as the English language. There is no use of the semicolon or
curly-bracket, the indentation defines the code block.

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.

Free and Open Source


Python is freely available for everyone. It is freely available on its official
website www.python.org. It has a large community across the world that is dedicatedly working
towards make new python modules and functions.

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.

Large Standard Library


It provides a vast range of libraries for the various fields such as machine learning, web
developer, and also for the scripting. There are various machine learning libraries, such as Tensor
flow, Pandas, Numpy, Keras, and Pytorch, etc. Django, flask, pyramids are the popular
framework for Python web development.

GUI Programming 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.

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.

Installation process of Python in Windows


Step 1: Select Version to Install Python

Step 2: Downloading the Python Installer

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

Step 3: Running the Executable Installer

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

Step 4: Verify the Python Installation in Windows

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.

Install Python on Linux

• Getting Started with Python

• Check if Python already exists

• Python 3.13 Installation in Linux

o Step 1: Updating and Upgrading Operating System

o Step 2: Adding the deadsnakes PPA to your system’s package sources

o Step 3: Installing Python3.13 in Linux

o Step 4: Verifying the Installation of python3.13 in Linux

o Step 5: Installing PIP

o Step 6: Verifying Installation of PIP3.13

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.

• Python shell with syntax highlighting

• Call stack’s clear visibility


Page 9
BCA IIInd Year Subject – Python Programming

• 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.

• Program animation or stepping.

Python real times IDEs

What are Code Editor And IDE?

• 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.

• Integrated Development Environment (IDE): IDEs are full-fledged environments,


which provide all the essential tools needed for software development. It just doesn’t
handle the code (for example, write, edit, syntax highlighting, and auto-completion) but
also provides other features such as debugging, execution, testing, and code formatting
that helps programmers.

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

• Auto code completion and syntax highlighting.

• Ability to search and edit the variables from the graphical user interface itself.

• Static code analysis

• It is very efficient in tracing each step of the script execution by a powerful debugger.

Visual Studio Code

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.

• Thousands of plugins/extensions are available through the VS Code Marketplace.

• Powerful debugger by which the user can debug code from the editor itself.

• Easily customizable.

• Multi-platform, multi-language support, multi-split window feature, and vertical


orientation.

Atom

Atom is an open-source cross-platform IDE built using web technologies. It is based on a


framework built by GitHub named Electron. Atom is highly customizable and provides Python
language support installing the extension when Atom is running. Some of the good packages for
Python development are atom-python-run, Python Black, python-indent, atom-python-test,
autocomplete-python, Python Tools, linter-flake8, python-debugger, etc. Below are some nice
features of Atom.

• Enables support for third-party packages

• Lightweight, smart auto-completion, multi-language support with good syntax


highlighting

• Multiple panes and themes

• Allows installation and management of packages

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:

• A variable name must start with a letter or the underscore character


• A variable name cannot start with a number
• A variable name can only contain alpha-numeric characters and underscores (A-z, 0-9,
and _ )
• Variable names are case-sensitive (age, Age and AGE are three different variables)
• A variable name cannot be any of the Python keywords.
Multi Words Variable Names
Variable names with more than one word can be difficult to read.
There are several techniques you can use to make them more readable:
Camel Case
Each word, except the first, starts with a capital letter:
myVariableName = "John"

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"

Many Values to Multiple Variables

Python allows you to assign values to multiple variables in one line:

Example

x, y, z = "Orange", "Banana", "Cherry"


print(x)
print(y)
print(z)

Page 12
BCA IIInd Year Subject – Python Programming

One Value to Multiple Variables

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

Text Type: Str


Numeric Types: int, float, complex
Sequence Types: list, tuple, range
Mapping Type: Dict
Set Types: set, frozenset
Boolean Type: Bool

Page 13
BCA IIInd Year Subject – Python Programming

Python Numbers

There are three numeric types in Python:

• 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

#convert from int to float:


a = float(x)

#convert from float to int:


b = int(y)

#convert from int to complex:


c = complex(x)

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.

Below are some of the most common uses for comments:

o Readability of the Code

o Restrict code execution

o Provide an overview of the program or project metadata

o To add resources to the code

Types of Comments in Python

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

a) Multiline comments using multiple hashtags (#)


Python does not provide the facility for multi-line comments. However,
there are indeed many ways to create multi-line comments.

Code

# it is a
# comment
# extending to multiple lines

b) Using String Literals


On executing the above code we can see that there will not be any output so
we use the strings with triple quotes(“””) as multiline comments.

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.

Operator Name Example


+ Addition a + b = 30
- Subtraction a – b = -10
* Multiplication a * b = 200
/ Division b/a=2

% Modulus b%a=0

** Exponent a**b =10**20


// Floor Division 9//2 = 4

Comparison operator

Comparison operators are used to compare two values:

Operator Name Example

== Equal (a == b) is not true.

!= Not equal (a != b) is true.

> Greater than (a > b) is not true.

< Less than (a < b) is true.

>= Greater than or equal to (a >= b) is not true.

<= Less than or equal to (a <= b) is true.

Page 17
BCA IIInd Year Subject – Python Programming

Assignment Operators

Operator Example Same As

= 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

Logical operators are used to combine conditional statements:

Operator Name Example

and AND a and b

or OR a or b

not NOT not(a)

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:

Operator Description Example

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

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

Operator Description Example

in Returns True if it finds a variable in the specified a in b


sequence, false otherwise.

not in returns True if it does not finds a variable in the a not in b


specified sequence and false otherwise.

Bitwise Operators

Bitwise operators are used to compare (binary) numbers:

Operator Name Example

& AND a&b

| OR a|b

^ XOR a^b

~ NOT ~a

<< Zero fill left shift a << 3

>> Signed right shift a >> 3

Page 19
BCA IIInd Year Subject – Python Programming

Input Output Operation

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:

name = input("Enter your name: ")


print(name)

Example 2:

name = input("Enter your name: ") # String Input


age = int(input("Enter your age: ")) # Integer Input
marks = float(input("Enter your marks: ")) # Float Input

Page 20
BCA IIInd Year Subject – Python Programming

Suggested Question:

1. What is Python? Explain different features of python.


2. Explain different IDEs Python.
3. What is operator? Explain different types of operator.
4. Explain different types of python comments in details.

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.

Types of Conditional Statements in Python

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.

The syntax of the if-statement is given below.

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

print("Sorry! you have to wait !!");

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

Python programming language provides two types of Python loopshecking time

While 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.

Python While Loop Syntax:

while expression:
statement(s)

Page 24
BCA IIInd Year Subject – Python Programming

Example

count = 0

while (count < 3):

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.

Syntax of the for Loop


for value in sequence:
code block

fruits = ["apple", "banana", "cherry"]


for x in fruits:
print(x)

The range() Function


With the help of the range() function, we may produce a series of numbers. range(10) will
produce values between 0 and 9. (10 numbers).

Example:
n=4
for i in range(0, n):
print(i)

Loop Control Statements


Statements used to control loops and change the course of iteration are called control statements.
All the objects produced within the local scope of the loop are deleted when execution is
completed.

Break statement
This command terminates the loop's execution and transfers the program's control to the
statement next to the loop.

fruits = ["apple", "banana", "cherry"]


Page 25
BCA IIInd Year Subject – Python Programming

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.

list1 = [1, 2, "Python", "Program", 15.9]

list2 = ["Amy", "Ryan", "Henry", "Emma"]

# printing the list

print(list1)

print(list2)

Page 26
BCA IIInd Year Subject – Python Programming

# printing the type of list

print(type(list1))

print(type(list2))

Getting the size of Python list

Python len() is used to get the length of the list.

# Creating a List
List1 = []
print(len(List1))
# Creating a List of numbers
List2 = [10, 20, 14]
print(len(List2))
output
1
3

Accessing elements from the List

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.

# Creating a List with


# the use of multiple values
List = ["Ram", "For", "Ramesh"]

# accessing a element from the


# list using index number
print("Accessing a element from the list")
print(List[0])
print(List[2])

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.

List = [1, 2, 'Ram', 4, ‘Sita', 6, 'Raj']


print("Accessing element using negative indexing")

# print the last element of list


print(List[-1])

# print the third last element of list


print(List[-3])
Output:

Accessing element using negative indexing

Ram
Sita

Change Item Value


To change the value of a specific item, refer to the index number:
thislist = ["apple", "banana", "cherry"]
thislist[1] = "blackcurrant"
print(thislist)
Output:
['apple', 'blackcurrant', 'cherry']

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:

thislist = ["apple", "banana", "cherry"]


thislist.insert(1, "orange")
print(thislist)

Output:
['apple', 'orange', 'banana', 'cherry']

Page 28
BCA IIInd Year Subject – Python Programming

Remove Specified Item

The remove() method removes the specified item.

thislist = ["apple", "banana", "cherry"]


thislist.remove("banana")
print(thislist)

Output:
['apple', 'cherry']

Sort List Alphanumerically


List objects have a sort() method that will sort the list alphanumerically, ascending, by default:

thislist = ["orange", "mango", "kiwi", "pineapple", "banana"]


thislist.sort()
print(thislist)

Output:
['banana', 'kiwi', 'mango', 'orange', 'pineapple']

Sort Descending

To sort descending, use the keyword argument reverse = True:

thislist = ["orange", "mango", "kiwi", "pineapple", "banana"]


thislist.sort(reverse = True)
print(thislist)

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.

Features of Python Tuple


o Tuples are an immutable data type, meaning their elements cannot be changed after they
are generated.
o Each element in a tuple has a specific order that will never change because tuples are
ordered sequences.

Page 29
BCA IIInd Year Subject – Python Programming

Creating Python Tuples


There are various ways by which you can create a tuple in Python. They are as follows:
• Using round brackets
• With one item
• Tuple Constructor

thistuple = ("apple", "banana", "cherry")


print(thistuple)

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.

thistuple = ("apple", "banana", "cherry", "orange", "kiwi", "melon", "mango")


print(thistuple[2:5])

Output:('cherry', 'orange', 'kiwi')

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.

thistuple = ("apple", "banana", "cherry")


y = list(thistuple)
y.append("orange")
thistuple = tuple(y)

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:

thistuple = ("apple", "banana", "cherry")


y = ("orange",)
thistuple += y
print(thistuple)

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

thistuple = ("apple", "banana", "cherry")


y = list(thistuple)
y.remove("apple")
thistuple = tuple(y)

The del keyword can delete the tuple completely:

thistuple = ("apple", "banana", "cherry")


del thistuple
print(thistuple) #this will raise an error because the tuple no longer exists

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
{}.

Example 1: Using curly braces

Days = {"Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"}


print(Days)

print(type(Days))

print("looping through the set elements ... ")

for i in Days:

print(i)

Example 2: Using set() method

Days = set(["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunda


y"])

print(Days)

print(type(Days))

Page 31
BCA IIInd Year Subject – Python Programming

print("looping through the set elements ... ")

for i in Days:

print(i)

Adding items to the set

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.

Example: 1 - Using add() method


Months = set(["January","February", "March", "April", "May", "June"])
print("\nprinting the original set ... ")
print(months)
print("\nAdding other months to the set...");
Months.add("July");
Months.add ("August");
print("\nPrinting the modified set...");
print(Months)
print("\nlooping through the set elements ... ")
for i in Months:
print(i)

Example - 2 Using update() function

Months = set(["January","February", "March", "April", "May", "June"])


print("\nprinting the original set ... ")
print(Months)
print("\nupdating the original set ... ")
Months.update(["July","August","September","October"]);
print("\nprinting the modified set ... ")
print(Months);

Remove Item

To remove an item in a set, use the remove(), or the discard() method.

thisset = {"apple", "banana", "cherry"}


thisset.remove("banana")
print(thisset)

Page 32
BCA IIInd Year Subject – Python Programming

remove "banana" by using the discard() method:


thisset = {"apple", "banana", "cherry"}
thisset.discard("banana")
print(thisset)

Clear Method
Example
The clear() method empties the set:
thisset = {"apple", "banana", "cherry"}
thisset.clear()
print(thisset)

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.

Example:

Employee = {"Name": "Johnny", "Age": 32, "salary":26000,"Company":"^TCS"}print(type(


Employee))
print("printing Employee data .... ")
print(Employee)
Output:
<class 'dict'>
printing Employee data ....
{'Name': 'Johnny', 'Age': 32, 'salary': 26000, 'Company': TCS}

Accessing the dictionary values


Employee = {"Name": "Dev", "Age": 20, "salary":45000,"Company":"WIPRO"}
print(type(Employee))
print("printing Employee data .... ")
print("Name : %s" %Employee["Name"])
print("Age : %d" %Employee["Age"])
print("Salary : %d" %Employee["salary"])
print("Company : %s" %Employee["Company"])

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

Update the "year" of the car by using the update() method:

thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
thisdict.update({"year": 2020})

Removing Items

There are several methods to remove items from a dictionary:

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:

{'brand': 'Ford', 'year': 1964}

Page 34
BCA IIInd Year Subject – Python Programming

Comparison of list tuple and set in python

List Set Tuple

Lists is Mutable Set is Mutable Tuple is Immutable

It is Ordered collection It is Unordered collection of items It is Ordered collection of


of items items

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.

Python Function Declaration


The syntax to declare a function is:

Types of Functions in Python


Below are the different types of functions in Python:
• Built-in library function: These are Standard functions in Python that are available to
use.
• User-defined function: We can create our own functions based on our requirements.

Page 35
BCA IIInd Year Subject – Python Programming

Creating a Function in Python


We can define a function in Python, using the def keyword
Example:
# A simple Python function
def fun():
print("Welcome to GFG")
# Driver code to call a function
fun()

Python Function with Parameters

def function_name(parameter: data_type) -> return_type:


"""Docstring"""
# body of the function
return expression

def add(num1: int, num2: int) -> int:


"""Add two numbers"""
num3 = num1 + num2

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.

# Python program to demonstrate


# default arguments
def myFun(x, y=50):
print("x: ", x)
print("y: ", y)

# Driver code (We call myFun() with only


# argument)
myFun(10)

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.

# Python code to demonstrate the use of keyword arguments


# Defining a function
def function( n1, n2 ):
print("number 1 is: ", n1)
print("number 2 is: ", n2)

# Calling function and passing arguments without using keyword


print( "Without using keyword" )
function( 50, 30)

# Calling function and passing arguments using keyword


print( "With using keyword" )
function( n2 = 50, n1 = 30)

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:

def nameAge(name, age):


print("Hi, I am", name)
print("My age is ", age)
# You will get correct output because
# argument is given in order
print("Case-1:")
nameAge("Suraj", 27)
# You will get incorrect output because
# argument is not in order
print("\nCase-2:")
nameAge(27, "Suraj")

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:

1. Explain different conditional statement.


2. Explain list ,Tuple and set.
3. What do you mean by function ? Explain with its types.
4. Explain filter and Lamda function in python.

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.

o Python itself allows for the creation of modules.


o Similar to the re (regular expression) module, a module can be primarily written in C
programming language and then dynamically inserted at run-time.
o A built-in module, such as the itertools module, is inherently included in the interpreter.

A module is a file containing Python code, definitions of functions, statements, or classes. An


example_module.py file is a module we will create and whose name is example_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

Python math Module

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 - Date and Time


A Python program can handle date and time in several ways. Converting between date formats is
a common chore for computers

Getting the Calendar for a Month


The calendar module gives a wide range of methods to play with yearly and monthly calendars.
Example:
import calendar
cal = calendar.month(2023, 4)
print ("Here is the calendar:")
print (cal)
Output:

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

Creating Date Objects


To create a date, we can use the datetime() class (constructor) of the datetime module.
The datetime() class requires three parameters to create a date: year, month, day.

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:\\

What is a Python Package?


Python Packages are a way to organize and structure your Python code into reusable
components. Think of it like a folder that contains related Python files (modules) that work
together to provide certain functionality. Packages help keep your code organized, make it easier
to manage and maintain, and allow you to share your code with others. They’re like a toolbox
where you can store and organize your tools (functions and classes) for easy access and reuse in
different projects.

Page 42
BCA IIInd Year Subject – Python Programming

How to Create Package in Python?


Creating packages in Python allows you to organize your code into reusable and manageable
modules. Here’s a brief overview of how to create packages:
• Create a Directory: Start by creating a directory (folder) for your package. This
directory will serve as the root of your package structure.
• Add Modules: Within the package directory, you can add Python files (modules)
containing your code. Each module should represent a distinct functionality or
component of your package.
• Init File: Include an __init__.py file in the package directory. This file can be empty or
can contain an initialization code for your package. It signals to Python that the directory
should be treated as a package.
• Subpackages: You can create sub-packages within your package by adding additional
directories containing modules, along with their own __init__.py files.
• Importing: To use modules from your package, import them into your Python scripts
using dot notation. For example, if you have a module named module1.py inside a
package named mypackage, you would import its function like this: from
mypackage.module1 import greet.
• Distribution: If you want to distribute your package for others to use, you can create a
setup.py file using Python’s setuptools library. This file defines metadata about your
package and specifies how it should be installed.
Code Example

# module1.py
def greet(name):
print(f"Hello, {name}!")

# module2.py
def add(a, b):
return a + b

from mypackage import module1, module2

# Using functions from module1


module1.greet("Alice")

# Using functions from module2


result = module2.add(3, 5)
print("The result of addition is:", result)

Python File Handling:


Python supports file handling and allows users to handle files i.e., to read and write files, along
with many other file handling options, to operate on files.

Python File Open


The key function for working with files in Python is the open() function.
The open() function takes two parameters; filename, and mode.
Page 43
BCA IIInd Year Subject – Python Programming

Where the following mode is supported:


1. r: open an existing file for a read operation.
2. w: open an existing file for a write operation. If the file already contains some data, then
it will be overridden but if the file is not present then it creates the file as well.
3. a: open an existing file for append operation. It won’t override existing data.
4. r+: To read and write data into the file. This mode does not override the existing data, but
you can modify the data starting from the beginning of the file.
5. w+: To write and read data. It overwrites the previous file if one exists, it will truncate
the file to zero length or create a file if it does not exist.
6. a+: To append and read data from the file. It won’t override existing data.

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:

1. What is module? Explain OS , Math and Date time module.


2. Explain package.
3. What is the use of file handling? Explain file modes.

Page 44
BCA IIInd Year Subject – Python Programming

Unit-IV

Procedural Oriented Programming Object-Oriented Programming

In procedural programming, the In object-oriented programming, the


program is divided into small parts program is divided into small parts
called functions. called objects.

Procedural programming follows a top- Object-oriented programming follows


down approach. a bottom-up approach.

There is no access specifier in Object-oriented programming has


procedural programming. access specifiers like private, public,
protected, etc.

Adding new data and functions is not Adding new data and function is easy.
easy.

Procedural programming does not have Object-oriented programming provides


any proper way of hiding data so it data hiding so it is more secure.
is less secure.

In procedural programming, Overloading is possible in object-


overloading is not possible. oriented programming.

In procedural programming, there is no In object-oriented programming, the


concept of data hiding and inheritance. concept of data hiding and inheritance
is used.

In procedural programming, the In object-oriented programming, data


function is more important than the is more important than function.
data.

Procedural programming is based on Object-oriented programming is based


the unreal world. on the real world.

Page 45
BCA IIInd Year Subject – Python Programming

Procedural Oriented Programming Object-Oriented Programming

Procedural programming is used for Object-oriented programming is used


designing medium-sized programs. for designing large and complex
programs.

Procedural programming uses the Object-oriented programming uses the


concept of procedure abstraction. concept of data abstraction.

Code reusability absent in procedural Code reusability present in object-


programming, oriented programming.

Examples: C, FORTRAN, Pascal, Examples: C++, Java, Python, C#, etc.


Basic, etc.
Unit IV
Python OOPs Concepts
OOPs Concepts in Python
• Class in Python
• Objects in Python
• Polymorphism in Python
• Encapsulation in Python
• Inheritance in Python
• Data Abstraction in Python

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

The method is a function that is associated with an object. In Python, a method is


not unique to class instances. Any object type can have methods.
Inheritance
Inheritance is the most important aspect of object-oriented programming, which
simulates the real-world concept of inheritance. It specifies that the child object
acquires all the properties and behaviors of the parent object.
By using inheritance, we can create a class which uses all the properties and
behavior of another class. The new class is known as a derived class or child class,
and the one whose properties are acquired is known as a base class or parent class.
It provides the re-usability of the code.

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

An object is a particular instance of a class with unique characteristics and


functions.
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def greet(self):
print("Hello, my name is " + self.name)

# 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

Creating the constructor in python


In Python, the method the __init__() simulates the constructor of the class. This
method is called when the class is instantiated. It accepts the self-keyword as a first
argument which allows accessing the attributes or method of the class.
Python Non-Parameterized Constructor
The non-parameterized constructor uses when we do not want to manipulate the
value or the constructor that has only self as an argument.

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")

Python Parameterized Constructor


The parameterized constructor has multiple parameters along with the self.
Consider the following example.
class Student:
# Constructor - parameterized
def __init__(self, name):
print("This is parametrized constructor")
self.name = name
def show(self):
print("Hello",self.name)
student = Student("John")
student.show()

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

Data abstraction in python


Abstraction is an important aspect of object-oriented programming. In python, we
can also perform data hiding by adding the double underscore (___) as a prefix to
the attribute which is to be hidden. After this, the attribute will not be visible
outside of the class through the object.

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()

Python Multi-Level inheritance


Multi-Level inheritance is possible in python like other object-oriented languages.
Multi-level inheritance is archived when a derived class inherits another derived
class. There is no limit on the number of levels up to which, the multi-level
inheritance is archived in python.
Syntax
class class1:
<class-suite>
class class2(class1):
<class suite>
class class3(class2):
<class suite>

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>

class Derived(Base1, Base2, ...... 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?

A document with definitions of functions and various statements written in Python


is called a Python module.

o Python itself allows for the creation of modules.


o Similar to the re (regular expression) module, a module can be primarily
written in C programming language and then dynamically inserted at run-
time.

Page 52
BCA IIInd Year Subject – Python Programming

o A built-in module, such as the itertools module, is inherently included in the


interpreter.

A module is a file containing Python code, definitions of functions, statements, or


classes. An example_module.py file is a module we will create and whose name is
example_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

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))

Import Modules in Python


Page 54
BCA IIInd Year Subject – Python Programming

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)

Importing Module using “from”


In the above code module, math is imported, and its variables can be accessed by
considering it to be a class and pi as its object. The value of pi is returned
by __import__().

Example:
from math import pi
print(pi)

importing `*` in Python


In the above code module, math is not imported, rather just pi has been imported as
a variable.
All the functions and constants can be imported using *.

Example:
from math import *
print(pi)
print(factorial(6))

Inner Class in Python


A class defined in another class is known as an inner class or nested class. If an
object is created using child class means inner class then the object can also be
used by parent class or root class. A parent class can have one or more inner classes
but generally inner classes are avoided.

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)

# create Inner Lightgreen class


class Lightgreen:
def __init__(self):
self.name = 'Light Green'
self.code = '024avc'
def display(self):
print('Name:', self.name)
print('Code:', self.code)
# create Color class object
outer = Color()
# method calling
outer.show()
# create a Lightgreen
# inner class object
g = outer.lg
# inner class method calling
g.display()

What Is __Init__.Py File in Python?


The __init__.py file is a Python file that is executed when a package is
imported. __init__.py is a special file used in Python to define packages and
initialize their namespaces. It can contain an initialization code that runs when the
package is imported. Without this file, Python won't recognize a directory as a
package. It serves two main purposes:
• It marks the directory as a Python Package so that the interpreter can find the
modules inside it.
• It can contain initialization code for the Package, such as importing
submodules, defining variables, or executing other code.

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

try, except, else and finally Blocks


try Block
try block lets us test a block of code for errors. Python will “try” to execute the
code in this block. If an exception occurs, execution will immediately jump to the
except block.
except Block
except block enables us to handle the error or exception. If the code inside the try
block throws an error, Python jumps to the except block and executes it. We can
handle specific exceptions or use a general except to catch all exceptions.
else Block
else block is optional and if included, must follow all except blocks. The else block
runs only if no exceptions are raised in the try block. This is useful for code that
should execute if the try block succeeds.
finally Block
finally block always runs, regardless of whether an exception occurred or not. It is
typically used for cleanup operations (closing files, releasing resources).

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

# Import required module


from threading import *

# Extending Thread class


class Mythread(Thread):

# Target function for thread


def run(self):
for i in range(10):
print('Child Thread')

# Driver Code

# Creating thread class object


t = Mythread()

# Execution of target function


t.start()

# Executed by main thread


for i in range(10):
print('Main Thread')

Life cycle of Thread


A thread object goes through different stages during its life cycle. When a new
thread object is created, it must be started, which calls the run() method of thread
class. This method contains the logic of the process to be performed by the new
thread. The thread completes its task as the run() method is over, and the newly
created thread merges with the main thread.

States of a Thread Life Cycle in Python


Following are the stages of the Python Thread life cycle −

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

Starting a Thread − Once a thread object is created, it must be started by calling


its start() method. This initiates the thread's activity and invokes its run() method in
a separate thread.
Paused/Blocked State − Threads can be paused or blocked for various reasons,
such as waiting for I/O operations to complete or another thread to perform a task.
This is typically managed by calling its join() method. This blocks the calling
thread until the thread being joined terminates.
Synchronizing Threads − Synchronization ensures orderly execution and shared
resource management among threads. This can be done by using synchronization
primitives like locks, semaphores, or condition variables.
Termination − A thread terminates when its run() method completes execution,
either by finishing its task or encountering an exception.

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.

1. Import the threading module


Create a new thread by importing the threading module, as shown.
Syntax:
import threading
A threading module is made up of a Thread class, which is instantiated to create a
Python thread.

2. Declaration of the thread parameters: It contains the target function,


argument, and kwargs as the parameter in the Thread() class.
o Target: It defines the function name that is executed by the thread.
o Args: It defines the arguments that are passed to the target function name.

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")

4.Synchronizing Threads in Python


It is a thread synchronization mechanism that makes sure that no two threads can
run the same part of the program at the same time to access shared resources.
Critical sections could be used to describe the situation. To avoid the critical
section condition, in which two threads cannot simultaneously access resources,
we employ a race condition.

import time # import time module


import threading
from threading import *
def cal_sqre(num): # define a square calculating function
print(" Calculate the square root of the given number")
for n in num: # Use for loop
time.sleep(0.3) # at each iteration it waits for 0.3 time
print(' Square is : ', n * n)

def cal_cube(num): # define a cube calculating function


print(" Calculate the cube of the given number")
for n in num: # for loop
time.sleep(0.3) # at each iteration it waits for 0.3 time
print(" Cube is : ", n * n *n)

ar = [4, 5, 6, 7, 2] # given array

t = time.time() # get total time to execute the functions

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.

2. Cyclic Garbage Collector


Sometimes, objects reference each other in a cycle (e.g., a references b, and b
references a), which can cause their reference counts to never drop to zero. Python
uses a cyclic garbage collector to detect and break such reference cycles.
The gc module can be used to interact with Python's garbage collector:

Introduction of Numpy: NumPy is an open-source Python library that provides


support for large, multi-dimensional arrays and matrices. It also have a collection
of high-level mathematical functions to operate on arrays.

Features of NumPy
NumPy has various features which make them popular over lists.

Page 63
BCA IIInd Year Subject – Python Programming

• Provides powerful, multidimensional array objects (ndarrays).


• Supports advanced slicing and indexing techniques.
• Reduces the need for explicit loops with efficient array operations.
• Easily integrates with other libraries like pandas, matplotlib, and SciPy.
• Useful linear algebra, Fourier transform, and random number capabilities

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.

What is Python Pandas used for?


The Pandas library is generally used for data science, but have you wondered why?
This is because the Pandas library is used in conjunction with other libraries that
are used for data science. It is built on top of the NumPy library which means that
a lot of the structures of NumPy are used or replicated in Pandas.

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

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy