Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
115 views

Python

Python is an interpreted, high-level programming language created by Guido van Rossum in 1991. It emphasizes code readability and allows programmers to express concepts in fewer lines of code compared to languages like C++ and Java. Python supports object-oriented, imperative, and functional programming. It has a large standard library and is free, open-source, and platform independent. Variables in Python are containers that store values and do not require declaration or type specification. A variable name starts with a letter or underscore and can contain alphanumeric characters and underscores.

Uploaded by

sivamahen143
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
115 views

Python

Python is an interpreted, high-level programming language created by Guido van Rossum in 1991. It emphasizes code readability and allows programmers to express concepts in fewer lines of code compared to languages like C++ and Java. Python supports object-oriented, imperative, and functional programming. It has a large standard library and is free, open-source, and platform independent. Variables in Python are containers that store values and do not require declaration or type specification. A variable name starts with a letter or underscore and can contain alphanumeric characters and underscores.

Uploaded by

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

DON BOSCO COLLEGE DHARMAPURI

UNIT -I
Python-origins-features-variables and assignment -python basics-statement and syntax-
identifiers-basic style guidelines -python objects-standard types and other built -in types-internal
types -standard type operators-standard type built-in functions.
Python:

❖ PYTHON is a widely used general-purpose, high level programming language. It was


created by Guido van Rossum in 1991 and further developed by the Python Software
Foundation. It was designed with an emphasis on code readability, and its syntax allows
programmers to express their concepts in fewer lines of code.
❖ Python is a programming language that lets you work quickly and integrate systems
more efficiently.
❖ There are two major Python versions: Python 2 and Python 3. Both are quite different.
Origins:

❖ Work on Python began in late 1989 by Guido van Rossum, then at CWI (Centrum voor
Wiskunde en Informatica, the National Research Institute for Mathematics and Computer
Science) in the Netherlands. It was eventually released for public distribution in early
1991. How did it all begin? Like C, C++, Lisp, Java, and Perl, Python came from a
research background where the programmer was having a hard time getting the job done
with the existing tools at hand, and envisioned and developed a better way.
❖ At the time, van Rossum was a researcher with considerable language design experience
with the interpreted language ABC, also developed at CWI, but he was unsatisfied with
its ability to be developed into something more. Having used and partially developed a
higher-level language like ABC, falling back to C was not an attractive possibility. Some
of the tools he envisioned were for performing general system administration tasks, so he
also wanted access to the power of system calls that were available through the Amoeba
distributed operating system. Although van Rossum gave some thought to an Amoeba-
specific language, a generalized language made more sense, and late in 1989, the seeds of
Python were sown.
Beginning with Python programming:

Finding an Interpreter:

❖ Before we start Python programming, we need to have an interpreter to interpret and


run our programs. There are certain online interpreters
like https://ide.geeksforgeeks.org/ that can be used to run Python programs without
installing an interpreter.
❖ Windows: There are many interpreters available freely to run Python scripts like IDLE
(Integrated Development Environment) that comes bundled with the Python software
downloaded from http://python.org/.
DON BOSCO COLLEGE DHARMAPURI

❖ Linux: Python comes preinstalled with popular Linux distros such as Ubuntu and
Fedora. To check which version of Python you’re running, type “python” in the
terminal emulator. The interpreter should start and print the version number.
❖ macOS: Generally, Python 2.7 comes bundled with macOS. You’ll have to manually
install Python 3 from http://python.org/.
Writing our first program:
Just type in the following code after you start the interpreter.
print(“hello world”)
Output:
Hello world
Let’s analyze the script line by line.
Line 1: [# Script Begins] In Python, comments begin with a #. This statement is ignored by
the interpreter and serves as documentation for our code.
Line 2: [print(“GeeksQuiz”)] To print something on the console, print() function is used. This
function also adds a newline after our message is printed(unlike in C). Note that in Python 2,
“print” is not a function but a keyword and therefore can be used without parentheses.
However, in Python 3, it is a function and must be invoked with parentheses.
Line 3: [# Script Ends] This is just another comment like in Line 1.
Python designed by Guido van Rossum at CWI has become a widely used general-purpose,
high-level programming language.
Prerequisites:
Knowledge of any programming language can be a plus.

Reason for increasing popularity

1. Emphasis on code readability, shorter codes, ease of writing


2. Programmers can express logical concepts in fewer lines of code in comparison to
languages such as C++ or Java.
3. Python supports multiple programming paradigms, like object-oriented, imperative
and functional programming or procedural.
4. There exists inbuilt functions for almost all of the frequently used concepts.
5. Philosophy is “Simplicity is the best”.

LANGUAGE FEATURES

Interpreted
• There are no separate compilation and execution steps like C and C++.
• Directly run the program from the source code.
• Internally, Python converts the source code into an intermediate form
called bytecodes which is then translated into native language of specific
computer to run it.
• No need to worry about linking and loading with libraries, etc.
DON BOSCO COLLEGE DHARMAPURI

❖ Platform Independent
• Python programs can be developed and executed on multiple operating
system platforms.
• Python can be used on Linux, Windows, Macintosh, Solaris and many
more.
❖ Free and Open Source; Redistributable
❖ High-level Language
• In Python, no need to take care about low-level details such as managing
the memory used by the program.
❖ Simple
• Closer to English language;Easy to Learn
• More emphasis on the solution to the problem rather than the syntax
❖ Embeddable
• Python can be used within C/C++ program to give scripting capabilities
for the program’s users.
❖ Robust:
• Exceptional handling features
• Memory management techniques in built
❖ Rich Library Support
• The Python Standard Library is very vast.
• Known as the “batteries included” philosophy of Python ;It can help do
various things involving regular expressions, documentation generation,
unit testing, threading, databases, web browsers, CGI, email, XML,
HTML, WAV files, cryptography, GUI and many more.
• Besides the standard library, there are various other high-quality libraries
such as the Python Imaging Library which is an amazingly simple image
manipulation library.
Python Variables:
❖ Python Variable is containers that store values. Python is not “statically typed”. We do
not need to declare variables before using them or declare their type. A variable is
created the moment we first assign a value to it. A Python variable is a name given to a
memory location. It is the basic unit of storage in a program. In this article, we will see
how to define a variable in Python.
Example of Variable in Python:

❖ An Example of a Variable in Python is a representational name that serves as a pointer


to an object. Once an object is assigned to a variable, it can be referred to by that name.
In layman’s terms, we can say that Variable in Python is containers that store values.
❖ Here we have stored “Geeksforgeeks” in a variable var, and when we call its name the
stored information will get printed.

Var = "Geeksforgeeks"
print(Var)

Output:
Geeksforgeeks
DON BOSCO COLLEGE DHARMAPURI

Notes:
•The value stored in a variable can be changed during program execution.
•A Variables in Python is only a name given to a memory location, all the operations
done on the variable effects that memory location.
Rules for Python variables
• A Python variable name must start with a letter or the underscore character.
• A Python variable name cannot start with a number.
• A Python variable name can only contain alpha-numeric characters and underscores
(A-z, 0-9, and _ ).
• Variable in Python names are case-sensitive (name, Name, and NAME are three
different variables).
• The reserved words(keywords) in Python cannot be used to name the variable in
Python.
Example :

# valid variable name


geeks = 1
Geeks = 2
Ge_e_ks = 5
_geeks = 6
geeks_ = 7
_GEEKS_ = 8

print(geeks, Geeks, Ge_e_ks)


print(_geeks, geeks_, _GEEKS_)

Output:
125
678

Variables Assignment in Python:


Here, we will define a variable in python. Here, clearly we have assigned a number, a floating
point number, and a string to a variable such as age, salary, and name.
DON BOSCO COLLEGE DHARMAPURI

# An integer assignment
age = 45

# A floating point
salary = 1456.8

# A string
name = "John"

print(age)
print(salary)
print(name)

Output:
45
1456.8
John
Declaration and Initialization of Variables:

Let’s see how to declare a variable and how to define a variable and print the variable.

# declaring the var


Number = 100

# display
print( Number)
Output:
100
Redeclaring variables in Python
We can re-declare the Python variable once we have declared the variable and define variable
in python already.

# declaring the var


Number = 100

# display
print("Before declare: ", Number)

# re-declare the var


Number = 120.3

print("After re-declare:", Number)


DON BOSCO COLLEGE DHARMAPURI

Output:
Before declare: 100
After re-declare: 120.3

Python Assign Values to Multiple Variables:


• Also, Python allows assigning a single value to several variables simultaneously with
“=” operators.
For example:

a = b = c = 10
print(a)
print(b)
print(c)

Output:
10
10
10
Assigning different values to multiple variables:
• Python allows adding different values in a single line with “,” operators.

a, b, c = 1, 20.2, "GeeksforGeeks"
print(a)
print(b)
print(c)

Output:
1
20.2
GeeksforGeeks

Python basics:

• Python is a high-level, general-purpose, and very popular programming language. Python


programming language (latest Python 3) is being used in web development, Machine
Learning applications, along with all cutting-edge technology in Software Industry.
• Python language is being used by almost all tech-giant companies like – Google, Amazon,
Facebook, Instagram, Dropbox, Uber… etc.
• The biggest strength of Python is huge collection of standard library which can be used for
the following:
DON BOSCO COLLEGE DHARMAPURI

• Machine Learning
• GUI Applications (like Kivy, Tkinter, PyQt etc. )
• Web frameworks like Django (used by YouTube, Instagram, Dropbox)
• Image processing (like OpenCV, Pillow)
• Web scraping (like Scrapy, BeautifulSoup, Selenium)
• Test frameworks
• Multimedia
• Scientific computing
• Text processing and many more..

Statements and Syntax

Some rules and certain symbols are used with regard to statements in Python:

• Hash mark ( # ) indicates Python comments

• NEWLINE ( \n ) is the standard line separator (one statement per line)

• Backslash ( \ ) continues a line

• Semicolon ( ; ) joins two statements on a line

• Colon ( : ) separates a header line from its suite

• Statements (code blocks) grouped as suites

• Suites delimited via indentation

• Python files organized as “modules”


We will also discuss different rules and examples for Python Statement, Python Indentation,
Python Comment, and the Difference Between ‘Docstrings’ and ‘Multi-line Comments.
What is Statement in Python:

• A Python statement is an instruction that the Python interpreter can execute. There are
different types of statements in Python language as Assignment statements,
Conditional statements, Looping statements, etc. The token character NEWLINE is
used to end a statement in Python. It signifies that each line of a Python script contains
a statement. These all help the user to get the required output.
DON BOSCO COLLEGE DHARMAPURI

Types of statements in Python?

The different types of Python statements are listed below:


• Multi-Line Statements
• Python Conditional and Loop Statements
• Python If-else
• Python for loop
• Python while loop
• Python try-except
• Python with statement
• Python Expression statements
• Python pass statement
• Python del statement
• Python return statement
• Python import statement
• Python continue and
• Python break statement
Example:
• Statement in Python can be extended to one or more lines using parentheses (), braces
{}, square brackets [], semi-colon (;), and continuation character slash (\). When the
programmer needs to do long calculations and cannot fit his statements into one line,
one can make use of these characters.
Declared using Continuation Character (\):
s=1+2+3+\
4+5+6+\
7+8+9

Declared using parentheses () :


n = (1 * 2 * 3 + 7 + 8 + 9)

Declared using square brackets [] :


footballer = ['MESSI',
'NEYMAR',
'SUAREZ']
Declared using braces {} :
x = {1 + 2 + 3 + 4 + 5 + 6 +
7 + 8 + 9}
DON BOSCO COLLEGE DHARMAPURI

Declared using semicolons(;)


flag = 2; ropes = 3; pole = 4
Types of comments in Python:

• A comment can be written on a single line, next to the corresponding line of code, or in
a block of multiple lines. Here, we will try to understand examples of comment in
Python one by one:
Single-line comment in Python:

• Python single-line comment starts with a hash 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 comment. 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 1:
Python allows comments at the start of lines, and Python will ignore the whole line.

# This is a comment
# Print “GeeksforGeeks” to console
print("GeeksforGeeks")

Output
GeeksforGeeks
Example 2:
Python also allows comments at the end of lines, ignoring the previous text.

a, b = 1, 3 # Declaring two integers


sum = a + b # adding two integers
print(sum) # displaying the output

Output
4
Multiline comment in Python
• Use a hash (#) for each extra line to create a multiline comment. In fact, Python
multiline comments are not supported by Python’s syntax. Additionally, we can use
Python multi-line comments by using multiline strings. It is a piece of text enclosed in a
delimiter (“””) on each end of the comment.
DON BOSCO COLLEGE DHARMAPURI

• Again there should be no white space between delimiter (“””). They are useful when
the comment text does not fit into one line; therefore need to span across lines. Python
Multi-line comments or paragraphs serve as documentation for others reading your
code. See the following code snippet demonstrating a multi-line comment:
Example 1:
In this example, we are using an extra # for each extra line to create a Python multiline
comment.

# This is a comment
# This is second comment
# Print “GeeksforGeeks” to console
print("GeeksforGeeks")

Output
GeeksforGeeks
Example 2:
In this example, we are using three double quotes (“) at the start and end of the string without
any space to create a Python multiline comment.


"""
print("GeeksForGeeks")

Output
GeeksForGeeks
Example 3:
In this example, we are using three single quotes (‘) at the start and end of the string without
any space to create a Python multiline comment.

'''This article on geeksforgeeks gives you a


perfect example of
multi-line comments'''
print("GeeksForGeeks")

Output
GeeksForGeeks
DON BOSCO COLLEGE DHARMAPURI

Docstring in Python:
• Python Docstrings are a type of comment that is used to show how the program works.
Docstrings in Python are surrounded by Triple Quotes in Python (“”” “””). Docstrings
are also neglected by the interpreter.

# program illustrates the use of docstrings


def helloWorld():
# This is a docstring comment
""" This program prints out hello world """
print("Hello World")
helloWorld()

Output
Hello World

Difference Between ‘Docstrings’ and ‘Multi-line Comments :

Docstrings and Multi-line comments may look the same but they aren’t.
• Docstrings are written in the functions and classes to show how to use the program.
• Multi-line comments are used to show how a block of code works.

Don't miss your chance to ride the wave of the data revolution! Every industry is scaling new
heights by tapping into the power of data. Sharpen your skills, become a part of the hottest
trend in the 21st century.
Dive into the future of technology - explore the Complete Machine Learning and Data Science
Program by GeeksforGeeks and stay ahead of the curve.
Python if statement:

The if statement is the most simple decision-making statement. It is used to decide whether a
certain statement or block of statements will be executed or not.
Syntax:
if condition:
# Statements to execute if
# condition is true
• Here, the condition after evaluation will be either true or false. if the statement accepts
boolean values – if the value is true then it will execute the block of statements below it
otherwise not.
• As we know, python uses indentation to identify a block. So the block under an if
statement will be identified as shown in the below example:
DON BOSCO COLLEGE DHARMAPURI

if condition:
statement1
statement2
# Here if the condition is true, if block
# will consider only statement1 to be inside
# its block.
Example of Python if Statement
• As the condition present in the if statement is false. So, the block below the if statement
is executed.

i = 10
if (i > 15):
print("10 is less than 15")
print("I am Not in if")

Output:
I am Not in if

Python If-Else Statement:

• The if statement alone tells us that if a condition is true it will execute a block of
statements and if the condition is false it won’t. But if we want to do something else if
the condition is false, we can use the else statement with the if statement to execute a
block of code when the if condition is false.
Syntax of Python If-Else:
if (condition):
# Executes this block if
# condition is true
else:
# Executes this block if
# condition is false
Using Python if-else statement:
• The block of code following the else statement is executed as the condition present in the
if statement is false after calling the statement which is not in the block(without spaces).
DON BOSCO COLLEGE DHARMAPURI

# python program to illustrate If else statement


#!/usr/bin/python
i = 20
if (i < 15):
print("i is smaller than 15")
print("i'm in if Block")
else:
print("i is greater than 15")
print("i'm in else Block")
print("i'm not in if and not in else Block")

Output:
i is greater than 15
i'm in else Block
i'm not in if and not in else Block

Identifiers in Python:

Identifier is a user-defined name given to a variable, function, class, module, etc. The
identifier is a combination of character digits and an underscore. They are case-sensitive i.e.,
‘num’ and ‘Num’ and ‘NUM’ are three different identifiers in python. It is a good
programming practice to give meaningful names to identifiers to make the code
understandable.
We can also use the Python string isidentifier() method to check whether a string is a valid
identifier or not.
Rules for Naming Python Identifiers
• It cannot be a reserved python keyword.
• It should not contain white space.
• It can be a combination of A-Z, a-z, 0-9, or underscore.
• It should start with an alphabet character or an underscore ( _ ).
• It should not contain any special character other than an underscore ( _ ).
Examples of Python Identifiers
Valid identifiers:
• var1
• _var1
• _1_var
• var_1
Invalid Identifiers
• !var1
• 1var
DON BOSCO COLLEGE DHARMAPURI

• 1_var
• var#1
• var 1
Python Keywords and Identifiers Examples
Example 1: Example of and, or, not, True, False keywords.

print("example of True, False, and, or, not keywords")


# compare two operands using and operator
print(True and True)
# compare two operands using or operator
print(True or False)
# use of not operator
print(not False)

Output
example of True, False, and, or, not keywords
True
True
True
Example 2: Example of a break, continue keywords and identifier.

# execute for loop


for i in range(1, 11):
# print the value of i
print(i)
# check the value of i is less than 5
# if i lessthan 5 then continue loop
if i < 5:
continue
# if i greater than 5 then break loop
else:
break
DON BOSCO COLLEGE DHARMAPURI

Output
1
2
3
4
5
Basic style guidelines:
• PEP 8 has emerged as the style guide that most projects adhere to; it promotes a very
readable and eye-pleasing coding style. Every Python developer should read it at some
point; here are the most important points extracted for you
1. Use 4-space indentation and no tabs.
Examples:
# Aligned with opening delimiter.
grow = function_name(variable_one, variable_two,
variable_three, variable_four)
# First line contains no argument. Second line onwards
# more indentation included to distinguish this from
# the rest.
def function_name(
variable_one, variable_two, variable_three,
variable_four):
print(variable_one)
The 4 space rule is not always mandatory and can be overruled for continuation line.
2. Use docstrings :
• There are both single and multi-line docstrings that can be used in Python. However,
the single line comment fits in one line, triple quotes are used in both cases. These are
used to define a particular program or define a particular function.
Example:
def exam():
"""This is single line docstring"""

"""This is
a
multiline comment"""
DON BOSCO COLLEGE DHARMAPURI

3. Wrap lines so that they don’t exceed 79 characters :


• The Python standard library is conservative and requires limiting lines to 79 characters.
The lines can be wrapped using parenthesis, brackets, and braces. They should be used
in preference to backslashes.
Example:
with open('/path/from/where/you/want/to/read/file') as file_one, \
open('/path/where/you/want/the/file/to/be/written', 'w') as file_two:
file_two.write(file_one.read())

5. Use of trailing commas : This is not mandatory except while making a tuple.
Example:
tup = ("geek",)

6. Using spaces

• It's one of the best practices to use a space before and after an operator. Use a space after
the comma as well for more readability.

Example:
import random
result = random.randint(1, 3) + random.randint(1, 2)

7. Naming Variables, Constants, Classes and Functions

• Follow the same case for variables, constants, classes and functions across the program.
Most of the Python users will use snake_case for functions and variables naming
and PascalCase for classes naming. For constants, use all uppercase letter separated with
underscores (ex:- PI_TWO).

snake_case => this_is_function

PascalCase => ThisIsClass

CONSTANT => THIS_IS_CONSTANT

8. Importing one module at a time

• Don't try to import multiple modules in a single even though it is syntactically correct. See
the example below.
DON BOSCO COLLEGE DHARMAPURI

# don't
import math, random
# do
import math
import random

9. Comment updating

• Always keep your comments up to date. Don't forget to update the comments while
updating code. It's one of the most important things in coding. And most of the user will
forget it. Keep this in mind.

Python objects:

• An Object is an instance of a Class. A class is like a blueprint while an instance is a copy


of the class with actual values. Python is an object-oriented programming language that
stresses objects i.e. it mainly emphasizes functions. Python Objects are basically an
encapsulation of data variables and methods acting on that data into a single entity.

Syntax:
obj = MyClass()
print(obj.x)
Creating a Python Object:
Working of the Program: Audi = Cars()
• A block of memory is allocated on the heap. The size of memory allocated is
decided by the attributes and methods available in that class(Cars).
• After the memory block is allocated, the special method init__() is called
internally. Initial data is stored in the variables through this method.
• The location of the allocated memory address of the instance is returned to the
object(Cars).
• The memory location is passed to self.
DON BOSCO COLLEGE DHARMAPURI

class Cars:
def init (self, m, p):
self.model = m
self.price = p
Audi = Cars("R8", 100000)
print(Audi.model)
print(Audi.price)

Output:
R8
100000
Standard types and other built-in types:

• You'll learn about Python Data Types and their uses in this post as we efficiently write
Python programs. You will learn about their purpose, syntax, and how to apply them in
programs through examples. The language Python requires no introduction. It is highly
strong, adaptable, quick, and simple to learn.
• One of the languages that continue to expand and gain popularity year after year is
Python. Python is an object-oriented, interpreted computer language used for general-
purpose programming. This tutorial will teach us about the various data types in the Python
programming language.

Built-in Data Types in Python

There are different types of data types in Python. Some built-in Python data types are −

• Numeric data types − int, float, complex


• String data types − str
• Sequence types − list, tuple, range
• Binary types − bytes, bytearray, memoryview
• Mapping data type − dict
• Boolean type − bool
• Set data types − set, frozenset
DON BOSCO COLLEGE DHARMAPURI

Python Numeric Data types:

In Python, the numeric data type is used to hold numeric values.

Integers, floating-point, and complex numbers fall under the Python numbers category. They are
defined as int, float, and complex classes in Python.

• int − holds signed integers of non-limited length.


• float − holds floating decimal points, and it's accurate up to 15 decimal places.
• complex − holds complex numbers.

Python String Data type:

• A string is a collection of Unicode symbols. The name for String in Python is str. Single or
double quotations are used to represent strings. The use of triple quotes """ or "'” to indicate
multiple strings is acceptable. Between the quotations, every character is a part of the
string.
• The only restriction is the machine system's memory resources, which one may use as many
characters as they like. In Python programming, deleting or updating a string will result in
an error. As a result, the Python programming language does not permit the alteration of
strings.

Python Sequence Data types:

• List − The list is a flexible data type only available in Python. It resembles the array in
C/C++ in certain ways. However, the list in Python is noteworthy because it can store many
sorts of data simultaneously. A list is an ordered collection of information expressed using
commas and square brackets ([]). (,).
• Tuple − The list and a tuple are comparable in many respects. Tuples hold a collection of
elements of various data kinds, much like lists do. The tuple's components are separated
by commas (,) and parenthesized (). Due to the inability to change the elements' size and
value, tuples are read-only data structures.
• Range − The range() method in Python returns a list of integers that fall inside a specified
range. It is most frequently used to iterate over a series of integers using Python loops.
DON BOSCO COLLEGE DHARMAPURI

Python Data Binary types:

• bytes − A bytes object results from the bytes() function. It can produce empty byte objects
of the desired size or transform items into byte objects. Bytes() and bytearray() return
different types of objects: bytes() returns an immutable object, whereas bytearray() returns
an alterable object.
• bytearray − The bytearray object, an array of the specified bytes, is returned by the
bytearray() function. A modifiable series of numbers from 0 to x to 256 is provided.
• memoryview − Python programs may access an object's internal data that implements the
buffer protocol using memoryview objects without copying. The byte-oriented data of an
object may be read and written directly without copying it using the memoryview()
method.

Python Mapping Data type:

• dict − A dictionary in Python is a collection of data items that are stored in an unordered
fashion, much like a map. Dictionaries are made up of key-value pairs, as contrast to other
data types, which can only contain a single value. Key-value pairs are included in the
dictionary to increase its efficiency. A comma "separates each key," whereas each key-
value pair in the representation of a dictionary data type is separated by a colon.

Python Boolean Data type:

• bool − True and False are the two pre-built values the boolean type offers. The provided
statement's truth or falsity is determined using these values. It's identified by the bool class.
Any non-zero integer or the letter "T" can be used to denote truth, while the number "0" or
the letter "F" can denote falsehood.

Python Set Data types:

• set − The data type's unordered collection is called a Python Set. It has components that
are unique, iterable, and changeable (may change after creation). The order of the items in
a set is ambiguous; it can yield the element's modified sequence. Use the built-in method
set() to build the set, or give a list of elements enclosed in curly braces and separated by
commas. It may include several kinds of values.
• frozenset − The frozenset() method returns an immutable frozenset object whose initial
elements are taken from the supplied iterable.
DON BOSCO COLLEGE DHARMAPURI

• A frozen set is an immutable version of a Python set object. The elements of a set can be
altered at any time, but once a frozen set has been created, its elements cannot be altered.
• Example Data Type

x = "Hello World" str

x = 20 int

x = 20.5 float

x = 1j complex

x = ["apple", "banana", "cherry"] list

x = ("apple", "banana", "cherry") tuple

x = range(6) range

x = {"name" : "John", "age" : 36} dict

x = {"apple", "banana", "cherry"} set

x = frozenset({"apple", "banana", "cherry"}) frozenset

x = True bool

x = b"Hello" bytes

x = bytearray(5) bytearray

x = memoryview(bytes(5)) memoryview

x = None NoneType

Python Operators:
• In Python programming, Operators in general are used to perform operations on values and
variables. These are standard symbols used for the purpose of logical and arithmetic operations. In
this article, we will look into different types of Python operators.
• OPERATORS: These are the special symbols. Eg- + , * , /, etc.
• OPERAND: It is the value on which the operator is applied.
DON BOSCO COLLEGE DHARMAPURI

Types of Operators in Python


1. Arithmetic Operators
2. Comparison Operators
3. Logical Operators
4. Bitwise Operators
5. Assignment Operators
6. Identity Operators and Membership Operators
Arithmetic Operators in Python:
• Python Arithmetic operators are used to perform basic mathematical operations
like addition, subtraction, multiplication, and division.
• In Python 3.x the result of division is a floating-point while in Python 2.x division of 2
integers was an integer. To obtain an integer result in Python 3.x floored (// integer) is used.
Operator Description Syntax

Addition: adds two


+ x+y
operands

Subtraction: subtracts two


– x–y
operands

Multiplication: multiplies
* x*y
two operands

Division (float): divides the


/ x/y
first operand by the second

Division (floor): divides the


// x // y
first operand by the second

Modulus: returns the


remainder when the first
% x%y
operand is divided by the
second

Power: Returns first raised


** x ** y
to power second

There are two types of division operators:


1. Float division
2. Floor division
DON BOSCO COLLEGE DHARMAPURI

Float division:
• The quotient returned by this operator is always a float number, no matter if two numbers
are integers. For example

print(5/5)
print(10/2)
print(-10/2)
print(20.0/2)
Output:
1.0
5.0
-5.0
10.0
Integer division( Floor division):
• The quotient returned by this operator is dependent on the argument being passed. If any
of the numbers is float, it returns output in float. It is also known as Floor division
because, if any number is negative, then the output will be floored. For example:

print(10//3)
print (-5//2)
print (5.0//2)
print (-5.0//2)
Output:
3
-3
2.0
-3.0
Arithmetic Operators With Addition, Subtraction, Multiplication, Modulo and Power:
• Here is an example showing how different Arithmetic Operators in Python work:

Example: The code performs basic arithmetic operations with the values of ‘a' and ‘b'. It
adds (‘+'), subtracts (‘-'), multiplies (‘*'), computes the remainder (‘%'), and raises a to the
power of ‘b (**)’. The results of these operations are printed.
DON BOSCO COLLEGE DHARMAPURI

a=9
b=4
add = a + b
sub = a - b
mul = a * b
mod = a % b
p = a ** b
print(add)
print(sub)
print(mul)
print(mod)
print(p)

Output:
13
5
36
1
6561
Comparison Operators in Python
• In Python Comparison of Relational operators compares the values. It either
returns True or False according to the condition.
Operator Description Syntax

Greater than: True if the left


> x>y
operand is greater than the right

Less than: True if the left operand is


< x<y
less than the right

Equal to: True if both operands are


== x == y
equal

Not equal to – True if operands are


!= x != y
not equal
DON BOSCO COLLEGE DHARMAPURI

Operator Description Syntax

Greater than or equal to True if the


>= left operand is greater than or equal x >= y
to the right

Less than or equal to True if the left


<= operand is less than or equal to the x <= y
right

= is an assignment operator and == comparison operator.

Example of Comparison Operators in Python:

• Let’s see an example of Comparison Operators in Python.

Example: The code compares the values of ‘a' and ‘b' using various comparison operators and
prints the results. It checks if ‘a' is greater than, less than, equal to, not equal to, greater than or
equal to, and less than or equal to ‘b'.

a = 13
b = 33
print(a > b)
print(a < b)
print(a == b)
print(a != b)
print(a >= b)
print(a <= b)

Output
False
True
False
True
False
True
DON BOSCO COLLEGE DHARMAPURI

Logical Operators in Python:


• Python Logical operators perform Logical AND, Logical OR, and Logical
NOT operations. It is used to combine conditional statements.
Operator Description Syntax

Logical AND: True if both


and x and y
the operands are true

Logical OR: True if either of


or x or y
the operands is true

Logical NOT: True if the


not not x
operand is false

Example of Logical Operators in Python:

• The following code shows how to implement Logical Operators in Python:

Example: The code performs logical operations with Boolean values. It checks if
both ‘a' and ‘b' are true (‘and'), if at least one of them is true (‘or'), and negates the value
of ‘a' using ‘not'. The results are printed accordingly.

a = True
b = False
print(a and b)
print(a or b)
print(not a)

Output
False
True
False

Bitwise Operators in Python:

• Python Bitwise operators act on bits and perform bit-by-bit operations. These are used
to operate on binary numbers.
Operator Description Syntax

& Bitwise AND x&y


DON BOSCO COLLEGE DHARMAPURI

Operator Description Syntax

| Bitwise OR x|y

~ Bitwise NOT ~x

^ Bitwise XOR x^y

>> Bitwise right shift x>>

<< Bitwise left shift x<<

Bitwise Operators in Python:


• Here is an example showing how Bitwise Operators in Python work:

Example: The code demonstrates various bitwise operations with the values of ‘a' and ‘b'. It
performs bitwise AND (&), OR (|), NOT (~), XOR (^), right shift (>>), and left shift
(<<) operations and prints the results. These operations manipulate the binary representations
of the numbers.

a = 10
b=4
print(a & b)
print(a | b)
print(~a)
print(a ^ b)
print(a >> 2)
print(a << 2)

Output
0
14
-11
14
2
40
DON BOSCO COLLEGE DHARMAPURI

Assignment Operators in Python


Python Assignment operators are used to assign values to the variables.
Operator Description Syntax

Assign the value of the right side of the expression to


= x=y+z
the left side operand

Add AND: Add right-side operand with left-side


+= a+=b a=a+b
operand and then assign to left operand

Subtract AND: Subtract right operand from left


-= a-=b a=a-b
operand and then assign to left operand

Multiply AND: Multiply right operand with left


*= a*=b a=a*b
operand and then assign to left operand

Divide AND: Divide left operand with right operand


/= a/=b a=a/b
and then assign to left operand

Modulus AND: Takes modulus using left and right


%= a%=b a=a%b
operands and assign the result to left operand

Divide(floor) AND: Divide left operand with right


//= a//=b a=a//b
operand and then assign the value(floor) to left operand

Exponent AND: Calculate exponent(raise power) value


**= a**=b a=a**b
using operands and assign value to left operand

Performs Bitwise AND on operands and assign value


&= a&=b a=a&b
to left operand
DON BOSCO COLLEGE DHARMAPURI

Operator Description Syntax

Performs Bitwise OR on operands and assign value to


|= a|=b a=a|b
left operand

Performs Bitwise xOR on operands and assign value to


^= a^=b a=a^b
left operand

Performs Bitwise right shift on operands and assign


>>= a>>=b a=a>>b
value to left operand

Performs Bitwise left shift on operands and assign a <<= b a= a <<


<<=
value to left operand b

Assignment Operators in Python:


• Let’s see an example of Assignment Operators in Python.

Example: The code starts with ‘a' and ‘b' both having the value 10. It then performs a series
of operations: addition, subtraction, multiplication, and a left shift operation on ‘b'. The results
of each operation are printed, showing the impact of these operations on the value of ‘b'.

a = 10
b=a
print(b)
b += a
print(b)
b -= a
print(b)
b *= a
print(b)
b <<= a
print(b)

Output
10
20
10
100
102400
DON BOSCO COLLEGE DHARMAPURI

Identity Operators in Python:


• In Python, is and is not are the identity operators both are used to check if two values
are located on the same part of the memory. Two variables that are equal do not imply
that they are identical.
is True if the operands are identical
is not True if the operands are not identical
Example:

a = 10
b = 20
c=a
print(a is not b)
print(a is c)

Output
True
True
Membership Operators in Python:
• In Python, in and not in are the membership operators that are used to test whether a
value or variable is in a sequence.
in True if value is found in the sequence
not in True if value is not found in the sequence
Example:

x = 24
y = 20
list = [10, 20, 30, 40, 50]

if (x not in list):
print("x is NOT present in given list")
else:
print("x is present in given list")

if (y in list):
print("y is present in given list")
else:
print("y is NOT present in given list")
Output
x is NOT present in given list
y is present in given list
DON BOSCO COLLEGE DHARMAPURI

standard type built-in functions:


• Python provides a lot of built-in functions that ease the writing of code. In this article,
you will learn about Python’s built-in functions, exploring their various applications
and highlighting some of the most commonly used ones.
1) append()
• This method adds an item at the end of the existing list, tuple, or any other set. Then, the
length of the list gets increased by one. We can append an item to the list and also list to
a list. It adds any data type which is to be added at the end of the list. It has time
complexity: O(1).
Syntax:
append(item)
• where item refers to the item needed to be appended with the existing element.
For Example:
a=[“apple”,” banana”,” mango”,” grapes”]
a.append(“orange”)
print(a)
Output:
[“apple”,” banana”,” mango”,” grapes”,” orange”]

2) reduce()

• The reduce() function applies a function of two arguments collectively on a list of objects
in succession from left to right to reduce it to one value. It is defined in a functools library.
This works better than for loop.
Syntax:
reduce(function, iterable)
• where, function refers to the function which will be used in a program, and iterable refers
to the value that will be iterated in the program.
For Example:
From functools import reduce
Def sum(a, b):
res=return (sum, [1,2,4,5])
print res
Output:
12
DON BOSCO COLLEGE DHARMAPURI

3) slice()

• This function returns the sliced object from a given set of elements. It allows you to
access any set of sequences whether it is ta tuple, list, or set. Time complexity of slice()
is O(n).
Syntax:
slice(start, stop, step)
• where start refers to the start index from where you have to copy, stop refers to the
index till where you want to slice, and step refers to the count by which you want to
skip.
For Example:
a=”Hello World”
y=slice(2,4,1)
print(y)
Output:
lo

4) sorted()

• This function sorts the given element in specified (ascending or descending) order. The
set of elements could be a list, tuple, and dictionary. The time complexity of the sorted
function is O(n.logn).
Syntax:
sorted(set of elements)
• where a set of elements refers to the elements which need to be sorted.
For Example:
a=[1,7,3,8]
y=sorted(a)
print(y)
Output:
[1,3,7,8]

5) split()

• This method breaks up the string into a list of substrings, based on the specified separator.
It returns strings as a list. By default, whitespace is the separator. Time complexity of
split() is O(n).
DON BOSCO COLLEGE DHARMAPURI

Syntax:
split(separator)
• where separator refers to the value which is to be split from the given sequence.
For Example:
a=”HelloWorld”
y=a.split(‘l’)
print(y)
Output:
['He','oWor','d']

6) eval()

• The eval() function evaluates the given expression whether it is a mathematical or logical
expression. If a string is passed through it, it parses the function, compiles it to bytecode,
and then returns the output. Since operators have no time complexity therefore eval
doesn’t have one.
Syntax:
eval(expression)
• where the expression could be any operation such as mathematical or logical.
For Example:
x=6
y=eval(‘x*8’)
print(y)
Output:
48

7) bin()

• This function converts an integer to a binary string that has the prefix 0b. Also, the integer
passed could be negative or positive. Its time complexity for a number n is O(log(n))
Syntax:
bin(integer)
• where the integer is any value passed to receive its binary form.
For Example:
print(bin(8))
Output:
0b1000
DON BOSCO COLLEGE DHARMAPURI

8) map()

• This function returns a map object(which is an iterator) of the results after applying the
given function to each item of a given iterable (list, tuple, etc.). It applies a function to
all objects in a list. The time of complexity of the map() function is O(n).
Syntax:
map(function, iterable)
• where function refers to the function which will be used in a program, iterable refers to
the value that will be iterated in the program.
For Example:
def add(x):
return x+2
x = map(add, (3, 5, 7, 11, 13))
print (x)
Output:
(2,7,9,13,15)

9) filter()

