0% found this document useful (0 votes)
7 views166 pages

Python Programming Notes-III Cs

Uploaded by

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

Python Programming Notes-III Cs

Uploaded by

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

Programming in Python

UNIT-I

Python – origins – features – variable 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.

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.

UNIT-III

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 built-in methods – File built-in
attributes – Standard files – command line arguments.

UNIT-IV

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.

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.

Learning Resources

Text Books

Title of Book Publisher Year of Publication 1 Wesley J. Chun Core Python Programming
Pearson Education Publication 2012

PYTHON NOTES Page 1


Reference Books

1. Wesley J. Chun Core Python Application Programming Pearson Education Publication 2015

2. Eric Matthes Python crash course William pollock 2016

3. Zed Shaw Learn Python the hard way Addition Wesley 2017

4. Mark Lutz Python pocket reference O’Reilly Media 2014 Pedagogy

PYTHON NOTES Page 2


UNIT-I
1.1 PYTHON
Introduction

• Python is a high-level, interpreted, interactive and object-oriented scripting language.

Python is Interpreted

• Python is processed at runtime by the interpreter.


• No need to compile the program before executing it.
• This is similar to PERL and PHP.

Python is Interactive

• We can interact with the interpreter directly to write the programs.

Python is Object-Oriented

• Python supports Object-Oriented style.


• It encapsulates code within objects.

Python is a Beginner's Language

• Python is a great language for the beginner level programmers.


• It supports the development of a wide range of applications from simple text processing
to WWW browsers to games.

History of python

• Python was developed by Guido van Rossum at National Research Institute for
Mathematics and Computer Science in Netherlands in 1990.
• Rossum wanted the name of his new language to be short, unique and mysterious.
• Inspired by Monty Python‘s Flying Circus, a BBC comedy series, he named the language
Python.
• Python became a popular programming language.
• It is widely used in both industry and academia because of its simple, concise and
extensive support of libraries.
• It is a general purpose, interpreted and object-oriented programming language.

PYTHON NOTES Page 3


• Python source code is available under General Public License (GPL) and maintained by a
core development team.
• Python 1.0 was released in November 1994. In 2000, Python 2.0 was released.
• Python 2.7.11 is the latest edition of Python 2.
• Python 3.0 was released in 2008. Python 3 is not backward compatible with Python 2.
• Python 3.5.1 is the latest version of Python 3.

1.2 Python Features:


Python is a feature rich high-level, interpreted, interactive and object-oriented scripting language.
This tutorial will list down some of the important features of Python:

Following section will explain these features in more detail:

➢ Python is Easy to Learn

• This is one of the most important reasons for the popularity of Python. Python has a
limited set of keywords.
• Its features such as simple syntax, usage of indentation to avoid clutter of curly
brackets and dynamic typing that doesn't necessitate prior declaration of variable help
a beginner to learn Python quickly and easily.

➢ Python is Interpreter Based


• Python is an interpreter based language. The interpreter takes one instruction from
the source code at a time, translates it into machine code and executes it.

PYTHON NOTES Page 4


• Instructions before the first occurrence of error are executed. With this feature, it is
easier to debug the program and thus proves useful for the beginner level
programmer to gain confidence gradually.
• Python therefore is a beginner-friendly language.

➢ Python is Interactive
• Standard Python distribution comes with an interactive shell that works on the
principle of REPL (Read – Evaluate – Print – Loop).
• The shell presents a Python prompt >>>. You can type any valid Python expression
and press Enter. Python interpreter immediately returns the response and the prompt
comes back to read the next expression.

>>>2*3+1

>>>print ("Hello World")

Hello World

• The interactive mode is especially useful to get familiar with a library and test out its
functionality. You can try out small code snippets in interactive mode before writing a
program.
➢ Python is Multi-Paradigm
• Python is a completely object-oriented language. Everything in a Python program is an
object. However, Python conveniently encapsulates its object orientation to be used as an
imperative or procedural language – such as C.
• Python also provides certain functionality that resembles functional programming.
• Moreover, certain third-party tools have been developed to support other programming
paradigms such as aspect-oriented and logic programming.
➢ Python's Standard Library
• Even though it has a very few keywords (only Thirty Five), Python software is
distributed with a standard library made of large number of modules and packages.
• Thus Python has out of box support for programming needs such as serialization, data
compression, internet data handling, and many more. Python is known for its batteries
included approach.
➢ Python is Open Source and Cross Platform
• You can download pre-compiled binaries for various operating system
platforms. In addition, the source code is also freely available, which is why it
comes under open source category.

PYTHON NOTES Page 5


