0% found this document useful (0 votes)
2 views169 pages

I BCA Python Final Class Notes With Practical Programs1

The document outlines a Python Programming course offered by Arignar Anna College, detailing the curriculum across five units covering basics, control statements, functions, data structures, and file handling. It highlights Python's features such as simplicity, dynamic typing, and portability, alongside installation and execution methods. Additionally, it addresses debugging techniques and common error types in Python programming.

Uploaded by

mindcreativity6
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)
2 views169 pages

I BCA Python Final Class Notes With Practical Programs1

The document outlines a Python Programming course offered by Arignar Anna College, detailing the curriculum across five units covering basics, control statements, functions, data structures, and file handling. It highlights Python's features such as simplicity, dynamic typing, and portability, alongside installation and execution methods. Additionally, it addresses debugging techniques and common error types in Python programming.

Uploaded by

mindcreativity6
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/ 169

ARIGNAR ANNA COLLEGE

(ARTS & SCIENCE)


KRISHNAGIRI

BACHELOR OF COMPUTER APPLICATIONS


PYTHON PROGRAMMING

M. Nareshkumar M.C.A.,M.Phil.,B.Ed.,
Asst.Professor
Department of B.C.A
PYTHON PROGRAMMING
UNIT - I
Basics of Python Programming: History of Python-Features of Python-Literal-
Constants-Variables - Identifiers–Keywords-Built-in Data Types-Output Statements – Input
Statements-Comments – Indentation- Operators-Expressions-Type conversions. Python
Arrays: Defining and Processing Arrays – Array methods

UNIT – II
Control Statements: Selection/Conditional Branching statements: if, if-else, nested if
and if-elif-else statements. Iterative Statements: while loop, for loop, else suite in loop and
nested loops. Jump Statements: break, continue and pass statements

UNIT -III
Functions: Function Definition – Function Call – Variable Scope and its Lifetime-
Return Statement. Function Arguments: Required Arguments, Keyword Arguments, Default
Arguments and Variable Length Arguments- Recursion. Python Strings: String operations-
Immutable Strings - Built-in String Methods and Functions - String Comparison. Modules:
import statement- The Python module – dir( ) function – Modules and Namespace – Defining
our own modules.

UNIT -IV
Lists: Creating a list -Access values in List-Updating values in Lists- Nested lists -
Basic list operations-List Methods. Tuples: Creating, Accessing, Updating and Deleting
Elements in a tuple – Nested tuples– Difference between lists and tuples. Dictionaries:
Creating, Accessing, Updating and Deleting Elements in a Dictionary – Dictionary Functions
and Methods - Difference between Lists and Dictionaries.

UNIT – V
Python File Handling: Types of files in Python - Opening and Closing files-Reading
and Writing files: write( ) and writelines( ) methods- append( ) method – read( ) and
readlines( ) methods – with keyword – Splitting words – File methods - File Positions-
Renaming and deleting files.
I BCA – PYTHON PROGRAMMING M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,

UNIT – I
Basics of Python Programming:
INTRODUCTION: THE PYTHONPROGRAMMING LANGUAGE
➢ Python is an object-oriented, high level language, interpreted, dynamic and
multipurpose programming language.
➢ Python is not intended to work on special area such as web programming. That is why
it is known as multipurpose because it can be used with web, enterprise, 3D CAD etc.
➢ We don’t need to use data types to declare variable because it is dynamically
typed so we can write a=10 to declare an integer value in a variable.
➢ Python makes the development and debugging fast because there is no compilation
step included in python development.

HISTORY
➢ Python was first introduced by Guido Van Rossum in 1991 at the National Research
Institute for Mathematics and Computer Science, Netherlands.
➢ Though the language was introduced in 1991, the development began in the 1980s.
Previouslyvan Rossum worked on the ABC language at CentrumWiskunde
&Informatica (CWI) inthe Netherlands.
➢ The ABC language was capable of exception handling and interfacing with the
Amoeba operating system. Inspired by the language, Van Rossum first tried out
making his own version of it.
➢ Python is influenced by programming languages like: ABC language, Modula-3,
Python is used for software development at companies and organizations such as
Google, Yahoo, CERN, Industrial Light and Magic, and NASA.
Why the Name Python?
➢ Python developer, Rossum always wanted the name of his new language to be short,
unique, and mysterious.
➢ Inspired by Monty Python’s Flying Circus, a BBC comedy series,he named it
Python.

FEATURES
There are various reasons why Python is gaining good popularity in the programming
community. The following are some of the important features of Python:
Simple:
➢ Python is a simple programming language. When we read a Python program, we
feel like reading English sentences. It means more clarity and less stress on
understanding the syntax of the language. Hence, developing and understanding
programs will become easy.

ARIGNAR ANNA COLLEGE (ARTS & SCIENCE )-KRISHNAGIRI 1


I BCA – PYTHON PROGRAMMING M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,

Easy to learn:
➢ Python uses very few keywords. Its programs use very simple structure. So,
developing programs in Python become easy. Also, Python resembles C language.
Most of the language constructs in C are also available in Python. Hence,
migrating from C to Python is easy for programmers.

Open source:
➢ There is no need to pay for Python software. Python can be freely downloaded from
www.python.org website. Its source code can be read, modified and can be used in
programs as desired by the programmers.

High level language:


➢ Programming languages are of two types: low level and high level. A low level
language uses machine code instructions to develop programs.
➢ These instructions directly interact with the CPU.
➢ Machine language and assembly language are called low level languages.
➢ High level languages use English words to develop programs.
➢ These are easy to learn and use. Like COBOL, PHP or Java, Python also uses
English words in its programs and hence it is called high level programming
language.

Dynamically typed:
➢ In Python, we need not declare anything. An assignment statement binds a
name to an object, and the object can be of any type.
➢ If a name is assigned to an object of one type, it may later be assigned to an object
of a different type.
➢ This is the meaning of the saying that Python is a dynamically typed language.
➢ Languages like C and Java are statically typed. In these languages, the variable
names and data types should be mentioned properly.
➢ Attempting to assign an object of the wrong type to a variable name triggers error
or exception.

Platform independent:
➢ When a Python program is compiled using a Python compiler, it generates byte
code.
➢ Python‟s byte code represents a fixed set of instructions that run on all operating
systems and hardware.
➢ Using a Python Virtual Machine (PVM), anybody can run these byte code
instructions on any computer system. Hence, Python programs are not dependent on
any specific operating system.
➢ We can use Python on almost all operating systems like UNIX, Linux,
Windows,Macintosh, Solaris, OS/2, Amiga, AROS, AS/400, etc. This makes Python
an ideal programming language for any network or Internet.

ARIGNAR ANNA COLLEGE (ARTS & SCIENCE )-KRISHNAGIRI 2


I BCA – PYTHON PROGRAMMING M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,

Portable:
➢ When a program yields the same result on any computer in the world, then it is
called a portable program.
➢ Python programs will give the same result since they are platform independent.
➢ Once a Python program is written, it can run on any computer system using PVM.
However, Python also contains some system dependent modules (or code), which
are specific to operating system.
➢ Programmers should be careful about such code while developing the software if
they want it to be completely portable.
➢ Suppose you are running Python on Windows and you need to shift the same to either a
Mac or a Linux system, then you can easily achieve the same in Python without
having to worry about changing the code.
➢ This is not possible in other programming languages, thus making Python one of the
most portable languages available in the industry.

Procedure and object oriented:


➢ Python is a procedure oriented as well as an object oriented programming language.
➢ In procedure oriented programming languages (e.g. C and Pascal), the programs are
built using functions and procedures.
➢ But in object oriented languages (e.g. C++ and Java), the programs use classes and
objects.
➢ One of the key aspects of Python is its object-oriented approach. This basically
means that Python recognizes the concept of class and object encapsulation thus
allowing programs to be efficient in the long run.
Easy to Code:
➢ Python is a very developer-friendly language which means that anyone and everyone
can learn to code it in a couple of hours ordays.
➢ As compared to other object-oriented programming languages like Java, C, C++, and
C#, Python is one of the easiest to learn.

Support for GUI:


➢ GUI or Graphical User Interface is one of the key aspects of any programming
language because it has the ability to add flair to code and make the results more
visual.
➢ Python has support for a wide array of GUIs which can easily be imported to the
interpreter, thus making this one of the most favorite languages for developers.

Large Standard Library:


➢ Out of the box, Python comes inbuilt with a large number of libraries that can
be imported at any instance and be used in a specific program.
➢ The presence of libraries also makes sure that you don’t need to write all the code
yourself and can import the same from those that already exist in the libraries.

ARIGNAR ANNA COLLEGE (ARTS & SCIENCE )-KRISHNAGIRI 3


I BCA – PYTHON PROGRAMMING M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,

INSTALLING PYTHON
➢ To install Python, firstly download the Python distribution from official website of
python (www.python.org/ download).
➢ Having downloaded the Python distribution now execute it.
Setting Path in Python:
Before starting working with Python, a specific path is to set to set path follow the steps:
Right click on My Computer--> Properties -->Advanced System setting -->Environment
Variable -->New
In Variable name write path and in Variable value copy path up to C:// Python (i.e., path
where Python is installed). Click Ok ->Ok.

RUNNING PYTHON PROGRAM:


There are different ways of working in Python:
How to Execute Python Program Using Command Prompt:
➢ If you want to create a Python file in .py extension and run. You can use the
Windows command prompt to execute the Python code.
Example:
➢ Here is the simple code of Python given in the Python file demo.py. It contains only
single line code of Python which prints the text “Hello World!” on execution.
➢ So, how you can execute the Python program using the command prompt. To see
this, you have to first open the command prompt using the ‘window+r’ keyboard
shortcut. Now, type the word ‘cmd’ to open the command prompt.
➢ This opens the command prompt with the screen as given below. Change the
directory location to the location where you have just saved your Python .py
extension file.
➢ We can use the cmd command ‘cd’ to change the directory location. Use ‘cd..’ to
come out of directory and “cd” to come inside of the directory. Get the file location
where you saved your Python file.

ARIGNAR ANNA COLLEGE (ARTS & SCIENCE )-KRISHNAGIRI 4


I BCA – PYTHON PROGRAMMING M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,

➢ To execute the Python file, you have to use the keyword ‘Python’ followed by the
file name with extension.py See the example given in the screen above with the output
of the file.
Interactive Mode to Execute Python Program:
➢ To execute the code directly in the interactive mode. You have to open the interactive
mode. Press the window button and type the text “Python”. Click the “Python 3.7(32
bit) Desktop app” as given below to open the interactive mode of Python.

➢ You can type the Python code directly in the Python interactive mode. Here, in the
image below contains the print program of Python.
➢ Press the enter button to execute the print code of Python. The output gives the text
“Hello World!” after you press the enter button.

Type any code of Python you want to execute and run directly on interactive mode.

ARIGNAR ANNA COLLEGE (ARTS & SCIENCE )-KRISHNAGIRI 5


I BCA – PYTHON PROGRAMMING M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,

Using IDLE (Python GUI) to Execute Python Program:


➢ Another useful method of executing the Python code. Use the Python IDLE GUI
Shell to execute the Python program on Windows system.
➢ Open the Python IDLE shell by pressing the window button of the keyboard. Type
“Python” and click the “IDLE (Python 3.7 32 bit)” to open the Python shell.

➢ Create a Python file with .py extension and open it with the Python shell. The file looks
like the image given below.

ARIGNAR ANNA COLLEGE (ARTS & SCIENCE )-KRISHNAGIRI 6


I BCA – PYTHON PROGRAMMING M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,

➢ It contains the simple Python code which prints the text “Hello World!”. In order to
execute the Python code, you have to open the ‘run’ menu and press the ‘Run Module’
option.

➢ A new shell window will open which contains the output of the Python code. Create
your own file and execute the Python code using this simple method using Python
IDLE.

DEBUGGING
➢ Debugging means the complete control over the program execution. Developers use
debugging to overcome program from any bad issues.
➢ debugging is a healthier process for the program and keeps thediseases bugs far away.
➢ Python also allows developers to debug the programs using pdb module that comes
with standard Python by default.
➢ We just need to import pdb module in the Python script. Using pdb module, we can set
breakpoints in the program to check the current status.
➢ We can Change the flow of execution by using jump, continue statements.

ARIGNAR ANNA COLLEGE (ARTS & SCIENCE )-KRISHNAGIRI 7


I BCA – PYTHON PROGRAMMING M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,

Syntax Error:
➢ Errors are the mistakes or faults performed by the user which results in abnormal
working of the program.
➢ However, we cannot detect programming errors before the compilation of programs.
The process of removing errors from a program is called Debugging.
➢ A syntax error occurs when we do not use properly defined syntax in any
programming language. For example: incorrect arguments, indentation, use of
undefined variables etc.