• This function creates a new iterator from an existing one (such as a list, tuple, or
dictionary) that filters elements. It checks whether the given condition is available in the
sequence or not and then prints the output. The time complexity of the filter function is
O(n).
Syntax:
filter(function, iterable)
• where function refers to the function which will be used in a program, iterable refers to
the value that will be iterated in the program.
For Example:
c = [‘Ant’,’Lizard’,’Mosquito’,’Snake’]
def vowels(x):
return x[0].lower() in ‘aeiou’
items = filter(vowels, c)
print(list(items))
Output:
['Ant']
DON BOSCO COLLEGE DHARMAPURI

10) exec()

• This function executes the given condition and prints the output in python expression. It
executes the program dynamically Python exec() function executes the dynamically
created program, which is either a string or a code object. If it is a string, then it is parsed
as a Python statement and then executed; else, a syntax error occurs.
Syntax:
exec(object[, globals[, locals]])
• where the object can be a string or object code, globals can be a dictionary and the
parameter is optional, and locals can be a mapping object and are also optional.
For Example:
exec(print(sum(2,8)))
Output:
10

UNIT-1 COMPLETED
DON BOSCO COLLEGE DHARMAPURI

UNIT-II
Numbers-introduction to numbers-Integers-Double precision floating point numbers-complex
numbers-operators-Numeric type functions-Sequences:Strings,Lists,and Tuples-sequences-
strings and strings operators-string built-in methods -Lists-List type built-in methods-Tuples.
Numbers
Introduction to Numbers:
• Number data types store numeric values. They are immutable data types, which means that
changing the value of a number data type results in a newly allocated object.
Different types of Number data types are :
• int
• float
• complex
Python Int type:

•Python int is the whole number, including negative numbers but not fractions. In Python,
there is no limit to how long an integer value can be.
Example 1: Creating int and checking type

num = -8

# print the data type


print(type(num))

Output:
<class 'int'>
Example 2: Performing arithmetic Operations on int type
DON BOSCO COLLEGE DHARMAPURI

a=5
b=6
# Addition
c=a+b
print("Addition:",c)
d=9
e=6
# Subtraction
f=d-e
print("Subtraction:",f)
g=8
h=2
# Division
i = g // h
print("Division:",i)
j=3
k=5
# Multiplication
l=j*k
print("Multiplication:",l)
m = 25
n=5
# Modulus
o=m%n
print("Modulus:",o)
p=6
q=2
# Exponent
r = p ** q
print("Exponent:",r)

Output:
Addition: 11
Subtraction: 3
Division: 4
Multiplication: 15
Modulus: 0
Exponent: 36
Python Float type:
• This is a real number with a floating-point representation. It is specified by a decimal point.
Optionally, the character e or E followed by a positive or negative integer may be appended
to specify scientific notation. . Some examples of numbers that are represented as floats
are 0.5 and -7.823457.
• They can be created directly by entering a number with a decimal point, or by using
operations such as division on integers. Extra zeros present at the number’s end are ignored
automatically.
DON BOSCO COLLEGE DHARMAPURI

Example 1: Creating float and checking type

num = 3/4
# print the data type
print(type(num))

Output:
<class 'float'>
As we have seen, dividing any two integers produces a float. A float is also produced by running
an operation on two floats, or a float and an integer.

num = 6 * 7.0
print(type(num))

Output:
<class 'float'>
Example 2: Performing arithmetic Operations on the float type

a = 5.5
b = 3.2
# Addition
c=a+b
print("Addition:", c)
# Subtraction
c = a-b
print("Subtraction:", c)
# Division
c = a/b
print("Division:", c)
# Multiplication
c = a*b
print("Multiplication:", c)

Output
Addition: 8.7
Subtraction: 2.3
Division: 1.71875
Multiplication: 17.6
Note: The accuracy of a floating-point number is only up to 15 decimal places, the 16th place can
be inaccurate.
DON BOSCO COLLEGE DHARMAPURI

Python Complex type:

• A complex number is a number that consists of real and imaginary parts. For example, 2 +
3j is a complex number where 2 is the real component, and 3 multiplied by j is an imaginary
part.
Example 1: Creating Complex and checking type

num = 6 + 9j
print(type(num))

Output:
<class 'complex'>
Example 2: Performing arithmetic operations on complex type

a = 1 + 5j
b = 2 + 3j
# Addition
c=a+b
print("Addition:",c)
d = 1 + 5j
e = 2 - 3j
# Subtraction
f=d-e
print("Subtraction:",f)
g = 1 + 5j
h = 2 + 3j
# Division
i=g/h
print("Division:",i)
j = 1 + 5j
k = 2 + 3j
# Multiplication
l=j*k
print("Multiplication:",l)

Output:
Addition: (3+8j)
Subtraction: (-1+8j)
Division: (1.307692307692308+0.5384615384615384j)
Multiplication: (-13+13j)
Type Conversion in Python:
• We can convert one number into the other form by two methods:
DON BOSCO COLLEGE DHARMAPURI

Using Arithmetic Operations:


• We can use operations like addition, and subtraction to change the type of number
implicitly(automatically), if one of the operands is float. This method is not working for
complex numbers.
Example: Type conversion using arithmetic operations

a = 1.6
b=5
c=a+b
print(c)

Output:
6.6
Using built-in functions:
• We can also use built-in functions like int(), float() and complex() to convert into
different types explicitly.
Example: Type conversion using built-in functions

a=2
print(float(a))
b = 5.6
print(int(b))
c = '3'
print(type(int(c)))
d = '5.6'
print(type(float(c)))
e=5
print(complex(e))
f = 6.5
print(complex(f))

Output:
2.0
5
<class 'int'>
<class 'float'>
(5+0j)
(6.5+0j)
When we convert float to int, the decimal part is truncated.
DON BOSCO COLLEGE DHARMAPURI

Note:
1. We can’t convert a complex data type number into int data type and float data type
numbers.
2. We can’t apply complex built-in functions on strings.

Decimal Numbers in Python:


• Arithmetic operations on the floating number can give some unexpected results.

Example 1:
• Let’s consider a case where we want to add 1.1 to 2.2. You all must be wondering why
the result of this operation should be 3.3 but let’s see the output given by Python.

a = 1.1
b = 2.2
c = a+b
print(c)

Output:
3.3000000000000003
INTEGERS:
• In Python, value of an integer is not restricted by the number of bits and can expand
to the limit of the available memory (Sources : this and this). Thus we never need any
special arrangement for storing large numbers (Imagine doing above arithmetic in
C/C++).
As a side note, in Python 3, there is only one type “int” for all type of integers. In
Python 2.7. there are two separate types “int” (which is 32 bit) and “long int” that is
same as “int” of Python 3.x, i.e., can store arbitrarily large numbers.

# A Python program to show that there are two types in


# Python 2.7 : int and long int
# And in Python 3 there is only one type : int
x = 10
print(type(x))
x = 10000000000000000000000000000000000000000000
print(type(x))

Output

<type 'int'>
<type 'long'>
DON BOSCO COLLEGE DHARMAPURI

# A Python3 program to show that there are two types in


# Python 2.7 : int and long int
# And in Python 3 there is only one type : int

x = 10
print(type(x))

x = 10000000000000000000000000000000000000000000
print(type(x))

Output
<type 'int'>
<type 'int'>
Double precision floating point numbers:
• The float type in Python represents the floating point number. Float is used to represent
real numbers and is written with a decimal point dividing the integer and fractional
parts. For example, 97.98, 32.3+e18, -32.54e100 all are floating point numbers.
• Python float values are represented as 64-bit double-precision values. The maximum
value any floating-point number can be is approx 1.8 x 10308. Any number greater than
this will be indicated by the string inf in Python.

# Python code to demonstrate float values.


print(1.7e308)
# greater than 1.8 * 10^308
# will print 'inf'
print(1.82e308)

Output:
1.7e+308
inf
• Floating-point numbers are represented in computer hardware as base 2 (binary)
fractions. For example, the decimal fraction 0.125 has value 1/10 + 2/100 + 5/1000, and
in the same way the binary fraction 0.001 has value 0/2 + 0/4 + 1/8. These two fractions
have identical values, the only real difference being that the first is written in base 10
fractional notation, and the second in base 2.
• Unfortunately, most decimal fractions cannot be represented exactly as binary fractions.
A consequence is that, in general, the decimal floating-point numbers you enter are
only approximated by the binary floating-point numbers actually stored in the machine.
• The float type implements the numbers.Real abstract base class. Returns an expression
which is converted into floating point number. float also has the following additional
methods:
• float.as_integer_ratio() : Returns a pair of integers whose ratio is exactly equal to the
actual float having a positive denominator.In case of infinites, it raises overflow error
and value errors on Not a number (NaNs).
DON BOSCO COLLEGE DHARMAPURI

# Python3 program to illustrate


# working of float.as_integer_ratio()
def frac(d):

# Using as_integer_ratio
b = d.as_integer_ratio()
return b
# Driver code
if __name__=='__main__':
b = frac(3.5)
print(b[0], "/", b[1])

Output:
7/2
float.is_integer() : Returns True in case the float instance is finite with integral value, else,
False.

# Python3 program to illustrate


# working of float.is_integer()
def booln():
# using is_integer
print((-5.0).is_integer())
print((4.8).is_integer())
print(float.is_integer(275.0))

# Driver code
if __name__=='__main__':
booln()

Output:
True
False
True
float.hex() : Returns a representation of a floating-point number as a hexadecimal string.

# Python3 program to illustrate


# working of float.hex()
def frac(a):
# using float.hex()
a = float.hex(35.0)
return a
# Driver code
if __name__=='__main__':
b = frac(35.0)
DON BOSCO COLLEGE DHARMAPURI

print(b)

Output:
'0x1.1800000000000p+5'
float.fromhex(s) : Returns the float represented by a hexadecimal string s. String s may have
leading and trailing whitespaces.

# Python3 program to illustrate


# working of float.fromhex()
def frac(a):
# using a float.fromhex()
a = float.fromhex('0x1.1800000000000p+5')
return a
# Driver code
if __name__=='__main__':
b = frac('0x1.1800000000000p+5')
print(b)

Output:
35.0
Note : float.hex() is an instance method, but float.fromhex() is a class method.
Complex numbers:
• Not only real numbers, Python can also handle complex numbers and its associated
functions using the file “cmath”. Complex numbers have their uses in many
applications related to mathematics and python provides useful tools to handle and
manipulate them.
• Converting real numbers to complex number An complex number is represented by
“ x + yi “. Python converts the real numbers x and y into complex using the
function complex(x,y). The real part can be accessed using the function real() and
imaginary part can be represented by imag().
DON BOSCO COLLEGE DHARMAPURI

# Python code to demonstrate the working of


# complex(), real() and imag()
# importing "cmath" for complex number operations
import cmath
# Initializing real numbers
x=5
y=3
# converting x and y into complex number
z = complex(x,y);
# printing real and imaginary part of complex number
print ("The real part of complex number is : ",end="")
print (z.real)
print ("The imaginary part of complex number is : ",end="")
print (z.imag)

Output:
The real part of complex number is : 5.0
The imaginary part of complex number is : 3.0
An alternative way to initialize a complex number
• Below is the implementation of how can we make complex no. without
using complex() function

# Aleternative way how can complex no can initialize


# importing "cmath" for complex number operations
import cmath
# Initializing complex number
z = 5+3j
# Print the parts of Complex No.
print("The real part of complex number is : ", end="")
print(z.real)
print("The imaginary part of complex number is : ", end="")
print(z.imag)

Output:
The real part of complex number is : 5.0
The imaginary part of complex number is : 3.0
Explanation: Phase of complex number Geometrically, the phase of a complex number is
the angle between the positive real axis and the vector representing a complex number.
This is also known as the argument of a complex number. Phase is returned using phase(),
which takes a complex number as an argument. The range of phase lies from -pi to +pi. i.e
from -3.14 to +3.14.
DON BOSCO COLLEGE DHARMAPURI

# Python code to demonstrate the working of


# phase()
# importing "cmath" for complex number operations
import cmath
# Initializing real numbers
x = -1.0
y = 0.0
# converting x and y into complex number
z = complex(x,y);
# printing phase of a complex number using phase()
print ("The phase of complex number is : ",end="")
print (cmath.phase(z))

Output:
The phase of complex number is : 3.141592653589793
Python Operators
Introduction:

• In this article, we are discussing Python Operators. The operator is a symbol that performs
a specific operation between two operands, according to one definition. Operators serve as
the foundation upon which logic is constructed in a program in a particular programming
language. In every programming language, some operators perform several tasks. Same as
other languages, Python also has some operators, and these are given below -

o Arithmetic operators
o Comparison operators
o Assignment Operators
o Logical Operators
o Bitwise Operators
o Membership Operators
o Identity Operators
o Arithmetic Operators

Arithmetic Operators

• Arithmetic operators used between two operands for a particular operation. There are many
arithmetic operators. It includes the exponent (**) operator as well as the + (addition), -
(subtraction), * (multiplication), / (divide), % (reminder), and // (floor division) operators.
DON BOSCO COLLEGE DHARMAPURI

Consider the following table for a detailed explanation of arithmetic operators.

Operator Description

+ (Addition) It is used to add two operands. For example, if a = 10, b = 10 => a+b =
20

- (Subtraction) It is used to subtract the second operand from the first operand. If the
first operand is less than the second operand, the value results negative.
For example, if a = 20, b = 5 => a - b = 15

/ (divide) It returns the quotient after dividing the first operand by the second
operand. For example, if a = 20, b = 10 => a/b = 2.0

* It is used to multiply one operand with the other. For example, if a = 20,
(Multiplication) b = 4 => a * b = 80

% (reminder) It returns the reminder after dividing the first operand by the second
operand. For example, if a = 20, b = 10 => a%b = 0

** (Exponent) As it calculates the first operand's power to the second operand, it is an


exponent operator.

// (Floor It provides the quotient's floor value, which is obtained by dividing the
division) two operands.

Now we give code examples of arithmetic operators in Python. The code is given below -

1. a = 32 # Initialize the value of a


2. b = 6 # Initialize the value of b
3. print('Addition of two numbers:',a+b)
4. print('Subtraction of two numbers:',a-b)
5. print('Multiplication of two numbers:',a*b)
6. print('Division of two numbers:',a/b)
7. print('Reminder of two numbers:',a%b)
8. print('Exponent of two numbers:',a**b)
DON BOSCO COLLEGE DHARMAPURI