• Python software (along with the documentation) is distributed under Python
Software Foundation License.
• It is a BSD style permissive software license and compatible to GNU GPL
(General Public License).
• Python is a cross-platform language. Pre-compiled binaries are available for use
on various operating system platforms such as Windows, Linux, Mac OS, and
AndroidOS. The reference implementation of Python is called CPython and is
written in C. You can download the source code and compile it for your OS
platform..
➢ Python for GUI Applications
• Python's standard distribution has an excellent graphics library called TKinter. It
is a Python port for the vastly popular GUI toolkit called TCL/Tk. You can build
attractive user-friendly GUI applications in Python.
• GUI toolkits are generally written in C/C++. Many of them have been ported to
Python. Examples are PyQt, WxWidgets, and PySimpleGUI etc.
➢ Python's Database Connectivity
• Almost any type of database can be used as a backend with the Python
application.
• DB-API is a set of specifications for database driver software to let Python
communicate with a relational database.
• With many third party libraries, Python can also work with NoSQL databases
such as MongoDB.
➢ Python is Extensible
• The term extensibility implies the ability to add new features or modify existing
features. As stated earlier, CPython (which is Python's reference
implementation) is written in C.
• Hence one can easily write modules/libraries in C and incorporate them in the
standard library. There are other implementations of Python such as Jython
(written in Java) and IPython (written in C#).
➢ Python's Active Developer Community
• As a result of Python's popularity and open-source nature, a large number of
Python developers often interact with online forums and conferences.
• Python Software Foundation also has a significant member base, involved in the
organization's mission to "Promote, Protect, and Advance the Python
Programming Language"
• Python also enjoys a significant institutional support. Major IT companies
Google, Microsoft, and Meta contribute immensely by preparing documentation
and other resources.

PYTHON NOTES Page 6


1.3 Variable and Assignment
A variable is a string of characters and numbers associated with a piece of information.

The assignment operator, denoted by the “=” symbol, is the operator that is used to assign
values to variables in Python. The line x=1 takes the known value, 1, and assigns that value to
the variable with name “x”.

Variable Type Data/Info


----------------------------
x int 1
y int 2

Note that the equal sign in programming is not the same as a truth statement in mathematics.
In math, the statement x = 2 declares the universal truth within the given framework, x is 2. In
programming, the statement x=2 means a known value is being associated with a variable
name, store 2 in x. Although it is perfectly valid to say 1 = x in mathematics, assignments in
Python always go left: meaning the value to the right of the equal sign is assigned to the variable
on the left of the equal sign. Therefore, 1=x will generate an error in Python. The assignment
operator is always last in the order of operations relative to mathematical, logical, and
comparison operators.

EXAMPLE: What value will y have after the following lines of code are executed?

x=1
y=x+1
x=2
y

1.4 Python Basic

While Python has become an essential language and a very useful skill for data analysts, it
requires some basic terminology to get started. If you have a limited programming background,
here are a few important terms to know:

PYTHON NOTES Page 7


Comments

Use a hashtag to leave comments, or notes, to yourself or others explaining elements of your
code. In Python, comments are ignored so they are not incorrectly included in the final product.

Keywords

Every programming language relies on certain words to convey meanings or perform specific
functions. For example, True and False are used to represent the truth value of an expression
within the Python Boolean, one of Python’s built-in data types.

Built-in Data Types

Because variables can store different types of data, it’s important to input the correct data types
while programming. Python uses several data types, including numerics, strings, Booleans, lists,
and tuples.

Loops

Loops simplify the process of repeating an action for a specific number of steps or until a
condition is met. Python presents two types of loops when code needs to be
repeated: for and while.

1.5 Statement and Syntax

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

➢ Hash mark ( # ) indicates Python comments


➢ NEWLINE ( \n ) is the standard line separator (one statement per line)
➢ Backslash ( \ ) continues a line
➢ Semicolon ( ; ) joins two statements on a line
➢ Colon ( : ) separates a header line from its suite
➢ Statements (code blocks) grouped as suites
➢ Suites delimited via indentation
➢ Python files organized as “modules”

Some rules and certain symbols are used with regard to statements in Python: Hash mark (#)
indicates Python comments. NEWLINE (\n) is the standard line separator (one statement per
line) Backslash (\) continues a line.

PYTHON NOTES Page 8


For Example

classCls:
x=3# class variable
inst=Cls()
inst.x=inst.x+1# writes inst.x as 4 leaving Cls.x as 3

1.6 Identifiers
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

PYTHON NOTES Page 9


• 1var
• 1_var
• var#1

For Example

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

# compare two operands using and operator

print(True and True)

# compare two operands using or operator

print(True or False)

# use of not operator

print(not False)

Output

Example of True, False, and, or, not keywords


True
True
True

1.7 Basic Style Guidelines


Indeed coding and applying logic is the foundation of any programming language but there’s
also another factor that every coder must keep in mind while coding and that is the coding style.
Keeping this in mind, Python maintains a strict way of order and format of scripting. Following
this sometimes mandatory and is a great help on the user’s end, to understand. Making it easy for
others to read code is always a good idea, and adopting a nice coding style helps tremendously
for that..

1. Use 4-space indentation and no tabs.


Examples:

# Aligned with opening delimiter.


grow = function_name(variable_one, variable_two,

PYTHON NOTES Page 10


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 doctoring"""
"""This is a multiline comment"""

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

The Python standard library is conservative and requires limiting lines to 79 characters.
The lines can be wrapped using parenthesis, brackets, and braces. They should be used in
preference to backslashes.
Example:

with open('/path/from/where/you/want/to/read/file') as file_one,


\open('/path/where/you/want/the/file/to/be/written', 'w') as file_two:
file_two.write(file_one.read())

4. Use of regular and updated comments are valuable to both the coders and users:

There are also various types and conditions that if followed can be of great help from
programs and users point of view. Comments should form complete sentences. If a comment is a
full sentence, its first word should be capitalized, unless it is an identifier that begins with a
lower case letter. In short comments, the period at the end can be omitted. In block comments,

PYTHON NOTES Page 11


there are more than one paragraphs and each sentence must end with a period. Block comments
and inline comments can be written followed by a single ‘#’.
Example of inline comments:

geek = geek + 1 # Increment

5. Use of trailing commas : This is not mandatory except while making a tuple.
Example:

tup = ("geek",)

5. Use Python’s default UTF-8 or ASCII encodings and not any fancy encodings, if it is
meant for international environment.

6. Use spaces around operators and after commas, but not directly inside bracketing
constructs:

a = f(1, 2) + g(3, 4)

7. Naming Conventions :

There are few naming conventions that should be followed in order to make the program
less complex and more readable. At the same time, the naming conventions in Python is a bit of
mess, but here are few conventions that can be followed easily.
There is an overriding principle that follows that the names that are visible to the user as
public parts of API should follow conventions that reflect usage rather than implementation.
Here are few other naming conventions:

A (single lowercase letter)


B (single upper case letter)
lowercase
lower_case_with_underscores
UPPERCASE
UPPER_CASE_WITH_UNDERSCORES
CapitalizedWords (or CamelCase). This is also sometimes known as StudlyCaps.
Note: While using abbreviations in CapWords, capitalize all the letters of the abbreviation. Thus
HTTPServerError is better than HttpServerError.MixedCase (differs from CapitalizedWords by
initial lowercase character!)

PYTHON NOTES Page 12


8. Characters that should not be used for identifiers : ‘l’ (lowercase letter el), ‘O’ (uppercase
letter oh), or ‘I’ (uppercase letter eye) as single character variable names as these are similar to
the numerals one and zero.

9. Don’t use non-ASCII characters in identifiers if there is only the slightest chance people
speaking a different language will read or maintain the code.

10. Name your classes and functions consistently: The convention is to use CamelCase for
classes and lower_case_with_underscores for functions and methods. Always use self as the
name for the first method argument.

11. While naming of function of methods always use self for the first argument to instance
methods and cls for the first argument to class methods.If a functions argument name matches
with reserved words then it can be written with a trailing comma.

For example

# Python program to find the

# factorial of a number provided by the user.

# change the value for a different result

num = 7

# uncomment to take input from the user

#num = int(input("Enter a number: "))

factorial = 1

# check if the number is negative, positive or zero

if num < 0:

print("Sorry, factorial does not exist for negative numbers")

elif num == 0:

print("The factorial of 0 is 1")

else:

PYTHON NOTES Page 13


for i in range(1,num + 1):

factorial = factorial*i

print("The factorial of",num,"is",factorial)

Output
The factorial of 7 is 5040

1.8 Python objects


Python is an object-oriented programming language. Everything is in Python treated as
an object, including variable, function, list, tuple, dictionary, set, etc. Every object belongs to its
class. For example - An integer variable belongs to integer class. An object is a real-life entity.
An object is the collection of various data and functions that operate on those data. An object
contains the following properties.

o State - The attributes of an object represents its state. It also reflects the properties of an
object.
o Behavior - The method of an object represents its behavior.
o Identity - Each object must be uniquely identified and allow interacting with the other
objects.
The syntax of creating a class is given below.

Syntax:

class ClassName:
#statement_suite

Creating an Object of class

The object is essential to work with the class attributes. Instantiate is a term used when we create
the object of any class, and the instance is also referred to as an object. The object is created
using the class name. The syntax is given below.

Syntax:

<object-name> = <class-name>(<arguments>)
Example –

PYTHON NOTES Page 14


class Person:
name = "John"
age = 24
def display (self):
print("Age: %d \nName: %s"%(self.age,self.name))
# Creating a emp instance of Employee class
per = Person()
per.display()
Output:
Age: 24
Name: John

1.8.1 .Python’s Core Data Types

Python’s built-in object types and some of the syntax used to code their literals that is, the
expressions that generate these objects.

Some of these types will probably seem familiar if you’ve used other languages; for instance,
numbers and strings represent numeric and textual values, respectively, and files provide an
interface for processing files stored on your computer.

Built-in objects preview

Object type Example literals/creation

Numbers 1234, 3.1415, 999L, 3+4j, Decimal

Strings 'spam', "guido's"

Lists [1, [2, 'three'], 4]

Dictionaries {'food': 'spam', 'taste': 'yum'}

PYTHON NOTES Page 15


Object type Example literals/creation

Tuples (1,'spam', 4, 'U')

Files myfile = open('eggs', 'r')

Other types Sets, types, None, Booleans

1. Numbers
Python’s core object set includes the usual suspects: integers (numbers without a
fractional part), floating-point numbers (roughly, numbers with a decimal point in them), and
more exotic types (unlimited-precision “long” integers, complex numbers with imaginary parts,
fixed-precision decimals, and sets).

Although it offers some fancier options, Python’s basic number types are, well, basic.
Numbers in Python support the normal mathematical operations. For instance, the plus sign (+)
performs addition, a star (*) is used for multiplication, and two stars (**) are used for
exponentiation

a=5

print("Type of a: ", type(a))

b = 5.0

print("\nType of b: ", type(b))

c = 2 + 4j

print("\nType of c: ", type(c))

OUTPUT

Type of a: <class 'int'>


Type of b: <class 'float'>
Type of c: <class 'complex'>

PYTHON NOTES Page 16


2. Strings
Strings are used to record textual information as well as arbitrary collections of
bytes. They are our first example of what we call a sequence in Python—that is, a
positionally ordered collection of other objects. Sequences maintain a left-to-right order
among the items they contain: their items are stored and fetched by their relative position.
Strictly speaking, strings are sequences of one-character strings; other types of sequences
include lists and tuples (covered later).

• Sequence Operations

As sequences, strings support operations that assume a positional ordering among


items. For example, if we have a four-character string, we can verify its length with the built-
in len function and fetch its components with indexing expressions.

>>>S = 'Spam'
>>>len(S)# Length
4
>>>S[0]# The first item in S, indexing by zero-based position
'S'
>>>S[1]# The second item from the left
'p'

3. Lists
The Python list object is the most general sequence provided by the language. Lists are
positionally ordered collections of arbitrarily typed objects, and they have no fixed size. They are
also mutable unlike strings; lists can be modified in-place by assignment to offsets as well as a
variety of list method calls.

Python for list


>>>L = [123, 'spam', 1.23]# A list of three different-type objects
>>>len(L)# Number of items in the list
3

4. Tuples

He tuple object (pronounced “toople” or “tuhple,” depending on who you ask) is roughly
like a list that cannot be changed—tuples are sequences, like lists, but they are immutable, like
strings. Syntactically, they are coded in parentheses instead of square brackets, and they support
arbitrary types, nesting, and the usual sequence operations.

>>>T = (1, 2, 3, 4)# A 4-item tuple


>>>len(T)# Length

PYTHON NOTES Page 17


4

>>T + (5, 6)# Concatenation


(1, 2, 3, 4, 5, 6)

>>>T[0]# Indexing, slicing, and more


1

5. Files

File objects are Python code’s main interface to external files on your computer. They are
a core type, but they’re something of an oddball there is no specific literal syntax for creating
them. Rather, to create a file object, you call the built-in open function, passing in an external
filename as a string, and a processing mode string. For example, to create an output file, you
would pass in its name and the 'w' processing mode string to write data.

>>>f = open('data.txt', 'w')# Make a new file in output mode

>>>f.write('Hello\n')# Write strings of bytes to it


>>>f.write('world\n')
>>>f.close( )# Close to flush output buffers to disk

1.9 Standard types and other built-in types:

Python has many useful built in data types. Python variables can store different types of data
and can be created dynamically, without first defining a data type.

1.9.1 Integers

Integers are one of the Python data types. An integer is a whole number, negative, positive
or zero. In Python, integer variables can be defined by simply assigning a whole number to a
variable name. We can determine data type of a variable using the type() function.

>>> a = 5
>>> type(a)
<class 'int'>
>>> b = -2
>>> type(b)
<class 'int'>
>>> z = 0

PYTHON NOTES Page 18


>>> type(z)
<class `int'>

1.9.2. Floating Point Numbers

Floating point numbers or floats are another Python data type. Floats are decimals, positive,
negative and zero. Floats can also be numbers in scientific notation which contain exponents. 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'>
>>> e = 6.02e23
>>> e
6.02e+23
>>> type(e)
<class 'float'>

To make sure a variable is a float instead of an integer even if it is a whole number, a trailing
decimal point is used. Note the difference when a decimal point comes after a whole number:

>>> g = 5 # no decimal point


>>> type(g)
<class 'int'>
>>> g = 5. # decimal point
>>> type(g)
<class 'float'>

1.9.3 Boolean

The Boolean data type is either True or False. In Python, Boolean variables are defined
by the True and False key words. Note that True and False must have an Upper Case first letter.
Using a lowercase true returns an error.

a = True

PYTHON NOTES Page 19


type(a)
<class 'bool'>
b = False
type(b)
<class 'bool'>
c = true
Traceback (most recent call last):
File "<input>", line 1, in <module>
NameError: name 'true' is not defined
d = false
Traceback (most recent call last):
File "<input>", line 1, in <module>
NameError: name 'false' is not defined

1.9.4 String

Strings are sequences of letters, numbers, spaces and symbols. In Python, strings can be
almost any length and can contain spaces. String variables are assigned in Python using
quotation marks ' '.

string = 'z'
type(string)
<class 'str'>
string = 'Engineers'
type(string)
<class 'str'>

A numbers and decimals can be defined as strings too. If a decimal number is defined
using quotes ' ', it will be saved as a string rather than as a float. This is true of whole numbers as
well. Whole numbers defined using quotes will become strings just like decimal numbers defined
using quotes.

num = '5.2'
type(num)
<class 'str'>
num = '2'
type(num)

PYTHON NOTES Page 20


<class 'str'>

1.9.5. Complex numbers

One final data type useful to engineers are complex numbers. A complex number is
defined in Python using a real component + imaginary componentj. The letter j must be used in
the imaginary component. Using the letter i will return an error. Note how imaginary numbers
can be added to integers and floats.

comp = 4 + 2j
type(comp)
<class 'complex'>
comp2 = 4 + 2i
^
SyntaxError: invalid syntax

intgr = 3
type(intgr)
<class 'int'>
comp_sum = comp + intgr
print(comp_sum)
(7+2j)
flt = 2.1
comp_sum = comp + flt
print(comp_sum)
(6.1+2j)

1.10 Internal types:

• Code
• Frame
• Traceback
• Slice
• Ellipsis
• Xrange

PYTHON NOTES Page 21


We will briefly introduce these internal types here. The general application
programmer would typically not interact with these objects directly, but we include them here for
completeness. Please refer to the source code or Python internal and online documentation for
more information.

In case you were wondering about exceptions, they are now implemented as classes. In
older versions of Python, exceptions were implemented as strings. In Particular built in types
such as int, float, list, str, tuple, set, and dict all work this way. The attributes of the types
module are the built in types each with one or more names.

1.10.1. Code Objects

Code objects are executable pieces of Python source that are byte-compiled, usually as
return values from calling the compile() built-in function. Such objects are appropriate for
execution by either exec or by the eval() built-in function.

Code objects themselves do not contain any information regarding their execution
environment, but they are at the heart of every user-defined function, all of which do contain
some execution context. (The actual byte-compiled code as a code object is one attribute
belonging to a function). Along with the code object, a function's attributes also consist of the
administrative support which a function requires, including its name, documentation string,
default arguments, and global namespace.

1.10.2. Frames

These are objects representing execution stack frames in Python. Frame objects contain all
the information the Python interpreter needs to know during a runtime execution environment.
Some of its attributes include a link to the previous stack frame, the code object (see above) that
is being executed, dictionaries for the local and global namespaces, and the current instruction.
Each function call results in a new frame object, and for each frame object, a C stack frame is
created as well. One place where you can access a frame object is in a traceback object (see
below).

1.10.3. Tracebacks

When you make an error in Python, an exception is raised. If exceptions are not caught or
“handled,” the interpreter exits with some diagnostic information similar to the output shown
below:

Traceback (innermost last):


File "<stdin>", line N?, in ???

PYTHON NOTES Page 22


ErrorName: error reason

The traceback object is just a data item that holds the stack trace information for an
exception and is created when an exception occurs. If a handler is provided for an exception, this
handler is given access to the traceback object.

1.10.4. Slice Objects

Slice objects are created when using the Python extended slice syntax. This extended
syntax allows for different types of indexing. These various types of indexing include stride
indexing, multi-dimensional indexing, and indexing using the Ellipsis type. The syntax for multi-
dimensional indexing is sequence[start1 : end1, start2 : end2], or using the
ellipsis, sequence[…, start1 : end1]. Slice objects can also be generated by the slice() built-in
function. Extended slice syntax is currently supported only in external third party modules such
as the NumPy module and JPython.

Stride indexing for sequence types allows for a third slice element that allows for “step”-like
access with a syntax of sequence[starting_index : ending_index : stride]. We will demonstrate an
example of stride indexing using JPython here:

>>> foostr = 'abcde'


>>> foostr[::-1]
'edcba'
>>> foostr[::-2]
'eca'
>>> foolist = [123, 'xba', 342.23, 'abc']
>>> foolist[::-1]
['abc', 342.23, 'xba', 123]

1.10.5. Ellipsis

Ellipsis objects are used in extended slice notations as demonstrated above. These objects
are used to represent the actual ellipses in the slice syntax (…). Like the Null object, ellipsis
objects also have a single name, Ellipsis, and has a Boolean true value at all times.

PYTHON NOTES Page 23


1.10.6. Xranges

XRange objects are created by the built-in function xrange(), a sibling of


the range() built-in function and used when memory is limited and for when range() generates an
unusually large data set.

All standard type objects can be tested for truth value and compared to objects of the same type.
Objects have inherent true or false values. Objects take a false value when they are empty, any
numeric representation of zero, or the Null object None.

The following are defined as having false values in Python:

• None
• Any numeric zero:
• 0 ([plain] integer)
• 0.0 (float)
• 0L (long integer)
• 0.0+0.0j (complex)
• "" (empty string)
• [] (empty list)
• () (empty tuple)
• {} (empty dictionary)

Any value for an object other than the those above is considered to have a true value, i.e., non-
empty, non-zero, etc. User-created class instances have a false value when their nonzero
( __nonzero__() ) or length ( __len__() ) special methods, if defined, return a zero value.

1.11 Standard types in operators:

Comparison operators are used to determine equality of two data values between members of
the same type. These comparison operators are supported for all built-in types. Comparisons
yield true or false values, based on the validity of the comparison expression. Python chooses to
interpret these values as the plain integers 0 and 1 for false and true, respectively, meaning that
each comparison will result in one of those two possible values. A list of Python's value
comparison operators is given in Table 1.

PYTHON NOTES Page 24


Table 1. Standard Type Value Comparison Operators

operator function

expr1 < expr2 expr1 is less than expr2

expr1 > expr2 expr1 is greater than expr2

expr1 <= expr2 expr1 is less than or equal to expr2

expr1 >= expr2 expr1 is greater than or equal to expr2

expr1 == expr2 expr1 is equal to expr2

expr1 != expr2 expr1 is not equal to expr2 (C-style)

expr1 <> expr2 expr1 is not equal to expr2 (ABC/Pascal-style)[a]

Note that comparisons performed are those that are appropriate for each data type. In other
words, numeric types will be compared according to numeric value in sign and magnitude,
strings will compare lexicographically, etc.

>>> 2 == 2
1
>>> 2.46 <= 8.33
1
>>> 5+4j >= 2-3j

PYTHON NOTES Page 25


1
>>> 'abc' == 'xyz'
0
>>> 'abc' > 'xyz'
0
>>> 'abc' < 'xyz'
1
>>> [3, 'abc'] == ['abc', 3]
0
>>> [3, 'abc'] == [3, 'abc']
1

Also, unlike many other languages, multiple comparisons can be made on the same line,
evaluated in left-to-right order:

>>> 3 < 4 < 7 # same as ( 3 < 4 ) and ( 4 < 7 )


1
>>> 4 > 3 == 3 # same as ( 4 > 3 ) and ( 3 == 3 )
1
>>> 4 < 3 < 5 != 2 < 7
0

The comparisons are strictly between object values, meaning that the comparisons are between
the data values and not the actual data objects themselves.

1.11.1. Object Identity Comparison

In addition to value comparisons, Python also supports the notion of directly comparing
objects themselves. Objects can be assigned to other variables (by reference). Because each
variable points to the same (shared) data object, any change effected through one variable will
change the object and hence be reflected through all references to the same object.

In order to understand this, you will have to think of variables as linking to objects now and be
less concerned with the values themselves. Let us take a look at three examples.

Example 1: foo1 and foo2 reference the same object

PYTHON NOTES Page 26


foo1 = foo2 = 4

When you look at this statement from the value point-of-view, it appears that you are
performing a multiple assignment and assigning the numeric value of 4 to both
the foo1 and foo2 variables. This is true to a certain degree, but upon lifting the covers, you will
find that a numeric object with the contents or value of 4 has been created. Then that object's
reference is assigned to both foo1 and foo2, resulting in both foo1 and foo2 aliased to the same
object. Figure 4-1 shows an object with two references.

Figure 1-1. foo1 and foo2 Reference the Same Object

Example 2: foo1 and foo2 reference the same object

foo1 = 4
foo2 = foo1

This example is very much like the first: A numeric object with value 4 is created, then assigned
to one variable. When foo2 = foo1 occurs, foo2 is directed to the same object as foo1 since
Python deals with objects by passing references. foo2 then becomes a new and additional
reference for the original value. So both foo1 and foo2 now point to the same object. The same
figure above applies here as well.

Example 3: foo1 and foo2 reference different objects

foo1 = 4
foo2 = 1 + 3

This example is different. First, a numeric object is created, then assigned to foo1. Then a
second numeric object is created, and this time assigned to foo2. Although both objects are

PYTHON NOTES Page 27


storing the exact same value, there are indeed two distinct objects in the system,
with foo1 pointing to the first, and foo2 being a reference to the second. Figure 1-2 below shows
now we have two distinct objects even though both objects have the same value.

Figure 1-2. foo1 and foo2 Reference Different Objects

Why did we choose to use boxes in our diagrams above? Well, a good way to visualize
this concept is to imagine a box (with contents inside) as an object. When a variable is assigned
an object, that creates a “label” to stick on the box, indicating a reference has been made. Each
time a new reference to the same object is made, another sticker is put on the box. When
references are abandoned, then a label is removed. A box can be “recycled” only when all the
labels have been peeled off the box. How does the system keep track of how many labels are on
a box?

Each object has associated with it a counter that tracks the total number of references that exist to
that object. This number simply indicates how many variables are “pointing to” any particular
object. This is the reference count that we introduced in the last chapter in Sections 3.5.5–3.5.7.
Python provides the is and is not operators to test if a pair of variables do indeed refer to the
same object. Performing a check such as

a is b is an equivalent expression to id(a) == id(b)

The object identity comparison operators all share the same precedence level and are presented
in Table 2.

Table 2. Standard Type Object Identity Comparison Operators

operator function

obj1 is obj2 obj1 is the same object as obj2

PYTHON NOTES Page 28


Table 2. Standard Type Object Identity Comparison Operators

operator function

obj1 is not obj2 obj1 is not the same object as obj2

In the example below, we create a variable, then another that points to the same object.

>>> a = [ 5, 'hat', -9.3]


>>> b = a
>>> a is b
1
>>> a is not b
0
>>>
>>> b = 2.5e-5
>>> b
2.5e-005
>>> a
[5, 'hat', -9.3]
>>> a is b
0
>>> a is not b
1

Both the is and not identifiers are Python keywords.

1.11.2. Boolean

Expressions may be linked together or negated using the boolean logical


operators and, or, and not, all of which are Python keywords. These Boolean operations are in
highest-to-lowest order of precedence in Table 3. The not operator has the highest precedence
and is immediately one level below all the comparison operators. The and and or operators
follow, respectively.

PYTHON NOTES Page 29


Table 3. Standard Type Boolean Operators

operator function

not expr logical NOT of expr (negation)

expr1 and expr2 logical AND of expr1 and expr2 (conjunction)

expr1 or expr2 logical OR of expr1 and expr2 (disjunction)

>>> x, y = 3.1415926536, -1024


>>> x < 5.0
1
>>> not (x < 5.0)
0
>>> (x < 5.0) or (y > 2.718281828)
1
>>> (x < 5.0) and (y > 2.718281828)
0
>>> not (x is y)
1

Earlier, we introduced the notion that Python supports multiple comparisons within one
expression. These expressions have an implicit and operator joining them together.

>>> 3 < 4 < 7 # same as "( 3 < 4 ) and ( 4 < 7 )"


1

1.12 Standard types built-in functions

PYTHON NOTES Page 30


Python Built-in Functions List
Function Name Description

Python abs() Function Return the absolute value of a number

It takes an asynchronous iterable as an argument and returns an


Python aiter() Function asynchronous iterator for that iterable

Return true if all the elements of a given iterable( List, Dictionary,


Python all() Function Tuple, set, etc) are True else it returns False

Returns true if any of the elements of a given iterable( List,


Python any() Function Dictionary, Tuple, set, etc) are True else it returns False

Python anext() used for getting the next item from an asynchronous iterator
Function

Python ascii() Returns a string containing a printable representation of an object


Function

Python bin() Function Convert integer to a binary string

Python bool() Return or convert a value to a Boolean value i.e., True or False
Function

Python breakpoint() It is used for dropping into the debugger at the call site during
Function runtime for debugging purposes

Python bytearray() Returns a byte array object which is an array of given bytes
Function

PYTHON NOTES Page 31


Function Name Description

Python bytes() Converts an object to an immutable byte-represented object of a


Function given size and data

Python callable() Returns True if the object passed appears to be callable


Function

Returns a string representing a character whose Unicode code point


Python chr() Function is an integer

Python classmethod() Returns a class method for a given function


Function

Python compile() Returns a Python code object


Function

Python complex() Creates Complex Number


Function

Python delattr() Delete the named attribute from the object


Function

Python dict() Function Creates a Python Dictionary

Python dir() Function Returns a list of the attributes and methods of any object

Python divmod() Takes two numbers and returns a pair of numbers consisting of their
Function quotient and remainder

Python enumerate() Adds a counter to an iterable and returns it in a form of enumerating

PYTHON NOTES Page 32


Function Name Description

Function object

Parses the expression passed to it and runs Python expression(code)


Python eval() Function within the program

Python exec() Used for the dynamic execution of the program


Function

1.12.1 Abs() in Python


The Python abs() function return the absolute value. The absolute value of any number is
always positive it removes the negative sign of a number in Python.

Example:
Input: -29
Output: 29

Syntax
abs(number)
• number: Integer, floating-point number, complex number.

Return: Returns the absolute value.

Example.
abs() Function with an Integer Argument
In this example, we will pass an Integer value as an argument to the abs() function in Python and
print its value to see how it works.

# An integer
var = -94
print('Absolute value of integer is:', abs(var))

Output:
Absolute value of integer is: 94

PYTHON NOTES Page 33


1.12.2 Python – all() function
The Python all() function returns true if all the elements of a given iterable (List,
Dictionary, Tuple, set, etc.) are True otherwise it returns False. It also returns True if the
iterable object is empty. Sometimes while working on some code if we want to ensure that user
has not entered a False value then we use the all() function.
Syntax: all( iterable )
• Iterable: It is an iterable object such as a dictionary,tuple,list,set,etc.
Returns: boolean
Example:

print(all([True, True, False]))

Output:
False

1.11.3 Python any() function


Python any() function returns True if any of the elements of a given iterable( List, Dictionary,
Tuple, set, etc) are True else it returns False.

Example
Input: [True, False, False]
Output: True

Input: [False, False, False]


Output: False
Syntax: any(iterable)
• Iterable: It is an iterable object such as a dictionary, tuple, list, set, etc.
Returns: Returns True if any of the items is True.

Example
Python any() Function on Lists in Python. The below example returns True since at least one
element in the list (3rd element) is True.

# a List of boolean values

PYTHON NOTES Page 34


l = [False, False, True, False, False]

print(any(l))

Output:
True

5 Mark :

Write about the Python features?


Discuss the Variable and assignments with example?
Write the Internal types?
Explain the Identifiers with example?

10 Mark:

Explain about the Python objects with example?


Write about the Standard types in Operators?
Discuss the Standard types build in functions?

********UNIT I COMPLETED********

PYTHON NOTES Page 35


UNIT – II
2.1 Numbers
Numeric types and operations using numbers there are three numeric types in python: int
for integer, float for decimal numbers, and complex for complex numbers.
General mathematical operations such as addition, subtraction, and multiplication can be
done on them.

2.2 Integers and Double precision floating point numbers


Python has three built-in numeric data types: integers, floating-point numbers, and complex
numbers.

Integers

An integer is a whole number with no decimal places. For example, 1 is an integer,


but 1.0 isn’t. The name for the integer data type is int, which you can see with type():

>>>type(1)

<class 'int'>

Floating-Point Numbers

A floating-point number, or float for short, is a number with a decimal place. 1.0 is a
floating-point number, as is -2.75. The name of the floating-point data type is float

>>>float("1.25")
1.25

2.3 Complex numbers

PYTHON NOTES Page 36


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

# Python code to demonstrate the working of

# complex(), real() and imag()

# importing "cmath" for complex number operations

import cmath

# Initializing real numbers

x=5

y=3

# converting x and y into complex number

z = complex(x,y);

# printing real and imaginary part of complex number

print ("The real part of complex number is : ",end="")

print (z.real)

print ("The imaginary part of complex number is : ",end="")

print (z.imag)

Output:

The real part of complex number is : 5.0

The imaginary part of complex number is : 3.0

PYTHON NOTES Page 37


2.4 Operators
In Python, operators are special symbols or keywords that carry out operations on values
and python variables.

They serve as a basis for expressions, which are used to modify data and execute
computations. Python contains several operators, each with its unique purpose.

Types of Python Operators


Python language supports various types of operators, which are:

1. Arithmetic Operators
2. Comparison (Relational) Operators
3. Assignment Operators
4. Logical Operators
5. Bitwise Operators
6. Membership Operators
7. Identity Operators

1. Python Arithmetic Operators

Mathematical operations including addition, subtraction, multiplication, and division


are commonly carried out using Python arithmetic operators.

They are compatible with integers, variables, and expressions.

In addition to the standard arithmetic operators, there are operators for modulus,
exponentiation, and floor division.

Operator Name Example

+ Addition 10 + 20 = 30

- Subtraction 20 – 10 = 10

* Multiplication 10 * 20 = 200

/ Division 20 / 10 = 2

PYTHON NOTES Page 38


% Modulus 22 % 10 = 2

** Exponent 4**2 = 16

// Floor Division 9//2 = 4

Example of Python Arithmetic Operators


a = 21
b = 10
# Addition
print ("a + b : ", a + b)
# Subtraction
print ("a - b : ", a - b)
# Multiplication
print ("a * b : ", a * b)
# Division
print ("a / b : ", a / b)
# Modulus
print ("a % b : ", a % b)
# Exponent
print ("a ** b : ", a ** b)
# Floor Division
print ("a // b : ", a // b)
Run Code >>

The two variables "a" and "b" are defined in this code, which then applies several arithmetic
operations to them (including addition, subtraction, multiplication, division, modulus,
exponentiation, and floor division) and outputs the results.

Output
a + b :31
a - b :11
a * b :210
a / b :2.1
a % b :1
a ** b :16679880978201
a // b : 2

2. Python Comparison Operators


To compare two values, Python comparison operators are needed.
PYTHON NOTES Page 39
Based on the comparison, they produce a Boolean value (True or False).

Operator Name Example

== Equal 4 == 5 is not true.

!= Not Equal 4 != 5 is true.

> Greater Than 4 > 5 is not true

< Less Than 4 < 5 is true

>= Greater than or Equal to 4 >= 5 is not true.

<= Less than or Equal to 4 <= 5 is true.

Example of Python Comparison Operators


a=4
b=5
# Equal
print ("a == b : ", a == b)
# Not Equal
print ("a != b : ", a != b)
# Greater Than
print ("a >b : ", a > b)
# Less Than
print ("a <b : ", a < b)
# Greater Than or Equal to
print ("a >= b : ", a >= b)
# Less Than or Equal to
print ("a <= b : ", a <= b)
Run Code >>

This code compares the values of python variables 'a' and 'b' and prints if they are equal, not
equal, greater than, less than, more than or equal to, and less than or equal to each other.

Output
a == b : False
a != b : True
PYTHON NOTES Page 40
a >b : False
a <b : True
a >= b : False
a <= b : True

3. Python Assignment Operators

Python assignment operators are used to assign values to variables in Python.


The single equal symbol (=) is the most fundamental assignment operator.
It assigns the value on the operator's right side to the variable on the operator's left side.

Operator Name Example

= Assignment Operator a = 10

+= Addition Assignment a += 5 (Same as a = a + 5)

-= Subtraction Assignment a -= 5 (Same as a = a - 5)

*= Multiplication Assignment a *= 5 (Same as a = a * 5)

/= Division Assignment a /= 5 (Same as a = a / 5)

%= Remainder Assignment a %= 5 (Same as a = a % 5)

**= Exponent Assignment a **= 2 (Same as a = a ** 2)

//= Floor Division Assignment a //= 3 (Same as a = a // 3)

Example of Python Assignment Operators


# Assignment Operator
a = 10
# Addition Assignment
a += 5
print ("a += 5 : ", a)
# Subtraction Assignment
a -= 5
print ("a -= 5 : ", a)
# Multiplication Assignment

PYTHON NOTES Page 41


a *= 5
print ("a *= 5 : ", a)
# Division Assignment
a /= 5
print ("a /= 5 : ",a)
# Remainder Assignment
a %= 3
print ("a %= 3 : ", a)
# Exponent Assignment
a **= 2
print ("a **= 2 : ", a)
# Floor Division Assignment
a //= 3
print ("a //= 3 : ", a)

The Python assignment operators are shown in this code. It begins with the value of 'a' equal to
10, and then goes through the steps of addition, subtraction, multiplication, division, remainder,
exponentiation, and floor division, updating 'a' as necessary and outputting the results.

Output
a += 5 :105
a -= 5 :100
a *= 5 :500
a /= 5 :100.0
a %= 3 :1.0
a **= 2 :1.0
a //= 3 : 0.0

4. Python Bitwise Operators

Python bitwise operators execute operations on individual bits of binary integers.

They work with integer binary representations, performing logical operations on each bit
location.

Python includes various bitwise operators, such as AND (&), OR (|), NOT (), XOR (), left shift
(), and right shift (>>).

PYTHON NOTES Page 42


Operator Name Example

& Binary AND Sets each bit to 1 if both bits are 1

| Binary OR Sets each bit to 1 if one of the two bits is 1

^ Binary XOR Sets each bit to 1 if only one of two bits is 1

Binary Ones
~ Inverts all the bits
Complement

Binary Ones
~ Inverts all the bits
Complement

Shift left by pushing zeros in from the right and let the leftmost bits fall
<< Binary Left Shift
off

Shift right by pushing copies of the leftmost bit in from the left, and let
>> Binary Right Shift
the rightmost bits fall off

Example of Python Bitwise Operators


a = 60# 60 = 0011 1100
b = 13# 13 = 0000 1101
# Binary AND
c = a & b # 12 = 0000 1100
print ("a &b : ", c)
# Binary OR
c = a | b # 61 = 0011 1101
print ("a | b : ", c)
# Binary XOR
c = a ^ b # 49 = 0011 0001
print ("a ^ b : ", c)
# Binary Ones Complement
c = ~a; # -61 = 1100 0011
print ("~a : ", c)
# Binary Left Shift
c = a <<2; # 240 = 1111 0000
print ("a <<2 : ", c)
# Binary Right Shift
c = a >>2; # 15 = 0000 1111

PYTHON NOTES Page 43


print ("a >>2 : ", c)
Run Code >>

The binary representations of the numbers 'a and b' are subjected to bitwise operations in this
code. It displays the results of binary AND, OR, XOR, Ones Complement, Left Shift, and Right
Shift operations.

Output
a &b :12
a | b :61
a ^ b :49
~a : -61
a >>2 :240
a >>2 :15

5. Python Logical Operators

Python logical operators are used to compose Boolean expressions and evaluate their truth
values.

They are required for the creation of conditional statements as well as for managing the flow of
execution in programs.

Python has three basic logical operators: AND, OR, and NOT.

Operator Description Example

and Logical
If both of the operands are true then the condition becomes true. (a and b) is true.
AND

If any of the two operands is non-zero then the condition


or Logical OR (a or b) is true.
becomes true.

not Logical Not(a and b) is


Used to reverse the logical state of its operand
NOT false.

Example of Python Logical Operators


x=5

PYTHON NOTES Page 44


y = 10
if x >3and y <15:
print("Both x and y are within the specified range")
Run Code >>

The code assigns the values 5 and 10 to variables x and y. It determines whether x is larger than
3 and y is less than 15. If both conditions are met, it writes "Both x and y are within the specified
range."

Output
Both x and y are within the specified range

6. Python Membership Operators

Python membership operators are used to determine whether or not a certain value occurs within
a sequence.

They make it simple to determine the membership of elements in various data structures such
as lists, tuples, sets, and strings.

Python has two primary membership operators: the in and not in operators.

Operator Description Example

Evaluates to true if it finds a variable in the x in y, here in results in a 1 if x is a


In
specified sequence and false otherwise. member of sequence y.

Evaluates to true if it does not find a variable in the x not in y, here not in results in a 1 if x
not in
specified sequence and false otherwise. is not a member of sequence y.

Example of Python Membership Operators


fruits = ["apple", "banana", "cherry"]
if"banana"in fruits:
print("Yes, banana is a fruit!")
else:
print("No, banana is not a fruit!")
Run Code >>

PYTHON NOTES Page 45


The code defines a list of fruits and tests to see if the word "banana" appears in the list. If it is,
the message "Yes, banana is a fruit!" is displayed; otherwise, the message "No, banana is not a
fruit!" is displayed.

Output
Yes, banana is a fruit!
7. Python Identity Operators

Identity operators are used to compare the objects, not if they are equal, but if they are actually
the same object, with the same memory location:

Operator Description Example

is Returns true if both variables are the same object x is y

is not Returns true if both variables are not the same x is not y
object

Example:
x = ["apple", "banana"]
y = ["apple", "banana"]
z=x

print(x is z)

# returns True because z is the same object as x

print(x is y)

# returns False because x is not the same object as y, even if they have the same content

print(x == y)

PYTHON NOTES Page 46


# to demonstrate the difference betweeen "is" and "==": this comparison returns True because x
is equal to y

2.5 Numeric type functions

Python provides several built-in functions that are useful for working with numeric data types
such as `int`, `float`, and `complex`. Here’s an overview of some of the most commonly used
numeric functions, along with examples:

1. `abs()`
The `abs()` function returns the absolute value of a number. It can be used with both integers
and floating-point numbers.

Syntax
abs(x)
x: A number (integer or float)

Example:
print(abs(-5)) # Output: 5
print(abs(3.7)) # Output: 3.7
print(abs(-7.4)) # Output: 7.4

2. `round()`
The `round()` function returns a number rounded to a specified number of decimal places. If
no number of decimals is specified, it rounds to the nearest integer.

Syntax:
round(number, ndigits)

number: The number you want to round


ndigits (optional): The number of decimal places to round to. If omitted, it rounds to the
nearest integer.

Example:
print(round(3.14159, 2)) # Output: 3.14
print(round(2.718, 1)) # Output: 2.7
print(round(4.5)) # Output: 4

PYTHON NOTES Page 47


3. `pow()`
The `pow()` function returns the value of a number raised to the power of another number. It
can also take an optional modulus parameter.

Syntax:
pow(base, exp[, mod])

base: The base number


exp: The exponent to raise the base to
mod (optional): A modulus to take after exponentiation

Example:
print(pow(2, 3)) # Output: 8 (2 raised to the power of 3)
print(pow(3, 2)) # Output: 9 (3 raised to the power of 2)
print(pow(2, 3, 5)) # Output: 3 ((2^3) % 5 = 8 % 5 = 3)

4. `min()` and `max()`


The `min()` function returns the smallest item from an iterable or the smallest of two or more
arguments, and `max()` returns the largest.

Syntax:
min(iterable) or min(x, y, z, ...)
max(iterable) or max(x, y, z, ...)

iterable: An iterable (like a list or tuple) or a set of values to compare.

Example:
numbers = [3, 1, 9, 7, 4]
print(min(numbers)) # Output: 1
print(max(numbers)) # Output: 9
print(min(5, 10, 2)) # Output: 2
print(max(5, 10, 2)) # Output: 10

5. `sum()`
The `sum()` function returns the sum of all elements in an iterable (e.g., list or tuple).

Syntax:
sum(iterable, start)

PYTHON NOTES Page 48


iterable: The iterable (like a list or tuple) whose elements you want to sum.
start (optional): The starting value to add to the sum (defaults to 0).

Example:
numbers = [1, 2, 3, 4]
print(sum(numbers)) # Output: 10
print(sum(numbers, 5)) # Output: 15 (adding 5 to the sum)

6. `divmod()`
The `divmod()` function takes two numbers and returns a tuple containing the quotient and
the remainder when dividing the first number by the second.

Syntax:
divmod(a, b)

a: The dividend (numerator)


b: The divisor (denominator)

Example:
result = divmod(9, 4)
print(result) # Output: (2, 1) (quotient = 2, remainder = 1)

7. `int()`
The `int()` function converts a number or string to an integer.

Syntax:
int(x)

x: The number or string to convert to an integer.

Example:
print(int(3.5)) # Output: 3 (converts float to int)
print(int("123")) # Output: 123 (converts string to int)

8. `float()`
The `float()` function converts a number or a string to a floating-point number.

Syntax:
float(x)

PYTHON NOTES Page 49


x: The number or string to convert to a float.

Example:
print(float(5)) # Output: 5.0
print(float("3.14")) # Output: 3.14

9. `complex()`
The `complex()` function creates a complex number from real and imaginary parts.

Syntax:
complex(real, imag)

real: The real part of the complex number.


imag: The imaginary part of the complex number.

Example:
c1 = complex(2, 3)
c2 = complex(1, -4)
print(c1) # Output: (2+3j)
print(c2) # Output: (1-4j)

10. `isinstance()`
The `isinstance()` function is used to check whether an object is an instance of a specified
class or a tuple of classes.

Syntax
isinstance(object, classinfo)

object: The object to check


classinfo: A class, type, or tuple of classes to check against

Example:
print(isinstance(5, int)) # Output: True
print(isinstance(5.5, float)) # Output: True
print(isinstance("hello", str)) # Output: True
print(isinstance(5, float)) # Output: False

11. `math` module functions

PYTHON NOTES Page 50


Python provides a `math` module with additional numeric functions. Some common
functions include:

math.sqrt(x): Returns the square root of `x`


math.ceil(x): Returns the smallest integer greater than or equal to `x`
math.floor(x): Returns the largest integer less than or equal to `x`
math.factorial(x): Returns the factorial of `x`

Example
import math

print(math.sqrt(16)) # Output: 4.0


print(math.ceil(4.1)) # Output: 5
print(math.floor(4.9)) # Output: 4
print(math.factorial(5)) # Output: 120

.
2.6 Sequences
In Python, sequence is the generic term for an ordered set. There are several types of sequences
in Python, the following three are the most important.

Lists are the most versatile sequence type. The elements of a list can be any object, and lists
are mutable - they can be changed. Elements can be reassigned or removed, and new elements
can be inserted.

Tuples are like lists, but they are immutable - they can't be changed.

Strings are a special type of sequence that can only store characters, and they have a special
notation. However, all of the sequence operations described below can also be used on strings.

2.6.1 Strings:
In other languages, the elements in arrays and sometimes the characters in strings may be
accessed with the square brackets, or subscript operator.
>>>"Hello, world!"[0]
'H'
>>>"Hello, world!"[1]
'e'
>>>"Hello, world!"[2]

PYTHON NOTES Page 51


'l'
>>>"Hello, world!"[3]
'l'
>>>"Hello, world!"[4]
'o'

Indexes are numbered from 0 to n-1 where n is the number of items (or characters), and they are
given to the characters from the start of the string:

H e l l o , w o r l d !
0 1 2 3 4 5 6 7 8 9 10 11 12

Negative indexes (numbered from -1 to -n) are counted from the end of the string:

H e l l o , w o r l d !
-13 -12 -11 -10 -9 -8 -7 -6 -5 -4 -3 -2 -1

2.6.2 Python String Operators

PYTHON NOTES Page 52


Example

str1 = "Hello"
str2 = " World"
print(str1*3) # prints HelloHelloHello
print(str1+str2) # prints Hello world
print(str1[4]) # prints o
print(str1[2:4]) # prints ll
print('w' in str1) # prints false as w is not present in str1
print('Wo' not in str2) # prints false as Wo is present in str2.
print(r'Hello\n world') # prints Hello\n world as it is written
print("The string str1 : %s"%(str1)) # prints The string str : Hello

OUTPUT
HelloHelloHello
Hello World
o

PYTHON NOTES Page 53


ll
False
False
Hello\n world
The string str1: Hello

2.7. String Built-in functions


Python provides various in-built functions that are used for string handling. Those are

• len()
• lower()
• upper()
• replace()
• join()
• split()
• find()
• index()
• isalnum()
• isdigit()
• isnumeric()
• islower()
• isupper()

1. len()

In python string len() function returns length of the given string.


Syntax:

len(string)

Example:

str1="Python Language"
print(len(str1))

Output:

15

PYTHON NOTES Page 54


2. lower ()

In python, lower() method returns all characters of given string in lowercase.


Syntax:

str.lower()

Example:

str=”PyTHOn”
print(str.lower())

Output:

python

3. upper ()

In python upper() method converts all the character to uppercase and returns a uppercase string.
Syntax:

str.upper()

Example:

str=”PyTHOn”
print(str.upper())

Output:

PYTHON

4. replace()

In python replace() method replaces the old sequence of characters with the new sequence. If the
optional argument count is given, only the first count occurrences are replaced.
Syntax:

PYTHON NOTES Page 55


str.replace(old, new[, count])

old : An old string which will be replaced.


new :New string which will replace the old string.
count : The number of times to process the replace.
Example:

str = "Java is Object-Oriented and Java is Portable "


# Calling function
str2 = str.replace("Java","Python") # replaces all the occurences
# Displaying result
print("Old String: \n",str)
print("New String: \n",str2)

str3 = str.replace("Java","Python",1) # replaces first occurance only


# Displaying result
print("\n Old String: \n",str)
print("New String: \n",str3)

str4 = str1.replace(str1,"Python is Object-Oriented and Portable")


print("New String: \n",str4)

Output:

python
PYTHON
Old String:
Java is Object-Oriented and Java is Portable
New String:
Python is Object-Oriented and Python is Portable

Old String:
Java is Object-Oriented and Java is Portable
New String:
Python is Object-Oriented and Java is Portable

New String:
Python is Object-Oriented and Portable

PYTHON NOTES Page 56


5. join()

Python join() method is used to concat a string with iterable object. It returns a new string which
is the concatenation of the strings in iterable. It allows various iterables like: List, Tuple, String
etc.
Syntax:

str.join(sequence)

Example:

str1 = ":" # string


str2 = "NNRG" # iterable object
str3= str1.join(str2)
print(str3)

Output:

N:N:R:G

6. split()

In python split() method splits the string into a comma separated list. It separates string based on
the separator delimiter. The string splits according to the space if the delimiter is not provided.
Syntax:

str.split([sep=”delimiter”])

sep: It specifies the delimiter as separator.


Example:

str1 = "Java is a programming language"


str2 = str1.split()
# Displaying result
print(str1)
print(str2)
str1 = "Java,is,a,programming,language"
str2 = str1.split(sep=',')

PYTHON NOTES Page 57


# Displaying result
print(str1)
print(str2)

Output:

Java is a programming language


['Java', 'is', 'a', 'programming', 'language']
Java, is, a, programming, language
['Java', 'is', 'a', 'programming', 'language']

7. find()

In python find() method finds substring in the whole string and returns index of the first match. It
returns -1 if substring does not match.
Syntax:

str.find(sub[, start[,end]])

sub: it specifies sub string.


start: It specifies start index of range.
end : It specifies end index of range.
Example:

str1 = "python is a programming language"


str2 = str1.find("is")
str3 = str1.find("java")
str4 = str1.find("p",5)
str5 = str1.find("i",5,25)
print(str2,str3,str4,str5)

Output:

7 -1 12 7

PYTHON NOTES Page 58


8. index()

In python index() method is same as the find() method except it returns error on failure. This
method returns index of first occurred substring and an error if there is no match found.
Syntax:

index(sub[, start[,end]])

sub :it specifies sub string.


start :It specifies start index of range.
end : It specifies end index of range.

1.8 Lists:
In Python, a list is a built-in data structure that is used to store an ordered
collection of items. Lists are mutable, meaning that their contents can be changed after the list
has been created. They can hold a various of data types, including integers, floats, strings, and
even other lists.

Example:

a = [1, 'apple', 3.14, [5, 6]]

print(a)

Output
[1, 'apple', 3.14, [5, 6]]

A list is created using square brackets. For example, an empty list would be initialized like this:

spam=[]

The values of the list are separated by commas.

Example:

# List of integers
a = [1, 2, 3, 4, 5]

# List of strings

PYTHON NOTES Page 59


b = ['apple', 'banana', 'cherry']

# Mixed data types


c = [1, 'hello', 3.14, True]

print(a)
print(b)
print(c)

Output
[1, 2, 3, 4, 5]
['apple', 'banana', 'cherry']
[1, 'hello', 3.14, True]

2.8.1 List type Built in Methods

Lists are used to store multiple items in a single variable. Lists are one of 4 built-in data types in
Python used to store collections of data, the other 3 are Tuple, Set, and Dictionary, all with
different qualities and usage.

List Methods
• append(): Adds an element to the end of the list.
• copy(): Returns a shallow copy of the list.
• clear(): Removes all elements from the list.
• count(): Returns the number of times a specified element appears in the list.
• extend(): Adds elements from another list to the end of the current list.
• index(): Returns the index of the first occurrence of a specified element.
• insert(): Inserts an element at a specified position.
• pop(): Removes and returns the element at the specified position (or the last element if no
index is specified).
• remove(): Removes the first occurrence of a specified element.
• reverse(): Reverses the order of the elements in the list.
• sort(): Sorts the list in ascending order (by default).

Examples of List Methods

1. append():

PYTHON NOTES Page 60


Syntax: list_name.append(element)
In the code below, we will add an element to the list.

a = [1, 2, 3]

# Add 4 to the end of the list

a.append(4)

print(a)

Output
[1, 2, 3, 4]

2. copy():
Syntax: list_name.copy()

In the code below, we will create a copy of a list.

a = [1, 2, 3]

# Create a copy of the list

b = a.copy()

print(b)

Output
[1, 2, 3]

3. clear():
Syntax: list_name.clear()

In the code below, we will clear all elements from the list.

a = [1, 2, 3]

# Remove all elements from the list

a.clear()

print(a)

Output

PYTHON NOTES Page 61


[]

4. count():
Syntax: list_name.count(element)

In the code below, we will count the occurrences of a specific element in the list.

a = [1, 2, 3, 2]

# Count occurrences of 2 in the list

print(a.count(2))

Output
2

5. extend():
Syntax: list_name.extend(iterable)

In the code below, we will extend the list by adding elements from another list.

a = [1, 2]

# Extend list a by adding elements from list [3, 4]

a.extend([3, 4])

print(a)

Output
[1, 2, 3, 4]

6. index():
Syntax: list_name.index(element)

In the code below, we will find the index of a specific element in the list.

a = [1, 2, 3]

# Find the index of 2 in the list

print(a.index(2))

PYTHON NOTES Page 62


Output
1

7. insert():
Syntax: list_name.insert(index, element)

In the code below, we will insert an element at a specific position in the list.
a = [1, 3]

# Insert 2 at index 1

a.insert(1, 2)

print(a)

Output

[1, 2, 3]

8. pop():
Syntax: list_name.pop(index)

In the code below, we will remove the last element from the list.
Python
a = [1, 2, 3]

# Remove and return the last element in the list

a.pop()

print(a)

Output
[1, 2]

9. remove():
Syntax: list_name.remove(element)

In the code below, we will remove the first occurrence of a specified element from the list.
a = [1, 2, 3]

PYTHON NOTES Page 63


# Remove the first occurrence of 2

a.remove(2)

print(a)

Output
[1, 3]

10. reverse():
Syntax: list_name.reverse()

In the code below, we will reverse the order of the elements in the list.
a = [1, 2, 3]

# Reverse the list order

a.reverse()

print(a)

Output
[3, 2, 1]

11. sort():
Syntax: list_name.sort(key=None, reverse=False)

In the code below, we will sort the elements of the list in ascending order
Python
a = [3, 1, 2]

# Sort the list in ascending order

a.sort()

print(a)

Output
[1, 2, 3]

2.9 Tuples:

PYTHON NOTES Page 64


Python Tuple is a collection of Python Programming objects much like a list. The
sequence of values stored in a tuple can be of any type, and they are indexed by integers.
Values of a tuple are syntactically separated by ‘commas‘. Although it is not necessary, it is
more common to define a tuple by closing the sequence of values in parentheses. This helps in
understanding the Python tuples more easily.

Features of Python Tuple

o Tuples are an immutable data type, meaning their elements cannot be changed after they
are generated.
o Each element in a tuple has a specific order that will never change because tuples are
ordered sequences.
What is Immutable in Tuples?
Unlike Python lists, tuples are immutable. Some Characteristics of Tuples in Python.
• Like Lists, tuples are ordered and we can access their elements using their index values
• We cannot update items to a tuple once it is created.
• Tuples cannot be appended or extended.
• We cannot remove items from a tuple once it is created.

t = (1, 2, 3, 4, 5)

# tuples are indexed

print(t[1])

print(t[4])

# tuples contain duplicate elements

t = (1, 2, 3, 4, 2, 3)

print(t)

# updating an element

t[1] = 100

print(t)

Output:

PYTHON NOTES Page 65


2
5
(1, 2, 3, 4, 2, 3)
Traceback (most recent call last):
File "Solution.py", line 12, in <module>
t[1] = 100
TypeError: 'tuple' object does not support item assignment

Forming a Tuple:

All the objects-also known as "elements"-must be separated by a comma, enclosed in parenthesis


(). Although parentheses are not required, they are recommended.

Example:

# Note : In case of list, we use square

# brackets []. Here we use round brackets ()

t = (10, 20, 30)

print(t)

print(type(t))

Output
(10, 20, 30)
<class 'tuple'>

Accessing Values in Python Tuples


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

t = (10, 5, 20)

print("Value in t[0] = ", t[0])

PYTHON NOTES Page 66


print("Value in t[1] = ", t[1])

print("Value in t[2] = ", t[2])

Output
Value in t[0] = 10
Value in t[1] = 5
Value in t[2] = 20
2. 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 [].
Python

t = (10, 5, 20)

print("Value in t[-1] = ", t[-1])

print("Value in t[-2] = ", t[-2])

print("Value in t[-3] = ", t[-3])


Output
Value in t[-1] = 20
Value in t[-2] = 5
Value in t[-3] = 10

3. Deleting a Tuple in Python


In this example, we are deleting a tuple using ‘del’ keyword. The output will be in the
form of error because after deleting the tuple, it will give a NameError.
Note: Remove individual tuple elements is not possible, but we can delete the whole Tuple
using Del keyword.
# Code for deleting a tuple

t = ( 0, 1)

del t

print(t)

PYTHON NOTES Page 67


Output:
Hangup (SIGHUP)
Traceback (most recent call last):
File "Solution.py", line 5, in <module>
print(t)
NameError: name 't' is not defined

5 Mark:
Write about the Lists with example?
Discuss the Tuples?
Write the Strings with example?
Write the Floating points numbers ?
10 Mark:
Explain about the Numeric type functions?
Write the numbers and operators?
Discuss about the Strings and strings operators?
Write the string build in methods?

********UNIT II COMPLETED********

PYTHON NOTES Page 68


UNIT III
3.1 MAPPING TYPE
• 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.
• The value, we can use different kind of elements like lists, integers or any other mutable
type objects.

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

Some dictionary related methods and operations are −

• Method len(d)

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

• Operation d[k]

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

• Method iter(d)

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

• Method get(key[, default])

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

PYTHON NOTES Page 69


• Method items()

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

• Method keys()

Return the list of different keys in the dictionary.

• Method values()

Return the list of different values from the dictionary.

• Method update(elem)

Modify the element elem in the dictionary.

Example,
myDict={'ten':10,'twenty':20,'thirty':30,'forty':40}
print(myDict)
print(list(myDict.keys()))
print(list(myDict.values()))

#create items from the key-value pairs


print(list(myDict.items()))

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

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

3.2 DICTIONARIES

A Python dictionary is a data structure that stores the value in key: value pairs. Values in a
dictionary can be of any data type and can be duplicated, whereas keys can’t be repeated and
must be immutable.
Example: Here, The data is stored in key: value pairs in dictionaries, which makes it easier to
find values.
PYTHON NOTES Page 70
d = {1: 'Geeks', 2: 'For', 3: 'Geeks'}
2

print(d)

Output

{1: 'Geeks', 2: 'For', 3: 'Geeks'}


Python dictionaries are essential for efficient data mapping and manipulation in programming.

Python Dictionary Syntax


dict_var = {key1 : value1, key2 : value2, …..}
Note – Dictionary keys are case sensitive, the same name but different cases of Key will be
treated distinctly.

How to Create a Dictionary


In Python, a dictionary can be created by placing a sequence of elements within
curly {} braces, separated by a ‘comma’.

d1 = {1: 'Python', 2: 'For', 3: 'Python'}

print("\nDictionary with the use of Integer Keys: ")

print(d1)

d2 = {'Name': 'Python', 1: [1, 2, 3, 4]}

print("\nDictionary with the use of Mixed Keys: ")

print(d2)

Output
Dictionary with the use of Integer Keys:
{1: 'Python', 2: 'For', 3: 'Python'}

Dictionary with the use of Mixed Keys:


{'Name': 'Geeks', 1: [1, 2, 3, 4]}

PYTHON NOTES Page 71


Adding Elements to a Dictionary

The addition of elements can be done in multiple ways. One value at a time can be added to a
Dictionary by defining value along with the key e.g. Dict[Key] = ‘Value’.

Example: Add Items to a Python Dictionary with Different DataTypes


Adding elements with various data types, updating a key’s value, and nesting dictionaries within
the main dictionary. The code shows how to manipulate dictionaries in Python.

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


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

Output

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

Deleting Elements using del Keyword

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

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


print(type(Employee))
print("printing Employee data .... ")
print(Employee)
print("Deleting some of the employee data")
del Employee["Name"]

PYTHON NOTES Page 72


del Employee["Company"]
print("printing the modified information ")
print(Employee)
print("Deleting the dictionary: Employee");
del Employee
print("Lets try to print it again ");
print(Employee)

Output

<class 'dict'>
printing Employee data ....
{'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.

3.3 MAPPING TYPE OPERATORS


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

3.3.1. Standard Type Operators


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

>>> dict4 = {'abc': 123}


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

PYTHON NOTES Page 73


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.

3.3.2. Mapping Type Operators

Dictionary Key-Lookup Operator ( [ ] )


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

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

d[k] = v # set value 'v' in dictionary with key 'k' d[k] # lookup value in dictionary with
key 'k'

3.4 MAPPING TYPE BUILT IN & FACTORY FUNCTIONS


3.4.1. Standard Type Functions [type(), str(), and cmp()]
• The type() factory function, when applied to a dict, returns, as you might expect,
the dict type, "<type 'dict'>". The str() factory function will produce a printable string
representation of a dictionary. These are fairly straightforward.
• Comparisons of dictionaries are based on an algorithm that starts with sizes first, then
keys, and finally values. However, using cmp() on dictionaries isn't usually very useful.
• The next subsection goes into further detail about the algorithm used to compare
dictionaries, but this is advanced reading, and definitely optional since comparing
dictionaries is not very useful or very common.

*Dictionary Comparison Algorithm


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

PYTHON NOTES Page 74


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

PYTHON NOTES Page 75


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

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

(2) Compare Dictionary Keys


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

(3) Compare Dictionary Values


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

(4) Exact Match


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

Figure 7-1 illustrates the dictionary compare algorithm we just outlined.

PYTHON NOTES Page 76


Figure 3-1. How dictionaries are compared

3.4.2. Mapping Type Related Functions


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

If the argument is an iterable, i.e., a sequence, an iterator, or an object that supports iteration,
then each element of the iterable must come in pairs. For each pair, the first element will be a
new key in the dictionary with the second item as its value. Taking a cue from the official Python
documentation for 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}

• 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
PYTHON NOTES Page 77
• 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 the hash 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 their types differ). A TypeError will occur if an
unhashable type is given as the argument to hash() (and consequently 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

In Table 3.1, we summarize these three mapping type related functions.

Table 3.1. Mapping Type Related Functions


Function Operation
dict([container])Factory function for creating a dictionary populated with items from container, if
provided; if not, an empty dict is created
len(mapping) Returns the length of mapping (number of key-value pairs)
hash(obj) Returns hash value of obj

3.5. MAPPING TYPE BUILT IN METHODS


Dictionaries have an abundance of methods to help you get the job done, as indicated in Table
3.2.

Table 3.2. Dictionary Type Methods

PYTHON NOTES Page 78


Below, we showcase some of the more common dictionary methods. We have already
seen has_key() and its replacements in and not in at work above. Attempting to access a
nonexistent key will result in an exception (KeyError).

Basic dictionary methods focus on their keys and values. These are keys(), which returns a
list of the dictionary's keys, values(), which returns a list of the dictionary's values, and items(),
which returns a list of (key, value) tuple pairs. These are useful when you wish to iterate through
a dictionary's keys or values, albeit in no particular order.

PYTHON NOTES Page 79


The keys() method is fairly useful when used in conjunction with a for loop to retrieve a
dictionary’s values as it returns a list of a dictionary’s keys. However, because its items (as with
any keys of a hash table) are unordered, imposing some type of order is usually desired.

In Python versions prior to 2.4, you would have to call a dictionary’s keys() method to get
the list of its keys, then call that list’s sort() method to get a sorted list to iterate over. Now a
built-in function named sorted(), made especially for iterators, exists, which returns a sorted
iterator:

The update() method can be used to add the contents of one dictionary to another.
Any existing entries with duplicate keys will be overridden by the new incoming entries.
Nonexistent ones will be added. All entries in a dictionary can be removed with
the clear() method.

PYTHON NOTES Page 80


The copy() method simply returns a copy of a dictionary. Note that this is a shallow
copy only. Finally, the get() method is similar to using the key-lookup operator ( [ ] ), but allows
you to provide a default value returned if a key does not exist. If a key does not exist and a
default value is not given, then None is returned. This is a more flexible option than just using
key-lookup because you do not have to worry about an exception being raised if a key does not
exist.

3.6. CONDITIONAL AND LOOPS


Conditional statements in Python allow us to check for certain conditions and perform
actions based on the outcome of those checks.

There are several types of conditional statements in Python, including

o if statement
o if else statement
o if elif else statement
o nested if else statement

3.6.1. if statement

PYTHON NOTES Page 81


The if statement is used to check if a certain condition is true, and if so, execute a specific block
of code.

General form:

if BOOLEAN EXPRESSION:
STATEMENTS
Flowchart of an if statement

Here’s an example:

age = 18

if age >= 18:


print("You are old enough to vote.")

In this example, the if statement checks if the value of the variable age is greater than or equal to
18. If it is, the code inside the if statement is executed, which in this case is simply printing a
message to the console.

PYTHON NOTES Page 82


3.6.2. if else statement

The if else statement is used to execute one block of code if a condition is true, and another block
of code if the condition is false.

The syntax for an if else statement looks like this:

if BOOLEAN EXPRESSION:
STATEMENTS_1 # executed if condition evaluates to True
else:
STATEMENTS_2 # executed if condition evaluates to False

Flowchart of a if else statement

Here’s an example:

age = 16

if age >= 18:


print("You are old enough to vote.")
else:
print("You are not old enough to vote yet.")

PYTHON NOTES Page 83


In this example, the if statement checks if the value of age is greater than or equal to 18. If it is,
the message "You are old enough to vote." is printed. If it is not, the message "You are not old
enough to vote yet." is printed instead.

3.6.3. if elif else statement

The if elif else statement is used to check multiple conditions, and execute a specific block of
code based on which condition is true.

if x < y:
STATEMENTS_A
elif x > y:
STATEMENTS_B
else:
STATEMENTS_C

Flowchart of this chained conditional

Here’s an example:

age = 16

if age >= 18:


print("You are old enough to vote.")

PYTHON NOTES Page 84


elif age >= 16:
print("You can drive but cannot vote.")
else:
print("You cannot drive or vote yet.")

In this example, the first if statement checks if the value of age is greater than or equal to 18. If it
is, the message "You are old enough to vote." is printed. If not, the elif statement checks if age is
greater than or equal to 16. If it is, the message "You can drive but cannot vote." is printed. If
neither of these conditions are true, the else statement executes, and the message "You cannot
drive or vote yet." is printed.

3.6.4.. nested if else statement

The nested if else statement is used when we need to check a condition inside another condition.

if x < y:
STATEMENTS_A
else:
if x > y:
STATEMENTS_B
else:
STATEMENTS_C

Flowchart of this nested conditional

PYTHON NOTES Page 85


Here’s an example:

age = 18
gender = "female"

if age >= 18:


if gender == "male":
print("You are a male and old enough to vote.")
else:
print("You are a female and old enough to vote.")
else:
print("You are not old enough to vote yet.")

In this example, the first if statement checks if age is greater than or equal to 18. If it is, the
nested if statement checks if the value of gender is "male". If it is, the message "You are a male
and old enough to vote." is printed. If not, the message "You are a female and old enough.

PYTHON NOTES Page 86


3.7. LOOPS IN PYTHON

A loop is a repetitive statement or task.

3.7.1 While Loop Statement:

A while loop statement in Python is used to repeatedly execute a block of code as long as a
condition is true.

It is typically used when you don’t know how many times the loop will run in advance.

# Print numbers from 1 to 5 using a while loop


count = 1
while count <= 5:
print(count)
count +=1
OUTPUT:
>> 1
>> 2
>> 3
>> 4
>> 5

3.7.2 For Loop Statement:

PYTHON NOTES Page 87


A for-loop statement in Python is used to iterate over a sequence (such as a list, tuple, or string)
and perform a certain action for each item in the sequence.

# Print each character in a string using a for loop


word = "Python"
for letter in word:
print(letter)
OUTPUT:

>> P

>> Y

>> T

>> H

>> O

>> N

3.7.3. Break Statement

The break statement is used to immediately leave the body of its loop. The next statement to be
executed is the first one after the body

foriin[12,16,17,24,29]:

PYTHON NOTES Page 88


ifi%2==1:# if the number is odd
break# immediately exit the loop
print(i)
print("done")

output:

12
16
done

3.7.4. Continue Statement

Continue statement is a loop control statement that forces to execute the next iteration of
the loop while skipping the rest of the code inside the loop for the current iteration only,
i.e. when the continue statement is executed in the loop, the code inside the loop
following the continue statement will be skipped for the current iteration and the next
iteration of the loop will begin.

Python continue Statement Syntax


while True:
...
if x == 10:
continue
print(x)

PYTHON NOTES Page 89


3.7.5. PASS STATEMENT
The pass statement is used as a placeholder for future code.
When the pass statement is executed, nothing happens, but you avoid getting an error when
empty code is not allowed.
Empty code is not allowed in loops, function definitions, class definitions, or in if statements.

Example,
a = 33
b = 200

if b> a:
pass

3.8. ITERATORS AND THE ITER() FUNCTIONS

The python iter function is used to return an iterator for the object. The iter() is used to create an
object that will iterate one element at a time. The iter() takes two optional arguments as input.

The syntax of the iter() function is:

iter(object, sentinel)

PYTHON NOTES Page 90


iter() Parameters

The python iter() takes 2 optional parameters. The two optional parameters are:

object- this parameter is the object whose iterator must be created (tuples, sets, and so on)

sentinel- a unique value that represents the end of a sequence

Return value from iter()

For the provided object, the iter() function returns an iterator object.

The TypeError exception is raised if the user-defined function does not implement the _next_(),
the _iter_(), or the _getitem()_.

Iter() produces an iterator until the sentinel character isn’t found if the sentinel parameter is also
provided.

EXAMPLE,

# list of vowels

vowels =['a','e','i','o','u']

vowels_iter=iter(vowels)

print(next(vowels_iter))# 'a'

print(next(vowels_iter))# 'e'

print(next(vowels_iter))# 'i'

PYTHON NOTES Page 91


print(next(vowels_iter))# 'o'

print(next(vowels_iter))# 'u'

Output:

How does __ ITER __ work in Python?

The _iter_() in Python is used to return an iterator object each element at a time.

Example:

lst123 = [11, 22, 33, 44, 55]

iter_lst = iter(lst123)

while True:

try:

print(iter_lst.__next__())

except:

break

Output:

11

22

PYTHON NOTES Page 92


33

44

55

3.9. FILE OBJECT:

• A file object allows us to use, access and manipulate all the user accessible files.
• One can read and write any such files.
• When a file operation fails for an I/O-related reason, the exception IOError is raised.
• This includes situations where the operation is not defined for some reason, like seek() on
a tty device or writing a file opened for reading.
• Files have the following methods:

1) Open(): Opens a file in given access mode.

open(file_address, access_mode)

The mode parameter is optional and defaults to ‘r‘, which means opening the file in read mode.
There are several modes in which we can open a file:

• 'r': Read mode. The file is opened for reading (default).


• 'w': Write mode. The file is opened for writing. If the file already exists, its contents will
be truncated. If the file does not exist, a new file will be created.
• 'a': Append mode. The file is opened for writing, and data is appended to the end of the
file.
• 'x': Exclusive creation mode. The file is opened for writing, but only if it does not
already exist.
• 'b': Binary mode. The file is opened in binary mode, which is used for non-text files like
images or audio files.
• 't': Text mode. The file is opened in text mode, which is used for text files (default).

Once we have opened a file, we can read from or write to a file using Python methods
like read(), readline(), write(), and writelines().

PYTHON NOTES Page 93


2) read([size]): It reads the entire file and returns it contents in the form of a string. Reads
at most size bytes from the file (less if the read hits EOF before obtaining size bytes). If
the size argument is negative or omitted, read all data until EOF is reached.

# Reading a file

f = open(__file__, 'r')

#read()

text = f.read(10)

print(text)

f.close()

3) readline([size]): It reads the first line of the file i.e till a newline character or an EOF in
case of a file having a single line and returns a string. If the size argument is present and
non-negative, it is a maximum byte count (including the trailing newline) and an
incomplete line may be returned. An empty string is returned only when EOF is
encountered immediately.

# Reading a line in a file

f = open(__file__, 'r')

#readline()

text = f.readline(20)

print(text)

f.close()

4) Closing Files in Python


In Python, it’s important to properly close files after we’re done working with them.

Failing to do so can lead to resource leaks, which can slow down our program and potentially
cause other issues.

Fortunately, closing a file in Python is quite simple.

PYTHON NOTES Page 94


To close a file in Python, we can call the close() method on the file object that we opened.

For example:

file = open('example.txt', 'r')


# do some stuff with the file
file.close()
Copy
This will close the file and release any resources that were being used to keep it open. It’s a good
practice to always close files when we’re done working with them.

3.10. FILE BUILD IN FUNCTIONS:

File Built-in Function [open ()]

Python has a built-in function open() to open a file. Which accepts two arguments, file name and
access mode in which the file is accessed. The function returns a file object which can be used to
perform various operations like reading, writing, etc.
Syntax:

Fileobject = open (file-name, access-mode)

file-name: It specifies the name of the file to be opened.


access-mode: There are following access modes for opening a file:

access-mode Description

"w" Write - Opens a file for writing, creates the file if it does not exist.

PYTHON NOTES Page 95


access-mode Description

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

"w+" Open a file for updating (reading and writing), overwrite if the file exists.

"r+" Open a file for updating (reading and writing), doesn’t overwrite if the file exists.

In addition you can specify if the file should be handled as binary or text mode

access-mode Description

"t" Text - Default value. Text mode.

"b" - Binary - Binary mode (e.g. images)

Example:

fileptr = open("myfile.txt","r")
if fileptr:
print("file is opened successfully with read mode only")
Output:

file is opened successfully with read mode only


Example:

fileptr = open("myfile1.txt","x")
if fileptr:

PYTHON NOTES Page 96


print("new file was created successfully")
Output:

new file was created successfully

3.11. PYTHON FILE METHODS


• File object is created using open function and here is a list of functions which can be
called on this object.
• The built-in Python functions are pre-defined by the python interpreter.
• There are 68 built-in python functions. These functions perform a specific task and can
be used in any program, depending on the requirement of the user.

SL. No. Methods with Description

file.close()
1
Close the file. A closed file cannot be read or written any more.

file.flush()
2
Flush the internal buffer, like stdio'sfflush. This may be a no-op on some file-like objects.

file.fileno()
3
Returns the integer file descriptor that is used by the underlying implementation to request
I/O operations from the operating system.

file.isatty()
4
Returns True if the file is connected to a tty(-like) device, else False.

5 file.next()

PYTHON NOTES Page 97


Returns the next line from the file each time it is being called.

file.read([size])
6
Reads at most size bytes from the file (less if the read hits EOF before obtaining size bytes).

file.readline([size])
7
Reads one entire line from the file. A trailing newline character is kept in the string.

file.readlines([sizehint])

8 Reads until EOF using readline() and return a list containing the lines. If the optional
sizehint argument is present, instead of reading up to EOF, whole lines totalling
approximately sizehint bytes (possibly after rounding up to an internal buffer size) are read.

file.seek(offset[, whence])
9
Sets the file's current position

file.tell()
10
Returns the file's current position

file.truncate([size])
11
Truncates the file's size. If the optional size argument is present, the file is truncated to (at
most) that size.

file.write(str)
12
Writes a string to the file. There is no return value.

file.writelines(sequence)
13
Writes a sequence of strings to the file. The sequence can be any iterable object producing
strings, typically a list of strings.

• flush() method

The Python File flush() method flushes the internal buffer. This internal buffer is
maintained to speed up file operations.
PYTHON NOTES Page 98
For instance, whenever a write operation is performed on a file, the contents are first
written in the internal buffer; which is then transferred into the destination file once the buffer is
full. This is done to prevent frequent system calls for every write operation. And once the file is
closed, Python automatically flushes the buffer. But you may still want to flush the data before
closing any file.

Syntax
fileObject.flush();

Parameters

The method does not accept any parameters.


Return Value

This method does not return any value.

Example:

# Open a file
fo = open("foo.txt", "wb")
print("Name of the file: ", fo.name)

# Here it does nothing, but you can call it with read operation.
fo.flush()

# Close opened file

fo.close()

Output:
Name of the file: foo.txt

• fileno() method

The Python File fileno() method returns the file descriptor (or file handle) of an open
file. A file descriptor is an unsigned integer that is used by the operating system to identify the
open files in an os kernel. It only holds non-negative values.

PYTHON NOTES Page 99


The file descriptor acts just like the ID that is used to acquire a record stored in a
database. Therefore, Python uses it to perform various operations on the files; like opening a file,
writing into a file, reading from a file or closing a file etc.

Syntax
fileObject.fileno();

Parameters

The method does not accept any parameters.

Return Value

This method returns the integer file descriptor.

Example

The following example shows the usage of the Python File fileno() method. Here, we are trying
to open a file "foo.txt" in the writing binary(wb) mode using a file object. Then, the fileno()
method is called on this file object to retrieve the file descriptor referring to the current file.

# Open a file
fo = open("foo.txt", "wb")
print("Name of the file: ", fo.name)
fid = fo.fileno()
print("File Descriptor: ", fid)

# Close opened file


fo.close()
Output:
Name of the file: foo.txt
File Descriptor: 3

• readline() method

The Python File readline() method reads one entire line from the file. This method
appends a trailing newline character ('\n') at the end of the line read.

The readline() method also accepts an optional argument where one can specify the number
of bytes to be read from a line including the newline character. By default, this optional
argument will be 0, therefore, reading the entire line.

PYTHON NOTES Page 100


An empty string is returned only when EOF is encountered immediately.

Syntax
fileObject.readline(size);

Parameters
• size − This is the number of bytes to be read from the file.
Return Value

• This method returns the line read from the file.

Example

Let us use an existing file "foo.txt" to read a line from it using the Python File readline() method.
The contents in the foo.txt file are as follows −

This is 1st line


This is 2nd line
This is 3rd line
This is 4th line
This is 5th line

The following example shows the usage of readline() method on the demo file mentioned above.

# Open a file
fo = open("foo.txt", "r+")
print("Name of the file: ", fo.name)

# Assuming file has following 5 lines


# This is 1st line
# This is 2nd line
# This is 3rd line
# This is 4th line
# This is 5th line

line = fo.readline()
print("Read Line:", line)

PYTHON NOTES Page 101


# Close opened file
fo.close()
Output
Name of the file: foo.txt
Read Line: This is 1st line

• truncate() method

The Python File truncate() method truncates or shortens a file's size. In other words,
this method removes or deletes the contents of a file, and replaces them with some garbage (or
null) values to maintain the size. The size of this file is defaulted to the current position in it.

This method accepts an optional size argument where the file is truncated to (at most)
that size. The default value of this argument is the current file position. However, if the size
argument exceeds the current size of the file, the file is increased to that specified size by adding
either undefined content to the file, or zeroes. The result becomes platform-dependent.

Note − The truncate() method would not work in case a file is opened in read-only mode.

Syntax
fileObject.truncate(size)

Parameters
• size − (Optional) The size at which a file is to be truncated.

Return Value

This method does not return any value.

Example

Consider a demo file "foo.txt" containing strings.

This is 1st line


This is 2nd line
This is 3rd line
This is 4th line
This is 5th line

The following example shows the usage of the Python File truncate() method.

PYTHON NOTES Page 102


Open Compiler

# Open a file
fo = open("foo.txt", "w+")
print("Name of the file: ", fo.name)

# Assuming file has following 5 lines


# This is 1st line
# This is 2nd line
# This is 3rd line
# This is 4th line
# This is 5th line

line = fo.readline()
print("Read Line:", line)

# Now truncate remaining file.


fo.truncate()

# Try to read file now


line = fo.readline()
print("Read Line:", line)

# Close opened file


fo.close()
Output:
Name of the file: foo.txt
Read Line:
Read Line:

3.12. FILE BUILT-IN ATTRIBUTES

• The built-in class attributes provide us with information about the class.
• Using the dot (.) operator, we may access the built-in class attributes.

PYTHON NOTES Page 103


Attributes Description

__dict__ Dictionary containing the class namespace

__doc__ If there is a class documentation class, this


returns it. Otherwise, None

__name__ Class name.

__module__ Module name in which the class is defined.


This attribute is "__main__" in interactive
mode.

__bases__ A possibly empty tuple containing the base


classes, in the order of their occurrence in the
base class list.

Example 1: __dict__ Class Attribute

Here we are printing the dict of the class.

# creating a class say Tutorialspoint


class pythoncls:
'Welcome to Python'

def __init__(self):
print("The __init__ method")

# Printing the value of Built-in __dict__ attribute


print(pythoncls.__dict__)

PYTHON NOTES Page 104


Output

{'__module__': '__main__', '__doc__': 'Welcome to Python', '__init__': <function


pythoncls.__init__ at 0x7f1130c3f880>, '__dict__': <attribute '__dict__' of 'pythoncls' objects>,
'__weakref__': <attribute '__weakref__' of 'pythoncls' objects>}

Example 2: __doc__ Class Attribute

In the Python code below, we create a Tutorialspoint class with documentation.

Open Compiler
# creating a class say Tutorialspoint
class pythoncls:
'Welcome to Python'
def __init__(self):
print("The __init__ method")

# getting the documentation


# built-in __doc__ class attribute
print(pythoncls.__doc__)
Output:
Welcome to Python

Example 3: __name__ Class Attribute

In the Python code below, we print the name of the class using the __name__ class attribute

Open Compiler
class pythoncls:
'Welcome to Python'

def __init__(self):
print("The __init__ method")

# getting the name of the class using built-in __name__ class attribute
print(pythoncls.__name__)

PYTHON NOTES Page 105


Output:
Pythoncls

3.13. Standard files


In Python, there are several standard files and modules that are commonly used. These
files typically reside in the Python standard library, which provides a wide array of functions and
tools to handle tasks ranging from file input/output (I/O) to network programming, working with
data, and more. Here’s a breakdown of some standard files and modules that are commonly used
in Python:

3.13.1. Input and Output (I/O) Files

1. Text Files:
• Python's built-in `open()` function is used for reading from and writing to text files.

Common modes for `open()`:

❖ `'r'`: Read (default).


❖ `'w'`: Write (creates a new file or overwrites).
❖ `'a'`: Append (adds content at the end).
❖ `'b'`: Binary mode.

Example:

with open('file.txt', 'r') as f:

content = f.read()

2. CSV Files
• CSV (Comma Separated Values) files are used to store tabular data.
• Python's `csv` module provides methods to work with CSV files.

Example:

import csv

with open('file.csv', newline='') as f:

reader = csv.reader(f)

PYTHON NOTES Page 106


for row in reader:

print(row)

3. JSON Files
• JSON (JavaScript Object Notation) is commonly used for data exchange.
• Python’s `json` module allows for parsing and serializing JSON data.

Example:

import json

with open('file.json', 'r') as f:

data = json.load(f)

3.13.2. Configuration Files

INI Files - Often used to store configurations in sections, they are handled with the
`configparser` module.

Example:

import configparser

config = configparser.ConfigParser()

config.read('config.ini')

3.13.3. Log Files

Logging

• Python provides a built-in `logging` module for writing log files.


• Log files are often used for tracking application behavior or errors.

Example:

import logging

logging.basicConfig(filename='app.log', level=logging.DEBUG)

PYTHON NOTES Page 107


logging.debug('This is a debug message')

3.13.4. Pickle Files

Pickling

• Python has a `pickle` module for serializing and deserializing Python objects to/from
files.
• Useful for saving and loading complex Python objects.

Example:

import pickle

data = {'name': 'Alice', 'age': 30}

with open('data.pkl', 'wb') as f:

pickle.dump(data, f)

with open('data.pkl', 'rb') as f:

loaded_data = pickle.load(f)

3.13.5. Standard Library Modules

Here are a few commonly used standard Python modules (files) from the standard library:

• os: Provides functions to interact with the operating system, such as file manipulation,
directories, and environment variables.

Example:

import os

os.mkdir('new_folder') # Create a new directory

• sys: Provides access to system-specific parameters and functions, such as command-


line arguments and exiting the program.

Example:

PYTHON NOTES Page 108


import sys

print(sys.argv) # Print command-line arguments

• math: Contains mathematical functions like trigonometry, logarithms, and constants


like `pi` and `e`.

Example:

import math

print(math.sqrt(16)) # Output: 4.0

• datetime: Used for manipulating dates and times.

Example:

from datetime import datetime

now = datetime.now()

print(now) # Current date and time

• random: Provides functions for generating random numbers and performing random
operations.

Example:

import random

print(random.randint(1, 10)) # Random integer between 1 and 10

• re: Provides regular expression matching operations.

Example:

import re

PYTHON NOTES Page 109


pattern = r'\d+'

text = "There are 123 apples."

match = re.search(pattern, text)

print(match.group()) # Output: 123

• subprocess: Allows interaction with system processes (executing shell commands).

Example:

import subprocess

subprocess.run(['ls', '-l'])

3.14. Command Line Arguments

There are many options to read python command line arguments. The three most common ones
are:

1. Python sys.argv
2. Python getopt module
3. Python argparse module

Python sys module


Python sys module stores the command line arguments into a list, we can access it
using sys.argv. This is very useful and simple way to read command line arguments as String.
Let’s look at a simple example to read and print command line arguments using python sys
module.

import sys

print(type(sys.argv))
print('The command line arguments are:')
for i in sys.argv:
print(i)
Below image illustrates the output of a sample run of above program.

PYTHON NOTES Page 110


Python getopt module

Python getopt module is very similar in working as the C getopt() function for parsing
command-line parameters. Python getopt module is useful in parsing command line arguments
where we want user to enter some options too. Let’s look at a simple example to understand this.
import getopt
import sys

argv = sys.argv[1:]
try:
opts, args = getopt.getopt(argv, 'hm:d', ['help', 'my_file='])
print(opts)
print(args)
except getopt.GetoptError:
# Print a message or do something useful
print('Something went wrong!')
sys.exit(2)
Above example is very simple, but we can easily extend it to do various things. For example, if
help option is passed then print some user friendly message and exit. Here getopt module will
automatically parse the option value and map them. Below image shows a sample run.

Python argparse module

Python argparse module is the preferred way to parse command line arguments. It provides a lot
of option such as positional arguments, default value for arguments, help message, specifying
data type of argument etc. At the very simplest form, we can use it like below.

import argparse

parser = argparse.ArgumentParser()
parser.parse_args()

PYTHON NOTES Page 111


Below is the output from quick run of above script.

5 MARK

Explain about the Dictionaries?


Discuss about the mapping type operators?
Write about Conditional and loops?
Discuss the for statements?

10 MARK

Explain about the files and input/output with example?


Discuss the file built in attributes?
Write about the file build in function and methods?

*****************UNIT III COMPLETED*****************

UNIT – IV

4.1. FUNCTIONAL PROGRAMMING IN PYTHON


• Functional programming is a programming paradigm in which we try to bind everything
in pure mathematical functions style. It is a declarative type of programming style.
• Its main focus is on “what to solve” in contrast to an imperative style where the main
focus is “how to solve“.
• It uses expressions instead of statements.
• An expression is evaluated to produce a value whereas a statement is executed to assign
variables.

PYTHON NOTES Page 112


Concepts of Functional Programming
Pure Functions: These functions have two main properties. First, they always produce the same
output for the same arguments irrespective of anything else. Secondly, they have no side-effects
i.e. they do modify any argument or global variables or output something.

Recursion: There are no “for” or “while” loop in functional languages. Iteration in functional
languages is implemented through recursion.

Functions are First-Class and can be Higher-Order: First-class functions are treated as first-
class variable. The first-class variables can be passed to functions as a parameter, can be returned
from functions or stored in data structures.

Variables are Immutable: In functional programming, we can’t modify a variable after it’s
been initialized. We can create new variables – but we can’t modify existing variables.

Example,

# Python program to demonstrate

# pure functions

# A pure function that does Not

# changes the input list and

# returns the new List

def pure_func(List):

New_List = []

for i in List:

New_List.append(i**2)

return New_List

# Driver's code

Original_List = [1, 2, 3, 4]

Modified_List = pure_func(Original_List)

PYTHON NOTES Page 113


print("Original List:", Original_List)

print("Modified List:", Modified_List)

Output,

Original List: [1, 2, 3, 4]


Modified List: [1, 4, 9, 16]
4.2. FUNCTIONS
Python Functions is a block of statements that return the specific task. The idea is to
put some commonly or repeatedly done tasks together and make a function so that instead of
writing the same code again and again for different inputs, we can do the function calls to reuse
code contained in it over and over again.

Some Benefits of Using Functions

• Increase Code Readability


• Increase Code Reusability

Python Function Declaration

Types of Functions in Python

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

Example,

# A simple Python function

def fun():

print("Welcome to GFG")

PYTHON NOTES Page 114


4.3. CALLING A PYTHON FUNCTION

After creating a function in Python we can call it by using the name of the function followed by
parenthesis containing parameters of that particular function.

Example,

# A simple Python function

def fun():

print("Welcome to GFG")

# Driver code to call a function

fun()

Output:

Welcome to GFG

4.4. CREATING FUNCTION


• Use the keyword def to declare the function and follow this up with the function name.
• Add parameters to the function: they should be within the parentheses of the function.
End your line with a colon.
• Add statements that the functions should execute.
Example,
def my_function():
print("Hello from a function")

4.5. PASSING FUNCTIONS


A function can take multiple arguments, these arguments can be objects, variables(of
same or different data types) and functions.
Python functions are first class objects. In the example below, a function is assigned
to a variable. This assignment doesn’t call the function. It takes the function object referenced by
shout and creates a second name pointing to it, yell.
Example,
# Python program to illustrate functions

# can be treated as objects

def shout(text):

PYTHON NOTES Page 115


return text.upper()

print(shout('Hello'))

yell = shout

print(yell('Hello'))

Output,
HELLO
HELLO

4.6 BUILD IN FUNCTION

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.

1.map() - Python's map() method applies a specified function to each item of an iterable (such as
a list, tuple, or string) and then returns a new iterable containing the results.

The map() syntax is as follows:

map(function, iterable)

The first argument passed to the map function is itself a function, and the second argument
passed is an iterable (sequence of elements) such as a list, tuple, set, string, etc.

Example - usage of the map():

# Using map() to square each element of the data list


data = [1, 2, 3, 4, 5]

# Map function returns the map object


squares = map(lambda x: x*x, data)

# Iterating the elements of the squares


for i in squares:
print(i, end=" ")

# Also, we can convert the map object into a list


squares = list(map(lambda x: x*x, data))
print(f"Squares: {squares}")
Output:

PYTHON NOTES Page 116


1, 4, 9, 16, 25
Squares: [1, 4, 9, 16, 25]

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.

The syntax for the filter() is as follows:

filter(function, iterable)

Here also, the first argument passed to the filter function is itself a function, and the second
argument passed is an iterable (sequence of elements) such as a list, tuple, set, string, etc.

Example - usage of the filter():

You are given a list of integers and should filter the even numbers from the list.

# Using filter() to filter even numbers from a list


data = [1, 2, 3, 4, 5]
# The filter function filters the even numbers from the data
# and returns a filter object (an iterable)
evens = filter(lambda x: x % 2 == 0, data)
# Iterating the values of evens
for i in evens:
print(i, end=" ")
# We can convert the filter object into a list as follows:
evens = list(filter(lambda x: x % 2 == 0, data))

# Printing the evens list


print(f"Evens = {evens}")

Output:

24
Evens = [2, 4]

PYTHON NOTES Page 117


3. reduce() - In Python, reduce() is a built-in function that applies a given function to the
elements of an iterable, reducing them to a single value.

The syntax for reduce() is as follows:

reduce(function, iterable[, initializer])

The function argument is a function that takes two arguments and returns a single value. The
first argument is the accumulated value, and the second argument is the current value from the
iterable.

The iterable argument is the sequence of values to be reduced.

The optional initializer argument is used to provide an initial value for the accumulated result. If
no initializer is specified, the first element of the iterable is used as the initial value.

Here's an example that demonstrates how to use reduce() to find the sum of a list of numbers:

Example 1:

You are given a list containing some integers and you should find the sum of all elements in the
list using reduce function. Below is the solution of the problem:

# Examples to understand the reduce() function


from functools import reduce

# Function that returns the sum of two numbers


def add(a, b):
return a + b

# Our Iterable
num_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

# add function is passed as the first argument, and num_list is passed as the second argument
sum = reduce(add, num_list)
print(f"Sum of the integers of num_list : {sum}")

# Passing 10 as an initial value


sum = reduce(add, num_list, 10)
print(f"Sum of the integers of num_list with initial value 10 : {sum}")
Output:

Sum of the integers of num_list : 55

PYTHON NOTES Page 118


Sum of the integers of num_list with initial value 10 : 65

4.apply():The apply() method is one of the most common methods of data preprocessing. It
simplifies applying a function on each element in a pandas Series and each row or column in a
pandas DataFrame. In this tutorial, we'll learn how to use the apply() method in pandas — you'll
need to know the fundamentals of Python and lambda functions. If you aren't familiar with these
or need to brush up your Python skills, you might like to try our free Python Fundamentals
course.

Applying a Function on a Pandas Series

Series form the basis of pandas. They are essentially one-dimensional arrays with axis labels
called indices.There are different ways of creating a Series object (e.g., we can initialize a Series
with lists or dictionaries). Let’s define a Series object with two lists containing student names as
indices and their heights in centimeters as data:

import pandas as pd
import numpy as np
from IPython.display import display

students = pd.Series(data=[180, 175, 168, 190],


index=['Vik', 'Mehdi', 'Bella', 'Chriss'])
display(students)
print(type(students))

OUTPUT:
Vik 180
Mehdi 175
Bella 168
Chriss 190
dtype: int64
4.7. MODULES
In Python, Modules are simply files with the “. py” extension containing Python code that can be
imported inside another Python Program. In simple terms, we can consider a module to be the

PYTHON NOTES Page 119


same as a code library or a file that contains a set of functions that you want to include in your
application.

MODULES AND FILES

What is Python Module


A Python module is a file containing Python definitions and statements. A module can define
functions, classes, and variables. A module can also include runnable code.
Grouping related code into a module makes the code easier to understand and use. It also
makes the code logically organized.

Create a Python Module


To create a Python module, write the desired code and save that in a file with .py extension.
Let’s understand it better with an example:
Example:
Let’s create a simple calc.py in which we define two functions, one add and another subtract.
# A simple module, calc.py

def add(x, y):

return (x+y)

def subtract(x, y):

return (x-y)

Import module in Python


We can import the functions, and classes defined in a module to another module using
the import statement in some other Python source file.
When the interpreter encounters an import statement, it imports the module if the
module is present in the search path.
For example, to import the module calc.py, we need to put the following command at the top of
the script.
Syntax to Import Module in Python
import module

Note: This does not import the functions or classes directly instead imports the module only. To
access the functions inside the module the dot(.) operator is used.

Importing modules in Python Example


Now, we are importing the calc that we created earlier to perform add operation.
# importing module calc.py

import calc

PYTHON NOTES Page 120


print(calc.add(10, 2))

Output:
12

pydoc

You can use pydoc to search through the Python libraries installed on your system. At
the command prompt type.

$ pydoc -g

and the following will appear:

Documentation for most modules contains three color coded sections:

• Classes in pink
• Functions in orange
• Data in green

The keyword module contains a single function, iskeyword, which as its name suggests is a
boolean function that returns True if a string passed to it is a keyword:

>>>fromkeywordimport*
>>>iskeyword('for')
True
>>>iskeyword('all')
False
>>>

4.8. MODULES BUILD IN FUNCTIONS

PYTHON NOTES Page 121


Python is one of the most popular programming languages because of its vast collection
of modules which make the work of developers easy and save time from writing the code for a
particular task for their program. Python provides various types of modules which include
Python built-in modules and external modules. In this article, we will learn about the built-in
modules in Python and how to use them.
What are Python Built-in modules?
Python built-in modules are a set of libraries that come pre-installed with the Python
installation. It will become a tedious task to install any required modules in between the
process of development that's why Python comes with some most used modules required.
These modules provide a wide range of functionalities, from file operations and system-
related tasks to mathematical computations and web services. The use of these modules
simplifies the development process, as developers can leverage the built-in functions and
classes for common tasks, providing code reusability, and efficiency. Some examples of
Python built-in modules include "os", "sys", "math", and "datetime".
We can run the below command to get the all available modules in Python:
help('modules')

PYTHON NOTES Page 122


Advantages of built-in modules in Python
• Reduced Development Time
Built-in modules in Python are made to perform various tasks that are used without
installing external module or writing the lengthy code to perform that specific task. So,
developers used them according to their convenience to save the time.
• Optimized Performance
Some Python built-in modules are optimized for performance, using low-level code or
native bindings to execute tasks efficiently.
• Reliability
These modules have been rigorously tested and have been in use by the Python
community for years. As a result, they are typically stable and have fewer bugs compared to new
or less well-known third-party libraries.
• Consistency

PYTHON NOTES Page 123


Python Built-in modules provide consistent way to solve problems. Developers familiar
with these modules can easily understand and collaborate on codebases across different projects.
• Standardization
As these modules are part of the Python Standard Library, they establish a standard way
of performing tasks.
• Documentation
Python's official documentation is comprehensive and includes detailed explanations
and examples for Python built-in modules. This makes it easier to learn and utilize them.
• Maintainability
Python Built-in modules are maintained by the core Python team and community,
regular updates, bug fixes, and improvements are to be expected, ensuring long-term viability.
• Reduced Risk
Using third-party libraries can introduce risks, like discontinued support or security
vulnerabilities.

Using Built-in Modules in Python


I. JSON Module in Python
"json" module in Python is used to encode and decode JSON data. JSON format is a
widely used on the web to exchange the information. It is extremely useful for reading and
writing data in the JSON format.
Example:
In the below example, we have used json module to convert the Python dictionary into JSON
format. Firstly, we import the "json" module and then define the Python dictionary after that we
convert the Python dictionary into JSON format using "json.dumps()" method of "json" module
in Python and finally print the JSON data.

import json

data = {

&quot;name&quot;: &quot;Jonny&quot;,

&quot;age&quot;: 30,

&quot;is_student&quot;: True,

&quot;courses&quot;: [&quot;Web Dev&quot;, &quot;CP&quot;]

json_string = json.dumps(data, indent=4)

PYTHON NOTES Page 124


print(json_string)

Output
{
"name": "Jonny",
"age": 30,
"is_student": true,
"courses": [
"Web Dev",
"CP"
]
}
II. Tkinter module in Python
"tkinter" is the standard GUI (Graphical User Interface) library in
Python. "tkinter" module is used to create windows, buttons, text boxes, and other UI elements
for desktop applications.
Example
Firstly we imports the "tkinter" module as "tk" and defines a function, "on_button_click",
which updates a label's text. A main GUI window titled "Tkinter Example" is created,
containing a label and a button. The label displays "Click the button below", and the button,
labeled "Click Me", triggers the previously defined function when pressed. The application
remains responsive to user interactions by using the "root.mainloop()" event loop, allowing the
label's message to change upon button clicks.

import tkinter as tk

def on_button_click():

label.config(text=&quot;Hello, Geeks!&quot;)

root = tk.Tk()

root.title(&quot;Tkinter Example&quot;)

label = tk.Label(root, text=&quot;Click the button below&quot;)

label.pack(pady=40)

button = tk.Button(root, text=&quot;Click Me&quot;, command=on_button_click)

PYTHON NOTES Page 125


button.pack(pady=40)

root.mainloop()

III. Random module in Python


The "random" module in Python is used to generates random numbers and provides
the functionality of various random operations such as 'random.randint()', 'random.choice()',
'random.random()', 'random.shuffle()' and many more.
Example
In the below code, firstly we import the random module, then we are printing the the random
number from "1 to 10" and random item from the list by
using random.randint() and random.choice() methods of random module respectively.

import random
num = random.randint(1, 10)
print(f&quot;Random integer between 1 and 10: {num}&quot;)
fruits = [&quot;Java&quot;, &quot;C&quot;, &quot;C++&quot;, &quot;Python&quot;]
chosen_fruit = random.choice(fruits)
print(f&quot;Randomly chosen language: {chosen_fruit}&quot;)

Output
Random integer between 1 and 10: 9
Randomly chosen language: Python

PYTHON NOTES Page 126


4.9. CLASSES

• A class is a user-defined blueprint or prototype from which objects are created.


• Classes provide a means of bundling data and functionality together.
• Creating a new class creates a new type of object, allowing new instances of that type to
be made.
• Each class instance can have attributes attached to it for maintaining its state. Class
instances can also have methods (defined by their class) for modifying their state.
• To understand the need for creating a class and object in Python let’s consider an
example, let’s say you wanted to track the number of dogs that may have different
attributes like breed and age.

If a list is used, the first element could be the dog’s breed while the second element
could represent its age. Let’s suppose there are 100 different dogs, then how would you know
which element is supposed to be which? What if you wanted to add other properties to these
dogs? This lacks organization and it’s the exact need for classes.

Creating a Python Class

Here, the class keyword indicates that you are creating a class followed by the name of the class
(Dog in this case).

EXAMPLE

# a class

class Dog:

# A simple class

classDog:

sound ="bark"

# attribute

attr1 = "mammal"

attr2 = "dog"

PYTHON NOTES Page 127


# A sample method

def fun(self):

print("I'm a", self.attr1)

print("I'm a", self.attr2)

# Driver code

# Object instantiation

Rodger = Dog()

# Accessing class attributes

# and method through objects

print(Rodger.attr1)

Rodger.fun()

4.10. CLASS ATTRIBUTES

• Attributes are defined within a class and can be accessed and modified by both the class
and its objects.
• In Python, class attributes are defined directly within the class definition and are shared
among all instances of the class.
• They can be accessed using the class name and through an instance of the class.

EXAMPLE PROGRAM

class sampleclass:

count = 0 # class attribute

def increase(self):

sampleclass.count += 1

# Calling increase() on an object

s1 = sampleclass()

PYTHON NOTES Page 128


s1.increase()

print(s1.count)

# Calling increase on one more

# object

s2 = sampleclass()

s2.increase()

print(s2.count)

print(sampleclass.count)

OUTPUT

1
2
2

4.11. INSTANCE

Unlike class attributes, instance attributes are not shared by objects.

Every object has its own copy of the instance attribute (In case of class attributes all object refer
to single copy).

To list the attributes of an instance/object, we have two functions:-


1. vars()– This function displays the attribute of aninstance in the form of an dictionary.
2. dir()– This function displays more attributes than vars function,as it is not limited to instance.
It displays the class attributes as well. It also displays the attributes of its ancestor

classes.

# Python program to demonstrate


# instance attributes.
classemp:
def__init__(self):
self.name ='xyz'

PYTHON NOTES Page 129


self.salary =4000

defshow(self):
print(self.name)
print(self.salary)

e1 =emp()
print("Dictionary form :", vars(e1))
print(dir(e1))
Output

Dictionary form :{'salary': 4000, 'name': 'xyz'}

['__doc__', '__init__', '__module__', 'name', 'salary', 'show']

5 MARK:

Explain about the Functional programming?

Write about the creating functions?

Discuss the modules?

10 MARK:

Explain about the Build in functions with example?

Write about the Modules with files?

********UNIT IV COMPLETED********

PYTHON NOTES Page 130


UNIT – V

5.1. Introduction
In any application, there is a need for persistent storage. Generally, there are three
basic storage mechanisms: files, a relational database system (RDBMS), or some sort of hybrid,
i.e., an API (application programmer interface) that "sits on top of" one of those existing
systems, an object relational mapper (ORM), file manager, spreadsheet, configuration file, etc.

In an earlier chapter, we discussed persistent storage using both plain file access as
well as a Python and DBM overlay on top of files, i.e., *dbm, dbhash/bsddb files, shelve
(combination of pickle and DBM), and using their dictionary-like object interface. This chapter
will focus on using RDBMSs for the times when files or writing your own system does not
suffice for larger projects.

5.2. Basic Database Operations and SQL


Before we dig into databases and how to use them with Python, we want to present a
quick introduction (or review if you have some experience) to some elementary database
concepts and the Structured Query Language (SQL).

Underlying Storage
Databases usually have a fundamental persistent storage using the file system, i.e., normal
operating system files, special operating system files, and even raw disk partitions.

User Interface
Most database systems provide a command-line tool with which to issue SQL commands
or queries. There are also some GUI tools that use the command-line clients or the database
client library, giving users a much nicer interface.

Databases
An RDBMS can usually manage multiple databases, e.g., sales, marketing, customer
support, etc., all on the same server (if the RDBMS is server-based; simpler systems are usually
not). In the examples we will look at in this chapter, MySQL is an example of a server-based

PYTHON NOTES Page 131


RDBMS because there is a server process running continuously waiting for commands while
neither SQLite nor Gadfly have running servers.

Components
The table is the storage abstraction for databases. Each row of data will have fields that
correspond to database columns. The set of table definitions of columns and data types per table
all put together define the database schema.

Databases are created and dropped. The same is true for tables. Adding new rows to a database is
called inserting, changing existing rows in a table is called updating, and removing existing rows
in a table is called deleting. These actions are usually referred to as database commands or
operations.

Requesting rows from a database with optional criteria is called querying. each resulting row.
Some databases use the concept of a cursor for issuing SQL commands, queries, and grabbing
results, either all at once or one row at a time.

SQL
Database commands and queries are given to a database by SQL. Not all databases use
SQL, but the majority of relational databases do. Here are some examples of SQL commands.
Most databases are configured to be caseinsensitive, especially database commands. The
accepted style is to use CAPS for database keywords. Most command-line programs require a
trailing semicolon ( ; ) to terminate a SQL statement.

1.Creating a Database

CREATE DATABASE test;

GRANT ALL ON test.* to user(s);

The first line creates a database named "test," and assuming that you are a database
administrator, the second line can be used to grant permissions to specific users (or all of them)
so that they can perform the database operations below.

2.Using a Database
USE test;

If you logged into a database system without choosing which database you want to use, this
simple statement allows you to specify one with which to perform database operations.

PYTHON NOTES Page 132


3.Dropping a Database
DROP DATABASE test;

This simple statement removes all the tables and data from the database and deletes it from the
system.

4.Creating a Table

CREATE TABLE users (login VARCHAR(8), uid INT, prid INT);

This statement creates a new table with a string column login and a pair of integer fields uid and
prid.

5.Dropping a Table
DROP TABLE users;

This simple statement drops a database table along with all its data.

6.Inserting a Row
INSERT INTO users VALUES('leanna', 311, 1);

You can insert a new row in a database with the INSERT statement. Specify the table and the
values that go into each field. For our example, the string 'leanna' goes into the login field, and
311 and 1 to uidandprid, respectively.

7.Updating a Row
UPDATE users SET prid=4 WHERE prid=2;

UPDATE users SET prid=1 WHERE uid=311;

To change existing table rows, you use the UPDATE statement. Use SET for the columns that
are changing and provide any criteria for determining which rows should change. In the first
example, all users with a "project ID" or prid of 2 will be moved to project #4. In the second
example, we take one user (with a UID of 311) and move them to project #1.

8.Deleting a Row
DELETE FROM users WHERE prid=%d;

DELETE FROM users;

PYTHON NOTES Page 133


To delete a table row, use the DELETE FROM command, give the table you want to delete rows
from, and any optional criteria. Without it, as in the second example, all rows will be deleted.

Now that you are up to speed on basic database concepts, it should make following the rest of the
chapter and its examples much easier. If you need additional help, there are plenty of database
books out in the market that you can check out.

5.2.3. Databases and Python


We are going to cover the Python database API and look at how to access relational databases
from Python, either directly through a database interface, or via an ORM, and how you can
accomplish the same task but without necessarily having to give explicitly commands in SQL.

Topics such as database principles, concurrency, schema, atomicity, integrity, recovery, proper
complex left JOINs, triggers, query optimization, transactions, stored procedures, etc., are all
outside the scope of this text, and we will not be discussing these in this chapter other than direct
use from a Python application. There are plenty of resources you can refer to for general
information. Rather, we will present how to store and retrieve data to/from RDBMSs while
playing within a Python framework. You can then decide which is best for your current project
or application and be able to study sample code that can get you started instantly. The goal is to
get you up to speed as quickly as possible if you need to integrate your Python application with
some sort of database system.

We are also breaking out of our mode of covering only the "batteries included" features of the
Python standard library. While our original goal was to play only in that arena, it has become
clear that being able to work with databases is really a core component of everyday application
development

5.3 Examples of Using Database Adapters


MySQL

Use MySQL as the example here, along with the only MySQL Python adapter:

MySQLdb, aka MySQL-python. In the various bits of code, we will also show you (deliberately)
examples of error situations so that you have an idea of what to expect, and what you may wish
to create handlers for.

First log in as an administrator to create a database and grant permissions, then log back in as a
normal client.

>>> import MySQLdb

PYTHON NOTES Page 134


>>>cxn = MySQLdb.connect(user='root')

>>>cxn.query('DROP DATABASE test')

Traceback (most recent call last):

File "<stdin>", line 1, in ?

_mysql_exceptions.OperationalError: (1008, "Can't drop database 'test'; database doesn't exist")

>>>cxn.query('CREATE DATABASE test')

>>>cxn.query("GRANT ALL ON test.* to ''@'localhost'")

>>>cxn.commit()

>>>cxn.close()

In the code above, we did not use a cursor. Some adapters have Connection objects, which can
execute SQL queries with the query() method, but not all. We recommend you either not use it or
check your adapter to make sure it is available.

The commit() was optional for us as auto-commit is turned on by default in MySQL. We then
connect back to the new database as a regular user, create a table, and perform the usual queries
and commands using SQL to get our job done via Python. This time we use cursors and their
execute()method.

The next set of interactions shows us creating a table. An attempt to create it again (without first
dropping it) results in an error.

>>>cxn = MySQLdb.connect(db='test')

>>> cur = cxn.cursor()

>>>cur.execute('CREATE TABLE users(login VARCHAR(8), uid INT)') last bit features


updating the table, either updating or deleting rows.

>>>cur.execute("UPDATE users SET uid=7100 WHERE uid=7001") 1L

>>>cur.execute("SELECT * FROM users")

3L

>>> for data in cur.fetchall():

... print '%s\t%s' % data

PYTHON NOTES Page 135


...

john 7000 jane 7100 bob 7200

>>>cur.execute('DELETE FROM users WHERE login="bob"')

1L

>>>cur.execute('DROP TABLE users')

0L

>>>cur.close()

>>>cxn.commit()

>>>cxn.close()

MySQL is one of the most popular open source databases in the world, and it is no surprise that a
Python adapter is available for it. Keep in mind that no database modules are available in the
Python standard libraryall adapters are third-party packages that have to be downloaded and
installed separately from Python. Please see the References section toward the end of the chapter
to find out how to download it.

PostgreSQL
Another popular open source database is PostgreSQL. Unlike MySQL, there are no less
than three current Python adapters available for Postgres: psycopg, PyPgSQL, and PyGreSQL. A
fourth, PoPy, is now defunct, having contributed its project to combine with that of PyGreSQL
back in 2003. Each of the three remaining adapters has its own characteristics, strengths, and
weaknesses, so it would be a good idea to practice due diligence to determine which is right for
you.

The good news is that the interfaces are similar enough that you can create an application that,
say, measures the performance between all three (if that is a metricthat is important to you). Here
we show you the setup code to get a Connection object for each: psycopg

SQLite
For extremely simple applications, using files for persistent storage usually
suffices, but the most complex and data-driven applications demand a full relational
database. SQLite targets the intermediate systems and indeed is a hybrid of the two. It is
extremely lightweight and fast, plus it is serverless and requires little or no administration.
SQLite has seen a rapid growth in popularity, and it is available on many

PYTHON NOTES Page 136


platforms. With the introduction of the pysqlite database adapter in Python 2.5 as the
sqlite3 module, this marks the first time that the Python standard library has featured a
database adapter in any release.
It was bundled with Python not because it was favored over other databases and
adapters, but because it is simple, uses files (or memory) as its backend store like the
DBM modules do, does not require a server, and does not have licensing issues. It is
simply an alternative to other similar persistent storage solutions included with Python but
which happens to have a SQL interface.
Having a module like this in the standard library allows users to develop rapidly in
Python using SQLite, then migrate to a more powerful RDBMS such as MySQL,
PostgreSQL, Oracle, or SQL Server for production purposes if this is their intention.
Otherwise, it makes a great solution to stay with for those who do not need all that
horsepower.
Although the database adapter is now provided in the standard library, you still
have to download the actual database software yourself. However, once you have installed
it, all you need to do is start up
Python (and import the adapter) to gain immediate access:
>>> import sqlite3
>>> cxn = sqlite3.connect('sqlite_test/test')
>>> cur = cxn.cursor()
>>> cur.execute('CREATE TABLE users(login VARCHAR(8), uid
INTEGER)')
>>> cur.execute('INSERT INTO users VALUES("john", 100)')
>>> cur.execute('INSERT INTO users VALUES("jane", 110)')
>>> cur.execute('SELECT * FROM users')
>>> for eachUser in cur.fetchall():
... print eachUser
...
(u'john', 100)
(u'jane', 110)
>>> cur.execute('DROP TABLE users')
<sqlite3.Cursor object at 0x3d4320>
>>> cur.close()
>>> cxn.commit()
>>> cxn.close()

PYTHON NOTES Page 137


Okay, enough of the small examples. Next, we look at an application similar to our
earlier example withMySQL, but which does a few more things:

● Creates a database (if necessary)


● Creates a table
● Inserts rows into the table
● Updates rows in the table
● Deletes rows from the table
● Drops the table
For this example, we will use two other open source databases. SQLite has
becomequite popular of late.
It is very small, lightweight, and extremely fast for all the most common
database functions. Another database involved in this example is Gadfly, a mostly
SQL-compliant RDBMS written entirely in Python.
Some notes before we get to the code. Both SQLite and Gadfly require the user to
give the location to store database files (while MySQL has a default area and does not
require this information from the use). The most current incarnation of Gadfly is not yet
fully DB-API 2.0 compliant, and as a result.

5.4 Database Adapter Example Application


In the example below, we want to demonstrate how to use Python to access a database. In
fact, for variety, we added support for three different database systems: Gadfly, SQLite, and
MySQL. We are going to create a database (if one does not already exist), then run through
various database operations such as creating and dropping tables, and inserting, updating, and
deleting rows. Example will be duplicated for the upcoming section on ORMs as well.

Example . Database Adapter Example (ushuffle_db.py)

This script performs some basic operations using a variety of databases (MySQL, SQLite,
Gadfly) and a corresponding Python database adapter.

#!/usr/bin/env python

import os

from random import randrange as rrange

PYTHON NOTES Page 138


COLSIZ = 10

RDBMSs = {'s': 'sqlite', 'm': 'mysql', 'g': 'gadfly'}

DB_EXC = None

def setup():

return RDBMSs[raw_input('''

Choose a database system:

(M)ySQL

(G)adfly

(S)QLite

Enter choice: ''').strip().lower()[0]]

def connect(db, dbName):

global DB_EXC

dbDir = '%s_%s' % (db, dbName) if db == 'sqlite':

try:

import sqlite3

except ImportError, e:

try:

from pysqlite2 import dbapi2 as sqlite3

except ImportError, e:

return None

DB_EXC = sqlite3

if not os.path.isdir(dbDir):

os.mkdir(dbDir)

PYTHON NOTES Page 139


cxn = sqlite.connect(os.path.join(dbDir, dbName))

elifdb == 'mysql':

try:

import MySQLdb

import _mysql_exceptions as DB_EXC

except ImportError, e:

return None

try:

cxn = MySQLdb.connect(db=dbName)

except _mysql_exceptions.OperationalError, e:

cxn = MySQLdb.connect(user='root')

try:

cxn.query('DROP DATABASE %s' % dbName)

except DB_EXC.OperationalError, e:

pass

cxn.query('CREATE DATABASE %s' % dbName)

cxn.query("GRANT ALL ON %s.* to ''@'localhost'" % dbName)

cxn.commit()

cxn.close()

cxn = MySQLdb.connect(db=dbName)

elifdb == 'gadfly':

try:

from gadfly import gadfly

DB_EXC = gadfly

PYTHON NOTES Page 140


except ImportError, e:

return None

try:

cxn = gadfly(dbName, dbDir)

except IOError, e:

cxn = gadfly()

if not os.path.isdir(dbDir):

os.mkdir(dbDir)

cxn.startup(dbName, dbDir)

else:

return None

return cxn

def create(cur):

try

cur.execute('''

CREATE TABLE users (

login

5.5 Mysql - Regular Expression

MySQL supports various types of pattern matching operations to retrieve filtered result-sets from
huge database tables. In previous chapters, we have already learned about the LIKE operator for
pattern matching. In this chapter, we will see another pattern matching operation based on
regular expressions.

MySQL Regular Expressions

A regular expression is loosely defined as a sequence of characters that represent a pattern in an


input text. It is used to locate or replace text strings using some patterns; this pattern can either
be a single character, multiple characters or words, etc.

PYTHON NOTES Page 141


MySQL implements regular expression support using International Components for Unicode
(ICU), which provides full Unicode support and is multi-byte safe.

In MySQL, it is a powerful way to perform a complex search operations in a database to retrieve


desired content. And unlike the LIKE operator, the regular expressions are not restricted on
search patterns (like % and _) as they use several other meta characters to expand the flexibility
and control during pattern matching. This is performed using the REGEXP operator.

Syntax

Following is the basic syntax of the REGEXP operator in MySQL −

expression REGEXP pattern

Patterns used with REGEXP

Following is the table of pattern, which can be used along with the REGEXP operator

Pattern What the pattern matches

^ Beginning of string

$ End of string

. Any single character

[...] Any character listed between the square brackets

[^...] Any character not listed between the square brackets

p1|p2|p3 Alternation; matches any of the patterns p1, p2, or p3

* Zero or more instances of preceding element

PYTHON NOTES Page 142


+ One or more instances of preceding element

{n} n instances of preceding element

{m,n} m through n instances of preceding element

[A-Z] Any uppercase letter

[a-z] Any lowercase letter

[0-9] Any digit (from 0 to 9)

[[:<:]] Beginning of words

[[:>:]] Ending of words

[:class:] A character class, i.e. use [:alpha:] to match letters from the alphabet

Examples

The following example demonstrates the usage of some patterns mentioned in the table above,
along with the REGEXP operator. For that, we are first creating a database table to perform the
search on.

Assume we are creating a table called CUSTOMERS using the following query −

CREATE TABLE CUSTOMERS (


ID INT AUTO_INCREMENT,
NAME VARCHAR(20) NOT NULL,
AGE INT NOT NULL,
ADDRESS CHAR (25),
SALARY DECIMAL (18, 2),
PRIMARY KEY (ID)
);

PYTHON NOTES Page 143


Now, insert some values into it using the INSERT statements given below −

INSERT INTO CUSTOMERS (ID,NAME,AGE,ADDRESS,SALARY) VALUES


(1, 'Ramesh', 32, 'Ahmedabad', 2000.00 ),
(2, 'Khilan', 25, 'Delhi', 1500.00 ),
(3, 'Kaushik', 23, 'Kota', 2000.00 ),
(4, 'Chaitali', 25, 'Mumbai', 6500.00 ),
(5, 'Hardik', 27, 'Bhopal', 8500.00 ),
(6, 'Komal', 22, 'Hyderabad', 4500.00 ),
(7, 'Muffy', 24, 'Indore', 10000.00 );

Execute the following query to display all the records present in above created table −

SELECT * FROM CUSTOMERS

Following are the records present in CUSTOMERS table −

ID NAME AGE ADDRESS SALARY

1 Ramesh 32 Ahmedabad 2000.00

2 Khilan 25 Delhi 1500.00

3 Kaushik 23 Kota 2000.00

4 Chaitali 25 Mumbai 6500.00

5 Hardik 27 Bhopal 8500.00

6 Komal 22 Hyderabad 4500.00

7 Muffy 24 Indore 10000.00

REGEXP with Patterns −

Now, we are finding all the records in the CUSTOMERS table whose name starts with 'k' −

PYTHON NOTES Page 144


SELECT * FROM CUSTOMERS WHERE NAME REGEXP '^k';

Executing the query above will produce the following output −

ID NAME AGE ADDRESS SALARY

2 Khilan 25 Delhi 1500.00

3 Kaushik 23 Kota 2000.00

6 Komal 22 Hyderabad 4500.00

The following query retrieves all records in CUSTOMERS table whose name ends with 'sh' −

SELECT * FROM CUSTOMERS WHERE NAME REGEXP 'sh$';

Executing the query above will produce the following output −

ID NAME AGE ADDRESS SALARY

1 Ramesh 32 Ahmedabad 2000.00

Here, we are retrieving all the records whose name contain 'sh' −

SELECT * FROM CUSTOMERS WHERE NAME REGEXP 'sh';

As we can see the output, there are only two names that contain 'sh'.

ID NAME AGE ADDRESS SALARY

1 Ramesh 32 Ahmedabad 2000.00

3 Kaushik 23 Kota 2000.00

PYTHON NOTES Page 145


In the following query, we are finding all the names starting with a vowel and ending with 'ol' −

SELECT * FROM CUSTOMERS WHERE NAME REGEXP '^[aeiou].*ol$';

It returned an empty set because the CUSTOMERS table do not have any names who starts with
vowel and ends with 'ol'

Empty set (0.00 sec)

The following query finds all the names in the CUSTOMERS table whose name starts with a
consonant −

SELECT * FROM CUSTOMERS WHERE NAME REGEXP '^[^aeiou]';

Executing the query above will produce the following output −

ID NAME AGE ADDRESS SALARY

1 Ramesh 32 Ahmedabad 2000.00

2 Khilan 25 Delhi 1500.00

3 Kaushik 23 Kota 2000.00

4 Chaitali 25 Mumbai 6500.00

5 Hardik 27 Bhopal 8500.00

6 Komal 22 Hyderabad 4500.00

7 Muffy 24 Indore 10000.00

Regular Expression Functions and Operators

Following is the table of functions and operators of regular expressions.

PYTHON NOTES Page 146


S. No Function or Operator

1 NOT REGEXP
Negation of REGEXP

2 REGEXP
Checks whether the string matches regular expression or not

3 REGEXP_INSTR()
Returns the starting index of substring matching regular expression

4 REGEXP_LIKE()
Returns whether the string matches the regular expression

5 REGEXP_REPLACE()
Replaces substrings matching the regular expression

6 REGEXP_SUBSTR()
Returns substrings matching the regular expression

7 RLIKE
Checks whether the string matches regular expression or not

5.6. Special Symbols and Characters

In Python, special symbols and characters are often used for various purposes, such as string
manipulation, regular expressions, and syntax structure. Here is a list of some common special
symbols and characters in Python:

1. Escape Characters

Escape characters are used to insert special characters into strings, or to represent characters that
are difficult or impossible to type directly.

• \n: Newline (line break)


• \t: Horizontal tab
• \r: Carriage return
• \b: Backspace
• \f: Formfeed
• \v: Vertical tab
• \\: Backslash (to escape the backslash itself)
• \': Single quote (for strings with single quotes)
• \": Double quote (for strings with double quotes)
• \u: Unicode escape (e.g., \u00A9 for copyright symbol)

PYTHON NOTES Page 147


• \x: Hexadecimal escape (e.g., \x41 for 'A')

2. String Delimiters

• ': Single quote (e.g., 'Hello')


• ": Double quote (e.g., "Hello")
• """: Triple double quotes for multi-line strings (e.g., """This is a multi-line string.""")
• ''': Triple single quotes for multi-line strings (e.g., '''This is a multi-line string''')

3. Arithmetic Operators

• +: Addition
• -: Subtraction
• *: Multiplication
• /: Division (floating-point)
• //: Integer division
• %: Modulus (remainder of division)
• **: Exponentiation (power)

4. Comparison Operators

• ==: Equal to
• !=: Not equal to
• >: Greater than
• <: Less than
• >=: Greater than or equal to
• <=: Less than or equal to

5. Logical Operators

• and: Logical AND


• or: Logical OR
• not: Logical NOT

6. Assignment Operators

• =: Assign value
• +=: Add and assign
• -=: Subtract and assign
• *=: Multiply and assign
• /=: Divide and assign
• //=: Integer divide and assign
• %=: Modulus and assign
• **=: Exponentiate and assign

PYTHON NOTES Page 148


7. Identity Operators

• is: Tests object identity (whether two references point to the same object)
• is not: Tests if two references do not point to the same object

8. Membership Operators

• in: Checks if a value exists in a sequence (like a list, tuple, or string)


• not in: Checks if a value does not exist in a sequence

9. Bitwise Operators

• &: Bitwise AND


• |: Bitwise OR
• ^: Bitwise XOR
• ~: Bitwise NOT (inverts bits)
• <<: Bitwise left shift
• >>: Bitwise right shift

10. Other Special Symbols

• :: Used in slicing (e.g., lst[1:5]) and defining function arguments


• []: List or indexing (e.g., my_list[0])
• (): Parentheses for grouping expressions or calling functions (e.g., func() or (a + b))
• {}: Dictionary or set (e.g., my_dict = {} or my_set = set())
• ,: Separator (e.g., in function arguments or in lists)
• .: Dot for object or method access (e.g., object.method())
• =: Assignment operator

11. Comments

• #: Used for single-line comments (e.g., # This is a comment)

12. Other Useful Symbols

• @: Decorators (e.g., @staticmethod)


• _: Often used as a throwaway variable or for variable naming conventions (e.g., x, _ = (1,
2)).
• //: Integer division (division that returns an integer)

13. Regular Expression Special Characters

• .: Matches any single character except newline


• ^: Matches the start of a string
• $: Matches the end of a string

PYTHON NOTES Page 149


• []: Denotes a character class
• |: Logical OR
• (): Groups expressions
• \: Escape special characters (e.g., \d for a digit, \w for a word character)

5.7. Regular Expressions (REs) in Python

Regular expressions (REs) are powerful tools used for pattern matching and text
manipulation. In Python, regular expressions are handled by the re module, which provides a
wide range of functionality to search, match, replace, and manipulate strings based on specific
patterns.

Key Concepts in Regular Expressions

1. Pattern Matching: Regular expressions use special characters to define patterns that can
be matched against strings. These patterns allow you to check whether a string contains a
certain sequence of characters, extract parts of a string, or even replace specific portions
of a string.
2. Metacharacters: These are special characters that are interpreted differently from
ordinary characters. They form the foundation of regular expressions.

Some of the most commonly used metacharacters are:

o .: Matches any character except a newline.


o ^: Matches the start of a string.
o $: Matches the end of a string.
o *: Matches 0 or more repetitions of the preceding pattern.
o +: Matches 1 or more repetitions of the preceding pattern.
o ?: Matches 0 or 1 repetition of the preceding pattern.
o []: Defines a character class (e.g., [aeiou] matches any vowel).
o |: Logical OR (e.g., a|b matches either 'a' or 'b').
o (): Groups expressions (e.g., (abc)+ matches one or more repetitions of 'abc').
o \: Escapes special characters (e.g., \. to match a literal dot).

Common Functions in the re Module

Here are the most common functions provided by the re module in Python for working with
regular expressions:

1. re.match(pattern, string):
o Tries to match the pattern from the start of the string.
o Returns a match object if successful, otherwise returns None.
o Example: re.match(r"^abc", "abcdef") matches because "abc" is at the beginning
of the string.
2. re.search(pattern, string):

PYTHON NOTES Page 150


o Searches the entire string for the first location where the pattern matches.
o Returns a match object if successful, otherwise returns None.
o Example: re.search(r"abc", "xyzabcdef") matches because "abc" is present in the
string.
3. re.findall(pattern, string):
o Finds all non-overlapping matches of the pattern in the string.
o Returns a list of matched strings.
o Example: re.findall(r"\d+", "abc123xyz456") returns ['123', '456'].
4. re.finditer(pattern, string):
o Similar to findall, but returns an iterator of match objects instead of a list of
strings.
o Useful when you need to access details about the matches, such as position and
groupings.
o Example: re.finditer(r"\d+", "abc123xyz456") returns an iterator of match objects.
5. re.sub(pattern, repl, string):
o Replaces occurrences of the pattern in the string with a specified replacement
string.
o Example: re.sub(r"\d+", "number", "abc123xyz456") returns
'abcnumberxyznumber'.
6. re.split(pattern, string):
o Splits the string at occurrences of the pattern.
o Example: re.split(r"\s+", "hello world python") returns ['hello', 'world', 'python'].

7. re.compile(pattern):
o Compiles the pattern into a regular expression object, which can be used multiple
times for matching.
o Example: regex = re.compile(r"\d+") then regex.findall("abc123xyz456") returns
['123', '456'].

Special Sequences and Character Classes

1. \d: Matches any digit (equivalent to [0-9]).


2. \D: Matches any non-digit character (equivalent to [^0-9]).
3. \w: Matches any word character (letters, digits, and underscore; equivalent to [a-zA-Z0-
9_]).
4. \W: Matches any non-word character (equivalent to [^a-zA-Z0-9_]).
5. \s: Matches any whitespace character (spaces, tabs, newlines).
6. \S: Matches any non-whitespace character.
7. \b: Matches a word boundary.
8. \B: Matches a non-word boundary.

Grouping and Capturing

PYTHON NOTES Page 151


• (): Groups a part of the pattern together. You can capture this part and refer to it later.
o Example: In the pattern r"(\d+)\s+(\w+)", the first group (\d+) captures a number,
and the second group (\w+) captures a word.
• \1, \2, etc.: Refers to a specific group captured in the regular expression.
o Example: In the pattern r"(\d+)-(\d+)", you can refer to the first group (the first
number) as \1 and the second group (the second number) as \2.

Example Code

python
Copy code
import re

# Example 1: Basic match


text = "Hello, my name is John."
match = re.match(r"Hello", text)
if match:
print(f"Match found: {match.group()}")
else:
print("No match")

# Example 2: Searching for a pattern


text = "My phone number is 123-456-7890."
search_result = re.search(r"\d{3}-\d{3}-\d{4}", text)
if search_result:
print(f"Phone number found: {search_result.group()}")
else:
print("No phone number found")

# Example 3: Find all numbers in a string


text = "I have 2 apples and 10 oranges."
numbers = re.findall(r"\d+", text)
print(f"Numbers found: {numbers}")

# Example 4: Replacing text


text = "The weather is sunny."
updated_text = re.sub(r"sunny", "cloudy", text)
print(updated_text) # Output: The weather is cloudy.

# Example 5: Splitting a string


text = "apple, banana, cherry"
fruits = re.split(r",\s*", text) # Split by comma and optional space
print(fruits) # Output: ['apple', 'banana', 'cherry']

Tips for Using Regular Expressions in Python

PYTHON NOTES Page 152


• Raw strings (r"..."): It’s a good practice to use raw strings (denoted by r"...") for regular
expressions in Python. This prevents Python from interpreting backslashes as escape
characters.
o Example: Use r"\d+" instead of "\d+" to avoid Python interpreting \d as an escape
sequence.
• Test your regular expressions: Before using regular expressions in code, it’s helpful to
test them in interactive Python or a tool like regex101.com to ensure they behave as
expected.

5 MARK:

1.Explain In Database Programming?

2.Write Short Notes On Db Operations

3.Explain About Database Adapters?

10 MARK:

4.Explain Briefly Regular Expression?

5.Explain Special Symbols?

***************UNIT 5 COMPLETED****************

ALL UNITS ONE MARK

1. Who developed Python Programming Language?


a) Wick van Rossumb) Rasmus Lerdorf

c) Guido van Rossumd) Niene Stom

2. Which type of Programming does Python support?


a) object-oriented programming b) structured programming
c) functional programmingd) all of the mentioned

3. Is Python case sensitive when dealing with identifiers?


a) nob) yesc) machine dependentd) none of the mentioned

4. Which of the following is the correct extension of the Python file?


a) .pythonb) .plc) .pyd) .p

5. Is Python code compiled or interpreted?


a) Python code is both compiled and interpreted
PYTHON NOTES Page 153
b) Python code is neither compiled nor interpreted
c) Python code is only compiled
d) Python code is only interpreted

6. All keywords in Python are in _________


a) Capitalizedb) lower case
c) UPPER CASEd) None of the mentioned

7. What will be the value of the following Python expression?

4+3%5

a) 7 b) 2 c) 4 d) 1

8. Which of the following is used to define a block of code in Python language?


a) Indentationb) Keyc) Bracketsd) All of the mentioned

9. Whih keyword is used for function in Python language?


a) Functionb) defc) Fund) Define

10. Which of the following character is used to give single-line comments in Python?
a) //b) #c) !d) /*

11. What will be the output of the following Python code?

i=1
whileTrue:
if i%3==0:
break
print(i)
i + =1

a)1 2 3
b) error
c) 1 2
d) none of the mentioned

12. Which of the following functions can help us to find the version of python that we are
currently working on?
a) sys.version(1)
b) sys.version(0)
c) sys.version()
d) sys.version

PYTHON NOTES Page 154


13. Python supports the creation of anonymous functions at runtime, using a construct called
__________
a) pi
b) anonymous
c) lambda
d) none of the mentioned

14. What is the order of precedence in python?


a) Exponential, Parentheses, Multiplication, Division, Addition, Subtraction
b) Exponential, Parentheses, Division, Multiplication, Addition, Subtraction
c) Parentheses, Exponential, Multiplication, Division, Subtraction, Addition
d) Parentheses, Exponential, Multiplication, Division, Addition, Subtraction

15. What will be the output of the following Python code snippet if x=1?

x<<2

a) 4
b) 2
c) 1
d) 8

16. What does pip stand for python?


a) Pip Installs Python
b) Pip Installs Packages
c) Preferred Installer Program
d) All of the mentioned
17. Which of the following is true for variable names in Python?
a) underscore and ampersand are the only two special characters allowed
b) unlimited length
c) all private members must have leading and trailing underscores
d) none of the mentioned
18. What are the values of the following Python expressions?

2**(3**2)

(2**3)**2

2**3**2

PYTHON NOTES Page 155


a)512, 64, 512
b) 512, 512, 512
c) 64, 512, 64
d) 64, 64, 64

19. Which of the following is the truncation division operator in Python?


a) |
b) //
c) /
d) %20. What will be the output of the following Python code?

l=[1, 0, 2, 0, 'hello', '', []]

list(filter(bool, l))

a) [1, 0, 2, ‘hello’, ”, []]


b) Error
c) [1, 2, ‘hello’]
d) [1, 0, 2, 0, ‘hello’, ”, []]
21. Which of the following functions is a built-in function in python?
a) factorial()
b) print()
c) seed()
d) sqrt()
22. Which of the following is the use of id() function in python?
a) Every object doesn’t have a unique id
b) Id returns the identity of the object
c) All of the mentioned
d) None of the mentioned
23. The following python program can work with ____ parameters.

def f(x):

def f1(*args, **kwargs):

print("Sanfoundry")

returnx(*args, **kwargs)

return f1

PYTHON NOTES Page 156


a) any number of
b) 0
c) 1
d) 2
24. What will be the output of the following Python function?

min(max(False,-3,-4), 2,7)

a) -4
b) -3
c) 2
d) False
25. Which of the following is not a core data type in Python programming?
a) Tuples
b) Lists
c) Class
d) Dictionary
26. What will be the output of the following Python expression if x=56.236?

print("%.2f"%x)

a) 56.236
b) 56.23
c) 56.0000
d) 56.24
27. Which of these is the definition for packages in Python?
a) A set of main modules
b) A folder of python modules
c) A number of files containing Python definitions and statements
d) A set of programs making use of Python modules
28. What will be the output of the following Python function?

len(["hello",2, 4, 6])

a) Error
b) 6
c) 4
d) 3
29. What will be the output of the following Python code?

x = 'abcd'

foriin x:
PYTHON NOTES Page 157
print(i.upper())

a)a b b) a b c c) error d) abcd

30. What is the order of namespaces in which Python looks for an identifier?
a) Python first searches the built-in namespace, then the global namespace and finally the local
namespace
b) Python first searches the built-in namespace, then the local namespace and finally the global
namespace
c) Python first searches the local namespace, then the global namespace and finally the
built-in namespace
d) Python first searches the global namespace, then the local namespace and finally the built-in
namespace

31. What will be the output of the following Python code snippet?

foriin [1, 2, 3, 4][::-1]:

print(i, end=' ')

a) 4 3 2 1
b) error
c) 1 2 3 4
d) none of the mentioned
32. What will be the output of the following Python statement?

>>>"a"+"bc"

a) bc
b) abc
c) a
d) bca

33. Which function is called when the following Python program is executed?

f = foo()

format(f)

a) str()
b) format()
c) __str__()

PYTHON NOTES Page 158


d) __format__()

34. Which one of the following is not a keyword in Python language?


a) pass
b) eval
c) assert
d) nonlocal

35. What will be the output of the following Python code?

class tester:

def __init__(self, id):

self.id = str(id)

id="224"

>>>temp = tester(12)

>>>print(temp.id)

a) 12
b) 224
c) None
d) Error

36. What will be the output of the following Python program?

def foo(x):

x[0] = ['def']

x[1] = ['abc']

return id(x)

q = ['abc', 'def']

print(id(q) == foo(q))

PYTHON NOTES Page 159


a) Error
b) None
c) False
d) True
37. Which module in the python standard library parses options received from the command
line?
a) getarg
b) getopt
c) main
d) os

38. What will be the output of the following Python program?

z=set('abc')

z.add('san')

z.update(set(['p', 'q']))

a) {‘a’, ‘c’, ‘c’, ‘p’, ‘q’, ‘s’, ‘a’, ‘n’}


b) {‘abc’, ‘p’, ‘q’, ‘san’}
c) {‘a’, ‘b’, ‘c’, ‘p’, ‘q’, ‘san’}
d) {‘a’, ‘b’, ‘c’, [‘p’, ‘q’], ‘san}

39. What arithmetic operators cannot be used with strings in Python?


a) *
b) –
c) +
d) All of the mentioned

40. What will be the output of the following Python code?

print("abc. DEF".capitalize())

a) Abc. def
b) abc. def
c) Abc. Def

PYTHON NOTES Page 160


d) ABC. DEF

41. Which of the following statements is used to create an empty set in Python?
a) ( )
b) [ ]
c) { }
d) set()

42. What will be the value of ‘result’ in following Python program?

list1 = [1,2,3,4]

list2 = [2,4,5,6]

list3 = [2,6,7,8]

result = list()

result.extend(iforiin list1 ifinotin (list2+list3) andinotin result)

result.extend(iforiin list2 ifinotin (list1+list3) andinotin result)

result.extend(iforiin list3 ifinotin (list1+list2) andinotin result)

a) [1, 3, 5, 7, 8]
b) [1, 7, 8]
c) [1, 2, 4, 7, 8]
d) error

43. To add a new element to a list we use which Python command?


a) list1.addEnd(5)
b) list1.addLast(5)
c) list1.append(5)
d) list1.add(5)

44. What will be the output of the following Python code?

print('*', "abcde".center(6), '*', sep='')

a) * abcde *
b) *abcde *

PYTHON NOTES Page 161


c) * abcde*
d) * abcde *

45. What will be the output of the following Python code?

>>>list1 = [1, 3]

>>>list2 = list1

>>>list1[0] = 4

>>>print(list2)

a) [1, 4]
b) [1, 3, 4]
c) [4, 3]
d) [1, 3]

46. Which one of the following is the use of function in python?


a) Functions don’t provide better modularity for your application
b) you can’t also create your own functions
c) Functions are reusable pieces of programs
d) All of the mentioned

47. Which of the following Python statements will result in the output: 6?

A = [[1, 2, 3],

[4, 5, 6],

[7, 8, 9]]

a) A[2][1]
b) A[1][2]
c) A[3][2]
d) A[2][3]
48. What is the maximum possible length of an identifier in Python?
a) 79 characters
b) 31 characters
c) 63 characters

PYTHON NOTES Page 162


d) none of the mentioned

49. What will be the output of the following Python program?

i=0

whilei< 5:

print(i)

i += 1

ifi == 3:

break

else:

print(0)

a) error
b) 0 1 2 0
c) 0 1 2
d) none of the mentioned

50. What will be the output of the following Python code?

x = 'abcd'

foriin range(len(x)):

print(i)

a) error
b) 1 2 3 4
c) a b c d
d) 0 1 2 3
51. What are the two main types of functions in Python?
a) System function
b) Custom function
c) Built-in function & User defined function
d) User function

PYTHON NOTES Page 163


52. What will be the output of the following Python program?

def addItem(listParam):

listParam += [1]

mylist = [1, 2, 3, 4]

addItem(mylist)

print(len(mylist))

a) 5
b) 8
c) 2
d) 1
53. Which of the following is a Python tuple?
a) {1, 2, 3}
b) {}
c) [1, 2, 3]
d) (1, 2, 3)

54. What will be the output of the following Python code snippet?

z=set('abc$de')

'a' in z

a) Error
b) True
c) False
d) No output

55. What will be the output of the following Python expression?

round(4.576)

a) 4
b) 4.6
c) 5
d) 4.5

PYTHON NOTES Page 164


56. Which of the following is a feature of Python DocString?
a) In Python all functions should have a docstring
b) Docstrings can be accessed by the __doc__ attribute on objects
c) It provides a convenient way of associating documentation with Python modules,
functions, classes, and methods
d) All of the mentioned
57. What will be the output of the following Python code?

print("Hello {0[0]} and {0[1]}".format(('foo', 'bin')))

a) Hello (‘foo’, ‘bin’) and (‘foo’, ‘bin’)


b) Error
c) Hello foo and bin
d) None of the mentioned
58. What is output of print(math.pow(3, 2))?
a) 9.0
b) None
c) 9
d) None of the mentioned
59. Which of the following is the use of id() function in python?
a) Every object in Python doesn’t have a unique id
b) In Python Id function returns the identity of the object
c) None of the mentioned
d) All of the mentioned

60. What will be the output of the following Python code?

x = [[0], [1]]

print((' '.join(list(map(str, x))),))

a) 01
b) [0] [1]
c) (’01’)
d) (‘[0] [1]’,)

61. The process of pickling in Python includes ____________


a) conversion of a Python object hierarchy into byte stream
b) conversion of a datatable into a list
c) conversion of a byte stream into Python object hierarchy

PYTHON NOTES Page 165


d) conversion of a list into a datatable

62. What will be the output of the following Python code?

deffoo():

try:

return 1

finally:

return 2

k = foo()

print(k)

a) error, there is more than one return statement in a single try-finally block
b) 3
c) 2
d) 1

PYTHON NOTES Page 166

You might also like