Example:
age=16
if age>18:
print ("you can vote”) # syntax error because of not using indentation
else
print ("you cannot vote”) #syntax error because of not using indentation

Runtime Errors:
➢ The second type of error is a runtime error, so called because the error does not
appear until after the program has started running.
➢ These errors are also called exceptions because they usually indicate that something
exceptional (and bad) has happened.
Some examples of Python runtime errors:
➢ division by zero
➢ performing an operation on incompatible types
➢ using an identifier which has not been defined
➢ accessing a list element, dictionary value or object attribute which doesn’t exist
➢ trying to access a file which doesn’t exist

Semantic Errors:
➢ The third type of error is the semantic error. If there is a semantic error in your
program, it will run successfully in the sense that the computer will not generate any
error messages, but it will not do the right thing. It will do something else.
➢ The problem is that the program you wrote is not the program you wanted to write. The
meaning of the program (its semantics) is wrong.
➢ Identifying semantic errors can be tricky because it requires you to work backward by
looking at the output of the program and trying to figure out what it is doing.
Experimental Debugging:
➢ One of the most important skills you will acquire is debugging. Although it can be
frustrating, debugging is one of the most intellectually rich, challenging, and
interesting parts of programming.
➢ Debugging is also like an experimental science. Once you have an idea about what is
going wrong, you modify your program and try again.

ARIGNAR ANNA COLLEGE (ARTS & SCIENCE )-KRISHNAGIRI 8


I BCA – PYTHON PROGRAMMING M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,

➢ For some people, programming and debugging are the same thing. That is,
programming is the process of gradually debugging a program until it does what you
want.
➢ The idea is that you should start with a program that does something and make small
modifications, debugging them as you go, so that you always have a working
program.

FORMAL AND NATURAL LANGUAGES


➢ Natural languages are the languages people speak, such as English, Spanish, and
French. They were not designed by people (although people try to impose some order
on them); they evolved naturally.
➢ Formal languages are languages that are designed by people forspecific applications.
➢ For example, the notation that mathematicians use is a formal language that is
particularly good at denoting relationships among numbers and symbols. Chemists use
a formal language to represent the chemical structure of molecules.
➢ Programming languages are formal languages that have been designed to express
computations.
➢ Formal languages tend to have strict rules about syntax. For example, 3 + 3 = 6 is a
syntactically correct mathematical statement.
➢ Syntax rules come in two flavors, pertaining to tokens and structure. Tokens are the
basic elements of the language, such as words, numbers, and chemical elements.
➢ The second type of syntax rule pertains to the structure of a statement; that is, the way
the tokens are arranged. The statement 3+ = 3 is illegal because even though + and =
are legal tokens, you can’t have one right after the other.

THE DIFFERENCE BETWEEN BRACKETS,BRACES, AND PARENTHESES:


Brackets [ ]:
Brackets are used to define mutable data types such as list or list comprehensions.
Example:
To define a list with name as L1 with three elements 10,20 and 30
>>> L1 = [10,20,30]
>>> L1 [10,20,30]
➢ Brackets can be used for indexing and lookup of elements Example:
>>>L1[1] = 40
>>>L1 [10,40,30]

Example: To lookup the element of list L1


>>> L1[0]10
➢ Brackets can be used to access the individual characters of a string or to make string
slicing

ARIGNAR ANNA COLLEGE (ARTS & SCIENCE )-KRISHNAGIRI 9


I BCA – PYTHON PROGRAMMING M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,

Example:
Lookup the first characters of string
str>>>’mumbai’
>>> str [0]
‘m’
Example: To slice a string
>>> str [1:4]
‘umb’
Braces {}
➢ Curly braces are used in python to define set or dictionary.

Example:
Create a set with three elements 10,20,30.
>>> s1 = {10,20,30}
>>> type(s1)
<class ‘set’>
Example:
Create a dictionary with two elements with keys, ‘rollno’ and ‘name’
>>> d1= {‘rollno’:101, ‘name’:’ Vivek’}
>>> type(d1)
<class ‘dict’>

➢ Brackets can be used to access the value of dictionary element by specifying the key.
>>> d1[‘rollno’]
101

Parentheses ( )
➢ Parentheses can be used to create immutable sequence data type tuple.
Example: Create a tuple named ‘t1’ with elements 10,20,30
>>> t1= (10,20,30)
>>> type(t1)
<class ‘tuple’>
➢ Parentheses can be used to define the parameters of function definition and function
call.
Example:
Multiply two numbers using a function def mul(a,b):
#returns a*b
x=2y=3
z=mul (2,3)
print(x,’*’,y,’=’z)
➢ In the function definition def mul(a,b) formal parameters arespecified using
parentheses
➢ In the function call z=mul (2,3) actual values are specified using parenthesis.

ARIGNAR ANNA COLLEGE (ARTS & SCIENCE )-KRISHNAGIRI 10


I BCA – PYTHON PROGRAMMING M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,

Python Literals:
➢ literals are a notation for representing a fixed value in source code.
➢ They can also be defined as raw values or data given in variables or constants.
➢ Python has different types of literal such as:
1. String literals
2. Character literal
3. Numeric literals
4. Boolean literals
5. Literal Collections
6. Special literals
Python String literals
➢ A string is literal and can be created by writing a text(a group of Characters )
surrounded by a single(”), double(“), or triple quotes.
➢ By using triple quotes we can write multi-line strings or display them in the desired
way.
# in single quote
s = 'Welcome To BCA'

# in double quotes
t = "Welcome To BCA"

# multi-line String
m = '''Welcome
To
BCA'''
print(s)
print(t)
print(m)
Output
Welcome To BCA
Welcome To BCA
Welcome
To
BCA

Python Character literal


➢ It is also a type of string literal where a single character is surrounded by single or double
quotes.
# character literal in single quote
v = 'n'

# character literal in double quotes


w = "a"
print(v)
print(w)
Output :
n
a

ARIGNAR ANNA COLLEGE (ARTS & SCIENCE )-KRISHNAGIRI 11


I BCA – PYTHON PROGRAMMING M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,

Python Numeric literal


➢ They are immutable and there are three types of numeric literal:
• Integer
• Float
• Complex

Integer
➢ Both positive and negative numbers including 0.
➢ There should not be any fractional part.
➢ In this example, We assigned integer literals (0b10100, 50, 0o320, 0x12b) into different
variables. Here, ‘a‘ is a binary literal, ‘b’ is a decimal literal, ‘c‘ is an octal literal, and ‘d‘
is a hexadecimal literal.
➢ But on using the print function to display a value or to get the output they were converted
into decimal.
# integer literal

# Binary Literals
a = 0b10100

# Decimal Literal
b = 50

# Octal Literal
c = 0o320

# Hexadecimal Literal
d = 0x12b
print(a, b, c, d)
Output :
20 50 208 299
Float
➢ These are real numbers having both integer and fractional parts. In this example, 24.8 and
45.0 are floating-point literals because both 24.8 and 45.0 are floating-point numbers.

# Float Literal
e = 24.8
f = 45.0
print(e, f)
Output :
24.8 45.0

Complex
➢ The numerals will be in the form of a + bj, where ‘a’ is the real part and ‘b‘ is the
complex part.
Example: Numeric literal [ Complex ]
Python3
z = 7 + 5j

ARIGNAR ANNA COLLEGE (ARTS & SCIENCE )-KRISHNAGIRI 12


I BCA – PYTHON PROGRAMMING M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,

# real part is 0 here.


k = 7j
print(z, k)
Output :
(7+5j) 7j
Python Boolean literal
➢ There are only two Boolean literals in Python.
➢ They are true and false.
➢ In Python, True represents the value as 1, and False represents the value as 0.
➢ In this example ‘a‘ is True and ‘b‘ is False because 1 is equal to True.
a = (1 == True)
b = (1 == False)
c = True + 3
d = False + 7
print("a is", a)
print("b is", b)
print("c:", c)
print("d:", d)
Output :
a is True
b is False
c: 4
d: 7
Python literal collections
➢ Python provides four different types of literal collections:
1. List literals
2. Tuple literals
3. Dict literals
4. Set literals
List literal
➢ The list contains items of different data types.
➢ The values stored in the List are separated by a comma (,) and enclosed within square
brackets([]). We can store different types of data in a List.
➢ Lists are mutable.
number = [1, 2, 3, 4, 5]
name = ['Amit', 'kabir', 'bhaskar', 2]
print(number)
print(name)
Output :
[1, 2, 3, 4, 5]
['Amit', 'kabir', 'bhaskar', 2]
Tuple literal
➢ A tuple is a collection of different data-type. It is enclosed by the parentheses ‘()‘ and
each element is separated by the comma(,).
➢ It is immutable.
even_number = (2, 4, 6, 8)
odd_number = (1, 3, 5, 7)
print(even_number)

ARIGNAR ANNA COLLEGE (ARTS & SCIENCE )-KRISHNAGIRI 13


I BCA – PYTHON PROGRAMMING M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,

print(odd_number)
Output :
(2, 4, 6, 8)
(1, 3, 5, 7)

Dictionary literal
➢ The dictionary stores the data in the key-value pair.
➢ It is enclosed by curly braces ‘{}‘ and each pair is separated by the commas(,).
➢ We can store different types of data in a dictionary. Dictionaries are mutable.
alphabets = {'a': 'apple', 'b': 'ball', 'c': 'cat'}
information = {'name': 'amit', 'age': 20, 'ID': 20}
print(alphabets)
print(information)
Output :
{'a': 'apple', 'b': 'ball', 'c': 'cat'}
{'name': 'amit', 'age': 20, 'ID': 20}

Set literal
➢ Set is the collection of the unordered data set.
➢ It is enclosed by the {} and each element is separated by the comma(,).
vowels = {'a', 'e', 'i', 'o', 'u'}
fruits = {"apple", "banana", "cherry"}
print(vowels)
print(fruits)
Output :
{'o', 'e', 'a', 'u', 'i'}
{'apple', 'banana', 'cherry'}
Python Special literal
➢ Python contains one special literal (None).
➢ ‘None’ is used to define a null variable.
➢ If ‘None’ is compared with anything else other than a ‘None’, it will return false.
water_remain = None
print(water_remain)
Output :
None

Constants:
What are Constants?
➢ Generally, a constant term is used in Mathematics, a value or quantity that never changes.
➢ In programming, a constant refers to the name associated with a value that never changes
during the programming execution.
➢ Programming constant is different from other constants, and it consists of two things - a
name and an associated value.
➢ The name will describe what the constant is all about, and the value is the concrete
expression of the constant itself.
➢ Once we define the constant, we can only access its value but cannot change it over time.
However, we can modify the value of the variable.
➢ A real-life example is - The speed of light, the number of minutes in an hour, and the
name of a project's root folder.

ARIGNAR ANNA COLLEGE (ARTS & SCIENCE )-KRISHNAGIRI 14


I BCA – PYTHON PROGRAMMING M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,

Why Use Constant?


➢ In programming languages, Constants allow us to protect from accidentally changing
their value which can cause hard-to-debug errors. It is also helpful to make code more
readable and maintainable. Let's see some advantages of constant.
o Improved Readability - It helps to improve the readability of the code. For example, it is
easier to read and understand a constant named MAX_SPEED than the substantial speed
value itself.
o Clear communication of intent - Most developers consider the 3.14 as the pi constant.
However, the Pi, pi, or PI name will communicate intent more clearly. This practice will
allow another developer to understand our code.
o Better Maintainability - Constants allow us to use the same value throughout your code.
Suppose we want to update the constant's value; we don't need to change every instance.
o Low risk of errors - A constant representing a given value throughout a program is less
error-prone. If we want to change the precision in the calculations, replacing the value
can be risky. Instead of replacing it, we can create different constants for different
precision levels and change the code where we needed.
o Thread-safe data storage - A constants are thread-safe objects, meaning several threads
can simultaneously use a constant without risking losing data.
User-Defined Constants
➢ We need to use the naming convention in Python to define the constant in Python.
➢ We should write the name in capital letters with underscores separating words.
Following are the example of the user-defined Python constants -
PI = 3.14
MAX_SPEED = 300
DEFAULT_COLOR = "\033[1;34m"
WIDTH = 20
API_TOKEN = "567496396372"
BASE_URL = "https://api.example.com"
DEFAULT_TIMEOUT = 5
BUILTINS_METHODS = ("sum", "max", "min", "abs")
INSTALLED_APPS = [
"django.contrib.admin",
"django.contrib.auth",
"django.contrib.contenttypes",
...
]
➢ We have used the same way as we create variables in Python.
➢ So we can assume that Python constants are just variables, and the only distinction is that
the constant uses uppercase letters only.

ARIGNAR ANNA COLLEGE (ARTS & SCIENCE )-KRISHNAGIRI 15


I BCA – PYTHON PROGRAMMING M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,

➢ Using uppercase letters makes the constant stand out from our variables and is a useful or
preferred practice.
➢ Above we discussed the user-defined users; Python also provides several internal names
that can consider and should treat as constants.
Important Constants in Python
Built-in Constants
➢ In the official documentation, the True and False are listed as the first constant.
➢ These are Python Boolean values and are the instance of the int.

A True has a value of 1, and False has a value 0.


Example -
>>> True
True
>>> False
False

>>> isinstance(True, int)


True
>>> isinstance(False, int)
True

>>> int(True)
1
>>> int(False)
0

>>> True = 42
...
SyntaxError: cannot assign to True

>>> True is True


True
>>> False is False
True
Internal Dunder Names
➢ Python also has many internal dunder names that we can consider constants.
➢ There are several of these unique names, we will learn about __name__ and __file__ in
this section.
➢ The __name__ attribute is related to how to run a given piece of code.
➢ When importing a module, Python internal set the __name__ to a string containing the
name of the module.
new_file.py
1. print(f"The type of __name__ is: {type(__name__)}")
2. print(f"The value of __name__ is: {__name__}")
In the command-line and type the following command -
1. python -c "import new_file"

ARIGNAR ANNA COLLEGE (ARTS & SCIENCE )-KRISHNAGIRI 16


I BCA – PYTHON PROGRAMMING M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,

The -c is used to execute a small piece of code of Python at the command line. In the
above example, we imported the new_file module, which displays some messages on
the screen.
Output -
The type of __name__ is: <class 'str'>
The value of __name__ is: timezone
➢ As we can see that the __name__ stores the __main__ string, indicates that we
can run the executable files directly as Python program.
➢ On the other hand, the __file__ attribute has the file that Python is currently
importing or executing.
➢ If we use the __file__ attribute inside the file, we will get the path to the
module itself.
Let's see the following example -
Example -
1. print(f"The type of __file__ is: {type(__file__)}")
2. print(f"The value of __file__ is: {__file__}")
Output:
The type of __file__ is: <class 'str'>
The value of __file__ is: D:\Python Project\new_file.py
We can also run directly and will get the same result.
Example -
1. print(f"The type of __file__ is: {type(__file__)}")
2. print(f"The value of __file__ is: {__file__}")
Output:
python new_file.py
The type of __file__ is: <class 'str'>
The value of __file__ is: timezone.py
Useful String and Math Constants
➢ There are many valuable constants in the standard library. Some are strictly connected to
specific modules, functions, and classes; many are generic, and we can use them in
several scenarios.
➢ In the below example, we will use the math and string-related modules math and string,
respectively.
➢ Let's understand the following example -
Example -
>>> import math
>>> math.pi
3.141592653589793
>>> math.tau
6.283185307179586
>>> math.nan
nan
>>> math.inf
inf
>>> math.sin(30)
-0.9880316240928618
>>> math.cos(60)

ARIGNAR ANNA COLLEGE (ARTS & SCIENCE )-KRISHNAGIRI 17


I BCA – PYTHON PROGRAMMING M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,

-0.9524129804151563
>>> math.pi
3.141592653589793
➢ These constants will play a vital role when we write math-related code or perform some
specific computations.
Let's understand the following example -
Example -
import math

class Sphere:
def __init__(self, radius):
self.radius = radius

def area(self):
return math.pi * self.radius**2

def perimeter(self):
return 2 * math.pi * self.radius

def projected_volume(self):
return 4/3 * math.pi * self.radius**3

def __repr__(self):
return f"{self.__class__.__name__}(radius={self.radius})"
➢ In the above code, we have used the math.pi instead of custom PI constants.
➢ The math-related constant provides the more contexts to the program.
➢ The advantage of using math.pi constant is that if we are using an older version of
Python, we will get a 32-bit version of Pi.
➢ If we use the above program in modern version of Python, we will get a 64-bit version of
pi. So our program will self-adapt of its concrete execution environment.
➢ The string module also provides some useful built-in string constants. Below is the table
of the name and value of each constant.
Name Value

ascii_lowercase Abcdefghijklmnopqrstuvwxyz

ascii_uppercase ABCDEFGHIJKLMNOPQRSTUVWXYZ

ascii_letters ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz

digits 0123456789

hexdigits 0123456789abcdefABCDEF

octdigits 01234567
➢ We can use these string-related constants in regular expressions, processing natural
language, with the lot of string processing, and more.

ARIGNAR ANNA COLLEGE (ARTS & SCIENCE )-KRISHNAGIRI 18


I BCA – PYTHON PROGRAMMING M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,

Type-Annotating Constants
➢ The typing module includes a Final class that allows us to type-annotate constants.
➢ If we use the Final class to define the constants in the program, we will get the static type
error that the mypy checker checks and it will show that we cannot reassign to the Final
name. Let's understand the following example.

Example -
from typing import Final
MAX_Marks: Final[int] = 300
MAX_Students: Final[int] = 500
MAX_Marks = 450 # Cannot assign to final name "MAX_SPEED" mypy(error)

String Constants
➢ As discussed in the earlier section, Python doesn't support strict constants; it just has
variables that never change. Therefore, the Python community follows the naming
convention of using the uppercase letter to identify the constant variables.
➢ It can be an issue if we work on a large Python project with many programmers at
different levels. So it would be good practice to have a mechanism that allows us to use
strict constants. As we know, Python is a dynamic language, and there are several ways to
make constants unchangeable. In this section, we will learn about some of these ways.
o The .__slots__ Attributes
➢ Python classes provide the facility to use the __slots__ attributes. The slot has the special
mechanism to reduce the size of the objects. It is a concept of memory optimization on
objects. If we use the __slots__ attribute in the class, we won't be able to add the new
instance, because it doesn't use __dict__ attributes. Additionally, not having
a .__dict__ attribute implies an optimization in terms of memory consumption. Let's
understand the following example.
Example - Without using __slots__ attributes
class NewClass(object):
def __init__(self, *args, **kwargs):
self.a = 1
self.b = 2
if __name__ == "__main__":
instance = NewClass()
print(instance.__dict__)
Output -
{'a': 1, 'b': 2}
➢ Every object in Python contains a dynamic dictionary that allows adding attributes.
Dictionaries consume lots of memory, and using __slots__ reduces the wastage of space
and memory. Let's see another example.
Example -
class ConstantsName:
__slots__ = ()

ARIGNAR ANNA COLLEGE (ARTS & SCIENCE )-KRISHNAGIRI 19


I BCA – PYTHON PROGRAMMING M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,

PI = 3.141592653589793
EULER_NUMBER = 2.718281828459045
constant = ConstantsName()
print(constant.PI)
print(constant.EULER_NUMBER)
constant.PI = 3.14
print(constant.PI)
Output -

3.141592653589793
2.718281828459045

Python Keywords and Identifiers:


Python Keywords
➢ Keywords are predefined, reserved words used in Python programming that have special
meanings to the compiler.
➢ We cannot use a keyword as a variable name, function name, or any other identifier.
➢ They are used to define the syntax and structure of the Python language.
➢ All the keywords except True, False and None are in lowercase and they must be written
as they are. The list of all the keywords is given below.
Python Keywords List

False await else import pass


None break except in raise
True class finally is return
and continue for lambda try
as def from nonlocal while
assert del global not with
async elif if or yield
➢ Looking at all the keywords at once and trying to figure out what they mean might be
overwhelming.
➢ If you want to have an overview, here is the complete list of all the keywords with
examples.
➢ Identifiers are the name given to variables, classes, methods, etc. For example,
language = ‘Python’
➢ Here, language is a variable (an identifier) which holds the value 'Python'.
➢ We cannot use keywords as variable names as they are reserved names that are built-in to
Python. For example,
continue =’Python’
➢ The above code is wrong because we have used continue as a variable name.

Rules for Naming an Identifier


➢ Identifiers cannot be a keyword.
➢ Identifiers are case-sensitive.

ARIGNAR ANNA COLLEGE (ARTS & SCIENCE )-KRISHNAGIRI 20


I BCA – PYTHON PROGRAMMING M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,

➢ It can have a sequence of letters and digits. However, it must begin with a letter
or _. The first letter of an identifier cannot be a digit.
➢ It's a convention to start an identifier with a letter rather _.
➢ Whitespaces are not allowed.
➢ We cannot use special symbols like !, @, #, $, and so on.

Some Valid and Invalid Identifiers in Python


Valid Identifiers Invalid Identifiers
score @core
return_value return
highest_score highest score
name1 1name
convert_to_string convert to_string
Things to Remember
➢ Python is a case-sensitive language. This means, Variable and variable are not the
same.
➢ Always give the identifiers a name that makes sense. While c = 10 is a valid name,
writing count = 10 would make more sense, and it would be easier to figure out what it
represents when you look at your code after a long gap.
➢ Multiple words can be separated using an underscore, like this_is_a_long_variable.

Escape sequence characters:


\\ Backslash \’ Single quote \” Double quote \a ASCII Bell
\b Backspace \f ASCII Formfeed \n New line charater \t Horizontal tab

Python Variables:
➢ In programming, a variable is a container (storage area) to hold data. For example,
number =10
➢ Here, number is the variable storing the value 10.
Assigning values to Variables in Python
➢ As we can see from the above example, we use the assignment operator = to assign a value
to a variable.
# assign values to site name variable
site_name = ‘program’
print(site_name)
➢ In the above example, we assigned the value 'programiz.pro' to the site_name variable.
➢ Then, we printed out the value assigned to site_name.

Note: Python is a type-inferred language, so you don't have to explicitly define the variable type.
It automatically knows that programiz.pro is a string and declares the site_name variable as a
string.

Changing the Value of a Variable in Python


# assign values to site name variable
site_name = ‘program’
print(site_name)

ARIGNAR ANNA COLLEGE (ARTS & SCIENCE )-KRISHNAGIRI 21


I BCA – PYTHON PROGRAMMING M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,

# assign new values to site name variable


site_name = ‘apple’
print(site_name)

Output:
program
apple
➢ Here, the value of site_name is changed from 'program' to 'apple'.
Example: Assigning multiple values to multiple variables
a,b,c = 5,3.2, Hello’
print(a) #prints 5
print(b) #prints 3.2
print(c) #prints Hello
➢ If we want to assign the same value to multiple variables at once, we can do this as:
s1 =s2 = ‘programiz.com’
print(s1) #prints programiz.com
print(s2) #prints programiz.com
➢ Here, we have assigned the same string value 'programiz.com' to both the
variables s1 and s2.

Rules for Naming Python Variables


➢ Constant and variable names should have a combination of letters in lowercase
(a to z) or uppercase (A to Z) or digits (0 to 9) or an underscore (_). For example:
Snake_case , MACRO_CASE , camelCase , CapWords
➢ Create a name that makes sense. For example, vowel makes more sense than v.
➢ If you want to create a variable name having two words, use underscore to
separate them. For example:
my_name , current_salary
➢ Python is case-sensitive. So num and Num are different variables. For example,
var num = 5
var Num=55
print(num)
print(Num)
➢ Avoid using keywords like if, True, class, etc. as variable names.
Python Data Types:
➢ Python Data Types are used to define the type of a variable.
➢ It defines what type of data we are going to store in a variable.
➢ The data stored in memory can be of many types.
➢ For example, a person's age is stored as a numeric value and his or her address is stored
as alphanumeric characters.

Python has various built-in data types.


• Numeric - int, float, complex
• String - str
• Sequence - list, tuple, range
• Binary - bytes, bytearray, memoryview
• Mapping - dict
• Boolean - bool

ARIGNAR ANNA COLLEGE (ARTS & SCIENCE )-KRISHNAGIRI 22


I BCA – PYTHON PROGRAMMING M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,

• Set - set, frozenset


• None - NoneType

Python Numeric Data Type


➢ Python numeric data types store numeric values. Number objects are created when you
assign a value to them. For example −
var1 = 1
var2 = 10
var3 = 10.023
➢ Python supports four different numerical types −
• int (signed integers)
• long (long integers, they can also be represented in octal and hexadecimal)
• float (floating point real values)
• complex (complex numbers)
Examples
Here are some examples of numbers −
int long float complex
10 51924361L 0.0 3.14j
100 -0x19323L 15.20 45.j
-786 0122L -21.9 9.322e-36j
080 0xDEFABCECBDAECBFBAEl 32.3+e18 .876j
-0490 535633629843L -90. -.6545+0J
-0x260 -052318172735L -32.54e100 3e+26J
0x69 -4721885298529L 70.2-E12 4.53e-7j
➢ Python allows you to use a lowercase l with long, but it is recommended that you use
only an uppercase L to avoid confusion with the number 1.
➢ Python displays long integers with an uppercase L.
➢ A complex number consists of an ordered pair of real floating-point numbers denoted by
x + yj, where x and y are the real numbers and j is the imaginary unit.
Example : Following is an example to show the usage of Integer, Float and Complex
numbers:
# integer variable.
a=100
print("The type of variable having value", a, " is ", type(a))

# float variable.
b=20.345
print("The type of variable having value", b, " is ", type(b))

# complex variable.
c=10+3j
print("The type of variable having value", c, " is ", type(c))

Python String Data Type


➢ Python Strings are identified as a contiguous set of characters represented in the quotation
marks.
➢ Python allows for either pairs of single or double quotes.
➢ Subsets of strings can be taken using the slice operator ([ ] and [:] ) with indexes starting
at 0 in the beginning of the string and working their way from -1 at the end.

ARIGNAR ANNA COLLEGE (ARTS & SCIENCE )-KRISHNAGIRI 23


I BCA – PYTHON PROGRAMMING M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,

➢ The plus (+) sign is the string concatenation operator and the asterisk (*) is the repetition
operator in Python.
➢ For example −
str = 'Hello World!'
print (str) # Prints complete string
print (str[0]) # Prints first character of the string
print (str[2:5]) # Prints characters starting from 3rd to 5th
print (str[2:]) # Prints string starting from 3rd character
print (str * 2) # Prints string two times
print (str + "TEST") # Prints concatenated string
This will produce the following result −
Hello World!
H
llo
llo World!
Hello World!Hello World!
Hello World!TEST

Python List Data Type


➢ Python Lists are the most versatile compound data types.
➢ A Python list contains items separated by commas and enclosed within square brackets
([]).
➢ To some extent, Python lists are similar to arrays in C.
➢ One difference between them is that all the items belonging to a Python list can be of
different data type where as C array can store elements related to a particular data type.
➢ The values stored in a Python list can be accessed using the slice operator ([ ] and [:])
with indexes starting at 0 in the beginning of the list and working their way to end -1.
➢ The plus (+) sign is the list concatenation operator, and the asterisk (*) is the repetition
operator.
For example −
list = [ 'abcd', 786 , 2.23, 'john', 70.2 ]
tinylist = [123, 'john']
print (list) # Prints complete list
print (list[0]) # Prints first element of the list
print (list[1:3]) # Prints elements starting from 2nd till 3rd
print (list[2:]) # Prints elements starting from 3rd element
print (tinylist * 2) # Prints list two times
print (list + tinylist) # Prints concatenated lists
This produce the following result −
['abcd', 786, 2.23, 'john', 70.2]
abcd
[786, 2.23]
[2.23, 'john', 70.2]
[123, 'john', 123, 'john']
['abcd', 786, 2.23, 'john', 70.2, 123, 'john']
Python Tuple Data Type
➢ Python tuple is another sequence data type that is similar to a list.
➢ A Python tuple consists of a number of values separated by commas.
➢ Unlike lists, however, tuples are enclosed within parentheses.

ARIGNAR ANNA COLLEGE (ARTS & SCIENCE )-KRISHNAGIRI 24


I BCA – PYTHON PROGRAMMING M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,

➢ The main differences between lists and tuples are: Lists are enclosed in brackets ( [ ] ) and
their elements and size can be changed, while tuples are enclosed in parentheses ( ( ) )
and cannot be updated.
➢ Tuples can be thought of as read-only lists. For example −
tuple = ( 'abcd', 786 , 2.23, 'john', 70.2 )
tinytuple = (123, 'john')
print (tuple) # Prints the complete tuple
print (tuple[0]) # Prints first element of the tuple
print (tuple[1:3]) # Prints elements of the tuple starting from 2nd till 3rd
print (tuple[2:]) # Prints elements of the tuple starting from 3rd element
print (tinytuple * 2) # Prints the contents of the tuple twice
print (tuple + tinytuple) # Prints concatenated tuples
This produce the following result −
('abcd', 786, 2.23, 'john', 70.2)
abcd
(786, 2.23)
(2.23, 'john', 70.2)
(123, 'john', 123, 'john')
('abcd', 786, 2.23, 'john', 70.2, 123, 'john')
➢ The following code is invalid with tuple, because we attempted to update a tuple, which is
not allowed. Similar case is possible with lists −
tuple = ( 'abcd', 786 , 2.23, 'john', 70.2 )
list = [ 'abcd', 786 , 2.23, 'john', 70.2 ]
tuple[2] = 1000 # Invalid syntax with tuple
list[2] = 1000 # Valid syntax with list
Python Ranges
➢ Python range() is an in-built function in Python which returns a sequence of numbers
starting from 0 and increments to 1 until it reaches a specified number.
➢ We use range() function with for and while loop to generate a sequence of numbers.
Following is the syntax of the function:
range(start, stop, step)
Here is the description of the parameters used:
• start: Integer number to specify starting position, (Its optional, Default: 0)
• stop: Integer number to specify starting position (It's mandatory)
• step: Integer number to specify increment, (Its optional, Default: 1)
Examples
Following is a program which uses for loop to print number from 0 to 4 −
for i in range(5):
print(i)
This produce the following result −
0
1
2
3
4
Now let's modify above program to print the number starting from 1 instead of 0:
for i in range(1, 5):
print(i)

ARIGNAR ANNA COLLEGE (ARTS & SCIENCE )-KRISHNAGIRI 25


I BCA – PYTHON PROGRAMMING M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,

This produce the following result −


1
2
3
4
Again, let's modify the program to print the number starting from 1 but with an increment
of 2 instead of 1:
for i in range(1, 5, 2):
print(i)
This produce the following result −
1
3
Python Dictionary
➢ Python dictionaries are kind of hash table type.
➢ They work like associative arrays or hashes found in Perl and consist of key-value pairs.
➢ A dictionary key can be almost any Python type, but are usually numbers or strings.
Values, on the other hand, can be any arbitrary Python object.
➢ Dictionaries are enclosed by curly braces ({ }) and values can be assigned and accessed
using square braces ([]). For example −
dict = {}
dict['one'] = "This is one"
dict[2] = "This is two"
tinydict = {'name': 'john','code':6734, 'dept': 'sales'}
print (dict['one']) # Prints value for 'one' key
print (dict[2]) # Prints value for 2 key
print (tinydict) # Prints complete dictionary
print (tinydict.keys()) # Prints all the keys
print (tinydict.values()) # Prints all the values
This produce the following result −
This is one
This is two
{'dept': 'sales', 'code': 6734, 'name': 'john'}
['dept', 'code', 'name']
['sales', 6734, 'john']
➢ Python dictionaries have no concept of order among elements.
➢ It is incorrect to say that the elements are "out of order"; they are simply unordered.
Python Boolean Data Types
➢ Python boolean type is one of built-in data types which represents one of the two values
either True or False.
➢ Python bool() function allows you to evaluate the value of any expression and returns
either True or False based on the expression.
Examples
o Following is a program which prints the value of boolean variables a and b −
a = True
# display the value of a
print(a)

# display the data type of a


print(type(a))

ARIGNAR ANNA COLLEGE (ARTS & SCIENCE )-KRISHNAGIRI 26


I BCA – PYTHON PROGRAMMING M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,

This produce the following result −


true
<class 'bool'>
o Following is another program which evaluates the expressions and prints the
return values:
# Returns false as a is not equal to b
a=2
b=4
print(bool(a==b))

# Following also prints the same


print(a==b)

# Returns False as a is None


a = None
print(bool(a))

# Returns false as a is an empty sequence


a = ()
print(bool(a))

# Returns false as a is 0
a = 0.0
print(bool(a))

# Returns false as a is 10
a = 10
print(bool(a))
This produce the following result −
False
False
False
False
False
True

INPUT STATEMENTS:
How to Take Input from User in Python
➢ Sometimes a developer might want to take user input at some point in the
program. To do this Python provides an input() function.
Syntax:
input('prompt')
➢ where prompt is an optional string that is displayed on the string at the time of taking
input.

Example 1: Python get user input with a message


# Taking input from the user
name = input("Enter your name: ")

ARIGNAR ANNA COLLEGE (ARTS & SCIENCE )-KRISHNAGIRI 27


I BCA – PYTHON PROGRAMMING M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,

# Output
print("Hello, " + name)
print(type(name))
Output:
Enter your name: GFG
Hello, GFG
<class 'str'>
Note: Python takes all the input as a string input by default. To convert it to any other data type
we have to convert the input explicitly. For example, to convert the input to int or float we
have to use the int() and float() method respectively.

Example 2: Integer input in Python


# Taking input from the user as integer
num = int(input("Enter a number: "))
add = num + 1

# Output
print(add)

Output:
Enter a number: 25
26
How to take Multiple Inputs in Python :
➢ we can take multiple inputs of the same data type at a time in python, using map()
method in python.
a, b, c = map(int, input("Enter the Numbers : ").split())
print("The Numbers are : ",end = " ")
print(a, b, c)
Output :
Enter the Numbers : 2 3 4
The Numbers are : 2 3 4

How take inputs for the Sequence Data Types like List, Set, Tuple, etc.
In the case of List and Set the input can be taken from the user in two ways.
1. Taking List/Set elements one by one by using the append()/add() methods.
2. Using map() and list() / set() methods.

Taking List/Set elements one by one


➢ Take the elements of the List/Set one by one and use the append() method in the case of
List, and add() method in the case of a Set, to add the elements to the List / Set.
List = list()
Set = set()
l = int(input("Enter the size of the List : "))
s = int(input("Enter the size of the Set : "))
print("Enter the List elements : ")
for i in range(0, l):
List.append(int(input()))
print("Enter the Set elements : ")
for i in range(0, s):

ARIGNAR ANNA COLLEGE (ARTS & SCIENCE )-KRISHNAGIRI 28


I BCA – PYTHON PROGRAMMING M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,

Set.add(int(input()))
print(List)
print(Set)

Output :
Enter the size of the List : 4
Enter the size of the Set : 3
Enter the List elements :
9
0
1
3
Enter the Set elements :
2
9
1
[9, 0, 1, 3]
{9, 2, 1}
Using map() and list() / set() Methods
List = list(map(int, input("Enter List elements : ").split()))
Set = set(map(int, input("Enter the Set elements :").split()))
print(List)
print(Set)
Output :
Enter List elements : 3 4 8 9 0 11
Enter the Set elements :34 88 230 234 123
[3, 4, 8, 9, 0, 11]
{34, 230, 234, 88, 123}

Taking Input for Tuple


➢ We know that tuples are immutable, there are no methods available to add elements to
tuples.
➢ To add a new element to a tuple, first type cast the tuple to the list, later append the
element to the list, and again type cast list back to a tuple.
T = (2, 3, 4, 5, 6)
print("Tuple before adding new element")
print(T)
L = list(T)
L.append(int(input("Enter the new element : ")))
T = tuple(L)
print("Tuple After adding the new element")
print(T)
Output :
Tuple before adding new element
(2, 3, 4, 5, 6)
Enter the new element : 35
Tuple After adding the new element
(2, 3, 4, 5, 6, 35)

ARIGNAR ANNA COLLEGE (ARTS & SCIENCE )-KRISHNAGIRI 29


I BCA – PYTHON PROGRAMMING M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,

OUTPUT STATEMENTS
How to Display Output in Python
➢ Python provides the print() function to display output to the standard output
devices.
Syntax: print(value(s), sep= ‘ ‘, end = ‘\n’, file=file, flush=flush)
Parameters:
value(s) : Any value, and as many as you like. Will be converted to string before printed
sep=’separator’ : (Optional) Specify how to separate the objects, if there is more than one.
Default :’ ‘
end=’end’: (Optional) Specify what to print at the end.Default : ‘\n’
file : (Optional) An object with a write method. Default :sys.stdout
flush : (Optional) A Boolean, specifying if the output is flushed (True) or buffered (False).
Default: False
Returns: It returns output to the screen.

Example: Python Print Output


# Python program to demonstrate
# print() method
print("GFG")

# code for disabling the softspace feature


print('G', 'F', 'G')

Output
GFG
GFG
➢ In the above example, we can see that in the case of the 2nd print statement there is a
space between every letter and the print statement always add a new line character at
the end of the string.
➢ This is because after every character the sep parameter is printed and at the end of the
string the end parameter is printed. Let’s try to change this sep and end parameter.

Example: Python Print output with custom sep and end parameter
# Python program to demonstrate
# print() method
print("GFG", end = "@")

# code for disabling the softspace feature


print('G', 'F', 'G', sep="#")

Output
GFG@G#F#G
Formatting Output
Formatting output in Python can be done in many ways. Let’s discuss them below

Using formatted string literals


➢ We can use formatted string literals, by starting a string with f or F before opening
quotation marks or triple quotation marks.

ARIGNAR ANNA COLLEGE (ARTS & SCIENCE )-KRISHNAGIRI 30


I BCA – PYTHON PROGRAMMING M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,

➢ In this string, we can write Python expressions between { and } that can refer to a
variable or any literal value.
Example: Python String formatting using F string
# Declaring a variable
name = "Gfg"

# Output
print(f'Hello {name}! How are you?')

Output:
Hello Gfg! How are you?
Using format()

➢ We can also use format() function to format our output to make it look presentable.
➢ The curly braces { } work as placeholders.
➢ We can specify the order in which variables occur in the output.
Example: Python string formatting using format() function
# Initializing variables
a = 20
b = 10

# addition
sum = a + b

# subtraction
sub = a- b

# Output
print('The value of a is {} and b is {}'.format(a,b))
print('{2} is the sum of {0} and {1}'.format(a,b,sum))
print('{sub_value} is the subtraction of {value_a} and {value_b}'.format(value_a = a ,
value_b = b, sub_value = sub))
Output:
The value of a is 20 and b is 10
30 is the sum of 20 and 10
10 is the subtraction of 20 and 10
Using % Operator
➢ We can use ‘%’ operator.
➢ % values are replaced with zero or more value of elements.
➢ The formatting using % is similar to that of ‘printf’ in the C programming
language.
• %d – integer
• %f – float
• %s – string
• %x – hexadecimal
• %o – octal
Example:
# Taking input from the user
num = int(input("Enter a value: "))

ARIGNAR ANNA COLLEGE (ARTS & SCIENCE )-KRISHNAGIRI 31


I BCA – PYTHON PROGRAMMING M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,

add = num + 5
# Output
print("The sum is %d" %add)
Output:
Enter a value: 50
The sum is 55
Python Comments
➢ Comments in Python are the lines in the code that are ignored by the interpreter during
the execution of the program.
➢ Comments enhance the readability of the code and help the programmers to understand
the code very carefully.
There are three types of comments in Python:
• Single line Comments
• Multiline Comments
• Docstring Comments
Comments in Python
➢ In the example, it can be seen that Python Comments are ignored by the interpreter
during the execution of the program.
# sample comment
name = "welcome to I BCA"
print(name)
Output:
welcome to I BCA

Types of Comments in Python


Single-Line Comments in Python
➢ Python single-line comment starts with the hashtag symbol (#) with no white spaces and
lasts till the end of the line.
➢ If the comment exceeds one line then put a hashtag on the next line and continue the
Python Comments.
➢ Python’s single-line comments are proved useful for supplying short explanations for
variables, function declarations, and expressions.
➢ See the following code snippet demonstrating single line comment:
Example:
# Print “welcome to I BCA” to console
print("welcome to I BCA ")

Output
welcome to I BCA

Multi-Line Comments in Python


➢ Python does not provide the option for multiline comments. However, there are
different ways through which we can write multiline comments.
➢ Multiline comments using multiple hashtags (#)
➢ We can multiple hashtags (#) to write multiline comments in Python.
➢ Each and every line will be considered as a single-line comment.
# Python program to demonstrate
# multiline comments
print("Multiline comments")

ARIGNAR ANNA COLLEGE (ARTS & SCIENCE )-KRISHNAGIRI 32


I BCA – PYTHON PROGRAMMING M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,

Output
Multiline comments
String Literals In Python
➢ Python ignores the string literals that are not assigned to a variable so we can use these
string literals as Python Comments.
Single-line comments 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.
'This will be ignored by Python'

Multiline comments using string literals


""" Python program to demonstrate
multiline comments"""
print("Multiline comments")
Output
Multiline comments
Docstring in Python
➢ Python docstring is the string literals with triple quotes that are appeared right after the
function.
➢ It is used to associate documentation that has been written with Python modules,
functions, classes, and methods.
➢ It is added right below the functions, modules, or classes to describe what they do.
➢ In Python, the docstring is then made available via the doc attribute.
Example:
def multiply(a, b):
"""Multiplies the value of a and b"""
return a*b

# Print the docstring of multiply function


print(multiply.__doc__)
Output:
Multiplies the value of a and b
Advantages of comments in Python
Comments are generally used for the following purposes:
• Code Readability
• Explanation of the code or Metadata of the project
• Prevent execution of code
• To include resources

Indentation in Python
➢ Indentation is a very important concept of Python because without properly indenting
the Python code, you will end up seeing IndentationError and the code will not get
compiled.
Python Indentation
➢ Python indentation refers to adding white space before a statement to a particular block
of code.

ARIGNAR ANNA COLLEGE (ARTS & SCIENCE )-KRISHNAGIRI 33


I BCA – PYTHON PROGRAMMING M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,

➢ In another word, all the statements with the same space to the right, belong to the same
code block.

Example of Python Indentation


➢ Statement (line 1), if condition (line 2), and statement (last line) belongs to the same
block which means that after statement 1, if condition will be executed. and suppose the
if condition becomes False then the Python will jump to the last statement for
execution.
➢ The nested if-else belongs to block 2 which means that if nested if becomes False, then
Python will execute the statements inside the else condition.
➢ Statements inside nested if-else belong to block 3 and only one statement will be
executed depending on the if-else condition.
➢ Python indentation is a way of telling a Python interpreter that the group of statements
belongs to a particular block of code.
➢ A block is a combination of all these statements.
➢ Block can be regarded as the grouping of statements for a specific purpose.
➢ Most programming languages like C, C++, and Java use braces { } to define a block of
code. Python uses indentation to highlight the blocks of code.
➢ Whitespace is used for indentation in Python.
➢ All statements with the same distance to the right belong to the same block of code.
➢ If a block has to be more deeply nested, it is simply indented further to the right.
➢ You can understand it better by looking at the following lines of code.

Example 1
➢ The lines print(‘Logging on to I BCA…’) and print(‘retype the URL.’) are two separate
code blocks.
➢ The two blocks of code in our example if-statement are both indented four spaces.
➢ The final print(‘All set!’) is not indented, so it does not belong to the else block.
# Python program showing
# indentation
site = 'gfg'
if site == 'gfg':
print('Logging on to I BCA..')

ARIGNAR ANNA COLLEGE (ARTS & SCIENCE )-KRISHNAGIRI 34


I BCA – PYTHON PROGRAMMING M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,

else:
print('retype the URL.')
print('All set !')
Output:
Logging on to geeksforgeeks...
All set !
Example 2
➢ To indicate a block of code in Python, you must indent each line of the block by the
same whitespace.
➢ The two lines of code in the while loop are both indented four spaces.
➢ It is required for indicating what block of code a statement belongs to.
➢ For example, j=1 and while(j<=5): is not indented, and so it is not within the Python
while block.
➢ So, Python code structures by indentation.
j=1
while(j<= 5):
print(j)
j=j+1
Output:
1
2
3
4
5
Note: Python uses 4 spaces as indentation by default. However, the number of spaces is up to
you, but a minimum of 1 space has to be used .

OPERATORS
• Operators are particular symbols which operate on some values andproduce an output.
• The values are known as Operands.
Example:
4+5=9
Here 4 and 5 are Operands and (+), (=) signs are the operators.They produce the output 9
• Python supports the following operators:
1. Arithmetic Operators
2. Relational Operators.
3. Logical Operators.
4. Membership Operators.
5. Identity Operators
6. Assignment operator
7. Unary operator
8. Bitwise operator

ARIGNAR ANNA COLLEGE (ARTS & SCIENCE )-KRISHNAGIRI 35


I BCA – PYTHON PROGRAMMING M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,

1. Arithmetic Operators:

Operat Description
ors
// Perform Floor division (gives integer value after
division)
+ To perform addition
- To perform subtraction
* To perform multiplication
/ To perform division
% To return remainder after division (Modulus)
** Perform exponent (raise to power)
• Arithmetic Operator Examples:
Ex 1:
>>> 10+20
30
>>> 20-10
10
>>> 10*220
>>> 10/25
>>> 10%3
1
>>> 10**2
100
>>> 10//3
3

Ex2:
print(20 + 2)
print(20.5 -2)
print(20 * 2)
print(20.5/2)
print(30//2)
print(30.0//2)

OUTPUT
22
18.5
40
10.2
15
15.0

ARIGNAR ANNA COLLEGE (ARTS & SCIENCE )-KRISHNAGIRI 36


I BCA – PYTHON PROGRAMMING M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,

2. Relational Operators:

Operators Description
< Less than
> Greater than
<= Less than or equal to
>= Greater than or equal to
== Equal to
!= Not equal to

Relational Operators Examples:


>>> 10<20
True
>>> 10>20
False
>>> 10<=10
True
>>> 20>=15
True
>>> 5==6
False
>>>5!=6
True

Ex 2:
a = 10
b = 20
print('a < b is', a<b)
print('a <= b is', a<=b)
print('a > b is', a>b)
print('a >= b is', a>=b)

OUTPUT:
a < b is True
a <= b is True
a > b is False
a >= b is False

3. Logical Operators:

Operat Description
ors
and Logical AND (When both conditions are true output will be true)
or Logical OR (If any one condition is true output will be true
not Logical NOT (Compliment the condition i.e., reverse)

ARIGNAR ANNA COLLEGE (ARTS & SCIENCE )-KRISHNAGIRI 37


I BCA – PYTHON PROGRAMMING M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,

Logical Operators Examples:


a=5>4 and 3>2
print(a)
True
b=5>4 or 3<2
print(b)
True
c=not(5>4)
print(c)
False
4. Membership Operators:

Operat Description
ors
in Returns true if a variable is in sequence of another
variable, else false.
not in Returns true if a variable is not in sequence of
another variable, else false.
Membership Operators Examples:
a=10b=20
list= [10,20,30,40,50]
if (a in list):
print (“a is in given list”) else:
print (“a is not in given list”)if (b not in list):
print (“b is not given in list”)
else:
print (“b is given in list”)

Output:
>>>
a is in given listb is given in list
5. Identity operators:

Operat Description
ors
is Returns true if identity of two operands are same, else false
is not Returns true if identity of two operands are not same, else false.

Identity operators Examples


a=20b=20
if (a is b):
print (“a, b has same identity”)else:
print (“a, b is different”)b=10
if (a is not b):

ARIGNAR ANNA COLLEGE (ARTS & SCIENCE )-KRISHNAGIRI 38


I BCA – PYTHON PROGRAMMING M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,

print (“a, b has different identity”)


else:
print (“a, b has same identity”)
>>>
a, b has same identity
a, b has different identity

6. Bitwise Operators
➢ We can apply these operators bit by bit.
➢ These operators are applicable only for int and boolean types. By mistake if
we are trying to apply for anyother type then we will get Error
Following are the various bitwise operators used in Python:
1. Bitwise and (&)
2. Bitwise or (|)
3. Bitwise ex-or (^)
4. Bitwise complement (~)
5. Bitwise leftshift Operator (<<)
6. Bitwise rightshift Operator(>>)
Behavior of Bitwise Operators

& ==> If both bits are 1 then only result is 1 otherwise result is 0

| ==> If atleast one bit is 1 then result is 1 otherwise result is 0

^ ==>If bits are different then only result is 1 otherwise result is 0

~ ==> bitwise complement operator, i.e 1 means 0 and 0 means 1

<< ==> Bitwise Left shift Operataor


Bitwise Right Shift Operator ==>
>>
EX:
print(4 & 5) #100 & 101
print(4 & 5) #100 | 101
print(4 & 5) #100 ^ 101
print( ~4) #100 ^ 101 # 4 == > 100
print(10<<2)
print(10>>2)

OUTPUT
4
5
1
-5
40
2
7. Assignment operator

ARIGNAR ANNA COLLEGE (ARTS & SCIENCE )-KRISHNAGIRI 39


I BCA – PYTHON PROGRAMMING M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,

➢ We can use assignment operator to assign value to the variable.


x =2
➢ We can combine asignment operator with some other operator to form compound
assignment operator
Ex:
x+=10 ====> x = x+10
x = 10
x += 20 # x = x + 20
print(x)

Output:
30

8. Unary Minus Operator


➢ The unary minus operator is denoted by the symbol minus (-).
➢ When this operator is used before a variable, its value is negated.
➢ That means if the variable value is positive, it will be converted into negative and
vice versa.
n=10
print(-n) #displays -10
num = -10
num = -num
print(num) #displays 10

EXPRESSIONS:
➢ An expression is a combination of values, variables, and operators.
➢ A value all by itself is considered an expression, and so is a variable,so the following
are all legal expressions (assuming that the variable x has been assigned a value):

ARIGNAR ANNA COLLEGE (ARTS & SCIENCE )-KRISHNAGIRI 40


I BCA – PYTHON PROGRAMMING M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,

17
x
x + 17
➢ A statement is a unit of code that the Python interpreter can execute. Wehave seen
two kinds of statement: print and assignment.
➢ Technically an expression is also a statement, but it is probably simpler to think of
them as different things. The important differenceis that an expression has a value; a
statement does not.

1.Arithmetic Expression in Python:


➢ In Python expression, arithmetic expressions are used to perform mathematical operations
such as addition, subtraction, multiplication, and division.
➢ These expressions can be used in a variety of ways, such as in assignment statements,
function arguments, and conditional statements.
➢ Understanding the basics of arithmetic expressions is essential for writing efficient and
effective code.

Order of Operations:
➢ In Python expression, the order of operations follows the standard order of operations,
also known as PEMDAS (Parentheses, Exponentiation, Multiplication and Division, and
Addition and Subtraction).
➢ This means that operations inside parentheses are performed first, followed by
exponentiation, then multiplication and division, and finally addition and subtraction.
➢ Example 1
Let’s have a look at the below example of an arithmetic expression which is using
multiple operators in one expression.
x = 2 + 3 * 4 - 5 / 2 ** 3
result = x
print(result)
# Output: 13.6875
Explanation:
We solved it using the BODMASS rule or with the help of the order of operations.
➢ 2.Evaluation of Comparison Expressions:
When a comparison expression is evaluated, the values of the operands are compared, and
the result of the comparison is returned as either True or False.
➢ For example, if the expression "5 < 10" is evaluated, the result would be True, as 5 is less
than 10.
Examples:
Here are some examples of comparison Expression-
a = [1,2,3,4]
b = [1,2,3,4]
result = a is b
print(result)
# Output: False

ARIGNAR ANNA COLLEGE (ARTS & SCIENCE )-KRISHNAGIRI 41


I BCA – PYTHON PROGRAMMING M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,

➢ 3.Evaluation of Logical Expression in Python:


When a logical expression is evaluated, the values of the operands are compared, and the
result of the comparison is returned as either True or False.
➢ For example, if the expression "5 < 10 and 3 > 1" is evaluated, the result would be True,
as both comparisons in the expression are true.
Example:
Let’s look at the example which will use or operato
a = "hello"
b = "world"
result = a != b or len(a) > 3
print(result)
# Output: True
➢ Explanation:
In this example, the logical or operator (or) is used to combine the comparison
expressions "a != b" and "len(a) > 3".
➢ The first comparison is true, so the expression returns True and the result is printed.
Operator Precedence:
➢ Python expression follows a set of rules for determining the order in which operators are
applied in an expression.
➢ These rules, known as operator precedence, dictate that some operators are applied before
others.
➢ For example, the multiplication operator () has higher precedence than the addition
operator (+), so in the expression 2 + 3 4, the multiplication operator is applied first and
the result is 12.
Here is the precedence order of different operators in python:
• Parentheses ()
• Exponentiation **
• Unary + and –
• Multiplication, Division, Floor division, Modulus *, /, //, %
• Addition, Subtraction +, –
• Left and Right shift
• Bitwise AND &
• Bitwise XOR ^
• Bitwise OR |
• Comparison operators <, >, <=, >=, ==, !=
• Logical NOT not
• Logical AND and
• Logical OR or

Example –
Here is an example of an expression that uses multiple operators with different precedence:
x = (2 + 3) * 4 - 5 / 2
➢ In this expression, the multiplication of 3 and 4 is done first and returns 12. Then the
addition of 2 and 12 is done and returns 14. Next, the division of 5 by 2 is done and
returns 2.5. Finally, 14 – 2.5 = 11.5

ARIGNAR ANNA COLLEGE (ARTS & SCIENCE )-KRISHNAGIRI 42


I BCA – PYTHON PROGRAMMING M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,

TYPE CONVERSIONS:
➢ The process of converting the value of one data type (integer, string, float, etc.) to
another data type is called type conversion.
➢ Python has two typesof type conversion.

Implicit Type Conversion:


➢ In Implicit type conversion, Python automatically converts one data type to another
data type. This process doesn't need any user involvement.
➢ example where Python promotes the conversion of the lower data type (integer) to the
higher data type (float) to avoid data loss.

Example 1: Converting integer to float


num_int = 123
num_flo = 1.23
num_new = num_int + num_flo
print ("datatype of num_int:”, type(num_int)) print ("datatype of num_flo:”, type(num_flo))
print ("Value of num_new:”, num_new)
print ("datatype of num_new:”, type(num_new))

➢ When we run the above program, the output will be:datatype of num_int: <class 'int'>
datatype of num_flo: <class 'float'>
Value of num_new: 124.23
datatype of num_new: <class 'float'>
➢ In the above program, we add two variables num_int and num_flo,storing the value in
num_new.
➢ We will look at the data type of all three objects respectively.
➢ In the output, we can see the data type of num_int is an integer while the data type of
num_flo is a float.
➢ Also, we can see the num_new has a float data type because Python always converts
smaller data types to larger data types to avoid theloss of data.

Example 2: Addition of string(higher) data type and integer(lower) datatype


num_int = 123
num_str = “456”
print (“Data type of num_int:”, type(num_int)) print (“Data type of num_str:”,
type(num_str))print(num_int+num_str)
➢ When we run the above program, the output will be:
➢ Data type of num_int: <class 'int'> Data type of num_str: <class 'str'> Traceback
(most recent call last):
File "python", line 7, in <module>
TypeError: unsupported operand type(s) for +: 'int' and 'str'
➢ In the above program, we add two variables num_int and num_str.
➢ As we can see from the output, we got TypeError. Python is not able touse Implicit
Conversion in such conditions.
➢ However, Python has a solution for these types of situations which is known as
Explicit Conversion.

ARIGNAR ANNA COLLEGE (ARTS & SCIENCE )-KRISHNAGIRI 43


I BCA – PYTHON PROGRAMMING M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,

Explicit Type Conversion:


➢ In Explicit Type Conversion, users convert the data type of an objectto required
data type. We use the predefined functions like int(), float(), str(), etc to
perform explicit type conversion.
➢ This type of conversion is also called typecasting because the usercasts (changes)
the data type of the objects.

Syntax:
<required_datatype>(expression)
➢ Typecasting can be done by assigning the required data type function tothe
expression

Example 3: Addition of string and integer using explicit conversion


num_int = 123
num_str = "456"
print (“Data type of num_int:”, type(num_int))
print (“Data type of num_str before Type Casting:”, type(num_str))
num_str = int(num_str)
print (“Data type of num_str after Type Casting:”, type(num_str))
num_sum = num_int + num_str
print (“Sum of num_int and num_str:”, num_sum)
print (“Data type of the sum:”, type(num_sum))

➢ When we run the above program, the output will be:


Data type of num_int: <class 'int'>
Data type of num_str before Type Casting: <class 'str'>Data type of num_str after Type
Casting: <class 'int'> Sum of num_int and num_str: 579
Data type of the sum: <class 'int'>
➢ In the above program, we add num_str and num_int variable.
➢ We converted num_str from string(higher) to integer(lower) typeusing int() function
to perform the addition.
➢ After converting num_str to an integer value, Python is able to addthese two variables.
➢ We got the num_sum value and data type to be an integer.

ARIGNAR ANNA COLLEGE (ARTS & SCIENCE )-KRISHNAGIRI 44


I BCA – PYTHON PROGRAMMING M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,

Functions for Type Conversions:

ARRAYS:
➢ Array is a container which can hold a fix number of items and these items should be of
the same type.
➢ Most of the data structures make use of arrays to implement their algorithms.
Following are the important terms to understand the concept of Array are as follows −
• Element − Each item stored in an array is called an element.
• Index − Each location of an element in an array has a numerical index, which is
used to identify the element.
Array Representation
Arrays can be declared in various ways in different languages. Below is an illustration.

➢ As per the above illustration, following are the important points to be considered −
• Index starts with 0.
• Array length is 10, which means it can store 10 elements.
• Each element can be accessed via its index. For example, we can fetch an element
at index 6 as 9.
Basic Operations
➢ The basic operations supported by an array are as stated below −
➢ Traverse − print all the array elements one by one.
➢ Insertion − Adds an element at the given index.
➢ Deletion − Deletes an element at the given index.
➢ Search − Searches an element using the given index or by the value.
➢ Update − Updates an element at the given index.

ARIGNAR ANNA COLLEGE (ARTS & SCIENCE )-KRISHNAGIRI 45


I BCA – PYTHON PROGRAMMING M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,

➢ Array is created in Python by importing array module to the python program. Then, the
array is declared as shown below −
from array import *
arrayName = array(typecode, [Initializers])
➢ Typecode are the codes that are used to define the type of value the array will hold.
➢ Some common typecodes used are as follows −

Typecode Value

b Represents signed integer of size 1 byte

B Represents unsigned integer of size 1 byte

c Represents character of size 1 byte

i Represents signed integer of size 2 bytes

I Represents unsigned integer of size 2 bytes

f Represents floating point of size 4 bytes

d Represents floating point of size 8 bytes


➢ Before looking at various array operations lets create and print an array using python.
Example
The below code creates an array named array1.
from array import *
array1 = array('i', [10,20,30,40,50])
for x in array1:
print(x)
Output
➢ When we compile and execute the above program, it produces the following result −
10
20
30
40
50
Accessing Array Element
➢ We can access each element of an array using the index of the element.
➢ The below code shows how to access an array element.
Example
from array import *
array1 = array('i', [10,20,30,40,50])
print (array1[0])
print (array1[2])
Output
➢ When we compile and execute the above program, it produces the following result, which
shows the element is inserted at index position 1.
10

ARIGNAR ANNA COLLEGE (ARTS & SCIENCE )-KRISHNAGIRI 46


I BCA – PYTHON PROGRAMMING M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,

30
Insertion Operation
➢ Insert operation is to insert one or more data elements into an array.
➢ Based on the requirement, a new element can be added at the beginning, end, or any
given index of array.
Example
➢ Here, we add a data element at the middle of the array using the python in-built insert()
method.
from array import *
array1 = array('i', [10,20,30,40,50])
array1.insert(1,60)
for x in array1:
print(x)
➢ When we compile and execute the above program, it produces the following result which
shows the element is inserted at index position 1.
Output
10
60
20
30
40
50
Deletion Operation
➢ Deletion refers to removing an existing element from the array and re-organizing all
elements of an array.
Example
➢ Here, we remove a data element at the middle of the array using the python in-built
remove() method.
from array import *
array1 = array('i', [10,20,30,40,50])
array1.remove(40)
for x in array1:
print(x)
Output
➢ When we compile and execute the above program, it produces the following result which
shows the element is removed form the array.
10
20
30
50
Search Operation
➢ You can perform a search for an array element based on its value or its index.
Example
Here, we search a data element using the python in-built index() method.
from array import *
array1 = array('i', [10,20,30,40,50])
print (array1.index(40))

ARIGNAR ANNA COLLEGE (ARTS & SCIENCE )-KRISHNAGIRI 47


I BCA – PYTHON PROGRAMMING M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,

Output
➢ When we compile and execute the above program, it produces the following result which
shows the index of the element.
➢ If the value is not present in the array then th eprogram returns an error.
3
Update Operation
➢ Update operation refers to updating an existing element from the array at a given index.
Example
➢ Here, we simply reassign a new value to the desired index we want to update.
from array import *
array1 = array('i', [10,20,30,40,50])
array1[2] = 80
for x in array1:
print(x)
Output
➢ When we compile and execute the above program, it produces the following result which
shows the new value at the index position 2.
10
20
80
40
50
Array Methods:

Create an array containing car names:


cars = ["Ford", "Volvo", "BMW"]

Access the Elements of an Array


➢ You refer to an array element by referring to the index number.

ARIGNAR ANNA COLLEGE (ARTS & SCIENCE )-KRISHNAGIRI 48


I BCA – PYTHON PROGRAMMING M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,

Example
Get the value of the first array item:
x = cars[0] #Ford

Example
Modify the value of the first array item:
cars[0] = "Toyota" #cars = ["Toyota ", "Volvo", "BMW"]

The Length of an Array


➢ Use the len() method to return the length of an array (the number of elements in an array).
Example
Return the number of elements in the cars array:
x = len(cars) # 3
Note: The length of an array is always one more than the highest array index.

Looping Array Elements


➢ You can use the for in loop to loop through all the elements of an array.
Example
Print each item in the cars array:
for x in cars:
print(x)
Output
Toyota
Volvo
BMW

Adding Array Elements


➢ You can use the append() method to add an element to an array.
Example
Add one more element to the cars array:
cars.append("Honda") # Toyota , Volvo , BMW , Honda

Removing Array Elements


➢ You can use the pop() method to remove an element from the array.
Example
Delete the second element of the cars array:
cars.pop(1) # Volvo will be removed
➢ You can also use the remove() method to remove an element from the array.
Example
Delete the element that has the value "Volvo":
cars.remove("Volvo") #Toyota , BMW , Honda

Sorting Numbers in Array Elements


import numpy as np
arr = np.array([3, 2, 0, 1])
print(np.sort(arr))

ARIGNAR ANNA COLLEGE (ARTS & SCIENCE )-KRISHNAGIRI 49


I BCA – PYTHON PROGRAMMING M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,

Output:
0
1
2
3

Sort the array alphabetically:


import numpy as np
arr = np.array(['banana', 'cherry', 'apple'])
print(np.sort(arr))

Output:
apple
banana
cherry

Sorting Two Dimensional Arrays in python


import numpy as np
arr = np.array([[3, 2, 4], [5, 0, 1]])
print(np.sort(arr))

Output:
[[2,3,4]
[0,1,5]]

ARIGNAR ANNA COLLEGE (ARTS & SCIENCE )-KRISHNAGIRI 50


I BCA – PYTHON PROGRAMMING M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,

UNIT - II
Control Statements:
1. Conditional Statements:
➢ Conditional Statement in Python perform different computations or actions
depending on whether a specific Boolean constraint evaluates to true or false.
➢ Conditional statements are handled by IF statements in Python.

Story of Two if’s:


➢ Consider the following if statement, coded in a C-like language: if (p > q)
{ p = 1; q = 2; }
Now, look at the equivalent statement in the Python language: if p > q:
p=1
q=2
➢ what Python adds
➢ what Python removes

1) Parentheses are optional if (x < y) ---> if x < y


2) End-of-line is end of statement
C-like languages Python language
x = 1; x=1
3) End of indentation is end of block Why Indentation Syntax?
A Few Special Cases
a = 1;
b = 2;
print (a + b)

➢ You can chain together only simple statements, like assignments, prints, and function
calls.

if statement:
Syntax
if (test expression):
statement1
-------
statement n
statement x

➢ Here, the program evaluates the test expression and will execute statement(s)
only if the test expression is True.
➢ If the test expression is False, the statement(s) is not executed.
➢ In Python, the body of the if statement is indicated by the indentation. The
body starts with an indentation and the first unindented line marks the end.
➢ Python interprets non-zero values as True. None and 0 are interpreted as False.

ARIGNAR ANNA COLLEGE (ARTS & SCIENCE )-KRISHNAGIRI 51


I BCA – PYTHON PROGRAMMING M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,

Flow chart:

Example: Python if Statement

# If the number is positive, we print an appropriate message


num = 3
if (num > 0):
print (num, "is a positive number.") print ("This is always printed.")
num = -1 if num > 0:
print (num, "is a positive number.") print ("This is also always printed.")

➢ When you run the program, the output will be:


3 is a positive number.
This is always printed.
This is also always printed.
➢ In the above example, num > 0 is the test expression.
➢ The body of if is executed only if this evaluates to True.
➢ When the variable num is equal to 3, test expression is true and statements
inside the body of if are executed.
➢ If the variable num is equal to -1, test expression is false and statements
inside the body of if are skipped.
➢ The print() statement falls outside of the if block (unindented). Hence, it is
executed regardless of the test expression.

if-else statement:
Syntax
if (test expression):
statement block 1
else:
statement block 2
statement x

➢ The if...else statement evaluates test expression and will executethe body of if only
when the test condition is True.
➢ If the condition is False, the body of else is executed. Indentation is used to separate
the blocks.

ARIGNAR ANNA COLLEGE (ARTS & SCIENCE )-KRISHNAGIRI 52


I BCA – PYTHON PROGRAMMING M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,

Flow chart :

Example:
# Program checks if the number is positive or negative# And displays an appropriate
message
num = 3
# Try these two variations as well. # num = -5
# num = 0
if (num >= 0):
print ("Positive or Zero")
else:
print ("Negative number")

Output:
Positive or Zero
➢ In the above example, when num is equal to 3, the test expression is true and
the body of if is executed and the body of else is skipped.
➢ If num is equal to -5, the test expression is false and the body of else is
executed and the body of if is skipped.
➢ If num is equal to 0, the test expression is true and body of if is executed and
body of else is skipped.

if...elif...else Statement:
Syntax:
if (test expression 1):
statement block 1
elif (test expression 2):
statement block 2
…………………
elif (test expression N):
statement block n
else:
statement block X
statement Y

➢ The elif is short for else if. It allows us to check for multiple expressions.
➢ If the condition for if is False, it checks the condition of the next elif block
and so on.

ARIGNAR ANNA COLLEGE (ARTS & SCIENCE )-KRISHNAGIRI 53


I BCA – PYTHON PROGRAMMING M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,

➢ If all the conditions are False, the body of else is executed.


➢ Only one block among the several if...elif...else blocks is executed according to
the condition.
➢ The if block can have only one else block. But it can have multiple elif
blocks.
Flow chart:

Example of if...elif...else:
➢ '''In this program, we check if the number is positive ornegative or zero and
display an appropriate message'''
num = 3.4
# Try these two variations as well:
# num = 0
# num = -4.5

if (num > 0):


print ("Positive number")
elif (num == 0):
print("Zero")
else:
print ("Negative number")

➢ When variable num is positive, Positive number is printed.


➢ If num is equal to 0, Zero is printed.
➢ If num is negative, Negative number is printed.

Nested if –else:
➢ We can have a if...elif...else statement insideanother
if...elif...else statement. This is called nesting in computer programming.
➢ Any number of these statements can be nested inside one another. Indentation is the
only way to figure out the level of nesting. They can get confusing, so they must be
avoided unless necessary.

ARIGNAR ANNA COLLEGE (ARTS & SCIENCE )-KRISHNAGIRI 54


I BCA – PYTHON PROGRAMMING M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,

Python Nested if Example


➢ '''In this program, we input a numbercheck if the number is positive or negative or
zero and display an appropriate message
➢ This time we use nested if statement'''
num = float (input ("Enter a number: "))
if (num >= 0):
if(num == 0):
print("Zero")
else:
print ("Positive number")
else:
print ("Negative number")

Output1:
Enter a number: 5 Positive number
Output2:
Enter a number: -1 Negative number
Output3:
Enter a number: 0 Zero

Looping Statements:
➢ In general, statements are executed sequentially: The first statement in a function is
executed first, followed by the second, and so on.
➢ There may be a situation when you need to execute a block of code several number of
times.
➢ Programming languages provide various control structures that allow for more
complicated
execution paths.
➢ A loop statement allows us to execute a statement or group of statements multiple
times.

for loop:

➢ The for loop in Python is used to iterate over a sequence (list, tuple, string) or
other iterable objects. Iterating over a sequence is called traversal.

Syntax :
for loop_control_variable in sequence:
statement block
➢ Here, val is the variable that takes the value of the item inside the sequence on each
iteration.
➢ Loop continues until we reach the last item in the sequence. The body of for loop is
separated from the rest of the code using indentation.

ARIGNAR ANNA COLLEGE (ARTS & SCIENCE )-KRISHNAGIRI 55


I BCA – PYTHON PROGRAMMING M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,

Flow chart:

Example: Python for Loop


# Program to find the sum of all numbers stored in a list # List of numbers
numbers = [6, 5, 3, 8, 4, 2, 5, 4, 11]
# variable to store the sum
sum = 0
# iterate over the list
for val in numbers:
sum = sum+val
print ("The sum is", sum)

➢ When you run the program, the output will be:


The sum is 48
The range () function:
➢ We can generate a sequence of numbers using range () function.
range (10) will generate numbers from 0 to 9 (10 numbers).
➢ We can also define the start, stop and step size as range (start, stop,step_size).
step_size defaults to 1, start to 0 and stop is end of object if not provided.
➢ This function does not store all the values in memory; it would be inefficient. So, it
remembers the start, stop, step size and generates the next number on the go.
➢ To force this function to output all the items, we can use the function list().

Example:
print(range(10))
print(list(range(10)))
print (list (range (2, 8)))
print (list (range (2, 20, 3)))

Output:
range (0, 10)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
[2, 3, 4, 5, 6, 7]
[2, 5, 8, 11, 14, 17]

ARIGNAR ANNA COLLEGE (ARTS & SCIENCE )-KRISHNAGIRI 56


I BCA – PYTHON PROGRAMMING M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,

➢ We can use the range () function in for loops to iterate through a sequence of
numbers.
➢ It can be combined with the len () function to iterate through a sequence using
indexing. Here is an example.
# Program to iterate through a list using indexing
city = ['pune', 'mumbai', 'delhi']
# iterate over the list using index
for i in range(len(city)):
print ("I like", city[i])

Output:
I like pune
I like mumbai I like delhi

for loop with else:


➢ A for loop can have an optional else block as well. The else part is executed if
the items in the sequence used in for loop exhausts.
➢ The break keyword can be used to stop a for loop. In such cases, the else part is
ignored.
➢ Hence, a for loop's else part runs if no break occurs.

Example:
digits = [0, 1, 5]
for i in digits:
print(i)
else:
print("No items left.")

When you run the program, the output will be:


0
1
5
No items left.

➢ Here, the for loop prints items of the list until the loop exhausts.
➢ When the for-loop exhausts, it executes the block of code in the else and
prints No items left.
➢ This for...else statement can be used with the break keyword to run the else block
only when the break keyword was not executed.

Example:
# program to display student's marks from record s
tudent_name = 'Soyuj'
marks = {'Ram': 90, 'Shayam': 55, 'Sujit': 77}

ARIGNAR ANNA COLLEGE (ARTS & SCIENCE )-KRISHNAGIRI 57


I BCA – PYTHON PROGRAMMING M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,

for student in marks:


if student == student_name:
print(marks[student]) break
else:
print ('No entry with that name found.')

Output:
No entry with that name found.
While loop:
➢ The while loop in Python is used to iterate over a block of code as long as the test
expression (condition) is true.
➢ We generally use while loop when we don't know the number oftimes to iterate
beforehand.
Syntax
statement - X
while (test_expression/condition):
statement block
statement - Y
➢ In the while loop, test expression is checked first. The body of theloop is
entered only if the test_expression evaluates to True.
➢ After one iteration, the test expression is checked again. This process continues
until the test_expression evaluates to False.
➢ In Python, the body of the while loop is determined through indentation.
➢ The body starts with indentation and the first unindented line marks the end.
➢ Python interprets any non-zero value as True. None and 0 areinterpreted as
False.

Example: Python while Loop


# Program to add natural # numbers up to
# sum = 1+2+3+...+n
# To take input from the user,
n = int (input (“Enter n: “))
# n = 10
# initialize sum and countersum = 0
i=1
while i <= n:
sum = sum + i
i = i+1 # update counter
# print the sum
print ("The sum is", sum)
➢ When you run the program, the output will be:
Enter n: 10
The sum is 55
➢ In the above program, the test expression will be True as long as our counter
variable i is less than or equal to n (10 in our program).
➢ We need to increase the value of the counter variable in the body of the loop.
➢ This is very important. Failing to do so will result in an infinite loop (never-ending loop).

ARIGNAR ANNA COLLEGE (ARTS & SCIENCE )-KRISHNAGIRI 58


I BCA – PYTHON PROGRAMMING M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,

While loop with else:


➢ Same as with for loops, while loops can also have an optional else block.
➢ The else part is executed if the condition in the while loop evaluates to False.
➢ The while loop can be terminated with a break statement. In such cases, the else part is
ignored. Hence, a while loop's else part runs if no break occurs and the condition is
false.
Example:
'''Example to illustrate the use of else statement with the while loop'''
counter = 0
while (counter < 3):
print ("Inside loop")
counter = counter + 1
else:
print ("Inside else")

Output:
Inside loop Inside loop Inside loop Inside else
➢ Here, we use a counter variable to print the string Inside loop three times.
➢ On the fourth iteration, the condition in while becomes False.
➢ Hence, the else part is executed.

Nested Loops:
➢ Loops can be nested in Python similar to nested loops in other programming
languages.
➢ Nested loop allows us to create one loop inside another loop.
➢ It is similar to nested conditional statements like nested ifstatement.
➢ Nesting of loop can be implemented on both for loop and while loop.
➢ We can use any loop inside loop for example, for loop can havewhile loop in it.

Nested for loop:


➢ For loop can hold another for loop inside it.
➢ In above situation inside for loop will finish its execution first and the control will be
returned back to outside for loop.
Syntax
for iterator in iterable:
for iterator2 in iterable2:
statement(s) of inside for loop
statement(s) of outside for loop

➢ In this first for loop will initiate the iteration and later second for loop will start
its first iteration and till second for loop complete its all iterations the control will
not be given to first for loop and statements of inside for loop will be executed.
➢ Once all iterations of inside for loop are completed then statements of outside for loop
will be executed and next iteration from first for loop will begin.

ARIGNAR ANNA COLLEGE (ARTS & SCIENCE )-KRISHNAGIRI 59


I BCA – PYTHON PROGRAMMING M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,

Example1: of nested for loop in python:


for i in range (1,11):
for j in range (1,11):
m=i*j
print (m, end=' ')
print (“Table of “, i)

Output:
1 2 3 4 5 6 7 8 9 10 Table of 1
2 4 6 8 10 12 14 16 18 20 Table of 2
3 6 9 12 15 18 21 24 27 30 Table of 3
4 8 12 16 20 24 28 32 36 40 Table of 4
5 10 15 20 25 30 35 40 45 50 Table of 5
6 12 18 24 30 36 42 48 54 60 Table of 6
7 14 21 28 35 42 49 56 63 70 Table of 7
8 16 24 32 40 48 56 64 72 80 Table of 8
9 18 27 36 45 54 63 72 81 90 Table of 9
10 20 30 40 50 60 70 80 90 100 Table of 10

Example2: of nested for loop in python:


for i in range (10):
for j in range(i):
print ("*”, end=' ')
print (" ")

Output:

*
**
***
****
*****
******
*******
********
*********

Nested while loop:


➢ While loop can hold another while loop inside it.
➢ In above situation inside while loop will finish its execution first and the control will
be returned back to outside while loop.

ARIGNAR ANNA COLLEGE (ARTS & SCIENCE )-KRISHNAGIRI 60


I BCA – PYTHON PROGRAMMING M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,

Syntax
while expression:
while expression2:
statement(s) of inside while loop
statement(s) of outside while loop
➢ In this first while loop will initiate the iteration and later second while loop will
start its first iteration and till second while loop complete its all iterations the
control will not be given to first while loop and statements of inside while loop will be
executed.
➢ Once all iterations of inside while loop are completed than statements of outside while
loop will be executed and next iteration from first while loop will begin.
➢ It is also possible that if first condition in while loop expression is False then second
while loop will never be executed.

Example1: Program to show nested while loop p=1


while (p<10):
q=1
while (q<=p):
print (p, end=" ")
q+=1
p+=1
print (" ")

Output:
1
22
333
4444
55555
666666
7777777
88888888
999999999

Exampleb2: Program to nested while loop


x=10
while (x>1):
y=10
while (y>=x):
print (x, end=" ")
y-=1
x-=1
print(" ")

ARIGNAR ANNA COLLEGE (ARTS & SCIENCE )-KRISHNAGIRI 61


I BCA – PYTHON PROGRAMMING M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,

Output:
10
99
888
7777
66666
555555
4444444
33333333
222222222

Jumping Statements:
➢ Control statements in python are used to control the order ofexecution of the
program based on the values and logic.
➢ Python provides us with three types of Control Statements:
1. Continue
2. Break
3. Pass
Terminating loops:
➢ The break statement is used inside the loop to exit out of the loop. It is useful
when we want to terminate the loop as soon as the condition is fulfilled
instead of doing the remaining iterations.
➢ It reduces execution time. Whenever the controller encountered a break statement,
it comes out of that loop immediately.
Syntax of break statement for element in sequence:
if condition:
break

Example:
for num in range (10):
if num > 5:
print ("stop processing.")
break
print(num)

Output:
0
1
2
3
4
5
stop processing.
Skipping specific conditions:
➢ The continue statement is used to skip the current iteration and continue with the
next iteration.

ARIGNAR ANNA COLLEGE (ARTS & SCIENCE )-KRISHNAGIRI 62


I BCA – PYTHON PROGRAMMING M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,

Syntax of continue statement for element in sequence:


if condition:
continue

Example of a continue statement:


for num in range (3, 8):
if num == 5:
continue
else:
print(num)

Output:
3
4
6
7

The pass statement:


➢ The pass statement is used when a statement is required syntactically but no command or
code has to be executed.
➢ It specifies a null operation or simply No Operation(NOP) statement.
➢ Nothing happens when the pass statement is executed.
Syntax:
pass

Example:
for letter in “Hello”;
pass #The statement is doing nothing
print(“Pass : “,letter)
print(“Done”)

Output
Pass : H
Pass : e
Pass : l
Pass : l
Pass : o
Done

ARIGNAR ANNA COLLEGE (ARTS & SCIENCE )-KRISHNAGIRI 63


I BCA – PYTHON PROGRAMMING M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,

UNIT - III

FUNCTIONS:
➢ Function is a sub program which consists of set of instructions used to perform a specific
task.
➢ A large program is divided into basic building blocks called function.

Need For Function:

➢ When the program is too complex and large they are divided into parts. Each part is
separately coded and combined into single program. Each subprogram is called as
function.
➢ Debugging, Testing and maintenance becomes easy when the program is divided into
subprograms.
➢ Functions are used to avoid rewriting same code again and again in a program.
➢ Function provides code re-usability
➢ The length of the program is reduced.

Types of function:

➢ Functions can be classified into two categories:


i) Built in function
ii) user defined function

i) Built in functions

➢ Built in functions are the functions that are already created and stored in python.
➢ These built in functions are always available for usage and accessed by a programmer. It
cannot be modified.

ARIGNAR ANNA COLLEGE (ARTS & SCIENCE )-KRISHNAGIRI 64


I BCA – PYTHON PROGRAMMING M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,

ii) User Defined Functions:

➢ User defined functions are the functions that programmers create for their requirement
and use.
➢ These functions can then be combined to form module which can be used in other
programs by importing them.

Advantages of user defined functions:


➢ Programmers working on large project can divide the workload by making different
functions.
➢ If repeated code occurs in a program, function can be used to include those codes and
execute when needed by calling that function.

Function definition: (Sub program)

➢ def keyword is used to define a function.


➢ Give the function name after def keyword followed by parentheses in which arguments
are given.
➢ End with colon (:)
➢ Inside the function add the program statements to be executed
➢ End with or without return statement

Syntax:
def fun_name(Parameter1,Parameter2…Parameter n):
statement1
statement2…
statement n
return[expression]

Example:
def my_add(a,b):
c=a+b
return c

Function Calling: (Main Function)


➢ Once we have defined a function, we can call it from another function, program or even
the Python prompt.
➢ To call a function we simply type the function name with appropriate arguments.
Example:
x=5
y=4
my_add(x,y)

Flow of Execution:
➢ The order in which statements are executed is called the flow of execution
➢ Execution always begins at the first statement of the program.

ARIGNAR ANNA COLLEGE (ARTS & SCIENCE )-KRISHNAGIRI 65


I BCA – PYTHON PROGRAMMING M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,

➢ Statements are executed one at a time, in order, from top to bottom.


➢ Function definitions do not alter the flow of execution of the program, but remember that
statements inside the function are not executed until the function is called.
➢ Function calls are like a bypass in the flow of execution. Instead of going to the next
statement, the flow jumps to the first line of the called function, executes all the
statements there, and then comes back to pick up where it left off.

Note: When you read a program, don’t read from top to bottom. Instead, follow the flow of
execution. This means that you will read the def statements as you are scanning from top to
bottom, but you should skip the statements of the function definition until you reach a point
where that function is called.

Function Prototypes:
i. Function without arguments and without return type
ii. Function with arguments and without return type
iii. Function without arguments and with return type
iv. Function with arguments and with return type
i) Function without arguments and without return type
➢ In this type no argument is passed through the function call and no output is return to
main function
➢ The sub function will read the input values perform the operation and print the result in
the same block
def add():
a=int(input("enter a"))
b=int(input("enter b"))
c=a+b
print(c)
add()

OUTPUT:
enter a 5
enter b 10
15

ii) Function with arguments and without return type


➢ Arguments are passed through the function call but output is not return to the main
function
def add(a,b):
c=a+b
print(c)
a=int(input("enter a"))
b=int(input("enter b"))
add(a,b)
OUTPUT:
enter a 5
enter b 10
15

ARIGNAR ANNA COLLEGE (ARTS & SCIENCE )-KRISHNAGIRI 66


I BCA – PYTHON PROGRAMMING M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,

iii) Function without arguments and with return type


➢ In this type no argument is passed through the function call but output is return to the
main function.
def add():
a=int(input("enter a"))
b=int(input("enter b"))
c=a+b
return c
c=add()
print(c)

OUTPUT:
enter a 5
enter b 10
15
iv) Function with arguments and with return type
➢ In this type arguments are passed through the function call and output is return to the
main function
def add(a,b):
c=a+b
return c
a=int(input("enter a"))
b=int(input("enter b"))
c=add(a,b)
print(c)