9. print('Floor division of two numbers:',a//b)

Output:

Now we compile the above code in Python, and after successful compilation, we run it. Then the
output is given below -

Addition of two numbers: 38


Subtraction of two numbers: 26
Multiplication of two numbers: 192
Division of two numbers: 5.333333333333333
Reminder of two numbers: 2
Exponent of two numbers: 1073741824
Floor division of two numbers: 5

Numeric Types functions:

• Python has many useful built-in data types. Python variables can store different types of
data based on a variable's data type. A variable's data type is created dynamically,
without the need to explicitly define a data type when the variable is created.

• It is useful for problem solvers to understand a couple of Python's core data types in order
to write well-constructed code.

A review of variable assignment in Python


• Recall from the previous chapter that variables in Python are defined with the assignment
operator, the equals sign =. To define a variable in Python, the variable name is written
first, then the assignment operator = followed by a value or expression.

• The general syntax to assign a value to variable name is below:

variable_name = value

Variable names in Python must adhere to the following rules:

• variable names must start with a letter


• variable names can only contain letters, numbers and the underscore character _
• variable names can not contain spaces or punctuation
• variable names are not enclosed in quotes or brackets

Below is a discussion of a few different built-in data types in Python.

Integers:
• Integers are one of the Python data types. An integer is a whole number, negative,
positive or zero. In Python, integer variables are defined by assigning a whole number to
a variable. Python's type() function can be used to determine the data type of a variable.
DON BOSCO COLLEGE DHARMAPURI

>>> a = 5
>>> type(a)
<class 'int'>
• The output <class 'int'> indicates the variable a is an integer. Integers can be negative or
zero.
>>> b = -2
>>> type(b)
<class 'int'>
>>> z = 0
>>> type(z)
<class 'int'>
Floating Point Numbers:

• Floating point numbers or floats are another Python data type. Floats are decimals,
positive, negative and zero. Floats can also be represented by numbers in scientific
notation which contain exponents.

• Both a lower case e or an upper case E can be used to define floats in scientific notation.
In Python, a float can be defined using a decimal point . when a variable is assigned.
>>> c = 6.2
>>> type(c)
<class 'float'>
>>> d = -0.03
>>> type(d)
<class 'float'>
>>> Na = 6.02e23
>>> Na
6.02e+23
>>> type(Na)
<class 'float'>
• To define a variable as a float instead of an integer, even if the variable is assigned a
whole number, a trailing decimal point . is used. Note the difference when a decimal
point . comes after a whole number:
>>> g = 5
>>> type(g)
<class 'int'>
>>> f = 5.
>>> type(r)
<class 'float'>
Complex Numbers:
• Another useful numeric data type for problem solvers is the complex number data type. A
complex number is defined in Python using a real component + an imaginary
component j. The letter j must be used to denote the imaginary component. Using the
letter i to define a complex number returns an error in Python.
>>> comp = 4 + 2j
>>> type(comp)
DON BOSCO COLLEGE DHARMAPURI

<class 'complex'>

>>> comp2 = 4 + 2i
^
SyntaxError: invalid syntax

Imaginary numbers can be added to integers and floats.

>>> intgr = 3
>>> type(intgr)
<class 'int'>

>>> comp_sum = comp + intgr


>>> print(comp_sum)
(7+2j)

>>> flt = 2.1


>>> comp_sum = comp + flt
>>> print(comp_sum)
(6.1+2j)
Sequences:
Python String
• A String is a data structure in Python that represents a sequence of characters. It is an
immutable data type, meaning that once you have created a string, you cannot change it.
Strings are used widely in many different applications, such as storing and manipulating
text data, representing names, addresses, and other types of data that can be represented
as text.
What is a String in Python?
• Python does not have a character data type, a single character is simply a string with a
length of 1.
Example:
"Geeksforgeeks" or 'Geeksforgeeks' or "a"

print("A Computer Science portal for geeks")


print('A')

Output:
A Computer Science portal for geeks
A
Creating a String in Python
• Strings in Python can be created using single quotes or double quotes or even triple
quotes. Let us see how we can define a string in Python.
Example:
• In this example, we will demonstrate different ways to create a Python String. We will
create a string using single quotes (‘ ‘), double quotes (” “), and triple double quotes (“””
“””). The triple quotes can be used to declare multiline strings in Python.
DON BOSCO COLLEGE DHARMAPURI

# Python Program for


# Creation of String
# Creating a String
# with single Quotes
String1 = 'Welcome to the Geeks World'
print("String with the use of Single Quotes: ")
print(String1)
# Creating a String
# with double Quotes
String1 = "I'm a Geek"
print("\nString with the use of Double Quotes: ")
print(String1)

# Creating a String
# with triple Quotes
String1 = '''I'm a Geek and I live in a world of "Geeks"'''
print("\nString with the use of Triple Quotes: ")
print(String1)

# Creating String with triple


# Quotes allows multiple lines
String1 = '''Geeks
For
Life'''
print("\nCreating a multiline String: ")
print(String1)

Output:
String with the use of Single Quotes:
Welcome to the Geeks World
String with the use of Double Quotes:
I'm a Geek
String with the use of Triple Quotes:
I'm a Geek and I live in a world of "Geeks"
Creating a multiline String:
Geeks
For
Life
Accessing characters in Python String
• In Python, individual characters of a String can be accessed by using the method of
Indexing. Indexing allows negative address references to access characters from the
back of the String, e.g. -1 refers to the last character, -2 refers to the second last
character, and so on.
While accessing an index out of the range will cause an IndexError. Only Integers are
allowed to be passed as an index, float or other types that will cause a TypeError.
DON BOSCO COLLEGE DHARMAPURI

Python String indexing

Example:
In this example, we will define a string in Python and access its characters using positive and
negative indexing. The 0th element will be the first character of the string whereas the -1th
element is the last character of the string.

# Python Program to Access


# characters of String
String1 = "GeeksForGeeks"
print("Initial String: ")
print(String1)
# Printing First character
print("\nFirst character of String is: ")
print(String1[0])
# Printing Last character
print("\nLast character of String is: ")
print(String1[-1])

Output:
Initial String:
GeeksForGeeks
First character of String is:
G
Last cha racter of String is:
s
String Slicing:
• In Python, the String Slicing method is used to access a range of characters in the
String. Slicing in a String is done by using a Slicing operator, i.e., a colon (:). One
thing to keep in mind while using this method is that the string returned after slicing
includes the character at the start index but not the character at the last index.
Example:
• In this example, we will use the string-slicing method to extract a substring of the
original string. The [3:12] indicates that the string slicing will start from the 3rd index
of the string to the 12th index, (12th character not including). We can also use negative
indexing in string slicing.
DON BOSCO COLLEGE DHARMAPURI

# Python Program to
# demonstrate String slicing
# Creating a String
String1 = "GeeksForGeeks"
print("Initial String: ")
print(String1)
# Printing 3rd to 12th character
print("\nSlicing characters from 3-12: ")
print(String1[3:12])
# Printing characters between
# 3rd and 2nd last character
print("\nSlicing characters between " +
"3rd and 2nd last character: ")
print(String1[3:-2])

Output:
Initial String:
GeeksForGeeks
Slicing characters from 3-12:
ksForGeek
Slicing characters between 3rd and 2nd last character:
ksForGee
Reversing a Python String
• By accessing characters from a string, we can also reverse strings in Python. We can
Reverse a string by using String slicing method.
Example:
• In this example, we will reverse a string by accessing the index. We did not specify the
first two parts of the slice indicating that we are considering the whole string, from the
start index to the last index.

#Program to reverse a string


gfg = "geeksforgeeks"
print(gfg[::-1])

Output:
skeegrofskeeg
Example:
• We can also reverse a string by using built-in join and reversed functions, and passing
the string as the parameter to the reversed() function.

# Program to reverse a string


gfg = "geeksforgeeks"
# Reverse the string using reversed and join function
gfg = "".join(reversed(gfg))
DON BOSCO COLLEGE DHARMAPURI

print(gfg)

Output:
skeegrofskeeg
Deleting/Updating from a String
• In Python, the Updation or deletion of characters from a String is not allowed. This will
cause an error because item assignment or item deletion from a String is not supported.
Although deletion of the entire String is possible with the use of a built-in del keyword.
This is because Strings are immutable, hence elements of a String cannot be changed
once assigned. Only new strings can be reassigned to the same name.
Updating a character:
• A character of a string can be updated in Python by first converting the string into
a Python List and then updating the element in the list. As lists are mutable in nature,
we can update the character and then convert the list back into the String.
• Another method is using the string slicing method. Slice the string before the character
you want to update, then add the new character and finally add the other part of the
string again by string slicing.
Example:
• In this example, we are using both the list and the string slicing method to update a
character. We converted the String1 to a list, changes its value at a particular element,
and then converted it back to a string using the Python string join() method.
• In the string-slicing method, we sliced the string up to the character we want to update,
concatenated the new character, and finally concatenate the remaining part of the string.

# Python Program to Update


# character of a String
String1 = "Hello, I'm a Geek"
print("Initial String: ")
print(String1)
# Updating a character of the String
## As python strings are immutable, they don't support item updation directly
### there are following two ways
#1
list1 = list(String1)
list1[2] = 'p'
String2 = ''.join(list1)
print("\nUpdating character at 2nd Index: ")
print(String2)
#2
String3 = String1[0:2] + 'p' + String1[3:]
print(String3)

Output:
Initial String:
Hello, I'm a Geek
Updating character at 2nd Index:
DON BOSCO COLLEGE DHARMAPURI

Heplo, I'm a Geek


Heplo, I'm a Geek
Updating Entire String:
• As Python strings are immutable in nature, we cannot update the existing string. We
can only assign a completely new value to the variable with the same name.
Example:
• In this example, we first assign a value to ‘String1’ and then updated it by assigning a
completely different value to it. We simply changed its reference.

# Python Program to Update


# entire String
String1 = "Hello, I'm a Geek"
print("Initial String: ")
print(String1)
# Updating a String
String1 = "Welcome to the Geek World"
print("\nUpdated String: ")
print(String1)

Output:
Initial String:
Hello, I'm a Geek
Updated String:
Welcome to the Geek World
Deleting a character:
• Python strings are immutable, that means we cannot delete a character from it. When
we try to delete thecharacter using the del keyword, it will generate an error.

# Python Program to delete


# character of a String
String1 = "Hello, I'm a Geek"
print("Initial String: ")
print(String1)
print("Deleting character at 2nd Index: ")
del String1[2]
print(String1)

Output:
Initial String:
Hello, I'm a Geek
Deleting character at 2nd Index:
Traceback (most recent call last):
File "e:\GFG\Python codes\Codes\demo.py", line 9, in <module>
del String1[2]
TypeError: 'str' object doesn't support item deletion
But using slicing we can remove the character from the original string and store the result in a
new string.
DON BOSCO COLLEGE DHARMAPURI

Example:
• In this example, we will first slice the string up to the character that we want to delete
and then concatenate the remaining string next from the deleted character.

# Python Program to Delete


# characters from a String
String1 = "Hello, I'm a Geek"
print("Initial String: ")
print(String1)
# Deleting a character
# of the String
String2 = String1[0:2] + String1[3:]
print("\nDeleting character at 2nd Index: ")
print(String2)

Output:
Initial String:
Hello, I'm a Geek
Deleting character at 2nd Index:
Helo, I'm a Geek
Deleting Entire String:
• Deletion of the entire string is possible with the use of del keyword. Further, if we try
to print the string, this will produce an error because the String is deleted and is
unavailable to be printed.

# Python Program to Delete


# entire String
String1 = "Hello, I'm a Geek"
print("Initial String: ")
print(String1)
# Deleting a String
# with the use of del
del String1
print("\nDeleting entire String: ")
print(String1)

Error:
Traceback (most recent call last):
File "/home/e4b8f2170f140da99d2fe57d9d8c6a94.py", line 12, in
print(String1)
NameError: name 'String1' is not defined
String built-in methods:
String Methods:
• In Python, there are certain methods implemented to use on strings. These are often
available with the string method and often they return a new string or boolean rather than
modifying the original string. This is because strings are immutable.
DON BOSCO COLLEGE DHARMAPURI

The table below explains a few of these methods with code examples from the Python shell
terminal.
Method Explanation Code Example on Python shell terminal
s.capitalize() This method when used converts the first character
to uppercase.

s.islower() This method returns True if all the characters in a


given string are lower case. Otherwise, False.

s.lower() This method is used to convert all the characters in a


string to lowercase.

s.isupper() This method returns True if all the characters in a


given string are uppercase. Otherwise, False

s.upper() This method is used to convert all the characters in a


string to uppercase.

s.find(substr Returns the index of a specified character in the


ing, [start, string or the start position of the given substring.
end])

s.count(subs Count the occurrence of a character or substring in


tring,[start,e string.
nd])

s.expandtab Replaces tabs defined by \t with spaces, optionally


s([tabsize]) using tabsize(default 8)

s.endswith(s Returns True if a string ends with the specified


ubstring,[sta substring. False otherwise.
rt, end])
s.startswith( Returns True if a string starts with the specified
substring, substring. False otherwise.
[start, end])
DON BOSCO COLLEGE DHARMAPURI

Method Explanation Code Example on Python shell terminal


s.isalnum() Return True if all characters in string are
alphanumeric. False otherwise.

s.isalpha() Return True if all characters in string are


alphabetic. False otherwise.

s.isdigit() Return True if all characters in string are


digits. False otherwise.

s.split([sepa Splits a string separated by a separator(defaults


rator],[maxs to whitespace) and an optional maxsplit to
plit]) determine the split limit. Returns a list.

s.join(iterab Joins all items in an iterable into a single string


le) separated by the string, s.
s.replace(old Replace old substring contained in string, s with a
, new substring.
new,[maxre
place])
s.swapcase() Returns a new string with swapped case. I.E,
uppercase becomes lowercase and vice versa.
s.strip([char Remove whitespaces or optional characters at the
acters]) beginning and at the end of the string.

s.lstrip([cha Remove leading whitespace or optional characters


racters]) from a string.
DON BOSCO COLLEGE DHARMAPURI

• There are quite a number of these methods and in this tutorial, we have gone over a
couple of them just to show you how to use them. To view an extensive list of these
methods, please check out Python methods from Python’s official documentation page.
String Operators:
• We just saw and uncovered what strings generally are. Now let’s take a look at what
operations can be carried out on strings. These operators are often intended to be used as
a means of interaction with one or more strings.

• We are just going to focus on the 6 most important operators


i.e. concatenation, repetition, slicing, indexing, membership, and comparison.
Operations on Strings
Operator Operation Description
Concatenation s1 + s2 Concatenates two strings, s1 and s2.
Repetition s*n Makes n copies of string, s.
Indexing s[i] Indexing a string, returning element at index i.
Slicing s [ i : j : stride] Slicing a string from i to j with an optional stride.
Membership x in s Returns True if the element, x is in the string, s. Otherwise False.
x not in s Returns True if the element, x is not in the string, x. Otherwise False.
Comparison s1 == s2 Returns True if string, s1 is the same as string, s2. Otherwise False.
s1 != s2 Returns True if string, s1 is not the same as string, s2. Otherwise False.

#1) (+) Concatenation Operator


Most often when programming, we run into the need to concatenate or join 2 or more strings.
The plus operator(+) is used in this respect to join or concatenate two strings.
Unlike in other languages like JavaScript where we can concatenate a string and an integer
thanks to type coercion, the concatenation operator in Python only concatenates objects of the
same type.
We shall later see how we can use the string join() method to join 2 or more strings.
Example : Concatenate two strings.
1string1 = "first" # define the first string
2string2 = "second" # define the second string
3
4concatenate_string = string1 + string2 # concatenate the two strings
5
6print(concatenate_string) # print the concatenated string
Output:
DON BOSCO COLLEGE DHARMAPURI

• We mentioned earlier that strings are immutable sequences. In the example above,
concatenating the two strings doesn’t modify either of the strings. Instead, the operation
takes the two strings “first” and “second” and creates a new string “firstsecond”.
• Beginners commonly use this operator to add spaces in between strings. Space here is
also a string, but this time it’s just an empty string.

Example 7: Print two strings with space in between.


1string1 = "first" # define the first string
2string2 = "second" # define the second string
3
4print(string1 +' '+ string2) # print two strings with a space in between.
Output

#2) (*) The Repetition Operator


• This operator is used to return a repeated string a specific number of times. The new
string contains the said string the number of times specified. The multiplication
operator(*) is used for this purpose.
• Say we have a string S, and an integer N. By doing S * N or N * S, we shall end up
with S repeated N times.
NB: This operator will raise a TypeError if N is a non-integer value.
Example : Make n copies of a string s
1string1 = "first." # define our string, s
2
3print(string1 * 2) # make 2 copies of s
4print(3 * string1) # make 3 copies of s
5
6print(string1 * 0) # make 0 copies of s
7print(string1 * -1) # make -1 copies of s
Output

• We should notice the last two print functions in the example above. Both actually print
empty strings. The last but one operation makes sense as it creates zero copy of the string
but the last operation is a bit fishy.
DON BOSCO COLLEGE DHARMAPURI

• However, we should note that multiplying a string by a negative number returns an empty
string.

#3) ([i]) String Indexing Operator


• Indexing a string, for example, s [ i ] returns the i element of a string. Strings
are ordered, zero-based sequences of characters. This makes it possible to access
specific characters using numeric values that represent their position in the string.
• Zero-based here means that the very first character of a string is located at index 0, the
next is 1, and so on.
Example : Access individual characters of a string using indexing.
1>>> string1 = "first. second"
2>>> string1
3'first. second'
4>>> string1[0]
5'f'
6>>> string1[5]
7'.'
8>>> string1[12] # same as string1[len(string1)-1]
9'd'
10>>> string1[13]
11Traceback (most recent call last):
12 File "<stdin>", line 1, in <module>
13IndexError: string index out of range
The last line of code in example above raised the IndexError exception. This is because we can’t
access an index that is out of range. The string above has 13 elements(including whitespace).
However, since strings are zero-based, the last element can be accessed at index 12(13-1)
We can also use negative indexing. In this case, the lookup will start backward.

Example : Access individual characters of a string using negative indexing.


1>>> string1 = "first. second"
2>>> string1[-1] # same as string1[12]
3'd'
4>>> string1[-13] # same as string1[0]
5'f'
DON BOSCO COLLEGE DHARMAPURI

NB: The figure under the section “Using negative indices for slicing” will elaborate more on
negative indices.
#4) ([i:j:stride]) String Slicing Operator
Just like all sequence types, strings support slicing. We can retrieve any character or substring
from a string by using s[i: j], where i and j are the start and end(exclusive) points of the slice
respectively.
Example :
1>>> name = "EyongKevin"
2>>> name[3:6]
3'ngK'
Let’s understand the process above with the diagram below:

Graphical demonstration of Python string slicing



From the figure above, our slicing starts at index 3 and ends at index 6, but as the
endpoint is exclusive, we end up with a substring from index 3 to 5.
• NB: We also notice from the figure above that string indices are zero-based i.e. the first
character in a string has the index, 0.
• While dealing with both the indices, an empty string will be returned if i is greater or
equal to j.
Example :
1>>> name = "EyongKevin"
2>>> name[3:3] # i == j
3''
4>>> name[5:3] # i > j
5''
Different Ways To Slice A String
The String slice operator can be constructed in many ways. Given the formula s [ n : m ], we
could do the following:
#1) Omit n
omit n as in s [ : m ]. In this case, our slicing will start at the beginning of the string(index 0) and
end at m-1.
Example :
DON BOSCO COLLEGE DHARMAPURI

1>>> name = "EyongKevin"


2>>> name[:6]
3'EyongK'
#2) Omit m
Omit m as in s [n : ]. In this case, our slicing will start at index n to the end of the string i.e. at
index len(s) – 1, where len(s) is the length of the string.
Example :
1>>> name = "EyongKevin"
2>>> name[3:]
3'ngKevin'
#3) Omit both m and n
Omit m and n as in s [ : ]. In this case, our slicing will return the entire string. Unlike with lists,
this operation returns a reference to the same object. So, a copy is not created.
Example :
1>>> name = "EyongKevin"
2>>> name[:]
3'EyongKevin'
#4) Using Negative Indices For Slicing
Negative indices can be used to slice a string. Slicing with negative indices can get confusing
without proper understanding. So, before we get into some code examples, let’s understand it
with the aid of a diagram.

Python Slicing with Positive and Negative Indices


For negative indices, we start counting backward. -1 references the last character in the string, -
2 references the second-to-last character, and so on.
Just as for positive indices, slicing from -n to -m results in a substring starting from –n and
ending at (-m-1). With this out of the way, we can write some code to see how it works.
Example :
1>>> name = "EyongKevin"
2>>> name[-7: -5] # slice from -7 to -6(-5-1)
3'ng'
DON BOSCO COLLEGE DHARMAPURI

4>>> name[-10: -5] # slice from -10 to -6(-5-1)


5'Eyong'
6>>> name[-5: ] # slice from -5 to end of string
7'Kevin'
8>>> name[2: -4] # slice from 2 to -5(-4-1)
9'ongK'
10>>> name[-2: -4] # n > m
11''
NB: The last operation returns an empty string because the n index(-2) is greater than
the m index(-4).
#5) Using Slides
You can even specify a skip number to the slice. For example, s [ n : m : x ] will tell the slice
that from the range starting from n to m, skip every x number of characters. It is by default a skip
of 1.
Example :
1>>> name = "EyongKevin"
2>>> name[1:8:2]
3'ynKv'
Let’s understand the above example using the below diagram:

Python string slicing with stride


We can also omit the indices as we saw above.
Example :
1>>> name = "EyongKevin"
2>>> name[:8:2]
3'Eoge'
4>>> name[1::3]
5'ygv'
DON BOSCO COLLEGE DHARMAPURI

6>>> name[::4]
7'Egi'
We can also specify a negative stride value. In this case, the steps are counted backward. Note
that, when the stride is negative, n should be greater than m, or else, an empty string will be
returned.
Example :
1>>> name[0:3:-2] # empty string returned because n < m
2''
3>>> name[3:0:-2]
4'ny'
5>>> name[:3:-2] # by default, n = -1
6'nvK'
7>>> name[::-2] # by default, n = -1, m = -10
8'nvKny'
Omitting both indices and a negative stride of -1 is a common way of reversing a string.
Example :
1>>> name = "EyongKevin"
2>>> name[::-1]
3'niveKgnoyE'
#5) (In and Not in) Membership Operator
These operators are often used to check if or if not an element or character exists in a particular
string. The in returns True if a character x exists in a given string and False otherwise. The not
in returns True if a character x does not exist in a given string and False otherwise.
Example : Verify if a certain character exists in a string or not.
1>>> greeting = "Hello World!"
2>>> 'H' in greeting # passed
3True
4>>> 'h' in greeting # failed. This operation is case-sensitive.
5False
6>>> 'Z' in greeting # failed. 'Z' doesn't exist in
7False
We should note that the membership operators also work with substrings i.e. we can verify if a
substring exists in a string or not.
DON BOSCO COLLEGE DHARMAPURI

Example : Verify if a substring exists in a string.


1>>> greeting = "Hello World!"
2>>> "He" in greeting
3True
4>>> "Hel" in greeting
5True
6>>> "Helo" in greeting
7False
8>>> "Hello World!" in greeting
9True
#6) ( == and != ) Comparison Operator
These operators in python just like their name specifies, are used to test the equivalence of two
operands, in this case, 2 strings. Just because they return a boolean they are mostly used in
conditional statements to evaluate the sameness of two strings.

The == operator returns True when the two said strings are the same and False when the two
said strings are not the same.
Example : Test the equivalence of two strings with the == operator.
1>>> fname = "Enow"
2>>> lname = "Eyong"
3>>> fname2 = "enow"
4>>> lname2 = "Eyong"
5>>> fname == fname2 # "Enow" == "enow", returns False as it is case-sensitive
6False
7>>> lname == lname2 # "Eyong" == "Eyong", returns True
8True
The != operator returns True when the two said strings are not the same and False when the two
said strings are the same.
Example : Test the equivalence of two strings with the != operator.
1>>> fname = "Enow"
2>>> lname = "Eyong"
3>>> fname2 = "enow"
4>>> fname != fname2 # "Enow" != "enow", return True as they are not the same
DON BOSCO COLLEGE DHARMAPURI

5True
6>>> lname != lname2 # "Eyong" != "Eyong", return False, as they are equivalent.
7False
So far we have gone over the most widely used operators on strings in Python. Before we wind
up this section, let’s throw some light on the unpacking operation. Strings are iterable, so they
can be unpacked as in c1, c2,…cn = s.
We see that we used the assignment operator(=) to perform the unpacking operation. Here,
dependent on the right operant, this operator can act either as an assignment or unpacking
operator.
Example : Unpack a string of vowels.
1>>> vowels = "aeiou"
2>>> v1,v2,v3,v4,v5 = vowels # unpacking
3>>> v1
4'a'
5>>> v2
6'e'
7>>> v3
8'i'
9>>> v4
10'o'
11>>> v5
12'u'
NB: We should be careful while using the unpacking operation. If the left operand doesn’t
contain exactly the same number of variables as they are the number of characters in the right
operand string, then a ValueError will be raised.

Python list and built in methods:

• Python List Methods are the built-in methods in lists used to perform operations on
Python lists/arrays.
• Below, we’ve explained all the methods you can use with Python lists, for
example, append(), copy(), insert(), and more.
List / Array Methods in Python:
• Let’s look at some different methods for lists in Python:
DON BOSCO COLLEGE DHARMAPURI

S.no Method Description

Used for adding elements to


1 append()
the end of the List.

It returns a shallow copy of a


2 copy()
list

This method is used for


3 clear() removing all items from the
list.

These methods count the


4 count()
elements.

Adds each element of an


5 extend()
iterable to the end of the List

Returns the lowest index


6 index()
where the element appears.

Inserts a given element at a


7 insert()
given index in a list.

Removes and returns the last


8 pop() value from the List or the
given index value.

Removes a given object from


9 remove()
the List.

Reverses objects of the List


10 reverse()
in place.

Sort a List in ascending,


11 sort() descending, or user-defined
order
DON BOSCO COLLEGE DHARMAPURI

S.no Method Description

Calculates the minimum of


12 min()
all the elements of the List

Calculates the maximum of


13 max()
all the elements of the List

1. Python append() method


Adds element to the end of a list.
Syntax: list.append (element)
Example:

# Adds List Element as value of List.


List = ['Mathematics', 'chemistry', 1997, 2000]
List.append(20544)
print(List)

Output
['Mathematics', 'chemistry', 1997, 2000, 20544]
2. Python insert() method
Inserts an element at the specified position.
Syntax:
list.insert(<position, element)
Note: The position mentioned should be within the range of List, as in this case between 0 and
4, else wise would throw IndexError.
Example:

List = ['Mathematics', 'chemistry', 1997, 2000]


# Insert at index 2 value 10087
List.insert(2, 10087)
print(List)

Output
['Mathematics', 'chemistry', 10087, 1997, 2000]
DON BOSCO COLLEGE DHARMAPURI

3. Python extend() method


Adds items of an iterable(list, array, string , etc.) to the end of a list
Syntax: List1.extend(List2)
Example:

List1 = [1, 2, 3]
List2 = [2, 3, 4, 5]
# Add List2 to List1
List1.extend(List2)
print(List1)
# Add List1 to List2 now
List2.extend(List1)
print(List2)

Output
[1, 2, 3, 2, 3, 4, 5]
[2, 3, 4, 5, 1, 2, 3, 2, 3, 4, 5]
Important functions of the Python List
We have mentioned some essential Python list functions along with their syntax and example:
1. Python sum() method
Calculates the sum of all the elements of the List.
Syntax: sum(List)
Example:

List = [1, 2, 3, 4, 5]
print(sum(List))

Output
15
1. Python count() method
Calculates the total occurrence of a given element of the List.
Syntax: List.count(element)
Example:
DON BOSCO COLLEGE DHARMAPURI

List = [1, 2, 3, 1, 2, 1, 2, 3, 2, 1]
print(List.count(1))

Output
4
3. Python len() method
Calculates the total length of the List.
Syntax: len(list_name)
Example:

List = [1, 2, 3, 1, 2, 1, 2, 3, 2, 1]
print(len(List))

Output
10
4. Python index() method
Returns the index of the first occurrence. The start and end indexes are not necessary
parameters.
Syntax: List.index(element[,start[,end]])
Example:

List = [1, 2, 3, 1, 2, 1, 2, 3, 2, 1]
print(List.index(2))

Output
1
Another example:

List = [1, 2, 3, 1, 2, 1, 2, 3, 2, 1]
print(List.index(2, 2))

Output
4
5. Python min() method
Calculates minimum of all the elements of List.
Syntax: min(iterable, *iterables[, key])
DON BOSCO COLLEGE DHARMAPURI

Example:

numbers = [5, 2, 8, 1, 9]
print(min(numbers))

Output
1
6. Python max() method
Calculates the maximum of all the elements of the List.
Syntax: max(iterable, *iterables[, key])

numbers = [5, 2, 8, 1, 9]
print(max(numbers))

Output
9
7. Python sort() method
Sort the given data structure (both tuple and list) in ascending order.
Key and reverse_flag are not necessary parameter and reverse_flag is set to False if nothing is
passed through sorted().
Syntax: list.sort([key,[Reverse_flag]])
Example:

List = [2.3, 4.445, 3, 5.33, 1.054, 2.5]


#Reverse flag is set True
List.sort(reverse=True)
#List.sort().reverse(), reverses the sorted list
print(List)

Output
[5.33, 4.445, 3, 2.5, 2.3, 1.054]
8. Python reverse() method
reverse() function reverses the order of list.
Syntax: list. reverse()
Example:
DON BOSCO COLLEGE DHARMAPURI

# creating a list
list = [1,2,3,4,5]
#reversing the list
list.reverse()
#printing the list
print(list)

Output
[5, 4, 3, 2, 1]
Deletion of List Elements
• To Delete one or more elements, i.e. remove an element, many built-in Python
functions can be used, such as pop() & remove() and keywords such as del.
1. Python pop() method
Removes an item from a specific index in a list.
Syntax: list.pop([index])
The index is not a necessary parameter, if not mentioned takes the last index.
Note: The index must be in the range of the List, elsewise IndexErrors occur.
Example 1:

List = [2.3, 4.445, 3, 5.33, 1.054, 2.5]


print(List.pop())

Output
2.5
Example 2:

List = [2.3, 4.445, 3, 5.33, 1.054, 2.5]


print(List.pop(0))

Output
2.3
2. Python del() method
Deletes an element from the list using it’s index.
Syntax: del list.[index]
Example:
DON BOSCO COLLEGE DHARMAPURI

List = [2.3, 4.445, 3, 5.33, 1.054, 2.5]


del List[0]
print(List)

Output
[4.445, 3, 5.33, 1.054, 2.5]
3. Python remove() method
Removes a specific element using it’s value/name.
Syntax: list.remove(element)
Example :

List = [2.3, 4.445, 3, 5.33, 1.054, 2.5]


List.remove(3)
print(List)

Output
[2.3, 4.445, 5.33, 1.054, 2.5]
Tuples:
• Python Tuple is a collection of objects separated by commas. In some ways, a tuple is
similar to a Python list in terms of indexing, nested objects, and repetition but the main
difference between both is Python tuple is immutable, unlike the Python list which is
mutable.
Creating Python Tuples
There are various ways by which you can create a tuple in Python. They are as follows:
• Using round brackets
• With one item
• Tuple Constructor
Create Tuples using Round Brackets ()
To create a tuple we will use () operators.

var = ("Geeks", "for", "Geeks")


print(var)

Output:
('Geeks', 'for', 'Geeks')
Create a Tuple With One Item
provides us with another way to create a Tuple.
DON BOSCO COLLEGE DHARMAPURI

values : tuple[int | str, ...] = (1,2,4,"Geek")


print(values)

Output:
(1, 2, 4, 'Geek')
Tuple Constructor in Python
To create a tuple with a Tuple constructor, we will pass the elements as its parameters.

tuple_constructor = tuple(("dsa", "developement", "deep learning"))


print(tuple_constructor)

Output :
('dsa', 'developement', 'deep learning')

What is Immutable in Tuples?


• Tuples in Python are similar to Python lists but not entirely. Tuples are immutable and
ordered and allow duplicate values. Some Characteristics of Tuples in Python.
• We can find items in a tuple since finding any item does not make changes in the
tuple.
• One cannot add items to a tuple once it is created.
• Tuples cannot be appended or extended.
• We cannot remove items from a tuple once it is created.
Let us see this with an example.

mytuple = (1, 2, 3, 4, 5)
# tuples are indexed
print(mytuple[1])
print(mytuple[4])
# tuples contain duplicate elements
mytuple = (1, 2, 3, 4, 2, 3)
print(mytuple)
# adding an element
mytuple[1] = 100
print(mytuple)

Output:
2
5
(1, 2, 3, 4, 2, 3)
Traceback (most recent call last):
File "e0eaddff843a8695575daec34506f126.py", line 11, in
tuple1[1] = 100
TypeError: 'tuple' object does not support item assignment
DON BOSCO COLLEGE DHARMAPURI

Accessing Values in Python Tuples


• Tuples in Python provide two ways by which we can access the elements of a tuple.
• Using a positive index
• Using a negative index
Python Access Tuple using a Positive Index
Using square brackets we can get the values from tuples in Python.

var = ("Geeks", "for", "Geeks")


print("Value in Var[0] = ", var[0])
print("Value in Var[1] = ", var[1])
print("Value in Var[2] = ", var[2])

Output:
Value in Var[0] = Geeks
Value in Var[1] = for
Value in Var[2] = Geeks
Access Tuple using Negative Index
• In the above methods, we use the positive index to access the value in Python, and here
we will use the negative index within [].

var = (1, 2, 3)
print("Value in Var[-1] = ", var[-1])
print("Value in Var[-2] = ", var[-2])
print("Value in Var[-3] = ", var[-3])

Output:
Value in Var[-1] = 3
Value in Var[-2] = 2
Value in Var[-3] = 1
Different Operations Related to Tuples
Below are the different operations related to tuples in Python:
• Concatenation
• Nesting
• Repetition
• Slicing
• Deleting
• Finding the length
• Multiple Data Types with tuples
• Conversion of lists to tuples
• Tuples in a Loop
---------------------------------------------UNIT – II COMPLETED-------------------------------------
DON BOSCO COLLEGE DHARMAPURI

UNIT 3

Mapping type: Dictionaries – Mapping type operators – Mapping type Built-in and Factory
Functions - Mapping type built in methods – Conditionals and loops – if statement – else Statement
– elif statement – conditional expression – while statement – for statement – break statement –
continue statement – pass statement – Iterators and the iter( ) function - Files and Input/Output –
File objects – File built-in functions – File builtin methods – File built-in attributes – Standard files
– command line arguments.

Python Dictionary
Dictionaries are a useful data structure for storing data in Python because they are capable of imitating real-world data
arrangements where a certain value exists for a given key.

The data is stored as key-value pairs using a Python dictionary.

o This data structure is mutable


o The components of dictionary were made using keys and values.
o Keys must only have one component.
o Values can be of any type, including integer, list, and tuple.

A dictionary is, in other words, a group of key-value pairs, where the values can be any Python object. The keys, in contrast,
are immutable Python objects, such as strings, tuples, or numbers. Dictionary entries are ordered as of Python version 3.7. In
Python 3.6 and before, dictionaries are generally unordered.

Creating the Dictionary


Curly brackets are the simplest way to generate a Python dictionary, although there are other approaches as well. With many
key-value pairs surrounded in curly brackets and a colon separating each key from its value, the dictionary can be built. (:).
The following provides the syntax for defining the dictionary.

Syntax:

Dict = {"Name": "Gayle", "Age": 25}

In the above dictionary Dict, The keys Name and Age are the strings which comes under the category of an immutable
object.

Let's see an example to create a dictionary and print its content.

Code

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


print(type(Employee))
print("printing Employee data ..... ")
print(Employee)
DON BOSCO COLLEGE DHARMAPURI
Output

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

Python provides the built-in function dict() method which is also used to create the dictionary.The

empty curly braces {} is used to create empty dictionary.

Code

# Creating an empty Dictionary


Dict = {}
print("Empty Dictionary: ")
print(Dict)

# Creating a Dictionary
# with dict() method
Dict = dict({1: 'Hcl', 2: 'WIPRO', 3:'Facebook'})
print("\nCreate Dictionary by using dict(): ")
print(Dict)

# Creating a Dictionary
# with each item as a Pair
Dict = dict([(4, 'Rinku'), (2, Singh)])
print("\nDictionary with each item as a pair: ")
print(Dict)

Output

Empty Dictionary:
{}

Create Dictionary by using dict():


{1: 'Hcl', 2: 'WIPRO', 3: 'Facebook'}

Dictionary with each item as a pair:


{4: 'Rinku', 2: 'Singh'}

Accessing the dictionary values


To access data contained in lists and tuples, indexing has been studied. The keys of the dictionary can be used to obtain the
values because they are unique from one another. The following method can be used to access dictionary values.

Code

Employee = {"Name": "Dev", "Age": 20, "salary":45000,"Company":"WIPRO"}


print(type(Employee))
DON BOSCO COLLEGE DHARMAPURI

print("printing Employee data ..... ")


print("Name : %s" %Employee["Name"])
print("Age : %d" %Employee["Age"])
print("Salary : %d" %Employee["salary"])
print("Company : %s" %Employee["Company"])

Output

ee["Company"])
Output
<class 'dict'>
printing Employee data ....
Name : Dev
Age : 20
Salary : 45000
Company : WIPRO

Python provides us with an alternative to use the get() method to access the dictionary values. It would give the same result
as given by the indexing.

Adding Dictionary Values


The dictionary is a mutable data type, and utilising the right keys allows you to change its values. Dict[key] = value and the
value can both be modified. An existing value can also be updated using the update() method.

Note: The value is updated if the key-value pair is already present in the dictionary. Otherwise, the dictionary's newly added keys.

Let's see an example to update the dictionary values.

Example - 1:

Code

# Creating an empty Dictionary


Dict = {}
print("Empty Dictionary: ")
print(Dict)

# Adding elements to dictionary one at a time


Dict[0] = 'Peter'
Dict[2] = 'Joseph'
Dict[3] = 'Ricky'
print("\nDictionary after adding 3 elements: ")
print(Dict)

# Adding set of values


# with a single Key
# The Emp_ages doesn't exist to dictionary
DON BOSCO COLLEGE DHARMAPURI

Dict['Emp_ages'] = 20, 33, 24


print("\nDictionary after adding 3 elements: ")
print(Dict)

# Updating existing Key's Value


Dict[3] = 'JavaTpoint'
print("\nUpdated key value: ")
print(Dict)

Output

Empty Dictionary:
{}

Dictionary after adding 3 elements:


{0: 'Peter', 2: 'Joseph', 3: 'Ricky'}

Dictionary after adding 3 elements:


{0: 'Peter', 2: 'Joseph', 3: 'Ricky', 'Emp_ages': (20, 33, 24)}

Updated key value:


{0: 'Peter', 2: 'Joseph', 3: 'JavaTpoint', 'Emp_ages': (20, 33, 24)}

Deleting Elements using del Keyword


The items of the dictionary can be deleted by using the del keyword as given below.

Code

Employee = {"Name": "David", "Age": 30, "salary":55000,"Company":"WIPRO"}


print(type(Employee))
print("printing Employee data ..... ")
print(Employee)
print("Deleting some of the employee data")
del Employee["Name"]
del Employee["Company"]
print("printing the modified information ")
print(Employee)
print("Deleting the dictionary: Employee");
del Employee
print("Lets try to print it again ");
print(Employee)

Output

<class 'dict'>
printing Employee data ....
DON BOSCO COLLEGE DHARMAPURI
{'Name': 'David', 'Age': 30, 'salary': 55000, 'Company': 'WIPRO'}
Deleting some of the employee data
printing the modified information
{'Age': 30, 'salary': 55000}
Deleting the dictionary: Employee
Lets try to print it again
NameError: name 'Employee' is not defined.

The last print statement in the above code, it raised an error because we tried to print the Employee
dictionary that already deleted.

Mapping Type Operators

Dictionaries will work with all of the standard type operators but do not support operations such as
concatenation and repetition. Those operations, although they make sense for sequence types, do not
translate to mapping types. In the next two subsections, we introduce you to the operators you can use
with dictionaries.

Standard Type Operators

The standard type operators were introduced in Chapter 4. Here are some basic examples using some of
those operators:

>>> dict4 = {'abc': 123} >>> dict5 = {'abc': 456} >>> dict6 = {'abc': 123, 98.6: 37} >>> dict7 = {'xyz':
123} >>> dict4 < dict5 True >>> (dict4 < dict6) and (dict4 < dict7) True >>> (dict5 < dict6) and (dict5
< dict7) True >>> dict6 < dict7 False

How are all these comparisons performed? Like lists and tuples, the process is a bit more complex than
it is for numbers and strings.
Mapping Type Operators

Dictionary Key-Lookup Operator ( [ ] )

The only operator specific to dictionaries is the key-lookup operator, which works very similarly to the
single element slice operator for sequence types.

For sequence types, an index offset is the sole argument or subscript to access a single element of a
sequence. For a dictionary, lookups are by key, so that is the argument rather than an index. The key-
lookup operator is used for both assigning values to and retrieving values from a dictionary:

d[k] = v # set value 'v' in dictionary with key 'k' d[k] # lookup value in dictionary with key 'k'
(Key) Membership (in, not in)
programmers can use the in and not in operators to check key membership instead of
the has_key() method:

>>> 'name' in dict2 True >>> 'phone' in dict2 False

Mapping Type Built-in and Factory Functions


DON BOSCO COLLEGE DHARMAPURI
Standard Type Functions [type(), str(), and cmp()]

The type() factory function, when applied to a dict, returns, as you might expect, the dict type, "<type 'dict'>".
The str() factory function will produce a printable string representation of a dictionary. These are fairly
straightforward.

In each of the last three chapters, we showed how the cmp() BIF worked with numbers, strings, lists, and
tuples. So how about dictionaries? Comparisons of dictionaries are based on an algorithm that starts with
sizes first, then keys, and finally values. However, using cmp() on dictionaries isn't usually very useful.

The next subsection goes into further detail about the algorithm used to compare dictionaries, but this is
advanced reading, and definitely optional since comparing dictionaries is not very useful or very common.

*Dictionary Comparison Algorithm

In the following example, we create two dictionaries and compare them, then slowly modify the
dictionaries to show how these changes affect their comparisons:

>>> dict1 = {} >>> dict2 = {'host': 'earth', 'port': 80} >>> cmp(dict1, dict2) -1 >>> dict1['host'] =
'earth' >>> cmp(dict1, dict2) -1

In the first comparison, dict1 is deemed smaller because dict2 has more elements (2 items vs. 0 items).
After adding one element to dict1, it is still smaller (2 vs. 1), even if the item added is also in dict2.
>>> dict1['port'] = 8080 >>> cmp(dict1, dict2) 1 >>> dict1['port'] = 80 >>> cmp(dict1, dict2) 0

After we add the second element to dict1, both dictionaries have the same size, so their keys are then
compared. At this juncture, both sets of keys match, so comparison proceeds to checking their values.
The values for the 'host' keys are the same, but when we get to the 'port' key, dict2 is deemed larger because
its value is greater than that of dict1's 'port' key (8080 vs. 80). When resetting dict2's 'port' key to the same
value as dict1's 'port' key, then both dictionaries form equals: They have the same size, their keys match,
and so do their values, hence the reason that 0 is returned by cmp().

>>> dict1['prot'] = 'tcp' >>> cmp(dict1, dict2) 1 >>> dict2['prot'] = 'udp' >>> cmp(dict1, dict2) -1
As soon as an element is added to one of the dictionaries, it immediately becomes the "larger one," as in
this case with dict1. Adding another key-value pair to dict2 can tip the scales again, as both dictionaries'
sizes match and comparison progresses to checking keys and values.

>>> cdict = {'fruits':1} >>> ddict = {'fruits':1} >>> cmp(cdict, ddict) 0 >>> cdict['oranges'] = 0 >>>
ddict['apples'] = 0 >>> cmp(cdict, ddict) 14

Our final example reminds as that cmp() may return values other than -1, 0, or 1. The algorithm pursues
comparisons in the following order.
DON BOSCO COLLEGE DHARMAPURI
(1) Compare Dictionary Sizes

If the dictionary lengths are different, then for cmp (dict1, dict2), cmp() will return a positive numberif
dict1 is longer and a negative number if dict2 is longer. In other words, the dictionary with more keysis
greater, i.e.,

len(dict1) > len(dict2) dict1 > dict2

(2) Compare Dictionary Keys


