0% found this document useful (0 votes)
10 views148 pages

Python Notes

The document provides an overview of Python programming, including its definition, installation steps, and features. It covers the history of Python, data types, variables, identifiers, and the differences between lists and tuples. Additionally, it includes instructions for installing various IDEs and tools for Python development.
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)
10 views148 pages

Python Notes

The document provides an overview of Python programming, including its definition, installation steps, and features. It covers the history of Python, data types, variables, identifiers, and the differences between lists and tuples. Additionally, it includes instructions for installing various IDEs and tools for Python development.
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

Python Programming Notes TeluguWebGuru

Why Programming?

Computers are programmed. A program is a set of instructions. Whatever we input
through the program, the computer will execute and follow it.

​ Generally we solve real world problems by developing various softwares by learning


some of the available programming languages.

What is Python?

Python is an easy to learn, beginner-friendly & powerful programming language. It


has efficient high-level data structures and a simple but effective approach to object-oriented
programming. Python’s elegant syntax and dynamic typing, together with its interpreted
nature, make it an ideal language for scripting and rapid application development in many
areas on most platforms.​

Python development work was conceived at 1980’s by Guido Van Rossum. Python is
one of the High level programming languages.

As we all know, computers only understand 0 & 1. So Any program written using any
programming language must be converted into 0 & 1 and then only computers understand our
program’s instructions. This conversion process is carried out by Language Translators.
Compilers and Interpreters are examples of Language Translators.

[Link] @teluguwebguru
Python Programming Notes TeluguWebGuru

Steps to download and Install Python :

1)​ Visit [Link] website


2)​ Click on Downloads menu and select your computer’s operating system

3)​ Then the Installer file will be downloaded into the Downloads folder of your system.
4)​ Double click on it to start installation
5)​ In the first installation screen, select add [Link] to path option so that we are able
to run our python programs from any drive and any folder

[Link] @teluguwebguru
Python Programming Notes TeluguWebGuru

6)​ Follow on screen instructions by clicking the next button so that the installation
process is completed.
7)​ Once installation is completed, open the command prompt ( Windows Key + R) and
check the “Python –version” command. If the system shows a python version, it
confirms that installation completed successfully.

Python Command prompt version Vs IDLE Version:

​ Once we install python software successfully, we will get two versions of [Link] is the
command prompt version and the other is the IDLE version.

IDLE means Integrated Development and Learning Environment. It provides some


extra features like syntax highlighting, auto completion etc.,

[Link] @teluguwebguru
Python Programming Notes TeluguWebGuru

Installing IDEs (Jupyter Notebook, PyCharm, Visual Studio Code):

Steps to install Jupyter Notebook:


1)​ Visit [Link] distributing website that provides the required Jupyter Notebook
and all other required packages as a bundle.
2)​ Click on “Free Download”

3)​ Download required (According to your system OS) version of software


4)​ Install it by following on screen instructions
5)​ After installation open anaconda command prompt version and type “jupyter
notebook” which opens Jupyter Notebook web application automatically

[Link] @teluguwebguru
Python Programming Notes TeluguWebGuru

6)​ Create new python notebook and run print (“Welcome”) and check whether Welcome
is displayed in output or not

Steps to install PyCharm:

1)​ Search “Pycharm Download” in Google and visit the suggested JetBrains link

2)​ Click Download => select the suitable software and download it
3)​ Install the downloaded software
4)​ Open PyCharm
5)​ Select New Project option and name it with some name
6)​ Right click on project name and select new python file => name it as [Link]

[Link] @teluguwebguru
Python Programming Notes TeluguWebGuru

7)​ Type your code. For example print (“Welcome”)


8)​ Save the [Link] click on the code area and run the project.

Steps to install Visual Studio Code:

1)​ Visit [Link]/download web page and download suitable vs code


software to your os

2)​ Install the software by following on screen instructions.


3)​ After installation, open vs code => create new file => save it with some name and
extension must be “.py”. For example : [Link]
4)​ Install python extension suggested by vs code at bottom right corner of the interface

5)​ Type the entire program. For example, print (“Hello”)


6)​ Save the updated file
7)​ Run the program clicking on the run icon which is on the top right side of our
program.

[Link] @teluguwebguru
Python Programming Notes TeluguWebGuru

History of Python?

Initially designed by Guido van Rossum - 1991 and developed by python software foundation
●​ 1980 - Working on python started
●​ 1989 - Began it’s application based work at CWI Institute in Netherlands
●​ Python is the successor of ABC Programming Language.
●​ The name python came from a BBC Comedy show “Monty Python's Flying Circus”
●​ 1991 - The language was finally released
●​ 2000 - Python 2.0 released
●​ 2008 - python 3.0 released
●​ 2025 apr 8 = > 3.13.3 version released

Features of Python:

Easy to Code (Simple) :


Python is often called simple due to its clear, readable and user-friendly syntax and
focus on code clarity, which makes it easy to learn and use, even for beginners.

Free and Open Source


​ Python is available in both free and open source versions. So, anyone can use the
open source version of Python (C-Python) and develop their own distributions

Object Oriented and procedure oriented:


​ Python supports both Object oriented and Procedure oriented paradigms. As we know
that procedure oriented programming always gives priority to tasks which make the code
more complex. To overcome this, an object oriented programming paradigm is introduced
which always concentrates on classes and objects. Python never forces us to implement in
object oriented style only. It supports both paradigms and so developers have free hand to
develop according to their needs.

Support for GUI (pyqt5):


​ Python allows us to create Graphical User Interface applications with the help of other
modules that are available in python itself.

[Link] @teluguwebguru
Python Programming Notes TeluguWebGuru

High level:
​ Python syntax is very close to our regular English language which in turn is converted
into machine code with the help of language translators.

Large Community Support


​ Python has a very large community so we will get support and help while writing
python code at any time.

Robust(Strong):
​ Python allows us to develop very strong applications with its internal features like
exception handling. So python is called robust.

Portable & platform independent:


​ Python is one of the platform independent languages. Python generates bytecode (not
machine code) on compilation. This byte code is understandable to Python Virtual Machine
(PVM) only. So once we develop python code and compile it, we can easily move our code
to any other platform and execute directly there. As we can move our code easily between
different platforms, python is called portable.

Extensible & Embedded


​ ​ We can use other programming language code in python and at the same time
we can use python code in other programming languages also. This makes python extensible
and embedded

Interpreted:​ As python will compile and execute code line by line, it is called as
interpreted
Dynamically Typed:
​ While writing python code, we need not declare data types explicitly. Python can
automatically decide the data types of variables based on the value assigned to it. This makes
python a dynamically typed language.
Dynamic Memory Management:
​ Python performs memory management automatically. Whenever a garbage collector
finds unused objects, those will be removed from memory automatically.

[Link] @teluguwebguru
Python Programming Notes TeluguWebGuru

Literals in Python:

Python literals are the raw values you use directly in code, like numbers, text, or
True/False etc., Python supports Integer, floating point, String, Boolean, Collection type
literals

Variables:

Python variables serve as symbolic names or labels that refer to objects in memory.
They are used to store and manage data values within a program.

Consider the above example. A variable with the name ‘a’ is declared with the value
2. Whenever we declare such variables immediately required memory is allocated and value
is stored into that particular location. Whatever the variable name that we declared ‘a’ is
associated with that memory location so that we can access that particular value through this
variable. However system memory internally allocates memory addresses to each and every
location apart from the variable names. We can retrieve the same with the use of id function
as shown in above screenshot.

Above figure represents the entire above concept.

[Link] @teluguwebguru
Python Programming Notes TeluguWebGuru

Identifiers

Python Identifier is the name we give to identify a variable, function, class, module or other
object. That means whenever we want to give an entity a name, that's called an identifier.

The following are rules to frame identifier name:

●​ The name of identifiers should be the combination of alphabets,digits and underscore (_)
symbols.
●​ The name of identifiers in python cannot begin with a number. It should Starts with an
alphabet or _
●​ No other symbols are allowed in identifier name except _
●​ Keywords cannot be used as identifiers in python
●​ Names of identifiers in python are case sensitive

DataTypes:
Python provides several built-in data types to store different kinds of values. These
data types are essentially classes, and variables are instances (objects) of these classes. In
simple words, Data types decide the amount of memory needed to allocate to a variable.

The following are available data types in Python.

Fundamental Category Data types :


int, float, bool, complex
Sequence Category:
str,bytes,bytearray,range
List Category :
list,tuple
Set Category:
set, frozenset
Dict Category:
dict
None type Category:
none

[Link] @teluguwebguru
Python Programming Notes TeluguWebGuru

Let’s discuss about each data type below

int :
int represents Integers (Whole numbers) and Binary, Octal, Hexadecimal numbers.

Examples of int data type are


​ ​ a=2
​ ​ a1=34
​ ​ a123=67

Bin numbers are represented with the prefix ‘0b’ or ‘0B’.

​ For example :

We can use class names as identifiers

—-----------------------------------

String Indexing

Forward / Positive Indexing


Backward / Negative Indexing

s=”Telugu Web Guru”

print s[0] ========> T


print s[1] ========> e
print s[5] ========> u
print s[8] ========> e
print s[-6] ========> b
print s[-4] ========> G
print s[-8] ========> W
print s[len(s)-1] ========> u
print s[-len(s)] ========> T

Show some index error examples also → print (s[len(s)]

[Link] @teluguwebguru
Python Programming Notes TeluguWebGuru

Slicing

print(s[0:4]) =============> Telu


print(s[2:8]) =============> lugu W
print(s[4:0]) =============>
print(s[-8:-2]) =============> Web Gu
print(s[-8:-1]) =============> Web Gur
print(s[-3:-1]) =============> ur
print(s[-7:-4]) =============> eb
print(s[-4:-7]) =============>
print(s[1:-4]) =============> elugu Web
print(s[0:]) =============> Telugu Web Guru
print(s[:4]) =============> Telu
print(s[:]) =============> Telugu Web Guru
print(s[0:4:1]) =============> Telu
print(s[0:4:2]) =============> Tl
print(s[0:4:-1]) =============>
print (s[4:0:-1]) =============> gule

Mutable and Immutable:

Mutable -> Changeable in the same address : lists, sets


Immutable → not changeable : int,float,str,complex,bool,str

Type Casting:

Type casting, also known as type conversion, is the process of changing the data type of a
variable from one type to another possible type.

To convert one data type into another, Python provides predefined functions like int(),
float() so on.

int:

To convert other data type values into int, python provides int() function

Syntax:

int(source)

[Link] @teluguwebguru
Python Programming Notes TeluguWebGuru

Example:
x=3.2
y = int(x) ⇐=== Converting float value to int

List of possible types to convert into int are float, bool, String type int values.

[Link] @teluguwebguru
Python Programming Notes TeluguWebGuru

Lists and Tuples in Python

Lists and Tuples are fundamental data structures in Python used to store ordered
collections of items of similar or different types.

Lists:

List is mutable(allow changes in same memory location) and tuples are immutable
(Does not allow changes in same memory location).

How to create Lists?

​ Lists are created by using square brackets [ ] as shown below.

Empty Lists : These are Lists with no elements.

Syntax to create empty lists:

Listobject = [ ]
Listobject = list( )

Examples
​ ​ Marks = [44,50,45,46,49,48]
user=[“santosh”, 41, True, 3.4]

Lists are created by using [ ] brackets

Understanding index concept of lists:

Indexing and Slicing with lists will work same as indexing and slicing with strings.

For example let us take below list and represent how indexes are maintained

-9 -8 -7 -6 -5 -4 -3 -2 -1

marks = [ 49 48 44 46 47 48 35 39 50 ]

0 1 2 3 4 5 6 7 8

[Link] @teluguwebguru
Python Programming Notes TeluguWebGuru

Let us see some examples on indexing and slicing now

To find number of elements in a list we need to use len function as follows

len(marks)

It returns 9 as output which indicates the marks list contains 9 total number of
elements.

Pre defined functions in List:

append() :
​ To add elements at the end of the list, append function will be used.

[Link]("orange")
[Link](b)
clear() :
To remove all elements from the list

[Link]()
copy() :
To create duplicate copy of a list, copy() function will be used

x = [Link]() => means same memory location referred by 2 objects


count():
To retrieve the number of times that an element occurs in a list, we will use the count
function.
x = [Link]("cherry")

[Link] @teluguwebguru
Python Programming Notes TeluguWebGuru

extend()
​ To add a list at the end of another list we will use extend

[Link](cars) adds second list elements as individual


index()
​ To get the index of a particular element in a List
x = [Link]("cherry")
insert()
​ To insert a particular element at given index in the given list
[Link](1, "orange")
pop()
​ To remove last element from the list
pop(index)
​ To remove element at the given position
[Link](1)
remove()
[Link]("banana")
reverse()
[Link]()
sort()
[Link]()

del operator:
​ It is used to delete collection elements at a particular index or on slicing basis also.

Nested List :
lists that contain other lists as their elements

[Link] @teluguwebguru
Python Programming Notes TeluguWebGuru

Tuple: immutable

Empty tuple
x=()
x=tuple()

Non-empty tuple
x=(10,20,30,40)
Or

x= 10,20,30,40

X[0]
X[2]
X[5]
X[-2]
x[1]=34 ===> Error

a=30
b=tuple([a])
Or
b=(a,)

Predefined methods:

count()
index()

These only will work on tuple because tuple is immutable one.


—-------

Copy will not work


Sort also will not work … to implement sort we need to convert this into list and then perform
sort operation and then convert back into tuple again

Or else we may use the general function called sorted

[Link] @teluguwebguru
Python Programming Notes TeluguWebGuru

Nested Tuples
We can include lists also as inner elements in the tuple

Tuple in tuple
List in tuple
List in list
Tuple in list

Sets:
A set is a built-in data type used to store a collection of unique elements.
Sets are unordered, which means the elements do not have a specific index and
their order can change. Sets are also mutable, allowing to add or remove
[Link] automatically remove duplicate elements.

Set does not guarantee insertion order

Set object does not allow indexing and slicing operations

2 data types in set category

1)​ set
2)​ frozenset

{}

s1={10,55,60,22,35,76,98}

Sets are mutable in case of adding elements and immutable in case of item assignment

Empty set:
x=set()
Non Empty Set:
s1={10,55,60,22,35,76,98}
s2=set(s1)

[Link] @teluguwebguru
Python Programming Notes TeluguWebGuru

Predefined functions on set :

add() :
Used to add elements to the existing set.

Syntax:

[Link](element)

Example
[Link]("orange")

clear() :
Used to clear all elements from the set at a time.

Syntax:
[Link]()

Example:
[Link]()

copy() :

Used to create a copy of the existing set.

Syntax:
Newobj = [Link]()

Example:
x = [Link]()

difference() -
Returns a set containing the difference between two or more sets
x = {"apple", "banana", "cherry"}
y = {"google", "microsoft", "apple"}

z = [Link](y)

[Link] @teluguwebguru
Python Programming Notes TeluguWebGuru

difference_update() -=

Removes the items in this set that are also included in another, specified set
x = {"apple", "banana", "cherry"}
y = {"google", "microsoft", "apple"}
x.difference_update(y)
print(x) —-> {'cherry', 'banana'}

discard()
Remove the specified item …same like remove() where it will not give any KeyError in case
of trying to delete not existed element

[Link]("banana")

intersection() &

z = [Link](y)

intersection_update()
Removes the items in this set that are not present in other, specified
set(s)

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


y = {"google", "microsoft", "apple"}
x.intersection_update(y)
print(x) —---> {'apple'}

isdisjoint()
Returns whether two sets have a intersection or not
z = [Link](y)

issubset()
<= Returns whether another set contains this set or not
< Returns whether all items in this set is present in other, specified set(s)

issuperset()
>= Returns whether this set contains another set or not
> Returns whether all items in other, specified set(s) is present in this set

[Link] @teluguwebguru
Python Programming Notes TeluguWebGuru

pop() : any element which comes first according to hash values(arbitrary) will be removed
first. If we display the set and then perform the pop then it will always remove the first
element.

remove() : removes particular element

symmetric_difference() ​ Returns a set with the symmetric differences of two sets


Either in first one or in second one but not both

symmetric_difference_update() Inserts the symmetric differences from this set and


another

Remove the items that are present in both sets, AND insert the items that is not
present in both sets:

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


y = {"google", "microsoft", "apple"}

x.symmetric_difference_update(y)

print(x)

{'microsoft', 'cherry', 'banana', 'google'}

union() : all unique elements of set1 and set2

update() :

The update() method updates the current set, by adding items from another set

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


y = {"google", "microsoft", "apple"}

[Link](y)

print(x)

{'google', 'cherry', 'banana', 'apple', 'microsoft'}

[Link] @teluguwebguru
Python Programming Notes TeluguWebGuru

Nested Sets

Set in Set → Not possible because it is not hashable and mutable


List in Set
Tuple in Set -> it is only possible because tuple is immutable

Set in List
Set in Tuple

frozenset:

In Python, a frozenset is an immutable version of a set.

s1={10,20,30}
s2=frozenset(s1) frozenset({10,20,30})

