Python
Python
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:
❖ 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:
❖ 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.
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:
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 :
Output:
125
678
# 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.
# 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.
# display
print("Before declare: ", Number)
Output:
Before declare: 100
After re-declare: 120.3
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:
• 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..
Some rules and certain symbols are used with regard to statements 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
• 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.
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.
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.
Output
Hello World
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
• 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
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.
Output
example of True, False, and, or, not keywords
True
True
True
Example 2: Example of a break, continue keywords and identifier.
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
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)
• 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).
• 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:
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.
There are different types of data types in Python. Some built-in Python data types are −
Integers, floating-point, and complex numbers fall under the Python numbers category. They are
defined as int, float, and complex classes in Python.
• 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.
• 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
• 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.
• 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.
• 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.
• 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 = 20 int
x = 20.5 float
x = 1j complex
x = range(6) range
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
Multiplication: multiplies
* x*y
two operands
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
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
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
• Python Bitwise operators act on bits and perform bit-by-bit operations. These are used
to operate on binary numbers.
Operator Description Syntax
| Bitwise OR x|y
~ Bitwise NOT ~x
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
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
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
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
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
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
• 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
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.
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.
Output
<type 'int'>
<type 'long'>
DON BOSCO COLLEGE DHARMAPURI
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.
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
# 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.
# Driver code
if __name__=='__main__':
booln()
Output:
True
False
True
float.hex() : Returns a representation of a floating-point number as a hexadecimal string.
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.
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
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
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
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
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
// (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 -
Output:
Now we compile the above code in Python, and after successful compilation, we run it. Then the
output is given below -
• 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.
variable_name = value
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
>>> intgr = 3
>>> type(intgr)
<class 'int'>
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
# 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)
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
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.
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.
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.
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.
Output:
Initial String:
Hello, I'm a Geek
Updating character at 2nd Index:
DON BOSCO COLLEGE DHARMAPURI
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.
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.
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.
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.
• 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 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.
• 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.
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:
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
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 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
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:
Output
['Mathematics', 'chemistry', 10087, 1997, 2000]
DON BOSCO COLLEGE DHARMAPURI
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:
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:
Output
2.5
Example 2:
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
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 :
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.
Output:
('Geeks', 'for', 'Geeks')
Create a Tuple With One Item
provides us with another way to create a Tuple.
DON BOSCO COLLEGE DHARMAPURI
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.
Output :
('dsa', 'developement', 'deep learning')
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
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.
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.
Syntax:
In the above dictionary Dict, The keys Name and Age are the strings which comes under the category of an immutable
object.
Code
<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
Code
# 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:
{}
Code
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.
Note: The value is updated if the key-value pair is already present in the dictionary. Otherwise, the dictionary's newly added keys.
Example - 1:
Code
Output
Empty Dictionary:
{}
Code
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.
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.
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
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:
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.
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.,
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.
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.
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:
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
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.
Method len(d)
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()).
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()
Method keys()
Method values()
Method update(elem)
Example Code
myDict.update({'fifty' : 50})
print(myDict)
Output
The most straightforward form contrasts a subject value with one or more regular expressions:
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.
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.
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.
if expression:
statement
Example 1
Output:
Output:
Enter a: 100
Enter b: 120
Enter c: 130
From the above three numbers given c is largest
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.
if condition:
#block of statements
else:
#another block of statements (else-block)
Output:
Output:
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.
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
Output:
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.
2 For loop This type of loop executes a code block multiple times and
abbreviates the code that manages the loop variable.
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.
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.
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
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
Output:
The list of squares is [16, 4, 36, 49, 9, 25, 64, 100, 36, 1, 81, 4]
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.
Code
# 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
Syntax:
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)
Output:
3
9
3
9
7
These are the odd numbers present in the tuple
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.
Code
print(range(15))
print(list(range(15)))
print(list(range(4, 9)))
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
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.
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
Output:
Python Loops
Python Loops
Python Loops
Python 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
Output:
Python Loops
Python Loops
Python Loops
Python Loops
Code block inside the else statement
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
Now we will discuss the loop control statements in detail. We will see an example of each
control statement.
Continue Statement
Code
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
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
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.
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.
if <conditional expression>
Statement
else
Statement
Code
a, b = 6, 5
Output:
a is greater than b
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
a, b = 6, 5
Output:
a is greater than b
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.
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
a, b = 9, 9
print(code)
Output:
a is greater than b
DON BOSCO COLLEGE DHARMAPURI
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
a, b = 9, 9
print(code)
Output:
a is equal to b
Code
A = 100
B = 200
C = 300
if B % C == 0:
if A % C == 0:
print("C is a common factor of A and B")
Output:
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
print(next(myit))
print(next(myit))
print(next(myit))
Even strings are iterable objects, and can return an iterator:
Example
print(next(myit))
print(next(myit))
print(next(myit))
print(next(myit))
print(next(myit))
print(next(myit))
Looping Through an Iterator
Example
for x in mytuple:
print(x)
Example
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
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
class MyNumbers:
def iter (self):
self.a = 1
return self
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
Return
# 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.
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.
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 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.
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 -
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
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
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.
Syntax
fileobject.close()
Here we write the program code for the closing method in Python. The code is given below -#
if fileptr:
print("The existing file is opened successfully in Python")
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.
try:
fileptr = open("file.txt")
# perform file operations
finally:
fileptr.close()
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 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.
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)
Here we write the program code for with statement in Python. The code is given below -
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.
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
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
Here we write the program code for write method in Python. The code is given below -
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
Here we write the program code for write method in Python. The code is given below -
Now we compile the above code in Python, and after successful compilation, we run it. Then the output
is given below -
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:
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.
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 -
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.
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 -
Here we give an example of read file using for loop. The code is given below -
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:
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 -
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()
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 -
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
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.
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 -
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
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()
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 -
#after the read operation file pointer modifies. tell() returns the location of the fileptr.
Output:
Now we compile the above code in Python, and after successful compilation, we run it. Then the output
is given below -
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 -
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
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:
<file-ptr>.seek(offset[, from)
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.
Here we give the example of how to modifying the pointer position using seek() method in Python. The
code is given below -
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:
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:
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.
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
Output:
Now we compile the above code in Python, and after successful compilation, we run it. Then the output
is given below -
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
The os module provides the remove() method which is used to remove the specified file.
Syntax:
remove(file-name)
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 -
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 -
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:
Output:
Parameter:
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.
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 -
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 -
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.
Syntax
os.getcwd()
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'
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 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
chdir("new-directory")
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'
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 -
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)
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 -
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 -
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 -
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
file.py
import subprocess
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.
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.
10 File.tell() It returns the current position of the file pointer within the
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
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:
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
Example:
fileptr = open("myfile.txt","r")
if fileptr:
print("file is opened successfully with read mode only")
Output:
fileptr = open("myfile1.txt","x")
if fileptr:
print("new file was created successfully")
Output:
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])
Output:
☞ 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
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:
☞ 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
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:
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:
☞ 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:
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
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
f = open("myfile.txt", "r")
print(f.seek(9))
print(f.read())
f.close();
Output:
myfile.txtr
False
DON BOSCO COLLEGE DHARMAPURI
True
Python program to print number of lines, words and characters in given file.
myfile.txt
Output: Case 2
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.
Example:
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
Example:
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.
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.
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 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.
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.
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.
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.
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 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.
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.
Efficient programming code can reduce the consumption of the resources and time taken by the
completion programs.
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.
Here is the program which shows the call by value in the C++.
#include<iostream.h>
#include<conio.h>
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();
}
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.
We usually will do the function overloading when we want to perform one operation, containing
different numbers or types of arguments.
# 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:
# 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
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.
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:
The accept intensity is denoted as BI(n), current accept intensity can be defined as shown below:
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
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).
13
DON BOSCO COLLEGE DHARMAPURI
19
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 -
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 -
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 -
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.
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.
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.
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.
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'.
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.
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 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.
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.
You are given a list of integers and should filter the even numbers from the list.
# 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)
Output:
24
Evens = [2, 4]
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.
Output:
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.
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
# Method 2
Output:
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 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 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:
# 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}")
Output:
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.
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.
# Importing operator
import operator
# Creating lists
my_list1 = [1, 2, 3, 4, 5]
my_list2 = ["I", "Love", "Javatpoint"]
# 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:
Here, the function argument in the reduce function is replaced with the operator functions. All the steps
are same as previous examples.
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:
# Using reduce to find the largest of all and printing the result
largest = reduce(large, num)
print(f"Largest found with method 1: {largest}")
# 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}")
# 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:
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.
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.
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.
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.
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.
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:
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.
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:
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:
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, 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.
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.
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).
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
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:
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.
class Class_Name:
attribute (variable)1
attribute (variable)2
...
attribute (variable)N
def Method_name1(self,arg1,...,argn):
def Method_name2(self):
...
def Method_nameN(self,arg1,...,argn):
Example programs:
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:
Output:
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.
The constructor
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.
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."
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.")
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.
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}"
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.
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."
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.
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.
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.
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.
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.
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.
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.
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.
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.
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 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.
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.
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.
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.
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.
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.
Example
import mysql.connector
Output:
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
Output:
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.
<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")
print(cur)
Output:
In this section of the tutorial, we will create the new database PythonDB.
We can get the list of all the databases by using the following MySQL query.
Example
import mysql.connector
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',)
Example
import mysql.connector
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.
> 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
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.
Example
import mysql.connector
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
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.
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)
except:
myconn.rollback()
print(cur.rowcount,"record inserted!")
myconn.close()
Output:
1 record inserted!
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).
Example
import mysql.connector
try:
#inserting the values into the table
cur.executemany(sql,val)
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.
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)
#getting rowid
print(cur.rowcount,"record inserted! id:",cur.lastrowid)
except:
myconn.rollback()
myconn.close()
Output:
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
try:
#Reading the Employee data
cur.execute("select * from Employee")
for x in result:
print(x);
except:
myconn.rollback()
myconn.close()
Output:
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")
Output:
The fetchone() method is used to fetch only one row from the table. The fetchone() method returns the
next row of the result-set.
Example
import mysql.connector
try:
#Reading the Employee data
cur.execute("select name, id, salary from Employee")
except:
myconn.rollback()
myconn.close()
Output:
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.
Example
import mysql.connector
try:
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
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.
import mysql.connector
try:
#Reading the Employee data
cur.execute("select name, id, salary from Employee where name like 'J%'")
print("Name id Salary");
myconn.close()
Output:
Name id Salary
John 101 25000
John 102 25000
import mysql.connector
try:
#Reading the Employee data
cur.execute("select name, id, salary from Employee where id in (101,102,103)")
print("Name id Salary");
myconn.close()
Output:
DON BOSCO COLLEGE DHARMAPURI
Name id Salary
John 101 25000
John 102 25000
David 103 2500
The ORDER BY clause is used to order the result. Consider the following example.
Example
import mysql.connector
try:
#Reading the Employee data
cur.execute("select name, id, salary from Employee order by name")
print("Name id Salary");
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
Example
import mysql.connector
try:
#Reading the Employee data
cur.execute("select name, id, salary from Employee order by name desc")
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.
Example
import mysql.connector
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.
Example
import mysql.connector
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.
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
except:
myconn.rollback()
myconn.close()
DON BOSCO COLLEGE DHARMAPURI
Output:
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.
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
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
except:
myconn.rollback()
myconn.close()
Output:
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
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:
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.
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)
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.
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.
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:
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.
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.
[: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:
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:
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:
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:
Executing the statement, we will get the desired result. See the below output:
The following are the list of regular functions and operators in MySQL:
Name Descriptions
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.
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:
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:
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.
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
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:
Example
The below statement returns 0 because 'a' is found in the given range.
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.
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.
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:
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
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:
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.
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
None of these.
Answer: B
Explanation: SQL is a programming language used for managing data in a relational database
management system. It is pronounced as See-Qwell.
FLOAT
NUMERIC
DECIMAL
CHARACTER
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.
TRUNCATE
ALTER
CREATE
UPDATE
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.
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
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.
Simple tables
Virtual tables
Complex tables
Actual Tables
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.
Only 1
Only 2
Depends on no of Columns
Depends on DBA
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.
CHAR
RAW
NUMERIC
VARCHAR
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.
VARCHAR stores variable string data in a fixed length. Its maximum length is 4000 bytes.
Primary Key
Not Null
Check
Union
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.
COUNT
COMPUTE
SUM
MAX
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
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
ANY
BETWEEN
ALL
IN
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.
NOT Operator
Exists Operator
IS NULL Operator
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
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
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.
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.
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.
POINT
JAVAT
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
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;
SELF JOIN
EQUI JOIN
NON-EQUI JOIN
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.
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.
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
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.
Prints:
is illegal
garbage
726
70
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.
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.
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
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.
25) How can you change "Thomas" into "Michel" in the "LastName" column in the Users table?
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:
CREATE
UPDATE
ALTER
SELECT
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
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).
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.
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.
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
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?
Indexes are special lookup tables that will be used by the database search engine.
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
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
Read operations
DON BOSCO COLLEGE DHARMAPURI
Write operations
A & B both
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.
Numeric value
Alphanumeric value
A & B both
Answer: C
39 digits
38 digits
40 digits
37 digits
Answer: B
Explanation: The number generated using a sequence can have a maximum of 38 digits.
DON BOSCO COLLEGE
DHARMAPURI
GROUP BYANS: B
PART - B (5 MARKS)