OUTPUT:
enter a 5
enter b 10
15

Variable Scope and Lifetime in Python


➢ The scope of variable is a region of the program where a variable is visible or accessible.
➢ Lifetime of a variable is the duration for which a variable exists in the memory.
➢ The existence and accessibility depend on the declaration of a variable in the program.
➢ For example, the lifetime of a variable declared inside a function is as long as the function
is alive.
➢ When the execution of function body is finished, then the variable defined inside a
function will destroy.
Types of Scope of Variables in Python
➢ There are two basic types of scope of variables in Python. They are:
• Global variable scope
• Local variable scope
➢ Let’s understand each type of variable scope with the help of examples.

ARIGNAR ANNA COLLEGE (ARTS & SCIENCE )-KRISHNAGIRI 67


I BCA – PYTHON PROGRAMMING M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,

Global variable Scope in Python


➢ When we define a variable inside the main program but outside the function body, then it
has a global scope.
➢ The variable declared in the main body of the program or file is a global variable.
➢ In the global scope, the global variable will be visible throughout the program or file, and
also inside any file which imports that file.
➢ We can easily access a variable defined in global scope from all kinds of functions and
blocks.
➢ Let’s take some important example programs based on the global scope in Python.

Example :
Let’s write a program in Python in which we will define a global variable and access it from
both inside the function and main program body.
# Declaring a global variable in the global scope.
x = 50
# Declare a simple function that prints the value of x.
def showMe():
print('Value of x from local scope = ',x) # calling variable x inside the
function.