isdisjoint()
issuperset()
issubset()
union()
intersection()
difference()
symmetric_difference()

Dict :

I want to store data not only in values format, but also with keys in the form of Key,Value
pairs then we can use this dictionary

To store data in the form of key,value pairs we will use dict data type.

user={“name”:”santosh”,”age”:41,”contact”:”7013484024”}

print(user)
print(user[“name”])

[Link] @teluguwebguru
Python Programming Notes TeluguWebGuru

Empty dict:

s={}
s=dict()

Non-Empty dict
user={“name”:”santosh”,”age”:41,”contact”:”7013484024”}

user[key]=value

Predefined functions in dictionary:

clear()​ ​ Removes all the elements from the dictionary

copy()​ ​ Returns a copy of the dictionary


fromkeys()​ Returns a dictionary with the specified keys and value

x = ('key1', 'key2', 'key3')


y=0
thisdict = [Link](x, y)
print(thisdict)
{'key1': 0, 'key2': 0, 'key3': 0}

get()​ ​ Returns the value of the specified key


x = [Link]("model")
items()​
Returns a list containing a tuple for each key value pair
​ ​ ​ car = {
"brand": "Ford",
​ "model": "Mustang",
​ "year": 1964
}

x = [Link]()

print(x)

dict_items([('brand', 'Ford'), ('model', 'Mustang'), ('year', 1964)])

[Link] @teluguwebguru
Python Programming Notes TeluguWebGuru

keys()​ ​ Returns a list containing the dictionary's keys


car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}

x = [Link]()

print(x)

dict_keys(['brand', 'model', 'year'])

pop(key)​ ​ Removes the element with the specified key


​ ​
popitem()​ Removes the last inserted key-value pair [Link]()
setdefault()​ Returns the value of the specified key. If the key does not exist: insert
the key, with the specified value
x = [Link]("color", "white")
update()​ Updates the dictionary with the specified key-value pairs
[Link]({"color": "White"})
values()​ Returns a list of all the values in the dictionary
​ ​ x = [Link]()

—----------

[Link] @teluguwebguru
Python Programming Notes TeluguWebGuru

Bytes, bytearray,memoryview

The bytes data type in Python represents an immutable sequence of single bytes. Each element in
a bytes object is an integer in the range of 0 to 255, inclusive, representing the value of one byte.

bytes objects are distinct from str (string) objects. Strings represent sequences of Unicode
characters, while bytes represent raw binary data. Conversion between str and bytes requires
encoding (from str to bytes) or decoding (from bytes to str) using a specific character encoding
like UTF-8.

The bytearray type is a mutable version of bytes. If you need to modify binary data, bytearray is
the appropriate choice, while bytes is used when immutability is desired or required.

x = bytes(4)
print(x)
B'\x00\x00\x00\x00'

x = bytearray(4)
print(x)
—-----
The memoryview data type in Python provides a way to access the internal buffer of an object
without creating a copy of the [Link] is particularly useful for efficient handling of large
datasets and binary data, as it avoids the overhead of memory duplication.

Key characteristics of memoryview:


Zero-copy operations:,Buffer Protocol:

data = bytearray(b'Hello World')


mv = memoryview(data)

# Accessing elements
print(mv[0]) # Output: 72 (ASCII for 'H')

# Modifying the underlying data through the memoryview


mv[0] = 65 # ASCII for 'A'
print(data) # Output: bytearray(b'Aello World')

# Slicing a memoryview
sub_mv = mv[1:5]
print(sub_mv.tobytes()) # Output: b'ello'

None type is used to show no value or null


a=None

[Link] @teluguwebguru
Python Programming Notes TeluguWebGuru

print statement:

print (variable)
print(var1,var2,var3…varn)

print(msg1,msg2,msg3)
print(msg1+msg2+ms3) ===> it won’t maintain spaces between text in output

print(“my age is ”+str(41))


OR
print(“my age is:,41)

print(“we have”,30,”students in online out of”,70,”total strength”)

print(“value of a={}”.format(a))

print(“value of a={} and b={}”.format(a,b))

Let’s write the same with format specifier:


%d, %s, %f
print(“value of a=%d and b=%5d” %(a,b))

%0.2f indicates two decimal places to be displayed in float

l=[10,20,30,40]
print(l)
10
20
30
40
print(l,end=” ”)

print(“=”*25)

Read input from keyboard

​ input()
​ input(message)

Two numbers addition


Area of circle : pi r r
Area of rectangle l*b

[Link] @teluguwebguru
Python Programming Notes TeluguWebGuru

Operators in Python:

Operators are used to perform operations on variables and values.

Python divides the operators in the following groups:

Arithmetic operators
Assignment operators
Comparison/Relational operators
Logical operators
Identity operators
Membership operators
Bitwise 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
//​ ​ ​ Floor Division​ ​ 9//2 = 4
%​ ​ ​ Modulus​ ​ 22 % 10 = 2
**​ ​ ​ Exponent​ ​ 4**2 = 16

2. Python Comparison Operators


To compare two values, Python comparison operators are needed.
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.

[Link] @teluguwebguru
Python Programming Notes TeluguWebGuru

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 (a = a % 5)
**=​ ​ ​ ​ Exponent Assignment​ ​ a **= 2 (a = a ** 2)
//=​ ​ ​ ​ Floor Division Assignment​ a //= 3 (Same as a = a // 3)

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

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 Complement​ Inverts all the bits
<<​ ​ Binary Left Shift​ ​ Shift left by pushing zeros in from the
right and let the leftmost bits fall off
>>​ ​ Binary Right Shift​ ​ Shift right by pushing copies of the
leftmost bit in from the left, and let the
rightmost bits fall off

5. Python Logical Operators (Short circuit evaluation) (100 and 200)


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

[Link] @teluguwebguru
Python Programming Notes TeluguWebGuru

and Logical AND​ If both of the operands are true ​ ​ (a and b) is true.
then the condition becomes true.​
or Logical OR​ ​ If any of the two operands is non-zero
then the condition becomes true.​ ​ (a or b) is true.
not Logical NOT​ Used to reverse the logical state of its operand​ Not(a and b) is false.

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 Python data
structures such as lists, tuples, sets, and strings.
Python has two primary membership operators: the in and not in operators.

Operator​ Description​ ​ ​ ​ ​ Example


in​ ​ Evaluates to true if it finds a variable ​ ​ x in y
in the specified sequence​ ​
not in​ ​ Evaluates to true if it does not find​ ​ x not in y,
a variable in the specified sequence
and false otherwise.​

7. Python Identity Operators

Python identity operators are used to compare two objects' memory addresses rather than
their values. If the two objects refer to the same memory address, they evaluate to True;
otherwise, they evaluate to [Link] includes two identity operators: the is and is not
operators.

Operator​ Description​ ​ ​ ​ ​ Example


is​ ​ Evaluates to true if the ​ ​ ​ x is y
variables on either side of the
operator point to the same object
and false otherwise​

is not​ ​ Evaluates to false if the variables


on either side of the operator point
to the same object and true otherwise​ ​ x is not y

[Link] @teluguwebguru
Python Programming Notes TeluguWebGuru

Python Operators Precedence


Python Operator's Precedence can be explained by this given table,

Precedence​ ​ Operators​ ​ ​ Description​ ​ ​


1​ ​ ​ ()​ ​ ​ ​ Parentheses​ ​ ​
2​ ​ ​ x[index], x[index:index]​ Subscription, slicing​ ​
3​ ​ ​ **​ ​ ​ ​ Exponentiation​​ ​
4​ ​ ​ ~x​ ​ ​ ​ Positive, negative, bitwise NOT
5​ ​ ​ *, /, //, %​ ​ ​ Multiplication,division,
floor division, remainder​
6​ ​ ​ +, -​ ​ ​ ​ Addition and subtraction​
7​ ​ ​ <<, >>​ ​ ​ ​ Shifts ​ ​ ​ ​
8​ ​ ​ &​ ​ ​ ​ Bitwise AND​ ​ ​
9​ ​ ​ ^​ ​ ​ ​ Bitwise XOR​ ​ ​
10​ ​ ​ |​ ​ ​ ​ Bitwise OR​ ​ ​
11​ ​ ​ in, not in, is, is not, ​ ​ Comparisons, membership
<, <=, >, >=, !=, ==​ ​ identity tests​ ​ ​
12​ ​ ​ not x​ ​ ​ ​ Boolean NOT​ ​ ​
13​ ​ ​ and​ ​ ​ ​ Boolean AND​ ​ ​
14​ ​ ​ or​ ​ ​ ​ Boolean OR​ ​ ​
15​ ​ ​ :=​ ​ ​ ​ Assignment expression ​

Python Control Statements:

Control statements in programming determine the flow of execution of a program.


They allow you to make decisions, repeat blocks of code, and jump to different parts of the
program based on certain conditions

1)​ Selection Statements


​ if (simple if, if-else,if-elif-else), match
2)​ Iterative
for
while
3)​ Jump (Transfer flow)
break
continue
pass
return

[Link] @teluguwebguru
Python Programming Notes TeluguWebGuru

Selection Statements:

​ Selection statements, also known as conditional or decision-making statements,


are fundamental programming constructs that allow a program to execute different blocks
of code based on whether a specified condition is true or false

simple if: This version of if allows us to execute a block of statements on success of a


condition.

Syntax:
if (condition):
Statement1

Here colon (:) is called an indentation symbol.

The Python system expects an indentation block immediately after (:) indentation symbol.

Syntax:
​ ​
​ ​ if (Condition) :
​ ​ ​ Statement1
​ ​ ​ Statement2
​ ​ ​ Statement3

As shown in above syntax, statements should be included in the if block by maintaining


proper indentation (spaces)

Example:
if(a>b):
print (“hello”)
print(“a is big”)
print(“ Program Ends”)

Limitation of this simple if is : it addresses condition true case only. We can’t associate
any statements and execute under condition failure case.

[Link] @teluguwebguru
Python Programming Notes TeluguWebGuru

if-else condition:

​ if-else allows us to address both condition true and false cases.

Syntax:
​ if(condition):
​ ​ Statement1
​ ​ Statement2
​ else:
​ ​ Statement1
​ ​ Statement2

Example:

​ if(a>b):
​ ​ print(“hello”)
​ ​ print(“a is big”)
​ else:
​ ​ print(“Welcome”)
​ ​ print(“b is big”)
​ print(“program ends”)

Program to find biggest among given two numbers

#program to add two numbers


a=10
b=5
if a>b:
print("a is big")
else:
print("b is big")
print("program ends")

Output:

[Link] @teluguwebguru
Python Programming Notes TeluguWebGuru

Python Program to check whether a given number is positive or negative?

#python program to check whether given input is positive or negative number


#step-1: read a number
a=int(input("enter a number"))

#check if number>0 or not


if(a>0):
print("a is positive")
#check if number<0 or not
if(a<0):
print("a is negative")

Output:

Even or odd example


(a%2==0)
Positive or negative or zero
(a>0)
Program to compare two numbers and print which is bigger
(a>b)
Program to check whether given number is divisible by 3,11 or not
(a%3==0 && a%11==0)
Program to check vowel or consonant
(a==’a’ or a==’e’ … )
Leap year or not
(year%4==0 and year%100!=0 or year%400==0)

Digit to word conversion

[Link] @teluguwebguru
Python Programming Notes TeluguWebGuru

def get_day_type(day_number):
match day_number:
case 1 | 2 | 3 | 4 | 5:
return "Weekday"
case 6 | 7:
return "Weekend"
case _: # The wildcard '_' acts as the default case
return "Invalid day number"

print(get_day_type(3))
print(get_day_type(6))
print(get_day_type(9))

Program to print first 10 numbers


Program to print sum of first n numbers

[Link] @teluguwebguru
Python Programming Notes TeluguWebGuru

Program to check whether a number is prime or not

n=13;

#take a variable to indicate prime


p=0;

#check from 2 to n/2


for i in range(2,n//2):
if(n%i==0):
p=1;
print ("Not a prime");
break;

if(p==0):
print ("It is prime");

Program to check product of n numbers

n=10
p=1
i=1

while(i<=n):
p=p*i
i=i+1
else:
print(p)

Program to find sum of digits of a number

n=4597;
sum=0;
ld=0;

while (n>0):
ld=n%10;
sum=sum+ld;
n=n//10;

print ("sum is :",sum);

[Link] @teluguwebguru
Python Programming Notes TeluguWebGuru

Program to print reverse of a number

n=345;
ld=0;
rev=0;

while (n>0):
ld=n%10;
rev=(rev*10)+ld;
n=n//10;

print ("reverse of given number is:",rev)

Program to find sum of first and last digits of a number


n=345;
fd=0;
ld=0;
sum=0;

#finding last digit


ld=n%10;

#finding first digit


while(n>0):
n=n//10;
if(n>0):
fd=n;

#print sum
sum=fd+ld;

print ("ld is",ld)


print ("sum of fd and ld is: ",sum);

Program to check whether given number is palindrome or not

n=121;
num=n;
ld=0;
rev=0;

while (n>0):
ld=n%10;
rev=(rev*10)+ld;
n=n//10;

[Link] @teluguwebguru
Python Programming Notes TeluguWebGuru

if(num==rev):
print ("palindrome")
else:
print ("not a palindrome")

Program to print a number in words

n=345;
ld=0;
rev=0;

while (n>0):
ld=n%10;
rev=(rev*10)+ld;
n=n//10;

num=rev;

while(num>0):

ld=num%10;

if(ld==0):
print ("zero ");
elif(ld==1):
print ("one ");
elif(ld==2):
print ("two ");
elif(ld==3):
print ("three ");
elif(ld==4):
print ("four ");
elif(ld==5):
print ("five ");
elif(ld==6):
print ("six ");
elif(ld==7):
print ("seven ");
elif(ld==8):
print ("eight ");
elif(ld==9):
print ("nine ");

num=num//10;

[Link] @teluguwebguru
Python Programming Notes TeluguWebGuru

Program to find exponent of a base number without using exponent


operator (**)

base=2;
exponent=5;

r=1;

for i in range(1,exponent+1):
r=r*base;

print (base," power of ",exponent," is :",r);

Program to find all factors of a number

n=int(input("enter n value:"));
for i in range(1,n+1):
if(n%i==0):
print (i,end=" ");

Program to print 100 below fibonacci series

a=0;
b=1;
c=a+b;
print (a," ",b," ",end=" ");

while(c<=100):
print(c," ",end=" ");
a=b;
b=c;
c=a+b;

[Link] @teluguwebguru
Python Programming Notes TeluguWebGuru

Program to print square star pattern

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

for i in range(1,5):
for j in range(1,5):
print ("* ",end=" ")
print ("")

Program to print right angled triangle


*
* *
* * *
* * * *
* * * * *
for i in range(1,6):
for j in range(1,i+1):
print ("* ",end=" ")
print ("")

Program to print inverted right angled triangle


* * * * *
* * * *
* * *
* *
*
for i in range(5,0,-1):
for j in range(1,i+1):
print ("* ",end=" ")
print ("")

[Link] @teluguwebguru
Python Programming Notes TeluguWebGuru

Program to print hollow square star pattern


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

for i in range(1,6):
for j in range(1,6):
if(i==1 or i==5 or j==1 or j==5):
print("* ",end=" ");
else:
print(" ",end=" ");
print("");

Program to print hollow right triangle star pattern


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

for i in range(1,6):
for j in range(1,i+1):
if(j==1 or i==5 or i==j):
print ("* ",end=" ");
else:
print (" ",end=" ");
print ("");

Program to print rhombus or parallelogram star pattern

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

for i in range(1,6):
for j in range(1,(5-i)+1):
print (" ",end=" ")
for j in range(1,6):
print ("* ",end=" ")
print ("")

[Link] @teluguwebguru
Python Programming Notes TeluguWebGuru

Program to print hollow rhombus or parallelogram star pattern

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

for i in range(1,6):
for j in range(1,(5-i)+1):
print (" ",end=" ")
for j in range(1,6):
if(i==1 or i==5 or j==1 or j==5):
print ("* ",end=" ")
else:
print (" ",end=" ");
print ("")

Multiplication tables (how many tables, what are they)


Read n
l=[]
For i in range(1,n+1):
​ a=int(input(f“enter {i} value”))
​ [Link](a)

For x in l:
​ For k in range(1,11):
​ ​ print(f”{x} X {k} = {x*k}”)

—-----
Perfect or not (sum of factors must be equal to the number)

—-----

Print function escape sequences:


​ \n \t \\ \’ \”

String functions:
1)​capitalization: [Link]()
It converts first letter of first word into capital
2)​title()
It converts every word’s first letter into capital
3)​swapcase()

[Link] @teluguwebguru
Python Programming Notes TeluguWebGuru

Converts the lowercase into upper and uppercase into lower.


4)​upper()
Converts whole string into uppercase
5)​lower()
Converts whole string into lowercase
6)​isupper()
True - if total string is in uppercase
7)​islower()
True - if total string is in lowercase
8)​isalpha()
True - if string contains only alphabets(not even spaces)
9)​isdigit()
​ ​ True- if it contains only numbers
10)​ isalnum()
True- if it contains only alphabets and numbers (not even
spaces)
11)​ split