If both dictionaries are the same size, then their keys are compared; the order in which the keys are
checked is the same order as returned by the keys() method. (It is important to note here that keys thatare
the same will map to the same locations in the hash table. This keeps key-checking consistent.) At the
point where keys from both do not match, they are directly compared and cmp() will return a positive
number if the first differing key for dict1 is greater than the first differing key of dict2.

(3) Compare Dictionary Values

If both dictionary lengths are the same and the keys match exactly, the values for each key in both
dictionaries are compared. Once the first key with non-matching values is found, those values are
compared directly. Then cmp() will return a positive number if, using the same key, the value in dict1 is
greater than the value in dict2.

(4) Exact Match

If we have reached this point, i.e., the dictionaries have the same length, the same keys, and the same
values for each key, then the dictionaries are an exact match and 0 is returned.

illustrates the dictionary compare algorithm we just outlined.


DON BOSCO COLLEGE DHARMAPURI
Figure : How dictionaries are compared

Mapping Type Related Functions

dict ( )

The dict() factory function is used for creating dictionaries. If no argument is provided, then an empty
dictionary is created. The fun happens when a container object is passed in as an argument to dict().

If the argument is an iterable, i.e., a sequence, an iterator, or an object that supports iteration, then each
element of the iterable must come in pairs. For each pair, the first element will be a new key in the
dictionary with the second item as its value. Taking a cue from the official Python documentationfor
dict():

>>> dict(zip(('x', 'y'), (1, 2))) {'y': 2, 'x': 1} >>> dict([['x', 1], ['y', 2]]) {'y': 2, 'x': 1} >>> dict([('xy'[i-1],
i) for i in range(1,3)]) {'y': 2, 'x': 1}

If it is a(nother) mapping object, i.e., a dictionary, then dict() will just create a new dictionary and copy
the contents of the existing one. The new dictionary is actually a shallow copy of the original one and the
same results can be accomplished by using a dictionary's copy() built-in method. Because creating a new
dictionary from an existing one using dict() is measurably slower than using copy(), we recommend using
the latter.
DON BOSCO COLLEGE DHARMAPURI
Starting in Python 2.3, it is possible to call dict() with an existing dictionary or keyword argument
dictionary (** function operator, covered in Chapter 11):

>>> dict(x=1, y=2) {'y': 2, 'x': 1} >>> dict8 = dict(x=1, y=2) >>> dict8 {'y': 2, 'x': 1} >>> dict9 =
dict(**dict8) >>> dict9 {'y': 2, 'x': 1}

We remind viewers that the dict9 example is only an exercise in understanding the calling semantics of
dict() and not a realistic example. It would be wiser (and better performance-wise) to execute something
more along the lines of:

>>> dict9 = dict8.copy() >>> dict9 {'y': 2, 'x' : 1}

len()
The len() BIF is flexible. It works with sequences, mapping types, and sets (as we will find out later on
in this chapter). For a dictionary, it returns the total number of items, that is, key-value pairs:

>>> dict2 = {'name': 'earth', 'port': 80} >>> dict2 {'port': 80, 'name': 'earth'} >>> len(dict2) 2

We mentioned earlier that dictionary items are unordered. We can see that above, whenreferencing
dict2, the items are listed in reverse order from which they were entered into the dictionary.hash()

The hash() BIF is not really meant to be used for dictionaries per se, but it can be used to determine whether
an object is fit to be a dictionary key (or not). Given an object as its argument, hash() returns thehash value
of that object. The object can only be a dictionary key if it is hashable (meaning this function returns a[n
integer] value without errors or raising an exception). Numeric values that are equal (when pitted against
each other using a comparison operator) hash to the same value (even if theirtypes differ). A TypeError
will occur if an unhashable type is given as the argument to hash() (andconsequently if an attempt is made
to use such an object as the key when assigning a value to a dictionary):

>>> hash([]) Traceback (innermost last): File "<stdin>", line 1, in ? TypeError: list objects are unhashable
>>> >>> dict2[{}] = 'foo' Traceback (most recent call last): File "<stdin>", line 1, in ? TypeError: dict
objects are unhashable

Mapping Type Related Functions

Function Operation
dict([container])Factory
function for creating a dictionary populated with items from container, if provided;
if not, an empty dict is created
len(mapping) Returns the length of mapping (number of key-value pairs)
hash(obj) Returns
Python Mapping hash value of obj
Types
DON BOSCO COLLEGE DHARMAPURI
The mapping objects are used to map hash table values to arbitrary objects. In python there is mapping
type called dictionary. It is mutable.

The keys of the dictionary are arbitrary. As the value, we can use different kind of elements like lists,
integers or any other mutable type objects.

Some dictionary related methods and operations are −

Method len(d)

The len() method returns the number of elements in the dictionary.

Operation d[k]

It will return the item of d with the key ‘k’. It may raise KeyError if the key is not mapped.

Method iter(d)

This method will return an iterator over the keys of dictionary. We can also perform this taks by
using iter(d.keys()).

Method get(key[, default])

The get() method will return the value from the key. The second argument is optional. If the key is not
present, it will return the default value.

Method items()

It will return the items using (key, value) pairs format.

Method keys()

Return the list of different keys in the dictionary.

Method values()

Return the list of different values from the dictionary.

Method update(elem)

Modify the element elem in the dictionary.

Example Code

myDict = {'ten' : 10, 'twenty' : 20, 'thirty' : 30, 'forty' : 40}


print(myDict)
print(list(myDict.keys()))
print(list(myDict.values()))
DON BOSCO COLLEGE DHARMAPURI

#create items from the key-value pairs


print(list(myDict.items()))

myDict.update({'fifty' : 50})
print(myDict)

Output

{'ten': 10, 'twenty': 20, 'thirty': 30, 'forty': 40}


['ten', 'twenty', 'thirty', 'forty']
[10, 20, 30, 40]
[('ten', 10), ('twenty', 20), ('thirty', 30), ('forty', 40)]
{'ten': 10, 'twenty': 20, 'thirty': 30, 'forty': 40, 'fifty': 50}

The most straightforward form contrasts a subject value with one or more regular expressions:

Python If-else statements

Decision making is the most important aspect of almost all the programming languages. As the name
implies, decision making allows us to run a particular block of code for a particular decision. Here, the
decisions are made on the validity of the particular conditions. Condition checking is the backbone of
decision making.

In python, decision making is performed by the following statements.

Statement Description

If Statement The if statement is used to test a specific condition. If the condition is true, a
block of code (if-block) will be executed.

If - else The if-else statement is similar to if statement except the fact that, it also
Statement provides the block of the code for the false case of the condition to be checked.
If the condition provided in the if statement is false, then the else statement will
be executed.

Nested if Nested if statements enable us to use if ? else statement inside an outer if


Statement statement.

Indentation in Python

For the ease of programming and to achieve simplicity, python doesn't allow the use of parentheses for
the block level code. In Python, indentation is used to declare a block. If two statements are at the same
indentation level, then they are the part of the same block.

Generally, four spaces are given to indent the statements which are a typical amount of indentation in
python.
DON BOSCO COLLEGE DHARMAPURI
Indentation is the most used part of the python language since it declares the block of code. All the
statements of one block are intended at the same level indentation. We will see how the actual indentation
takes place in decision making and other stuff in python.

The if statement

The if statement is used to test a particular condition and if the condition is true, it executes a block of
code known as if-block. The condition of if statement can be any valid logical expression which can be
either evaluated to true or false.

The syntax of the if-statement is given below.

if expression:
statement

Example 1

# Simple Python program to understand the if statement


nu m = int(input("enter the number:"))
# H ere, we are taking an integer num and taking input dynamically
if num%2 == 0:
# H ere, we are checking the condition. If the condition is true, we will enter the block
print("The Given number is an even number")

Output:

enter the number: 10


The Given number is an even number

Example 2 : Program to print the largest of the three numbers.

# Simple Python Program to print the largest of the three numbers.


a = int (input("Enter a: "));
b = int (input("Enter b: "));
c = int (input("Enter c: "));
DON BOSCO COLLEGE DHARMAPURI

if a>b and a>c:


# Here, we are checking the condition. If the condition is true, we will enter the block
print ("From the above three numbers given a is largest");
if b>a and b>c:
# Here, we are checking the condition. If the condition is true, we will enter the block
print ("From the above three numbers given b is largest");
if c>a and c>b:
# Here, we are checking the condition. If the condition is true, we will enter the block
print ("From the above three numbers given c is largest");

Output:

Enter a: 100
Enter b: 120
Enter c: 130
From the above three numbers given c is largest

The if-else statement

The if-else statement provides an else block combined with the if statement which is executed in the
false case of the condition.

If the condition is true, then the if-block is executed. Otherwise, the else-block is executed.

The syntax of the if-else statement is given below.

if condition:
#block of statements
else:
#another block of statements (else-block)

Example 1 : Program to check whether a person is eligible to vote or not.

# Simple Python Program to check whether a person is eligible to vote or not.


age = int (input("Enter your age: "))
DON BOSCO COLLEGE DHARMAPURI

# Here, we are taking an integer num and taking input dynamically


if age>=18:
# Here, we are checking the condition. If the condition is true, we will enter the block
print("You are eligible to vote !!");
else:
print("Sorry! you have to wait !!");

Output:

Enter your age: 90


You are eligible to vote !!

Example 2: Program to check whether a number is even or not.

# Simple Python Program to check whether a number is even or not.


num = int(input("enter the number:"))
# Here, we are taking an integer num and taking input dynamically
if num%2 == 0:
# Here, we are checking the condition. If the condition is true, we will enter the block
print("The Given number is an even number")
else:
print("The Given Number is an odd number")

Output:

enter the number: 10


The Given number is even number

The elif statement

The elif statement enables us to check multiple conditions and execute the specific block of statements
depending upon the true condition among them. We can have any number of elif statements in our
program depending upon our need. However, using elif is optional.

The elif statement works like an if-else-if ladder statement in C. It must be succeeded by an if statement.

The syntax of the elif statement is given below.

if expression 1:
# block of statements

elif expression 2:
# block of statements

elif expression 3:
# block of statements
DON BOSCO COLLEGE DHARMAPURI

else:
# block of statements

Example

# Simple Python program to understand elif statement


number = int(input("Enter the number?"))
# Here, we are taking an integer number and taking input dynamically
if number==10:
# Here, we are checking the condition. If the condition is true, we will enter the block
print("The given number is equals to 10")
elif number==50:
# Here, we are checking the condition. If the condition is true, we will enter the block
print("The given number is equal to 50");
elif number==100:
# Here, we are checking the condition. If the condition is true, we will enter the block
print("The given number is equal to 100");
else:
print("The given number is not equal to 10, 50 or 100");

Output:

Enter the number?15


The given number is not equal to 10, 50 or 100
Enter the marks? 89
Congrats ! you scored grade A ...

Python Loops
DON BOSCO COLLEGE DHARMAPURI
The following loops are available in Python to fulfil the looping needs. Python offers 3 choices for
running the loops. The basic functionality of all the techniques is the same, although the syntax and the
amount of time required for checking the condition differ.

We can run a single statement or set of statements repeatedly using a loop command.

The following sorts of loops are available in the Python programming language.

Sr.No. Name of Loop Type & Description


the loop

1 While loop Repeats a statement or group of statements while a given condition is


TRUE. It tests the condition before executing the loop body.

2 For loop This type of loop executes a code block multiple times and
abbreviates the code that manages the loop variable.

3 Nested We can iterate a loop inside another loop.


loops

Loop Control Statements

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

Python provides the following control statements. We will discuss them later in detail.

Let us quickly go over the definitions of these loop control statements.

Sr.No. Name of the Description


control
statement

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

2 Continue This command skips the current iteration of the loop. The
statement statements following the continue statement are not executed
once the Python interpreter reaches the continue statement.

3 Pass statement The pass statement is used when a statement is syntactically


necessary, but no code is to be executed.

The for Loop

Python's for loop is designed to repeatedly execute a code block while iterating through a list, tuple,
dictionary, or other iterable objects of Python. The process of traversing a sequence is known as iteration.
DON BOSCO COLLEGE DHARMAPURI
Syntax of the for Loop

for value in sequence:


{ code block }

In this case, the variable value is used to hold the value of every item present in the sequence before the
iteration begins until this particular iteration is completed.

Loop iterates until the final item of the sequence are reached.

Code

# Python program to show how the for loop works

# Creating a sequence which is a tuple of numbers


numbers = [4, 2, 6, 7, 3, 5, 8, 10, 6, 1, 9, 2]

# variable to store the square of the number


square = 0

# Creating an empty list


squares = []

# Creating a for loop


for value in numbers:
square = value ** 2
squares.append(square)
print("The list of squares is", squares)

Output:

The list of squares is [16, 4, 36, 49, 9, 25, 64, 100, 36, 1, 81, 4]

Using else Statement with for Loop

As already said, a for loop executes the code block until the sequence element is reached. The statement
is written right after the for loop is executed after the execution of the for loop is complete.

Only if the execution is complete does the else statement comes into play. It won't be executed if we
exit the loop or if an error is thrown.

Here is a code to better understand if-else statements.

Code

# Python program to show how if-else statements work


DON BOSCO COLLEGE DHARMAPURI

string = "Python Loop"

# Initiating a loop
for s in a string:
# giving a condition in if block
if s == "o":
print("If block")
# if condition is not satisfied then else block will be executed
else:
print(s)

Output:

P
y
t
h
If block
n

L
If block
If block
p

Now similarly, using else with for loop.

Syntax:

for value in sequence:


# executes the statements until sequences are exhausted
else:
# executes these statements when for loop is completed

Code

# Python program to show how to use else statement with for loop

# Creating a sequence
tuple_ = (3, 4, 6, 8, 9, 2, 3, 8, 9, 7)

# Initiating the loop


for value in tuple_:
if value % 2 != 0:
print(value)
# giving an else statement
else:
DON BOSCO COLLEGE DHARMAPURI

print("These are the odd numbers present in the tuple")

Output:

3
9
3
9
7
These are the odd numbers present in the tuple

The range() Function

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

We can give specific start, stop, and step size values in the manner range(start, stop, step size). If the step
size is not specified, it defaults to 1.

Since it doesn't create every value it "contains" after we construct it, the range object can be characterized
as being "slow." It does provide in, len, and getitem actions, but it is not an iterator.

The example that follows will make this clear.

Code

# Python program to show the working of range() function

print(range(15))

print(list(range(15)))

print(list(range(4, 9)))

print(list(range(5, 25, 4)))

Output:

range(0, 15)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14]
[4, 5, 6, 7, 8]
[5, 9, 13, 17, 21]

To iterate through a sequence of items, we can apply the range() method in for loops. We can use indexing
to iterate through the given sequence by combining it with an iterable's len() function. Here's an
illustration.

Code
DON BOSCO COLLEGE DHARMAPURI

# Python program to iterate over a sequence with the help of indexing

tuple_ = ("Python", "Loops", "Sequence", "Condition", "Range")

# iterating over tuple_ using range() function


for iterator in range(len(tuple_)):
print(tuple_[iterator].upper())

Output:

PYTHON
LOOPS
SEQUENCE
CONDITION
RANGE

While Loop

While loops are used in Python to iterate until a specified condition is met. However, the statement in
the program that follows the while loop is executed once the condition changes to false.

Syntax of the while loop is:

while <condition>:
{ code block }

All the coding statements that follow a structural command define a code block. These statements
are intended with the same number of spaces. Python groups statements together with indentation.
Code

# Python program to show how to use a while loop


counter = 0
# Initiating the loop
while counter < 10: # giving the condition
counter = counter + 3
print("Python Loops")

Output:

Python Loops
Python Loops
Python Loops
Python Loops

Using else Statement with while Loops

As discussed earlier in the for loop section, we can use the else statement with the while loop also. It
has the same syntax.
DON BOSCO COLLEGE DHARMAPURI
Code

#Python program to show how to use else statement with the while loop
counter = 0

# Iterating through the while loop


while (counter < 10):
counter = counter + 3
print("Python Loops") # Executed untile condition is met
# Once the condition of while loop gives False this statement will be executed
else:
print("Code block inside the else statement")

Output:

Python Loops
Python Loops
Python Loops
Python Loops
Code block inside the else statement

Single statement while Block

The loop can be declared in a single statement, as seen below. This is similar to the if-else block, where
we can write the code block in a single line.

Code

# Python program to show how to write a single statement while loop


counter = 0
while (count < 3): print("Python Loops")

Loop Control Statements

Now we will discuss the loop control statements in detail. We will see an example of each
control statement.

Continue Statement

It returns the control to the beginning of the loop.

Code

# Python program to show how the continue statement works

# Initiating the loop


for string in "Python Loops":
DON BOSCO COLLEGE DHARMAPURI

if string == "o" or string == "p" or string == "t":


continue
print('Current Letter:', string)

Output:

Current Letter: P
Current Letter: y
Current Letter: h
Current Letter: n
Current Letter:
Current Letter: L
Current Letter: s

Break Statement

It stops the execution of the loop when the break statement is reached.

Code

# Python program to show how the break statement works

# Initiating the loop


for string in "Python Loops":
if string == 'L':
break
print('Current Letter: ', string)

Output:

Current Letter: P
Current Letter: y
Current Letter: t
Current Letter: h
Current Letter: o
Current Letter: n
Current Letter:

Pass Statement

Pass statements are used to create empty loops. Pass statement is also employed for classes, functions,
and empty control statements.

Code

# Python program to show how the pass statement works


for a string in "Python Loops":
pass
DON BOSCO COLLEGE DHARMAPURI

print( 'Last Letter:', string)

Output:

Last Letter: s
Conditional Expressions in Python

Python's conditional statements carry out various calculations or operations according to whether a
particular Boolean condition is evaluated as true or false. In Python, IF statements deal with conditional
statements.

We'll learn how to use conditional statements in Python in this tutorial.

What is Python If Statement?

To make decisions, utilize the if statement in Python. It has a body of instructions that only executes
whenever the if statement's condition is met. The additional else statement, which includes some
instructions for the else statement, runs if the if condition is false.

Python's if-else statement is used when you wish to satisfy one statement while the other is false.

Python Syntax of the if Statement:

if <conditional expression>
Statement
else
Statement

Code

# Python program to execute if statement

a, b = 6, 5

# Initializing the if condition


if a > b:
code = "a is greater than b"
print(code)

Output:

a is greater than b

How to Use the else Condition?

The "else condition" is usually used when judging one statement based on another. If the condition
mentioned in the if code block is wrong, then the interpreter will execute the else code block.
DON BOSCO COLLEGE DHARMAPURI
Code

# Python program to execute if-else statement

a, b = 6, 5

# Initializing the if-else condition


if a < b:
code = "a is less than b"
print(code)
else:
print("a is greater than b")

Output:

a is greater than b

When the else Statement does not Work

There could be a lot of situations where your "otherwise condition" doesn't produce the desired
outcome. Due to a flaw in the program's logic, it will print the incorrect result. This typically
occurs when there are more than two statements or conditions in a program.

An illustration will make this notion easier for you to grasp.

Since both variables, in this case, are identical (9, 9), the program's output that "x is greater than
y" is FALSE. This is because it evaluates the first condition, or the if expression in Python, then
prints the next condition (the else statement) by default if the first condition fails. The following
step will examine how to fix this mistake.

Code

# Python program when else condition does not work

a, b = 9, 9

# Initializing the if-else condition


if a < b:
code = "a is less than b"
else:
code = "a is greater than b"

print(code)

Output:

a is greater than b
DON BOSCO COLLEGE DHARMAPURI

How to use the elif Condition?

We can employ the "elif" clause to fix the issue caused by the "else condition" made earlier. You
can instruct the software to print the third condition or alternative when the first two conditions
fail or are erroneous by using the "elif" condition.

Code

# Python program to show how to use elif condition

a, b = 9, 9

# Initializing the if-else condition


if a < b:
code = "a is less than b"
elif a == b:
code = "a is equal to b"
else:
code = "a is greater than b"

print(code)

Output:

a is equal to b

Python Nested if Statement

The following example demonstrates nested if Statement Python

Code

# Python program to show the nested if-else conditions

A = 100
B = 200
C = 300

# Initializing the if-else conditions


if B > A:
if B > C:
print("B is the largest number")
else:
if A > B:
if A > C:
DON BOSCO COLLEGE DHARMAPURI

print("A is the largest number")


elif C > A:
if C > B:

print("C is the largest number")


else:

print("All numbers are equal")

if B % C == 0:
if A % C == 0:
print("C is a common factor of A and B")

Output:

C is the largest number

Python Iterators
An iterator is an object that contains a countable number of values.

An iterator is an object that can be iterated upon, meaning that you can traverse through all the values.

Technically, in Python, an iterator is an object which implements the iterator protocol, which consist of the
methods iter () and next ().

Iterator vs Iterable

Lists, tuples, dictionaries, and sets are all iterable objects. They are iterable containers which you can
get an iterator from.

All these objects have a iter() method which is used to get an iterator:

Example

Return an iterator from a tuple, and print each value:

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


myit = iter(mytuple)

print(next(myit))
print(next(myit))
print(next(myit))
Even strings are iterable objects, and can return an iterator:
Example

Strings are also iterable objects, containing a sequence of characters:


DON BOSCO COLLEGE DHARMAPURI
mystr = "banana"
myit = iter(mystr)

print(next(myit))
print(next(myit))
print(next(myit))
print(next(myit))
print(next(myit))
print(next(myit))
Looping Through an Iterator

We can also use a for loop to iterate through an iterable object:

Example

Iterate the values of a tuple:

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

for x in mytuple:
print(x)
Example

Iterate the characters of a string:

mystr = "banana"

for x in mystr:
print(x)

The for loop actually creates an iterator object and executes the next() method for each loop.

Create an Iterator

To create an object/class as an iterator you have to implement the methods iter () and next () toyour
object.

As you have learned in the Python Classes/Objects chapter, all classes have a function called init (),
which allows you to do some initializing when the object is being created.

The iter () method acts similar, you can do operations (initializing etc.), but must always return the
iterator object itself.

The next () method also allows you to do operations, and must return the next item in the sequence.

Example

Create an iterator that returns numbers, starting with 1, and each sequence will increase by one
(returning 1,2,3,4,5 etc.):
DON BOSCO COLLEGE DHARMAPURI
class MyNumbers:
def iter (self):
self.a = 1
return self

def next (self):


x = self.a
self.a += 1
return x

myclass = MyNumbers()
myiter = iter(myclass)

print(next(myiter))
print(next(myiter))
print(next(myiter))
print(next(myiter))
print(next(myiter))

StopIteration

The example above would continue forever if you had enough next() statements, or if it was used in
a for loop.

To prevent the iteration from going on forever, we can use the StopIteration statement.

In the next () method, we can add a terminating condition to raise an error if the iteration is done a
specified number of times:

Example

Stop after 20 iterations:

class MyNumbers:
def iter (self):
self.a = 1
return self

def next (self):


if self.a <= 20:
x = self.a
self.a += 1
return x
else:
raise StopIteration

myclass = MyNumbers()
myiter = iter(myclass)
DON BOSCO COLLEGE DHARMAPURI
for x in myiter:
print(x)
Python iter() Function

The python iter() function is used to return an iterator object. It creates an object which can be iterated
one element at a time.

Signature

iter(object, sentinel)

Parameters

object: An iterable object.

sentinel (optional)- It is a special value that represents the end of a sequence.

Return

It returns an iterator object.

Python iter() Function Example 1

The below example shows the working of iter().

# list of numbers
list = [1,2,3,4,5]

listIter = iter(list)

# prints '1'
print(next(listIter))

# prints '2'
print(next(listIter))

# prints '3'
print(next(listIter))

# prints '4'
print(next(listIter))

# prints '5'
print(next(listIter))

Output:
DON BOSCO COLLEGE DHARMAPURI
1
2
3
4
5

Explanation: In the above example, iter() function converts an list iterable to an iterator.

Python File Handling

Introduction:

In this tutorial, we are discussing Python file handling. Python supports the file-handling process. Till
now, we were taking the input from the console and writing it back to the console to interact with the
user. Users can easily handle the files, like read and write the files in Python. In another programming
language, the file-handling process is lengthy and complicated. But we know Python is an easy
programming language. So, like other things, file handling is also effortless and short in Python.

Sometimes, it is not enough to only display the data on the console. The data to be displayed may be very
large, and only a limited amount of data can be displayed on the console since the memory is volatile, it
is impossible to recover the programmatically generated data again and again.

The file handling plays an important role when the data needs to be stored permanently into the file. A
file is a named location on disk to store related information. We can access the stored information (non-
volatile) after the program termination.

In Python, files are treated in two modes as text or binary. The file may be in the text or binary format,
and each line of a file is ended with the special character like a comma (,) or a newline character. Python
executes the code line by line. So, it works in one line and then asks the interpreter to start the new line
again. This is a continuous process in Python.

Hence, a file operation can be done in the following order.

o Open a file
o Read or write - Performing operation
o Close the file

Opening a file

A file operation starts with the file opening. At first, open the File then Python will start the operation.
File opening is done with the open() function in Python. This function will accepts two arguments, file
name and access mode in which the file is accessed. When we use the open() function, that time we must
be specified the mode for which the File is opening. The function returns a file object which can be used
to perform various operations like reading, writing, etc.

Syntax:

The syntax for opening a file in Python is given below -


DON BOSCO COLLEGE DHARMAPURI

file object = open(<file-name>, <access-mode>, <buffering>)

The files can be accessed using various modes like read, write, or append. The following are the details
about the access mode to open a file.

SN Access Description
mode

1 r r means to read. So, it opens a file for read-only operation. The file pointer
exists at the beginning. The file is by default open in this mode if no access
mode is passed.

2 rb It opens the file to read-only in binary format. The file pointer exists at the
beginning of the file.

3 r+ It opens the file to read and write both. The file pointer exists at the
beginning of the file.

4 rb+ It opens the file to read and write both in binary format. The file pointer
exists at the beginning of the file.

5 w It opens the file to write only. It overwrites the file if previously exists or
creates a new one if no file exists with the same name. The file pointer exists
at the beginning of the file.

6 wb It opens the file to write only in binary format. It overwrites the file if it exists
previously or creates a new one if no file exists. The file pointer exists at the
beginning of the file.

7 w+ It opens the file to write and read both. It is different from r+ in the sense that
it overwrites the previous file if one exists whereas r+ doesn't overwrite the
previously written file. It creates a new file if no file exists. The file pointer
exists at the beginning of the file.

8 wb+ It opens the file to write and read both in binary format. The file pointer
exists at the beginning of the file.

9 a It opens the file in the append mode. The file pointer exists at the end of the
previously written file if exists any. It creates a new file if no file exists with
the same name.

10 ab It opens the file in the append mode in binary format. The pointer exists at
the end of the previously written file. It creates a new file in binary format
if no file exists with the same name.

11 a+ It opens a file to append and read both. The file pointer remains at the end
of the file if a file exists. It creates a new file if no file exists with the same
name.

12 ab+ It opens a file to append and read both in binary format. The file pointer
remains at the end of the file.
DON BOSCO COLLEGE DHARMAPURI
Let's look at the simple example to open a file named "file.txt" (stored in the same directory) in read mode
and printing its content on the console.

Program code for read mode:

It is a read operation in Python. We open an existing file with the given code and then read it. The code
is given below -

#opens the file file.txt in read mode


fileptr = open("file.txt","r")

if fileptr:
print("file is opened successfully")

Output:

Now we compile the above code in Python, and after successful compilation, we run it. Then the output
is given below -

<class '_io.TextIOWrapper'>
file is opened successfully

In the above code, we have passed filename as a first argument and opened file in read mode as we
mentioned r as the second argument. The fileptr holds the file object and if the file is opened successfully,
it will execute the print statement

Program code for Write Mode:

It is a write operation in Python. We open an existing file using the given code and then write on it. The
code is given below -

file = open('file.txt','w')
file.write("Here we write a command")
file.write("Hello users of JAVATPOINT")
file.close()

Output:

Now we compile the above code in Python, and after successful compilation, we run it. Then the output
is given below -

> Hi
ERROR!
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'Hi' is not defined

The close() Method


DON BOSCO COLLEGE DHARMAPURI
The close method used to terminate the program. Once all the operations are done on the file, we must
close it through our Python script using the close() method. Any unwritten information gets destroyed
once the close() method is called on a file object.

We can perform any operation on the file externally using the file system which is the currently opened
in Python; hence it is good practice to close the file once all the operations are done. Earlier use of the
close() method can cause the of destroyed some information that you want to write in your File.

The syntax to use the close() method is given below.

Syntax

The syntax for closing a file in Python is given below -

fileobject.close()

Consider the following example.

Program code for Closing Method:

Here we write the program code for the closing method in Python. The code is given below -#

opens the file file.txt in read mode


fileptr = open("file.txt","r")

if fileptr:
print("The existing file is opened successfully in Python")

#closes the opened file


fileptr.close()

After closing the file, we cannot perform any operation in the file. The file needs to be properly closed.
If any exception occurs while performing some operations in the file then the program terminates without
closing the file.

We should use the following method to overcome such type of problem.

try:
fileptr = open("file.txt")
# perform file operations
finally:
fileptr.close()

The with statement

The with statement was introduced in python 2.5. The with statement is useful in the case of
manipulating the files. It is used in the scenario where a pair of statements is to be executed with a block
of code in between.
DON BOSCO COLLEGE DHARMAPURI
Syntax:

The syntax of with statement of a file in Python is given below -

with open(<file name>, <access mode>) as <file-pointer>:


#statement suite

The advantage of using with statement is that it provides the guarantee to close the file regardless of how
the nested block exits.

It is always suggestible to use the with statement in the case of files because, if the break, return, or
exception occurs in the nested block of code then it automatically closes the file, we don't need to write
the close() function. It doesn't let the file to corrupt.

Program code 1 for with statement:

Here we write the program code for with statement in Python. The code is given below -

with open("file.txt",'r') as f:
content = f.read();
print(content)

Program code 2 for with statement:

Here we write the program code for with statement in Python. The code is given below -

with open("file.txt", "H") as f:


A = f.write("Hello Coders")
Print(A)

Writing the file

To write some text to a file, we need to open the file using the open method and then we can use the
write method for writing in this File. If we want to open a file that does not exist in our system, it creates
a new one. On the other hand, if the File exists, then erase the past content and add new content to this
File. the It is done by the following access modes.

w: It will overwrite the file if any file exists. The file pointer is at the beginning of the file.

a: It will append the existing file. The file pointer is at the end of the file. It creates a new file if no file
exists.

Program code 1 for Write Method:

Here we write the program code for write method in Python. The code is given below -

# open the file.txt in append mode. Create a new file if no such file exists.
fileptr = open("file2.txt", "w")
DON BOSCO COLLEGE DHARMAPURI

# appending the content to the file