# Main program.
showMe() # calling function.
print('Value of x from global scope = ',x)

Output:
Value of x from local scope = 50
Value of x from global scope = 50
➢ In this example, variable x is a global variable. We have accessed it from both inside the
function and outside the function because it has a global scope.

Local variable Scope


➢ A variable defined or created inside a function body or a block has a local scope.
➢ We can access it only within the declared function or block and not from outside that
function or block.
➢ As the execution of function body or block is finished, Python destroys the local variable
from the memory.
➢ In other words, local variable exists in the memory as long as the function is executing.
➢ Consider the following example code below in which we will define a local variable
within in a function and we will access it inside a function and from outside the function.
Example :
def my_funct():
msg = 'Good morning!' # local variable with local scope.
print(msg) # accessing local variable from inside the function.
my_funct()
print(msg) # accessing local variable from outside the function.

ARIGNAR ANNA COLLEGE (ARTS & SCIENCE )-KRISHNAGIRI 68


I BCA – PYTHON PROGRAMMING M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,

Output:
Good morning!
print(msg) # accessing local variable from outside the function.
NameError: name 'msg' is not defined
➢ As you can see in the output, as we called local variable from outside the function or
main program, we got error because Python destroyed the local variable after the
execution of function.
➢ That is, the local variable does not exist outside the function.
➢ When we define a variable inside the function, it is not related to any way to another
variable with the same name used outside the function.
➢ However, a variable defined outside a function will be read inside a function only when
the function does not change the value. Let’s an example of it.
Example :
# Creating a variable city and set to New York.
city = 'New York' # global scope.
def showMe():
city = 'Dhanbad' # local scope within a function.
print('City:',city)
# Function call
showMe()
print('City:',city) # accessing global variable from the global scope.

Output:
City: Dhanbad
City: New York
➢ In the above program code, first we have assigned a value ‘New York’ to the city, and
then printed the value of city on the console after calling the function.
➢ Next, we have created a function named showMe(). Inside the function showMe(), we
have defined a variable with the same name as that of global variable but with a change
value.
➢ When we accessed this variable, then Python prints the change value on the console, not
the value of global variable because it is not related to any way to another variable with
the same name used outside the function.
➢ As the execution of function body is completed, the value of city is destroyed because it
is a local variable to that function only.
For this reason, the following code throws an exception:
def foo():
print(min([1, 2, 3]))
min = lambda n: "local"foo()
throws the exception:
Traceback (most recent call last):
File "example.py", line 5, in <module>
foo()
File "example.py", line 2, in foo
print(min([1, 2, 3]))
UnboundLocalError: local variable 'min' referenced before assignment

ARIGNAR ANNA COLLEGE (ARTS & SCIENCE )-KRISHNAGIRI 69


I BCA – PYTHON PROGRAMMING M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,

The “global” statement


➢ You can assign a value to a global variable in a function with the global statement:
x = "global"def foo():
global x
x = "local"foo()
print(x) # gives "local"

➢ I need this very rarely. To make sure that I don’t confuse anything, I like to use
the globals() dictionary. In this case, I would rather use:
x = "global"def foo():
globals()["x"] = "local"foo()
print(x) # gives "local"
The “nonlocal” statement
➢ You can assign a value to an enclosed variable with the nonlocal statement:
x = "global"def foo():
x = "enclosed" def bar():
nonlocal x
x = "local" bar()
print(x) # gives "local"foo()
print(x) # gives "local"

RETURN STATEMENT:
➢ The return statement is used to exit a function and go back to the place from where it was
called.
➢ If the return statement has no arguments, then it will not return any values.
➢ But exits from function.
Syntax:

return[expression]

Example:
def my_add(a,b):
c=a+b
return c
x=5
y=4
print(my_add(x,y))

Output:
9

Parameters And Arguments:


Parameters:
➢ Parameters are the value(s) provided in the parenthesis when we write function header.
➢ These are the values required by function to work.
➢ If there is more than one value required, all of them will be listed in parameter list
separated by comma.

ARIGNAR ANNA COLLEGE (ARTS & SCIENCE )-KRISHNAGIRI 70


I BCA – PYTHON PROGRAMMING M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,

Example: def my_add(a,b):

Arguments :
➢ Arguments are the value(s) provided in function call/invoke statement.
➢ List of arguments should be supplied in same way as parameters are listed.
➢ Bounding of parameters to arguments is done 1:1, and so there should be same number
and type of arguments as mentioned in parameter list.
Example: my_add(x,y)

Arguments types:
1. Required Arguments
2. Keyword Arguments
3. Default Arguments
4. Variable length Arguments

1. Required Arguments:
➢ The number of arguments in the function call should match exactly with the function
definition.
def my_details( name, age ):
print("Name: ", name)
print("Age ", age)
return
my_details("george",56)
Output:
Name: george
Age 56

2. Keyword Arguments:
➢ Python interpreter is able to use the keywords provided to match the values with
parameters even though if they are arranged in out of order.
def my_details( name, age ):
print("Name: ", name)
print("Age ", age)
return
my_details(age=56,name="george")
Output:
Name: george
Age 56

3. Default Arguments:
➢ Assumes a default value if a value is not provided in the function call for that argument.
def my_details( name, age=40 ):
print("Name: ", name)
print("Age ", age)
return
my_details(name="george")

ARIGNAR ANNA COLLEGE (ARTS & SCIENCE )-KRISHNAGIRI 71


I BCA – PYTHON PROGRAMMING M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,

Output:
Name: george
Age 40

4. Variable length Arguments