It returns list of words from that string


Default delimiter is space

We can set our own delimiter as [Link](“-”)

12)​ join()
[Link](k) -> it joins every word of list k with empty string
h and result will be stored in h

[Link] @teluguwebguru
Python Programming Notes TeluguWebGuru

Shallow Copy Vs Deep Copy:

In Python, shallow copy and deep copy are distinct methods for creating
copies of objects, particularly relevant when dealing with mutable objects
and nested data structures.

Shallow Copy:

●​ A shallow copy creates a new compound object but populates it with


references to the same objects found in the original.
●​ This means that while the top-level container (e.g., a list) is a new object, any
mutable objects nested within it (e.g., another list inside the first list) are not
copied; instead, their references are copied.
●​ Consequently, modifications to mutable nested objects in either the original or
the shallow copy will be reflected in both, as they point to the same underlying
data.
●​ Shallow copies are typically faster and consume less memory than deep
copies, as they do not involve recursive copying of nested structures.
●​ The [Link]() function from the copy module or slicing ([:] for lists)
can be used to perform a shallow copy.
●​

Deep Copy:

●​ A deep copy creates a new compound object and recursively inserts copies of
all objects found in the original, including nested mutable objects.
●​ This ensures that the copied object is entirely independent of the original.
●​ Changes made to the deep-copied object or its nested elements will not affect
the original, and vice versa.
●​ Deep copies are more resource-intensive (slower and consume more
memory) due to the recursive nature of the copying process.
●​ The [Link]() function from the copy module is used to perform a
deep copy.

>>> import copy


>>> l=[10,20,30]

[Link] @teluguwebguru
Python Programming Notes TeluguWebGuru

>>> id(l)
1991552457216
>>> for i in l:
... print(i,id(i))
...
10 140715173627080
20 140715173627400
30 140715173627720
>>> m=[Link](l)
>>> id(m)
1991552461952
>>> for i in m:
... print(i,id(i))
...
10 140715173627080
20 140715173627400
30 140715173627720
>>> import copy
>>> l=[[1,2,3],[10,20,30]]
>>> print(l,id(l))
[[1, 2, 3], [10, 20, 30]] 1991552464768
>>> for i in l:
... print(i,id(i))
...
[1, 2, 3] 1991552465344
[10, 20, 30] 1991552461504
>>> m=[Link](l)
>>> print(m,id(m))
[[1, 2, 3], [10, 20, 30]] 1991552466048
>>> for i in m:
... print(i,id(i))
...
[1, 2, 3] 1991552465344
[10, 20, 30] 1991552461504
>>> n=[Link](l)
>>> print(n,id(n))
[[1, 2, 3], [10, 20, 30]] 1991552465600
>>> for i in n:
... print(i,id(i))
...
[1, 2, 3] 1991552434112
[10, 20, 30] 1991552460416

[Link] @teluguwebguru
Python Programming Notes TeluguWebGuru

Functions in Python:

Functions in Python are self-contained blocks of code designed to


perform a specific task. They are fundamental for organizing
code, promoting reusability, and improving readability and
maintainability.

Creating/Defining a Function:
Functions are defined using the def keyword, followed by the
function name, parentheses for parameters, and a colon. The
function's code block is indented.

def function_name(parameter1, parameter2):


# Function body
# Perform operations
return result # Optional: return a value

function_name(parameter values) → Function call

Function approaches
Not Taking input from function call - process in func body -
print result

Not Taking input from function call - process in func body -


return result

Taking input from function call - process in func body - print


result

Taking input from function call - process in func body - return


result

a,b,c=add()

res=add() → it stores result in tuple

[Link] @teluguwebguru
Python Programming Notes TeluguWebGuru

Global and local variables


global keyword

globals()

In Python, the globals() function is used to return the global


symbol table - a dictionary representing all the global variables
in the current module or script. It provides access to the global
variables that are defined in the current scope. This function is
particularly useful when you want to inspect or modify global
variables dynamically during the execution of the program.

Keys: Variable names (as strings) that are defined globally in


the script.
Values: The corresponding values of those global variables.

print(globals())
print("")

p,q,r,s=10,100,1000,10000
print(globals())

{'__name__': '__main__', '__doc__': None, '__package__': None,


'__loader__':
<class '_frozen_importlib.BuiltinImporter'>, '__spec__': None,
'__annotations__': {},
'__builtins__': <module 'builtins' (built-in)>}

{'__name__': '__main__', '__doc__': None, '__package__': None,


'__loader__':
<class '_frozen_importlib.BuiltinImporter'>, '__spec__': None,
'__annotations__': {},
'__builtins__': <module 'builtins' (built-in)>, 'p': 10, 'q':
100, 'r': 1000,'s':10000}

Explanation:

The first print(globals()) displays the global symbol table,


which includes built-in variables and functions.
After defining the variables p, q, r, and s, the second
print(globals()) shows the updated global symbol table, now
including these variables with their assigned values.

[Link] @teluguwebguru
Python Programming Notes TeluguWebGuru

Anonymous or Lambda Functions:

In Python, an anonymous function is a function defined without a


name, also known as a lambda function. These functions are
typically used for short, simple (Instant) operations and are
defined using the lambda keyword.

variable=lambda parameters-list: expression

It contains single executable statement(not multiple statements)

Example

​ sum=lambda a,b:a+b
res=sum(10,20)
Here sum is an object of type function class and it can be used
for function calls.

—-------
Conditional operator in python
a if a>b else b
—---------

vowelcheck=lambda w:”vowel” if w==’a’ or w==’e’ or w==’i’ or w==o


or w==’u’ else “consonant”

—---------------

[Link] @teluguwebguru
Python Programming Notes TeluguWebGuru

Default arguments example


def greet(name, greeting="Hello"):
print(f"{greeting}, {name}!")

greet("Alice")
greet("Bob", "Hi")

[Link] @teluguwebguru
Python Programming Notes TeluguWebGuru

3 special functions:
1)​filter
2)​map
3)​reduce

The filter() function in Python is a built-in function used to


construct an iterator from elements of an iterable for which a specific
function returns True.

filter (function,iterable)

function:
This is a function that takes a single element from the iterable as
input and returns a boolean value (True or False). Elements for which
this function returns True are included in the filtered output. This
can be a user-defined function, a built-in function, or a lambda
function.

iterable:
This is the sequence (e.g., list, tuple, set, string) that you want to
filter.

Return Value:
The filter() function returns an iterator (a filter object). To obtain
a list, tuple, or other collection of the filtered elements, you
typically need to explicitly convert this iterator using functions like
list(), tuple(), etc.

Example:
To filter out even numbers from a list:​

numbers={1,2,3,4,5,6,7,8,9,10,11,12,13,14,15}

result=filter(lambda n:n%2==0,numbers)

print(list(result))

example-2:Filter words with more than 3 letters

words = ['the', 'sun', 'is', 'shining', 'bright']


long_words = list(filter(lambda w: len(w) > 3, words))
print(long_words) # Output: ['shining', 'bright']

[Link] @teluguwebguru
Python Programming Notes TeluguWebGuru

Example-3 : filter positive numbers


nums = [-5, -2, 0, 1, 7]
non_negative = list(filter(lambda x: x >= 0, nums))
print(non_negative) # Output: [0, 1, 7]

map:

The map() function in Python is a built-in higher-order function used


to apply a specified function to each item in an iterable (such as a
list, tuple, or set) and return an iterator containing the results.

Transform one list of values into another list by applying consistent


function on each element.

Syntax:

map(function, iterable, ...)

Example-1:

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

# Using a lambda function to square each number


squared_numbers = map(lambda x: x**2, numbers)
print(list(squared_numbers)) # Output: [1, 4, 9, 16, 25]

Example-2:Convert all strings to uppercase

names = ['alice', 'bob', 'charlie']


upper_names = list(map([Link], names))
print(upper_names) # Output: ['ALICE', 'BOB', 'CHARLIE']

Example 3: Add 10 to each number

nums = [10, 20, 30]


plus_ten = list(map(lambda x: x + 10, nums))
print(plus_ten) # Output: [20, 30, 40]

[Link] @teluguwebguru
Python Programming Notes TeluguWebGuru

filter vs map :

In Python, map() and filter() are built-in functions that operate on


iterables, but they serve different purposes:

map

Purpose:
map() applies a given function to every item in an iterable (like a
list, tuple, etc.) and returns a new iterable (a map object) containing
the results.
Transformation:
It's used for transforming data, where you want to change each element
in a consistent way.
Output Size:
The output iterable will have the same number of elements as the input
iterable.

filter

Purpose:

filter() constructs an iterator from elements of an iterable for which


a function returns True. It selects elements that satisfy a specific
condition.

Selection/Filtering:
It's used for filtering data, where you want to keep only the elements
that meet certain criteria.

Output Size:
The output iterable (a filter object) may have fewer elements than the
input iterable, as elements failing the condition are discarded.

—---------

We can tell an example of numbers list with positive and negative


numbers where we can find positive numbers list using filter and then
use map to calculate double of that number

—-----------

List of words in reverse order example


words=input().split()
rwords=list(map(lambda w:w[::-1],words))

[Link] @teluguwebguru
Python Programming Notes TeluguWebGuru

print (rwords)

—---------------------------

reduce

The reduce() function in Python is a higher-order function that applies


a specified function cumulatively to the items of an iterable, reducing
the iterable to a single value. It is part of the functools module and
needs to be imported explicitly.

from functools import reduce

reduce(function, iterable[, initializer])

Example-1:

from functools import reduce

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

# Summing elements using reduce()


sum_result = reduce(lambda x, y: x + y, numbers)
print(f"Sum: {sum_result}")

Example-2: product

from functools import reduce

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

# Finding the product of elements using reduce()


product_result = reduce(lambda x, y: x * y, numbers)
print(f"Product: {product_result}")

Example-3: find max number


nums = [10, 50, 32, 75, 23]
maximum = reduce(lambda a, b: a if a > b else b, nums)
print(maximum) # Output: 75

[Link] @teluguwebguru
Python Programming Notes TeluguWebGuru

Modules in Python:

A module is a file containing Python definitions and statements.

Modules are collection of global variables, functions and classnames

In Python, a module is a file containing Python definitions and


statements, typically saved with a .py extension. Modules serve as a
way to organize related code into logical units, making programs more
structured, reusable, and easier to manage.

Key characteristics of Python modules:

Organization:
Modules allow you to group related functions, classes, and variables
into a single file.

Reusability:
Code defined in a module can be imported and used in other Python
scripts or modules, promoting code reuse and reducing redundancy.

Namespace:
Each module has its own distinct namespace, preventing naming conflicts
when combining code from different sources.

Importability:
Modules can be imported using the import statement, making their
contents accessible within the importing script.

— —-----
discuss one example that shows using variables and functions of one
program is not possible in another program

Then discuss what are modules

How to solve this case

What are the limitations of modules (same folder


—------

Functions are meant for providing reusability within the same program
only

To resolve this modules are introduced

But modules have a limitation that all files must be within same folder
—------

[Link] @teluguwebguru
Python Programming Notes TeluguWebGuru

Within a module, the module’s name (as a string) is available as the


value of the global variable __name__. For instance, use your favorite
text editor to create a file called [Link] in the current directory
with the following contents:

—----------
2 types of modules
1)​Pre-defined (Builtin)
2)​User Defined Modules

Pre-defined are already defined by python. We can use those by


importing into our programs
Default imported pre-defined module by all python programs is
“builtins”

User defined are defined by developers as per their requirements

—-----------

To define user defined module

Define global variables


Define functions
Define classes

And save program with [Link]

Whenever a module is created python automatically creates a folder


called __pycache__ and stores compiled bytecode files of Python modules
with the names in the format of [Link]

Using modules in other files:

1)​By using import statement


4 ways
i) import modulename —> imports one module
ii) import module1,module2,module3 —> import 3 modules
iii)import modulename as a (alias name)
iv) import module1 as m1,module2 as m2
2)​By using from … import
i) from modulename import variablenames,functionnames,class
ii) from module import var1 as a,func1 as b,class1 as c
iii)from module import * (Not recommended)

[Link] @teluguwebguru
Python Programming Notes TeluguWebGuru

Discuss example like


1)​Calculate reverse of a number in one module and check palindrome
or not in another module

Built-in Modules:

Type help(‘modules’) in python prompt to get complete details of


modules

●​ os module

●​ random module

●​ math module

●​ time module

●​ sys module

●​ collections module

●​ statistics module

os module

This module has functions to perform many tasks of operating system.

mkdir():

We can create a new directory using mkdir() function from os module.

>>> import os

>>> [Link]("d:\\tempdir")

A new directory corresponding to path in string argument in the function will be created. If we

open D drive in Windows explorer we should notice tempdir folder created.

chdir():

To change current working directory to use chdir() function.

>>> import os

[Link] @teluguwebguru
Python Programming Notes TeluguWebGuru

>>> [Link]("d:\\temp")

getcwd():

This function in returns name off current working directory.

>>> [Link]()

'd:\\temp'

Directory paths can also be relative. If current directory is set to D drive and then to temp without

mentioning preceding path, then also current working directory will be changed to d:\temp

>>> [Link]("d:\\")
>>> [Link]()
'd:\\'
>>> [Link]("temp")
>>> [Link]()

'd:\\temp'

In order to set current directory to parent directory use ".." as the argument to chdir() function.

>>> [Link]("d:\\temp")
>>> [Link]()
'd:\\temp'
>>> [Link]("..")
>>> [Link]()

'd:\\'

rmdir():

The rmdir() function in os module removes a specified directory either with absolute or relative

path. However it should not be the current working directory and it should be empty.

>>> [Link]("tempdir")
>>> [Link]()
'd:\\tempdir'
>>> [Link]("d:\\temp")
PermissionError: [WinError 32] The process cannot access the file
because it is being used by another process: 'd:\\temp'

[Link] @teluguwebguru
Python Programming Notes TeluguWebGuru

>>> [Link]("..")

>>> [Link]("temp")

listdir():

The os module has listdir() function which returns list of all files in specified directory.

>>> [Link]("c:\\Users")

['acer', 'All Users', 'Default', 'Default User', '[Link]',

'Public']

random module

Python’s standard library contains random module which defines various functions for handling

randomization. Python uses a pseudo-random generator based upon Mersenne Twister

algorithm that produces 53-bit precision floats. Functions in this module depend on

pseudo-random number generator function random() which generates a random float number

between 0.0 and 1.0.

[Link](): Returns a random float number between 0.0 to 1.0. The function doesn’t

need any arguments

>>> import random


>>> [Link]()

0.755173688207591

Other functions in random module are described here:​

[Link](): Returns a random integer between the specified integers

>>> import random


>>> [Link](1,100)
58
>>> [Link](1,100)

[Link] @teluguwebguru
Python Programming Notes TeluguWebGuru

91

[Link](): Returns a random element from the range created by start, stop and step

arguments. The start , stop and step parameters behave similar to range() function.

>>> [Link](1,10)
2
>>> [Link](1,10,2)
3
>>> [Link](0,101,10)

40

[Link](): Returns a randomly selected element from a sequence object such as string,

list or tuple. An empty sequence as argument raises IndexError

>>> import random


>>> [Link]('computer')
'o'
>>> [Link]([12,23,45,67,65,43])
65
>>> [Link]((12,23,45,67,65,43))

23

[Link](): This function randomly reorders elements in a list.

>>> numbers=[12,23,45,67,65,43]
>>> [Link](numbers)
>>> numbers
[23, 12, 43, 65, 67, 45]
>>> [Link](numbers)
>>> numbers

[23, 43, 65, 45, 12, 67]

[Link] @teluguwebguru
Python Programming Notes TeluguWebGuru

math module

This module presents commonly required mathematical functions.

●​ trigonometric functions

●​ representation functions

●​ logarithmic functions

●​ angle conversion functions

In addition, two mathematical constants are also defined in this module.

Pie π which is defined as ratio of circumference to diameter of a circle and its value is

3.141592653589793, is available in math module.

>>> import math


>>> [Link]

3.141592653589793

Another mathematical constant in this module is e. It is called Euler’s number and is a base of

natural logarithm. Its value is 2.718281828459045

>>> math.e

2.718281828459045

[Link](81)

[Link](6.35) -> round to the next largest int

[Link](6.35)->6

[Link](2,7)

[Link](-5.65)->5.65 returns absolute number as a float

[Link](5)

[Link](2)

[Link] @teluguwebguru
Python Programming Notes TeluguWebGuru

Trigonometric functions:

radians(): converts angle in degrees to radians.(Note: π radians is equivalent to 180 degrees)

>>> [Link](30)

0.5235987755982988

degrees(): converts angle in radians to degree.

>>> [Link]([Link]/6)

29.999999999999996

Following statements show sin, cos and tan ratios for angle of 30 degrees (0.5235987755982988

radians)

>> [Link](0.5235987755982988)
0.49999999999999994
>>> [Link](0.5235987755982988)
0.8660254037844387
>>> [Link](0.5235987755982988)