fileptr.write(''''''''Python is the modern programming language. It is done any kind of program in
shortest way.''')

# closing the opened the file


fileptr.close()

Output:

Now we compile the above code in Python, and after successful compilation, we run it. Then the output
is given below -

File2.txt
Python is the modern programming language. It is done any kind of program in shortest way.

We have opened the file in w mode. The file1.txt file doesn't exist, it created a new file and we have
written the content in the file using the write() function

Program code 2 for Write Method:

Here we write the program code for write method in Python. The code is given below -

with open(test1.txt', 'w') as file2:


file2.write('Hello coders')
fil2.write('Welcome to javaTpoint')

Output:

Now we compile the above code in Python, and after successful compilation, we run it. Then the output
is given below -

Hello coders
Welcome to javaTpoint

Program code 3 for Write Method:

Here we write the program code for write method in Python. The code is given below -

#open the file.txt in write mode.


fileptr = open("file2.txt","a")

#overwriting the content of the file


fileptr.write(" Python has an easy syntax and user-friendly interaction.")

#closing the opened file


fileptr.close()
DON BOSCO COLLEGE DHARMAPURI
Output:

Now we compile the above code in Python, and after successful compilation, we run it. Then the output
is given below -

Python is the modern day language. It makes things so simple.


It is the fastest growing language Python has an easy syntax and user-friendly interaction.

Snapshot of the file2.txt

We can see that the content of the file is modified. We have opened the file in a mode and it appended
the content in the existing file2.txt.

To read a file using the Python script, the Python provides the read() method. The read() method reads
a string from the file. It can read the data in the text as well as a binary format.

Syntax:

The syntax of read() method of a file in Python is given below -

fileobj.read(<count>)

Here, the count is the number of bytes to be read from the file starting from the beginning of the file. If
the count is not specified, then it may read the content of the file until the end.

Program code for read() Method:

Here we write the program code for read() method in Python. The code is given below -

#open the file.txt in read mode. causes error if no such file exists.
fileptr = open("file2.txt","r")
#stores all the data of the file into the variable content
content = fileptr.read(10)
# prints the type of the data stored in the file
print(type(content))
#prints the content of the file
print(content)
#closes the opened file
fileptr.close()
DON BOSCO COLLEGE DHARMAPURI
Output:

Now we compile the above code in Python, and after successful compilation, we run it. Then the output
is given below -

<class 'str'>
Python is

In the above code, we have read the content of file2.txt by using the read() function. We have passed
count value as ten which means it will read the first ten characters from the file.

If we use the following line, then it will print all content of the file. So, it only prints 'Python is'. For
read the whole file contents, the code is given below -

content = fileptr.read()
print(content)

Output:

Now we compile the above code in Python, and after successful compilation, we run it. Then the output
is given below -

Python is the modern-day language. It makes things so simple.


It is the fastest-growing programming language Python has easy an syntax and user-friendly
interaction.

Read file through for loop

We can use read() method when we open the file. Read method is also done through the for loop. We
can read the file using for loop. Consider the following example.

Program code 1 for Read File using For Loop:

Here we give an example of read file using for loop. The code is given below -

#open the file.txt in read mode. causes an error if no such file exists.
fileptr = open("file2.txt","r");
#running a for loop
for i in fileptr:
print(i) # i contains each line of the file

Output:

Now we compile the above code in Python, and after successful compilation, we run it. Then the output
is given below -

Python is the modern day language.


DON BOSCO COLLEGE DHARMAPURI
It makes things so simple.

Python has easy syntax and user-friendly interaction.

Program code 2 for Read File using For Loop:

Here we give an example of read file using for loop. The code is given below -

A = ["Hello\n", "Coders\n", "JavaTpoint\n"]


f1 = open('myfile.txt', 'w')
f1.writelines(A)
f1.close()
f1 = open('myfile.txt', 'r')
Lines = f1.read()
count = 0
for line in Lines:
count += 1
print("Line{}: {}".format(count, line.strip()))

Output:

Line1: H
Line2: e
Line3: l
Line4: l
Line5: o
Line6:
Line7: C
Line8: o
Line9: d
Line10: e
Line11: r
Line12: s
Line13:
Line14: J
Line15: a
Line16: v
Line17: a
Line18: T
Line19: p
Line20: o
Line21: i
Line22: n
DON BOSCO COLLEGE DHARMAPURI
Line23: t
Line24:

Read Lines of the file

Python facilitates to read the file line by line by using a function readline() method. The
readline() method reads the lines of the file from the beginning, i.e., if we use the readline() method two
times, then we can get the first two lines of the file.

Consider the following example which contains a function readline() that reads the first line of our file
"file2.txt" containing three lines. Consider the following example.

Here we give the example of reading the lines using the readline() function in Python. The code is given
below -

#open the file.txt in read mode. causes error if no such file exists.
fileptr = open("file2.txt","r");
#stores all the data of the file into the variable content
content = fileptr.readline()
content1 = fileptr.readline()
#prints the content of the file
print(content)
print(content1)
#closes the opened file
fileptr.close()

Output:

Now we compile the above code in Python, and after successful compilation, we run it. Then the output
is given below -

Python is the modern day language.

It makes things so simple.

We called the readline() function two times that's why it read two lines from the file.That means, if you
called readline() function n times in your program, then it read n number of lines from the file. This is the
uses of readline() function in Python. Python provides also the readlines() method which is used forthe
reading lines. It returns the list of the lines till the end of file(EOF) is reached.

Example 2:

Here we give the example of reading the lines using the readline() function in Python. The code is given
below -

#open the file.txt in read mode. causes error if no such file exists.
fileptr = open("file2.txt","r");
DON BOSCO COLLEGE DHARMAPURI

#stores all the data of the file into the variable content
content = fileptr.readlines()

#prints the content of the file


print(content)

#closes the opened file


fileptr.close()

Output:

Now we compile the above code in Python, and after successful compilation, we run it. Then the output
is given below -

['Python is the modern day language.\n', 'It makes things so simple.\n', 'Python has easy syntax and
user-friendly interaction.']

Example 3:

Here we give the example of reading the lines using the readline() function in Python. The code is
given below -

A = ["Hello\n", "Coders\n", "JavaTpoint\n"]


f1 = open('myfile.txt', 'w')
f1.writelines(A)
f1.close()
f1 = open('myfile.txt', 'r')
Lines = f1.readlines()
count = 0
for line in Lines:
count += 1
print("Line{}: {}".format(count, line.strip()))

Output:

Now we compile the above code in Python, and after successful compilation, we run it. Then the output
is given below -

Line1: Hello
Line2: Coders
Line3: JavaTpoint

Creating a new file

The new file can be created by using one of the following access modes with the function open().The
open() function used so many parameters. The syntax of it is given below -
DON BOSCO COLLEGE DHARMAPURI
file = open(path_to_file, mode)

x, a and w is the modes of open() function. The uses of these modes are given below -

x: it creates a new file with the specified name. It causes an error a file exists with the same name.

a: It creates a new file with the specified name if no such file exists. It appends the content to the file if
the file already exists with the specified name.

w: It creates a new file with the specified name if no such file exists. It overwrites the existing file.

Consider the following example.

Program code1 for Creating a new file:

Here we give an example for creating a new file in Python. For creates a file, we have to used the open()
method. The code is given below -

#open the file.txt in read mode. causes error if no such file exists.
fileptr = open("file2.txt","x")
print(fileptr)
if fileptr:
print("File created successfully")

Output:

Now we compile the above code in Python, and after successful compilation, we run it. Then the output
is given below -

<_io.TextIOWrapper name='file2.txt' mode='x' encoding='cp1252'>


File created successfully

Program code2 for creating a new file:

Here we give an example for creating a new file in Python. For creates a file, we have to use the open()
method. Here we use try block for erase the errors. The code is given below -

try:
with open('file1.txt', 'w') as f:
f.write('Here we create a new file')
except FileNotFoundError:
print("The file is does not exist")

Output:

Now we compile the above code in Python, and after successful compilation, we run it. Then the output
is given below -
DON BOSCO COLLEGE DHARMAPURI
The file is does not exist

File Pointer positions

Python provides the tell() method which is used to print the byte number at which the file pointer
currently exists. The tell() methods is return the position of read or write pointer in this file. The syntax
of tell() method is given below -

fileobject.tell()

Program code1 for File Pointer Position:

Here we give an example for how to find file pointer position in Python. Here we use tell() method
and it is return byte number. The code is given below -

# open the file file2.txt in read mode


fileptr = open("file2.txt","r")

#initially the filepointer is at 0


print("The filepointer is at byte :",fileptr.tell())

#reading the content of the file


content = fileptr.read();

#after the read operation file pointer modifies. tell() returns the location of the fileptr.

print("After reading, the filepointer is at:",fileptr.tell())

Output:

Now we compile the above code in Python, and after successful compilation, we run it. Then the output
is given below -

The filepointer is at byte : 0


After reading, the filepointer is at: 117

Program code2 for File Pointer Position:

Here we give another example for how to find file pointer position in Python. Here we also use tell()
method, which is return byte number. The code is given below -

file = open("File2.txt", "r")


print("The pointer position is: ", file.tell())

Output:

Now we compile the above code in Python, and after successful compilation, we run it. Then the output
is given below -
DON BOSCO COLLEGE DHARMAPURI
The pointer position is: 0

Modifying file pointer position

In real-world applications, sometimes we need to change the file pointer location externally since we may
need to read or write the content at various locations.

For this purpose, the Python provides us the seek() method which enables us to modify the file pointer
position externally. That means, using seek() method we can easily change the cursor in the file, from
where we want to read or write a file.

Syntax:

The syntax for seek() method is given below -

<file-ptr>.seek(offset[, from)

The seek() method accepts two parameters:

offset: It refers to the new position of the file pointer within the file.

from: It indicates the reference position from where the bytes are to be moved. If it is set to 0, the
beginning of the file is used as the reference position. If it is set to 1, the current position of the file pointer
is used as the reference position. If it is set to 2, the end of the file pointer is used as the reference position.

Consider the following example.

Here we give the example of how to modifying the pointer position using seek() method in Python. The
code is given below -

# open the file file2.txt in read mode


fileptr = open("file2.txt","r")

#initially the filepointer is at 0


print("The filepointer is at byte :",fileptr.tell())

#changing the file pointer location to 10.


fileptr.seek(10);

#tell() returns the location of the fileptr.


print("After reading, the filepointer is at:",fileptr.tell())

Output:

Now we compile the above code in Python, and after successful compilation, we run it. Then the output
is given below -
DON BOSCO COLLEGE DHARMAPURI
The filepointer is at byte : 0
After reading, the filepointer is at: 10

Python OS module:

Renaming the file

The Python os module enables interaction with the operating system. It comes from the Python standard
utility module. The os module provides a portable way to use the operating system-dependent
functionality in Python. The os module provides the functions that are involved in file processing
operations like renaming, deleting, etc. It provides us the rename() method to rename the specified file to
a new name. Using the rename() method, we can easily rename the existing File. This method has not
any return value. The syntax to use the rename() method is given below.

Syntax:

The syntax of rename method in Python is given below -

rename(current-name, new-name)

The first argument is the current file name and the second argument is the modified name. We can
change the file name bypassing these two arguments.

Program code 1 for rename() Method:

Here we give an example of the renaming of the files using rename() method in Python. The current file
name is file2.txt, and the new file name is file3.txt. The code is given below -

import os

#rename file2.txt to file3.txt


os.rename("file2.txt","file3.txt")

Output:

Now we compile the above code in Python, and after successful compilation, we run it. Then the output
is given below -

The above code renamed current file2.txt to file3.txt

Program code 2 for rename() Method:

Here we give an example of the renaming of the files using rename() method in Python. The current file
name is the source, and the new file name is the destination. The code is given below -

import os
def main():
i=0
DON BOSCO COLLEGE DHARMAPURI

path="D:/JavaTpoint/"
for filename in os.listdir(path):
destination = "new" + str(i) + ".png"
source = path + filename
destination = path + destination
os.rename(source, destination)
i += 1

if name == ' main ':


main()

Removing the file

The os module provides the remove() method which is used to remove the specified file.

Syntax:

The syntax of remove method is given below -

remove(file-name)

Program code 1 for remove() method:

import os;
#deleting the file named file3.txt
os.remove("file3.txt")

Output:

Now we compile the above code in Python, and after successful compilation, we run it. Then the output
is given below -

The file named file3.txt is deleted.

Program code 2 for remove() Method:

Here we give an example of removing a file using the remove() method in Python. The file name is
file3.txt, which the remove() method deletes. Print the command "This file is not existed" if the File does
not exist. The code is given below -

import os
if os.path.exists("file3.txt "):
os.remove("file3.txt ")
else:
print("This file is not existed")

Output:
DON BOSCO COLLEGE DHARMAPURI
Now we compile the above code in Python, and after successful compilation, we run it. Then the output
is given below -

This file is not existed

Creating the new directory

The mkdir() method is used to create the directories in the current working directory.It creates
dictionary in numeric mode. If the file already presents in the system, then it occurs error, which is known
as FileExistsError in Python. The mkdir() method does not return any kind of value. The syntax to create
the new directory is given below.

Syntax:

The syntax of mkdir() method in Python is given below -

os.mkdir (path, mode = 0o777, *, dir_fd = None)

Output:

Parameter:

The syntax of mkdir() method in Python is given below -

path - A path like object represent a path either bytes or the strings object.

mode - Mode is represented by integer value, which means mode is created. If mode is not created then
the default value will be 0o777. Its use is optional in mkdir() method.

dir_fd - When the specified path is absolute, in that case dir_fd is ignored. Its use is optional in mkdir()
method.

Program code 1 for mkdir() Method:

Here we give the example of mkdir() method by which we can create new dictionary in Python. The code
is given below -

import os
#creating a new directory with the name new
os.mkdir("new")

Output:

Now we compile the above code in Python, and after successful compilation, we run it. Then the output
is given below -

Create a new dictionary which is named new

Program code 2 for mkdir() Method:


DON BOSCO COLLEGE DHARMAPURI
Here we give the example of mkdir() method by which we can create new dictionary in Python. The code
is given below -

import os
path = '/D:/JavaTpoint'
try:
os.mkdir(path)
except OSError as error:
print(error)

Output:

Now we compile the above code in Python, and after successful compilation, we run it. Then the output
is given below -

[Error 20] File exists: '/D:/JavaTpoint'

The getcwd() method:

This method returns the current working directory which have absolute value. The getcwd() method
returns the string value which represents the working dictionary in Python. In getcwd() method, do not
require any parameter.

The syntax to use the getcwd() method is given below.

Syntax

The syntax of getcwd() method in Python is given below -

os.getcwd()

Program code 1 for getcwd() Method:

Here we give the example of getcwd() method by which we can create new dictionary in Python.
The code is given below -

import os
os.getcwd()

Output:

Now we compile the above code in Python, and after successful compilation, we run it. Then the output
is given below -

'C:\\Users\\DEVANSH SHARMA'

Program code 2 for getcwd() Method:


DON BOSCO COLLEGE DHARMAPURI
Here we give the example of getcwd() method by which we can create new dictionary in Python. The
code is given below -

import os
c = os.getcwd()
print("The working directory is:", c)

Output:

Now we compile the above code in Python, and after successful compilation, we run it. Then the output
is given below -

The working directory is: C:\\Users\\JavaTpoint

Changing the current working directory

The chdir() method is used to change the current working directory to a specified directory.The chdir()
method takes a single argument for the new dictionary path. The chdir() method does not return any
kind of value.

Syntax

The syntax of chdir() method is given below -

chdir("new-directory")

Program code 1 for chdir() Method:

Here we give the example of chdir() method by which we can change the current working
dictionary into new dictionary in Python. The code is given below -

import os
# Changing current directory with the new directiory
os.chdir("C:\\Users\\DEVANSH SHARMA\\Documents")
#It will display the current working directory
os.getcwd()

Output:

Now we compile the above code in Python, and after successful compilation, we run it. Then the output
is given below -

'C:\\Users\\DEVANSH SHARMA\\Documents'

Program code 2 for chdir() Method:

Here we give another example of chdir() method by which we can change the current working
dictionary into new dictionary in Python. The code is given below -
DON BOSCO COLLEGE DHARMAPURI

import os
os.chdir(r"C:\Users\JavaTpoint")
print("Currently working directory is changed")

Output:

Now we compile the above code in Python, and after successful compilation, we run it. Then the output
is given below -

Currently working directory is changed

Deleting directory:

The rmdir() method is used to delete the specified directory. If the directory is not empty then there is
occurs OSError. The rmdir() method does not have and kind of return value.

Syntax

os.rmdir(directory name)

Program code 1 for rmdir() Method:

Here we give the example of rmdir() method by which we can delete a dictionary in Python. The code
is given below -

import os
#removing the new directory
os.rmdir("directory_name")

Output:

Now we compile the above code in Python, and after successful compilation, we run it. Then the output
is given below -

It will remove the specified directory.

Program code 2 for rmdir() Method:

Here we give another example of rmdir() method by which we can delete a dictionary in Python. The
code is given below -

import os
directory = "JavaTpoint"
parent = "/D:/User/Documents"
path = os.path.join(parent, directory)
os.rmdir(path)
print("The directory '%s' is successfully removed", %directory)
DON BOSCO COLLEGE DHARMAPURI
Output:

Now we compile the above code in Python, and after successful compilation, we run it. Then the output
is given below -

The directory 'JavaTpoint' is successfully removed

Output:

Here we give the example of rmdir() method by which we can delete a dictionary in Python. Here we
use try block for handle the error. The code is given below -

import os
dir = "JavaTpoint"
parent = "/D:/User/Documents"
path = os.path.join(parent, dir)
try:
os.rmdir(path)
print("The directory '%s' is successfully removed", %dir)
except OSError as error:
print(error)
print("The directory '%s' cannot be removed successfully", %dir)

Output:

Now we compile the above code in Python, and after successful compilation, we run it. Then the output
is given below -

[Error 30] Permission denied: '/D:/User/Documents/JavaTpoint'


The directory 'JavaTpoint' cannot be removed successfully

Writing Python output to the files:

In Python, there are the requirements to write the output of a Python script to a file.

The check_call() method of module subprocess is used to execute a Python script and write the output
of that script to a file.

The following example contains two python scripts. The script file1.py executes the script file.py and
writes its output to the text file output.txt.

Program code:

file1.py

temperatures=[10,-20,-289,100]
def c_to_f(c):
if c< -273.15:
DON BOSCO COLLEGE DHARMAPURI

return "That temperature doesn't make sense!"


else:
f=c*9/5+32
return f
for t in temperatures:
print(c_to_f(t))

file.py

import subprocess

with open("output.txt", "wb") as f:


subprocess.check_call(["python", "file.py"], stdout=f)

File Related Methods:

The file object provides the following methods to manipulate the files on various operating systems.
Here we discuss the method and their uses in Python.

SN Method Description

1 file.close() It closes the opened file. The file once closed, it can't be read
or write anymore.

2 File.fush() It flushes the internal buffer.

3 File.fileno() It returns the file descriptor used by the underlying


implementation to request I/O from the OS.

4 File.isatty() It returns true if the file is connected to a TTY device,


otherwise returns false.

5 File.next() It returns the next line from the file.

6 File.read([size]) It reads the file for the specified size.

7 File.readline([size]) It reads one line from the file and places the file pointer to
the beginning of the new line.

8 File.readlines([sizehint]) It returns a list containing all the lines of the file. It reads the
file until the EOF occurs using readline() function.

9 File.seek(offset[,from) It modifies the position of the file pointer to a specified


offset with the specified reference.

10 File.tell() It returns the current position of the file pointer within the
file.

11 File.truncate([size]) It truncates the file to the optional specified size.


DON BOSCO COLLEGE DHARMAPURI

12 File.write(str) It writes the specified string to a file

13 File.writelines(seq) It writes a sequence of the strings to a file.

Conclusion:

In this tutorial, we briefly discussed the Python file handling. Users can easily handle the files, like read
and write the files in Python. Here we discuss various methods in Python by which we can easily read,
write, delete, or rename a file. We also give the program code of these methods for better understanding.

Files in Python
Till now, we were taking the input from the console and writing it back to the console to interact with the user. Instead of that we
can able use files as input or output.
File is a named location on disk to store related information. It is used to permanently store data in a non-volatile memory (e.g.
hard disk).
When we want to read from or write to a file we need to open it first. When we are done, it needs to be closed, so that resources
that are tied with the file are freed.
Hence, in Python, a file operation takes place in the following order.

• Open a file
• Read or write (perform operation)
• Close the file

File Built-in Function [open ()]

Python has a built-in function open() to open a file. Which accepts two arguments, file name and access mode in which the file is
accessed. The function returns a file object which can be used to perform various operations like reading, writing, etc.
Syntax:

Fileobject = open (file-name, access-mode)

file-name: It specifies the name of the file to be opened.


access-mode: There are following access modes for opening a file:

access-mode Description

"w" Write - Opens a file for writing, creates the file if it does not exist.

"r" Read - Default value. Opens a file for reading, error if the file does not exist.

"a" Append - Opens a file for appending, creates the file if it does not exist.

"x" Create - Creates the specified file, returns an error if the file exists.
DON BOSCO COLLEGE DHARMAPURI

access-mode Description

"w+" Open a file for updating (reading and writing), overwrite if the file exists.

"r+" Open a file for updating (reading and writing), doesn’t overwrite if the file exists.

In addition you can specify if the file should be handled as binary or text mode

access-mode Description

"t" Text - Default value. Text mode.

"b" - Binary - Binary mode (e.g. images)

Example:

fileptr = open("myfile.txt","r")
if fileptr:
print("file is opened successfully with read mode only")
Output:

file is opened successfully with read mode only


Example:

fileptr = open("myfile1.txt","x")
if fileptr:
print("new file was created successfully")
Output:

new file was created successfully

File Built-in Methods

Python supports file handling and allows users to handle files i.e., to read and write files, along with many other file handling
options, to operate on files. For this, python provides following built–in functions, those are

• close()
• read()
• readline()
• write()
• writelines()
• tell()
• seek()

☞ close()
DON BOSCO COLLEGE DHARMAPURI
The close() method used to close the currently opened file, after which no more writing or Reading can be done.
Python automatically closes a file when the reference object of a file is reassigned to another file. It is a good practice to use the
close() method to close a file.
Syntax:

Fileobject.close()

Example:

f = open("myfile.txt", "r")
f.close()

☞ read()
The read () method is used to read the content from file. To read a file in Python, we must open the file in reading mode.
Syntax:

Fileobject.read([size])

Where ‘size’ specifies number of bytes to be read.


myfile.txt

function open() to open a file.


method read() to read a file.
Example:

# Opening a file with read mode


fileptr = open("myfile.txt","r")
if fileptr:
print("file is opened successfully")
content = fileptr.read(5) #read 5 characters
print(content)
content = fileptr.read() #read all characters
print(content)
else:
print("file not opened ")
fileptr.close();

Output:

file is opened successfully


funct
ion open() to open a file.
method read() to read a file.

☞ readline()
Python facilitates us to read the file line by line by using a function readline(). The readline() method reads the lines of the file
from the beginning, i.e., if we use the readline() method two times, then we can get the first two lines of the file.
Syntax:

Fileobject.readline()
DON BOSCO COLLEGE DHARMAPURI

myfile.txt

function open() to open a file.


method read() to read a file.

Example:

fileptr = open("myfile.txt","r")
if fileptr:
print("file is opened successfully")
content=fileptr.readline() print(content)
content=fileptr.readline() print(content)
fileptr.close();

Output:

file is opened successfully


function open() to open a file.
method read() to read a file.

☞ write()
The write () method is used to write the content into file. To write some text to a file, we need to open the file using the open
method with one of the following access modes.
w: It will overwrite the file if any file exists. The file pointer point at the beginning of the file in this mode.
Syntax:

Fileobject.write(content)

myfile.txt

function open() to open a file.


method read() to read a file.
Example:

fileptr = open("myfile.txt","w");
#appending the content to the file
fileptr.write("Python is the modern day language.")
#closing the opened file
fileptr.close();

myfile.txt:

Python is the modern day language.


a: It will append the existing file. The file pointer point at the end of the file.
myfile.txt

function open() to open a file.


method read() to read a file.

Example:
DON BOSCO COLLEGE DHARMAPURI

fileptr = open("myfile.txt","a");
#appending the content to the file
fileptr.write ("Python is the modern day language.")
#closing the opened file
fileptr.close();
myfile.txt:

function open() to open a file.


method read() to read a file.
Python is the modern day language.

Now, we can see that the content of the file is modified.

☞ writelines()
The writelines () method is used to write multiple lines of content into file. To write some lines to a file
Syntax:

Fileobject.writelines(list)
list − This is the Sequence of the strings.
Example:

f = open("myfile.txt", "w")
f.writelines(["Python supports Files \n", "python supports Strings."])
f.close()
myfile.txt:

Python supports Files


python supports Strings.

File Positions

Methods that set or modify the current position within the file

☞ tell()
The tell() method returns the current file position in a file stream. You can change the current file position with the seek() method.
Syntax:

Fileobject.tell()

myfile.txt

function open() to open a file.


method read() to read a file.
Example:

f = open("myfile.txt", "r")
print(f.readline())
print(f.tell())
DON BOSCO COLLEGE DHARMAPURI

f.close();
Output:

33
In the fist line of file that is "function open() to open a file." with 32 charecters so the output is 33

☞ seek()
The seek() method sets and returns the current file position in a file stream.
Syntax:

Fileobject.seek(offset)

myfile.txt

function open() to open a file.


method read() to read a file.
Example:

f = open("myfile.txt", "r")
print(f.seek(9))
print(f.read())
f.close();
Output:

open() to open a file.


method read() to read a file.
First We moved 9bytes with seek function and then started reading

File Built-in Attributes

Python Supports following built-in attributes, those are

• file.name - returns the name of the file which is already opened.


• file.mode - returns the access mode of opened file.
• file.closed - returns true, if the file closed, otherwise false.
Example:

f = open ("myfile.txt", "r")


print(f.name)
print(f.mode)
print(f.closed)
f.close()
print(f.closed)
Output:

myfile.txtr
False
DON BOSCO COLLEGE DHARMAPURI

True
Python program to print number of lines, words and characters in given file.
myfile.txt

function open() to open a file.


method read() to read a file.
Python is the modern day language.
Python supports Files
python supports Strings
Example:

fname = input("Enter file name: ")


num_lines = 0
num_words = 0
num_chars = 0
try:
fp=open(fname,"r")
for i in fp:
# i contains each line of the file
words = i.split()
num_lines += 1
num_words += len(words)
num_chars += len(i)
print("Lines = ",num_lines)
print("Words = ",num_words)
print("Characters = ",num_chars)
fp.close()
except Exception:
print("Enter valid filename")
Output: Case 1

Enter file name: myfile.txt


Lines = 5
Words = 24
Characters = 144

Output: Case 2

Enter file name: gh


Enter valid filename

Command-Line Arguments in Python

Till now, we have taken input in python using raw_input() or input(). There is another method that uses command line arguments.
The command line arguments must be given whenever we want to give the input before the start of the script, while on the other
hand, input() is used to get the input while the python program / script is running.

How do I use it?


DON BOSCO COLLEGE DHARMAPURI
To use it, you will first have to import it (import sys) The first argument, sys.argv[0], is always the name of the program as it was
invoked, and sys.argv[1] is the first argument you pass to the program. It's common that you slice the list to access the actual
command line argument:
The sys module also provides access to any command-line arguments via sys.argv. Command-line
arguments are those arguments given to the program in addition to the script name on invocation.

• sys.argv is the list of command-line arguments


• len(sys.argv) is the number of command-line arguments.
To use argv, you will first have to import it (import sys) The first argument, sys.argv[0], is always the name of the program as it was
invoked, and sys.argv[1] is the first argument you pass to the program. It's common that you slice the list to access the actual
command line arguments.

Example:

# file name "cmdarg.py"


import sys
program_name = sys.argv[0]
arguments = sys.argv[1:]
count = len(arguments)
print(program_name)
print(arguments)
print("Number of arguments ",count)
Output:

python cmdarg.py 45 56
cmdarg.py
['45', '56']
Number of arguments 2

Example Program:

Aim: Python Program to merge two files using command line argument.
myfile.txt

function open() to open a file.


method read() to read a file.
Python is the modern day language.
myfile1.txt

Python supports Files


python supports Strings.

Example:

# file name "fileprg.py"


from sys import argv
if len(argv)==4:
try:
fp1=open(argv[1],"r")
fp2=open(argv[2],"r")
fp3=open(argv[3],"w+") #w+ mode create a file if file doesn’t exist.
DON BOSCO COLLEGE
DHARMAPURI
for i in fp1:
fp3.write(i) # write content from first file to third
filefor i in fp2:
fp3.write(i) # write content from second file to third file
print("Two files merged successfully")
print("Content in ",argv[3])
fp3.seek(0,0) # to move file point cursor to starting of
filefor i in fp3:
print(i,end=" ")
fp1.clo
se()
fp2.clo
se()
fp3.clo
se()
except Exception:
print("Enter valid filenames")
Output: Case 1

>>python fileprg.py myfile.txt myfile1.txt


myfile2.txtTwo files merged successfully
Content in myfile2.txt

function open() to open a file.


method read() to read a file.
Python is the modern day
languagePython supports Files
python supports Strings.
Output: Case 2

>>python fileprg.py abc.txt myfile1.txt


myfile2.txtEnter valid filenames
In case 2 we had an exception because abc.txt file does not exist
DON BOSCO COLLEGE DHARMAPURI

UNIT – 4
Functions and Functional Programming – Functions – calling functions – creating functions –
passing functions – Built-in Functions: apply( ), filter( ), map( ) and reduce( ) - Modules – Modules
and Files – Modules built-in functions - classes – class attributes – Instances.
Functional Programming

Functional programming is designed to handle the symbolic computation and application processing list,
and it is based on mathematical work. The most popular functional programming languages are Python,
Lisp, Haskell, Clojure, Erlang etc.

Functional Programming has two types; those are shown as below:

Pure Functional Languages: Pure functional language supports only the functional pattern. An example
of the pure functional language is Haskell.

Impure Functional Language: Impure Functional language supports the prototype of functions and the
programming's imperative style. An example of an impure functional language is LISP.

Characteristics of the Functional Programming Language

Characteristics of the functional programming languages are like as shown below:

Functional programming languages are designed to perform the functions of mathematical functions.
These functions use conditional expressions and recursion to perform the computation.

Functional programming supports functions in higher-orderand features of lazy evaluation.

Functional Programming language directly uses the functions and function calls. It does not support the
flow of the controls like statements of the loop, and statements are like the conditional statements such
as If-Else and Switch Statements.

Object-Oriented Programming supports the Abstraction, Encapsulation, and Polymorphism, just like
functional programming languages support OOPS concepts.

Advantages of the Functional Programming

Advantages of the functional programming languages are as shown below:

Bugs-Free code: Functional Programming language does not support state, so there is no side effect of
the functional programming; hence we can write the error-free code.

Efficient Programming Language: Functional Programming language has no mutable state, so there
is no state change issue. We can do the program "Functions" to work parallel to "Instruction". This type
of code supports reusability and testability easily.
DON BOSCO COLLEGE DHARMAPURI
Efficiency- Functional Program contains the Independent Units. Independent units run concurrently.
Hence these functional programs are more efficient.

Supports Nested Functions- Nested functions are supported by functional programming.

Lazy Evaluation- Lazy Functional Constructions are also supported by functional programming such
as Lazy Lists, Lazy Maps, etc.

Functional programming does not have any state, so all the time, there is a need to create new objects to
perform the actions. That's why functional programming needs a large memory space.

Functional programming is used to perform the different operations on the same data set.

The LISP supports artificial intelligence applications such as language processing, Machine learning,
Modelling of speech and vision.

Differences between the Functional Programming and Object-Oriented Programming are:

Sr.No. Functional Programming Object-Oriented Programming

1. The functional programming language OOP uses mutable data.


supports immutable data.

2. Functional Programming supports the OOP supports the imperative Programming Model.
Declarative Programming Model.

3. Functional Programming focuses on the OOP focuses on the "How we are doing".
"What we are doing".
4. The methods of Functional Methods of the OOP can produce the side-effects.
Programming will not produce any side-
effects.
5. Functional Programming follows OOP does not work on parallel programming.
parallel programming.
6. For the flow control, we do function Object-Oriented Programming supports the use of
calls & function calls with recursion. the loops and conditional statements for the flow
control.
7. For the iteration of the data collection, Object-Oriented Programming uses the "Loop"
functional programming uses concept for the iteration of Data collection. For
the"Recursion" concept. example, For-each loop in Java
8. For functional programming, the It is essential for the oop programming to execute
execution of statements in the order is the statements in order is very important.
not so important.

9. Functional Programming supports OOP supports only "Abstraction over Data".


"Abstraction over Data" and
"Abstraction over Behavior".
DON BOSCO COLLEGE DHARMAPURI
Efficiency of Program

The program's code is directly proportional to the efficiency of the algorithm and the execution speed of
the program. If the efficiency is good, that means the performance will be high in the program.

The efficiency of the program is affected by the below factors:

The machine's speed affects the efficiency of the program.

The compiler's speed also affects the efficiency of the program.

The operating system also plays a crucial role in the efficiency of the programming code.

The choice of the right Programming language affects the efficiency of the programming.

Data organization is also affecting the efficiency of the program.

The use of the algorithm in the program affects the efficiency of the programs. An algorithm in the
Functional Programming solves the problem.

We can increase the efficiency of the programming language with the help of the below tasks -

To increase the program's efficiency, we have to remove the program's unusable code or the code that is
having redundant processing.

The use of optimal memory and non-volatile storage helps to improve the efficiency of the
programming language.

We can reuse the components. This will also help to increase the efficiency of the program.

By using the error & exception handling on all the layers of the program.

During the program's coding, the program should have to be ensured about the data's integrity and
consistency.

By using the programming code, we can do design logic and flow.

Efficient programming code can reduce the consumption of the resources and time taken by the
completion programs.

Functional Programming-Call by Value

After defining the function, there is a need to pass the arguments into the function to get the desired
output. All the programming language supports the call by value and call by reference methods after
arguments passed into the functions.

"Call by value" works only on the object-oriented programming language like C++. Functional
programming language like Python also supports "call by value".
DON BOSCO COLLEGE DHARMAPURI
The original value of the call by value method will not change when we pass the arguments to the function.
The function will store the value locally through the function parameter in stack's memory. The changed
value in the function will not affect functions from the outside.

Call by Value in C++

Here is the program which shows the call by value in the C++.

#include<iostream.h>
#include<conio.h>

void swap(int x, int y)


{
int temp;
temp=x;
x=y;
y=temp;
}

void main()
{
int x=400, y=600;
clrscr();
swap(x, y); // arguments passed to the function
cout<<"Value of x"<<x;
cout<<"Value of y"<<y;
getch();
}

This will show the following output:

Value of x is: 200


Value of y is: 100

Call by Value in Python

Below program shows the working of Call by Value in Python:

def swap (x, y):


t = x;
x = y;
DON BOSCO COLLEGE DHARMAPURI
y = t;
print " the value of x argument inside the function: ", x
print " the value of y argument inside the function: ", y
# Now we will call swap function
x = 70
y = 75
print " the value of x argument before assigning into function: ", x
print " the value of y argument before assigning into function: ", y
swap (x, y)
print " the value of x argument after assigning into function: ", y
print " the value of y argument after assigning into function: ", x

The output of the above program will look like as shown below:

Function Overloading

When any program contains multiple functions, whose name is the same, but the parameters are different,
they are known as overloaded. We use this technique to increase the readability of the program.

To overload the functions, we will use two methods. -

The function contains a different number of arguments.

Function having different types of arguments.

We usually will do the function overloading when we want to perform one operation, containing
different numbers or types of arguments.

Function Overloading in C++

Function Overloading in C++ will be like as shown below:

# include <iostream>
using namespace std;
void addNum(int, int);
void addNum(int, int, int);
int main()
{
DON BOSCO COLLEGE DHARMAPURI
addNum(5, 7);
addNum(5, 6, 8);
return 0;
}
void addNum(int a, int b)
{
cout << "Integer number would be: " << a + b << endl;
}
void addNum(int a, int b, int c)
{
cout << "Float number would be: " << a + b + c << endl;
}

The output of the above program will look like, as shown below:

Now we will take another example of the function overloading.

# include <iostream>
using namespace std;

void print(int g)
{
cout << " int number is:" << g << endl;
}
void print(double f)
{
cout << " double number is: " << f << endl;
}
void print(char const *c)
{
cout << " Char is: " << c << endl;
}

int main()
{
print(20);
DON BOSCO COLLEGE DHARMAPURI
print(20.20);
print("twenty");
return 0;
}

Now the output of the above program will look like as shown in the below screenshot:

Output

Function Overloading in Erlang

In the system, the Overloading process regulates the use of the CPU. In the function overloading, the
main application calls the request function before doing any job and executes the process when it returns
the positive value; else, the job will not start.

Overload is the part of the sas1 application, and we can define all the configuration parameter here.

We will maintain the two sets of intensity; those are the total intensity and the accept intensity.
Intensities can be measured through the configuration parameters, which are: MaxIntensity and the
Weight value. Both the intensities will be measured according to the 1/second.

Total intensity can be calculated, as shown below:

The assumption is that the current call to request/0 is K(n), and the time of the previous call was K(n-1).
The current total intensity is denoted as KI(n). We will calculate the intensity through the below formulas:

KI(m) = exp(-Weight*(K(m) - K(m-1)) * KI(m-1) + Weight

Where KI(n-1) is the previous total intensity.

The accept intensity is denoted as BI(n), current accept intensity can be defined as shown below:

BI(n) = exp(-Weight*(T(m) - T(m-1)) * AI(m-1) + Weight

where AI(n-1) is known as the previous accept intensity, provided that the value of exp(-Weight*(T(n) -
T(n-1)) * AI(n-1) is less than MaxIntensity; else the value is
DON BOSCO COLLEGE DHARMAPURI

AI(n) = exp(-Weight*(T(n) - T(n-1)) * AI(n-1)

Speed is controlled by the value of the configuration parameter (Weight), and the intensities' calculations
will react according to the changes in the input intensity. The inverted value of Weight will be denoted
like as shown below,

T = 1/Weight

This value can be defined as the "time constant," which is the intensity calculation formulas. For example,
if Weight = 0.1, then the input intensity change is denoted by the total and accepts the 10 seconds'
intensities. The overload process defined one alarm, which sets the alarm_handler:set_alarm(Alarm). We
will define the alarm as:

{overload, []}

We will set this alarm when the current accept intensity exceeds MaxIntensity.

Now we will perform function overloading in Erlang, Erlang is a functional programming language:

-module(helloworld).
- export([add / 3, add / 3, start / 0]).

add(X, Y)->
Z = X + Y,
io: fwrite("~w~n",[Z]).

add(X, Y, Z)->
A = X + Y + Z,
io: fwrite("~w~n",[A]).

start()->
add(5, 8),
add(5, 6, 8).

Output of the above program will look like as shown below:

13
DON BOSCO COLLEGE DHARMAPURI
19

Pass function as parameter python

In this article, we are discussing the pass function as a parameter in python. Functions can take multiple
arguments. These arguments can be objects, variables (of the same or different data types), and functions.
Python functions are the first elegant gadgets.

Within the following instance, a feature is assigned to a variable. This project no longer names a function.
This takes the feature object pointed to by "shout" and creates a second call, "yell," pointing to it.

Facts may be exceeded to features as arguments. Arguments are unique after the characteristic call-in
parentheses. You could add as many arguments as possible; separate them with commas.

The following example has a function with one argument (fname). At the same time, the function is
referred to as passing the name used in the characteristic to print the overall call.

Example 1: Right here, we give an instance of the pass function as a parameter in python. The example
is given below -

def my_function(fname):
print(fname + " Id")
my_function("Emil")
my_function("Phone")

Result: We assemble the above program, and after compilation, we run the program. Then the result is
given below -

Email Id
Phone Id

Example 2: Right here, we give another instance of the pass function as a parameter in python. The
example is given below -

def shout(text):
return text.upper()
print(shout('Hello World'))
yell = shout
print(yell('Hello Coders'))

Result: We assemble the above program, and after compilation, we run the program. Then the result is
given below -

HELLO WORLD
DON BOSCO COLLEGE DHARMAPURI
HELLO CODERS

Wrapper Function: A wrapper function or decorator allows you to wrap another function and extend
it without permanently changing the behavior of the wrapped function. In the decorator, the function is
taken as an argument of another function and called inside the wrapper function.

Example 1: Right here, we give an instance of a wrapper function as a parameter in python. The example
is given below -

def hello_decorator(func):
def inner1():
print ("Hello coders, it is before the function execution")
func ()
print ("It is after the function execution")
return inner1
def function_to_be_used():
print ("It is inside of this function")
function_to_be_used = hello_decorator(function_to_be_used)
function_to_be_used()

Result: We assemble the above program, and after compilation, we run the program. Then the result is
given below -

Hello coders, it is before the function execution


It is inside of this function
It is after the function execution

Lambda wrapper function: In Python, a nameless function approach that the character has no call. As
you recognize, the def keyword defines ordinary functions, and the lambda keyword is used to create
anonymous functions. This characteristic will have a variety of arguments but evaluates and returns the
simplest expression.

A lambda function also can have every other character as an argument. The subsequent example
suggests a primary Lambda characteristic surpassed every other Lambda function as a controversy.

Example 1: Right here, we give an instance of the lambda wrapper function as a parameter in python.
The example is given below -

square = lambda a:a * a


cube = lambda func:func**3
print ("The square of 4 is:"+str (square (4)))
print ("\nThe cube of "+str (square (4)) +" is :" +str (cube (square (4))))
DON BOSCO COLLEGE DHARMAPURI
Result: We assemble the above program, and after compilation, we run the program. Then the result is
given below -

The square of 4 is:16


The cube of 16 is: 4096

Higher order function: Since functions are objects, we can pass them as arguments to other features.
Capabilities that take other features as arguments are also referred to as better-order functions. The
subsequent instance creates a Greet feature that takes a feature as an issue.

Example 1: Right here, we give an instance of a higher order function as a parameter in python. The
example is given below -

def shout(text):
return text.upper()
def whisper(text):
return text.lower()
def greet(function):
greeting = function ("Hello, we are created by a higher order function passed as an argument.")
print(greeting)
greet(shout)
greet(whisper)

Result: We assemble the above program and run the program after compilation. Then the result is given
below -

HELLO, WE ARE CREATED BY A HIGHER ORDER FUNCTION PASSED AS AN ARGUMENT.


hello, we are created by a higher order function passed as an argument.

Conclusion: In Python, you can pass function objects to other functions. Functions can be propagated in
Python. Python has built-in functions requiring you to specify the function as one or more arguments so
you can call it later.

map, filter, and reduce in Python with Examples

Python Streams

Python stream is a term for a particular paradigm for data processing that involves the sequential
processing of data items as they pass through a pipeline of processes. Streams allow dataprocessing
to be continuous, effective, and memory-friendly without loading the entire dataset into memory at once.

The map, filter, and reduce functions in Python are higher-order functions that work on sequences of data,
such as lists or other iterable objects. Streams can be used in conjunction with these methods.
DON BOSCO COLLEGE DHARMAPURI
With the help of these functions, you may quickly and effectively analyze typical data on sequence
elements.

What is functional programming?

Functional programming is a programming paradigm that treats computation as evaluating


mathematical functions and avoids changing state and mutable data.

In functional programming, functions are first-class citizens, meaning they can be assigned to variables,
passed as arguments to other functions, and returned as values from other functions.

Functional programming emphasizes immutability, meaning that once a value is assigned, it cannot be
changed, and it avoids side effects, which are changes to the state or behaviour that affect the result of a
function beyond its return value.

Functional programming is possible in Python using a number of features and tools, such as:

1. Higher-order functions - Python enables the assignment of functions to variables, the passing of
functions as arguments, and the return of functions as values. Higher-order functions are the functions
that accept other functions as arguments or return them as results and can be used as a result of
this. Strong functional programming techniques like giving functions as parameters, returning functions
from functions, and constructing functions on the fly are made possible by higher-order functions.

# Example of using higher-order functions in Python


# Function that adds 1 to the passed value (x)
def add(x):
return x + 1

# Function that multiplies the passed value (x) by 2


def multiply(x):
return x * 2

# Function that applies another function on passed value (x)


def apply(func, x):
return func(x)

result1 = apply(add, 3) # Result: 4


result2 = apply(multiply, 3) # Result: 6

2. Lambda Functions - Lambda functions, also known as anonymous functions, can be defined inline
without requiring a formal function declaration and are short and one-time-use functions. They are helpful
for the performance of a single task that only requires one line of code to convey.

# Example of using lambda functions in Python


DON BOSCO COLLEGE DHARMAPURI
# Lambda function that adds 1 to x
add = lambda x: x + 1

# Lambda function that multiplies x by 2


multiply = lambda x: x * 2

result1 = add(3) # Result: 4


result2 = multiply(3) # Result: 6

3. map, filter, and reduce - Map, Filter, and Reduce are built-in Python functions that can be used for
functional programming tasks. With the help of these operations, you may apply a specific function to
sequence items using the 'map', filter sequence elements based on a condition using the 'filter', and
cumulatively aggregate elements using the 'reduce'.

# Example of using map, filter, and reduce in Python


data = [1, 2, 3, 4, 5]

# Using the map to apply a function to each element


# Lambda function returns the square of x
result1 = map(lambda x: x * 2, data) # Result: [2, 4, 6, 8, 10]

# Using the filter to filter elements based on a condition


# Lambda function returns True for an even number
result2 = filter(lambda x: x % 2 == 0, data) # Result: [2, 4]

# Using reduce to aggregate elements


# Lambda function returns product of x and y
from functools import reduce
result3 = reduce(lambda x, y: x * y, data) # Result: 120

4. List Comprehension - List comprehensions are supported by Python, which are simple and
expressive techniques to build new lists from older ones. Functional programming techniques such as
mapping, filtering, and aggregating can be implemented using list comprehensions.

# Example of using list comprehensions in Python


data = [1, 2, 3, 4, 5]

# Using list comprehension to apply a function to each element


result1 = [x * 2 for x in data] # Result: [2, 4, 6, 8, 10]
DON BOSCO COLLEGE DHARMAPURI
# Using list comprehension to filter elements based on a condition
result2 = [x for x in data if x % 2 == 0] # Result: [2, 4]

# Using list comprehension to aggregate elements


result3 = reduce(lambda x, y: x * y, data) # Result 120

Let's dive deeper into the map(), filter(), and reduce() functions in Python.

1. map() - Python's map() method applies a specified function to each item of an iterable (such as a list,
tuple, or string) and then returns a new iterable containing the results.

The map() syntax is as follows: map(function, iterable)

The first argument passed to the map function is itself a function, and the second argument passed is an
iterable (sequence of elements) such as a list, tuple, set, string, etc.

Example 1 - usage of the map():

# Using map() to square each element of the data list


data = [1, 2, 3, 4, 5]

# Map function returns the map object


squares = map(lambda x: x*x, data)

# Iterating the elements of the squares


for i in squares:
print(i, end=" ")

# Also, we can convert the map object into a list


squares = list(map(lambda x: x*x, data))
print(f"Squares: {squares}")

Output:

1, 4, 9, 16, 25
Squares: [1, 4, 9, 16, 25]

Here, the map function takes each element one by one from the data starting from x = 1. Each element
is passed to the lambda function, returning its square. And the returned value is stored in the map object
(an iterable).

2. filter() - The filter() function in Python filters elements from an iterable based on a given condition
or function and returns a new iterable with the filtered elements.
DON BOSCO COLLEGE DHARMAPURI
The syntax for the filter() is as follows: filter(function, iterable)

Here also, the first argument passed to the filter function is itself a function, and the second argument
passed is an iterable (sequence of elements) such as a list, tuple, set, string, etc.

Example 1 - usage of the filter():

You are given a list of integers and should filter the even numbers from the list.

# Using filter() to filter even numbers from a list


data = [1, 2, 3, 4, 5]

# The filter function filters the even numbers from the data
# and returns a filter object (an iterable)
evens = filter(lambda x: x % 2 == 0, data)

# Iterating the values of evens


for i in evens:
print(i, end=" ")

# We can convert the filter object into a list as follows:


evens = list(filter(lambda x: x % 2 == 0, data))

# Printing the evens list


print(f"Evens = {evens}")

Output:

24
Evens = [2, 4]

Example 2: Filtering Perfect Squares

You are given a list of random integers and should filter the perfect squares from them. A perfect
square is a number that can be expressed as the product of the same whole number.

# Python to demonstrate usage of filter function


from math import sqrt

# List that contains random integer values


data = [0, 1, 4, 6, 8, 9, 10, 12, 16, 81, 23, 36]
DON BOSCO COLLEGE DHARMAPURI
# Function that returns true for perfect squares
def isPerfectSqr(i):
return sqrt(i).is_integer()

# Storing the result


answer = list(filter(isPerfectSqr, data))

# Printing the result


print("Answer: ", answer)

Output:

Answer: [0, 1, 4, 9, 16, 81, 36]

In the above example, we have a data list that contains some random integers. The 'isPerfectSqr' function
returns True for perfect square numbers and False for others. The filter function filters out the numbers
from the data, which is a perfect square, and returns an iterable that contains those perfect square numbers.
In the end, we converted the result into a list and printed it into the console.

Example 3: Filter Out Names Starting with H

You are given a list containing names of persons and you should filter out the names starting with the
letter 'H'. Below is the solution of the problem:

# Method 1

# Using filter() to filter names starting with letter H


# A list containing names
names = ["Arun", "Sonu", "Harsh", "Harry", "Anu", "Hassi"]

# The filter function filters the name from the names


# and returns a filter object (an iterable)
# We can convert the filter object into a list as follows:
name_start_with_H = list(filter(lambda x: x[0] == 'H', names))

# Printing the name_start_with_H list


print(f"Method 1 result = {name_start_with_H}")

# Method 2

# We can also use a function instead of lambda function


# The H_name function returns true if x (name) starts with 'H'
DON BOSCO COLLEGE DHARMAPURI
def H_name(x):
return x[0] == 'H'

# Filtering the result and printing it into the console


name_start_with_H = list(filter(H_name, names))
print(f"Method 2 result = {name_start_with_H}")

Output:

Method 1 result = ['Harsh', 'Harry', 'Hassi']


Method 2 result = ['Harsh', 'Harry', 'Hassi']

In the above example, the lambda or H_name function returns true for each x in names starting with
letter H. The filter function filters all the names which satisfies the condition.

3. reduce() - In Python, reduce() is a built-in function that applies a given function to the elements of
an iterable, reducing them to a single value.

The syntax for reduce() is as follows: reduce(function, iterable[, initializer])

The function argument is a function that takes two arguments and returns a single value. The first
argument is the accumulated value, and the second argument is the current value from the iterable.

The iterable argument is the sequence of values to be reduced.

The optional initializer argument is used to provide an initial value for the accumulated result. If no
initializer is specified, the first element of the iterable is used as the initial value.

Here's an example that demonstrates how to use reduce() to find the sum of a list of numbers:

Example 1:

You are given a list containing some integers and you should find the sum of all elements in the list
using reduce function. Below is the solution of the problem:

# Examples to understand the reduce() function


from functools import reduce

# Function that returns the sum of two numbers


def add(a, b):
return a + b

# Our Iterable
num_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
DON BOSCO COLLEGE DHARMAPURI

# add function is passed as the first argument, and num_list is passed as the second argument
sum = reduce(add, num_list)
print(f"Sum of the integers of num_list : {sum}")

# Passing 10 as an initial value


sum = reduce(add, num_list, 10)
print(f"Sum of the integers of num_list with initial value 10 : {sum}")

Output:

Sum of the integers of num_list : 55


Sum of the integers of num_list with initial value 10 : 65

In the above example, the reduce function takes two elements 1 and 2 from the num_list and passes to
the add function in the first iteration. The add function returns the some of the 1 and 2 which is 3. In the
second iteration, the reduce function passes the result of the previous call which is 3 and the next element
which is also 3. This process is repeated until all elements have been processed.

In the case, where we pass the initial value (10), the reduce function takes one element from the num_list
and initial value (10) and passes to the add function in the first iteration.

Example 2: Using operator functions with reduce function

In the below example, we have used operator.add to perform addition, operator.mul to perform
multiplication and operator.concat to perform concatenation on strings.

# Python program to demonstrate


# how to use operator functions with reduce function

# Importing reduce function


from functools import reduce

# Importing operator
import operator

# Creating lists
my_list1 = [1, 2, 3, 4, 5]
my_list2 = ["I", "Love", "Javatpoint"]

# Calculating the sum of the numbers of my_list1


# using reduce and operator.add
DON BOSCO COLLEGE DHARMAPURI
sum = reduce(operator.add, my_list1)

# Calculating the product of the numbers of my_list1


# using reduce and operator.mul
product = reduce(operator.mul, my_list1)

# Concatenating all the elements in my_list2


# using reduce and operator.concat
concated_str1 = reduce(operator.concat, my_list2)

# We can achieve the same output by using operator.add


concated_str2 = reduce(operator.add, my_list2)

# Printing result
print(f"Sum of all elements in my_list1 : {sum}")
print(f"Product of all elements in my_list1 : {product}")
print(f"Concatenated string by using operator.concat : {concated_str1}")
print(f"Concatenated string by using operator.add : {concated_str2}")

Output:

Sum of all elements in my_list1 : 15


Product of all elements in my_list1 : 120
Concatenated string by using operator.concat : ILoveJavatpoint
Concatenated string by using operator.add : ILoveJavatpoint

Here, the function argument in the reduce function is replaced with the operator functions. All the steps
are same as previous examples.

Example 3: Find the largest of the given numbers.

In this example, you are given a list of integers and you should find the largest number using the reduce
function. Below is the solution of the problem:

The are three methods, we can use to achieve the same result:

Method 1 - Using normal function

# Importing reduce function from the functools module


from functools import reduce

# A list containing some integers


DON BOSCO COLLEGE DHARMAPURI
num = [20, 22, 24, 12, 6, 88, 10, 55, 66]

""" Method 1 - Using simple function """

# Function that returns the largest of x and y


def large(x, y):
return x if x > y else y

# Using reduce to find the largest of all and printing the result
largest = reduce(large, num)
print(f"Largest found with method 1: {largest}")

Method 2 - Using Lambda function

""" Method 2 - Using lambda function """

# Using reduce to find the largest of all and printing the result
largest = reduce(lambda x, y: x if x > y else y, num)
print(f"Largest found with method 2: {largest}")

Method 3 - Using max function

""" Method 3 - Using max() function """

# Using reduce to find the largest of all and printing the result
largest = reduce(max, num)
print(f"Largest found with method 3: {largest}")

Output:

Largest found with method 1: 88


Largest found with method 2: 88
Largest found with method 3: 88

In the above example, the large function, lambda function, and the max function returns the maximum of
x and y to the reduce function. And the reduce function parse all the elements one by one. At the end, it
returns the largest of all.

CONCLUSION:
DON BOSCO COLLEGE DHARMAPURI
In conclusion, map(), filter(), and reduce() are built-in functions in Python that are commonly used
for functional programming.

map() is used to apply a given function to each element of an iterable and returns a new iterable with the
results.

filter() is used to filter elements from an iterable based on a given condition or function and returns a
new iterable with the filtered elements.

reduce() is used to apply a given function to the elements of an iterable in a cumulative way, reducing
the iterable to a single value.

These functions or tools give you strong capabilities for processing data quickly and expressively, making
it simple to convert, filter, and aggregate data. They are frequently used in Python's functional
programming concepts to create readable and efficient codes.

Python Modules

In this tutorial, 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:

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.
DON BOSCO COLLEGE DHARMAPURI
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.

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.
DON BOSCO COLLEGE DHARMAPURI
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

Output:

The value of euler's number is 2.718281828459045


DON BOSCO COLLEGE DHARMAPURI
Classes and Objects in Python

You wanted to build a house. What is the first thing you do to start the building process? You create a
plan on how you want your house. You follow the plan to build the house. A plan is like a blueprint of
the house that is not built yet and will be built based on it.

Why do we even need a plan? For the organization of all components like different rooms, walls,
windows, and doors in the right places with the correct dimensions.

Definition of a class:

In any programming language, a class is a user-defined plan or blueprint using which objects or
instances of the class are created.

You may wonder why we need classes in programming. We can create something like a variable or a
structure, store what we want, and use it.

A class can have its attributes - variables and functions with pre-stored values and functionalities.

Example situation: If we want to store the data of different age groups of children and their details in an
orphanage :

We cannot just create a list and keep on storing the ages and names of the children without any
organization.

Creating multiple lists for multiple age groups - one list to store ages, one for names, another to match -
becomes complex and leads to ambiguity.

Syntax:

#Definition of a class

class class_name:
#body of the class
#variables
#functions
#body of the functions

Important points:

"class" is a keyword in python libraries.

A class name must be capitalized.

Attributes are the variables owned by the class (declared inside the class) that the created objects can
use.
DON BOSCO COLLEGE DHARMAPURI
Methods are the functions owned by the class (defined inside the class) that the created objects can use.

The created objects using the dot (.) operator uses these attributes and methods of a class.

Example program:

class Employee:
#Attributes like name, id
#Methods

Now, let's get the overview of Objects:

OBJECTS - The instances of a class

Now, we have the blueprint. This is the time for action and implementing the idea of the class. The house
- the plan is ready. It is time to start the construction. The organizing pattern is ready. Now, we build the
rooms one by one. You can assume one of the objects of the house class is a room. We can create many
objects-many different rooms. An object is like a specimen of the class.

The characteristics of an object:

State: The state of an object refers to the attributes of the object - different variables with different info
about the object.

Identity: It is the object's name to identify every object uniquely from another.

Behavior: The behavior of an object refers to the methods of object-different functionalities.

Examples for the characteristics of an object(Random):


DON BOSCO COLLEGE DHARMAPURI

Object Identity State Behavior

A person Rakesh Literate, qualified, vegetarian Speaking, walking, reading

A shopping sale Republic day sale Started, offers, Ended, Cancelled Earn loyalty points

If we created a class, say, people, a person is an object in that class. The person's name is the unique
identity to identify the object; variables like literate and vegetarian refer to the object's state - different
attributes of the object. The functions like walking; sleeping explains the person's behavior (object).

If the object is a dog:

Declaring an object:

Object_name = Class_name()

Depending on the need, we can create as many objects as we want for a single function. So, we create a
class and store the blueprint to do a task or organize something; we store them in variables called
attributes and functions called methods.

Then, in the program, when we need the functionality of a class or its attributes and methods, we access
them by declaring an object of that class.

Syntax to access:

#Declaring
Object_name = Class_name()
DON BOSCO COLLEGE DHARMAPURI
#To access a class-attribute
Object_name.class_attribute = value

#To access a class-method


Object_name.method_name(arguments)

Let us take the example above - A Dog.

Program:

class Our_Puppy:
Name = "Snoopy"
Color = "Brown"
Breed = "German Sheppard"
Hungry = "yes"

Snoopy = Our_Puppy()
print("The color of my dog is:",Snoopy.Color)

Output:

The color of my dog is: Brown

Now, going to the methods of a class, we need to learn about the self variable and the init
method.

The init () method is a constructor which will be invoked by default when a new object is created
and initialized.

"self" is not a keyword in python. It is a special variable. When we declare a method in a class, we
need to declare the first argument as self.

We will be able to access the attributes and the methods of the class using this self-argument. It holds
the arguments to the attributes.

Even in the init method, we must declare the first argument as self.

Self determines the current instance of the class; In the case of the init method, it refers to the newly
created object, while in other methods, it refers to the object whose method is called.

Even if we want to create a method with no arguments, we need to keep the self variable as the only
argument in the method.

The syntax will look like this:


DON BOSCO COLLEGE DHARMAPURI

class Class_Name:
attribute (variable)1
attribute (variable)2
...
attribute (variable)N

def init (self,arg1,...,argn):

def Method_name1(self,arg1,...,argn):

def Method_name2(self):
...
def Method_nameN(self,arg1,...,argn):

Example programs:

# Using init method

class Student:
def init (self,name,age,email):
self.name = name
self.age = age
self.email = email
name = input("Please enter the name of the student1: ")
age = int(input("Please enter the age of the student1: "))
stud = Student(name,age,'santhosh@gmail.com')
name = input("Please enter the name of the student2: ")
age = int(input("Please enter the age of the student2: "))
stud2 = Student(name,age,'')
print("Stud_1.name =",stud.name)
print("Stud_2.name =",stud2.name)

Output:

Please enter the name of the student1: Santhosh


Please enter the age of the student1: 19
Please enter the name of the student2: Rakesh
Please enter the age of the student2: 19
DON BOSCO COLLEGE DHARMAPURI
Stud_1.name = Santhosh
Stud_2.name = Rakesh

#Using more methods in the class


class Person_details:
def init (self,name):
self.name = name
def setName(self,name):
self.name = name
def getName(self):
return self.name

name = input("Enter the name of the person1: ")


p1 = Person_details(name)
name = input("Enter the name of the person2: ")
p2 = Person_details(name)
print("Person P1 name:",p1.getName())
print("Person P2 name:",p2.getName())

Output:

Enter the name of the person1: Mahesh


Enter the name of the person2: Rakesh
Person P1 name: Mahesh
Person P2 name: Rakesh

Attributes for an Empty class:

Python language allows the programmer to create attributes of an object declared for an empty class.
We can even modify the values of attributes in different objects.

Here is an example of an empty class "Student_info". In the body of the program, we created an object
Stud_1 for the class and gave values to 3 attributes for the class:

class Student_info:
pass

Stud_1 = Student()
Stud_1.name = 'Sonu'
Stud_1.age = 19
DON BOSCO COLLEGE DHARMAPURI
Stud_1.graduate = 'B-tech'
print("Stud_1.name:",Stud_1.name)
print("Stud_1.age:", Stud_1.age)
print("Stud_1.graduate:", Stud_1.graduate)

Output:

Stud_1.name: Sonu
Stud_1.age: 19
Stud_1.graduate: B-tech

We discussed above that the init method is a constructor. Diving deep into Constructors in python:

A constructor can be understood as a type of a method. We use this to perform actions or tasks like
initializing variables and other tasks that must be done when a new object is created.

In python, we use the same init (self) in all classes. The conventions of the name: Two leading
and trailing underscores. It is designed this way to prevent ambiguity with user-defined methods.

If we create a class without using the constructor, by default, python creates a constructor which doesn't
have functionality other than instantiating the created object.

Let's summarize the learned topic till now:

Every class in python will consist of 3 key partners:

The constructor

Attributes of the class

Methods of the class

We create a class. Inside the class, we build the constructor init () with self argument and other
arguments that we bind with the class attributes inside the body. So, when we create an object with
some parameters, these parameters will occupy the arguments and be stored in the class attributes.

It is the same in normal methods, but in normal methods, we will have a task going on, but in the init, it
is only about initializing the arguments.

The self keyword helps bind the parameters and arguments of the constructor and other methods. It
must be declared as the first argument in any method.

Python Instance

Introduction

Python is a type of programming language used by developers worldwide. One of the essential features
of Python is object-oriented programming (OOP). It allow the programmer to create objects, classes,
DON BOSCO COLLEGE DHARMAPURI
and instances. In this article, we are going to discuss Python instances in detail and demonstrate how they
work with an example.

Understanding Object-Oriented Programming

Before we know about Python instances, it's very much important to understand the basics of object-
oriented programming. OOP is a programming concept that revolves around objects, which are instances
of classes. Classes are user-defined data types that encapsulate data and functions that operate on that
data.

In OOP, objects are created from classes, and each object is unique. You can create multiple objects from
the same class, and each object will have its own data and behavior. The following code shows how to
define a class in Python:

Program 1:

class MyClass:
def init (self, name, age):
self.name = name
self.age = age

def get_info(self):
return f"{self.name} is {self.age} years old."

# create an instance of MyClass


my_obj = MyClass("John", 25)

# call get_info method to print out the information


print(my_obj.get_info()) # output: John is 25 years old.

Output:

Explanation

The above code defines a class MyClass with an init method . The init method initializes two instance
variables name and age. The get_info method returns a formatted string that includes the values of the
name and age instance variables.

An instance of the class is created with the name "John" and age 25. Then, the get_info method is called
on the instance, which prints the information "John is 25 years old." to the console.
DON BOSCO COLLEGE DHARMAPURI
Creating Python Instances

Once the programmer have defined a class, then they can create objects (or instances) from that class. To
create an instance, the programmer simply call the class and assign the result to a variable. The following
code snippet shows how to create an instance of the MyClass class:

Program 2:

class Person:
def init (self, name, age):
self.name = name
self.age = age

def greet(self):
print(f"Hello, my name is {self.name} and I am {self.age} years old.")

# create instances of Person class


person1 = Person("Alice", 25)
person2 = Person("Bob", 30)

# call the greet method on each instance


person1.greet() # output: Hello, my name is Alice and I am 25 years old.
person2.greet() # output: Hello, my name is Bob and I am 30 years old.

Output:

Explanation

The above code defines a Person class with a constructor that initializes name and age instance variables.
The class also has a greet method that prints out a greeting with the name and age of the person.

Two instances of the Person class are created with different name and age values. Then, the greet method
is called on each instance, which prints out the greeting with the corresponding values for nameand age.

Accessing Instance Attributes and Methods


DON BOSCO COLLEGE DHARMAPURI
Once the programmer have created an instance, then the programmer can access its attributes and methods
using the dot notation. The following code snippet shows how to access the name attribute and call the
get_info method of the person object:

Program 3:

class Car:
def init (self, make, model, year, color):
self.make = make
self.model = model
self.year = year
self.color = color

def get_info(self):
return f"{self.year} {self.make} {self.model} in {self.color}"

# create an instance of Car


my_car = Car("Toyota", "Corolla", 2020, "blue")

# access instance attributes


print(my_car.make) # output: Toyota
print(my_car.year) # output: 2020

# call instance method


car_info = my_car.get_info()
print(car_info) # output: 2020 Toyota Corolla in blue

Output:

Explanation

The above code shows a class Car with an init__ method that initializes four instance variables make,
model, year, and color. The get_info method returns a formatted string that includes the values of the
year, make, model, and color instance variables.

An instance of the class is created with the make "Toyota", model "Corolla", year 2020, and color "blue".
Then, the make and year instance variables are accessed using dot notation to print their values.
DON BOSCO COLLEGE DHARMAPURI
Finally, the get_info method is called on the instance and the returned string is stored in a variable car_info
which is then printed to the console.

Modifying Instance Attributes

The programmer can also modify the attributes of an instance after it has been created. The following
code snippet shows how to modify the attribute of the object:

Program 4:

class MyClass:
def init (self, name, age):
self.name = name
self.age = age

def get_info(self):
return f"{self.name} is {self.age} years old."

# create an instance of MyClass


my_obj = MyClass("John", 25)

# print the initial information


print(my_obj.get_info()) # output: John is 25 years old.

# modify the instance attributes


my_obj.name = "Jane"
my_obj.age = 30

# print the modified information


print(my_obj.get_info()) # output: Jane is 30 years old.

Output:

Explanation

The above code shows a MyClass class with an __init method that initializes two instance variables name
and age. Here the get_info method returns a formatted string that includes the values of the name and age
instance variables.
DON BOSCO COLLEGE DHARMAPURI
An instance of the class is created with the name "John" and age 25. The initial information is printed
by calling the get_info method on the instance.

The instance attributes name and age are then modified by directly accessing them using the instance
name and the dot notation.

Finally, the modified information is printed by calling the get_info method on the instance again, and it
prints the modified information "Jane is 30 years old." to the console.

Benefit of using Python Instance

There are so many advantages of using Python instances in the programming projects. These are as
follows.

Encapsulation: Python instances allow the programmer to encapsulate data and functions that operate
on that data. This means that the programmer can group related data and functionality together, making
the code more organized and modular.

Reusability: Once the programmer have defined a class, then the programmer can create multiple
instances of that class. This allows the programmer to reuse code and avoid duplicating functionality in
the program.

Customization: Each instance of a class is unique and can be customized to suit specific needs. This
means that the programmer can create objects that have different attributes and behavior based on their
specific use case.

Inheritance: In Python, the programmer can create subclasses that inherit attributes and behavior from a
parent class. This allows the programmer to create more specialized classes that build on the functionality
of existing classes.

Polymorphism: Polymorphism is a programming concept that allows the programmer to use the same
code to operate on different types of objects. Python instances support polymorphism, which means that
the programmer can write code that works with different types of objects as long as they share a common
interface.

Disadvantages of using Python Instance

There are also so many disadvantages of using python instances. These are as follows.

Overhead: when the programmer wants to create instances for a class, it can be computationally
expensive, especially if the class has complex data structures or methods. This overhead can impact the
performance of the code, particularly in applications that require high-speed processing.

Memory Usage: Each instance of a class requires memory to store its data and methods. If the
programmer creates many instances of a class, it can consume a significant amount of memory, which
may cause the application to slow down or crash.
DON BOSCO COLLEGE DHARMAPURI
Complexity: Object-oriented programming can be more complex than other programming paradigms,
especially for beginners. Understanding how to create classes and instances, and how they interact with
each other, requires a more comprehensive understanding of programming concepts.

Maintenance: As the code grows, managing instances and their relationships can become more
challenging. Code changes to a class can impact the behavior of all instances of that class, which can
make it harder to maintain and debug code.

Design: To use instances effectively, the programmer need to design your classes and objects carefully.
Poor design decisions can lead to a codebase that is difficult to understand and maintain.

Conclusion

Python instances are objects created from classes that encapsulate data and functions. The programmer
can create multiple instances from the same class, and each instance will have its own data and behavior.
Python instances are a powerful feature of object-oriented programming that allows the programmer to
model real-world objects and their behavior in code. By mastering Python instances, theprogrammer will
be able to write more modular, maintainable, and scalable Python code.

PART - A ( 1 Marks )
1. What will be the output of the following Python code?

import functools
l=[1,2,3,4]print(functools.reduce(lambda x,y:x*y,l))
a) Error
b) 10
c) 24
d) No output
View Answer

Answer: c
Explanation: The code shown above returns the product of all the elements of the list. Hence the
output is 1*2*3*4 = 24.

2. What will be the output of the following Python code?

l=[1, -2, -3,4,5]def f1(x):


return x<2
m1=filter(f1, l)print(list(m1))
a) [1, 4, 5 ]
b) Error
c) [-2, -3]
d) [1, -2, -3]
View Answer
DON BOSCO COLLEGE DHARMAPURI
Answer: d
Explanation: The code shown above returns only those elements from the list, which are less than 2.
The functional programming tool used to achieve this operation is filter. Hence the output of the code
is:[1, -2, -3].

3. Python supports the creation of anonymous functions at runtime, using a construct called

a) lambda
b) pi
c) anonymous
d) none of the mentioned
View Answer

Answer: a
Explanation: Python supports the creation of anonymous functions (i.e. functions that are not bound
to a name) at runtime, using a construct called lambda. Lambda functions are restricted to a single
expression. They can be used wherever normal functions can be used.

4. Which keyword is use for function?


A. define
B. fun
C. def
D. function
View Answer
Ans : C
Explanation: Keyword def marks the start of function header. So, option C is correct.

5. Which of the following items are present in the function header?


A. function name
B. parameter list
C. return value
D. Both A and B
View Answer
Ans : D
Explanation: function header consists of function name and parameter list. So, option D is correct.

6. What is called when a function is defined inside a class?


A. class
B. function
C. method
D. module
DON BOSCO COLLEGE DHARMAPURI
View Answer
Ans : C
Explanation: method is called when a function is defined inside a class. So, option C is correct.

7. If return statement is not used inside the function, the function will return:
A. None
B. 0
C. Null
D. Arbitary value
View Answer
Ans : A
Explanation: If return statement is not used inside the function, the function will return None. So,
option A is correct.

8. What is a recursive function?


A. A function that calls other function.
B. A function which calls itself.
C. Both A and B
D. None of the above
View Answer
Ans : B
Explanation: Recursive functions are the functions which calls itself. So, option B is correct.

9. Which of the following is the use of id() function in python?


A. Id() returns the size of object.
B. Id() returns the identity of the object.
C. Both A and B
D. None of the above
View Answer
Ans : B
Explanation: The id() function returns the identity of the object. This is an integer that is unique for
the given object and remains constant during its lifetime. So, option B is correct.

10. Which of the following function headers is correct?


A. def fun(a = 2, b = 3, c)
B. def fun(a = 2, b, c = 3)
DON BOSCO COLLEGE DHARMAPURI
C. def fun(a, b = 2, c = 3)
D. def fun(a, b, c = 3, d)
View Answer
Ans : C
Explanation: All required parameters must be placed before any default arguments. Simply because
they are mandatory, whereas default arguments are not. Syntactically, it would be impossible for the
interpreter to decide which values match which arguments if mixed modes were allowed. A
SyntaxError is raised if the arguments are not given in the correct order. So, option C is correct.

11. In which part of memory does the system stores the parameter and local variables of funtion call?
A. heap
B. stack
C. Uninitialized data segment
D. None of the above
View Answer
Ans : B
Explanation: Stack, where variables are stored, along with information that is saved each time a
function is called. Each time a function is called, the address of where to return to and certain
information about the caller's environment, such as some of the machine registers, are saved on the
stack. So, option B is correct.

12. Which of the following will print the pi value defined in math module?
A. print(pi)
B. print(math.pi)
C. from math import pi
print(pi)
D. from math import pi
print(math.pi)
View Answer
Ans : C
Explanation: from math import pi, print(pi) will print the pi value defined in math module. So,
option C is correct.

13. Which operator is used in Python to import modules from packages?


A. .
B. *
C. ->
D. &
View Answer
DON BOSCO COLLEGE DHARMAPURI
Ans : A
Explanation: . operator is used in Python to import modules from packages. So, option A is correct.

14. Where is function defined?


A. Module
B. class
C. Another Function
D. All of the above
View Answer
Ans : D
Explanation: Function can be defined in module, class and another function. So, option D is correct.

15. Lambda is a function in python?


A. True
B. False
C. Lambda is a function in python but user can not use it.
D. None of the above
View Answer

16. What is a variable defined outside a function referred to as?


A. local variable
B. global variable
C. static Variable
D. automatic variable
View Answer
Ans : B
Explanation: Variable defined outside a function is referred as Global variable and can be accessible
by other functions. So, option B is correct.

17. What is the output of the following program?


z = lambda x : x * x

print(z(6))
A. 6
B. 36
C. 0
D. error
View Answer
DON BOSCO COLLEGE DHARMAPURI
Ans : B
Explanation: This lambda function will calculate the square of a number. So, option B is correct.

18. What is the output of the following program?

print(chr(ord(chr(97))))

A. a
B. A
C. 97
D. error
View Answer
Ans : A
Explanation: Outer chr and ord will cancel out and we will be left with chr(97) which will return "a".
So, option A is correct.

19. How is a function declared in Python?


A. def function function_name():
B. declare function function_name():
C. def function_name():
D. declare function_name():
View Answer
Ans : C
Explanation: By using def function_name(): we can declared in Python. So option C is correct.

20. Which one of the following is the correct way of calling a function?
A. function_name()
B. call function_name()
C. ret function_name()
D. function function_name()
View Answer
Ans : A
Explanation: By using function_name() we can call a function in Python. So option A is correct.

21. Choose the correct option with reference to below Python code?
def fn(a):
print(a)
x=90
fn(x)
DON BOSCO COLLEGE DHARMAPURI
A. x is the formal argument.
B. a is the actual argument.
C. fn(x) is the function signature.
D. x is the actual argument.
View Answer
Ans : D
Explanation: x is the actual argument that is the correct option with reference to below Python code.
So option D is correct.

22. Which one of the following is incorrect?


A. The variables used inside function are called local variables.
B. The local variables of a particular function can be used inside other functions, but these cannot be
used in global space
C. The variables used outside function are called global variables
D. In order to change the value of global variable inside function, keyword global is used.
View Answer

23. You can also create your own functions, these functions are called?
A. built-in functions
B. user-defined functions
C. py function
D. None of the above
View Answer
Ans : B
Explanation: Python gives you many built-in functions like print(), etc. but you can also create your
own functions. These functions are called user-defined functions.
24. Function blocks begin with the keyword?
A. define
B. fun
C. function
D. def
View Answer
Ans : D
Explanation: Function blocks begin with the keyword def followed by the function name and
parentheses ( ( ) ).

PART - B (5 MARKS)
1) Write a differences between Functions and Functional Programming?
DON BOSCO COLLEGE
DHARMAPURI
2) Explain about Built in functions?
3) Write shortly about function call by reference and call by value?
4) Write about function modules?
5) Explain function classes and class attributes?
PART - C (10 MARKS)
1) Explain briefly about types of functions ?
2) Explain that built in functions and module built in functions?
3) Write different type of calling functions in functions?
DON BOSCO COLLEGE
DHARMAPURI
DON BOSCO COLLEGE DHARMAPURI

UNIT - V
Database Programming – Introduction - Basic Database Operations and SQL - Example of using
Database Adapters, Mysql - Regular Expression – Special Symbols and Characters – REs and Python

What is Database

The database is a collection of inter-related data which is used to retrieve, insert and delete the data
efficiently. It is also used to organize the data in the form of a table, schema, views, and reports, etc.

For example: The college Database organizes the data about the admin, staff, students and faculty etc.

Using the database, you can easily retrieve, insert, and delete the information.

Database Management System

Database management system is a software which is used to manage the database. For example:
MySQL, Oracle, etc are a very popular commercial database which is used in different applications.

DBMS provides an interface to perform various operations like database creation, storing data in it,
updating data, creating a table in the database and a lot more.

It provides protection and security to the database. In the case of multiple users, it also maintains data
consistency.

DBMS allows users the following tasks:

Data Definition: It is used for creation, modification, and removal of definition that defines the
organization of data in the database.

Data Updation: It is used for the insertion, modification, and deletion of the actual data in the database.

Data Retrieval: It is used to retrieve the data from the database which can be used by applications for
various purposes.

User Administration: It is used for registering and monitoring users, maintain data integrity, enforcing
data security, dealing with concurrency control, monitoring performance and recovering information
corrupted by unexpected failure.

Characteristics of DBMS

It uses a digital repository established on a server to store and manage the information.It

can provide a clear and logical view of the process that manipulates data.

DBMS contains automatic backup and recovery procedures.


DON BOSCO COLLEGE DHARMAPURI
It contains ACID properties which maintain data in a healthy state in case of failure.

It can reduce the complex relationship between data.

It is used to support manipulation and processing of data.

It is used to provide security of data.

It can view the database from different viewpoints according to the requirements of the user.

Advantages of DBMS

Controls database redundancy: It can control data redundancy because it stores all the data in one single
database file and that recorded data is placed in the database.

Data sharing: In DBMS, the authorized users of an organization can share the data among multiple users.

Easily Maintenance: It can be easily maintainable due to the centralized nature of the database system.

Reduce time: It reduces development time and maintenance need.

Backup: It provides backup and recovery subsystems which create automatic backup of data from
hardware and software failures and restores the data if required.

multiple user interface: It provides different types of user interfaces like graphical user interfaces,
application program interfaces

Disadvantages of DBMS

Cost of Hardware and Software: It requires a high speed of data processor and large memory size to
run DBMS software.

Size: It occupies a large space of disks and large memory to run them efficiently.

Complexity: Database system creates additional complexity and requirements.

Higher impact of failure: Failure is highly impacted the database because in most of the organization,
all the data stored in a single database and if the database is damaged due to electric failure or database
corruption then the data may be lost forever.

Database Connection

In this section of the tutorial, we will discuss the steps to connect the python application to the database.

There are the following steps to connect a python application to our database.

Import mysql.connector module


DON BOSCO COLLEGE DHARMAPURI
Create the connection object.

Create the cursor object

Execute the query

Creating the connection

To create a connection between the MySQL database and the python application, the connect() method
of mysql.connector module is used.

Pass the database details like HostName, username, and the database password in the method call. The
method returns the connection object.

The syntax to use the connect() is given below.

Connection-Object= mysql.connector.connect(host = <host-


name> , user = <username> , passwd = <password> )

Consider the following example.

Example

import mysql.connector

#Create the connection object


myconn = mysql.connector.connect(host = "localhost", user = "root",passwd = "google")

#printing the connection object


print(myconn)

Output:

<mysql.connector.connection.MySQLConnection object at 0x7fb142edd780>

Here, we must notice that we can specify the database name in the connect() method if we want to
connect to a specific database.

Example

import mysql.connector
DON BOSCO COLLEGE DHARMAPURI

#Create the connection object


myconn = mysql.connector.connect(host = "localhost", user = "root",passwd = "google", database = "m
ydb")

#printing the connection object


print(myconn)

Output:

<mysql.connector.connection.MySQLConnection object at 0x7ff64aa3d7b8>

Creating a cursor object

The cursor object can be defined as an abstraction specified in the Python DB-API 2.0. It facilitates us to
have multiple separate working environments through the same connection to the database. We can create
the cursor object by calling the 'cursor' function of the connection object. The cursor object is an important
aspect of executing queries to the databases.

The syntax to create the cursor object is given below.

<my_cur> = conn.cursor()

Example

import mysql.connector
#Create the connection object
myconn = mysql.connector.connect(host = "localhost", user = "root",passwd = "google", database = "m
ydb")

#printing the connection object


print(myconn)

#creating the cursor object


cur = myconn.cursor()

print(cur)

Output:

<mysql.connector.connection.MySQLConnection object at 0x7faa17a15748>


MySQLCursor: (Nothing executed yet)
DON BOSCO COLLEGE DHARMAPURI
Creating new databases

In this section of the tutorial, we will create the new database PythonDB.

Getting the list of existing databases

We can get the list of all the databases by using the following MySQL query.

> show databases;

Example

import mysql.connector

#Create the connection object


myconn = mysql.connector.connect(host = "localhost", user = "root",passwd = "google")

#creating the cursor object


cur = myconn.cursor()

try:
dbs = cur.execute("show databases")
except:
myconn.rollback()
for x in cur:
print(x)
myconn.close()

Output:

('EmployeeDB',)
('Test',)
('TestDB',)
('information_schema',)
('javatpoint',)
('javatpoint1',)
('mydb',)
('mysql',)
('performance_schema',)
('testDB',)

Creating the new database


DON BOSCO COLLEGE DHARMAPURI
The new database can be created by using the following SQL query.

> create database <database-name>

Example

import mysql.connector

#Create the connection object


myconn = mysql.connector.connect(host = "localhost", user = "root",passwd = "google")

#creating the cursor object


cur = myconn.cursor()

try:
#creating a new database
cur.execute("create database PythonDB2")

#getting the list of all the databases which will now include the new database PythonDB
dbs = cur.execute("show databases")

except:
myconn.rollback()

for x in cur:
print(x)

myconn.close()

Output:

('EmployeeDB',)
('PythonDB',)
('Test',)
('TestDB',)
('anshika',)
('information_schema',)
('javatpoint',)
('javatpoint1',)
DON BOSCO COLLEGE DHARMAPURI
('mydb',)
('mydb1',)
('mysql',)
('performance_schema',)
('testDB',)
Creating the table

In this section of the tutorial, we will create the new table Employee. We have to mention the database
name while establishing the connection object.

We can create the new table by using the CREATE TABLE statement of SQL. In our database PythonDB,
the table Employee will have the four columns, i.e., name, id, salary, and department_id initially.

The following query is used to create the new table Employee.

> create table Employee (name varchar(20) not null, id int primary key, salary float not null, Dept_Id i
nt not null)

Example

import mysql.connector

#Create the connection object


myconn = mysql.connector.connect(host = "localhost", user = "root",passwd = "google",database = "Py
thonDB")

#creating the cursor object


cur = myconn.cursor()

try:
#Creating a table with name Employee having four columns i.e., name, id, salary, and department id
dbs = cur.execute("create table Employee(name varchar(20) not null, id int(20) not null primary key,
salary float not null, Dept_id int not null)")
except:
myconn.rollback()

myconn.close()
DON BOSCO COLLEGE DHARMAPURI

Now, we may check that the table Employee is present in the database.

Alter Table

Sometimes, we may forget to create some columns, or we may need to update the table schema. The alter
statement used to alter the table schema if required. Here, we will add the column branch_name to the
table Employee. The following SQL query is used for this purpose.

alter table Employee add branch_name varchar(20) not null

Consider the following example.

Example

import mysql.connector

#Create the connection object


myconn = mysql.connector.connect(host = "localhost", user = "root",passwd = "google",database = "Py
thonDB")

#creating the cursor object


cur = myconn.cursor()

try:
#adding a column branch name to the table Employee
DON BOSCO COLLEGE DHARMAPURI
cur.execute("alter table Employee add branch_name varchar(20) not null")
except:
myconn.rollback()

myconn.close()

Insert Operation

Adding a record to the table

The INSERT INTO statement is used to add a record to the table. In python, we can mention the
format specifier (%s) in place of values.

We provide the actual values in the form of tuple in the execute() method of the cursor.

Consider the following example.

Example

import mysql.connector
#Create the connection object
myconn = mysql.connector.connect(host = "localhost", user = "root",passwd = "google",database = "Py
thonDB")
#creating the cursor object
cur = myconn.cursor()
sql = "insert into Employee(name, id, salary, dept_id, branch_name) values (%s, %s, %s, %s, %s)"
DON BOSCO COLLEGE DHARMAPURI
#The row values are provided in the form of tuple
val = ("John", 110, 25000.00, 201, "Newyork")

try:
#inserting the values into the table
cur.execute(sql,val)

#commit the transaction


myconn.commit()

except:
myconn.rollback()

print(cur.rowcount,"record inserted!")
myconn.close()

Output:

1 record inserted!

Insert multiple rows

We can also insert multiple rows at once using the python script. The multiple rows are mentioned as
the list of various tuples.
DON BOSCO COLLEGE DHARMAPURI
Each element of the list is treated as one particular row, whereas each element of the tuple is treated as
one particular column value (attribute).

Consider the following example.

Example

import mysql.connector

#Create the connection object


myconn = mysql.connector.connect(host = "localhost", user = "root",passwd = "google",database = "Py
thonDB")

#creating the cursor object


cur = myconn.cursor()
sql = "insert into Employee(name, id, salary, dept_id, branch_name) values (%s, %s, %s, %s, %s)"
val = [("John", 102, 25000.00, 201, "Newyork"),("David",103,25000.00,202,"Port of spain"),("Nick",1
04,90000.00,201,"Newyork")]

try:
#inserting the values into the table
cur.executemany(sql,val)

#commit the transaction


myconn.commit()
print(cur.rowcount,"records inserted!")

except:
myconn.rollback()

myconn.close()

Output:

3 records inserted!
DON BOSCO COLLEGE DHARMAPURI

Row ID

In SQL, a particular row is represented by an insertion id which is known as row id. We can get the last
inserted row id by using the attribute lastrowid of the cursor object.

Consider the following example.

Example

import mysql.connector
#Create the connection object
myconn = mysql.connector.connect(host = "localhost", user = "root",passwd = "google",database = "Py
thonDB")
#creating the cursor object
cur = myconn.cursor()

sql = "insert into Employee(name, id, salary, dept_id, branch_name) values (%s, %s, %s, %s, %s)"

val = ("Mike",105,28000,202,"Guyana")

try:
#inserting the values into the table
cur.execute(sql,val)

#commit the transaction


DON BOSCO COLLEGE DHARMAPURI
myconn.commit()

#getting rowid
print(cur.rowcount,"record inserted! id:",cur.lastrowid)

except:
myconn.rollback()

myconn.close()

Output:

1 record inserted! Id: 0


Read Operation

The SELECT statement is used to read the values from the databases. We can restrict the output of a
select query by using various clause in SQL like where, limit, etc.

Python provides the fetchall() method returns the data stored inside the table in the form of rows. We
can iterate the result to get the individual rows.

In this section of the tutorial, we will extract the data from the database by using the python script. We
will also format the output to print it on the console.

Example

import mysql.connector

#Create the connection object


myconn = mysql.connector.connect(host = "localhost", user = "root",passwd = "google",database = "Py
thonDB")

#creating the cursor object


cur = myconn.cursor()

try:
#Reading the Employee data
cur.execute("select * from Employee")

#fetching the rows from the cursor object


result = cur.fetchall()
#printing the result
DON BOSCO COLLEGE DHARMAPURI

for x in result:
print(x);
except:
myconn.rollback()

myconn.close()

Output:

Backward Skip 10sPlay VideoForward Skip 10s


('John', 101, 25000.0, 201, 'Newyork')
('John', 102, 25000.0, 201, 'Newyork')
('David', 103, 25000.0, 202, 'Port of spain')
('Nick', 104, 90000.0, 201, 'Newyork')
('Mike', 105, 28000.0, 202, 'Guyana')

Reading specific columns

We can read the specific columns by mentioning their names instead of using star (*).

In the following example, we will read the name, id, and salary from the Employee table and print it on
the console.

Example

import mysql.connector
#Create the connection object
myconn = mysql.connector.connect(host = "localhost", user = "root",passwd = "google",database = "Py
thonDB")
#creating the cursor object
cur = myconn.cursor()
try:
#Reading the Employee data
cur.execute("select name, id, salary from Employee")

#fetching the rows from the cursor object


result = cur.fetchall()
#printing the result
for x in result:
DON BOSCO COLLEGE DHARMAPURI
print(x);
except:
myconn.rollback()
myconn.close()

Output:

('John', 101, 25000.0)


('John', 102, 25000.0)
('David', 103, 25000.0)
('Nick', 104, 90000.0)
('Mike', 105, 28000.0)

The fetchone() method

The fetchone() method is used to fetch only one row from the table. The fetchone() method returns the
next row of the result-set.

Consider the following example.

Example

import mysql.connector

#Create the connection object


myconn = mysql.connector.connect(host = "localhost", user = "root",passwd = "google",database = "Py
thonDB")

#creating the cursor object


cur = myconn.cursor()

try:
#Reading the Employee data
cur.execute("select name, id, salary from Employee")

#fetching the first row from the cursor object


result = cur.fetchone()

#printing the result


print(result)
DON BOSCO COLLEGE DHARMAPURI

except:
myconn.rollback()

myconn.close()

Output:

('John', 101, 25000.0)

Formatting the result

We can format the result by iterating over the result produced by the fetchall() or fetchone() method of
cursor object since the result exists as the tuple object which is not readable.

Consider the following example.

Example

import mysql.connector

#Create the connection object


myconn = mysql.connector.connect(host = "localhost", user = "root",passwd = "google",database = "Py
thonDB")

#creating the cursor object


cur = myconn.cursor()

try:

#Reading the Employee data


cur.execute("select name, id, salary from Employee")

#fetching the rows from the cursor object


result = cur.fetchall()

print("Name id Salary");
for row in result:
print("%s %d %d"%(row[0],row[1],row[2]))
except:
myconn.rollback()
DON BOSCO COLLEGE DHARMAPURI

myconn.close()

Output:

Name id Salary
John 101 25000
John 102 25000
David 103 25000
Nick 104 90000
Mike 105 28000

Using where clause

We can restrict the result produced by the select statement by using the where clause. This will extract
only those columns which satisfy the where condition.

Consider the following example.

Example: printing the names that start with j

import mysql.connector

#Create the connection object


myconn = mysql.connector.connect(host = "localhost", user = "root",passwd = "google",database = "Py
thonDB")

#creating the cursor object


cur = myconn.cursor()

try:
#Reading the Employee data
cur.execute("select name, id, salary from Employee where name like 'J%'")

#fetching the rows from the cursor object


result = cur.fetchall()

print("Name id Salary");

for row in result:


DON BOSCO COLLEGE DHARMAPURI
print("%s %d %d"%(row[0],row[1],row[2]))
except:
myconn.rollback()

myconn.close()

Output:

Name id Salary
John 101 25000
John 102 25000

Example: printing the names with id = 101, 102, and 103

import mysql.connector

#Create the connection object


myconn = mysql.connector.connect(host = "localhost", user = "root",passwd = "google",database = "Py
thonDB")

#creating the cursor object


cur = myconn.cursor()

try:
#Reading the Employee data
cur.execute("select name, id, salary from Employee where id in (101,102,103)")

#fetching the rows from the cursor object


result = cur.fetchall()

print("Name id Salary");

for row in result:


print("%s %d %d"%(row[0],row[1],row[2]))
except:
myconn.rollback()

myconn.close()

Output:
DON BOSCO COLLEGE DHARMAPURI
Name id Salary
John 101 25000
John 102 25000
David 103 2500

Ordering the result

The ORDER BY clause is used to order the result. Consider the following example.

Example

import mysql.connector

#Create the connection object


myconn = mysql.connector.connect(host = "localhost", user = "root",passwd = "google",database = "Py
thonDB")

#creating the cursor object


cur = myconn.cursor()

try:
#Reading the Employee data
cur.execute("select name, id, salary from Employee order by name")

#fetching the rows from the cursor object


result = cur.fetchall()

print("Name id Salary");

for row in result:


print("%s %d %d"%(row[0],row[1],row[2]))
except:
myconn.rollback()

myconn.close()

Output:

Name id Salary
David 103 25000
DON BOSCO COLLEGE DHARMAPURI
John 101 25000
John 102 25000
Mike 105 28000
Nick 104 90000

Order by DESC

This orders the result in the decreasing order of a particular column.

Example

import mysql.connector

#Create the connection object


myconn = mysql.connector.connect(host = "localhost", user = "root",passwd = "google",database = "Py
thonDB")

#creating the cursor object


cur = myconn.cursor()

try:
#Reading the Employee data
cur.execute("select name, id, salary from Employee order by name desc")

#fetching the rows from the cursor object


result = cur.fetchall()

#printing the result


print("Name id Salary");
for row in result:
print("%s %d %d"%(row[0],row[1],row[2]))

except:
myconn.rollback()

myconn.close()

Output:

Name id Salary
DON BOSCO COLLEGE DHARMAPURI
Nick 104 90000
Mike 105 28000
John 101 25000
John 102 25000
David 103 25000
Update Operation

The UPDATE-SET statement is used to update any column inside the table. The following SQL query
is used to update a column.

> update Employee set name = 'alex' where id = 110

Consider the following example.

Example

import mysql.connector

#Create the connection object


myconn = mysql.connector.connect(host = "localhost", user = "root",passwd = "google",database = "Py
thonDB")

#creating the cursor object


cur = myconn.cursor()

try:
#updating the name of the employee whose id is 110
cur.execute("update Employee set name = 'alex' where id = 110")
myconn.commit()
except:

myconn.rollback()

myconn.close()
DON BOSCO COLLEGE DHARMAPURI

Delete Operation

The DELETE FROM statement is used to delete a specific record from the table. Here, we must impose
a condition using WHERE clause otherwise all the records from the table will be removed.

The following SQL query is used to delete the employee detail whose id is 110 from the table.

> delete from Employee where id = 110

Consider the following example.

Example

import mysql.connector

#Create the connection object


myconn = mysql.connector.connect(host = "localhost", user = "root",passwd = "google",database = "Py
thonDB")

#creating the cursor object


cur = myconn.cursor()

try:
DON BOSCO COLLEGE DHARMAPURI
#Deleting the employee details whose id is 110
cur.execute("delete from Employee where id = 110")
myconn.commit()
except:

myconn.rollback()

myconn.close()
Join Operation

We can combine the columns from two or more tables by using some common column among them by
using the join statement.

We have only one table in our database, let's create one more table Departments with two columns
department_id and department_name.

create table Departments (Dept_id int(20) primary key not null, Dept_Name varchar(20) not null);

As we have created a new table Departments as shown in the above image. However, we haven't yet
inserted any value inside it.

Let's insert some Departments ids and departments names so that we can map this to our Employee
table.

insert into Departments values (201, "CS");


DON BOSCO COLLEGE DHARMAPURI
insert into Departments values (202, "IT");

Let's look at the values inserted in each of the tables. Consider the following image.

Now, let's create a python script that joins the two tables on the common column, i.e., dept_id.

Example

import mysql.connector

#Create the connection object


myconn = mysql.connector.connect(host = "localhost", user = "root",passwd = "google",database = "Py
thonDB")
#creating the cursor object
cur = myconn.cursor()
try:
#joining the two tables on departments_id
cur.execute("select Employee.id, Employee.name, Employee.salary, Departments.Dept_id, Departme
nts.Dept_Name from Departments join Employee on Departments.Dept_id = Employee.Dept_id")
print("ID Name Salary Dept_Id Dept_Name")
for row in cur:
print("%d %s %d %d %s"%(row[0], row[1],row[2],row[3],row[4]))

except:
myconn.rollback()

myconn.close()
DON BOSCO COLLEGE DHARMAPURI
Output:

ID Name Salary Dept_Id Dept_Name


101 John 25000 201 CS
102 John 25000 201 CS
103 David 25000 202 IT
104 Nick 90000 201 CS
105 Mike 28000 202 IT

Right Join

Right join shows all the columns of the right-hand side table as we have two tables in the database
PythonDB, i.e., Departments and Employee. We do not have any Employee in the table who is not
working for any department (Employee for which department id is null). However, to understand the
concept of right join let's create the one.

Execute the following query on the MySQL server.

insert into Employee(name, id, salary, branch_name) values ("Alex",108,29900,"Mumbai");

This will insert an employee Alex who doesn't work for any department (department id is null).

Now, we have an employee in the Employee table whose department id is not present in the
Departments table. Let's perform the right join on the two tables now.

Example

import mysql.connector

#Create the connection object


myconn = mysql.connector.connect(host = "localhost", user = "root",passwd = "google",database = "Py
thonDB")

#creating the cursor object


cur = myconn.cursor()

try:
#joining the two tables on departments_id
result = cur.execute("select Employee.id, Employee.name, Employee.salary, Departments.Dept_id,
Departments.Dept_Name from Departments right join Employee on Departments.Dept_id = Employee.
Dept_id")
DON BOSCO COLLEGE DHARMAPURI

print("ID Name Salary Dept_Id Dept_Name")

for row in cur:


print(row[0]," ", row[1]," ",row[2]," ",row[3]," ",row[4])

except:
myconn.rollback()

myconn.close()

Output:

ID Name Salary Dept_Id Dept_Name


101 John 25000.0 201 CS
102 John 25000.0 201 CS
103 David 25000.0 202 IT
104 Nick 90000.0 201 CS
105 Mike 28000.0 202 IT
108 Alex 29900.0 None None

Left Join

The left join covers all the data from the left-hand side table. It has just opposite effect to the right join.
Consider the following example.

Example

import mysql.connector

#Create the connection object


myconn = mysql.connector.connect(host = "localhost", user = "root",passwd = "google",database = "Py
thonDB")

#creating the cursor object


cur = myconn.cursor()

try:
DON BOSCO COLLEGE DHARMAPURI
#joining the two tables on departments_id
result = cur.execute("select Employee.id, Employee.name, Employee.salary, Departments.Dept_id,
Departments.Dept_Name from Departments left join Employee on Departments.Dept_id = Employee.D
ept_id")
print("ID Name Salary Dept_Id Dept_Name")
for row in cur:
print(row[0]," ", row[1]," ",row[2]," ",row[3]," ",row[4])

except:
myconn.rollback()

myconn.close()

Output:

ID Name Salary Dept_Id Dept_Name


101 John 25000.0 201 CS
102 John 25000.0 201 CS
103 David 25000.0 202 IT
104 Nick 90000.0 201 CS
105 Mike 28000.0 202 IT
Transaction property

The transaction has the four properties. These are used to maintain consistency in a database, before
and after the transaction.

Property of Transaction

Atomicity

Consistency

Isolation

Durability
DON BOSCO COLLEGE DHARMAPURI

Atomicity

It states that all operations of the transaction take place at once if not, the transaction is aborted.

There is no midway, i.e., the transaction cannot occur partially. Each transaction is treated as one unit
and either run to completion or is not executed at all.

Atomicity involves the following two operations:

Abort: If a transaction aborts then all the changes made are not visible.

Commit: If a transaction commits then all the changes made are visible.

Example: Let's assume that following transaction T consisting of T1 and T2. A consists of Rs 600 and
B consists of Rs 300. Transfer Rs 100 from account A to account B.

T1 T2

Read(A) Read(B)
A:= A-100 Y:= Y+100
Write(A) Write(B)

After completion of the transaction, A consists of Rs 500 and B consists of Rs 400.

If the transaction T fails after the completion of transaction T1 but before completion of transaction T2,
then the amount will be deducted from A but not added to B. This shows the inconsistent database state.
In order to ensure correctness of database state, the transaction must be executed in entirety.
DON BOSCO COLLEGE DHARMAPURI
Consistency

The integrity constraints are maintained so that the database is consistent before and after the
transaction.

The execution of a transaction will leave a database in either its prior stable state or a new stable state.

The consistent property of database states that every transaction sees a consistent database instance.

The transaction is used to transform the database from one consistent state to another consistent state.

For example: The total amount must be maintained before or after the transaction.

Total before T occurs = 600+300=900


Total after T occurs= 500+400=900

Therefore, the database is consistent. In the case when T1 is completed but T2 fails, then inconsistency
will occur.

Isolation

It shows that the data which is used at the time of execution of a transaction cannot be used by the
second transaction until the first one is completed.

In isolation, if the transaction T1 is being executed and using the data item X, then that data item can't
be accessed by any other transaction T2 until the transaction T1 ends.

The concurrency control subsystem of the DBMS enforced the isolation property.

Durability

The durability property is used to indicate the performance of the database's consistent state. It states
that the transaction made the permanent changes.

They cannot be lost by the erroneous operation of a faulty transaction or by the system failure. When a
transaction is completed, then the database reaches a state known as the consistent state. That consistent
state cannot be lost, even in the event of a system's failure.

The recovery subsystem of the DBMS has the responsibility of Durability property.

MySQL Regular Expressions

A regular expression is a special string that describes a search pattern. It's a powerful tool to givea
concise and flexible way for identifying text strings such as characters and words based on patterns.
DON BOSCO COLLEGE DHARMAPURI
It uses its own syntax that can be interpreted by a regular expression processor. A regular expression is
widely used in almost all platforms, from programming languages to databases, including MySQL.

A regular expression uses the backslash as an escape character that should be considered in the pattern
match if double backslashes have used. The regular expressions are not case sensitive. It is abbreviated
as REGEX or REGEXP in MySQL.

The advantage of using regular expression is that we are not limited to search for a string based on a fixed
pattern with the percent (%) sign and underscore (_) in the LIKE operator. The regular expressionhas
more meta-characters that allow more flexibility and control while performing pattern matching.

We have previously learned about wildcards, which allows us to get a similar result as regular
expressions. So we may ask why we learn regular expressions if we will get the same result as the
wildcards. It is because regular expressions allow us to search data matching even more complex ways
compared to wildcards.

Syntax

MySQL adapts the regular expression implemented by Henry Spencer. MySQL allows us to match
patterns right in the SQL statements by using the REGEXP operator. The following is the basic syntax
that illustrates the use of regular expressions in MySQL:

SELECT column_lists FROM table_name WHERE field_name REGEXP 'pattern';

In this syntax, the column_list indicates the column name returns in the result set. The table_name is the
name of the table that data will be retrieved using the pattern. The WHERE field_name represents the
column name on which the regular expression is performed. The REGEXP is the regular expression
operator, and the pattern is the search condition to be matched by REGEXP. We can also use the
RLIKE operator, which is the synonym for REGEXP that gives the same results as REGEXP. We can
avoid the confusion to use this statement with the LIKE operator by using the REGEXP instead of LIKE.

This statement returns true if a value in the WHERE field_name matches the pattern. Otherwise, it returns
false. If either field_name or pattern is NULL, the result is always NULL. The negation form of the
REGEXP operator is NOT REGEXP.

Regular Expression Meta-Characters


DON BOSCO COLLEGE DHARMAPURI
The following table shows the most commonly used meta-characters and constructs in a regular

Meta- Descriptions
Character

^ The caret (^) character is used to start matches at the beginning of a searched string.

$ The dollar ($) character is used to start matches at the end of a searched string.
. The dot (.) character matches any single character except for a new line.
[abc] It is used to match any characters enclosed in the square brackets.
[^abc] It is used to match any characters not specified in the square brackets.

* The asterisk (*) character matches zero (0) or more instances of the preceding strings .

+ The plus (+) character matches one or more instances of preceding strings.
{n} It is used to match n instances of the preceding element.

{m, n} It is used to match m to n instance of the preceding element.


p1|p2 It is used to isolate alternatives that match any of the patterns p1 or p2.
? The question mark (?) character matches zero (0) or one instance of preceding
strings.
[A-Z] It is used to match any upper case character.

[a-z] It is used to match any lower case character.


[0-9] It is used to match numeric digits from 0 to 9.
[[:<:]] It matches the beginning of words.
[[:>:]] It matches the end of words.

[:class:] It is used to match a character class, i.e. [:alpha:] matches letters, [:space:] match es
white space, [:punct:] matches punctuations and [:upper:] for upper-class letters.
expression:

Let us understand the regular expressions using practical examples given below:

Suppose we have a table named student_info that contains the following data. We will demonstrate
various examples based on this table data.
DON BOSCO COLLEGE DHARMAPURI

If we want to search for students whose name start with "A or B", we can use a regular expression
together with the meta-characters as follows:

mysql> SELECT * FROM student_info WHERE stud_name REGEXP '^[ab]';

Executing the statement, we will get the desired result. See the below output:

If we want to get the student information whose name ends with k, we can use 'k$' meta-character to
match the end of a string as follows:

mysql> SELECT * FROM student_info WHERE stud_name REGEXP 'k$';

Executing the statement, we will get the desired result. See the below output:
DON BOSCO COLLEGE DHARMAPURI
If we want to get the student information whose name contains exactly six characters, we can do this
using '^' and '$ meta-characters. These characters match the beginning and end of the student name
and repeat {6} times of any character '.' in-between as shown in the following statement:

mysql> SELECT * FROM student_info WHERE stud_name REGEXP '^.{6}$';

Executing the statement, we will get the desired result. See the below output:

If we want to get the student info whose subjects contains 'i' characters, we can do this by using the
below query:

mysql> SELECT * FROM student_info WHERE subject REGEXP 'i';

Executing the statement, we will get the desired result. See the below output:

Regular Expression Functions and


Operators

The following are the list of regular functions and operators in MySQL:

Name Descriptions

NOT_REGEXP It is the negation of a REGEXP operator.


DON BOSCO COLLEGE DHARMAPURI

REGEXP This operator represents whether the string matches regular expression
or not.
RLIKE This operator represents whether the string matches regular expression
or not.
REGEXP_INSTR() It is a function that gives a result when the starting index of substring
matches a regular expression.

REGEXP_LIKE() This function represents whether the string matches regular expression
or not.
REGEXP_REPLACE() It gives results by replacing substrings that match the regular
expression.
REGEXP_SUBSTRING() This function return substring that matches a regular expression.

Let's see all of them in detail.

REGEXP, RLIKE, & REGEXP_LIKE()

Although these functions and operators return the same result, REGEXP_LIKE() gives us more
functionality with the optional parameters. We can use them as follows:

expression REGEXP pattern


expression RLIKE pattern
REGEXP(expression, pattern[, match_type])

These statements give output whether string expression matches regular expression pattern or not. We
will get 1 if an expression matches the pattern. Otherwise, they return 0. The below examples explain it
more clearly.

In the below image, the first statement returns '1' because 'B' is in the range A-Z. The second statement
limited the range of the pattern to B-Z. So 'A' will not match any character within the range, and MySQL
returns 0. Here we have used the alias match_ and not_match_ so that the returned column will be more
understandable.
DON BOSCO COLLEGE DHARMAPURI

REGEXP_LIKE() Parameter

The following are the five possible parameters to modify the function output:

c: It represents a case-sensitive matching.

i: It represents a case-insensitive matching.

m: It represents a multiple-line mode that allows line terminators within the string. By default, this
function matches line terminators at the start and end of the string.

n: It is used to modify the . (dot) character to match line terminators.

u: It represents Unix-only line endings.

Example

In this example, we have added the 'c' and 'i' as an optional parameter, which invokes case- sensitive
and case-insensitive matching. The first query gives the output 0 because 'a' is in the range 'a-z', but not
in the range of capital letters A-Z. The second query gives the output 1 because of case- insensitive
features.
DON BOSCO COLLEGE DHARMAPURI

NOT REGEXP & NOT RLIKE

They are regular expression operators that compare the specified pattern and return the result, which does
not match the patterns. These operators return 1 if no match is found. Otherwise, they return 0. We can
use these functions as follows:

SELECT (expr NOT REGEXP pat);


OR
SELECT (expr NOT RLIKE pat);

Example

The below statement returns 0 because 'a' is found in the given range.

mysql> SELECT ('a' NOT REGEXP '[a-z]') AS not_match;

Here is the output:

REGEXP_INSTR()
DON BOSCO COLLEGE DHARMAPURI
It is a function that gives a result when the starting index of substring expression matches the pattern. It
returns 0 if there is no match found. If either expression or pattern is NULL, it returns NULL. Here
indexing starts at 1.

REGEXP_INSTR(expr, pat[, pos[, occurrence[, return_option[, match_type]]]])

This function uses various optional parameters that are pos, occurrence, return_option, match_type, etc.

Example

Suppose we want to get the index position of substring 'a' within expr (a b c d e f a). The first query returns
1 because we have not set any optional parameters, which is the string's first index. The second query
returns 13 because we have modified the query with optional parameter occurrence.

SELECT REGEXP_INSTR('a b c d e f a', 'a', 1, 1, 0) AS start_index_;


SELECT REGEXP_INSTR('a b c d e f a', 'a', 1, 2, 0) AS a_index_2;

REGEXP_REPLACE()

This function replaces the specified string character by matching characters and then returns the resulting
string. If any expression, pattern, or replaceable string is not found, it will return NULL. This function
can be used as follows:

SELECT REGEXP_REPLACE ('expression', 'character', 'replace_character');

The replace character uses the optional parameters such as pos, occurrence, and match_type.

Example

This statement replaces the 'tutorials' pattern with the 'javat' pattern.
DON BOSCO COLLEGE DHARMAPURI

mysql> SELECT REGEXP_REPLACE ('tutorialspoint', 'tutorials', 'javat') AS replaced;

Here is the output:

REGEXP_SUBSTRING()

This function returns the substring of an expression that matches the specified pattern. If the expression
or specified pattern or even no match is found, it returns NULL. This function can be used as follows:

SELECT REGEXP_SUBSTR ('expr', 'pattern');

The pattern uses the optional parameters such as pos, occurrence, and match_type.

Example

This statement returns the 'point' pattern, which is the third occurrence of the given range.

mysql> SELECT REGEXP_SUBSTR ('java t point', '[a-z]+', 2, 3) AS substring;

Here is the output:

DATABASE ADAPTER:

Python offers database adapters through its modules that allow access to major databases such as MySQL,
PostgreSQL, SQL Server, and SQLite. Furthermore, all of these modules rely on Python's database API
(DB-API) for managing databases.
DON BOSCO COLLEGE DHARMAPURI
Database adapter

Atualizado pela última vez: 2023-01-26


Out-of-the-box, virtual member manager provides a default database profile repository (wimDB), that
supports all common virtual member manager supported profile repository features.
Note: The database user who configures the repository needs to have database administrator privileges
such as permissions to create tables in the database schema and to access the data in the database tables.
The database repository is designed using relational database. The database adapter is a bridge between
the virtual member manager profile and schema managers and the underlying database. The adapter looks
up the data source and updates or queries the database using SQL queries.
The database repository supports all entity types that are predefined in the virtual member manager model
schema definition, such as: Person, Group, OrgContainer, and PersonAccount. The database adapter can
also support any user-defined entity types that extend from the virtual member manager standard schema.
It creates the user-defined entities in the database during runtime.
The database repository supports predefined property definitions that are consistent with the virtual
member manager schema, as well as dynamically defined new properties during runtime.
A database repository property definition extends the virtual member manager schema property
definition. It contains:
name
Specifies the name of the property. This is a required property.
data type
Specifies a data type. String, Integer, Long, Double, Timestamp, Base64Binary, Identifier and Object are
the default supported data types. If a property has user-defined data type, set Objects as data type and set
the user-defined data type class name in the DBPROP table “classname” column. For example, to
support a Boolean data type, set the “type_id” column OBJECT and set the “classname” column to
java.lang.Boolean. This is a required property.
Note: Supported data types are defined in the SchemaConstant.java file.
applicable for entity types
Specifies a list of entity types for which this property is applicable, for example, PersonAccount;Group.
This is a required property.
required for entity types
Specifies a list of entity types that require this property value to be set during the entity creation. This
is an optional property.
multiValued
Specifies whether the database repository can store multiple values for a property. By default,
multiValued is true. This is an optional parameter.
metaName
Specifies the name of metadata. By default, it is set to DEFAULT, which means that there is no
associated metadata. This is an optional parameter.
readOnly
Specifies if a property is read only. By default, it is false. This is an optional parameter.
caseExactMatch
Specifies if a property is case sensitive during the search. By default, it is set to true. This is an
optional parameter.
valueLength
Specifies he maximum length of a property if it is String type. The default value is 1500. For other
data types, this property is ignored. This is an optional parameter.
isComposite
Specifies if a property is a composite property. By default, it is false. This is an optional parameter.
classname
DON BOSCO COLLEGE DHARMAPURI
Specifies user-defined data type. If a user-defined data type exists, the value of data type needs to be
set to Object. This is an optional parameter.
description
Specifies the description of the property. This is an optional parameter.
application ID
Specifies the ID of the application that uses this property. By default, the parameter is set to
com.ibm.websphere.wim. This is an optional parameter.
Note: To predefine a database repository property before the virtual member manager is running, set the
property definitions in the wimdbpropreties.xml file. The wimdbproperty.xsd. file is the schema file for
the wimdbproperties.xml file.

• Configuring the database adapter


The database adapter is configured using the wsadmin commands.

PART - A(1 MARKS)

1) What is the full form of SQL?

Structured Query List

Structure Query Language

Sample Query Language

None of these.

Hide Answer Workspace

Answer: B

Explanation: SQL is a programming language used for managing data in a relational database
management system. It is pronounced as See-Qwell.

2) Which of the following is not a valid SQL type?

FLOAT

NUMERIC

DECIMAL

CHARACTER

Hide Answer Workspace

Answer: C
DON BOSCO COLLEGE DHARMAPURI
Explanation:

DECIMAL is not a valid SQL type because it is nothing but numeric only in SQL.

NUMERIC has fixed precision, and scale numbers range from -10^38+1 to 10^38-1.

FLOAT has floating precision number ranges from -1.79E + 308 to 1.79E + 308.

CHARACTER is a fixed-width character string data type that can be up to 8000 characters.

3) Which of the following is not a DDL command?

TRUNCATE

ALTER

CREATE

UPDATE

Hide Answer Workspace

Answer: D

Explanation: DDL commands are used to define the structure of the database, table, schemas, etc.
It enables us to perform the operations like CREATE, DROP, ALTER, RENAME, and TRUNCATE
schema objects.

An UPDATE command is used for managing the data stored in a database. It is an example of a
DML command that also includes the INSERT and DELETE commands.

4) Which of the following are TCL commands?

COMMIT and ROLLBACK

UPDATE and TRUNCATE

SELECT and INSERT

GRANT and REVOKE

Show Answer Workspace

5) Which statement is used to delete all rows in a table without having the action logged?
DON BOSCO COLLEGE DHARMAPURI
DELETE

REMOVE

DROP

TRUNCATE

Hide Answer Workspace

Answer: D

Explanation: TRUNCATE statement removes all rows in a table without logging the individual row
deletions. It uses fewer system and transaction log resources, which makes its execution fast. This
statement is similar to the DELETE statement without the WHERE clause.

6) SQL Views are also known as

Simple tables

Virtual tables

Complex tables

Actual Tables

Hide Answer Workspace

Answer: B

Explanation: A view is also known as a virtual table because it contains rows and columns similar
to a real table. It shows the table interface but cannot be stored in a database.

7) How many Primary keys can have in a table?

Only 1

Only 2

Depends on no of Columns

Depends on DBA

Hide Answer Workspace


DON BOSCO COLLEGE DHARMAPURI
Answer: A

Explanation: The primary key can consist of a single or combination of the field that uniquely
identifies each record in a table. It cannot be null or empty. A table may have duplicate columns, but
it can contain only one primary key.

8) Which datatype can store unstructured data in a column?

CHAR

RAW

NUMERIC

VARCHAR

Hide Answer Workspace

Answer: B

Explanation:

RAW datatype stores variable-length binary data that can be queried and inserted but not
manipulated. Its maximum length is 32767 bytes.

CHAR stores character data in a fixed length.

NUMERIC stores numeric values only.

VARCHAR stores variable string data in a fixed length. Its maximum length is 4000 bytes.

9) Which of the following is not Constraint in SQL?

Primary Key

Not Null

Check

Union

Hide Answer Workspace

Answer: D
DON BOSCO COLLEGE DHARMAPURI
Explanation:

Constraint specifies the rule to allow or restrict what data will be stored in a table. The PRIMARY
KEY, NOT NULL, and CHECK are the constraints that specify rules for data insertion.

UNION is an operator that combines two or more results from multiple SELECT queries into a single
result set.

10) Which of the following is not a valid aggregate function?

COUNT

COMPUTE

SUM

MAX

Hide Answer Workspace

Answer: B

Explanation: Aggregate function is used to perform calculations on multiple values and return the
output in a single value. It is mostly used with the SELECT statement. COUNT, SUM, and MAX are
all aggregate functions.

COMPUTE is not an aggregate function. It is used to generate totals as an additional column at the
end of the result set.

11) Which data manipulation command is used to combines the records from one or more tables?

SELECT

PROJECT

JOIN

PRODUCT

Hide Answer Workspace

Answer: C

Explanation: JOIN command is used with the SELECT statement to retrieve data from multiple
tables. It must be needed whenever we want to fetch records from two or more tables.
DON BOSCO COLLEGE DHARMAPURI

12) Which operator is used to compare a value to a specified list of values?

ANY

BETWEEN

ALL

IN

Hide Answer Workspace

Answer: D

Explanation: The IN operator easily tests the expression if it matches any value in a specified list
of values. It reduces the use of multiple OR conditions.

The WHERE or HAVING clause uses the ANY and ALL operators. ANY gives the result when any
subquery value matches the specified condition. The ALL give the result when all subquery values
match the specified condition.

The BETWEEN operator selects values only in the given range.

13) What operator tests column for absence of data

NOT Operator

Exists Operator

IS NULL Operator

None of the above

Hide Answer Workspace

Answer: C

Explanation: The IS NULL operator is used to testing the empty values in the table's column. It
returns true if column values are NULL.

The NOT operator gives the result only when the specified condition is not true.

The EXISTS operator used in combination with a subquery, and if a subquery returns any record, this
operator returns true. Otherwise, it will return false.
DON BOSCO COLLEGE DHARMAPURI

14) In which of the following cases a DML statement is not executed?

When existing rows are modified.

When a table is deleted.

When some rows are deleted.

All of the above

Hide Answer Workspace

Answer: B

Explanation: The DML statement is used to access and manipulate the data in an existing table.
Therefore, it cannot be used in table deletion.

15) If we have not specified ASC or DESC after a SQL ORDER BY clause, the following is used
by default

DESC

ASC

There is no default value

None of the mentioned

Hide Answer Workspace

Answer: B

Explanation: If we have not specified any sorting with the ORDER BY clause, SQL always uses
the ASC as a default sorting order. SQL treats Null as the lowest possible values while sorting.

16) Which of the following statement is true?

TRUNCATE free the table space while DELETE does not.

Both TRUNCATE and DELETE statements free the table's space.

Both TRUNCATE and DELETE statement does not free the table's space.
DON BOSCO COLLEGE DHARMAPURI
DELETE free the table space while TRUNCATE does not.

Hide Answer Workspace

Answer: A

Explanation:

The TRUNCATE statement in SQL removes all data from the table and free the table's space.

SQL's DELETE statement removes all data from the table but does not free the table's space.

17) What is returned by INSTR ('JAVAT POINT', 'P')?

POINT

JAVAT

Hide Answer Workspace

Answer: B

Explanation: The INSTR function searches the string for substring and returns the numeric value
of the specified character's first occurrence.

18) A command that lets you change one or more field in a table is:

INSERT

MODIFY

LOOK-UP

All of the above

Hide Answer Workspace

Answer: B

Explanation: The modify command is used to change one or more columns in the existing table. It
is generally used with ALTER TABLE statement as follows.
DON BOSCO COLLEGE DHARMAPURI
LTER TABLE table_name MODIFY column_name column_type;

19) Which of the following is also called an INNER JOIN?

SELF JOIN

EQUI JOIN

NON-EQUI JOIN

None of the above

Hide Answer Workspace

Answer: B

Explanation: The INNER JOIN returns data from the two or more tables that match the specified
condition and hides other records. EQUI JOIN is similar to INNER JOIN that returns records for
equality or matching column(s) values of the relative tables.

NON-EQUI JOIN is returned those records that are not matching in the relative tables.

SELF JOIN returns records from the tables by joining itself.

20) Which of the following is true about the HAVING clause?

Similar to the WHERE clause but is used for columns rather than groups.

Similar to WHERE clause but is used for rows rather than columns.

Similar to WHERE clause but is used for groups rather than rows.

Acts exactly like a WHERE clause.

Hide Answer Workspace

Answer: C

Explanation: The HAVING clause is always used with the GROUP BY clause and returns the rows
where the condition is TRUE.

21) clause creates temporary relation for the query on which it is defined.

WITH
DON BOSCO COLLEGE DHARMAPURI
FROM

WHERE

SELECT

Hide Answer Workspace

Answer: A

Explanation: The WITH clause in SQL allows us to provide a sub-query block, a name that can be
referenced in several places within the main query. It is used for defining a temporary relation whose
definition is available by the query in which the WITH clause is associated.

22) The SQL statement:

SELECT ROUND (65.726, -1) FROM DUAL;

Prints:

is illegal

garbage

726

70

Hide Answer Workspace

Answer: D

Explanation: Here, the ROUND() function statement will produce the rounded result of the given
number 65.726 from the left of decimal point up to 1.

23) Which of the following is true about the SQL AS clause?

The AS clause in SQL is used to change the column name in the output or assign a name to a
derived column.

The SQL AS clause can only be used with the JOIN clause.

The AS clause in SQL is used to defines a search condition.


DON BOSCO COLLEGE DHARMAPURI
All of the mentioned

Hide Answer Workspace

Answer: A

Explanation: SQL AS clauses are defined for columns and tables to give an alias name. Basically,
aliases are created to increase the readability of the query and column headings in the output.

24) command makes the updates performed by the transaction permanent in the
database?

ROLLBACK

COMMIT

TRUNCATE

DELETE

Hide Answer Workspace

Answer: B

Explanation:

The COMMIT statement is a transactional command used to end the current transaction and make
all changes performed in the transaction permanent.

The ROLLBACK statement is a transactional command used to back out or cancels the current
transaction changes and restores changed data in its previous state.

TRUNCATE and DELETE are not transactional commands.

25) How can you change "Thomas" into "Michel" in the "LastName" column in the Users table?

UPDATE User SET LastName = 'Thomas' INTO LastName = 'Michel'

MODIFY Users SET LastName = 'Michel' WHERE LastName = 'Thomas'

MODIFY Users SET LastName = 'Thomas' INTO LastName = 'Michel'

UPDATE Users SET LastName = 'Michel' WHERE LastName = 'Thomas'

Hide Answer Workspace


DON BOSCO COLLEGE DHARMAPURI
Answer: D

Explanation: The UPDATE statement is used for modifying the table data by using the SET and
WHERE clause. The SET clause is used to change the values of the column specified in the WHERE
clause. See the below syntax:

UPDATE table SET column1 = expression1, column2 = expression2,... WHERE conditions

26) Which command is used to change the definition of a table in SQL?

CREATE

UPDATE

ALTER

SELECT

Hide Answer Workspace

Answer: C

Explanation: The ALTER statement is used to change our table's definition, such as table name,
column name, column constraint, etc. It also allows us to add or delete an existing column in a table.
This statement must be used with ADD, DROP, and MODIFY clauses according to the situation.

27) Which type of JOIN is used to returns rows that do not have matching values?

Natural JOIN

Outer JOIN

EQUI JOIN

All of the above

Hide Answer Workspace

Answer: B

Explanation:

OUTER JOIN is the only join that returned the unmatched rows in one or both tables. It can be
classified into the following types:

LEFT JOIN that shows only the unmatched rows from the left table.
DON BOSCO COLLEGE DHARMAPURI
RIGHT JOIN that shows only the unmatched rows from the right table.

FULL OUTER JOIN that shows the unmatched rows from both tables.

EQUI JOIN shows records for equality or matching column(s) values of the relative tables.

A Natural join can only be performed if at least one common attribute exists between two relations
(the attributes should be the same name and domain).

28) A CASE SQL statement is ?

A way to establish a loop in SQL.

A way to establish an IF-THEN-ELSE in SQL

A way to establish a data definition in SQL

All of the above.

Hide Answer Workspace

Answer: B

Explanation: A CASE statement is one of the control flow function that allows us to write an if- else
or if-then-else logic in a SQL query. This expression validates various conditions and shows the
output when the first condition is true, and stops traversing. If any condition is not true, it executes
the else block. It shows a null value if the else block is not found.

29) Which statement is true regarding routines and triggers?

Both run automatically.

Both are stored in the database.

Both consist of procedural code.

Both have to be called to operate.

Hide Answer Workspace

Answer: C

Explanation:
DON BOSCO COLLEGE DHARMAPURI
Routines, also known as subroutines, are the group of multiple commands that can be called whenever
required.

Triggers are a special type of stored procedure containing a set of SQL statements that will be fired
automatically whenever any database event occurs. It always resides in the system catalog.

So option C is the correct choice.

30) Which statement is true regarding procedures?

They include procedural and SQL statements.

They work similarly to the functions.

It does not need unique names.

It cannot be created with SQL statements.

Hide Answer Workspace

Answer: A

Explanation: A procedure is a prepared SQL code that can be saved in the system and reused
whenever needed. It can return one or more values through parameters. So option A is the correct
choice.

31) Which of the following is the basic approaches for joining tables?

Union JOIN

Natural JOIN

Subqueries

All of the above

Hide Answer Workspace

Answer: D

Explanation:

We already know that Union and Natural are the approaches for joining two or more tables.
DON BOSCO COLLEGE DHARMAPURI
A subquery is a query nested into another SQL query. It can be embedded with SELECT, INSERT,
UPDATE or DELETE statement. A subquery is known as the inner query. In many cases, we can use
the subquery instead of a JOIN. Therefore, option D is the correct choice.

32) Why we need to create an index if the primary key is already present in a table?

Index improves the speed of data retrieval operations on a table.

Indexes are special lookup tables that will be used by the database search engine.

Indexes are synonyms of a column in a table.

All of the above

Hide Answer Workspace

Answer: A

Explanation: When we define a primary key in a table, the Database Engine enforces the data's
uniqueness by creating a unique index for those columns. This indexing process improves data
retrieval when the primary key is used in queries. Therefore, we need to create an index if a primary
key is already present in a table.

33) Group of operations that form a single logical unit of work is known as

View

Network

Unit

Transaction

Hide Answer Workspace

Answer: D

Explanation: A transaction is a sequential group of statements such as select, insert, update or delete
to perform as one single logical unit of work that can be committed or rolled back

34) Shared locks are applied while performing

Read operations
DON BOSCO COLLEGE DHARMAPURI
Write operations

A & B both

None of the above

Hide Answer Workspace

Answer: A

Explanation: A shared lock can only be applied while reading or changing in data is performed. It
is also known as the READ lock. Therefore, option A is the right choice.

35) Sequence can generate

Numeric value

Alphanumeric value

A & B both

None of the above

Hide Answer Workspace

Answer: C

Explanation: A sequence is an arrangement of integers that generates unique values (numeric or


alphanumeric) in ascending order on specific demand.

36) A sequence in SQL can generate a maximum number:

39 digits

38 digits

40 digits

37 digits

Hide Answer Workspace

Answer: B

Explanation: The number generated using a sequence can have a maximum of 38 digits.
DON BOSCO COLLEGE
DHARMAPURI

37) Which of the following is the correct order of a SQL statement?

SELECT, GROUP BY, WHERE,

HAVING SELECT, WHERE,

GROUP BY, HAVING SELECT,

HAVING, WHERE, GROUP BY

SELECT, WHERE, HAVING,

GROUP BYANS: B

PART - B (5 MARKS)

1. what is Database and explain different types of databases.


2. Explain about basics of databases
3. What is sql and mysql? Differentiate it?
4. Explain that how to install mysql? How it will work.
5. Explain special symbol and characteristics of sql databases.
PART - C (10 MARKS)
1. Fetch data from sql databases by using different student details.
2. Explain about SQL, mySQL, DBMS and RDBMS?
3. Explain what is REs and python?
DON BOSCO COLLEGE
DHARMAPURI

You might also like