Python Notes
Python Notes
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.
What is Python?
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
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.
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.
[Link] @teluguwebguru
Python Programming Notes TeluguWebGuru
[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
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
[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:
[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.
Robust(Strong):
Python allows us to develop very strong applications with its internal features like
exception handling. So python is called robust.
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.
[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 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.
[Link] @teluguwebguru
Python Programming Notes TeluguWebGuru
int :
int represents Integers (Whole numbers) and Binary, Octal, Hexadecimal numbers.
For example :
—-----------------------------------
String Indexing
[Link] @teluguwebguru
Python Programming Notes TeluguWebGuru
Slicing
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 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).
Listobject = [ ]
Listobject = list( )
Examples
Marks = [44,50,45,46,49,48]
user=[“santosh”, 41, True, 3.4]
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
len(marks)
It returns 9 as output which indicates the marks list contains 9 total number of
elements.
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
[Link] @teluguwebguru
Python Programming Notes TeluguWebGuru
extend()
To add a list at the end of another list we will use extend
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()
[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.
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
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() :
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)
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 the items that are present in both sets, AND insert the items that is not
present in both sets:
x.symmetric_difference_update(y)
print(x)
update() :
The update() method updates the current set, by adding items from another set
[Link](y)
print(x)
[Link] @teluguwebguru
Python Programming Notes TeluguWebGuru
Nested Sets
Set in List
Set in Tuple
frozenset:
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
x = [Link]()
print(x)
[Link] @teluguwebguru
Python Programming Notes TeluguWebGuru
x = [Link]()
print(x)
—----------
[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.
# Accessing elements
print(mv[0]) # Output: 72 (ASCII for 'H')
# Slicing a memoryview
sub_mv = mv[1:5]
print(sub_mv.tobytes()) # Output: b'ello'
[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(“value of a={}”.format(a))
l=[10,20,30,40]
print(l)
10
20
30
40
print(l,end=” ”)
print(“=”*25)
input()
input(message)
[Link] @teluguwebguru
Python Programming Notes TeluguWebGuru
Operators in Python:
Arithmetic operators
Assignment operators
Comparison/Relational operators
Logical operators
Identity operators
Membership operators
Bitwise operators
In addition to the standard arithmetic operators, there are operators for modulus,
exponentiation, and floor division.
[Link] @teluguwebguru
Python Programming Notes TeluguWebGuru
[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.
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.
[Link] @teluguwebguru
Python Programming Notes TeluguWebGuru
[Link] @teluguwebguru
Python Programming Notes TeluguWebGuru
Selection Statements:
Syntax:
if (condition):
Statement1
The Python system expects an indentation block immediately after (:) indentation symbol.
Syntax:
if (Condition) :
Statement1
Statement2
Statement3
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:
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”)
Output:
[Link] @teluguwebguru
Python Programming Notes TeluguWebGuru
Output:
[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))
[Link] @teluguwebguru
Python Programming Notes TeluguWebGuru
n=13;
if(p==0):
print ("It is prime");
n=10
p=1
i=1
while(i<=n):
p=p*i
i=i+1
else:
print(p)
n=4597;
sum=0;
ld=0;
while (n>0):
ld=n%10;
sum=sum+ld;
n=n//10;
[Link] @teluguwebguru
Python Programming Notes TeluguWebGuru
n=345;
ld=0;
rev=0;
while (n>0):
ld=n%10;
rev=(rev*10)+ld;
n=n//10;
#print sum
sum=fd+ld;
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")
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
base=2;
exponent=5;
r=1;
for i in range(1,exponent+1):
r=r*base;
n=int(input("enter n value:"));
for i in range(1,n+1):
if(n%i==0):
print (i,end=" ");
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
*****
*****
*****
*****
*****
for i in range(1,5):
for j in range(1,5):
print ("* ",end=" ")
print ("")
[Link] @teluguwebguru
Python Programming Notes TeluguWebGuru
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("");
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 ("");
* * * * *
* * * * *
* * * * *
* * * * *
* * * * *
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
* * * * *
* *
* *
* *
* * * * *
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 ("")
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)
—-----
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
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
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:
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.
[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:
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.
Function approaches
Not Taking input from function call - process in func body -
print result
a,b,c=add()
[Link] @teluguwebguru
Python Programming Notes TeluguWebGuru
globals()
print(globals())
print("")
p,q,r,s=10,100,1000,10000
print(globals())
Explanation:
[Link] @teluguwebguru
Python Programming Notes TeluguWebGuru
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
—---------
—---------------
[Link] @teluguwebguru
Python Programming Notes TeluguWebGuru
greet("Alice")
greet("Bob", "Hi")
[Link] @teluguwebguru
Python Programming Notes TeluguWebGuru
3 special functions:
1)filter
2)map
3)reduce
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))
[Link] @teluguwebguru
Python Programming Notes TeluguWebGuru
map:
Syntax:
Example-1:
numbers = [1, 2, 3, 4, 5]
[Link] @teluguwebguru
Python Programming Notes TeluguWebGuru
filter vs map :
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:
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.
—---------
—-----------
[Link] @teluguwebguru
Python Programming Notes TeluguWebGuru
print (rwords)
—---------------------------
reduce
Example-1:
numbers = [1, 2, 3, 4, 5]
Example-2: product
numbers = [1, 2, 3, 4, 5]
[Link] @teluguwebguru
Python Programming Notes TeluguWebGuru
Modules in Python:
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
Functions are meant for providing reusability within the same program
only
But modules have a limitation that all files must be within same folder
—------
[Link] @teluguwebguru
Python Programming Notes TeluguWebGuru
—----------
2 types of modules
1)Pre-defined (Builtin)
2)User Defined Modules
—-----------
[Link] @teluguwebguru
Python Programming Notes TeluguWebGuru
Built-in Modules:
● os module
● random module
● math module
● time module
● sys module
● collections module
● statistics module
os module
mkdir():
>>> import os
>>> [Link]("d:\\tempdir")
A new directory corresponding to path in string argument in the function will be created. If we
chdir():
>>> import os
[Link] @teluguwebguru
Python Programming Notes TeluguWebGuru
>>> [Link]("d:\\temp")
getcwd():
>>> [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")
'Public']
random module
Python’s standard library contains random module which defines various functions for handling
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
[Link](): Returns a random float number between 0.0 to 1.0. The function doesn’t
0.755173688207591
[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,
23
>>> numbers=[12,23,45,67,65,43]
>>> [Link](numbers)
>>> numbers
[23, 12, 43, 65, 67, 45]
>>> [Link](numbers)
>>> numbers
[Link] @teluguwebguru
Python Programming Notes TeluguWebGuru
math module
● trigonometric functions
● representation functions
● logarithmic functions
Pie π which is defined as ratio of circumference to diameter of a circle and its value is
3.141592653589793
Another mathematical constant in this module is e. It is called Euler’s number and is a base of
>>> math.e
2.718281828459045
[Link](81)
[Link](6.35)->6
[Link](2,7)
[Link](5)
[Link](2)
[Link] @teluguwebguru
Python Programming Notes TeluguWebGuru
Trigonometric functions:
>>> [Link](30)
0.5235987755982988
>>> [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(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
>>> [Link](4,4)
256.0
>>> 4**4
256
>>> [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
[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]
9223372036854775807
[Link]
This is an environment variable that returns search path for all Python modules.
[Link] @teluguwebguru
Python Programming Notes TeluguWebGuru
>>> [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
[Link] @teluguwebguru
Python Programming Notes TeluguWebGuru
>>> [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
A 20
B 30
D 50
C 40
[Link] @teluguwebguru
Python Programming Notes TeluguWebGuru
>>> d2['C']=40
>>> d2['D']=50
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
statistics module
[Link] @teluguwebguru
Python Programming Notes TeluguWebGuru
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.
5.0
1.3693063937629153
time module
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():
>>> tk=[Link]()
>>> [Link](tk)
asctime():
>>> tk=[Link]()
>>> tp=[Link](tk)
>>> [Link](tp)
ctime():
>>> [Link]()
sleep():
This function halts current program execution for a specified duration in seconds.
>>> [Link]()
'Sun Dec 9 15:19:14 2018'
>>> [Link](20)
>>> [Link]()
[Link] @teluguwebguru
Python Programming Notes TeluguWebGuru
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:
>>>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()
open("non_existent_file.txt", "r")
FileNotFoundError
[Link] @teluguwebguru
Python Programming Notes TeluguWebGuru
ZeroDivisionError
KeyError
ValueError
TypeError
IndexError
NameError
ModuleNotFoundError
AttributeError
IndentationErrror
FileNotFoundError
OSError
IOError
FileExistError
DatabaseError
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
First, the try clause (the statement(s) between the try and except
keywords) is executed.
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:
[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}")
—-------------------
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
NameError – User selects an option that requires a variable that was never
defined
if choice == "1":
print("Your name is:", user_name) # user_name is never defined!
[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("=============================")
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.")
[Link] @teluguwebguru
Python Programming Notes TeluguWebGuru
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
Operations on Files:
1) Write : transferring/saving object data into file
2) Read : Reading / transferring the records from file into object
write operation
Read Operation
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
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
open()
varname=open(filename,file mode)
xyz=open(“[Link]”,’r’)
[Link] @teluguwebguru
Python Programming Notes TeluguWebGuru
with open() as
—---------------------------
Example1:
xyz=open(“[Link]”,”r”)
print([Link])
[Link]
[Link]()
[Link]()
[Link]
—------------------------------
Writing:
[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
Press $ to stop
while(True):
d=input(“enter some data”)
if(d!=”$”):
[Link](d)
else:
Break
File copy:
[Link] @teluguwebguru
Python Programming Notes TeluguWebGuru
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.
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
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.
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
[Link] @teluguwebguru
Python Programming Notes TeluguWebGuru
[Link] @teluguwebguru
Python Programming Notes TeluguWebGuru
Generators in Python:
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
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 :
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
un = "twguser"
cs = "localhost:1521/XE" # for Oracle Database Free users
pw = [Link](f"Enter password for {un}@{cs}: ")
[Link] @teluguwebguru
Python Programming Notes TeluguWebGuru
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
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()
—----------------
[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()
import [Link]
con=[Link](host=”localhost”,user=”root”,passwd=”root”)
cur=[Link]()
q=”create database hospital”
[Link](q)
[Link] @teluguwebguru
Python Programming Notes TeluguWebGuru
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
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
Object :
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
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
class Student:
coursename=”python live training”
def initializedata(self):
[Link]=”twg2”
[Link]=”Rossum”
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 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.
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
# 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())
# Use Cases:
# 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])}")
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:
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
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:
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.
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'>
pat=r"[a-z]-\d+"
s="This is Python Live Training Batch-1"
print([Link](pat, s))
Output: None
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
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']
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'>
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.
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
Character classes
Quantifiers
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)
● | alternation
[Link] @teluguwebguru
Python Programming Notes TeluguWebGuru
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
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:
[Link] @teluguwebguru
Python Programming Notes TeluguWebGuru
MultiThreading
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.
[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.
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
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]()
[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]()
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
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]()
[Link] @teluguwebguru
Python Programming Notes TeluguWebGuru
NUMPY Introduction:
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.
● Faster
[Link] @teluguwebguru
Python Programming Notes TeluguWebGuru
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:
pip list will show list of all modules packages available in the system
import numpy
arr = [Link]([1, 2, 3, 4, 5])
print(arr)
print(type(arr))
Output:
[1 2 3 4 5]
<class '[Link]'>
import numpy as np
print(np.__version__)
Dimensions in Arrays:
[Link] @teluguwebguru
Python Programming Notes TeluguWebGuru
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.
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.
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
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
[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
OUTPUT
7
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
Output:
2nd element on 1st row: 2
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
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
Output:
Last element from 2nd dim: 10
[Link] @teluguwebguru
Python Programming Notes TeluguWebGuru
Slicing in python means taking elements from one given index to another given index.
import numpy as np
arr = [Link]([1, 2, 3, 4, 5, 6, 7])
print(arr[1:5])
Output:
[2 3 4 5]
import numpy as np
arr = [Link]([1, 2, 3, 4, 5, 6, 7])
print(arr[4:])
Output:
[5 6 7]
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
import numpy as np
arr = [Link]([1, 2, 3, 4, 5, 6, 7])
print(arr[-3:-1])
Output
[5 6]
STEP:
import numpy as np
arr = [Link]([1, 2, 3, 4, 5, 6, 7])
print(arr[1:5:2])
Output:
[2 4]
import numpy as np
arr = [Link]([1, 2, 3, 4, 5, 6, 7])
print(arr[::2])
Output:
[1 3 5 7]
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]]
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
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
import numpy as np
arr = [Link](['apple', 'banana', 'cherry'])
print([Link])
Output:
<U6
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
[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
import numpy as np
arr = [Link](['a', '2', '3'], dtype='i')
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
import numpy as np
arr = [Link]([1, 0, 3])
newarr = [Link](bool)
print(newarr)
print([Link])
Output:
[ True False True]
bool
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
print(arr)
print(x)
Output:
[42 2 3 4 5]
[1 2 3 4 5]
View Example:
import numpy as np
print(arr)
print(x)
Output:
[42 2 3 4 5]
[42 2 3 4 5]
import numpy as np
[Link] @teluguwebguru
Python Programming Notes TeluguWebGuru
x = [Link]()
y = [Link]()
print([Link])
print([Link])
Output:
None
[1 2 3 4 5]
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.
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]]
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]]]
[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)
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]
—-----------
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
import numpy as np
print(newarr)
Output:
[[[1 2]
[3 4]]
[[5 6]
[7 8]]]
import numpy as np
arr = [Link]([[1, 2, 3], [4, 5, 6]])
newarr = [Link](-1)
print(newarr)
OUTPUT
[1 2 3 4 5 6]
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]
print(arr)
OUTPUT:
[[1 2 5 6]
[3 4 7 8]]
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
OUTPUT:
[[1 4]
[2 5]
[3 6]]
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]
OUTPUT:
[[1 2 3]
[4 5 6]]
[Link] @teluguwebguru
Python Programming Notes TeluguWebGuru
import numpy as np
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]]]
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.
import numpy as np
newarr = np.array_split(arr, 4)
print(newarr)
OUTPUT:
[array([1, 2]), array([3, 4]), array([5]), array([6])]
[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]
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.
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]),)
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.
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.
[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
import numpy as np
arr = [Link]([41, 42, 43, 44])
x = [True, False, True, False]
newarr = arr[x]
print(newarr)
Output:
[41 43]
[Link] @teluguwebguru
Python Programming Notes TeluguWebGuru
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]]]
[Link] @teluguwebguru
Python Programming Notes TeluguWebGuru
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
Aggregation Functions
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.
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.
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]])
—-------------------------
Stacking Arrays:
Stack arrays vertically (rows) or horizontally (columns).
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]
[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.
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.
The name "Pandas" has a reference to both "Panel Data", and "Python Data Analysis" and
was created by Wes McKinney in 2008.
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:
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.
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.
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
import pandas as pd
a=[[10,20,30],[100,200,300]]
print([Link](a,columns=["marks1","marks2","marks3"]))
import pandas as pd
a=[[10,20,30],[100,200,300]]
print([Link](a,index=["S1","S2"],columns=["marks1","marks2","mark
s3"]))
import pandas as pd
a=[(1,"Santosh","CSE"),(2,"Suresh","ECE")]
print([Link](a,index=["S1","S2"],columns=["rno","name","branch"])
)
import pandas as pd
d1={"rno":[1,2],"name":["Santosh","Suresh"],"branch":["CSE","ECE"]}
print([Link](d1,index=["s1","s2"]))
[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"]))
0 1 2
s1 1 Santosh CSE
s2 2 Suresh ECE
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
Example:
import pandas as pd
import numpy as np
s=pd.read_csv("C:\\Users\\Santosh\\Desktop\\[Link]")
print (s)
Output:
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)
—--------------------------------------------------
Operations on DataFrame:
Creating DataFrame object using csv file and perform various operations
import pandas as pd
import numpy as np
s=pd.read_csv("C:\\Users\\Santosh\\Desktop\\[Link]")
print ([Link]())
[Link] @teluguwebguru
Python Programming Notes TeluguWebGuru
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)
[Link] @teluguwebguru
Python Programming Notes TeluguWebGuru
0 stud1
1 stud2
2 stud3
3 stud4
4 stud5
5 stud6
.
.
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
0 60
3 78
6 81
Name: java, dtype: int64
[Link] @teluguwebguru
Python Programming Notes TeluguWebGuru
s["total"]=s["c"]+s["java"]+s["python"]+s["php"]+s["go"]+s["javascript"
]
Or
s["total"]=None
s["average"]=s["total"]/600
—-----------------------
Filtering
[Link][s["python"]>75]
[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"]]
—----------------
[Link](columns="grade")
—----------
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
s.sort_values(["python"])
s.sort_values(["python"],ascending=False)
It will sort in descending order
—-----------------
—----------------
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
—------------
print([Link]("grade").sum())
Distinction 57 stud12stud14stud15stud16
246
First 77 stud1stud3stud4stud5stud6stud7stud8stud9stud10...
585
Second 2 stud2
45
[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
It helps us to create graphs and charts like line charts, bar charts,
scatter plots, etc.
—---------
—-------------------
[Link] @teluguwebguru
Python Programming Notes TeluguWebGuru
—-----------------
Bar Chart: Easy way to compare categories.
[Link](students, marks)
[Link]("Student Marks")
[Link]("Students")
[Link]("Marks")
[Link]()
—-----------
[Link] @teluguwebguru
Python Programming Notes TeluguWebGuru
Pie Chart
[Link] @teluguwebguru
Python Programming Notes TeluguWebGuru
x = [1, 2, 3, 4, 5]
y1 = [2, 4, 6, 8, 10]
y2 = [1, 3, 5, 7, 9]
[Link] @teluguwebguru