0.5773502691896257

[Link](): returns natural logarithm of given number. Natural logarithm is calculated to the base

e.

math.log10(): returns base-10 logarithm or standard logarithm of given number.

>>> math.log10(10)

1.0

[Link](): returns a float number after raising e (math.e) to given number. exp(x) is equivalent

to e**x

[Link] @teluguwebguru
Python Programming Notes TeluguWebGuru

>>> math.log10(10)
1.0
>>> math.e**10

22026.465794806703

[Link](): This function receives two float arguments, raises first to second and returns the

result. pow(4,4) is equivalent to 4**4

>>> [Link](4,4)
256.0
>>> 4**4

256

[Link](): This function computes square root of given number

>>> [Link](100)
10.0
>>> [Link](3)

1.7320508075688772

Representation functions:

The ceil() function approximates given number to smallest integer greater than or equal to given

floating point number. The floor() function returns a largest integer less than or equal to given

number

>>> [Link](4.5867)
5
>>> [Link](4.5687)

[Link] @teluguwebguru
Python Programming Notes TeluguWebGuru

sys module

This module provides functions and variables used to manipulate different parts of the Python
runtime environment.

[Link]

This return list of command line arguments passed to a Python script. Item at 0th index of this
list is always the name of the script. Rest of the arguments are stored at subsequent indices.

Here is a Python script ([Link]) consuming two arguments from command line.

import sys

print ("My name is {}. I am {} years old".format([Link][1],


[Link][2]))

This script is executed from command line as follows:

C:\python37>python [Link] Anil 23

My name is Anil. I am 23 years old

[Link]

This causes program to end and return to either Python console or command prompt. It is used
to safely exit from program in case of exception.

[Link]

It returns the largest integer a variable can take.

>>> import sys


>>> [Link]

9223372036854775807

[Link]

This is an environment variable that returns search path for all Python modules.

[Link] @teluguwebguru
Python Programming Notes TeluguWebGuru

>>> [Link]

['', 'C:\\python37\\Lib\\idlelib', 'C:\\python37\\[Link]',


'C:\\python37\\DLLs', 'C:\\python37\\lib', 'C:\\python37',
'C:\\Users\\acer\\AppData\\Roaming\\Python\\Python37\\site-packages',
'C:\\python37\\lib\\site-packages']

[Link], [Link], [Link]

These are file objects used by the interpreter for standard input, output and errors. stdin is used
for all interactive input (Python shell). stdout is used for the output of print() and of input(). The
interpreter’s prompts and error messages go to stderr.

[Link]

This attribute displays a string containing version number of current Python interpreter.

collections module

This module provides alternatives to built-in container data types such as list, tuple and dict.

namedtuple() function

This function is a factory function that returns object of a tuple subclass with named fields. Any
valid Python identifier may be used for a field name except for names starting with an
underscore.

[Link](typename, field-list)

The typename parameter is the subclass of tuple. Its object has attributes mentioned in field list.
These field attributes can be accessed by lookup as well as by its index.

Following statement declares a employee namedtuple having name, age and salary as fields

>>> import collections


>>> employee=[Link]('employee', [name, age, salary])
To create a new object of this namedtuple

>>> e1=employee("Ravi", 251, 20000)

[Link] @teluguwebguru
Python Programming Notes TeluguWebGuru

Values of the field can be accessible by attribute lookup

>>> [Link]

'Ravi'

Or by index

>>> e1[0]

'Ravi'

OrderedDict() function

Ordered dictionary is similar to a normal dictionary. However, normal dictionary the order of
insertion of keys in it whereas ordered dictionary object remembers the same. The key-value
pairs in normal dictionary object appear in arbitrary order.

>>> d1={}
>>> d1['A']=20
>>> d1['B']=30
>>> d1['C']=40

>>> d1['D']=50

We then traverse the dictionary by a for loop,

>>> for k,v in [Link]():


print (k,v)

A 20
B 30
D 50

C 40

But in case of OrderedDict object:

>>> import collections


>>> d2=[Link]()
>>> d2['A']=20
>>> d2['B']=30

[Link] @teluguwebguru
Python Programming Notes TeluguWebGuru

>>> d2['C']=40

>>> d2['D']=50

Key-value pairs will appear in the order of their insertion.

>>> for k,v in [Link]():


print (k,v)
A 20
B 30
C 40

D 50

deque() function

A deque object supports append and pop operation from both ends of a list. It is more memory
efficient than a normal list object because in a normal list, removing one of iem causes all items
to its right to be shifted towards left. Hence it is very slow.

>>> q=[Link]([10,20,30,40])
>>> [Link](110)
>>> q
deque([110, 10, 20, 30, 40])
>>> [Link](41)
>>> q
deque([0, 10, 20, 30, 40, 41])
>>> [Link]()
40
>>> q
deque([0, 10, 20, 30, 40])
>>> [Link]()
110
>>> q

deque([10, 20, 30, 40])

statistics module

[Link] @teluguwebguru
Python Programming Notes TeluguWebGuru

This module provides following statistical functions :​



mean() : calculate arithmetic mean of numbers in a list

>>> import statistics


>>> [Link]([2,5,6,9])

5.5

median() : returns middle value of numeric data in a list. For odd items in list, it returns value at
(n+1)/2 position. For even values, average of values at n/2 and (n/2)+1 positions is returned.

>>> import statistics


>>> [Link]([1,2,3,8,9])
3
>>> [Link]([1,2,3,7,8,9])

5.0

mode(): returns most repeated data point in the list.

>>> import statistics


>>> [Link]([2,5,3,2,8,3,9,4,2,5,6])

stdev() : calculates standard deviation on given sample in the form of list.

>>> import statistics


>>> [Link]([1,1.5,2,2.5,3,3.5,4,4.5,5])

1.3693063937629153

time module

This module has many time related functions.

time():

This function returns current system time in ticks. The ticks is number of seconds elapsed after
epoch time i.e. 12.00 am, January 1, 1970.

[Link] @teluguwebguru
Python Programming Notes TeluguWebGuru

>>> [Link]()

1544348359.1183174

localtime():

This function translates time in ticks in a time tuple notation.

>>> tk=[Link]()
>>> [Link](tk)

time.struct_time(tm_year=2018, tm_mon=12, tm_mday=9, tm_hour=15,


tm_min=11, tm_sec=25, tm_wday=6, tm_yday=343, tm_isdst=0)

asctime():

This functions returns a readable format of local time

>>> tk=[Link]()
>>> tp=[Link](tk)
>>> [Link](tp)

'Sun Dec 9 15:11:25 2018'

ctime():

This function returns string representation of system's current time

>>> [Link]()

'Sun Dec 9 15:17:40 2018'

sleep():

This function halts current program execution for a specified duration in seconds.

>>> [Link]()
'Sun Dec 9 15:19:14 2018'
>>> [Link](20)
>>> [Link]()

'Sun Dec 9 15:19:34 2018'

[Link] @teluguwebguru
Python Programming Notes TeluguWebGuru

Exception Handling in Python:

Exception handling in Python is a mechanism for managing runtime errors


that occur during program execution, preventing the program from
crashing and allowing for graceful error recovery. It involves using
try, except, else, and finally blocks.

Compile time errors


Logical errors
Run time errors (exceptions)

Compile time errors(.py->.pvc) occur during the compilation process.


These type of errors occur due to wrong [Link] are solved by
developers during development time

Logical errors occur during execution time (.pvc->pvm). These errors


occur due to wrong [Link] can be solved by developers during
development time

Runtime errors occur during execution time or run time. These errors
occur due to wrong input entered by the end user. Every developer must
concentrate their time here to convert technical error messages to user
friendly messages.

SyntaxError:

while True print('Hello world')


File "<stdin>", line 1
while True print('Hello world')
^^^^^
SyntaxError: invalid syntax

>>>10 * (1/0)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
10 * (1/0)
~^~
ZeroDivisionError: division by zero

>>>4 + spam*3
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
4 + spam*3
^^^^
NameError: name 'spam' is not defined

[Link] @teluguwebguru
Python Programming Notes TeluguWebGuru

>>> '2' + 2
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
'2' + 2
~~~~^~~
TypeError: can only concatenate str (not "int") to str

num = int("forty-two")
ValueError

UnboundLocalError
The UnboundLocalError often occurs when you use a local variable within
a function or method before assigning a value to it. For example,
referencing the name variable before setting its value:

def display_name():
print(name)
name = "John"

display_name()

Traceback (most recent call last):


File "/home/stanley/code_samples/[Link]", line 1, in <module>
import arrow
ModuleNotFoundError: No module named 'arrow'

open("non_existent_file.txt", "r")
FileNotFoundError

import non_existent_module # ImportError: No module named


'non_existent_module'

"hello".append(1) # AttributeError: 'str' object has no attribute


'append'
AttributeError

[Link] @teluguwebguru
Python Programming Notes TeluguWebGuru

ZeroDivisionError
KeyError
ValueError
TypeError
IndexError
NameError
ModuleNotFoundError
AttributeError
IndentationErrror
FileNotFoundError
OSError
IOError
FileExistError
DatabaseError

Key Components of Exception Handling:


try
except
else
finally
raise

while True:
try:
x = int(input("Please enter a number: "))
break
except ValueError:
print("Oops! That was no valid number. Try again...")

[Link] @teluguwebguru
Python Programming Notes TeluguWebGuru

The try statement works as follows.

First, the try clause (the statement(s) between the try and except
keywords) is executed.

If no exception occurs, the except clause is skipped and execution of


the try statement is finished.

If an exception occurs during execution of the try clause, the rest of


the clause is skipped. Then, if its type matches the exception named
after the except keyword, the except clause is executed, and then
execution continues after the try/except block.

If an exception occurs which does not match the exception named in the
except clause, it is passed on to outer try statements; if no handler
is found, it is an unhandled exception and execution stops with an
error message.

A try statement may have more than one except clause, to specify
handlers for different exceptions. At most one handler will be
executed. Handlers only handle exceptions that occur in the
corresponding try clause, not in other handlers of the same try
statement. An except clause may name multiple exceptions as a
parenthesized tuple, for example:

... except (RuntimeError, TypeError, NameError):


... pass

[Link] @teluguwebguru
Python Programming Notes TeluguWebGuru

User-defined exception:

class MyCustomError(Exception):
pass

def check_value(value):
if value < 0:
raise MyCustomError("Value cannot be negative.")
print(f"Value is {value}")

# Example usage
try:
check_value(10)
check_value(-5)
except MyCustomError as e:
print(f"Caught a custom error: {e}")

—-------------------

# define Python user-defined exceptions


class InvalidAgeException(Exception):
"Raised when the input value is less than 18"
pass

# you need to guess this number


number = 18

try:
input_num = int(input("Enter a number: "))
if input_num < number:
raise InvalidAgeException
else:
print("Eligible to Vote")

except InvalidAgeException:
print("Exception occurred: Invalid Age")

Output
Enter a number: 45
Eligible to Vote

Enter a number: 14
Exception occurred: Invalid Age

[Link] @teluguwebguru
Python Programming Notes TeluguWebGuru

KeyError – User searches for a key not present in a dictionary

# Real-life: Lookup system for student scores


student_scores = {"John": 85, "Alice": 92}

name = input("Enter student name to view score: ")


try:
print(f"{name}'s score is: {student_scores[name]}")
except KeyError:
print(f"No score found for {name}.")

NameError – User selects an option that requires a variable that was never
defined

# Real-life: Menu-based system that forgets to define a variable


print("Choose an option:")
print("1. Show name")
print("2. Exit")

choice = input("Enter your choice: ")

if choice == "1":
print("Your name is:", user_name) # user_name is never defined!

ValueError – User enters invalid input (like a word instead of a number)


# Real-life: Asking user to enter age
try:
age = int(input("Enter your age: ")) # User enters "twenty"
print("You will be", age + 1, "years old next year.")
except ValueError:
print("Invalid input! Please enter a numeric value for age.")

[Link] @teluguwebguru
Python Programming Notes TeluguWebGuru

Banking Application:
[Link]
balance = 1000 # Global variable for account balance

def deposit(amount):
global balance
balance += amount
print(f"{amount} deposited successfully.")

def sendamount(amount):
global balance
if amount > balance:
print("Insufficient balance. Transaction failed.")
else:
balance -= amount
print(f"{amount} sent successfully.")

def showbalance():
print(f"Current balance: ₹{balance}")

[Link]

import bank

while True:
print("\n========= Bank Menu =========")
print("1. Deposit Amount")
print("2. Show Balance")
print("3. Send Payment")
print("4. Exit")
print("=============================")

choice = input("Enter your choice (1-4): ")

if choice == "1":
try:
amount = float(input("Enter amount to deposit: ₹"))
if amount <= 0:
print("Please enter a positive amount.")
else:
[Link](amount)
except ValueError:
print("Invalid input. Please enter a valid number.")

elif choice == "2":


[Link]()

[Link] @teluguwebguru
Python Programming Notes TeluguWebGuru

elif choice == "3":


try:
amount = float(input("Enter amount to send: ₹"))
if amount <= 0:
print("Please enter a positive amount.")
else:
[Link](amount)
except ValueError:
print("Invalid input. Please enter a valid number.")

elif choice == "4":


print("Thank you for using our banking system. Goodbye!")
break

else:
print("Invalid option. Please enter 1 to 4.")

[Link] @teluguwebguru
Python Programming Notes TeluguWebGuru

Decorators in Python:

In Python, a decorator is a design pattern that allows you to modify the functionality of a function
by wrapping it in another function.
Steps:
1)​ Define a normal function
2)​ Define a decorator function that contains inner function and returns inner function name
3)​ Inner function of the decorator function uses the normal function defined in step-1 and
extend/modify it’s code
4)​ Write decorator as @decorator_function_name above normal function
5)​ Call normal function
def decor(f):
def modifyit():
n=f()
print ("hello ",n)
return modifyit

@decor
def getname():
return "Santosh"

getname()

Output
hello Santosh
Example-2:
def smart_divide(func):
def inner(a, b):
print("I am going to divide", a, "and", b)
if b == 0:
print("Whoops! cannot divide")
return
return func(a, b)
return inner

@smart_divide
def divide(a, b):
print(a/b)

divide(2,5)
divide(2,0)
I am going to divide 2 and 5
0.4
I am going to divide 2 and 0
Whoops! cannot divide

[Link] @teluguwebguru
Python Programming Notes TeluguWebGuru

Files in Python:

We can store data permanently (Persistancy) by using one of the below ways
1)​ Files
2)​ Database

A File is a collection of records.


Flow between object in main memory to file in secondary memory is called a stream

Operations on Files:
1)​ Write : transferring/saving object data into file
2)​ Read : Reading / transferring the records from file into object

write operation

1)​ Choose the file name


2)​ Open the file in write mode
3)​ Perform write operations

Exception related to Files


1)​ IOError
2)​ FileExistsError
3)​ OSError

Read Operation

1)​ Choose the file name


2)​ Open the file in read mode
3)​ Perform read operations

Exceptions related to read mode:


1)​ FileNotFoundError
2)​ EOFError

Files Types
1)​ Text File : contains data in the form of alphabets, digits and special symbols. Denoted by
letter ‘t’ and it is default
2)​ Binary File : contains data in the form of binary format (0,1) or pixels . These are denoted
by a letter called ‘b’
Examples includes all image files, video files, audio files

[Link] @teluguwebguru
Python Programming Notes TeluguWebGuru

File Opening modes:


r- used for opening the file in read mode and this is default mode

w-used for creating and opening a new file / opening an existing file in write mode. Incase of
existing file, new data will replaces the old data

a- used for creating and opening a new file / opening an existing file in write mode. Incase of
existing file, new data will appends to the existing old data

r+- used for opening the file in read mode. Once after opened the file, first we can read the data
and then we can also write data,

w+ - used for creating and opening a new file / opening an existing file in write mode. Incase of
existing file, new data will replaces the old data. First we can write and then we can also read

a+- used for creating and opening a new file / opening an existing file in write mode. Incase of
existing file, new data will appends to the existing old data. After writing we can able to read
also

x- exclusive mode : creating the file and opening in write mode exclusively. It file already exists
it returns FileExistsError

x+- exclusive mode : creating the file and opening in write mode exclusively. If the file already
exists it returns FileExistsError. After write we can read also

Approaches to open a file:


1)​ open()
2)​ with open() as

open()

varname=open(filename,file mode)

xyz=open(“[Link]”,’r’)

Here variable name is of type _Io.TextIOWrapper

[Link] @teluguwebguru
Python Programming Notes TeluguWebGuru

with open() as

with open(filename,file mode) as variablename:


Block of statements

with open(“[Link]”,”r”) as xyz:


Statements
In this option we no need to close the file. The system will close the file on behalf of us. Because
it calls __entry__ and __exit__ on behalf of us.

—---------------------------

Example1:

xyz=open(“[Link]”,”r”)
print([Link])
[Link]
[Link]()
[Link]()
[Link]

—------------------------------

Writing:

write() —> [Link](str data)