➢ If we want to specify more arguments than specified while defining the function, variable
length arguments are used. It is denoted by * symbol before parameter.
def my_details(*name ):
print(*name)
my_details("rajan","rahul","micheal", ärjun")
Output:
rajan rahul micheal ärjun

Recursion Function
➢ Recursion is the process of defining something in terms of itself.
➢ A physical world example would be to place two parallel mirrors facing each other. Any
object in between them would be reflected recursively.

Python Recursive Function


➢ In Python, we know that a function can call other functions.
➢ It is even possible for the function to call itself.
➢ These types of construct are termed as recursive functions.
➢ The following image shows the working of a recursive function called recurse.

➢ Following is an example of a recursive function to find the factorial of an integer.


➢ Factorial of a number is the product of all the integers from 1 to that number.
➢ For example, the factorial of 6 (denoted as 6!) is 1*2*3*4*5*6 = 720.

Example of a recursive function:


Def factorial(x)
“”” This is a recursive function to find the factorial of an integer”””
if x == 1:
return 1
else:
return( x * factorial(x-1))
num = 3
print(“The factorial of”,num “is” , factorial(num))

Output:
The factorial of 3 is 6
➢ In the above example, factorial() is a recursive function as it calls itself.

ARIGNAR ANNA COLLEGE (ARTS & SCIENCE )-KRISHNAGIRI 72


I BCA – PYTHON PROGRAMMING M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,

➢ When we call this function with a positive integer, it will recursively call itself by
decreasing the number.
➢ Each function multiplies the number with the factorial of the number below it until it is
equal to one.
➢ This recursive call can be explained in the following steps.

factorial(3) # 1st call with 3


3 * factorial(2) # 2nd call with 2
3 * 2 * factorial(1) # 3rd call with 1
3*2*1 # return from 3rd call as number=1
3*2 # return from 2nd call
6 # return from 1st call

➢ Let's look at an image that shows a step-by-step process of what is going on:

➢ Our recursion ends when the number reduces to 1. This is called the base condition.
➢ Every recursive function must have a base condition that stops the recursion or else the
function calls itself infinitely.
➢ The Python interpreter limits the depths of recursion to help avoid infinite recursions,
resulting in stack overflows.
➢ By default, the maximum depth of recursion is 1000.
➢ If the limit is crossed, it results in RecursionError. Let's look at one such condition.

ARIGNAR ANNA COLLEGE (ARTS & SCIENCE )-KRISHNAGIRI 73


I BCA – PYTHON PROGRAMMING M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,

def recursor( ):
recursor( )
recursor( )

Output

Traceback (most recent call last):


File "<string>", line 3, in <module>
File "<string>", line 2, in a
File "<string>", line 2, in a
File "<string>", line 2, in a
[Previous line repeated 996 more times]
RecursionError: maximum recursion depth exceeded

Advantages of Recursion
1. Recursive functions make the code look clean and elegant.
2. A complex task can be broken down into simpler sub-problems using recursion.
3. Sequence generation is easier with recursion than using some nested iteration.
Disadvantages of Recursion
1. Sometimes the logic behind recursion is hard to follow through.
2. Recursive calls are expensive (inefficient) as they take up a lot of memory and time.
3. Recursive functions are hard to debug.

PYTHON STRINGS:
➢ There are numerous types of sequences in Python.
➢ Strings are a special type of sequence that can only store characters, and they have a
special notation.
➢ Strings are sequences of characters and are immutable.
➢ A string is a sequence of characters. We can access the characters one at a
time with the bracket operator:
>>>food = 'roti'
>>>letter = food[1]
➢ The second statement retrieves the character at index position onefrom the food variable
and assigns it to the letter variable.
➢ The expression in brackets is called an index. The index indicates which
character in thesequence you required.
Example.
‘I want to read book’. This is a string, It has been surrounded in single
quotes.
Declaring Python String
String literals in Python
String literals are surrounded by single quotes or double-quotes.

ARIGNAR ANNA COLLEGE (ARTS & SCIENCE )-KRISHNAGIRI 74


I BCA – PYTHON PROGRAMMING M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,

‘I want to read book’


“I want to read book’”

You can also surround them with triple quotes (groups of 3 single quotes
or double quotes).
“””I want to read book’”””
”’ I want to read book’”’

Or using backslashes.
>> ‘Thank\
Good Morning Sir !’
‘ThanksGood Morning Sir!’

➢ You cannot start a string with a single quote and end it with a doublequote..
➢ But if you surround a string with single quotes and also want to use singlequotes as
part of the string, you have to escape it with a backslash (\).
‘Send message to Madam\’s son ’
This statement causes a SyntaxError:
‘Send message to Madam’s son’
➢ You can also do this with double-quotes. If you want to ignore escape sequences, you
can create a raw string by using an ‘r’ or ‘R’ prefix with the string.
Common escape sequences:
➢ \\ Backslash
➢ \n Linefeed
➢ \t Horizontal tab
➢ \’ Single quotes
➢ \” Double quotes
We can assign a string to a variable.

Creating String in Python


➢ We can create a string by enclosing the characters in single-quotes or double- quotes.
➢ Python also provides triple-quotes to represent the string, but it is generally used for
multiline string or docstrings.
#Using single quotes
str1 = 'Hello Python'
print(str1)
#Using double quotes
str2 = "Hello Python"
print(str2)

ARIGNAR ANNA COLLEGE (ARTS & SCIENCE )-KRISHNAGIRI 75


I BCA – PYTHON PROGRAMMING M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,

#Using triple quotes


str3 = '''''Triple quotes are generally used for
represent the multiline or
docstring'''
print(str3)
Output:

Hello Python
Hello Python
➢ Triple quotes are generally used for represent the multiline or docstring

Python String Operators

Operator Description

+ It is known as concatenation operator used to join the strings.


* It is known as repetition operator. It concatenates the multiple copies of the same
string.
[] It is known as slice operator. It is used to access the sub-strings of a particular
string.
[:] It is known as range slice operator. It is used to access the characters from the
specified range.
in It is known as membership operator. It returns if a particular sub-string is present in
the specified string.
not in It is also a membership operator and does the exact reverse of in. It returns true if a
particular substring is not present in the specified string.
r/R It is used to specify the raw string. To define any string as a raw string, the
character r or R is followed by the string. Such as "hello \n python".
% It is used to perform string formatting. It makes use of the format specifies used in
C programming like %d or %f to map their values in python.

ARIGNAR ANNA COLLEGE (ARTS & SCIENCE )-KRISHNAGIRI 76


I BCA – PYTHON PROGRAMMING M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,

str1 = "Hello"
str2 = " World"
print(str1*3) # prints HelloHelloHello
print(str1+str2) # prints Hello world
print(str1[4]) # prints o
print(str1[2:4]) # prints ll
print('w' in str1) # prints false as w is not present in str1
print('Wo' not in str2) # prints false as Wo is present in str2.

Output:
HelloHelloHello
Hello World
o
ll
False
False
Hello\n world
The string str1 : Hello

String Operations:
➢ String is an array of bytes that represent the Unicode characters in Python.
➢ Python does not support character datatype.
➢ A single character also works as a string.Python supports writing the string within a
single quote('') and a double quote("").

Example
"Python" or 'Python'Code
SingleQuotes ='Python in Single Quotes'
DoubleQuotes ="Python in Double Quotes"
print(SingleQuotes)
print(DoubleQuotes)

Output:
Python in Single Quotes Python in Double
Quotes
➢ A single character is simply a string with a length of 1. The squarebrackets can be
used to access the elements from the string.
print()
➢ This function is used for displaying the output or result on the user screen.
Syntax
print('Text or Result') or print("Text or Result')Indexing in String

ARIGNAR ANNA COLLEGE (ARTS & SCIENCE )-KRISHNAGIRI 77


I BCA – PYTHON PROGRAMMING M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,

➢ It returns a particular character from the given string.


Syntax
getChar = a[index] message = "Hello, Python!"
➢ If I want to fetch the characters of the 7th index from the given string.
Syntax
print(string[index])Code print(message[7])
Output:
P
Concatenating the Strings:
➢ The words concatenate means to join together.
➢ Python allows you to concatenate two strings using the + operator.
Example:
str = “Hello”
str2 = “I BCA”
str3 = str1 + str2
print(“ The concatenated string is: “ str3)
Output:
The concatenated string is: Hello I BCA
Appending the String:
➢ Append mean to add something at the end.
➢ In Python you can add one string at the end of another string using += operator.
Example:
str = “Hai , “
name = input(“\n Enter your Department Name: “)
str += name
str += “. Welcome to Arignar Anna College “
print(str)
Output:
Enter your Department Name : I BCA
Hai I BCA . Welcome to Arignar Anna College

Multiplying The String


➢ We can use the * operator to repeat a string n number of times.
Example:
str = “Ta!”
print( str * 3)
Output:
Ta!Ta!Ta!
➢ The str( ) function is used to convert values of any other type into string type.

ARIGNAR ANNA COLLEGE (ARTS & SCIENCE )-KRISHNAGIRI 78


I BCA – PYTHON PROGRAMMING M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,

➢ This helps the programmer to concatenate a string with any data which is
otherwise not allowed.
Example:
str1 = “Hello”
var = 7
str2 = str1 + str(var)
print(str2)
Output:
Hello7
Python slice string:
syntax:
str_object[start_pos:end_pos:step]
➢ The slicing starts with the start_pos index (included) and ends at
end_pos index (excluded).
➢ The step parameter is used to specify the steps to take from start to
end index.

➢ Python String slicing always follows this rule: s[:i] + s[i:] == s for any index ‘i’.
➢ All these parameters are optional – start_pos default value is 0, theend_pos
default value is the length of string and step default value is 1.
➢ Let’s look at some simple examples of string slice function to create substring.

s = 'HelloWorld'
print(s[:])
print(s[::])

Output:
HelloWorld
HelloWorld
➢ Note that since none of the slicing parameters were provided, the substringis
equal to the original string.
➢ Let’s look at some more examples of slicing a string.
s = 'HelloWorld'
first_five_chars = s[:5]
print(first_five_chars)
third_to_fifth_chars = s[2:5]
print(third_to_fifth_chars)
Output:
Hello
Llo
➢ Note that index value starts from 0, so start_pos 2 refers to the third
character in the string.

ARIGNAR ANNA COLLEGE (ARTS & SCIENCE )-KRISHNAGIRI 79


I BCA – PYTHON PROGRAMMING M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,

Reverse a String using Slicing


➢ We can reverse a string using slicing by providing the step value as -1.
s = 'HelloWorld'
reverse_str = s[::-1]
print(reverse_str)
Output:
dlroWolleH

➢ Let’s look at some other examples of using steps and negative index
values.
s1 = s[2:8:2]
print(s1)
Output:
Loo

➢ Here the substring contains characters from indexes 2,4 and 6.


s1 = s[8:1:-1]
print(s1)
Output:
lroWoll

STRINGS ARE IMMUTABLE:


➢ The standard wisdom is that Python strings are immutable. Youcan't change a
string's value, only the reference to the string. Like so:
x = "hello"
x = "goodbye" # New string!

➢ Which implies that each time you make a change to a string variable, you are actually
producing a brand new string.
➢ Because of this, tutorials out there warn you to avoid string concatenation inside a loop
andadvise using join instead for performance reasons.
➢ Even the official documentation says so!

This is wrong. Sort of.


➢ There is a common case for when strings in Python are actually mutable.
➢ I will show you an example by inspecting the string object's unique ID using the builtin
id() function, which is just the memory address.
➢ The number is different for each object. (Objects can be shared though, such as with
interning.)
➢ An unchanging article alludes to the item which is once made can’t change its worth all
its lifetime. Attempt to execute the accompanying code:
name_1 = "Aarun"
name_1[0] = 'T'

ARIGNAR ANNA COLLEGE (ARTS & SCIENCE )-KRISHNAGIRI 80


I BCA – PYTHON PROGRAMMING M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,

➢ You will get a mistake message when you need to change the substance ofthe string.
Traceback (latest call last):
Record "/home/ca508dc8fa5ad71190ca982b0e3493a8.py", line 2, in
<module>
name_1[0] = 'T'
TypeError: 'str' object doesn't uphold thing task

Arrangement
➢ One potential arrangement is to make another string object with vital alterations:
name_1 = "Aarun"
name_2 = "T" + name_1[1:]
print("name_1 = ", name_1, "and name_2 = ", name_2)
name_1 = Aarun and name_2 = Tarun
➢ To watch that they are various strings, check with the id() work:
name_1 = "Aarun"
name_2 = "T" + name_1[1:]
print("id of name_1 = ", id(name_1))
print("id of name_2 = ", id(name_2))
Output:
id of name_1 = 2342565667256
id of name_2 = 2342565669888

➢ To see more about the idea of string permanence, think about theaccompanying code:
name_1 = "Aarun"
name_2 = "Aarun"
print("id of name_1 = ", id(name_1))
print("id of name_2 = ", id(name_2))
Output:
id of name_1 = 2342565667256
id of name_1 with new value = 2342565668656

Built In String Methods and Functions in Python:

Method Description Examples


capitalize() Returns a copy of the string with >>> mystring = "hello python"
its first character capitalized and >>> print(mystring.capitalize())
the rest lowercased. Hello python
Casefold() Returns a casefolded copy of the >>> mystring = "hello PYTHON"
string. Casefolded strings may be >>> print(mystring.casefold())
used for caseless matching. hello python
Center(width, [fillchar]) Returns the string centered in a >>> mystring = "Hello"
string of length width. Padding >>> x = mystring.center(12,
can be done using the "-")
specified fillchar (the default >>> print(x)
padding uses an ASCII space). ---Hello----

ARIGNAR ANNA COLLEGE (ARTS & SCIENCE )-KRISHNAGIRI 81


I BCA – PYTHON PROGRAMMING M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,

The original string is returned


if width is less than or equal to
len(s)
Count(sub, [start], [end]) Returns the number of non- >>> mystr = "Hello Python"
overlapping occurrences of >>> print(mystr.count("o"))
substring (sub) in the range 2
[start, end]. Optional >>> print(mystr.count("th"))
arguments startand end are 1
interpreted as in slice notation. >>> print(mystr.count("l"))
2
>>> print(mystr.count("h"))
1
>>> print(mystr.count("H"))
1
>>> print(mystr.count("hH"))
0
Encode(encoding = “utf-g”, Returns an encoded version of >>> mystr = 'python!'
errors = “strict”) the string as a bytes object. The >>> print('The string is:',mystr)
default encoding is utf-8. errors The string is: python!
may be given to set a different >>> print('The encoded version is: ',
error handling scheme. The mystr.encode("ascii", "ignore"))
possible value for errors are: The encoded version is: b'python!'
• strict (encoding errors >>> print('The encoded version (with
raise a UnicodeError) replace) is:', mystr.encode("ascii",
• ignore "replace"))
• replace The encoded version (with replace) is:
• xmlcharrefreplace b'python!'
• backslashreplace
• any other name
registered via
codecs.register_error()

endswith(suffix, [start], [end]) Returns True if the string ends >>> mystr = "Python"
with the specified suffix, >>>print(mystr.endswith("y"))
otherwise it returns False. False
>>>print(mystr.endswith("hon"))
True
Expandtabs(tabsize=8) Returns a copy of the string >>> mystr = "1\t2\t3"
where all tab characters are >>> print(mystr)
replaced by one or more spaces, 123
depending on the current column >>>print(mystr.expandtabs())
and the given tab size. 123
>>>print(mystr.expandtabs(tabsize=15))
12
3
>>>print(mystr.expandtabs(tabsize=2))
123
Find(sub, [start], [end]) Returns the lowest index in the >>> mystring = "Python"
string where substring sub is >>>print(mystring.find("P"))
found within the slice 0
s[start:end]. >>>print(mystring.find("on")) 4

ARIGNAR ANNA COLLEGE (ARTS & SCIENCE )-KRISHNAGIRI 82


I BCA – PYTHON PROGRAMMING M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,