writelines() —> [Link](iterable)

Python program to demonstrate how to write data to the file


with open(“[Link]”,”w”) as f:
[Link](str(250))
[Link](“python”)
[Link](str(11.11))

[Link] @teluguwebguru
Python Programming Notes TeluguWebGuru

Reading:

​ read() - to read entire contents of the file at a time and return as a string

​ readlines() - to read file contents and return as a list of strings where each line of the file
will be represented as an element in the list

Writing data dynamically:

Press $ to stop

while(True):
d=input(“enter some data”)
if(d!=”$”):
[Link](d)
else:
Break

File copy:

sf=input(“enter src file”)


df=input(“enter dest file”)

with open(sf,”r”) as fr:


with open(df,”w”) as fw:
[Link]([Link]())

[Link] @teluguwebguru
Python Programming Notes TeluguWebGuru

Pickling and Unpickling in Python:

Python Pickling
Pickling is the Python term for serializing an object, which entails transforming it into a binary
representation that can be stored in a file or communicated over a network. Python has built-in
functions for the pickling objects in the pickle module.

Example: Python Object Serialization

In this example, we are creating a file named '[Link]' that stores the serialized form of a
Python object. We will create a dictionary object 'person' which will be serialized. The file object
represents the file that will be used for writing the pickled object. The [Link]() function is
then used to pickle the person object to the file. It takes two arguments - the object to be pickled
and the file object to which the pickled object should be written.

import pickle

# Define a Python object


person = {
“name”: “Alice”,
“age”: 30,
“gender”: “female”;
}

# Pickle the object to a binary file


with open(“[Link]”, “wb”) as file:
[Link](person, file)

print(“Pickling completed”)

[Link] @teluguwebguru
Python Programming Notes TeluguWebGuru

Unpickling in Python
In Python, deserializing a pickled object entails turning it from its binary representation back to a
Python object that can be used in code. This process is known as unpickling. Python's built-in
pickle module has functions for unpickling objects.

Example: Python Object Deserializing

In this example, we will load the pickle file in our Python code using the load() function of the
pickle module. The [Link]() function is used to deserialize and unpickle the object from the
file. It takes one argument - the file object from which the object should be loaded. The unpickled
object is stored in the variable data.

import pickle

# load the data from a file


with open('[Link]', 'rb') as f:
data = [Link](f)

# print the data


print(data)

[Link] @teluguwebguru
Python Programming Notes TeluguWebGuru

Reading data from csv files without using csv modules :

with open(“[Link]”,”r”) as fp:


data=[Link]()
print(data)

Reading data from csv files with using csv module:


import csv
with open(“[Link]”,”r”) as fp:
c=[Link](fp)
for i in c:
for j in i:
print(j,end=” “)

Creating csv file from python program:


inport csv
h=[“empno”,”ename”,”designation”]
d=[ [1,”Santosh”,”Director”], [2,”Suresh”,”Manager”], [3,”Sateesh”,”Manager”],
[4,”Kishore”,”Developer”], [5,”Mahesh”,”Tester”] ]
with open(“[Link]”,”a”) as fp:
w=[Link](fp)
[Link](h)
[Link](d)

[Link] @teluguwebguru
Python Programming Notes TeluguWebGuru

Generators in Python:

In Python, a generator is a special type of function or expression that creates an iterator,


allowing for the generation of a sequence of values lazily, one at a time, rather than storing all
values in memory simultaneously. This makes them highly memory-efficient, especially when
dealing with large datasets or infinite sequences.

Key characteristics of Python generators:

Yield keyword:
Instead of return, generator functions use the yield keyword to produce a value. When yield is
encountered, the function's execution is paused, and the yielded value is returned to the caller.
The state of the function is saved, and it can resume from where it left off when the next value is
requested.

Lazy evaluation:
Values are generated on demand as they are iterated over, rather than being computed and stored
upfront. This is the core of their memory efficiency.

Iterator protocol:
Generators automatically implement the iterator protocol, meaning they can be directly used in
for loops and other contexts that expect iterators.

Generator expressions:
Similar to list comprehensions, generator expressions provide a concise way to create generators
using a compact syntax, e.g., (item for item in iterable)

def count_up_to(n):
count = 1
while count <= n:
yield count
count += 1

# Using the generator


my_generator = count_up_to(5)

print(next(my_generator))

[Link] @teluguwebguru
Python Programming Notes TeluguWebGuru

def firstn(n):
i=0
while i<n:
yield i
i=i+1

sum_of_first_n = sum(firstn(1000000))

iter() Function:
The iter() function is used to obtain an iterator from an iterable object. An iterable is any object
that can be iterated over (e.g., lists, tuples, strings, dictionaries).
When iter() is called on an iterable, it returns an iterator object. This iterator object has a
__next__() method that can be called to retrieve the next item in the sequence.
The iter() function is fundamental to how for loops and other iteration constructs work in Python.

yield Keyword:
The yield keyword is used within a function to define a generator function.
When a generator function is called, it does not execute immediately. Instead, it returns a
generator object.

The yield keyword pauses the execution of the generator function and returns a value. When the
generator is iterated over (e.g., in a for loop or by calling next()), the function resumes from
where it left off after the yield statement.
Generators are a special type of iterator that generate values on the fly, one at a time, without
storing the entire sequence in memory. This makes them highly memory-efficient, especially for
large or infinite sequences.

Key Differences:
Purpose:
iter() converts an existing iterable into an iterator, while yield creates a generator function that
generates values on demand.
Return Value:
iter() returns an iterator object from an existing iterable. yield returns a generator object from a
generator function.
Memory Usage:
iter() works with existing data structures, which might consume significant memory if the iterable
is large. yield creates values lazily, resulting in lower memory consumption, especially for large
datasets or infinite sequences.
Definition:
iter() is a built-in function. yield is a keyword used within a function definition.
State Management:

[Link] @teluguwebguru
Python Programming Notes TeluguWebGuru

Generators (using yield) automatically manage their internal state (local variables, execution
point) between successive yield calls. Iterators created with iter() rely on the underlying iterable's
ability to provide the next item.

Database Connectivity in Python:


Issues with Files:
1)​ Files lacking security
2)​ Data searching becomes more complex as it does not store data in organizing way
3)​ File Archiving may differ from one os to another os

Database :
​ Collection of records
Data is stored in the form of relations (tables)
​ We can access any database from python programs
​ We need to use third party modules to develop python database connectivity

Softwares:
Python
​ Oracle Installation

Select * from global_name returns service name of oracle

To connect python with oracle database install oracledb module

python -m pip install oracledb --upgrade --user


import oracledb
import getpass

un = "twguser"
cs = "localhost:1521/XE" # for Oracle Database Free users
pw = [Link](f"Enter password for {un}@{cs}: ")

with [Link](user=un, password=pw, dsn=cs) as connection:


... with [Link]() as cursor:
... sql = "select sysdate from dual"
... for r in [Link](sql):
... print(r)

[Link] @teluguwebguru
Python Programming Notes TeluguWebGuru

Create Table example:

import oracledb
with [Link](user="system", password="Twg12345",dsn="localhost/xe") as
connection:
with [Link]() as cursor:
[Link]("create table student(rno INT,name varchar(100))")

—---------
To insert values dynamically from variables

q=”insert into student values(%d,’%s’,%f)”


[Link](q %(rno,sname,marks))

import oracledb
with [Link](user="system", password="Twg12345",dsn="localhost/xe") as
connection:
with [Link]() as cursor:
#[Link]("create table student(rno INT,name varchar(100))")
rno=int(input("Enter roll number: "))
name=input("Enter name: ")
[Link]("insert into student values(:r, :n)", r=rno, n=name)
[Link]()
[Link]("select * from student")
d=[Link]
for i in d:
print(i[0], end="\t")
print()
res=[Link]()
for row in res:
for i in row:
print(i, end="\t")
print()

—----------------

To fetch records from cursor


fetchone()
fetchmany(size)
fetchall()

[Link] @teluguwebguru
Python Programming Notes TeluguWebGuru

Example
import oracledb
with [Link](user="system", password="Twg12345",dsn="localhost/xe") as
connection:
with [Link]() as cursor:
#[Link]("create table student(rno INT,name varchar(100))")
[Link]("select * from student")
d=[Link]
for i in d:
print(i[0], end="\t")
print()
res=[Link]()
for row in res:
for i in row:
print(i, end="\t")
print()

MySQL Installing connector:

python -m pip install mysql-connector-python

import [Link]
con=[Link](host=”localhost”,user=”root”,passwd=”root”)
cur=[Link]()
q=”create database hospital”
[Link](q)

[Link] @teluguwebguru
Python Programming Notes TeluguWebGuru

Object Oriented Programming

Every language will satisfy one of these principles

Procedure Oriented principles (c, pascal, cobol)


Object Oriented Principles (java, python, c++)

Object Oriented Principles:


1)​ Class
2)​ Object
3)​ Data Abstraction
4)​ Encapsulation
5)​ Inheritance
6)​ Polymorphism
7)​ Message Passing

Advantages of OOP Principles:


1)​ Objects can store large volume of data
2)​ Objects can transfer large amounts of values at a time
3)​ Object data can be transferred in the form of cypher text (provides security)
4)​ Object use less amount of memory
5)​ Data is available in the form of objects

OOP: Object Management Group

Class:

To create our own data type and represent real world objects and implement real time
applications, we use classes and objects.

​ By developing our own data types we can store customized data as per our requirements

Every class name is a data type.

Definition of a class:
​ A class is a collection of data members and [Link] is a virtual entity so memory
will not be allocated to this.

​ Classes are used to develop user defined data types and store customized data

[Link] @teluguwebguru
Python Programming Notes TeluguWebGuru

Class is a virtual entity.

Object :

An object is an instance of a class. It is a real time entity.

Types of Data Members:


1)​ Instance data members
2)​ Class level data members

If we want to store this python batch details:


Sid, Sname, coursename

Here studentid and student name are different for each and every student so they are
called instance variables and coursename is common for all and that may be created as
class level variable

Syntax for defining a class:

class <class-name>:
Class level data members
def instance-method-name():
Instance data members
Statements

@classmethod
def class-method-name():
Instance data members
Statements

@staticmethod
def static-method-name():
Static data members
​ statements

[Link] @teluguwebguru
Python Programming Notes TeluguWebGuru

class Student:
coursename=”python live training”

x=Student()
print(id(x))
[Link]=”twg1”
[Link]=”Rossum”
print(x.__dict__)

Here sid and sname are instance variables / instant data members
Where coursename is class level data member

We can define instance data members after creating an object.


If we want to define instance variable inside the class then we may do so in instance methods
with the help of self keyword

class Student:
coursename=”python live training”
def initializedata(self):
[Link]=”twg2”
[Link]=”Rossum”

Class methods are used by all objects of the same class.

class Student:
coursename=”python live training”
def initializedata(self):
[Link]=”twg2”
[Link]=”Rossum”

@classmethod
def getclassdata(cls):
print([Link])

[Link] @teluguwebguru
Python Programming Notes TeluguWebGuru

Static methods in python:

Static methods will work as normal functions. Not related with class and not related with
instances also. These are like common functions that perform general tasks. We can call these
functions with class name

class Student:
coursename=”python live training”
def initializedata(self):
[Link]=”twg2”
[Link]=”Rossum”

@classmethod
def getclassdata(cls):
print([Link])

@staticmethod
def add(a,b):
print(a+b)

Constructors in Python:
We can initialize objects after creating it and calling methods.

Instead, Constructors allows us to initialize objects

Default Constructor
class Student:
​ def __init__(self):
​ ​ [Link]=1
​ ​ [Link]=”abc”

s1=Student()
print(s1.__dict__)​

Parameterized Constructor
class Student:
​ def __init__(self,p,q):
​ ​ [Link]=p
​ ​ [Link]=q

s1=Student(1,”abc”)
print(s1.__dict__)
Parameterized constructor accept arguments and initialize the object dynamically.

[Link] @teluguwebguru
Python Programming Notes TeluguWebGuru

class Student:
# Class Variable: Shared by all instances of the class.
# Used for data common to all students, like a school name.
school_name = "Central High School"
total_students = 0

def __init__(self, name, age, student_id):


# Instance Variables: Unique to each instance (object) of the class.
# Used for data specific to a particular student.
[Link] = name
[Link] = age
self.student_id = student_id
Student.total_students += 1

# Instance Method: Operates on instance variables and requires an instance to be called.


# Used for actions specific to a particular student.
def get_student_info(self):
return f"Name: {[Link]}, Age: {[Link]}, ID: {self.student_id}, School:
{Student.school_name}"

# Class Method: Operates on class variables and can be called using the class itself.
# Used for actions related to the class as a whole, like creating instances from different
inputs.
@classmethod
def create_from_string(cls, student_string):
name, age, student_id = student_string.split(',')
return cls([Link](), int([Link]()), student_id.strip())

# Static Method: Does not operate on instance or class variables.


# Used for utility functions that logically belong to the class but don't require class or
instance state.
@staticmethod
def is_adult(age):
return age >= 18

# Use Cases:

# 1. Instance Variables and Instance Methods


student1 = Student("Alice Smith", 16, "S001")
student2 = Student("Bob Johnson", 18, "S002")
print(student1.get_student_info())
print(student2.get_student_info())

# 2. Class Variables
print(f"School Name: {Student.school_name}")
print(f"Total Students: {Student.total_students}")

# 3. Class Method
student_data_string = "Charlie Brown, 17, S003"

[Link] @teluguwebguru
Python Programming Notes TeluguWebGuru

student3 = Student.create_from_string(student_data_string)
print(student3.get_student_info())

# 4. Static Method
print(f"Is Alice an adult? {Student.is_adult([Link])}")
print(f"Is Bob an adult? {Student.is_adult([Link])}")

Data Encapsulation and Data Abstraction:

Representing essential features without including background details is called Data Abstraction

__DataMember
__method

class DebitCard:
def __init__(self):
[Link]=”1111 1111 1111 1111”
self.__pin=1234
[Link]=”12/28”
self.__cvv=456

def __secretmethod(self):
print(“This is abstracted method”)

We can hide the entire class also but it is not recommended to use
class __CrediCard:
pass

[Link] @teluguwebguru
Python Programming Notes TeluguWebGuru

Inheritance:

We can achieve reusability at class level by using inheritance.

The process of acquiring variables and methods of one object of one class into another object is
called Inheritance. Because of this, The application implementation time,memory usage,
execution time will be saved and it improves application performance and removes redundancy
also

class Vehicle:
def __init__(self, make, model):
[Link] = make
[Link] = model

def display_info(self):
return f"Make: {[Link]}, Model: {[Link]}"

class Car(Vehicle):
def __init__(self, make, model, year):
super().__init__(make, model) # Call the parent class's __init__
[Link] = year

def display_info(self): # Overriding the method


return f"{super().display_info()}, Year: {[Link]}"

class Motorcycle(Vehicle):
def __init__(self, make, model, engine_size):
super().__init__(make, model)
self.engine_size = engine_size

def display_info(self):
return f"{super().display_info()}, Engine Size: {self.engine_size}cc"

# Creating instances
my_car = Car("Toyota", "Camry", 2023)
my_motorcycle = Motorcycle("Harley-Davidson", "Sportster", 1200)
print(my_car.display_info())
print(my_motorcycle.display_info())

[Link] @teluguwebguru
Python Programming Notes TeluguWebGuru

Types of Inheritance:

Single Inheritance:
Single super class -> Single Subclass
class A => class B
Multi Level Inheritance:
Super Class => Sub Class => Sub class of Sub Class
Class GrandFather => Class Parent => Class Child
Hierarchical Inheritance:
​ ​ Class A => Class B, Class C, Class D
Multiple Inheritance:
Class A, Class B, Class C => Class D

Hybrid Inheritance:
Combination of different types of inheritances

Polymorphism:

Poly + Morphic => Many Forms

We can implement this in python using method over riding and constructor over riding

From the overridden method of sub class if we call super().methodofsuperclass() then it will
execute the version of super class also.

Discuss overriding
super().greet()

[Link] @teluguwebguru
Python Programming Notes TeluguWebGuru

Regular Expressions:

Regular expressions (regex) in Python are used for pattern matching and manipulation of strings.
The re module provides the necessary functions.

Fast way to search, validate, extract, transform text.


Core functions

[Link](pat, s): first match anywhere

import re

pat=r"[a-z]-\d+"
s="This is Python Live Training Batch-1"
print([Link](pat, s))

Output:
<[Link] object; span=(33, 36), match='h-1'>

[Link](pat, s): match only at start (prefer ^… with search)


import re

pat=r"[a-z]-\d+"
s="This is Python Live Training Batch-1"
print([Link](pat, s))

Output: None

[Link](pat, s): whole string must match


import re

pat=r"[a-z]-\d+"
s="This is Python Live Training Batch-1"
print([Link](pat, s))

Output : None

[Link] @teluguwebguru
Python Programming Notes TeluguWebGuru

[Link](pat, s): list of matching substrings


import re

pat=r"[a-z]-\d+"
s="This is Python Live Training Batch-1 and we are running Batch-2 also."
print([Link](pat, s))

Output:
['h-1', 'h-2']

[Link](pat, s): iterator of Match objects


import re

pat=r"[a-z]-\d+"
s="This is Python Live Training Batch-1 and we are running Batch-2 also."
i=[Link](pat, s)
for q in i:
print(q)

Output:
<[Link] object; span=(33, 36), match='h-1'>
<[Link] object; span=(60, 63), match='h-2'>

[Link](pat, repl, s): replace; [Link] also returns count


import re

pat=r"[a-z]-\d+"
s="This is Python Live Training Batch-1 and we are running Batch-2 also."
print([Link](pat,"*****", s))

Output:
This is Python Live Training Batc***** and we are running Batc***** also.

[Link](pat, s): split by regex


import re

pat=r"[a-z]-\d+"
s="This is Python Live Training Batch-1 and we are running Batch-2 also."
print([Link](pat,s))

Output:
['This is Python Live Training Batc', ' and we are running Batc', ' also.']

[Link] @teluguwebguru
Python Programming Notes TeluguWebGuru

Pattern Building Blocks:

Character classes

●​ \d digit, \w word char, \s whitespace​

●​ Negations: \D, \W, \S​

●​ Custom sets: [abc], ranges: [a-zA-Z], negate: [^0-9]​

[Link](r"\d\d", "a1b23c456") ⇒ [‘23’,’45’]


[Link](r"[A-F][0-9]", "A1 B9 F5 Z2") # ['A1', 'F5']

Anchors & boundaries:


^ start, $ end​

\b word boundary, \B non-boundary

[Link](r"^hello", "hello\nhello", flags=re.M) # ['hello', 'hello']

[Link](r"\bcat\b", "concatenate cat scat") # ['cat']

Quantifiers

●​ * 0+, + 1+, ? 0/1


●​ {m}, {m,}, {m,n}​

●​ Greedy vs non-greedy: add ? → +?, *?, {m,n}?

s = "<p>first</p><p>second</p>"
[Link](r"<p>.*</p>", s) # ['<p>first</p><p>second</p>'] (greedy)
[Link](r"<p>.*?</p>", s) # ['<p>first</p>', '<p>second</p>'] (non-greedy)

Grouping & alternation

●​ ( … ) capture, (?: … ) non-capturing​

●​ | alternation

[Link] @teluguwebguru
Python Programming Notes TeluguWebGuru

m = [Link](r"(Mr|Ms)\. (\w+)", "Ms. Priya")


[Link](0), [Link](1), [Link](2) # ('Ms. Priya', 'Ms', 'Priya')

Example: Finding all numbers in a string


This example demonstrates how to find all sequences of digits within a given text.

import re

text = "The price is $12.99, and the quantity is 50. Discount applies to orders over 100."
pattern = r'\d+' # Matches one or more digits

# Find all non-overlapping matches of the pattern in the string


numbers = [Link](pattern, text)

print(f"Original text: {text}")


print(f"Extracted numbers: {numbers}")

Original text: The price is $12.99, and the quantity is 50. Discount
applies to orders over 100.
Extracted numbers: ['12', '99', '50', '100']

Explanation:

●​ import re: Imports the regular expression module.


●​ text: The string in which to search for patterns.
●​ pattern = r'\d+': Defines the regular expression pattern.
●​ r prefix indicates a "raw string," which prevents backslashes from
being interpreted as escape sequences by Python, ensuring they are
passed directly to the regex engine.
●​ \d is a special sequence that matches any digit (0-9).
●​ + is a quantifier that matches one or more occurrences of the
preceding character or group (\d in this case).
●​ [Link](pattern, text): This function finds all non-overlapping
matches of the pattern in the text and returns them as a list of strings.

[Link] @teluguwebguru
Python Programming Notes TeluguWebGuru

MultiThreading

Multiprocessing, multitasking, and multithreading are concepts related to concurrent


execution in computing, but they differ in their scope and underlying mechanisms:

Multitasking:
This is an operating system's ability to execute multiple tasks or programs concurrently, giving
the illusion of simultaneous execution on a single CPU. The OS rapidly switches between tasks,
allocating small time slices to each, so that all tasks appear to be progressing at the same time.
This is achieved through time-sharing and context switching.

Multithreading:
This is a technique within a single process where multiple independent sequences of execution,
called threads, can run concurrently. Threads within the same process share the same memory
space and resources, making communication and data sharing between them efficient.
Multithreading is often used to improve responsiveness in applications by allowing long-running
operations to execute in separate threads without blocking the main program's execution.

Multiprocessing:
This involves the use of multiple processing units (CPUs or CPU cores) within a single computer
system to execute multiple processes or programs truly in parallel. Each process typically has its
own independent memory space, and the operating system distributes tasks among the available
processors. Multiprocessing is used to achieve true parallelism and significantly improve
performance for computationally intensive tasks.

Key Differences:

Execution Unit:
Multitasking and multithreading operate on a single CPU core (though multithreading can
leverage multiple cores if available), while multiprocessing explicitly utilizes multiple CPU
cores.

Resource Sharing:
Threads within a process share memory and resources, while processes in multiprocessing
typically have separate memory spaces.

Concurrency vs. Parallelism:


Multitasking and multithreading achieve concurrency (appearing to run simultaneously), while
multiprocessing achieves true parallelism (actually running simultaneously on different cores).

[Link] @teluguwebguru
Python Programming Notes TeluguWebGuru

Overhead: Creating and managing processes in multiprocessing generally incurs more overhead
than creating and managing threads due to separate memory spaces and inter-process
communication requirements.

Without Threading Example

import threading
import time

print("Main Start")

def mymethod(s):
for i in range(1,11):
print(s,i)
[Link](2)

mymethod("One")
mymethod("Two")

print("Main Ends")

With Threads
import threading
import time

print("Main Thread Start")

def mymethod(s):
for i in range(1,11):
print(s,i)
[Link](1)

#main thread

t1=[Link](target=mymethod,args=("One",))
t2=[Link](target=mymethod,args=("Two",))

[Link]()
[Link]()

print("Main Thread Ends")


Main threads ends before child threads here

[Link] @teluguwebguru
Python Programming Notes TeluguWebGuru

In Python's threading module, the join() method is used to manage the execution flow of threads,
specifically to ensure that one thread waits for another to complete its execution before
proceeding.

Purpose of join():
The primary purpose of [Link]() is to block the calling thread (often the main thread) until
the thread on which join() is called terminates. This termination can occur due to:
Normal completion: The thread finishes executing its target function.

Unhandled exception: An error occurs within the thread, causing it to terminate prematurely.

Timeout: If a timeout argument is provided to join(), the calling thread will wait for a specified
duration. If the target thread does not complete within this time, the calling thread will resume
execution without waiting further.

If we add
[Link]()
[Link]()

Then main program must waits until completion of t1 and t2

Daemon threads — background helpers that don’t keep the program alive
daemon=True means this thread will not block program exit.

import threading
import time

print("Main Thread Start")

def mymethod(s):
for i in range(1,11):
print(s,i)
[Link](1)

#main thread

t1=[Link](target=mymethod,args=("One",),daemon=True)

[Link]()

print("Main Thread Ends")

[Link] @teluguwebguru
Python Programming Notes TeluguWebGuru

NUMPY Introduction:

NumPy is short for "Numerical Python".

NumPy is the fundamental package for scientific computing in Python. It is a Python


library that provides a multidimensional array object, various derived objects (such as masked
arrays and matrices), and an assortment of routines for fast operations on arrays, including
mathematical, logical, shape manipulation, sorting, selecting, I/O, discrete Fourier transforms,
basic linear algebra, basic statistical operations, random simulation and much more.

NumPy is an open source project that enables numerical computing with Python. It was
created in 2005 building on the early work of the Numeric and Numarray libraries. NumPy will
always be 100% open source software and free for all to use. Developed by Travis EL Oliphant

At the core of the NumPy package, is the ndarray object. This encapsulates n-dimensional
arrays of homogeneous data types, with many operations being performed in compiled code for
performance. There are several important differences between NumPy arrays and the standard
Python sequences:

We can use arrays concept in other programming languages to organize homogeneous elements.

Python does not have an array concept but we can implement arrays through the numpy module.

The array object in NumPy is called ndarray, it provides a lot of supporting functions that make
working with ndarray very easy.

Arrays, particularly those from libraries like NumPy, are used over Python's built-in lists in
specific scenarios due to their advantages in performance, memory efficiency, and specialized
functionalities, especially for numerical and scientific computing.

Reasons for using arrays over lists:

Why use NumPy over Python lists?

●​ Faster

●​ Requires less memory

●​ Provides vectorized operations (no for loops)

[Link] @teluguwebguru
Python Programming Notes TeluguWebGuru

Why is numpy Fast?

Vectorization describes the absence of any explicit looping, indexing, etc., in the code - these
things are taking place, of course, just “behind the scenes” in optimized, pre-compiled C code.

Installing Numpy:

We can install numpy in our system by using pip command

pip install numpy

pip list will show list of all modules packages available in the system

pip show numpy : to get details about numpy installed package

How to create an array with numpy:

import numpy
arr = [Link]([1, 2, 3, 4, 5])
print(arr)
print(type(arr))

Output:
[1 2 3 4 5]
<class '[Link]'>

We may use the alias name also while importing numpy


import numpy as np
arr = [Link]([1, 2, 3, 4, 5])
print(arr)
print(type(arr))

We can check the numpy version by using __version__

import numpy as np
print(np.__version__)

Dimensions in Arrays:

[Link] @teluguwebguru
Python Programming Notes TeluguWebGuru

A dimension in arrays is one level of array depth (nested arrays).

0-D Arrays

0-D arrays, or Scalars, are the elements in an array. Each value in an array is a 0-D array.

import numpy as np
arr = [Link](42)
print(arr)
print([Link])

Output:
42
0

1-D Arrays:

An array that has 0-D arrays as its elements is called uni-dimensional or 1-D array.

import numpy as np
arr = [Link]([1, 2, 3, 4, 5])
print(arr)
print([Link])

Output:
[1 2 3 4 5]
1

2-D Arrays:

An array that has 1-D arrays as its elements is called a 2-D array.

These are often used to represent matrix or 2nd order tensors.

import numpy as np
arr = [Link]([[1, 2, 3], [4, 5, 6]])
print(arr)
print([Link])

Output:

[Link] @teluguwebguru
Python Programming Notes TeluguWebGuru

[[1 2 3]
[4 5 6]]
2

3-D arrays:

An array that has 2-D arrays (matrices) as its elements is called 3-D array.

These are often used to represent a 3rd order tensor.

import numpy as np
arr = [Link]([[[1, 2, 3], [4, 5, 6]], [[1, 2, 3], [4, 5, 6]]])
print(arr)
print([Link])

Output:
[[[1 2 3]
[4 5 6]]

[[1 2 3]
[4 5 6]]]
3

Higher Dimensional Arrays:

An array can have any number of dimensions.


When the array is created, you can define the number of dimensions by using the ndmin
argument.

import numpy as np
arr = [Link]([1, 2, 3, 4], ndmin=5)
print(arr)
print('number of dimensions :', [Link])

Output:
[[[[[1 2 3 4]]]]]
number of dimensions : 5

NumPy Array Indexing: Accessing Array Elements

[Link] @teluguwebguru
Python Programming Notes TeluguWebGuru

Array indexing is the same as accessing an array [Link] can access an array element by
referring to its index number.

The indexes in NumPy arrays start with 0, meaning that the first element has index 0, and the
second has index 1 etc. and negative indexing also works the same as sequences.

import numpy as np
arr = [Link]([1, 2, 3, 4, 5, 6])
print(arr[0])
print(arr[-2])
print(arr[3])

Output:
1
5
4

Get third and fourth elements from the following array and add them.
import numpy as np

arr = [Link]([1, 2, 3, 4])


print(arr[2] + arr[3])

OUTPUT
7

Access 2-D Arrays:

To access elements from 2-D arrays we can use comma separated integers representing the
dimension and the index of the element.

Think of 2-D arrays like a table with rows and columns, where the dimension represents the row
and the index represents the column.

import numpy as np
arr = [Link]([[1,2,3,4,5], [6,7,8,9,10]])

[Link] @teluguwebguru
Python Programming Notes TeluguWebGuru

print('2nd element on 1st row: ', arr[0, 1])

Output:
2nd element on 1st row: 2

Access the element on the 2nd row, 5th column:

import numpy as np
arr = [Link]([[1,2,3,4,5], [6,7,8,9,10]])
print('5th element on 2nd row: ', arr[1, 4])

Output:
5th element on 2nd row: 10

Access 3-D Arrays

To access elements from 3-D arrays we can use comma separated integers representing the
dimensions and the index of the element.

import numpy as np
arr = [Link]([[[1, 2, 3], [4, 5, 6]], [[7, 8, 9], [10, 11, 12]]])
print(arr[0, 1, 2])

Output:
6

Negative Indexing

import numpy as np

arr = [Link]([[1,2,3,4,5], [6,7,8,9,10]])

print('Last element from 2nd dim: ', arr[1, -1])

Output:
Last element from 2nd dim: 10

NumPy Array Slicing:

[Link] @teluguwebguru
Python Programming Notes TeluguWebGuru

Slicing in python means taking elements from one given index to another given index.

We pass slice instead of index like this: [start:end].

We can also define the step, like this: [start:end:step].

If we don't pass start its considered 0

If we don't pass end its considered length of array in that dimension

If we don't pass step its considered 1

import numpy as np
arr = [Link]([1, 2, 3, 4, 5, 6, 7])
print(arr[1:5])

Output:
[2 3 4 5]

Slice elements from index 4 to the end of the array:

import numpy as np
arr = [Link]([1, 2, 3, 4, 5, 6, 7])
print(arr[4:])

Output:
[5 6 7]

Slice elements from the beginning to index 4 (not included):

import numpy as np
arr = [Link]([1, 2, 3, 4, 5, 6, 7])
print(arr[:4])

Output:
[1 2 3 4]

Negative Slicing

[Link] @teluguwebguru
Python Programming Notes TeluguWebGuru

Use the minus operator to refer to an index from the end:

import numpy as np
arr = [Link]([1, 2, 3, 4, 5, 6, 7])
print(arr[-3:-1])

Output
[5 6]

STEP:

Use the step value to determine the step of the slicing:

import numpy as np
arr = [Link]([1, 2, 3, 4, 5, 6, 7])
print(arr[1:5:2])

Output:
[2 4]

Return every other element from the entire array:

import numpy as np
arr = [Link]([1, 2, 3, 4, 5, 6, 7])
print(arr[::2])

Output:
[1 3 5 7]

Slicing 2-D Arrays

From the second element, slice elements from index 1 to index 4 (not included):

import numpy as np
arr = [Link]([[1, 2, 3, 4, 5], [6, 7, 8, 9, 10]])
print(arr[1, 1:4])

Output: [7 8 9]
From both elements, return index 2:

[Link] @teluguwebguru
Python Programming Notes TeluguWebGuru

import numpy as np
arr = [Link]([[1, 2, 3, 4, 5], [6, 7, 8, 9, 10]])
print(arr[0:2, 2])

Output:
[3 8]

From both elements, slice index 1 to index 4 (not included), this will return a 2-D array:

import numpy as np
arr = [Link]([[1, 2, 3, 4, 5], [6, 7, 8, 9, 10]])
print(arr[0:2, 1:4])

Output:

[[2 3 4]
[7 8 9]]

NumPy Data Types:

Data Types in Python


By default Python have these data types:

strings - used to represent text data, the text is given under quote marks. e.g. "ABCD"
integer - used to represent integer numbers. e.g. -1, -2, -3
float - used to represent real numbers. e.g. 1.2, 42.42
boolean - used to represent True or False.
complex - used to represent complex numbers. e.g. 1.0 + 2.0j, 1.5 + 2.5j

Data Types in NumPy


NumPy has some extra data types, and refer to data types with one character, like i for integers, u
for unsigned integers etc.

Below is a list of all data types in NumPy and the characters used to represent them.

i - integer
b - boolean
u - unsigned integer
f - float
c - complex float
m - timedelta
M - datetime

[Link] @teluguwebguru
Python Programming Notes TeluguWebGuru

O - object
S - string
U - unicode string
V - fixed chunk of memory for other type ( void )

The NumPy array object has a property called dtype that returns the data type of the array:

import numpy as np
arr = [Link]([1, 2, 3, 4])
print([Link])

Output:
Int64

Get the data type of an array containing strings:

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

Output:
<U6

Creating Arrays With a Defined Data Type:

We use the array() function to create arrays, this function can take an optional argument: dtype
that allows us to define the expected data type of the array elements:

import numpy as np
arr = [Link]([1, 2, 3, 4], dtype='S')
print(arr)
print([Link])

Output:
[b'1' b'2' b'3' b'4']
|S1

>-Big Endian < Little Endian | No Order

For i, u, f, S and U we can define size as well.

[Link] @teluguwebguru
Python Programming Notes TeluguWebGuru