Format(*args, **kwargs) Performs a string formatting >>> print("{} and


operation. The string on which {}".format("Apple","Banana"))
this method is called can contain Apple and Banana
literal text or replacement fields >>> print("{1} and {0}".format("Apple",
delimited by braces {}. "Banana"))
Banana and Apple
>>> print("{lunch} and
{dinner}".format(lunch="Peas ",
dinner="Beans"))
Peas and Beans
format_map(mapping) Similar to format(**mapping), >>> lunch = {"Food":
except that mapping is used "Pizza", "Drink": "Wine"}
directly and not copied to a >>> print("Lunch: {Food},
dictionary. {Drink}".format_map(lunch))
Lunch: Pizza, Wine
>>> class Default(dict):
def __missing__(self, key):
return key
>>> lunch = {"Drink": "Wine"}
>>> print("Lunch: {Food},
{Drink}".format_map(Default(lunch)))
Lunch: Food, Wine
Index(sub, [start], [end]) Searches the string for a >>> mystr = "HelloPython"
specified value and returns the >>> print(mystr.index("P"))
position of where it was found 5
>>>print(mystr.index("hon"))
8
>>> print(mystr.index("o"))
4
isalnum Returns True if all characters in >>> mystr = "HelloPython"
the string are alphanumeric >>> print(mystr.isalnum())
True
>>> a = "123"
>>> print(a.isalnum())
True
>>> a= "$*%!!!"
>>> print(a.isalnum())
False
Isalpha() Returns True if all characters in >>> mystr = "HelloPython"
the string are in the alphabet >>> print(mystr.isalpha())
True
>>> a = "123"
>>> print(a.isalpha())
False
>>> a= "$*%!!!"
>>> print(a.isalpha())
False
Isdecimal() Returns True if all characters in >>> mystr = "HelloPython"
the string are decimals >>> print(mystr.isdecimal())
False
>>> a="1.23"

ARIGNAR ANNA COLLEGE (ARTS & SCIENCE )-KRISHNAGIRI 83


I BCA – PYTHON PROGRAMMING M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,

>>> print(a.isdecimal())
False
>>> c = u"\u00B2"
>>> print(c.isdecimal())
False
>>> c="133"
>>> print(c.isdecimal())
True
Isdigit() Returns True if all characters in >>> c="133"
the string are digits >>> print(c.isdigit())
True
>>> c = u"\u00B2"
>>> print(c.isdigit())
True
>>> a="1.23"
>>> print(a.isdigit())
False
isidentifier() Returns True if the string is an >>> c="133"
identifier >>> print(c.isidentifier())
False
>>> c="_user_123"
>>> print(c.isidentifier())
True
>>> c="Python"
>>> print(c.isidentifier())
True
Islower() Returns True if all characters in >>> c="Python"
the string are lower case >>> print(c.islower())
False
>>> c="_user_123"
>>> print(c.islower())
True
>>> print(c.islower())
False
Isnumeric() Returns True if all characters in >>> c="133"
the string are numeric >>> print(c.isnumeric())
True
>>> c="_user_123"
>>> print(c.isnumeric())
False
>>> c="Python"
>>> print(c.isnumeric())
False
isprintable() Returns True if all characters in >>> c="133"
the string are printable >>> print(c.isprintable())
True
>>> c="_user_123"
>>> print(c.isprintable())
True
>>> c="\t"
>>> print(c.isprintable()) False

ARIGNAR ANNA COLLEGE (ARTS & SCIENCE )-KRISHNAGIRI 84


I BCA – PYTHON PROGRAMMING M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,

isspace() Returns True if all characters in >>> c="133"


the string are whitespaces >>> print(c.isspace()) False
>>> c="Hello Pytho "
>>> print(c.isspace()) False
73
>>> c="Hello"
>>> print(c.isspace()) False
>>> c="\t"
>>> print(c.isspace()) True
istitle() Returns True if the string follows >>> c="133"
the rules of a title >>> print(c.istitle()) False
>>> c="Python"
>>> print(c.istitle()) True
>>> c="\t"
>>> print(c.istitle()) False
isupper() Returns True if all characters in >>> c="Python"
the string are upper case >>> print(c.isupper()) False
>>> c="PYHTON"
>>> print(c.isupper()) True
>>> c="\t"
>>> print(c.isupper()) False
join(iterable) Joins the elements of an iterable >>> a ="-"
to the end of the string >>> print(a.join("123"))
1-2-3
>>> a="Hello Python"
>>> a="**"
>>> print(a.join("Hello Python"))
H**e**l**l**o**
**P**y**t**h**o**n
ljust(width[,fillchar]) Returns a left justified version of >>> a="Hello"
the string >>> b = a.ljust(12, "_")
>>> print(b)
Hello______
lower() Converts a string into lower case >>> a = "Python"
>>> print(a.lower())
Python
lstrip([chars]) Returns a left trim version of the >>> a = " Hello "
string >>> print(a.lstrip(), "!")
Hello
maketrans(x[, y[, z]]) Returns a translation table to be >>> frm = "SecretCode"
used in translations >>> to = "4203040540"
>>> trans_table = str.maketrans(frm,to)
>>> sec_code = "Secret
Code".translate(trans_table)
>>> print(sec_code)
400304 0540
partition(sep) Returns a tuple where the string >>> mystr = "Hello-Python"
is parted into three parts >>> print(mystr.partition("-"))
('Hello', '-', 'Python')
74
>>>print(mystr.partition("."))

ARIGNAR ANNA COLLEGE (ARTS & SCIENCE )-KRISHNAGIRI 85


I BCA – PYTHON PROGRAMMING M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,

('Hello-Python', '', '')


replace(old, new[,count]) Returns a string where a >>> mystr = "Hello Python.
specified value is replaced with a Hello Java. Hello C++."
specified value >>>
print(mystr.replace("Hello","Bye"))
Bye Python. Bye Java. Bye
C++.
>>>
print(mystr.replace("Hello","Hell", 2))
Hell Python. Hell Java.
Hello C++.
rfind(sub[, start[,end]]) Searches the string for a >>> mystr = "Hello-Python"
specified value and returns the >>> print(mystr.rfind("P"))
last position of where it was 6
found >>> print(mystr.rfind("-"))
5
>>> print(mystr.rfind("z"))
-1
rindex(sub[, start[,end]]) Searches the string for a >>> mystr = "Hello-Python"
specified value and returns the >>> print(mystr.rindex("P"))
last position of where it was 6
found >>> print(mystr.rindex("-"))
5
>>> print(mystr.rindex("z"))
Traceback (most recent call last):
File "<pyshell#253>", line
1, in <module>
print(mystr.rindex("z"))
ValueError: substring not found
rjust(width[,fillchar]) Returns the string right justified >>> mystr = "Hello Python"
in a string of length width. >>> mystr1 = mystr.rjust(20, "-")
>>> print(mystr1)
--------Hello Python
rpartition(sep) Returns a tuple where the string >>> mystr = "Hello Python"
is parted into three parts >>>
print(mystr.rpartition("."))
('', '', 'Hello Python')
>>> print(mystr.rpartition("")) ('Hello', ' ',
'Python')
rsplit(sep=None, maxsplit=-1) Splits the string at the specified >>> mystr = "Hello Python"
separator, and returns a list >>> print(mystr.rsplit())
['Hello', 'Python']
>>> mystr = "Hello-Python-Hello"
>>> print(mystr.rsplit(sep="-
",maxsplit=1))
['Hello-Python', 'Hello']
rstrip([chars]) Returns a right trim version of >>> mystr = "Hello Python"
the string >>> print(mystr.rstrip(),"!")
Hello Python !
>>> mystr = "--------Hello Python--------"
>>> print(mystr.rstrip(), "-")

ARIGNAR ANNA COLLEGE (ARTS & SCIENCE )-KRISHNAGIRI 86


I BCA – PYTHON PROGRAMMING M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,

------------Hello Python----------- -
>>> print(mystr.rstrip(),"_")
------------Hello Python----------- _
split(sep=None, maxsplit=-1) Splits the string at the specified >>> mystr = "Hello Python"
separator, and returns a list >>> print(mystr.split())
['Hello', 'Python']
>>> mystr1="Hello,,Python"
>>> print(mystr1.split(","))
['Hello', '', 'Python']
splitlines([keepends]) Splits the string at line breaks >>> mystr = "Hello:\n\n
and returns a list Python\r\nJava\nC++\n"
>>>print(mystr.splitlines())
['Hello:', '', ' Python',
'Java', 'C++']
>>>print(mystr.splitlines(keepe
nds=True))
['Hello:\n', '\n', '
Python\r\n', 'Java\n',
'C++\n']
startswith(prefix[,start[, end]]) Returns true if the string starts >>> mystr = "Hello Python"
with the specified value >>>print(mystr.startswith("P"))
False
>>>print(mystr.startswith("H"))
True
>>>print(mystr.startswith("Hell"))
True
strip([chars]) Returns a trimmed version of the >>> mystr = "Hello Python"
string >>> print(mystr.strip(),"!")
Hello Python !
>>> print(mystr.strip(), "")
Hello Python
swapcase() Swaps cases, lower case >>> mystr = "Hello PYthon"
becomes upper case and vice >>> print(mystr.swapcase())
versa hELLO python
title() Converts the first character of >>> mystr = "Hello PYthon"
each word to upper case >>> print(mystr.title())
Hello Python
>>> mystr = "HELLO JAVA"
>>> print(mystr.title())
Hello Java
translate(table) Returns a translated string >>> frm = "helloPython"
>>> to = "40250666333"
>>> trans_table =str.maketrans(frm, to)
>>> secret_code = "Secret
Code".translate(trans_table)
>>> print(secret_code)
S0cr06 C3d0
upper() Converts a string into upper case >>> mystr = "hello Python"
>>> print(mystr.upper())
HELLO PYTHON
zfill(width) Fills the string with a specified >>> mystr = "999"

ARIGNAR ANNA COLLEGE (ARTS & SCIENCE )-KRISHNAGIRI 87


I BCA – PYTHON PROGRAMMING M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,

number of 0 values at the >>> print(mystr.zfill(9))


beginning 000000999
>>> mystr = "-40"
>>> print(mystr.zfill(5))
-0040

STRING COMPARITIONS:
The following are the ways to compare two string in Python:
1. By using == (equal to) operator
2. By using != (not equal to) operator
3. By using sorted() method
4. By using is operator
5. By using Comparison operators

1. Comparing two strings using == (equal to) operator


str1 = input("Enter the first String: ")
str2 = input("Enter the second String: ")
if str1 == str2:
print ("First and second strings are equal and same")
else:
print ("First and second strings are not same")
Output:
Enter the first String: AA
Enter the second String:
AA
First and second strings are equal and same

2. Comparing two strings using != (not equal to) operator


str1 = input("Enter the first String: ")
str2 = input("Enter the second String: ")
if str1 != str2:
print ("First and second strings are not equal.")
else:
print ("First and second strings are the same.")
Output:
Enter the first String: ab Enter the second String: ba
First and second strings are not equal.

3. Comparing two strings using the sorted() method:


➢ If we wish to compare two strings and check for their equality even if the order of
characters/words is different, then we first need to use sorted() method and then compare
two strings.
str1 = input("Enter the first String: ")
str2 = input("Enter the second String: ")
if sorted(str1) == sorted(str2):
print ("First and second strings are equal.")
else:

ARIGNAR ANNA COLLEGE (ARTS & SCIENCE )-KRISHNAGIRI 88


I BCA – PYTHON PROGRAMMING M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,

print ("First and second strings are not the same.")

Output:
Enter the first String: Engineering Discipline
Enter the second String: Discipline
EngineeringFirst and second strings are
equal.
4. Comparing two strings using ‘is’ operator
o Python is Operator returns True if two variables refer to the same
objectinstance.
str1 = "DEED"
str2 = "DEED"
str3 = ''.join(['D', 'E', 'E', 'D'])
print(str1 is str2)
print("Comparision result = ", str1 is str3)

Output:
True
Comparision result = False
➢ In the above example, str1 is str3 returns False because object str3 wascreated
differently.

5. Comparing two strings using comparison operators


input = 'Engineering'
print(input < 'Engineering')
print(input > 'Engineering')
print(input <= 'Engineering')
print(input >= 'Engineering')

Output:
False
False
True
True

Python Modules
➢ Here we will explain how to construct and import custom Python modules.
➢ Additionally, we may import or integrate Python's built-in modules via various methods.

What is Modular Programming?


➢ Modular programming is the practice of segmenting a single, complicated coding task
into multiple, simpler, easier-to-manage sub-tasks.
➢ We call these subtasks modules. Therefore, we can build a bigger program by
assembling different modules that act like building blocks.
➢ Modularizing our code in a big application has a lot of benefits.

ARIGNAR ANNA COLLEGE (ARTS & SCIENCE )-KRISHNAGIRI 89


I BCA – PYTHON PROGRAMMING M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,

Simplification:
➢ A module often concentrates on one comparatively small area of the overall problem
instead of the full task.
➢ We will have a more manageable design problem to think about if we are only
concentrating on one module.
➢ Program development is now simpler and much less vulnerable to mistakes.
Flexibility:
➢ Modules are frequently used to establish conceptual separations between various problem
areas.
➢ It is less likely that changes to one module would influence other portions of the program
if modules are constructed in a fashion that reduces interconnectedness.
➢ (We might even be capable of editing a module despite being familiar with the program
beyond it.) It increases the likelihood that a group of numerous developers will be able to
collaborate on a big project.
Reusability:
➢ Functions created in a particular module may be readily accessed by different sections of
the assignment (through a suitably established api).
➢ As a result, duplicate code is no longer necessary.
Scope:
➢ Modules often declare a distinct namespace to prevent identifier clashes in various parts
of a program.
➢ In Python, modularization of the code is encouraged through the use of functions,
modules, and packages.

What are Modules in Python?


➢ A document with definitions of functions and various statements written in Python is
called a Python module.

In Python, we can define a module in one of 3 ways:


➢ Python itself allows for the creation of modules.
➢ Similar to the re (regular expression) module, a module can be primarily written in C
programming language and then dynamically inserted at run-time.
➢ 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.
➢ We employ modules to divide complicated programs into smaller, more understandable
pieces. Modules also allow for the reuse of code.

➢ Rather than duplicating their definitions into several applications, we may define our
most frequently used functions in a separate module and then import the complete
module.
➢ Let's construct a module. Save the file as example_module.py after entering the
following.

ARIGNAR ANNA COLLEGE (ARTS & SCIENCE )-KRISHNAGIRI 90


I BCA – PYTHON PROGRAMMING M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,

Example:
# Here, we are creating a simple Python program to show how to create a module.
# defining a function in the module to reuse it
def square( number ):
# here, the above function will square the number passed as the input
result = number ** 2
return result # here, we are returning the result of the function
➢ Here, a module called example_module contains the definition of the function square().
The function returns the square of a given number.

How to Import Modules in Python?


➢ In Python, we may import functions from one module into our program, or as we say into,
another module.
➢ For this, we make use of the import Python keyword.
➢ In the Python window, we add the next to import keyword, the name of the module we
need to import.
➢ We will import the module we defined earlier example_module.
Syntax:
import example_module
➢ The functions that we defined in the example_module are not immediately imported into
the present program. Only the name of the module, i.e., example_ module, is imported
here.
➢ We may use the dot operator to use the functions using the module name. For instance:
Example:
# here, we are calling the module square method and passing the value 4
result = example_module.square( 4 )
print("By using the module square of number is: ", result )
Output:
By using the module square of number is: 16
➢ There are several standard modules for Python.
➢ The complete list of Python standard modules is available. The list can be seen using the
help command.
➢ Similar to how we imported our module, a user-defined module, we can use an import
statement to import other standard modules.
➢ Importing a module can be done in a variety of ways. Below is a list of them.

Python import Statement


➢ Using the import Python keyword and the dot operator, we may import a standard module
and can access the defined functions within it. Here's an illustration.
Code
# Here, we are creating a simple Python program to show how to import a standard module
# Here, we are import the math module which is a standard module
import math
print( "The value of euler's number is", math.e )
# here, we are printing the euler's number from the math module

ARIGNAR ANNA COLLEGE (ARTS & SCIENCE )-KRISHNAGIRI 91


I BCA – PYTHON PROGRAMMING M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,

Output:
The value of euler's number is 2.718281828459045

Importing and also Renaming


➢ While importing a module, we can change its name too. Here is an example to show.
Code
# Here, we are creating a simple Python program to show how to import a module and re
name it # Here, we are import the math module and give a different name to it
import math as mt # here, we are importing the math module as mt
print( "The value of euler's number is", mt.e )
# here, we are printing the euler's number from the math module
Output:
The value of euler's number is 2.718281828459045

➢ The math module is now named mt in this program. In some situations, it might help us
type faster in case of modules having long names.
➢ Please take note that now the scope of our program does not include the term math. Thus,
mt.pi is the proper implementation of the module, whereas math.pi is invalid.

Python from...import Statement


➢ We can import specific names from a module without importing the module as a whole.
Here is an example.

Code
# Here, we are creating a simple Python program to show how to import specific
# objects from a module
# Here, we are import euler's number from the math module using the from keyword
from math import e
# here, the e value represents the euler's number
print( "The value of euler's number is", e )

Output:
The value of euler's number is 2.718281828459045

➢ Only the e constant from the math module was imported in this case.
➢ We avoid using the dot (.) operator in these scenarios. As follows, we may import many
attributes at the same time:
Code
# Here, we are creating a simple Python program to show how to import multiple
# objects from a module
from math import e, tau

ARIGNAR ANNA COLLEGE (ARTS & SCIENCE )-KRISHNAGIRI 92


I BCA – PYTHON PROGRAMMING M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,

print( "The value of tau constant is: ", tau )


print( "The value of the euler's number is: ", e )
Output:
The value of tau constant is: 6.283185307179586
The value of the euler's number is: 2.718281828459045

Import all Names - From import * Statement


➢ To import all the objects from a module within the present namespace, use the * symbol
and the from and import keyword.
Syntax:
from name_of_module import *
➢ There are benefits and drawbacks to using the symbol *.
➢ It is not advised to use * unless we are certain of our particular requirements from the
module; otherwise, do so.
Here is an example of the same.
Code
# Here, we are importing the complete math module using *
from math import *
# Here, we are accessing functions of math module without using the dot operator
print( "Calculating square root: ", sqrt(25) )
# here, we are getting the sqrt method and finding the square root of 25
print( "Calculating tangent of an angle: ", tan(pi/6) )
# here pi is also imported from the math module
Output:
Calculating square root: 5.0
Calculating tangent of an angle: 0.5773502691896257

Locating Path of Modules


➢ The interpreter searches numerous places when importing a module in the Python
program. Several directories are searched if the built-in module is not present.
➢ The list of directories can be accessed using sys.path.
➢ The Python interpreter looks for the module in the way described below:
➢ The module is initially looked for in the current working directory.
➢ Python then explores every directory in the shell parameter PYTHONPATH if the
module cannot be located in the current directory.
➢ A list of folders makes up the environment variable known as PYTHONPATH.
➢ Python examines the installation-dependent set of folders set up when Python is
downloaded if that also fails.
Here is an example to print the path.
Code
# Here, we are importing the sys module
import sys

ARIGNAR ANNA COLLEGE (ARTS & SCIENCE )-KRISHNAGIRI 93


I BCA – PYTHON PROGRAMMING M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,

# Here, we are printing the path using sys.path


print("Path of the sys module in the system is:", sys.path)
Output:
Path of the sys module in the system is:
['/home/pyodide', '/home/pyodide/lib/Python310.zip', '/lib/Python3.10',
'/lib/Python3.10/lib-dynload', '', '/lib/Python3.10/site-packages']

The dir() Built-in Function


➢ We may use the dir() method to identify names declared within a module.
➢ For instance, we have the following names in the standard module str. To print the names,
we will use the dir() method in the following way:
Code
# Here, we are creating a simple Python program to print the directory of a module
print( "List of functions:\n ", dir( str ), end=", " )
Output:
List of functions:
['__add__', '__class__', '__contains__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__',
'__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__gt__', '__hash__', '__init__',
'__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__mod__', '__mul__', '__ne__',
'__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmod__', '__rmul__', '__setattr__',
'__sizeof__', '__str__', '__subclasshook__', 'capitalize', 'casefold', 'center', 'count', 'encode',
'endswith', 'expandtabs', 'find', 'format', 'format_map', 'index', 'isalnum', 'isalpha', 'isascii',
'isdecimal', 'isdigit', 'isidentifier', 'islower', 'isnumeric', 'isprintable', 'isspace', 'istitle', 'isupper',
'join', 'ljust', 'lower', 'lstrip', 'maketrans', 'partition', 'removeprefix', 'removesuffix', 'replace', 'rfind',
'rindex', 'rjust', 'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title',
'translate', 'upper', 'zfill']

Namespaces and Scoping


➢ Objects are represented by names or identifiers called variables.
➢ A namespace is a dictionary containing the names of variables (keys) and the objects that
go with them (values).
➢ Both local and global namespace variables can be accessed by a Python statement.
➢ When two variables with the same name are local and global, the local variable takes the
role of the global variable.
➢ There is a separate local namespace for every function.
➢ The scoping rule for class methods is the same as for regular functions.
➢ Python determines if parameters are local or global based on reasonable predictions.
➢ Any variable that is allocated a value in a method is regarded as being local.
➢ Therefore, we must use the global statement before we may provide a value to a global
variable inside of a function.
➢ Python is informed that Var_Name is a global variable by the line global Var_Name.
Python stops looking for the variable inside the local namespace.
➢ We declare the variable Number, for instance, within the global namespace.

ARIGNAR ANNA COLLEGE (ARTS & SCIENCE )-KRISHNAGIRI 94


I BCA – PYTHON PROGRAMMING M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,

➢ Since we provide a Number a value inside the function, Python considers a Number to be
a local variable. UnboundLocalError will be the outcome if we try to access the value of
the local variable without or before declaring it global.
Code
Number = 204
def AddNumber(): # here, we are defining a function with the name Add Number
# Here, we are accessing the global namespace
global Number
Number = Number + 200
print("The number is:", Number)
# here, we are printing the number after performing the addition
AddNumber() # here, we are calling the function
print("The number is:", Number)
Output:
The number is: 204
The number is: 404

Making your own Modules:


➢ We can create as many bmodules as you want.In fact , you have already been doing
that.
➢ Every python program is a module, that is every file that you save as .py extension is a
module.
def display( ):
print(“Hello”)
print(“Name of called module is : “ , __ name __)

str = “Welcome to the world of Python !!! “ #variable definition


➢ Then open another file(main.py) and write the lines of code:
import MyModule
print(“MyModule str = “ , MyModule.str) #using variable defined in MyModule
MyModule.display( ) #using function defined in MyModule
print(“Named of calling module is : “,__name--)
➢ When you run this code , you will get the following output.

MyModule str = Welcome to world of Python!!!


Hello
Name of called module is : MyModule
Name of calling module is : __main__

Note : Modules should be placed in the same directory as that of the program in which it is
imported. It can also be stored in one of the directories listed in sys.path.

➢ Now that we have been using the dot operator to acess members(variables or functions)
of the module.

ARIGNAR ANNA COLLEGE (ARTS & SCIENCE )-KRISHNAGIRI 95


I BCA – PYTHON PROGRAMMING M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,

➢ Assuming that MyModule had many other variables or fumvtions definitions , we


could have specifically imporeted just str and display () by writing theimport statement
as.
From MyModule import str , display

# code in MyModule
def large(a,b):
if a>b:
return a
else:
return b
# code in Find.py
import MyModule
print(“Large(50, 100) = “ , MyModule.large(50,100))
print(“Large(‘B’, ‘c) = , MyModule.large(‘B’ , ‘c’))
print(“Large(‘HI’, ‘BI’) =”MyModule.large(“HI’ , ‘BI’))

Output:
Large(50 , 100) = 100
Large(‘B’ , ‘c’) = c
Large(‘HI’, ‘BI’) = HI

ARIGNAR ANNA COLLEGE (ARTS & SCIENCE )-KRISHNAGIRI 96


I BCA – PYTHON PROGRAMMING M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,

UNIT - IV
Python List:
➢ Python Lists are similar to dynamically scaled arrays.
➢ They are used to hold a series of different formats of data.
➢ Python lists are changeable (mutable), which means they can have their elements changed
after they are created.
➢ A Python list can also be defined as a collection of distinct types of values or items.
➢ The elements in the list are separated by using commas (,) and are surrounded by square
brackets [].
➢ A single list can contain Datatypes such as Integers, Strings, and Objects.
➢ Lists are changeable, which means they can be changed even after they are created.
➢ Each element in the list has a different location in the list, allowing for the duplication of
components in the list, each with its own individual place and credibility.

How to create a list?


➢ A Python list is generated in Python programming by putting all of the items (elements)
inside square brackets [], separated by commas.
➢ It can include an unlimited number of elements of various data types (integer, float, string,
etc.).
➢ Python Lists can also be created using the built-in list() method.
Example
# Python program to create Lists
# creating empty list
my_list = []
print(my_list)

# creating list using square brackets


lang = ['Python', 'Java', 'C++', 'SQL']
print('List of languages are:', lang)

# creating list with mixed values


my_list = ['John', 23, 'Car', 45.2837]
print(my_list)

# nesting list inside a list


nested = ['Values', [1, 2, 3], ['Marks']]
print(nested)

# creating list using built-in function


print(list('Hello World'))

Output
[]
List of languages are: ['Python', 'Java', 'C++', 'SQL']
['John', 23, 'Car', 45.2837]
['Values', [1, 2, 3], ['Marks']]
['H', 'e', 'l', 'l', 'o', ' ', 'W', 'o', 'r', 'l', 'd']

ARIGNAR ANNA COLLEGE (ARTS & SCIENCE )-KRISHNAGIRI 97


I BCA – PYTHON PROGRAMMING M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,

Access List Elements


➢ The elements of a list can be accessed in a variety of ways.

1.List Index
➢ Lists are ordered sequences of elements that, like all other ordered containers in Python, are
indexed with a starting index of 0.
➢ We supply the index (an integer) inside square brackets ([]) to access an element in a list.
Nested indexing is used to retrieve nested listings.
➢ Attempting to access indexes beyond the limit will result in an IndexError.
➢ The index must be a positive integer.
➢ We can’t use floats or other kinds because it will cause a TypeError.
Example
# Python program to illustrate List Indexing
my_list = ['A', 'B', 'Car', 'Dog', 'Egg']

print('List value at index 1:', my_list[1])


print('List value at index 2:', my_list[2])
print('List value at index 4:', my_list[4])

# nesting list
nested = ['Values', [1, 2, 3], ['Marks']]
print(nested[0][0])
print(nested[1][0])
print(nested[1][2])
print(nested[2][0])

# IndexError exception
print(my_list[10])

Output:
List value at index 1: B
List value at index 2: Car
List value at index 4: Egg
V
1
3
Marks
Traceback (most recent call last):
File "", line 16, in
IndexError: list index out of range

General Format:
Seq = List[start:stop:step]
Example:
num_list = [1,2,3,4,5,6,7,8,9,10]

ARIGNAR ANNA COLLEGE (ARTS & SCIENCE )-KRISHNAGIRI 98


I BCA – PYTHON PROGRAMMING M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,

print(“num_list is: “,num_list)


print(“First element in the list is” , num_list[0])
print(“num_list[2:5] =”, num_list[2:5])
print(“num_list[::2] =”, num_list[::5])
print(“num_list[1::3] =”, num_list[1::3])
Output:
num_list is: [1,2,3,4,5,6,7,8,9,10]
First element in the list is 1
num_list[2:5] = [3,4,5]
num_list[::2] = [1,3,5,7,9]
num_list[1::3] =[2,5,8]

2. Negative Indexing
➢ Negative sequence indexes in Python represent positions from the array’s end.
➢ Python sequences support negative indexing.
➢ The value of -1 denotes the last item, the index of -2 the second last item, and so on.
Example
# Python program to illustrate Negative Indexing
my_list = ['A', 2, 'Car', 'Dog', 'Egg', 100]
print(my_list[-1])
print(my_list[-3])
print(my_list[-6])
Output
100
Dog
A
Updating Values in Lists:
➢ Once created , one or more elements of a list can be easily updated by giving the slice on the
left -hand side of the assignment operator.
➢ We can also append new values in the list and remove existing values from the list using the
append( ) method and del statement respectively.
Example:
num_list = [1,2,3,4,5,6,7,8,9,10]
print(“num_list is: “,num_list)
num_list[5] = 100
print(“List after updation is :”,num_list)
num_list.append(200)
print(“List after appending a value is :”,num_list)
del num_list[3]
print(“List after deleting a value is :”,num_list)
Output:
num_list is: [1,2,3,4,5,6,7,8,9,10]
List after updation is : [1,2,3,4,5,100,7,8,9,10]
List after appending a value is : [1,2,3,4,5,100,7,8,9,10 , 200]
List after deleting a value is : [1,2,3,5,100,7,8,9,10 , 200]
➢ If you know exactly which element to delete , use the del statement, otherwise use the
remove( ) method to delete the unknown elements.

ARIGNAR ANNA COLLEGE (ARTS & SCIENCE )-KRISHNAGIRI 99


I BCA – PYTHON PROGRAMMING M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,

Example:
num_list = [1,2,3,4,5,6,7,8,9,10]
del num_list[2:4] # delete numbers at index 2 and 3
print(num_list)
Output:
[1,2,5,6,7,8,9,10]
➢ Can you now imagine what will happen if you write delnum num_list? Yes, the entire
variables will be deleted.
➢ If you make any attempt to use this variable after the del statement, then an error will be
generated. This is very much evident from the code given the following example.
num_list = [1,2,3,4,5,6,7,8,9,10]
del num_list # delete numbers at index 2 and 3
print(num_list)
Output:
Error name ‘num_list’ is not defined
➢ To insert items from another list or sequence at a particular location, you can use the
slice operation.
➢ This will result in the creation of a list with in anotherlist.
Example:
num_list = [1,9,11,13,15]
print(“Original List : “, num_list)
num_list[2] =[3,4,5]
print(“After inserting another list, the updated list is :”,num_list)
Output:
Original List :[1,9,11,13,15]
After inserting another list, the updated list is :[1,9,[3,5,7],13,15]

Nested Lists:
➢ Nested list means a list within another list.
➢ We have already said that a list has elements of different data types which can include
even a list,
Example:
list1= [1 , ‘a’ , “abc” , [2,3,4,5] , 8.9]
i=0
while i<(len(list1));
print[“list1[“,I,”] = “,list1[i])
i+=1
Output:
List1[0] = 1
List1[1] = a
List1[2] = abc
List1[3] = [2,3,4,5]
List1[4] = 8.9

Cloning Lists:
➢ If you want to modify a list and also keep a copy of the original list, then you should
create a separate copy of the list.

ARIGNAR ANNA COLLEGE (ARTS & SCIENCE )-KRISHNAGIRI 100


I BCA – PYTHON PROGRAMMING M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,

➢ This process is called cloning, The slice operation is used to clone a list.
Example:
list1 = [1,2,3,4,5,6,7,8,9,10]
list2 = list1
print(“List1 = “, list1)
print(“List2 = “, list2)
list3 = list1[2:6]
print(“List3 = “, list3)
Output:
List1 = [1,2,3,4,5,6,7,8,9,10]
List2 = [1,2,3,4,5,6,7,8,9,10]
List3 = [3,4,5,6]

Basic List Operations :

➢ Let behave in the similar way as strings when operators like + (concatenation) and
*(repetition) are used.

ARIGNAR ANNA COLLEGE (ARTS & SCIENCE )-KRISHNAGIRI 101


I BCA – PYTHON PROGRAMMING M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,

List Methods :
1. append( )
➢ This function is used to add value to the existing list. Just use the append keyword and
add the name.
➢ The new value will be added at the end of the list.
➢ If we pass another list in the append function, it will add a list as the value.
names = ["Sanjay", "Ramesh", "Suresh", "Ravi"]
names.append("John")
print (names)

Output:
[“Sanjay”, “Ramesh”, “Akshay”,” Ravi”, “John”]

nums = [1,2,3]
names.append(nums)
print (names)

output:
[“Sanjay”, “Ramesh”, “Akshay”, “Ravi”, “John”,[1,2,3]]

2. sort( )
➢ This function is used to arrange the data alphabetically in ascending or descending order.
➢ By default, it does the sort in ascending order.
➢ If we need to do the sorting in descending order, we need to reverse the keyword.

names = ["Sanjay", "Ramesh", "John", "Ravi", “Akshy”]


names.sort()
print (names)

Output:
["Akshay","John","Ramesh","Ravi","Sanjay"]

names.sort(reverse=True)

Output:
["Sanjay","Ravi","Ramesh","John","Akshay"]

3. copy( )
➢ If we want to make a copy of the list, we can assign it to a new variable, but in the case of
Python, a copy might be created, but the problem is that if we change any value in the
original list, then the value of the new list also changes.
➢ They are just sharing the reference of the original variable.
➢ So to avoid this, we can use the copy() function.

ARIGNAR ANNA COLLEGE (ARTS & SCIENCE )-KRISHNAGIRI 102


I BCA – PYTHON PROGRAMMING M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,

new_names = names.copy()
print(new_names)
Output:
["Sanjay","Ravi","Ramesh","John","Akshay"]

names.append(1)
print(names)

Output:
["Sanjay","Ravi","Ramesh","John","Akshay",1]

new_names = ["Sanjay","Ravi","Ramesh","John","Akshay",1]
print(new_names)

Output:
["Sanjay","Ravi","Ramesh","John","Akshay"]

4. clear( )
➢ This function is used to remove all the values from the list and return an empty list with a
square bracket.
names.clear()
print(names)

Output:
[]

5. reverse( )
➢ This function is used to reverse the items of the list.
➢ It will read the element from right to left and modify the current list.

names=["Sanjay","Ravi","Ramesh","John","Akshay"]
names.reverse()

Output:
["Akshay","John","Ramesh","Ravi","Sanjay"]

6. remove( )
➢ If we want to remove any value from the list and don’t know the value’s index position,
then we can use the remove() function.
➢ We have to pass the value which we want to remove from the list, and it will search that
element from left to right, from index position 0, and whichever the matching element
comes first will be removed.

ARIGNAR ANNA COLLEGE (ARTS & SCIENCE )-KRISHNAGIRI 103


I BCA – PYTHON PROGRAMMING M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,

names = ["Sanjay","Ravi","Ramesh","John","Akshay"]
names.remove("Ravi")
print(names)

Output:
["Sanjay","Ramesh","John","Akshay"]

7. pop( )
➢ This function is also similar to the remove() function, but in this function, we can remove
the value from the list based on an index, not a value.
➢ We must know the index position of the value in the list to remove it.

names = ["Sanjay","Ravi","Ramesh","John","Akshay"]
names.pop[2]
print(names)

Output:
["Sanjay","Ravi","John","Akshay"]

8. insert( )
➢ This function is also used to insert the value into the list, but we can insert value at a
specific index position using this function.
➢ The element that exists, in particular, will shift to the next index, which means all the
elements after that index will increment by 1.
names = ["Sanjay","Ravi","John","Akshay"]
names.insert(1,"David")
print(names)

Output:
["Sanjay","David","Ravi","John","Akshay"]

9. count( )
➢ This function is used to find which element exist and how many times in the list.
➢ It will count the total number based on which value is passed inside the function.

names = ["Sanjay","Ravi","John","Akshay","John"]
names.count("David")

Output:
1
names.count("John")
Output:
2

ARIGNAR ANNA COLLEGE (ARTS & SCIENCE )-KRISHNAGIRI 104


I BCA – PYTHON PROGRAMMING M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,

10. extend( )
➢ This function is similar to the append() function only difference is that if we add a list in
another list append() function will make it as a nested list, but in this function, if we add
another list, it will add items on that list instead of making it nested.
names = ["Sanjay",”Ramesh” ,"Akshay" ,"Ravi","John “]
names.append(nums)
print(names)

Output:
["Sanjay", "Ramesh", "Akshay", "Ravi", "John",1,2,3]

11. index( )
➢ This function is used to find the index of any element from the list.
➢ We need to pass the name of the value. Values are case-sensitive.
names = ["Sanjay","Ravi","John","Akshay","John"]
names.index("Ravi")

Output:
1

Example :
>>> fruits = ['orange', 'apple', 'pear', 'banana', 'kiwi', 'apple',
'banana']
>>> fruits.count('apple')
2
>>> fruits.count('tangerine')
0
>>> fruits.index('banana')
3
>>> fruits.index('banana', 4) # Find next banana starting at position 4
6
>>> fruits.reverse()
>>> fruits
['banana', 'apple', 'kiwi', 'banana', 'pear', 'apple', 'orange']
>>> fruits.append('grape')
>>> fruits
['banana', 'apple', 'kiwi', 'banana', 'pear', 'apple', 'orange', 'grape']
>>> fruits.sort()
>>> fruits
['apple', 'apple', 'banana', 'banana', 'grape', 'kiwi', 'orange', 'pear']
>>> fruits.pop()
'pear'

ARIGNAR ANNA COLLEGE (ARTS & SCIENCE )-KRISHNAGIRI 105


I BCA – PYTHON PROGRAMMING M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,

TUPELS IN PYTHON:
➢ A tuple in the Python is similar to the list. The difference between the two is that we
cannot change the element of the tuple once it is assigned to whereas we can change the
elements of a list
➢ The reasons for having immutable types apply to tuples: copy efficiency: rather than
copying an immutable object, you can alias it (bind a variable to a reference) ... interning:
you need to store at most of one copy of any immutable value.
➢ There’s no any need to synchronize access to immutable objects in concurrent code.

Creating a Tuple:
➢ A tuple is created by the placing all the elements inside parentheses '()', separated by
commas. The parentheses are the optional and however, it is a good practice to use
them.
➢ A tuple can have any number of the items and they may be a different types (integer,
float, list, string, etc.).
Example:
# Different types of tuples # Empty tuple
tuple = ( )
print(tuple)
# Tuple having integers
tuple = (1, 2, 3)
print(tuple)
# tuple with mixed datatypes
tuple = (1, "code", 3.4)
print(tuple)
# nested tuple
tuple = ("color ", [6, 4, 2], (1, 2, 3)) print(tuple)

Output:
()
(1, 2, 3)
(1, 'code', 3.4)
('color', [6, 4, 2], (1, 2, 3))

➢ A tuple can also be created without using parentheses. This is known astuple packing.
Example:
tuple = 3, 2.6, "c print(tuple)
# tuple unpacki a, b, c = tuple
print(a) #3
print(b) # 4.6
print(c) # dog

Output:
( 3, 2.6, 'color')
3
2.6
color

ARIGNAR ANNA COLLEGE (ARTS & SCIENCE )-KRISHNAGIRI 106


I BCA – PYTHON PROGRAMMING M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,

ACCESSING VALUES IN TUPLES


➢ There are various ways in which we can access the elements of a tuple.

1.Indexing:
➢ We can use the index operator [] to access an item in a tuple,where the index starts from 0.
➢ So, a tuple having 6 elements will have indices from 0 to 5.
➢ Trying to access an index outside of the tuple index range(6,7,... in this example) will raise
an IndexError.
➢ The index must be an integer, so we cannot use float or othertypes.
➢ This will result in TypeError.
➢ Likewise, nested tuples are accessed using nested indexing, as shown in the example below.

# Accessing tuple elements using indexingtuple = (’a’,’b’,’c’,’d’,’e’,’f’)


print(tuple[0]) # ’a’

print(tuple[5]) # ’f’

# IndexError: list index out of range# print(tuple[6])


# Index must be an integer

# TypeError: list indices must be integers, not float # tuple[2.0]


# nested tuple

tuple = ("color", [6, 4, 2], (1, 2, 3))# nested index


print(tuple[0][3]) # ’o’print(tuple[1][1]) # 4

Output:
afo4

2.Negative Indexing:
➢ Python allows negative indexing for its sequences.
➢ The index of -1 refers to the last item, -2 to the second last item and so on.

Example:
# Negative indexing for accessing tuple elements
tuple = (’a’,’b’,’c’,’d’,’e’,’f’)
# Output: ’f’ print(tuple[-1])
# Output: ’a’ print(tuple[-6])
Output:
fa

ARIGNAR ANNA COLLEGE (ARTS & SCIENCE )-KRISHNAGIRI 107


I BCA – PYTHON PROGRAMMING M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,

3.Slicing:
➢ We can access the range of items from the tuple by using theslicing operator colon:
Example:
# Accessing tuple elements using slicing
tuple = (’a’,’b’,’c’,’d’,’e’,’f’,’g’,’h’,’i’)
# elements 2nd to 4th
# Output: (’b’, ’c’, ’d’)
print(tuple[1:4])
# elements beginning to 2nd
# Output: (’a’, ’b’)
print(tuple[:-7])
# elements 8th to end
# Output: (’h’, ’i’)
print(tuple[7:])
# elements beginning to end
# Output: (’a’, ’b’, ’c’, ’d’, ’e’, ’f’, ’g’, ’h’, ’i’)
print(tuple[:])

Output:
(’b’, ’c’, ’d’)
(’a’, ’b’)
(’h’, ’i’)
(’a’, ’b’, ’c’, ’d’, ’e’, ’f’, ’g’, ’h’, ’i’)

Updating Tuple:
➢ We have already learn that tuple is immutable and so, the values in the tuple cannot be
changed.
➢ You can only extract values from a tuple to form a tuple.
Example:
Tup1 = (1,2,3,4,5)
Tup2 = (6,7,8,9,10)
Tup3 = Tup1 + Tup2
print(Tup3)
Output:
(1,2,3,4,5,6,7,8,9,10)
Deleting Elements in Tuple:
➢ Since tuple is an immutable data structure, you cannot delete values from it.
➢ Of course , you can create a new tuple that has all elements in your tuple except the ones
you don’t want.
➢ Observe the code given in the following example and note the error generated.
Tup1 =(1,2,3,4,5)
del Tup1[3]
print(Tup1)
Output :
Eror ‘tuple’ object doesn’t support item deletion.

ARIGNAR ANNA COLLEGE (ARTS & SCIENCE )-KRISHNAGIRI 108


I BCA – PYTHON PROGRAMMING M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,

➢ Here you can always delete the entire tuple by using the del statement. This is done in the
code given below.
Example:
Tup1 = (1,2,3,4,5)
del Tup1
print(Tup1)

Output:
NameError : name ‘Tup1’ is not defined

➢ Note that this exception is raised because you are now trying to print a tuple that has
already been deleted.

Tuple Operation:

Nested Tuples:
➢ Python allows you to define tuple inside another tuple. This is called a nested tuple.
Consider the program code given below.
➢ We have a list of students who have topped in their respective courses. We store the
name, course, and aggregate of three students as tuples into the tuple Toppers.

Example:
Toppers = ((“Arrav”,”BCA”,92.0),(“”Chaitanya”,”BCA”,99.0),(“Vijay”,”BCA”,97))
for i in Toppers:
print(i)
Output:
(‘Arav’,’BCA’,92.0)
(‘Chaitanya’,’BCA’,99.0)
(‘Vijay’,’BCA’,97)

ARIGNAR ANNA COLLEGE (ARTS & SCIENCE )-KRISHNAGIRI 109


I BCA – PYTHON PROGRAMMING M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,

➢ We can specify a list within a tuple.


Topper = (“Arun”,[94,95,96,97])
print(“Class Topper : “,Topper[0])
print(“Highest Scores in 4 Subjects : “, Topper[1:])
Output:
Class Topper : Arun
Highest Scores in 4 Subjects : ([94,95,96,97])
Checking the index:index( ) method
➢ The index of an element in the tuple can be obtained by using the index( ) method.
➢ If the element being searched is not present in the list, then error is generated.
Syntax:
List.index(obj)

Example:
Tup = (1,2,3,4,5,6,7,8)
print(Tup.index(4))
Output:
3
Difference between List and Tuple :
List
➢ List is a container to contain different types of objects and is used to iterate objects.
Example
list = ['a', 'b', 'c', 'd', 'e']
Tuples
➢ Tuple is also similar to list but contains immutable objects. Tuple processing is faster
than List.
Example
tuples = ('a', 'b', 'c', 'd', 'e')

Following are the important differences between List and Tuple.


Sr. No. Key List Tuple

1 Type List is mutable. Tuple is immutable.

Iteration List iteration is slower and Tuple iteration is faster.


2
is time consuming.

Appropriate for List is useful for insertion Tuple is useful for readonly
3
and deletion operations. operations like accessing elements.

Memory List consumes more Tuples consumes less memory.


4
Consumption memory.

ARIGNAR ANNA COLLEGE (ARTS & SCIENCE )-KRISHNAGIRI 110


I BCA – PYTHON PROGRAMMING M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,

Sr. No. Key List Tuple

Methods List provides many in-built Tuples have less in-built methods.
5
methods.

Error prone List operations are more Tuples operations are safe.
6
error prone.

Dictionaries:

Creating a Dictionary:
➢ To create the Python dictionary, we need to pass the sequence of the items inside curly
braces {}, and to separate them using a comma (,).
➢ Each item has a key and a value expressed as an "key:value" pair.
➢ The values can belong to the any of data type and they can repeat, but the keys are must
remain the unique.
➢ The following examples are demonstrate how to create the Python dictionaries:
Creating an empty dictionary:
dict_sample = {}

Creating a dictionary with integer keys:


dict_sample = {1: ’mango’, 2: ’pawpaw’}

Creating a dictionary with mixed keys:


dict_sample = {’fruit’: ’mango’, 1: [4, 6, 8]}
➢ We can also create a dictionary by explicitly calling the Python's dict()method:
dict_sample = dict({1:’mango’, 2:’pawpaw’})
➢ A dictionary can also be created from a sequence as shown below:
➢ Dictionaries can also be nested, which means that we can create adictionary inside
another dictionary. For example:
dict_sample = {1: {’student1’ : ’Nicholas’, ’student2’ : ’John’, ’student3’ :
’Mercy’}, 2: {’course1’ : ’Computer Science’, ’course2’ : ’Mathematics’, ’course3’
: ’Accounting’}}

➢ To print the dictionary contents, we can use the Python's print() function and pass the
dictionary name as the argument to the function. For example:
dict_sample = { "Company": "Toyota","model": "Premio","year": 2012 }
print(dict_sample)
Output:
{'Company': 'Toyota', 'model': 'Premio', 'year': 2012}

Accessing Values In A Dictionary


➢ To access the dictionary items, we need to pass the key insidesquare brackets [].
For example:
dict_sample = { "Company": "Toyota","model": "Premio", "year": 2012}
x = dict_sample["model"]

ARIGNAR ANNA COLLEGE (ARTS & SCIENCE )-KRISHNAGIRI 111


I BCA – PYTHON PROGRAMMING M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,

print(x)
Output:
Premio

➢ We created a dictionary named dict_sample.


➢ A variable named x is then created and its value is set to be the value for the key
"model" in thedictionary.

Updating Elements In Dictionary


➢ After adding a value to a dictionary we can then modify the existing dictionary element.
➢ You use the key of the element to change the corresponding value.
For example:
dict_sample = { "Company": "Toyota","model": "Premio","year": 2012}
dict_sample["year"] = 2014
print(dict_sample)
Output:
{’year’: 2014, ’model’: ’Premio’, ’Company’: ’Toyota’}

➢ In this example you can see that we have updated the value for the key"year" from
the old value of 2012 to a new value of 2014.

Deleting Elements From Dictionary


➢ The removal of an element from a dictionary can be done in several ways, which we'll
discuss one-by-one in this section:
➢ The del keyword can be used to remove the element with the specified key.
For example:
dict_sample = { "Company": "Toyota","model": "Premio", "year": 2012}
del dict_sample["year"]
print(dict_sample)
Output:
{’Company’: ’Toyota’, ’model’: ’Premio’}
➢ We called the del keyword followed by the dictionary name.
➢ Inside the square brackets that follow the dictionary name, we passed the key of the
element we need to delete from the dictionary, which in this example was "year".
➢ The entry for "year" in the dictionary was then deleted.
➢ Another type to delete a key-value pair is to use the pop() method and pass the key of the
entry to be deleted as the argument to the function.

ARIGNAR ANNA COLLEGE (ARTS & SCIENCE )-KRISHNAGIRI 112


I BCA – PYTHON PROGRAMMING M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,

For example:
dict_sample = { "Company": "Toyota","model": "Premio", "year": 2012 }
dict_sample.pop("year")
print(dict_sample)
Output:
{’Company’: ’Toyota’, ’model’: ’Premio’}

➢ We invoked that pop() method by appending it with the dictionary name. And, in this
example the entry for "year" in the dictionary will be deleted.
➢ The popitem() method removes the last item of inserted into the dictionary, without
needing to specify the key. Take a look at the following example:
dict_sample = { "Company": "Toyota","model": "Premio","year": 2012}
dict_sample.popitem()
print(dict_sample)

Output:
{’Company’: ’Toyota’, ’model’: ’Premio’}

➢ The last entry into the dictionary was "year". It has been removed after calling the
popitem() function.
➢ But what if you want to delete the entire dictionary? It would be difficult and
cumbersome to use one of these methods on every single key. Instead, you can use the del
keyword to delete the entire dictionary.
For example:
dict_sample = { "Company": "Toyota","model": "Premio", "year": 2012}
del dict_sample
print(dict_sample)
Output:
NameError: name ’dict_sample’ is not defined

➢ The code returns an error. The reason is we are trying to access the an dictionary which is
doesn't exist since it is has been deleted.
➢ However, your use-case may require you to just remove all dictionary elements and be
left with an empty dictionary.
➢ This can be achieved by calling the clear() function on the dictionary:
dict_sample = { "Company": "Toyota","model": "Premio", "year": 2012 }
dict_sample.clear()
print(dict_sample)
Output:
{}
➢ The code is returns an empty dictionary since all the dictionary elementshave been
removed.

ARIGNAR ANNA COLLEGE (ARTS & SCIENCE )-KRISHNAGIRI 113


I BCA – PYTHON PROGRAMMING M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,

Built – In Dictionar Functions and Methods:

ARIGNAR ANNA COLLEGE (ARTS & SCIENCE )-KRISHNAGIRI 114


I BCA – PYTHON PROGRAMMING M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,

ARIGNAR ANNA COLLEGE (ARTS & SCIENCE )-KRISHNAGIRI 115


I BCA – PYTHON PROGRAMMING M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,

UNIT - V

Types Of File in Python:

➢ There are two types of files in Python and each of them are explained below in detail with
examples for your easy understanding.
They are:
• Binary file
• Text file

Binary files in Python


➢ Most of the files that we see in our computer system are called binary files.
Example:
1. Document files: .pdf, .doc, .xls etc.
2. Image files: .png, .jpg, .gif, .bmp etc.
3. Video files: .mp4, .3gp, .mkv, .avi etc.
4. Audio files: .mp3, .wav, .mka, .aac etc.
5. Database files: .mdb, .accde, .frm, .sqlite etc.
6. Archive files: .zip, .rar, .iso, .7z etc.
7. Executable files: .exe, .dll, .class etc.
Recommended Reading =>> How to Open .7z File
➢ All binary files follow a specific format. We can open some binary files in the normal text
editor but we can’t read the content present inside the file.
➢ That’s because all the binary files will be encoded in the binary format, which can be
understood only by a computer or machine.
➢ For handling such binary files we need a specific type of software to open it.
For Example, You need Microsoft word software to open .doc binary files.
Likewise, you need a pdf reader software to open .pdf binary files and you need a photo
editor software to read the image files and so on.

Text files in Python


➢ Text files don’t have any specific encoding and it can be opened in normal text editor
itself.
Example:
➢ Web standards: html, XML, CSS, JSON etc.
➢ Source code: c, app, js, py, java etc.
➢ Documents: txt, tex, RTF etc.
➢ Tabular data: csv, tsv etc.
➢ Configuration: ini, cfg, reg etc.
➢ In this tutorial, we will see how to handle both text as well as binary files with some
classic examples.

Python File Handling Operations


Most importantly there are 4 types of operations that can be handled by Python on files:
• Open
• Read
• Write
• Close

ARIGNAR ANNA COLLEGE (ARTS & SCIENCE )-KRISHNAGIRI 116


I BCA – PYTHON PROGRAMMING M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,

Other operations include:


• Rename
• Delete

Python Create and Open a File


➢ Python has an in-built function called open() to open a file.
➢ It takes a minimum of one argument as mentioned in the below syntax.
➢ The open method returns a file object which is used to access the write, read and other in-
built methods.
Syntax:
file_object = open(file_name, mode)
➢ Here, file_name is the name of the file or the location of the file that you want to open,
and file_name should have the file extension included as well.
➢ Which means in test.txt – the term test is the name of the file and .txt is the extension of
the file.
➢ The mode in the open function syntax will tell Python as what operation you want to do
on a file.
• ‘r’ – Read Mode: Read mode is used only to read data from the file.
• ‘w’ – Write Mode: This mode is used when you want to write data into the file or
modify it. Remember write mode overwrites the data present in the file.
• ‘a’ – Append Mode: Append mode is used to append data to the file. Remember data
will be appended at the end of the file pointer.
• ‘r+’ – Read or Write Mode: This mode is used when we want to write or read the data
from the same file.
• ‘a+’ – Append or Read Mode: This mode is used when we want to read data from the
file or append the data into the same file.

Note: The above-mentioned modes are for opening, reading or writing text files only.
While using binary files, we have to use the same modes with the letter ‘b’ at the end. So that
Python can understand that we are interacting with binary files.
• ‘wb’ – Open a file for write only mode in the binary format.
• ‘rb’ – Open a file for the read-only mode in the binary format.
• ‘ab’ – Open a file for appending only mode in the binary format.
• ‘rb+’ – Open a file for read and write only mode in the binary format.
• ‘ab+’ – Open a file for appending and read-only mode in the binary format.
Example 1:
fo = open(“C:/Documents/Python/test.txt”, “r+”)
➢ In the above example, we are opening the file named ‘test.txt’ present at the location
‘C:/Documents/Python/’ and we are opening the same file in a read-write mode which
gives us more flexibility.
Example 2:
fo = open(“C:/Documents/Python/img.bmp”, “rb+”)
➢ In the above example, we are opening the file named ‘img.bmp’ present at the location
“C:/Documents/Python/”, But, here we are trying to open the binary file.

ARIGNAR ANNA COLLEGE (ARTS & SCIENCE )-KRISHNAGIRI 117


I BCA – PYTHON PROGRAMMING M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,

Python Read From File


➢ In order to read a file in python, we must open the file in read mode.

There are three ways in which we can read the files in python.
• read([n])
• readline([n])
• readlines()
• Here, n is the number of bytes to be read.
• First, let’s create a sample text file as shown below.

Now let’s observe what each read method does:

Example 1:
my_file = open(“C:/Documents/Python/test.txt”, “r”)
print(my_file.read(5))
Output:
Hello
➢ Here we are opening the file test.txt in a read-only mode and are reading only the first 5
characters of the file using the my_file.read(5) method.

Output:

Example 2:
my_file = open(“C:/Documents/Python/test.txt”, “r”)
print(my_file.read())
Output:
Hello World
Hello Python
Good Morning
➢ Here we have not provided any argument inside the read() function. Hence it will read all
the content present inside the file.

ARIGNAR ANNA COLLEGE (ARTS & SCIENCE )-KRISHNAGIRI 118


I BCA – PYTHON PROGRAMMING M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,

Output:

Example 3:
my_file = open(“C:/Documents/Python/test.txt”, “r”)
print(my_file.readline(2))
Output:
He
This function returns the first 2 characters of the next line.

Output:

Example 4:
my_file = open(“C:/Documents/Python/test.txt”, “r”)
print(my_file.readline())
Output:
Hello World
➢ Using this function we can read the content of the file on a line by line basis.

Output:

ARIGNAR ANNA COLLEGE (ARTS & SCIENCE )-KRISHNAGIRI 119


I BCA – PYTHON PROGRAMMING M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,

Example 5:
my_file = open(“C:/Documents/Python/test.txt”, “r”)
print(my_file.readlines())
Output:
[‘Hello World\n’, ‘Hello Python\n’, ‘Good Morning’]
Here we are reading all the lines present inside the text file including the newline characters.

Output:

Now let’s see some more practical examples of reading a file.

Reading a specific line from a File


line_number = 4
fo = open(“C:/Documents/Python/test.txt”, ’r’)
currentline = 1
for line in fo:
if(currentline == line_number):
print(line)
break
currentline = currentline +1
Output:
How are You
➢ In the above example, we are trying to read only the 4th line from the ‘test.txt’ file using
a “for loop”.

Output:

ARIGNAR ANNA COLLEGE (ARTS & SCIENCE )-KRISHNAGIRI 120


I BCA – PYTHON PROGRAMMING M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,

Reading the entire file at once


filename = “C:/Documents/Python/test.txt”
filehandle = open(filename, ‘r’)
filedata = filehandle.read()
print(filedata)
Output:
Hello World
Hello Python
Good Morning
How are You

Output:

Python Write to File

➢ In order to write data into a file, we must open the file in write mode.
➢ We need to be very careful while writing data into the file as it overwrites the content
present inside the file that you are writing, and all the previous data will be erased.
We have two methods for writing data into a file as shown below.
• write(string)
• writelines(list)
Example 1:
my_file = open(“C:/Documents/Python/test.txt”, “w”)
my_file.write(“Hello World”)
The above code writes the String ‘Hello World’ into the ‘test.txt’ file.
Before writing data to a test.txt file:

ARIGNAR ANNA COLLEGE (ARTS & SCIENCE )-KRISHNAGIRI 121


I BCA – PYTHON PROGRAMMING M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,

Output:

Example 2:
my_file = open(“C:/Documents/Python/test.txt”, “w”)
my_file.write(“Hello World\n”)
my_file.write(“Hello Python”)
➢ The first line will be ‘Hello World’ and as we have mentioned \n character, the cursor
will move to the next line of the file and then write ‘Hello Python’.
➢ Remember if we don’t mention \n character, then the data will be written continuously in
the text file like ‘Hello WorldHelloPython’

Output:

Example 3:
fruits = [“Apple\n”, “Orange\n”, “Grapes\n”, “Watermelon”]
my_file = open(“C:/Documents/Python/test.txt”, “w”)
my_file.writelines(fruits)
➢ The above code writes a list of data into the ‘test.txt’ file simultaneously.

ARIGNAR ANNA COLLEGE (ARTS & SCIENCE )-KRISHNAGIRI 122


I BCA – PYTHON PROGRAMMING M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,

Output:

Python Append to File


➢ To append data into a file we must open the file in ‘a+’ mode so that we will have access
to both the append as well as write modes.
Example 1:
my_file = open(“C:/Documents/Python/test.txt”, “a+”)
my_file.write (“Strawberry”)
The above code appends the string ‘Apple’ at the end of the ‘test.txt’ file.

Output:

Example 2:
my_file = open(“C:/Documents/Python/test.txt”, “a+”)
my_file.write (“\nGuava”)
➢ The above code appends the string ‘Apple’ at the end of the ‘test.txt’ file in a new line.

ARIGNAR ANNA COLLEGE (ARTS & SCIENCE )-KRISHNAGIRI 123


I BCA – PYTHON PROGRAMMING M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,

Output:

Example 3:
fruits = [“\nBanana”, “\nAvocado”, “\nFigs”, “\nMango”]
my_file = open(“C:/Documents/Python/test.txt”, “a+”)
my_file.writelines(fruits)
➢ The above code appends a list of data into a ‘test.txt’ file.

Output:

ARIGNAR ANNA COLLEGE (ARTS & SCIENCE )-KRISHNAGIRI 124


I BCA – PYTHON PROGRAMMING M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,

Example 4:
text=[&quot;\nHello&quot;,&quot;\nHi&quot;,&quot;\nPython&quot;]
my_file=open(&quot;C:/Documents/Python/test.txt&quot;,mode=&quot;a+&quot;)
my_file.writelines(text)
print(&quot;where the file cursor is:&quot;,my_file.tell())
my_file.seek(0)
for line in my_file:
print(line)
➢ In the above code, we are appending the list of data into the ‘test.txt’ file. Here, you can
observe that we have used the tell() method which prints where the cursor is currently at.
seek(offset): The offset takes three types of arguments namely 0,1 and 2.
When the offset is 0: Reference will be pointed at the beginning of the file.
When the offset is 1: Reference will be pointed at the current cursor position.
When the offset is 2: Reference will be pointed at the end of the file.

Output:

ARIGNAR ANNA COLLEGE (ARTS & SCIENCE )-KRISHNAGIRI 125


I BCA – PYTHON PROGRAMMING M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,

Python Close File


➢ In order to close a file, we must first open the file. In python, we have an in-built method
called close() to close the file which is opened.
➢ Whenever you open a file, it is important to close it, especially, with write method.
Because if we don’t call the close function after the write method then whatever data we
have written to a file will not be saved into the file.
Example 1:
my_file = open(“C:/Documents/Python/test.txt”, “r”)
print(my_file.read())
my_file.close()
Example 2:
my_file = open(“C:/Documents/Python/test.txt”, “w”)
my_file.write(“Hello World”)
my_file.close()

Python Rename or Delete File


➢ Python provides us with an “os” module which has some in-built methods that would
help us in performing the file operations such as renaming and deleting the file.
➢ In order to use this module, first of all, we need to import the “os” module in our program
and then call the related methods.
rename() method:
➢ This rename() method accepts two arguments i.e. the current file name and the new file
name.
Syntax:
os.rename(current_file_name, new_file_name)
Example 1:
import os
os.rename(“test.txt”, “test1.txt”)
Here ‘test.txt’ is the current file name and ‘test1.txt’ is the new file name.
➢ You can specify the location as well as shown in the below example.
Example 2:
import os
os.rename(“C:/Documents/Python/test.txt”, “C:/Documents/Python/test1.txt”)

Before Renaming the file:

ARIGNAR ANNA COLLEGE (ARTS & SCIENCE )-KRISHNAGIRI 126


I BCA – PYTHON PROGRAMMING M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,

After executing the above program

remove() method:
➢ We use the remove() method to delete the file by supplying the file name or the file
location that you want to delete.
Syntax:
os.remove(file_name)
Example 1:
import os
os.remove(“test.txt”)
Here ‘test.txt’ is the file that you want to remove.
Similarly, we can pass the file location as well to the arguments as shown in the below
example
Example 2:
import os
os.remove(“C:/Documents/Python/test.txt”)

Encoding in Files
➢ File encoding represents converting characters into a specific format which only a
machine can understand.
Different machines have different encoding format as shown below.
• Microsoft Windows OS uses ‘cp1252’ encoding format by default.
• Linux or Unix OS uses ‘utf-8’ encoding format by default.
• Apple’s MAC OS uses ‘utf-8’ or ‘utf-16’ encoding format by default.
Let’s see the encoding operation with some examples.
Example 1:
my_file = open(“C:/Documents/Python/test.txt”, mode=”r”)
print(“Microsoft Windows encoding format by default is:”, my_file.encoding)
my_file.close()
Output:
Microsoft Windows encoding format by default is cp1252.
➢ Here, I executed my program on the windows machine, so it has printed the default
encoding as ‘cp1252’.

ARIGNAR ANNA COLLEGE (ARTS & SCIENCE )-KRISHNAGIRI 127


I BCA – PYTHON PROGRAMMING M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,

Output:

➢ We can also change the encoding format of a file by passing it as arguments to the open
function.
Example 2:
my_file = open(“C:/Documents/Python/test.txt”, mode=”w”, encoding=”cp437”)
print(“File encoding format is:”, my_file.encoding)
my_file.close()
Output:
File encoding format is: cp437

Output:

Example 3:
my_file = open(“C:/Documents/Python/test.txt”, mode=”w”, encoding=”utf-16”)
print(“File encoding format is:”, my_file.encoding)
my_file.close()
Output:
File encoding format is: utf-16

Output:

Writing and Reading Data from a Binary File


➢ Binary files store data in the binary format (0’s and 1’s) which is understandable by the
machine.
➢ So when we open the binary file in our machine, it decodes the data and displays in a
human-readable format.

ARIGNAR ANNA COLLEGE (ARTS & SCIENCE )-KRISHNAGIRI 128


I BCA – PYTHON PROGRAMMING M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,

Example:
#Let’s create some binary file.
my_file = open(“C:/Documents/Python/bfile.bin”, “wb+”)
message = “Hello Python”
file_encode = message.encode(“ASCII”)
my_file.write(file_encode)
my_file.seek(0)
bdata = my_file.read()
print(“Binary Data:”, bdata)
ntext = bdata.decode(“ASCII”)
print(“Normal data:”, ntext)
➢ In the above example, first we are creating a binary file ‘bfile.bin’ with the read and write
access and whatever data you want to enter into the file must be encoded before you call
the write method.
➢ Also, we are printing the data without decoding it, so that we can observe how the data
exactly looks inside the file when it’s encoded and we are also printing the same data by
decoding it so that it can be readable by humans.
Output:
Binary Data: b’Hello Python’
Normal data: Hello Python

Output:

File I/O Attributes


Attribute Description
Name Return the name of the file
Mode Return mode of the file
Encoding Return the encoding format of the file
Closed Return true if the file closed else returns false
Example:
my_file = open(“C:/Documents/Python/test.txt”, “a+”)
print(“What is the file name? ”, my_file.name)
print(“What is the file mode? ”, my_file.mode)

ARIGNAR ANNA COLLEGE (ARTS & SCIENCE )-KRISHNAGIRI 129


I BCA – PYTHON PROGRAMMING M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,

print(“What is the encoding format? ”, my_file.encoding)


print(“Is File closed? ”, my_file.closed)
my_file.close()
print(“Is File closed? ”, my_file.closed)
Output:
What is the file name? C:/Documents/Python/test.txt
What is the file mode? r
What is the encoding format? cp1252
Is File closed? False
Is File closed? True

Output:

Let’s try out a few other methods of the file.


Example:
my_file = open(“C:/Documents/Python/test.txt”, “w+”)
my_file.write(“Hello Python\nHello World\nGood Morning”)
my_file.seek(0)
print(my_file.read())
print(“Is file readable: ?”, my_file.readable())
print(“Is file writeable: ?”, my_file.writable())
print(“File no:”, my_file.fileno())
my_file.close()
Output:
Hello Python
Hello World
Good Morning
Is file readable:? True
Is file writeable:? True
File no: 3

ARIGNAR ANNA COLLEGE (ARTS & SCIENCE )-KRISHNAGIRI 130


I BCA – PYTHON PROGRAMMING M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,

Output:

Using with Keyword:


➢ In Python, with statement is used in exception handling to make the code cleaner
and much more readable.
➢ It simplifies the management of common resources like file streams. Observe the
following code example on how the use of with statement makes code cleaner.
Example: (Without using ‘with’ keyword)
# file handling

# 1) without using with statement


file = open('file_path', 'w')
file.write('hello world !')
file.close()

Example: (With using ‘with’ keyword)


# using with statement
with open('file_path', 'w') as file:
file.write('hello world !')

Using split()
➢ We can use a for loop to iterate through the contents of the data file after opening it
with Python’s ‘with’ statement.
➢ After reading the data, the split() method is used to split the text into words.
➢ The split() method by default separates text using whitespace.
with open("examplefile.txt", 'r') as file_data:
for line in file_data:
data = line.split()
print(data)

ARIGNAR ANNA COLLEGE (ARTS & SCIENCE )-KRISHNAGIRI 131


I BCA – PYTHON PROGRAMMING M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,

Output:
['This', 'is', 'line', '1,']
['This', 'is', 'line', '2,']
['This', 'is', 'line', '3,']

Splitting a text file with a generator


➢ A generator in Python is a special trick that can be used to generate an array.
➢ A generator, like a function, returns an array one item at a time.
➢ The yield keyword is used by generators.
➢ When Python encounters a yield statement, it saves the function’s state until the
generator is called again later.
➢ The yield keyword guarantees that the state of our while loop is saved between
iterations.
➢ When dealing with large files, this can be useful
# creating a generator function
def generator_data(name):
# opening file
file = open(name, 'r')
while True:
line = file.readline()
if not line:
# closing file
file.close()
break
# yield line
yield line

data = generator_data("examplefile.txt")
for line in data:
print(line.split())

Output:
['This', 'is', 'line', '1,']
['This', 'is', 'line', '2,']
['This', 'is', 'line', '3,']

File Positions
➢ There are two more methods of file objects used to determine or get files positions.
tell()
seek()
tell():
➢ This method is used to tell us the current position within the file which means the
next read or write operation will be performed that many bytes away from the start
of the file.
Syntax :
obj.tell()

ARIGNAR ANNA COLLEGE (ARTS & SCIENCE )-KRISHNAGIRI 132


I BCA – PYTHON PROGRAMMING M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,

Example :
"""
Author : ITVoyagers (https://itvoyagers.in/)

Date :23rd December 2018


Description : Program to use of tell()
"""
#create file object and show the use tell()
object=open("itvoyagers.txt",'w')
object.write("first statement n")
object.write("second statement n")
object=open("itvoyagers.txt",'r')
s=11
c=object.read(s)
print(object.tell()) #tells the position based on parameter passed in read operation
g=object.read()
print(object.tell()) #tells position after performing read() on entire file

seek():
➢ This method is used to change the current position of file.
➢ This method has two main parameters offset and from.
Syntax :
obj.seek(offset,from)
➢ Here, offset argument means the number of bytes to be moved.

➢ from argument is used to specify the reference position from where the bytes needs to be
moved.

Points to Remember for “from” argument


if from is set to 0 ,it means use the beginning of the file as reference position
if from is set to 1 ,it means use the current position of the file as reference position
if from is set to 2 ,it means use the end of the file as reference position
Example :
"""
Author : ITVoyagers (https://itvoyagers.in/)
Date :23rd December 2018
Description : Program to use of seek()
"""
#create file object and show the use seek()
with open("itvoyagers.txt","r") as f:
s=10
c=f.read(s) #reads till 10 char
print(c,end=' ') #adds space after first read()
f.seek(0,0) #goes to start position in file
c=f.read(s)
print(c)
f.seek(0,1) #goes to current position in file

ARIGNAR ANNA COLLEGE (ARTS & SCIENCE )-KRISHNAGIRI 133


I BCA – PYTHON PROGRAMMING M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,

c=f.read(s)
print(c)
f.seek(0,2) #goes to end position in file
c=f.read(s)
print(c)

Python File Methods


Function Explanation
open() To open a file
close() Close an open file
fileno() Returns an integer number of the file
read(n) Reads ‘n’ characters from the file till end of the file
readable() Returns true if the file is readable
readline() Read and return one line from the file
readlines() Reads and returns all the lines from the file
seek(offset) Change the cursor position by bytes as specified by the offset
seekable() Returns true if the file supports random access
tell() Returns the current file location
writable() Returns true if the file is writable
write() Writes a string of data to the file
writelines() Writes a list of data to the file
Let’s see what we have discussed so far in an end-end program.
Example:
my_file = open(&quot;C:/Documents/Python/test.txt&quot;, mode=&quot;w+&quot;)
print(&quot;What is the file name? &quot;, my_file.name)
print(&quot;What is the mode of the file? &quot;, my_file.mode)
print(&quot;What is the encoding format?&quot;, my_file.encoding)

text = [&quot;Hello Python\n&quot;, &quot;Good Morning\n&quot;, &quot;Good Bye&quot;]


my_file.writelines(text)

print(&quot;Size of the file is:&quot;, my_file.__sizeof__())


print(&quot;Cursor position is at byte:&quot;, my_file.tell())
my_file.seek(0)
print(&quot;Content of the file is:&quot;, my_file.read())
my_file.close()
file = open(&quot;C:/Documents/Python/test.txt&quot;, mode=&quot;r&quot;)
line_number = 3
current_line = 1
data = 0
for line in file:
if current_line == line_number:
data = line
print(&quot;Data present at current line is:&quot;, data)
break
current_line = current_line + 1
bin_file = open(&quot;C:/Documents/Python/bfile.exe&quot;, mode=&quot;wb+&quot;)
message_content = data.encode(&quot;utf-32&quot;)

ARIGNAR ANNA COLLEGE (ARTS & SCIENCE )-KRISHNAGIRI 134


I BCA – PYTHON PROGRAMMING M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,

bin_file.write(message_content)
bin_file.seek(0)
bdata = bin_file.read()
print(&quot;Binary Data is:&quot;, bdata)
ndata = bdata.decode(&quot;utf-32&quot;)
print(&quot;Normal Data is:&quot;, ndata)
file.close()
bin_file.close()
Output:
What is the file name? C:/Documents/Python/test.txt
What is the mode of the file? w+
What is the encoding format? cp1252
Size of the file is: 192
Cursor position is at byte: 36
Content of the file is: Hello Python
Good Morning
Good Bye
Data present at the current line is: Good Bye
Binary Data is: b’\xff\xfe\x00\x00G\x00\x00\x00o\x00\x00\x00o\x00\x00\x00d\x00\x00\x00
\x00\x00\x00B\x00\x00\x00y\x00\x00\x00e\x00\x00\x00′
Normal Data is: Good Bye

ARIGNAR ANNA COLLEGE (ARTS & SCIENCE )-KRISHNAGIRI 135


I BCA – PYTHON PROGRAMMING M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,

Output:

ARIGNAR ANNA COLLEGE (ARTS & SCIENCE )-KRISHNAGIRI 136


I BCA – PYTHON PROGRAMMING M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,

PRACTICAL – I -PYTHON LAB

1. Program using variables, constants, I/O statements in Python.


2. Program using Operators in Python.
3. Program using Conditional Statements.
4. Program using Loops.
5. Program using Jump Statements.
6. Program using Functions.
7. Program using Recursion.
8. Program using Arrays.
9. Program using Strings.
10. Program using Modules.
11. Program using Lists.
12. Program using Tuples.
13. Program using Dictionaries.
14. Program for File Handling.

ARIGNAR ANNA COLLEGE (ARTS & SCIENCE )-KRISHNAGIRI 137


I BCA – PYTHON PROGRAMMING M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,

1. Program using variables, constants, I/O statements in Python.


AIM:
To create a python program for calculating area , perimeter , circumference calculation of
circle and square using variables, constants , I/O statements.

ALGORITHM:
Step 1: Start the program.
Step 2: Define the constant PI=3.14.
Step 3: Read the input values length , breath , radius using (len, bre, r) input variables.
Step 4: Calculate the area, perimeter, circumference values by using variables.
area1= len * bre , area2 = PI*r*r , perimeter=2*(len+bre) , circum=2*PI*r.
Step 5: Print the results as area, circumference, perimeter values (area1,area2,perimeter,circum)
using output statements.
Step 6: Stop the program.

FLOWCHART

ARIGNAR ANNA COLLEGE (ARTS & SCIENCE )-KRISHNAGIRI 138


I BCA – PYTHON PROGRAMMING M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,

PROGRAM :
print(‘To find the area , perimeter , circumference calculation using variable , constants , I/O
statements’)
PI=3.14
len=int(input("Enter the Length of rectangle:"))
bre=int(input("Enter the Breadth of rectangle:"))
r=int(input("Enter the Radius of Circle:"))
area1=len*bre
perimeter=2*(len+bre)
area2=PI*r*r
circum=2*PI*r
print("Area of Rectangle =",area1)
print("Perimeter of Rectangle =",perimeter)
print("Area of Circle =",area2)
print("Circumference of Circle =",circum)

OUTPUT:
To find the area , perimeter , circumference calculation using variable , constants , I/O statements:

Enter the Length of rectangle:20


Enter the Breadth of rectangle:30
Enter the Radius of Circle:10
Area of Rectangle = 600
Perimeter of Rectangle = 100
Area of Circle = 314.0
Circumference of Circle = 62.800000000000004

RESULT:
Thus the above program has executed successfully and outputs are verified.

ARIGNAR ANNA COLLEGE (ARTS & SCIENCE )-KRISHNAGIRI 139


I BCA – PYTHON PROGRAMMING M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,

2. Program using Operators in Python.


AIM:
To create a python program for evaluating the various expressions using operators.

ALGORITHM:
Step 1: Start the program.
Step 2: Read the input values a,b,x.
Step 3: Apply the input variable values to different expressions using different operators.
Step 4: Print the each expression and condition results to the output screen.
Step 5: Stop the program.

FLOWCHART:

ARIGNAR ANNA COLLEGE (ARTS & SCIENCE )-KRISHNAGIRI 140


I BCA – PYTHON PROGRAMMING M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,

PROGRAM:

print('Expressions Evaluations using operators \n')


a=int(input("Enter the First Number:"))
b=int(input("Enter the Second Number:"))
x=input("Enter the String:")

c=((a+b)*(a-b)/(a))
d=((a**b)+(a//b))
print('\nResult for using Arithmetic operators : ' , c , d)
a += b
print('Result for using Assignment Operator: ', (a))
print('Result for using Relational & Logical operators : ' , ((a > b) and (c <= d) or (b>=c)))
print('Result for using Bitwise operators (& , | , ~ , ^) : ' , (a&b) , (a|b) , (~a) , (a^b))
print('Result for using Bitwise Shift operators (<< , >>) : ' , (a<<2) , (b>>2))
print('Result for using Identity operators : ' , (a is b) , (c is not d))
print('Result for using Membershif Operators : ' , ('H' in x) , ('hello' not in x))

OUTPUT:
Expressions Evaluations using operators
Enter the First Number:4
Enter the Second Number:2
Enter the String:hello

Result for using Arithmetic operators : 3.0 18


Result for using Assignment Operator: 6
Result for using Relational & Logical operators : True
Result for using Bitwise operators (& , | , ~ , ^) : 2 6 -7 4
Result for using Bitwise Shift operators (<< , >>) : 24 0
Result for using Identity operators : False True
Result for using Membershif Operators : False False

RESULT:
Thus the above program has executed successfully and outputs are verified.

ARIGNAR ANNA COLLEGE (ARTS & SCIENCE )-KRISHNAGIRI 141


I BCA – PYTHON PROGRAMMING M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,

3. Program using Conditional Statements.


AIM:
To create a python program for finding the biggest and smallest among the given three
numbers using conditional statements.

ALGORITHM:
Step 1: Start the program.
Step 2: Read the input values a,b,c.
Step 3: Find the biggest number from the given three numbers using nested if statements
Step 3.1: Check the input condition(if(a>b)) if it’s true means check (if(a>c)) then assign ‘a’ value
otherwise assign ‘c’ value then check(if(b>c)) then assign ‘b’ value otherwise assign ’c’ value.
Step 3.2: Print the biggest number value.
Step 4: Find the smallest number from the given three numbers using if elif else statement.
Step 4.1: Check the if condition(if(a<b and a<c)) then its true means assign ‘a’ value otherwise false
means check (if(b<c)) then assign ‘b’ value otherwise assign ‘c’ value.
Step 4.2: Print the smallest number value.
Step 5: Stop the program.

FLOWCHART:

ARIGNAR ANNA COLLEGE (ARTS & SCIENCE )-KRISHNAGIRI 142


I BCA – PYTHON PROGRAMMING M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,

PROGRAM:
print('Finding Biggest and Smallest number using conditional statements')
print('\nTo Find the Biggest among the given three numbers for using Nested IF sttement')
print('and To Find the Smallest among the given three numbers for using IF_ElIF_ELSE sttement')
a=int(input('Enter the Number1: '))
b=int(input('Enter the Number2: '))
c=int(input('Enter the Number3:' ))
if (a>b):
if (a>c):
g=a
else:
g=c
else:
if (b>c):
g=b
else:
g=c
print('The Largest Number is = ',g)
s=0
if (a < b and a < c ):
s=a
elif (b < c):
s=b
else :
s=c
print('The Smallest Number is =',s)
OUTPUT:
Finding Biggest and Smallest number using conditional statements
To Find the Biggest among the given three numbers for using Nested IF sttement
and To Find the Smallest among the given three numbers for using IF_ElIF_ELSE sttement
Enter the Number1: 25
Enter the Number2: 45
Enter the Number3: 15
The Largest Number is = 45
The Smallest Number is = 15
RESULT: Thus the above program has executed successfully and outputs are verified.

ARIGNAR ANNA COLLEGE (ARTS & SCIENCE )-KRISHNAGIRI 143


I BCA – PYTHON PROGRAMMING M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,

4. Program using Loops

AIM:
To create a python program for finding the reverse of digits in the given number and also
find the sum of n natural numbers using looping statements.

ALGORITHM:
Step 1:Start the program.
Step 2: Read the input integer number.
Step 3: Assign revs_number=0.
Step 3.1: Check the while loop condition while(number>0) , Inside the body of the loop perform the
following calculations ( remainder = number%10 , revs_number=(revs_number*10)+remainder
, number = number//10)
Step 3.2: Print reverse digits of the given number.
Step 4: Read the input number num.
Step 5: Perform the for loop (for value in range(1,num+1)) then inside the loop body do the
calculation(sum = sum+value).
Step 5.1: Print the sum value.
Step 6: Stop the program.

FLOWCHART:

ARIGNAR ANNA COLLEGE (ARTS & SCIENCE )-KRISHNAGIRI 144


I BCA – PYTHON PROGRAMMING M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,

PROGRAM
print('Program For Demonstrating the various looping statements')
print('\n Print the reverse digits of given number using while loop')
number = int(input('Enter the integer number: '))
revs_number = 0
while (number > 0):
remainder = number % 10
revs_number = (revs_number * 10) + remainder
number = number // 10
print('The reverse number is : {}'.format(revs_number))
print('\n Sum of N natural numbers using for loop')
num = int(input("Please enter the number: "))
sum = 0
for value in range(1, num + 1):
sum = sum + value
print('the sum of first',num,'natural number is =',sum)

OUTPUT:
Program For Demonstrating the various looping statements

Print the reverse digits of given number using while loop


Enter the integer number: 6318
The reverse number is : 8136

Sum of N natural numbers using for loop


Please enter the number: 10
the sum of first 10 natural number is = 55

RESULT:

Thus the above program has executed successfully and outputs are verified.

ARIGNAR ANNA COLLEGE (ARTS & SCIENCE )-KRISHNAGIRI 145


I BCA – PYTHON PROGRAMMING M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,

5. Program using Jump Statements

AIM:
To create a python program for finding the square root of the given numbers using Jump
statements.

ALGORITHM:
Step 1: Start the program.
Step 2: import the math package.
Step 3: Perform the while loop condition while(1).
Step 4: Inside the while loop body read the input number and check the if condition (if(num == 999)
it’s true means break the reading inputs otherwise read the input num again.
Step 5: if(num<0) its true means the square root may not be calculated for negative numbers
otherwise print the squart value using (math.sqrt(num)) function.
Step 6: Stop the program.

FLOWCHART:

ARIGNAR ANNA COLLEGE (ARTS & SCIENCE )-KRISHNAGIRI 146


I BCA – PYTHON PROGRAMMING M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,

PROGRAM:
import math
print(‘To find the Square root of given numbers using Jump Statements\n’)
while(1):
num = int(input('Enter the Number:'))
if(num == 999):
break
elif (num<0):
print('Square root of negative numbers cannot be calculated')
continue
else:
print('Square root of',num,'=',math.sqrt(num))

OUTPUT:
To find the Square root of given numbers using Jump Statements
Enter the Number:81
Square root of 81 = 9.0
Enter the Number:78
Square root of 78 = 8.831760866327848
Enter the Number:-49
Square root of negative numbers cannot be calculated
Enter the Number:999

RESULT:

Thus the above program has executed successfully and outputs are verified.

ARIGNAR ANNA COLLEGE (ARTS & SCIENCE )-KRISHNAGIRI 147


I BCA – PYTHON PROGRAMMING M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,

6. Program using Functions.

AIM:
To create a python program for swapping of two numbers using user defined function.

ALGORITHM:
Step 1: Start the program.
Step 2: Define the function swap(x,y), Inside the function print the before swapping the numbers and
swap the numbers (x,y = y,x) then return the x,y value to function declaration part.
Step 3: Read the user inputs a,b values assign the values to swap(a,b).
Step 4: Print the After swapping values a,b.
Step 5: Stop the program.
Step 6: Stop the program.

FLOWCHART:

ARIGNAR ANNA COLLEGE (ARTS & SCIENCE )-KRISHNAGIRI 148


I BCA – PYTHON PROGRAMMING M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,

PROGRAM:
def swap(x,y):
print('Before swapping a :',x)
print('Before swapping b :',y)
x,y=y,x
return x,y
print('Swapping of two numbers using function\n')
a=int(input('Enter the a value : '))
b=int(input('Enter the b value : '))
a,b=swap(a,b)
print('After swapping a becomes :',a)
print('After swapping b becomes :',b)

OUTPUT:
Swapping of two numbers using function
Enter the a value : 80
Enter the b value : 40
Before swapping a : 80
Before swapping b : 40
After swapping a becomes : 40
After swapping b becomes : 80

RESULT:

Thus the above program has executed successfully and outputs are verified.

ARIGNAR ANNA COLLEGE (ARTS & SCIENCE )-KRISHNAGIRI 149


I BCA – PYTHON PROGRAMMING M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,

7. Program using Recursion.

AIM:
To create a python program to find the factorial value of given input using Recursion
function.

ALGORITHM:
Step 1: Start the program.
Step 2: Define the recr_factorial(n) function.
Step 3: Inside the function check (if(n==1) then return n value otherwise
return(n*recur_factorial(n-1) value.
Step 4: Read the user input value num.
Step 5: Check the if conditions (if(n<0)) then print factorial not calculated for negative number
otherwise (if(n==0)) then print factorial value is 1 otherwise the value passed to
(recur_factorial(num)) function.
Step 6: Stop the program.

FLOWCHART

ARIGNAR ANNA COLLEGE (ARTS & SCIENCE )-KRISHNAGIRI 150


I BCA – PYTHON PROGRAMMING M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,

PROGRAM:
def recur_factorial(n):
if (n == 1):
return n
else:
return n*recur_factorial(n-1)
print('Factorial Calculation Using Recursive Function')
num =int(input('Enter the Number : '))
if (num < 0):
print("Sorry, factorial does not exist for negative numbers")
elif (num == 0):
print("The factorial of 0 is 1")
else:
print("The factorial of", num, "is", recur_factorial(num))

OUTPUT:
Factorial Calculation Using Recursive Function
Enter the Number : 5
The factorial of 5 is 120

RESULT:

Thus the above program has executed successfully and outputs are verified.

ARIGNAR ANNA COLLEGE (ARTS & SCIENCE )-KRISHNAGIRI 151


I BCA – PYTHON PROGRAMMING M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,

8. Program using Arrays.


AIM:
To create a python program for sorting the n numbers using Arrays.

ALGORITHM:
Step 1: Start the program.
Step 2: Declare the NumArr = [ ] and Read the total number of array element value Number
Step 3: For using for loop as like (for i in range(1,Number +1) ) inside the loop body read the user
input values for an array and append it into NumArr.
Step 4: Do the For loop (for I in range(Number) and (for j in range(i+1,Number).
Step 5: Inside the nested for loop check the condition (if(NumArr[i]>NumArr[j]) then do the
following assignments: ( Temp = NumArr[i] ,NumArr[i] = NumArr[j] , NumArr[j] = temp)
Step 6: Print the sorted numbers in ascending order.
Step 7: Assigh (sort_numbers = sorted(NumArr,reverse = True)) and print the result of sorted
numbers in decending order.
Step 8: Stop the Program.

FLOWCHART:

ARIGNAR ANNA COLLEGE (ARTS & SCIENCE )-KRISHNAGIRI 152


I BCA – PYTHON PROGRAMMING M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,

PROGRAM:
print('Sorting the Numbers using Arrays')
NumArr = [ ]
Number = int(input('Please enter the Total Number of Array Elements: '))
for i in range(1, Number + 1):
value = int(input('Please enter the Value of %d Element : ' %i))
NumArr.append(value)
for i in range (Number):
for j in range(i + 1, Number):
if(NumArr[i] > NumArr[j]):
temp = NumArr[i]
NumArr[i] = NumArr[j]
NumArr[j] = temp
print('Element After Sorting Array Elements in Ascending Order is : ', NumArr)
sort_numbers = sorted(NumArr, reverse=True)
print('\nElements After Sorting Array Elements in Descending Order is :',sort_numbers)

OUTPUT:
Sorting the Numbers using Arrays
Please enter the Total Number of Array Elements: 5
Please enter the Value of 1 Element : 30
Please enter the Value of 2 Element : 50
Please enter the Value of 3 Element : 10
Please enter the Value of 4 Element : 20
Please enter the Value of 5 Element : 40
Element After Sorting Array Elements in Ascending Order is : [10, 20, 30, 40, 50]
Elements After Sorting Array Elements in Descending Order is : [50, 40, 30, 20, 10]

RESULT:

Thus the above program has executed successfully and outputs are verified.

ARIGNAR ANNA COLLEGE (ARTS & SCIENCE )-KRISHNAGIRI 153


I BCA – PYTHON PROGRAMMING M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,

9. Program using Strings.


AIM:
To create a python program to check whether the given string is palindrome or not , using
Strings.

ALGORITHM:
Step 1: Start the program.
Step 2: Define the function (isPalindrome(string)).
Step 3: Check the condition (if(string == string[::-1)) if it’s true means print the given string is
palindrome otherwise print the given string is not palindrome.
Step 4: Read the user input string and pass the input to function(ispalindrome(string)) and print the
function returned output.
Step 5: Stop the program.

FLOWCHART:

ARIGNAR ANNA COLLEGE (ARTS & SCIENCE )-KRISHNAGIRI 154


I BCA – PYTHON PROGRAMMING M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,

PROGRAM:
print('Palindrome Checking using Strings\n')
def isPalindrome(string):
if(string == string[::-1]) :
return'The given string is a palindrome.'
else:
return'The given string is not a palindrome.'
string = input('Enter the input string:')
print(isPalindrome(string))

OUTPUT:
Palindrome Checking using Strings
Enter the input string: AMMA
The given string is a palindrome.

Palindrome Checking using Strings


Enter the input string: Nareshkumar
The given string is not a palindrome.

RESULT:

Thus the above program has executed successfully and outputs are verified.

ARIGNAR ANNA COLLEGE (ARTS & SCIENCE )-KRISHNAGIRI 155


I BCA – PYTHON PROGRAMMING M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,

10. Program using Modules

AIM:
To create a python program to generate the Fibonacci series using modules.

ALGORITHM:
Step 1: Start the program.
Step 2: Create a module Fibonacci , Inside the module define the function (fib(nturms)).
Step 3: Inside the function declare the required variables and check the condition if(nterms<=0) if
it’s true means please enter positive integer will be printed otherwise go for next step
Step 4: Check (if(nterms == 1)) then print the (n1) value otherwise check the while loop
(while(count<nterms)) inside the loop body print (n1) value and do the following
assignments(nth = n1 + n2 , n1 = n2 , n2 = nth) then increase the count value by 1 up to the
while condition getting false onwards.
Step 5: Import the above module to another program.
Step 6: Read the user input value and pass it to the module (Fibonacci.fib(num)) then print the output
of the module.
Step 7: Stop the program.

FLOWCHART:

ARIGNAR ANNA COLLEGE (ARTS & SCIENCE )-KRISHNAGIRI 156


I BCA – PYTHON PROGRAMMING M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,

PROGRAM:
# Module (fibonacci.py)
def fib(nterms):
n1, n2 = 0, 1
count = 0
if (nterms <= 0):
print('Please enter a positive integer ')
elif (nterms == 1):
print('Fibonacci sequence upto',nterms,':')
print(n1)
else:
print('Fibonacci sequence:')
while (count < nterms):
print(n1)
nth = n1 + n2
n1 = n2
n2 = nth
count += 1

fibprog.py
import fibonacci
print('Fibonacci Series using Modules\n')
num=int(input('Enter any number to print Fibonacci series : '))
fibonacci.fib(num)

ARIGNAR ANNA COLLEGE (ARTS & SCIENCE )-KRISHNAGIRI 157


I BCA – PYTHON PROGRAMMING M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,

OUTPUT:
Fibonacci Series using Modules
Enter any number to print Fibonacci series : 6
Fibonacci sequence:
0
1
1
2
3
5

RESULT:

Thus the above program has executed successfully and outputs are verified.

ARIGNAR ANNA COLLEGE (ARTS & SCIENCE )-KRISHNAGIRI 158


I BCA – PYTHON PROGRAMMING M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,

11. Program using Lists.

AIM:
To create a python program for searching the element in given list using Lists.

ALGORITHM:
Step 1: Start the program.
Step 2: Read the elements from the user input and evaluate then store the inputs in lst variable.
Step 3: Calculate the length of the created list and Read the searching element from the user input
and assign to element variable.
Step 4: Do the for loop condition (for i in range (0,length)).
Step 5: Inside the for loop body check the condition (if(element= = lst[i])) if it’s true means print the
searching element present in the list otherwise break the above process, then print searching
element is presented in the list.
Step 6: Stop the program.

FLOWCHART:

ARIGNAR ANNA COLLEGE (ARTS & SCIENCE )-KRISHNAGIRI 159


I BCA – PYTHON PROGRAMMING M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,

PROGRAM:
print('Searching Element in List\n')
lst=eval(input('Enter list:'))
length=len(lst)
element=int(input('Enter element to be searched for:'))
for i in range(0,length):
if element==lst[i]:
print(element,'found at index',i)
break
else:
print(element,'not found in given list')

OUTPUT:
Searching Element in List
Enter list:5,15,25,35,45,55
Enter element to be searched for:35
35 found at index 3

Searching Element in List


Enter list:2,12,22,32,42,52
Enter element to be searched for:23
23 not found in given list

RESULT:

Thus the above program has executed successfully and outputs are verified.

ARIGNAR ANNA COLLEGE (ARTS & SCIENCE )-KRISHNAGIRI 160


I BCA – PYTHON PROGRAMMING M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,

12. Program using Tuples.

AIM:
To create a python program to find the sum of given positive numbers only using Tuples.

ALGORITHM:
Step 1: Start the program.
Step 2: Read the input values from the user It may contain the positive and negative numbers where
separated by commas.
Step 3: define the function (sum_pos(*args)) , Inside the function assign initial total value tot = 0.
Step 4: Do the for loop process (for i in args) , Inside the loop body check the condition (if(i>0) then
calculate total value tot += I and return the result.
Step 5: Print the sum of positive numbers output(sum_pos(*tp)).
Step 6: Stop the program.

FLOWCHART:

ARIGNAR ANNA COLLEGE (ARTS & SCIENCE )-KRISHNAGIRI 161


I BCA – PYTHON PROGRAMMING M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,

PROGRAM
print('Find the sum of given positive Numbers only using Tuple\n')
user_input = input('Enter space-separated integers: ')
tp = tuple(int(item) for item in user_input.split())
def sum_pos(*args):
tot = 0
for i in args:
if (i>0):
tot += i
return tot
print('The sum of Positive Numbers =',sum_pos(*tp))

OUTPUT:
Find the sum of given positive Numbers only using Tuple
Enter space-separated integers: 10 -20 35 -40 55 60 -32 25
The sum of Positive Numbers = 185

RESULT:

Thus the above program has executed successfully and outputs are verified.

ARIGNAR ANNA COLLEGE (ARTS & SCIENCE )-KRISHNAGIRI 162


I BCA – PYTHON PROGRAMMING M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,

13. Program using Dictionaries.

AIM:
To create a python program to print the employee salary details using Dictionary.

ALGORITHM:
Step 1: Start the program.
Step 2: Create a dictionary employees={ } and get maximum length of the dictionary.
Step 3: Do the while condition (while(len(employees)<max_length)) , Inside the loop body read the
employees name and salary details.
Step 4: Check the condition(if name not in employees) then assign employees[name]=salary and
print employees dictionary details.
Step 5: Check the condition (if employees[key]= = max(employees.values( ))) and print which
employees getting high salary.
Step 6: Stop the program.

FLOWCHART:

ARIGNAR ANNA COLLEGE (ARTS & SCIENCE )-KRISHNAGIRI 163


I BCA – PYTHON PROGRAMMING M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,

PROGRAM:
print('Employee salary details checking using Dictionary\n')
employees = { }
max_length = int(input('Please enter the Employees count: '))
while (len(employees) < max_length):
name = input('Enter employees name: ')
salary = input('Enter employees salary: ')
if name not in employees:
employees[name] = salary
print(employees)
print('The highest salary getting employee is')
print([key for key in employees.keys() if employees[key]==max(employees.values())])

OUTPUT:
Employee salary details checking using Dictionary
Please enter the Employees count: 3
Enter employees name: S.Prasanth
Enter employees salary: 30000
Enter employees name: K.Sathishwaran
Enter employees salary: 45000
Enter employees name: N.Anmol
Enter employees salary: 50000
{S.'Prasanth': '30000', 'K.Sathishwaran': '45000', 'N.Anmol': '50000'}
The highest salary getting employee is
['N.Anmol']

RESULT:
Thus the above program has executed successfully and outputs are verified.

ARIGNAR ANNA COLLEGE (ARTS & SCIENCE )-KRISHNAGIRI 164


I BCA – PYTHON PROGRAMMING M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,

14. Program for File Handling.

AIM:
To create a python program to copied the content from another file using Files.

ALGORITHM:
Step 1: Start the program.
Step 2: Import sys module, Read the input filename with its extension.
Step 3: Open the source file and write the content into the source file using writelines statement.
Step 4: Open the file1.txt in ‘r’ and file2.txt in ‘w’ mode.
Step 5: Assign num = 1 , Do the for loop (for line in file1) inside the loop body write the contents
into file2.txt and increase num = num +1.
Step 6: Close file1 , file2.
Step 7: Open file2.txt and read the contents from the file and print the contents in to user output
screen then close file2.txt.
Step 8: Stop the program.

FLOWCHART:

ARIGNAR ANNA COLLEGE (ARTS & SCIENCE )-KRISHNAGIRI 165


I BCA – PYTHON PROGRAMMING M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,

PROGRAM:
import sys
print('Copied the contents from one file into another file using File Methods\n')
file_name = input('Filename with extension, e.g. example.txt: ')
print('Press CTRL + D (Unix) or CTRL + Z (Windows) to exit')
with open(file_name, 'w', encoding='utf-8') as my_file:
my_file.writelines(sys.stdin.readlines( ))
file1 = open('file1.txt','r')
file2 = open('file2.txt','w')
num = 1
for line in file1:
file2.write(str(num) + ': ' +line)
num = num + 1
file1.close( )
file2.close( )
file2 = open('file2.txt','r')

ARIGNAR ANNA COLLEGE (ARTS & SCIENCE )-KRISHNAGIRI 166


I BCA – PYTHON PROGRAMMING M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,

print('File2 contents are copied from file1 suessfully!')


print('File2 copied contents are')
cons = file2.read( )
conlines = cons.split('\n')
for lines in conlines:
print(lines)
file2.close( )

OUTPUT:
Copied the contents from one file into another file using File Methods
Filename with extension, e.g. example.txt: file1.txt
Press CTRL + D (Unix) or CTRL + Z (Windows) to exit
ARIGNAR ANNA COLLEGE
WELCOME TO BCA
^Z
File2 contents are copied from file1 suessfully!
File2 copied contents are
1: ARIGNAR ANNA COLLEGE
2: WELCOME TO BCA

RESULT:
Thus the above program has executed successfully and outputs are verified.

ARIGNAR ANNA COLLEGE (ARTS & SCIENCE )-KRISHNAGIRI 167

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