import numpy as np
arr = [Link]([1, 2, 3, 4], dtype='i4')
print(arr)
print([Link])

Output:
[1 2 3 4]
Int32

The following code generates an ValueError as typecasting not possible here

import numpy as np
arr = [Link](['a', '2', '3'], dtype='i')

Converting Data Type on Existing Arrays:

The best way to change the data type of an existing array, is to make a copy of the array with the
astype() method.

The astype() function creates a copy of the array, and allows you to specify the data type as a
parameter.

The data type can be specified using a string, like 'f' for float, 'i' for integer etc. or you can use the
data type directly like float for float and int for integer.

Example:

Change data type from float to integer by using 'i' as parameter value:

import numpy as np
arr = [Link]([1.1, 2.1, 3.1])
newarr = [Link]('i')
print(newarr)
print([Link])

Output:

[1 2 3]
Int32
Change data type from float to integer by using int as parameter value:

[Link] @teluguwebguru
Python Programming Notes TeluguWebGuru

import numpy as np
arr = [Link]([1.1, 2.1, 3.1])
newarr = [Link](int)
print(newarr)
print([Link])

Output:
[1 2 3]
Int64

Change data type from integer to boolean:

import numpy as np
arr = [Link]([1, 0, 3])
newarr = [Link](bool)
print(newarr)
print([Link])

Output:
[ True False True]
bool

NumPy Array Copy vs View:

The main difference between a copy and a view of an array is that the copy is a new array, and the
view is just a view of the original array.

The copy owns the data and any changes made to the copy will not affect original array, and any
changes made to the original array will not affect the copy.

The view does not own the data and any changes made to the view will affect the original array,
and any changes made to the original array will affect the view.

Copy Example:

[Link] @teluguwebguru
Python Programming Notes TeluguWebGuru

import numpy as np

arr = [Link]([1, 2, 3, 4, 5])


x = [Link]()
arr[0] = 42

print(arr)
print(x)

Output:
[42 2 3 4 5]
[1 2 3 4 5]

View Example:

import numpy as np

arr = [Link]([1, 2, 3, 4, 5])


x = [Link]()
arr[0] = 42

print(arr)
print(x)

Output:
[42 2 3 4 5]
[42 2 3 4 5]

Check if Array Owns its Data


Every NumPy array has the attribute base that returns None if the array owns the
data.

Otherwise, the base attribute refers to the original object.

import numpy as np

[Link] @teluguwebguru
Python Programming Notes TeluguWebGuru

arr = [Link]([1, 2, 3, 4, 5])

x = [Link]()
y = [Link]()

print([Link])
print([Link])

Output:

None
[1 2 3 4 5]

NumPy Array Shape & Reshape

The shape of an array is the number of elements in each dimension.


NumPy arrays have an attribute called shape that returns a tuple with each index having the
number of corresponding elements.

import numpy as np
arr = [Link]([[[1, 2, 3, 4], [5, 6, 7, 8]],[[10, 20, 30, 40], [50, 60, 70, 80]]])
print([Link])

Output:
(2, 2, 4)

The example above returns (2,2, 4), which means that the array has 3 dimensions, where the first
dimension has 2 elements and the second has 2 and third has 4..

Create an array with 5 dimensions using ndmin using a vector with values 1,2,3,4 and verify that
last dimension has value 4:​

import numpy as np
arr = [Link]([1, 2, 3, 4], ndmin=5)
print(arr)
print('shape of array :', [Link])

Output:
[[[[[1 2 3 4]]]]]
shape of array : (1, 1, 1, 1, 4)
NumPy Array Reshaping:

[Link] @teluguwebguru
Python Programming Notes TeluguWebGuru

Reshaping arrays
Reshaping means changing the shape of an array.

The shape of an array is the number of elements in each dimension.

By reshaping we can add or remove dimensions or change number of elements in each


dimension.

Reshape From 1-D to 2-D:


Convert the following 1-D array with 12 elements into a 2-D array.

import numpy as np
arr = [Link]([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12])
newarr = [Link](4, 3)
print(newarr)

Output:
[[ 1 2 3]
[ 4 5 6]
[ 7 8 9]
[10 11 12]]

Reshape From 1-D to 3-D:

Convert the following 1-D array with 12 elements into a 3-D array.

The outermost dimension will have 2 arrays that contains 3 arrays, each with 2 elements:

import numpy as np
arr = [Link]([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12])
newarr = [Link](2, 3, 2)
print(newarr)

Output:
[[[ 1 2]
[ 3 4]
[ 5 6]]

[[ 7 8]
[ 9 10]
[11 12]]]

Can We Reshape Into any Shape?

[Link] @teluguwebguru
Python Programming Notes TeluguWebGuru

Yes, as long as the elements required for reshaping are equal in both shapes.

We can reshape an 8 elements 1D array into 4 elements in 2 rows 2D array but we cannot reshape
it into a 3 elements 3 rows 2D array as that would require 3x3 = 9 elements.

import numpy as np
arr = [Link]([1, 2, 3, 4, 5, 6, 7, 8])
newarr = [Link](3, 3)
print(newarr)

Output : Error
Traceback (most recent call last):
File "demo_numpy_array_reshape_error.py", line 5, in <module>
ValueError: cannot reshape array of size 8 into shape (3,3)

Returns Copy or View?

Check if the returned array is a copy or a view:

import numpy as np
arr = [Link]([1, 2, 3, 4, 5, 6, 7, 8])
print([Link](2, 4).base)

Output:
[1 2 3 4 5 6 7 8]

The example above returns the original array, so it is a view.

—-----------

Unknown Dimension
You are allowed to have one "unknown" dimension.

Meaning that you do not have to specify an exact number for one of the dimensions
in the reshape method.

Pass -1 as the value, and NumPy will calculate this number for you.

[Link] @teluguwebguru
Python Programming Notes TeluguWebGuru

Convert 1D array with 8 elements to 3D array with 2x2 elements:

import numpy as np

arr = [Link]([1, 2, 3, 4, 5, 6, 7, 8])

newarr = [Link](2, 2, -1)

print(newarr)

Output:
[[[1 2]
[3 4]]

[[5 6]
[7 8]]]

Flattening the arrays

Flattening array means converting a multidimensional array into a 1D array.

We can use reshape(-1) to do this.

import numpy as np
arr = [Link]([[1, 2, 3], [4, 5, 6]])
newarr = [Link](-1)
print(newarr)

OUTPUT
[1 2 3 4 5 6]

Joining NumPy Arrays


Joining means putting contents of two or more arrays in a single array.

In SQL we join tables based on a key, whereas in NumPy we join arrays by axes.

[Link] @teluguwebguru
Python Programming Notes TeluguWebGuru

We pass a sequence of arrays that we want to join to the concatenate() function, along with the
axis. If axis is not explicitly passed, it is taken as 0.

import numpy as np
arr1 = [Link]([1, 2, 3])
arr2 = [Link]([4, 5, 6])
arr = [Link]((arr1, arr2))
print(arr)

OUTPUT:
[1 2 3 4 5 6]

Join two 2-D arrays along rows (axis=1):


import numpy as np

arr1 = [Link]([[1, 2], [3, 4]])

arr2 = [Link]([[5, 6], [7, 8]])

arr = [Link]((arr1, arr2), axis=1)

print(arr)

OUTPUT:
[[1 2 5 6]
[3 4 7 8]]

Joining Arrays Using Stack Functions


Stacking is same as concatenation, the only difference is that stacking is done along a new axis.

We can concatenate two 1-D arrays along the second axis which would result in putting them one
over the other, ie. stacking.

We pass a sequence of arrays that we want to join to the stack() method along with the axis. If
axis is not explicitly passed it is taken as 0.

[Link] @teluguwebguru
Python Programming Notes TeluguWebGuru

import numpy as np

arr1 = [Link]([1, 2, 3])


arr2 = [Link]([4, 5, 6])
arr = [Link]((arr1, arr2), axis=1)
print(arr)

OUTPUT:
[[1 4]
[2 5]
[3 6]]

Stacking Along Rows


NumPy provides a helper function: hstack() to stack along rows.

import numpy as np
arr1 = [Link]([1, 2, 3])
arr2 = [Link]([4, 5, 6])
arr = [Link]((arr1, arr2))
print(arr)

OUTPUT:
[1 2 3 4 5 6]

Stacking Along Columns


NumPy provides a helper function: vstack() to stack along columns.
import numpy as np

arr1 = [Link]([1, 2, 3])


arr2 = [Link]([4, 5, 6])
arr = [Link]((arr1, arr2))
print(arr)

OUTPUT:
[[1 2 3]
[4 5 6]]

Stacking Along Height (depth):

[Link] @teluguwebguru
Python Programming Notes TeluguWebGuru

import numpy as np

arr1 = [Link]([[1, 2, 3],[10, 20, 30]])


arr2 = [Link]([[4, 5, 6],[40,50,60]])

arr = [Link]((arr1, arr2),axis=1)


print("concatenate with axis1:",arr)

arr = [Link]((arr1, arr2),axis=1)


print("stack with axis1:",arr)

arr = [Link]((arr1, arr2),axis=0)


print("concatenate with axis0:",arr)

arr = [Link]((arr1, arr2),axis=0)


print("stack with axis0:",arr)

Output:
concatenate with axis1: [[ 1 2 3 4 5 6]
[10 20 30 40 50 60]]
stack with axis1: [[[ 1 2 3]
[ 4 5 6]]

[[10 20 30]
[40 50 60]]]
concatenate with axis0: [[ 1 2 3]
[10 20 30]
[ 4 5 6]
[40 50 60]]
stack with axis0: [[[ 1 2 3]
[10 20 30]]

[[ 4 5 6]
[40 50 60]]]

NumPy provides a helper function: dstack() to stack along height, which is the same as depth.

import numpy as np
arr1 = [Link]([1, 2, 3])
arr2 = [Link]([4, 5, 6])
arr = [Link]((arr1, arr2))
print(arr)

[Link] @teluguwebguru
Python Programming Notes TeluguWebGuru

OUTPUT:
[[[1 4]
[2 5]
[3 6]]]

Splitting NumPy Arrays


Splitting is reverse operation of Joining.

Joining merges multiple arrays into one and Splitting breaks one array into multiple.

We use array_split() for splitting arrays, we pass it the array we want to split and the number of
splits.

import numpy as np
arr = [Link]([1, 2, 3, 4, 5, 6])
newarr = np.array_split(arr, 3)
print(newarr)

Output:
[array([1, 2]), array([3, 4]), array([5, 6])]

If the array has less elements than required, it will adjust from the end accordingly.

Split the array in 4 parts:

import numpy as np

arr = [Link]([1, 2, 3, 4, 5, 6])

newarr = np.array_split(arr, 4)

print(newarr)
OUTPUT:
[array([1, 2]), array([3, 4]), array([5]), array([6])]

Split Into Arrays


The return value of the array_split() method is an array containing each of the split as an array.

[Link] @teluguwebguru
Python Programming Notes TeluguWebGuru

If you split an array into 3 arrays, you can access them from the result just like any array element:

import numpy as np
arr = [Link]([1, 2, 3, 4, 5, 6])
newarr = np.array_split(arr, 3)
print(newarr[0])
print(newarr[1])
print(newarr[2])

Output:
[1 2]
[3 4]
[5 6]

Splitting 2-D Arrays


Use the same syntax when splitting 2-D arrays.

Use the array_split() method, pass in the array you want to split and the number of splits you
want to do.

import numpy as np
arr = [Link]([[1, 2], [3, 4], [5, 6], [7, 8], [9, 10], [11, 12]])
newarr = np.array_split(arr, 3)
print(newarr)

Output:
[array([[1, 2],
[3, 4]]), array([[5, 6],
[7, 8]]), array([[ 9, 10],
[11, 12]])]

Searching Arrays
You can search an array for a certain value, and return the indexes that get a match.

To search an array, use the where() method.

import numpy as np
arr = [Link]([1, 2, 3, 4, 5, 4, 4])

[Link] @teluguwebguru
Python Programming Notes TeluguWebGuru

x = [Link](arr == 4)
print(x)

Output:
(array([3, 5, 6]),)

Find the indexes where the values are even:

import numpy as np
arr = [Link]([1, 2, 3, 4, 5, 6, 7, 8])
x = [Link](arr%2 == 0)
print(x)

Output:
(array([1, 3, 5, 7]),)

Search Sorted
There is a method called searchsorted() which performs a binary search in the array, and returns
the index where the specified value would be inserted to maintain the search order.

The searchsorted() method is assumed to be used on sorted arrays.

import numpy as np
arr = [Link]([6, 7, 8, 9])
x = [Link](arr, 7)
print(x)

Output: 1

Example explained: The number 7 should be inserted on index 1 to remain the sort order.
The method starts the search from the left and returns the first index where the number 7 is no
longer larger than the next value.

Search From the Right Side


import numpy as np
arr = [Link]([6, 7, 8, 9])
x = [Link](arr, 7, side='right')
print(x)

[Link] @teluguwebguru
Python Programming Notes TeluguWebGuru

Output
2

Sorting Arrays
Sorting means putting elements in an ordered sequence.

Ordered sequence is any sequence that has an order corresponding to elements, like numeric or
alphabetical, ascending or descending.

The NumPy ndarray object has a function called sort(), that will sort a specified array.

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

Output:
[0 1 2 3]

This method returns a copy of the array, leaving the original array unchanged.

For descending:
[Link](arr)[::-1]

Filtering Arrays
Getting some elements out of an existing array and creating a new array out of them is called
filtering.

[Link] @teluguwebguru
Python Programming Notes TeluguWebGuru

In NumPy, you filter an array using a boolean index list.

A boolean index list is a list of booleans corresponding to indexes in the array.

import numpy as np
arr = [Link]([41, 42, 43, 44])
x = [True, False, True, False]
newarr = arr[x]
print(newarr)

Output:
[41 43]

ndarrays can be created by using 8 functions


array, arange, zeros, ones, full, identity(), hstack(), vstack()

[Link] @teluguwebguru
Python Programming Notes TeluguWebGuru

Shape and reshape

import numpy as np
arr = [Link]([[[1, 2, 3, 4], [5, 6, 7, 8]],[[10, 20, 30, 40], [50, 60, 70, 80]]])
print([Link])
print([Link](16))
print([Link](2,8))
print([Link](2,4,2))

Output:

(2, 2, 4)
[ 1 2 3 4 5 6 7 8 10 20 30 40 50 60 70 80]
[[ 1 2 3 4 5 6 7 8]
[10 20 30 40 50 60 70 80]]
[[[ 1 2]
[ 3 4]
[ 5 6]
[ 7 8]]

[[10 20]
[30 40]
[50 60]
[70 80]]]

Flattening : to convert any array to 1D.

a = [Link]([[1, 2, 3], [4, 5, 6]])


print([Link]) # (2, 3)
print([Link](3, 2)) # Reshape into 3x2
print([Link]()) # Convert to 1D array

Creating Arrays with NumPy Functions:

Zeros, Ones, Full

print([Link]((2, 3))) #All elements are 0


print([Link]((3, 2))) #All elements are 1
print([Link]((2, 2), 5)) #All elements are filled with 5

[Link] @teluguwebguru
Python Programming Notes TeluguWebGuru

Arange and Linspace

print([Link](1, 10, 2)) #Like range in Python


print([Link](0, 1, 5)) #Evenly spaced numbers between two values

Output:
[1 3 5 7 9]
[0. 0.25 0.5 0.75 1. ]

Operations on Arrays

Arithmetic Operations

a = [Link]([1, 2, 3])
b = [Link]([4, 5, 6])
print(a + b) # [5 7 9]
print(a * b) # [4 10 18]
print(a ** 2) # [1 4 9]

Broadcasting

x = [Link]([[1, 2], [3, 4]])


y = [Link]([10, 20])
print(x + y)

NumPy adjusts shapes to perform operations.


y (1D) is added to every row of x.

Aggregation Functions

a = [Link]([[1, 2], [3, 4]])


print([Link](a)) # 10
Note : sum(a,axis=0) -> sums columns
sum(a,axis=1) -> sums rows

print([Link](a)) #4
print([Link](a)) # 2.5
print([Link](a)) # Standard deviation
print([Link](a))

Unique values:

[Link] @teluguwebguru
Python Programming Notes TeluguWebGuru

To find the unique values in a NumPy array, the [Link]() function is used. This function
returns the sorted unique elements of an array.

import numpy as np
# Create a NumPy array with duplicate values
arr = [Link]([1, 2, 2, 3, 4, 4, 4, 5, 1])
# Find the unique values
unique_values = [Link](arr)
print(unique_values)

Output:
[1 2 3 4 5]

—------------
The [Link]() function in Python's NumPy library returns the
indices of the maximum values along a specified axis in an array. If
the maximum value appears multiple times, it returns the index of the
first occurrence.

[Link](array, axis=None, out=None)

Parameters:

array: The input array from which to find the maximum values.

axis: (Optional) An integer specifying the axis along which to find the
maximum values.
If axis=None (default), the function operates on the flattened array
and returns a single index.
If axis=0, it returns the indices of the maximum values for each
column.
If axis=1, it returns the indices of the maximum values for each row.

out: (Optional) An array where the result should be stored. It must


have a compatible shape and data type

import numpy as np

# 1D array
arr1d = [Link]([10, 20, 90, 40, 50])
max_index_1d = [Link](arr1d)
print(f"Index of max in 1D array: {max_index_1d}")
# Output: 2

# 2D array
arr2d = [Link]([[1, 5, 2],

[Link] @teluguwebguru
Python Programming Notes TeluguWebGuru

[8, 3, 6]])

# Max index in flattened array


max_index_flat = [Link](arr2d)
print(f"Index of max in flattened 2D array: {max_index_flat}")
# Output: 3 (index of 8)

# Max index along axis 0 (columns)


max_index_axis0 = [Link](arr2d, axis=0)
print(f"Indices of max along axis 0: {max_index_axis0}")
# Output: [1 0 1] (8 is at index 1 in col 0, 5 is at index 0 in col 1,
6 is at index 1 in col 2)

# Max index along axis 1 (rows)


max_index_axis1 = [Link](arr2d, axis=1)
print(f"Indices of max along axis 1: {max_index_axis1}")
# Output: [1 0] (5 is at index 1 in row 0, 8 is at index 0 in row 1)

—-------------------------

Stacking Arrays:
Stack arrays vertically (rows) or horizontally (columns).

a = [Link]([[1, 2], [3, 4]])


b = [Link]([[5, 6]])
print([Link]((a, b))) # vertical stack
print([Link]((a, a))) # horizontal stack

Output:

[[1 2]
[3 4]
[5 6]]
[[1 2 1 2]
[3 4 3 4]]

Boolean Indexing

You can filter values using conditions directly. Very useful in data
analysis.

a = [Link]([1, 2, 3, 4, 5])
print(a[a > 2]) # [3 4 5]

b = [Link]([[10, 20], [30, 40]])


print(b[b > 25]) # [30 40]

[Link] @teluguwebguru
Python Programming Notes TeluguWebGuru

PANDAS TUTORIAL:
Pandas is a Python library that is used to analyze data. Pandas is used for working with
data sets.

It has functions for analyzing, cleaning, exploring, and manipulating data.

Pandas allows us to analyze big data and make conclusions based on statistical theories.

Pandas can clean messy data sets, and make them readable and relevant.

Relevant data is very important in data science.

The name "Pandas" has a reference to both "Panel Data", and "Python Data Analysis" and
was created by Wes McKinney in 2008.

How to install pandas:

​ pip install pandas

Pandas gives you answers about the data. Like:

Is there a correlation between two or more columns?


What is average value?
Max value?
Min value?

Pandas is usually imported under the pd alias.

import pandas as pd
mydataset = {
'cars': ["BMW", "Volvo", "Ford"],
'passings': [3, 7, 2]
}
myvar = [Link](mydataset)
print(myvar)

Output:

cars passings
0 BMW 3
1 Volvo 7
2 Ford 2

[Link] @teluguwebguru
Python Programming Notes TeluguWebGuru

Pandas Series:

A Pandas Series is like a column in a table.

It is a one-dimensional array holding data of any type.

import pandas as pd
a = [1, 7, 2]
myvar = [Link](a)
print(myvar)

Output:
Index series
0 1
1 7
2 2

dtype: int64

If nothing else is specified, the values are labeled with their index
number. First value has index 0, second value has index 1 etc.

This label can be used to access a specified value.

print(myvar[0]) #prints 1

With the index argument, you can name your own labels.

import pandas as pd
a = [1, 7, 2]
myvar = [Link](a, index = ["x", "y", "z"])
print(myvar)

Output:

x 1
y 7
z 2
dtype: int64

When you have created labels, you can access an item by referring to
the label

[Link] @teluguwebguru
Python Programming Notes TeluguWebGuru

print(myvar["y"])
Key/Value Objects as Series

import pandas as pd
calories = {"day1": 420, "day2": 380, "day3": 390}
myvar = [Link](calories)
print(myvar)

Output:

day1 420
day2 380
day3 390
dtype: int64

To select only some of the items in the dictionary, use the index
argument and specify only the items you want to include in the Series.

import pandas as pd
calories = {"day1": 420, "day2": 380, "day3": 390}
myvar = [Link](calories, index = ["day1", "day2"])
print(myvar)

day1 420
day2 380
dtype: int64

Data Frame:
Data sets in Pandas are usually multi-dimensional tables, called
DataFrames.

Series is like a column, a DataFrame is the whole table.

import pandas as pd
a=[[10,20,30],[100,200,300]]
print([Link](a))

Output:

0 1 2
0 10 20 30
1 100 200 300

[Link] @teluguwebguru
Python Programming Notes TeluguWebGuru

We can assign column names also by providing columns attribute

import pandas as pd
a=[[10,20,30],[100,200,300]]
print([Link](a,columns=["marks1","marks2","marks3"]))

​ marks1 marks2 marks3


0 10 20 30
1 100 200 300

We can assign names in place of indexes also by using index attribute

import pandas as pd
a=[[10,20,30],[100,200,300]]
print([Link](a,index=["S1","S2"],columns=["marks1","marks2","mark
s3"]))

marks1 marks2 marks3


S1 10 20 30
S2 100 200 300

We can also convert list of tuples into dataframes. Generally database


results from fetchall function gives us this list of tuples and inturn
we can convert this into dataframe and analyze it

import pandas as pd
a=[(1,"Santosh","CSE"),(2,"Suresh","ECE")]
print([Link](a,index=["S1","S2"],columns=["rno","name","branch"])
)

rno name branch


S1 1 ​ Santosh CSE
S2 2 Suresh ECE

We can create a dictionary and convert into DataFrame

import pandas as pd
d1={"rno":[1,2],"name":["Santosh","Suresh"],"branch":["CSE","ECE"]}
print([Link](d1,index=["s1","s2"]))

rno name branch


s1 1 Santosh CSE
s2 2 Suresh ECE

[Link] @teluguwebguru
Python Programming Notes TeluguWebGuru

We can convert list into numpy ndarray and again convert this array
into dataframe

import pandas as pd
import numpy as np
d1=[(1,"Santosh","CSE"),(2,"Suresh","ECE")]
n=[Link](d1)
print("n:",n)
print([Link](n,index=["s1","s2"]))

n: [['1' 'Santosh' 'CSE']


['2' 'Suresh' 'ECE']]

0 1 2
s1 1 Santosh CSE
s2 2 Suresh ECE

Sets into DataFrame:

import pandas as pd
import numpy as np
s={11,32,23,12,15}
print([Link](s))

0
0 32
1 23
2 11
3 12
4 15

Realtime Scenario

​ Maximum times in real time, data coming from csv files/database only.

[Link] @teluguwebguru
Python Programming Notes TeluguWebGuru

Creating a data frame using CSV FIle:

For this we use below function

read_csv(“Absolute path of the file”)

Example:

import pandas as pd
import numpy as np
s=pd.read_csv("C:\\Users\\Santosh\\Desktop\\[Link]")
print (s)

Output:

rno name marks


0 1 Santosh 99
1 2 Suresh 89
2 3 Ramesh 77
3 4 Mahesh 88
4 5 Satish 75
5 6 Rajesh 66
6 7 Piyush 74
7 8 Saketh 81
8 9 Sankalp 69
9 10 Surya 98

Instead of separate index, we can assign one of the column as index


column

s.set_index("rno")

name​ marks
rno​ ​
1​ Santosh​ 99
2​ Suresh​ 89
3​ Ramesh​ 77
4​ Mahesh​ 88
5​ Satish​ 75
6​ Rajesh​ 66
7​ Piyush​ 74
8​ Saketh​ 81
9​ Sankalp​ 69
10​ Surya​ 98

[Link] @teluguwebguru
Python Programming Notes TeluguWebGuru

Example-2:

import pandas as pd
import numpy as np
s=pd.read_csv("C:\\Users\\Santosh\\Desktop\\[Link]")
print (s)

empno name desg salary


0 1 Santosh CEO 200000
1 2 Suresh Manager 130000
2 3 Ramesh Developer 100000
3 4 Mahesh Tester 90000

—--------------------------------------------------

Operations on DataFrame:

Creating DataFrame object using csv file and perform various operations

head() function returns first 5 records

import pandas as pd
import numpy as np
s=pd.read_csv("C:\\Users\\Santosh\\Desktop\\[Link]")
print ([Link]())

rno name c java python php go javascript


0 1 stud1 50 60 66 98 66 55
1 2 stud2 45 67 34 67 66 78
2 3 stud3 56 88 56 99 44 77
3 4 stud4 56 78 34 56 88 55
4 5 stud5 51 63 62 93 67 51

We can mention the number also inside head function

head(3) returns first 3 records


head(2) returns first 2 records

tail() will return last 5 records


tail(7) will return last 7 records

Shape attribute will returns [Link] rows and columns in a tuple

[Link] returns (15,8)

[Link] @teluguwebguru
Python Programming Notes TeluguWebGuru

Looping through dataframe: iterrows()

for i in [Link]():
print (i)

(0, rno 1
name stud1
c 50
java 60
python 66
php 98
go 66
javascript 55
Name: 0, dtype: object)
(1, rno 2
name stud2
c 45
java 67
python 34
php 67
go 66
javascript 78
Name: 1, dtype: object)
(2, rno 3
name stud3
c 56
java 88
python 56
php 99
go 44
javascript 77
Name: 2, dtype: object)

Like this it returns all records

Indexing and Slicing on Data Frames:

It works same as like indexing and slicing on sequences

S[0:3] returns 0,1,2 records

S[0:6:3] returns 0,3 records


S[::2] will return even indexed records 0,2,4 …

[Link] @teluguwebguru
Python Programming Notes TeluguWebGuru

Accessing elements by using column name:

S["name"] returns name column with values

0 stud1
1 stud2
2 stud3
3 stud4
4 stud5
5 stud6
.
.

Name: name, dtype: object

S[["name","c","java"]] will return all records with these 3 columns.


S[["name","c","java"]][1:5] will return 1 to 4 indexed records with
these three columns.

loc() and iloc() functions:

By using loc() We can access the data based on row indexes as well as
with column names also

loc[row-index]
loc[row-index,column-name]

[Link][0,”java”] -> returns oth row and java column value. It does not
allows column index and accepts column name only

[Link][0,4] -> returns 0th indexed row and 4th indexed column value. It
does not work with column name

[Link][0:6:3,"java"] ⇒ here start,stop both inclusive

0 60
3 78
6 81
Name: java, dtype: int64

[Link] ⇒ start inclusive and stop exclusive

[Link] @teluguwebguru
Python Programming Notes TeluguWebGuru

Add new columns to the DataFrame:

s["total"]=s["c"]+s["java"]+s["python"]+s["php"]+s["go"]+s["javascript"
]

Or

s["total"]=None

In first case with expression it calculates and sets total value


print(s)

rno​ name​ c​ java​ python php go​ javascript​ total


0​ 1​ stud1​50​ 60​ 66​ 98​ 66​ 55​ 395
1​ 2​ stud2​45​ 67​ 34​ 67​ 66​ 78​ 357
2​ 3​ stud3​56​ 88​ 56​ 99​ 44​ 77​ 420
.
.
.

s["average"]=s["total"]/600

s["average"]=round((s["total"]/600)*100,2) -> rounded to two digits

—-----------------------

Filtering

[Link][s["python"]>75]

It returns all records with python marks greater than 75

Rno name​ c​ java​ python php​ go avascript total​ average


8 9​ stud9 53​ 62​ 76​ 88​ 76​ 35​ 390 ​ 65.00
10 11 stud11 66​ 48​ 86​ 95​ 48​ 47​ 390​ 65.00
13 14 stud14 50​ 63​ 99​ 90​ 76​ 67​ 445​ 74.17
14 15 stud15 60​ 89​ 98​ 87​ 77​ 68​ 479​ 79.83

[Link][s["python"]>75,["name","python","javascript"]]
It returns only name,python,javascript columns of students with python
marks greater than 75

[Link] @teluguwebguru
Python Programming Notes TeluguWebGuru

Grading:

[Link][(s["average"]>70),["grade"]]="Distinction"
[Link][(s["average"]>=60) & (s["average"]<=70),["grade"]]="First"
[Link][(s["average"]>=60) & (s["average"]<70),["grade"]]="First"
[Link][(s["average"]>=50) & (s["average"]<60),["grade"]]="Second"
[Link][(s["average"]<50) & (s["average"]>=40),["grade"]]="Just Pass"
[Link][(s["average"]<40),["grade"]]="Failed"

[Link][1:6,["rno","name","average","grade"]]

rno​ name​ average grade


1​ 2​ stud2​59.50​ Second
2​ 3​ stud3​70.00​ First
3​ 4​ stud4​61.17​ First
4​ 5​ stud5​64.50​ First
5​ 6​ stud6​61.67​ First
6​ 7​ stud7​67.67​ First

—----------------

Removing column name from the data frame

[Link](columns="grade")

With inplace=True we can remove the column in the original


dataframe only

—----------

Export data to csv:

s.to_csv("C:\\Users\\Santosh\\Desktop\\[Link]")

—----------
Export data to excel:

s.to_excel("C:\\Users\\Santosh\\Desktop\\[Link]")
—--------------
Export data to txt:

s.to_csv("C:\\Users\\Santosh\\Desktop\\[Link]")

[Link] @teluguwebguru
Python Programming Notes TeluguWebGuru

Sorting the data in dataframe

s.sort_values(["python"])

It sorts and prints the dataframe in ascending order

s.sort_values(["python"],ascending=False)
It will sort in descending order

—-----------------

Check whether duplicates are there or not

[Link]() - will return True/False for every record based on


whether it is duplicated or not

—----------------
s.drop_duplicates() - delete the duplicated rows
s.drop_duplicates(inplace=True) - delete the duplicated rows and
modifies the original dataframe

—-----------------
Add row
[Link][15]=[16,"stud16",70,79,88,77,66,99,447,79.83,"Distinction"]
—-------------------

Removing rows
[Link](labels=15,axis=0)
Axis 0 indicates rows

[Link]([Link][[1,9]]) -> removes 1,9 indexed rows

—------------

Groupby: we can group rows based on columns and perform aggregate


functions like sum(),mean(),agg(),sum(),min(),max()

print([Link]("grade").sum())

Distinction 57 stud12stud14stud15stud16
246
First 77 stud1stud3stud4stud5stud6stud7stud8stud9stud10...
585
Second 2 stud2
45

java python php go javascript total average

[Link] @teluguwebguru
Python Programming Notes TeluguWebGuru

grade
Distinction 299 349 330 317 309 1818 308.33
First 770 658 945 733 635 4326 721.01
Second 67 34 67 66 78 357 59.50

Matplotlib Tutorial

1. Introduction

Matplotlib is a data visualization library in Python.

It helps us to create graphs and charts like line charts, bar charts,
scatter plots, etc.

Why useful? – Because seeing data in a chart is much easier than


looking at numbers in a table.

👉 Example: If you have student marks of 5 students, a chart shows who


scored highest and lowest at a glance.

—---------

Installing and Importing


Pip install matplotlib

—-------------------

Basic Line Plot:visualize trends, patterns, and changes in data

import [Link] as plt


x = [1, 2, 3, 4, 5] # x-axis values
y = [2, 4, 6, 8, 10] # y-axis values
[Link](x, y)
[Link]("Simple Line Chart")
[Link]("X-axis")
[Link]("Y-axis")
[Link]()

[Link] @teluguwebguru
Python Programming Notes TeluguWebGuru

—-----------------
Bar Chart: Easy way to compare categories.

students = ["A", "B", "C", "D", "E"]


marks = [85, 70, 90, 60, 75]

[Link](students, marks)
[Link]("Student Marks")
[Link]("Students")
[Link]("Marks")
[Link]()

—-----------

Scatter Plot : shows relationship between two sets of numbers.

[Link] @teluguwebguru
Python Programming Notes TeluguWebGuru

Pie Chart

activities = ["Study", "Sleep", "Play", "Others"]


time = [7, 8, 5, 4]

[Link](time, labels=activities, autopct='%1.1f%%')


[Link]("Daily Activities")
[Link]()

Customizing with Colors and Styles


x = [1, 2, 3, 4, 5]
y = [2, 4, 6, 8, 10]

[Link] @teluguwebguru
Python Programming Notes TeluguWebGuru

[Link](x, y, color="red", marker="o", linestyle="--")


[Link]("Customized Line Chart")
[Link]()

●​ color="red" → line color.​

●​ marker="o" → dots at data points.​

●​ linestyle="--" → dashed line.

Multiple Plots on Same Chart

x = [1, 2, 3, 4, 5]
y1 = [2, 4, 6, 8, 10]
y2 = [1, 3, 5, 7, 9]

[Link](x, y1, label="y=2x")


[Link](x, y2, label="y=2x-1")
[Link]("Multiple Lines")
[Link]("X-axis")
[Link]("Y-axis")
[Link]()
[Link]()

[Link] @teluguwebguru

You might also like