Python Master Level
Python Master Level
Guido van Rossum formally released the Python language in 1991. In the time since, it has
become one of the most popular in the world, primarily because it is open source, relatively
easy to use, and quite flexible.
Guido van Rossum began working on Python in the late 1980s as a successor to the ABC
programming language and first released it in 1991 as Python 0.9.0. Python 2.0 was released
in 2000. Python 3.0, released in 2008 and so on.
• It provides rich data types and easier to read syntax than any other programming
languages.
• A module in Python may have one or more classes and free functions.
• Libraries in Pythons are cross-platform compatible with Linux, Macintosh, and Windows.
• It supports interactive mode that allows interacting Testing and debugging of snippets of
code.
• In Python, since there is no compilation step, editing, debugging, and testing are fast.
Step 2) Once the download is completed, run the .exe file to install Python. Now click on
Install Now.
Step 4) When it finishes, you can see a screen that says the Setup was successful. Now click
on “Close”.
Here is a step by step process on how to download and install Pycharm IDE on Windows:
Python print() function prints the message to the screen or any other standard output
device.
Syntax: print(values(s),sep=‘’,end=‘\n’,file=file,flush=flush)
• values(s): Any value can print. Will be converted to String before printed.
• Sep=‘separator’: (optional) Specify how to separate the objects, if there is more than one.
Default:’’
• end=‘end’: (optional) Specify what to print at the end.Default :’\n’
X=10
print(“x=“,x)
print (‘Raj’,’software’,’solution’,sep=‘ ’)
Identifier is a user-defined name given to a variable, function, class, module, etc. The
identifier is a combination of character digits and an underscore. They are case-sensitive i.e.,
‘num’ and ‘Num’ and ‘NUM’ are three different identifiers in python. It is a good
programming practice to give meaningful names to identifiers to make the code
understandable.
In Python, indentation is the leading whitespace (spaces or/and tabs) before any statement.
• To indent in Python, whitespaces are preferred over tabs. Also, use either whitespace or tabs to
indent; mixing tabs and whitespaces in indentation can result in incorrect indentation errors.
© copyright 2024, RAJ SOFTWARE SOLUTION, All Rights Reserved
1. INTRODUCTION TO PYTHON
Comments and document interlude in Python
Comments in Python are the lines in the code that are ignored by the interpreter during the
execution of the program. Comments enhance the readability of the code and help the
programmers to understand the code very carefully.
Python single-line comment starts with the hashtag symbol (#) with no white spaces and
lasts till the end of the line.
Multiline comments using multiple hashtags (#).
Docstring in Python """RAJ SOFTWARE SOLUTION"""
© copyright 2024, RAJ SOFTWARE SOLUTION, All Rights Reserved
1. INTRODUCTION TO PYTHON
In Python, you can use triple-quoted strings to create a multiline comment or documentation
interlude. This is often referred to as a docstring. Docstrings are used to provide
documentation for functions, classes, modules, or methods in your code.
They are accessible through the __doc__ attribute of the corresponding object.
input (): This built-in function function first takes the input from the user and converts it into
a string.
For ex:
name = input('What is your name?\n’)
age = int(input('What is your age?\n’))
raw_input(): This function works in older version (like Python 2.x). This function takes exactly
what is typed from the keyboard, converts it to string, and then returns it to the variable in
which we want to store it.
• Python is not “statically typed”. We do not need to declare variables before using them or
declare their type.
• A variable is only a name given to a memory location, all the operations done on the
variable effects that memory location.
© copyright 2024, RAJ SOFTWARE SOLUTION, All Rights Reserved
1. INTRODUCTION TO PYTHON
Rules for creating variables in Python:
• A variable name must start with a letter or the underscore character.
• A variable name cannot start with a number.
• A variable name can only contain alpha-numeric characters and underscores (A-z, 0-9,
and _ ).
• Variable names are case-sensitive (name, Name and NAME are three different variables).
• The reserved words(keywords) cannot be used naming the variable.
# A floating point
salary=2345.8
# A string
name="RAJ SOFTWARE SOLUTION"
print(age)
print(salary)
print(name)
def f():
s = "Welcome Raj"
print(s)
f()
Global variables are the ones that are defined and declared outside a function, and we need
to use them inside a function.
# Name same as s. # Global scope
def f():
global s = "I love Raj
global s
print(s) Software"
f()
type()
x=5
y="Raj"
print(type(x))
print(type(y))
a=5
print("Type of a: ", type(a)) # int
b = 5.0
print("\nType of b: ", type(b)) # float
c = 2 + 4j
print("\nType of c: ", type(c)) # complex
String
Str1 = 'Welcome to RAJ SOFTWARE SOLUTION'
print("String with the use of Single Quotes:")
print(Str1)
Str4 = '''RAJ
SOFTWARE
SOLUTION'''
print("\nCreating a multiline String: ")
print(Str4)
print(type(True))
print(type(False))
Python type() is a built-in function that returns the type of the objects/data elements stored
in any data type or returns a new type object depending on the arguments passed to the
function.
type(object)
x=12
type(x)
Arithmetic Operators
Example: For arithmetic operators we will take simple example of addition where we will add
two-digit 4+5=9
x= 4
y= 5
print(x + y)
Comparison Operators
Various comparison operators in python are ( ==, != , <>, >,<=, etc.)
x=4
y=5
print(('x > y is',x>y))
Assignment Operators
Assignment Operators in Python are used for assigning the value of the right operand to the
left operand. Various assignment operators used in Python are (+=, – = , *=, /= , etc.).
num1 = 4
num2 = 5
num1+=10
num2+=30
The operator precedence determines which operators need to be evaluated first. To avoid
ambiguity in values, precedence operators are necessary. Just like in normal multiplication
method, multiplication has a higher precedence than addition. For example in 3+ 4*5, the
answer is 23, to change the order of precedence we use a parentheses (3+4)*5, now the
answer is 35. Precedence operator used in Python are (unary + – ~, **, * / %, + – , &) etc.
!=
A = 44
B = 284
C = 284
print(B!=A)
print(B!=C)
<>
X = 5 Y = 5 if ( X <> Y ): print("X is not equal to Y") else: print("X is equal to Y")
2. Tuple assignment:
# equivalent to: (x, y) = (50, 100)
x, y = 50, 100
print('x = ', x)
print('y = ', y)
3. List assignment:
[x, y] = [2, 4]
print('x = ', x)
print('y = ', y)
© copyright 2024, RAJ SOFTWARE SOLUTION, All Rights Reserved
1. INTRODUCTION TO PYTHON
Assignments
Different Forms of Assignment Statements
4. Sequence assignment:
a, b, c = 'RAJ'
print('a = ', a)
print('b = ', b)
print('c = ', c)
# equivalent to: x = x + 1
x += 1
print(x)
• The if statement
• The if-else statement
• The nested-if statement
• The if-elif-else ladder
• Short Hand if statement
• Short Hand if-else statement
• while loop
• for loop
• Nested loop
• break
• continue
• pass
• return
if statement
Syntax:
if condition:
# Statements to execute if True
If execute if statements
# condition is true (condition) block
And
The and keyword is a logical operator, and is used to combine conditional statements:
a = 100
b = 14
c = 700
if a > b and c > a:
print("Both conditions are True")
Or
The or keyword is a logical operator, and is used to combine conditional statements:
a = 100
b = 13
c = 200
if a > b or a > c:
print("At least one of the conditions is True")
for Loop
Syntax:
# Python program to illustrate for loop
for iterator_var in sequence:
cnt = 4
statements(s)
for i in range(0, cnt):
print(i)
while expression:
while expression:
statement(s)
statement(s)
Pass Statement
for i in range(1, 5):
pass
Creating a Array
Array in Python can be created by importing array module. array(data_type, value_list) is
used to create an array with data type and value list specified in its arguments.
# creating an array
importing "array" for array module # printing original array
import array as arr print ("The new created array is : ", end =" ")
integer type for i in range (0, 3):
a = arr.array('i', [1, 2, 3]) print (a[i], end =" ")
print()
© copyright 2024, RAJ SOFTWARE SOLUTION, All Rights Reserved
3. PYTHON ARRAYS
# creating an array with float type (f,d)
b = arr.array('d', [2.5, 3.2, 3.3])
• Remove() method only removes one element at a time, to remove range of elements,
iterator is used.
• pop() function can also be used to remove and return an element from the array, but by
default it removes only the last element of the array, to remove element from a specific
position of the array, index of the element is passed as an argument to the pop()
method.
• Note – Remove method in List will only remove the first occurrence of the searched
element
print ("\r")
print("\r")
Slicing of a Array
In Python array, there are multiple ways to print the whole array with all the elements, but
to print a specific range of elements from the array, we use Slice operation.
Slice operation is performed on array with the use of colon(:). To print elements from
beginning to a range use [:Index],
to print elements from end use [:-Index],
to print elements from specific Index till the end use [Index:],
to print elements within a range, use [Start Index:End Index] and to print whole List with
the use of slicing operation, use [:]. Further, to print whole array in reverse order, use [::-1].
a = arr.array('i', l)
print("Initial Array: ")
for i in (a):
print(i, end =" ")
# Print elements of a range, using Slice operation
Sliced_array = a[3:8]
print("\nSlicing elements in a range 3-8: ")
print(Sliced_array)
# initializing array with array values # initializes array with signed integers
arr = array.array('i', [1, 2, 3, 1, 2, 5])
Example: Following is the example for creating 2D array with 4 rows and 5 columns.
array=[[23,45,43,23,45],[45,67,54,32,45],[89,90,87,65,44],[23,45,67,32,10]]
#display
print(array)
#get the first row
print(array[0])
#get the third row
print(array[2])
#get the first row third element
print(array[0][2])
#get the third row forth element
print(array[2][3])
array=[[23,45,43,23,45],[45,67,54,32,45],[89,90,87,65,44],[23,45,67,32,10]]
#display
print(array)
© copyright 2024, RAJ SOFTWARE SOLUTION, All Rights Reserved
3. PYTHON ARRAYS
Deleting the values from two-dimensional array
You can delete rows using the del function
del array[index]
#creare 2D array with 4 rows and 5 columns
array=[[23,45,43,23,45],[45,67,54,32,45],[89,90,87,65,44],[23,45,67,32,10]]
#display
print(array)
#display
print(len(array))
Updation or deletion of characters from a String is not allowed. This will cause an error
because item assignment or item deletion from a String is not supported. Although deletion
of the entire String is possible with the use of a built-in del keyword. This is because Strings
are immutable, hence elements of a String cannot be changed once it has been assigned.
Only new strings can be reassigned to the same name.
# Updating a String
String1 = "Welcome to the RAJ World"
print("\nUpdated String: ")
print(String1)
While printing Strings with single and double quotes in it causes SyntaxError because String
already contains Single and Double Quotes and hence cannot be printed with the use of
either of these.
Hence, to print such a String either Triple Quotes are used or Escape sequences are used to
print such Strings.
# Initial String
String1 = '''I'm a "RAJ"'''
print("Initial String with use of Triple Quotes: ")
print(String1)
# Positional Formatting
String1 = "{1} {0} {2}".format('Software', 'Raj', 'Solution')
print("\nPrint String in Positional order: ")
print(String1)
# Formatting of Integers
String1 = "{0:b}".format(16)
print("\nBinary representation of 16 is ")
print(String1)
# Formatting of Floats
String1 = "{0:e}".format(165.6458)
print("\nExponent representation of 165.6458 is ")
print(String1)
Join
list1 = ['1','2','3','4']
s = "-“
s = "RajSoftware"
# counts the number of times substring occurs in the given string and returns an integer
print(string.count("raj"))
len()
# Length of below string is 5 # with list
string = "rajsoftware" l = [1,2,3,4]
print(len(string)) print(len(l))
# with tuple
tup = (1,2,3)
print(len(tup))
result = word.find('solution')
print ("Substring 'solution' found at index:", result )
• Python Functions
• Types of Python Functions
• Python Lambda Functions(Anonymous) with EXAMPLES
• What is the map() function in Python?
• Generator & Yield vs Return Example
• type() and isinstance() in Python — What is, Syntax & Examples
• Python time.sleep() — Add Delay to Your Code (Example)
• Python Timer Function — Measure Elapsed Time with EXAMPLES
• Any input parameters or arguments should be placed within these parentheses. You can
also define parameters inside these parentheses.
The statement return [expression] exits a function, optionally passing back an expression to
the caller.
Syntax:
def function_name(parameters):
"""docstring"""
statement(s)
return expression
Funuction
# A simple Python function
def fun():
print("Welcome to RAJ SOFTWARE")
Simple Function
Python Function Declaration :
def fun():
print("Welcome to RAJ SOFTWARE")
# Driver code
num1, num2 = 5, 15
add(num1, num2)
#Note : f for format function
Default arguments
A default argument is a parameter that assumes a default value if a value is not provided in
the function call for that argument. The following example illustrates Default arguments.
# Python program to demonstrate default arguments
def myFun(x, y=50):
print("x: ", x)
print("y: ", y)
# Driver code (We call myFun() with only argument)
myFun(10)
© copyright 2024, RAJ SOFTWARE SOLUTION, All Rights Reserved
5. PYTHON FUNCTIONS
Keyword arguments
The idea is to allow the caller to specify the argument name with values so that caller does
not need to remember the order of parameters.
# Python program to demonstrate Keyword Arguments
def student(firstname, lastname):
print(firstname, lastname)
student(firstname='Raj', lastname='Software')
student(lastname='Software', firstname='Raj’)
Variable-length arguments
In Python, we can pass a variable number of arguments to a function using special symbols.
There are two special symbols:
The first string after the function is called the Document string or Docstring in short. This is
used to describe the functionality of the function. The use of docstring in functions is
optional but it is considered a good practice.
The below syntax can be used to print out the docstring of a function:
Syntax: print(function_name.__doc__)
def evenOdd(x):
"""Function to check if the number is even or odd"""
if (x % 2 == 0):
print("even")
else:
print("odd")
The function return statement is used to exit from a function and go back to the function
caller and return the specified value or data item to the caller.
Syntax: return [expression_list]
def f1():
s = 'I love RAJ SOFTWARE'
# Driver's code
def f2(): f1()
print(s)
f2()
print(cube(7))
print(cube_v2(7))
numbers = (1, 2, 3, 4)
result = map(lambda x: x + x, numbers)
print(list(result))
Returns a list of the results after applying the given function to each item of a given iterable
(list, tuple etc.)
# Python program to demonstrate working of map. # Return double of n
def addition(n):
return n + n
# We double all numbers using map() # Driver's code
numbers = (1, 2, 3, 4) f1()
result = map(addition, numbers)
print(list(result))
We can also use lambda expressions with map to achieve above result.
A generator function in Python is defined like a normal function, but whenever it needs to
generate a value, it does so with the yield keyword rather than return. If the body of a def
contains yield, the function automatically becomes a Python generator function.
# A generator function that yields 1 for the first time, # 2 second time and 3 third time
def simpleGeneratorFun():
yield 1
yield 2
yield 3
c1.subtract(c2)
print(c1)
Python has a built-in function called type() that helps you find the class type of the variable
given as input. For example, if the input is a string, you will get the output as <class ‘str’>,
for the list, it will be <class ‘list’>, etc.
Using type() command, you can pass a single argument, and the return value will be the
class type of the argument given, example: type(object).
Python sleep() is a function used to delay the execution of code for the number of seconds
given as input to sleep().
The sleep() command is a part of the time module. You can use the sleep() function to
temporarily halt the execution of your code.
For example, you are waiting for a process to complete or a file upload.
import time
print("Welcome to Raj Software Solution")
time.sleep(5)
print("This message will be printed after a wait of 5 seconds")
import time
my_message = "RAJ SOFTWARE SOLUTION“
for i in my_message:
print(i)
time.sleep(1)
• Lists in Python
• More about Lists
• Understanding List Comprehensions and Lambda Expressions
• Next and Ranges
• Understanding and using Ranges
• More About Ranges
• Working with Tupes - Pack, Unpack, Compare, Slicing, Delete, Key
• Python Dictionaries
• Working with Other datatypes list, tuble, integer.
• Exploring Python Sets and Frozen Set
• Functions in Set
• Operators in Set
li1 = [“java”,88,True,89,”Male”]
list() Constructor
mylist = list(("Java", "C", "Python"))
print(mylist)
List = [1, 2, 6, 6, 4, 4, 4, 7, 5]
print("\nList with the use of Numbers: ")
print(List)
# Creating a List with mixed type of values (Having numbers and strings)
Negative indexing
List = [1, 2, 'Raj’, 4, 'For', 6, ‘Software’]
# Creating a List
List = [1, 2, 3, 4, 5, 6,7, 8, 9, 10, 11, 12]
print("Initial List: ")
print(List)
# Removing elements from List using Remove() method
List.remove(5)
List.remove(6)
print("\nList after Removal of two elements: ")
print(List)
Li=Li1
print("After Removing duplicates",Li)
# Removing element at a specific location from the Set using the pop() method
List.pop(2)
print("\nList after popping a specific element: ")
print(List)
Slicing of a List
# Creating a List
List = ['R', 'A', 'J', 'S', 'O', 'F',’T', 'W', 'A', 'R', 'E', 'S', 'O', 'L', 'U']
print("Initial List: ")
print(List)
Example
numbers = [12, 13, 14,]
doubled = [x *2 for x in numbers]
print(doubled)
# Displaying list
print(List)
# Displaying list
print(List)
li = [1, 2, 3]
l_iter = iter(li)
print(next(l_iter))
print(next(l_iter))
print(next(l_iter))
print(next(l_iter),"No more elements")
The Python range() function returns a sequence of numbers, in a given range. The
most common use of it is to iterate sequences on a sequence of numbers
using Python loops.
r_ele = range(10)[-1]
print("\nLast element:", r_ele)
r_ele = range(10)[4]
print("\nFifth element:", r_ele)
r_ele = range(10)[-1]
print("\nLast element:", r_ele)
r_ele = range(10)[4]
print("\nFifth element:", r_ele)
Creating Tuples
# An empty tuple
empty_tuple = ()
print (empty_tuple)
print(company)
print(emp)
print(profile)
Concatenation of Tuples
# Code for concatenating 2 tuples # Concatenating above two
tuple1 = (0, 1, 2, 3) print(tuple1 + tuple2)
tuple2 = ('python', 'raj')
© copyright 2024, RAJ SOFTWARE SOLUTION, All Rights Reserved
6. LIST, TUPLES, DICTIONARIES, SETS
Nesting of Tuples
# Code for creating nested tuples
tuple1 = (0, 1, 2, 3)
tuple2 = ('python', 'raj')
tuple3 = (tuple1, tuple2)
print(tuple3)
Repetition in Tuples
# Code to create a tuple with repetition
tuple3 = ('python',)*3
print(tuple3)
Immutable Tuples
#code to test that tuples are immutable
tuple1 = (0, 1, 2, 3)
tuple1[0] = 4 print(tuple1)
© copyright 2024, RAJ SOFTWARE SOLUTION, All Rights Reserved
6. LIST, TUPLES, DICTIONARIES, SETS
Slicing in Tuples
# code to test slicing
tuple1 = (0 ,1, 2, 3)
print(tuple1[1:])
print(tuple1[::-1])
print(tuple1[2:4])
Deleting a Tuple
# Code for deleting a tuple
tuple3 = (0, 1)
del tuple3
print(tuple3)
#case 3
a=(5,6)
Case 3: Comparison starts with a first element of each
b=(6,4)
tuple. In this case 5>6 which is false. So it goes into the
if (a>b):
else block and prints “b is bigger.”
print("a is bigger")
else:
print("b is bigger“)
• The dictionary is the data type in Python, which can simulate the real-life data
arrangement where some specific value exists for some particular key.
• Keys must be a single element Value can be any type such as list, tuple, integer, etc.
# Creating a Dictionary
Dict = {'Name': 'RAJ', 1: [1, 2, 3, 4]}
print("Creating Dictionary: ")
print(Dict)
# Creating a Dictionary
Dict = {1: 'RAJ', 'name': 'For', 3: 'RAJ’}
# Initial Dictionary
Dict = { 5 : 'Welcome', 6 : 'To', 7 : 'RAJ',
'A' : {1 : 'RAJ', 2 : 'For', 3 : 'RAJ'},
'B' : {1 : 'RAJ', 2 : 'Life'}}
print("Initial Dictionary: ")
print(Dict)
# A frozen set
frozen_set = frozenset(["e", "f", "g"])
print("\nFrozen Set")
print(frozen_set)
# Uncommenting below line would cause error as we are trying to add element to a frozen
set #
frozen_set.add("h")
© copyright 2024, RAJ SOFTWARE SOLUTION, All Rights Reserved
6. LIST, TUPLES, DICTIONARIES, SETS
Adding elements
# A Python program to demonstrate adding elements in a set Creating a Set
people = {"Raj", "Anand", "Sree"}
people.add("Vettri")
for i in range(3,9):
set2.add(i)
Difference
To find difference in between sets. Similar to find difference in linked list. This is done through
difference() or – operator
for i in range(5):
set1.add(i)
for i in range(3,9):
set2.add(i)
# Difference of two sets using difference() function
set3 = set1.difference(set2)
Clearing sets
Clear() method empties the whole set.
# Python program to demonstrate clearing of set
set1 = {1,2,3,4,5,6}
print("Initial set")
print(set1)
For example, if your filename is sample.py, the module name will be sample. With module
functionality, you can break your code into different files instead of writing everything inside
one file.
What is the Python import module?
• A file is considered as a module in python. To use the module, you have to import it
using the import keyword.
• The function or variables present inside the file can be used in another file by importing
the module.
• This functionality is available in other languages, like typescript, JavaScript, java, ruby, etc.
Step 2 :
Type the following code in mymodule.py
def display():
return "from my module"
Step 3 :
Create a file named as testmodule.py
Step 4 :
Import the mymodule.py using following code.
import mymodule
print(mymodule.display())
When you want only specific things to be imported, you can make use of "from" keyword to
import what you want.
So the syntax is
from module import your function_name , variables,... etc.
Syntax:
import module def display_message1():
Or by using return "All about Python!"
from module import *
test.py
my_name = "RAJ SOFTWARE SOLUTION"
my_address = "Salem"
def display_message():
return "Welcome to RAJ SOFTWARE Tutorials!"
Using just import module name, to refer to the variables and functions inside the module, it
has to prefix with module name.
import test
print(test.display_message())
print(test.display_message1())
print(test.my_name)
print(test.my_address)
Using import *, the functions and variables are directly accessible, as shown in the example
below:
From the command-line options, the -m option is used for locating the path of the given
module, and it executed the module as the __main__ module of the program.
The runpy module is the standard module of Python , which is used for internally supporting
this mechanism.
The runpy module allows a script to be located by using the namespace of the Python module
instead file system.
The run_module() function is used for executing the code containing the specific module, and
it will return the result of the module globals dictionary.
The module_name argument should be the actual module name. Suppose the name of the
module referred to any package instead of the normal module. In that case, that package will
be imported, and the __main__ sub module inside the package will be executed, and it will
return the result of the module globals dictionary.
The special global variables, that is, __name__, __spec__, __file__, __cached__, __loader__
and __package__ are set in the globals dictionary before the execution of module.
The run_path() function is used for executing the program in the file at the given path, and it
will return the module globals dictionary as a result. The given path can refer to the Python
source file, a compiled bytecode file, or a valid sys.path entry that contains the __main__
module, such as a zipfile including the top-level __main__.py file.
The special global variables, that is, __name__, __spec__, __file__, __cached__, __loader__
and __package__ are set in the globals dictionary before the execution of module.
def main():
p=4
q=6
r=2
s=8
t=7
print ("sum of p, q, r, s, t = ")
print (add(p,q,r,s,t))
return
if __name__=='__main__':
main()
Although, the user can execute the above file without importing it:
import runpy
runpy.run_module('runpy_example', run_name='__main__')
runpy.run_path('runpy_example.py', run_name='__main__')
dir() is a powerful inbuilt function in Python, which returns list of the attributes and methods
of any object (say functions , modules, strings, lists, dictionaries etc.)
print(dir())
------------------------
From Module
import random
import math
print(dir())
-------------------------
print("The contents of the random library are::“)
print(dir(random))
print(dir(RSS))
From Class :
class Sales:
def __dir__(self):
return['customer_name', 'product',
'quantity', 'price', 'date']
my_cart = Sales()
print(dir(my_cart))
Symbol table: Symbol table is a data structure which contains all necessary information about
the program. These include variable names, methods, classes, etc.
Global symbol table stores all information related to the global scope of the program, and is
accessed in Python using globals() method.
# global variable
name = 'raj software'
# Calling global()
globals()['name'] = raj software solution'
print('After modification:', name)
It is used to create global variables in python from a non-global scope i.e inside a function.
Global keyword is used inside a function only when we want to do assignments or when we
want to change a variable.
change()
UnboundLocalError: local variable 'a' referenced before assignment
def change():
# using a global keyword
global x
# increment value of a by 5
x=x+5
print("Value of x inside a function :", x)
change()
print("Value of x outside a function :", x)
Symbol table: It is a data structure created by a compiler for which is used to store all
information needed to execute a program.
Local symbol Table: This symbol table stores all information needed for the local scope of the
program and this information is accessed using python built-in function locals().
If you’ve altered the module source file using an outside editor and want to test the updated
version without leaving the Python interpreter, this is helpful. The module object is the return
value.
import importlib
importlib.reload(module)
import sys
import importlib
importlib.reload(sys)
print(sys.path)
Creating Package
Let’s create a package named mypckg that will contain two modules mod1 and mod2.
To create this module follow the below steps –
For example, we can also create the __init__.py file for the above module as –
__init__.py
from .mod1 import raj
from .mod2 import sum
mod1.raj()
res = mod2.sum(1, 2)
print(res)
• Overview of OOP
• Creating Classes and Objects
• The self variable
• Constructor
• Types of Methods
• Instance Methods
• Static Methods
• Class Methods
• Built-In Class Attributes
• Destroying Objects
• Inheritance super() function and Type of Inheritance
• Encapsulation and Polymorphsim
The main concept of OOPs is to bind the data and the functions that work on that together as
a single unit so that no other part of the code can access this data.
Objects
• The object is an entity that has a state and behavior associated with it.
• It may be any real-world object like a mouse, keyboard, chair, table, pen, etc.
• Integers, strings, floating-point numbers, even arrays, and dictionaries, are all objects.
An object consists of :
State: It is represented by the attributes of an object. It also reflects the properties of an
object.
Behavior: It is represented by the methods of an object. It also reflects the response of an
object to other objects.
Identity: It gives a unique name to an object and enables one object to interact with other
objects
© copyright 2024, RAJ SOFTWARE SOLUTION, All Rights Reserved
8. PYTHON CLASSES AND OBJECTS
Class Creation
class Person:
def print_name(self):
print("HelloWorld")
Object Creation
obj = Person()
2. If we have a method that takes no arguments, then we still have to have one argument.
Types of constructors :
default constructor: The default constructor is a simple constructor which doesn’t accept any
arguments.
parameterized constructor: constructor with parameters is known as parameterized
constructor. The parameterized constructor takes its first argument as a reference to the
instance being constructed known as self and the rest of the arguments are provided by the
programmer.
© copyright 2024, RAJ SOFTWARE SOLUTION, All Rights Reserved
8. PYTHON CLASSES AND OBJECTS
Example of default constructor :
class Person:
# default constructor
def __init__(self):
self.name = "Mr.Sethil Kumar"
Instance methods
Instance methods are the most used methods in a Python class. These methods are only
accessible through class objects. If we want to modify any class variable, this should be done
inside an instance method.
The first parameter in these methods is self. self is used to refer to the current class object’s
properties and attributes.
Instance methods
Instance methods are the most used methods in a Python class. These methods are only
accessible through class objects. If we want to modify any class variable, this should be done
inside an instance method.
The first parameter in these methods is self. self is used to refer to the current class object’s
properties and attributes.
def getTeamName(self):
return self.teamName
c = Cricket()
c.setTeamName('India')
print(c.getTeamName())
In class methods, we use use the cls variable to refer to the class.
class Cricket:
teamName = 'India'
@classmethod
def getTeamName(cls):
return cls.teamName
print(Cricket.getTeamName())
© copyright 2024, RAJ SOFTWARE SOLUTION, All Rights Reserved
8. PYTHON CLASSES AND OBJECTS
Static methods
Static methods are usually used as a utility function or when we do not want an inherited
class to modify a function definition. These methods do not have any relation to the class
variables and instance variables; so, are not allowed to modify the class attributes inside a
static method.
To declare a static method, we need to use the @staticmethod.
class Cricket:
teamName = 'India'
@staticmethod
def utility():
print("This is a static method.")
c1 = Cricket()
c1.utility()
Cricket.utility()
© copyright 2024, RAJ SOFTWARE SOLUTION, All Rights Reserved
8. PYTHON CLASSES AND OBJECTS
Built-In Class Attributes
Attribute Description
__dict__ This is a dictionary holding the class namespace.
__bases__ A possibly empty tuple containing the base classes in the order of their
occurrence.
# class
class Cricket:
def __init__(self):
print("Hello from __init__ method.")
O/P:
{'__module__': '__main__', '__doc__’: ‘……..
# class # class
class Cricket: class Cricket:
'This is a sample class called Cricket.' 'This is a sample class called Awesome.'
O/P: O/P:
This is a sample class called Cricket Cricket
# class # class
class Cricket: class Cricket:
O/P: O/P:
__main__ (<class 'object'>,)
Destroying Objects
Destructors are called when an object gets destroyed. In Python, destructors are not needed
as much as in C++ because Python has a garbage collector that handles memory
management automatically.
The __del__() method is a known as a destructor method in Python. It is called when all
references to the object have been deleted i.e when an object is garbage collected.
def __del__(self):
# body of destructor
# Initializing
def __init__(self):
print('Employee created.')
obj = Employee()
del obj
Inheritance is the capability of one class to derive or inherit the properties from another
class.
Class BaseClass:
{Body}
Class DerivedClass(BaseClass):
{Body}
class Emp(Person):
def Print(self):
print("Emp class called")
The super() function is a built-in function that returns the objects that represent the parent
class. It allows to access the parent class’s methods and attributes in the child class.
# parent class # child class
class Person(): class Student(Person):
def __init__(self, name, age): def __init__(self, name, age):
self.name = name self.sName = name
self.age = age self.sAge = age
# inheriting the properties of parent class
def display(self): super().__init__("Anand", age)
print(self.name, self.age) Person.__init__(self,"nss", age)
def displayInfo(self):
print(self.sName, self.sAge)
# Base class
class Parent:
def func1(self):
print("This function is in parent class.")
# Derived class
class Child(Parent):
def func2(self):
print("This function is in child class.")
# Driver's code
object = Child()
object.func1() object.func2()
© copyright 2024, RAJ SOFTWARE SOLUTION, All Rights Reserved
8. PYTHON CLASSES AND OBJECTS
2. Multiple Inheritance
# Python program to demonstrate multiple inheritance
# Base class1 # Derived class
class Mother: class Son(Mother, Father):
mothername = "" def parents(self):
print("Father :", self.fathername)
def mother(self): print("Mother :",
print(self.mothername) self.mothername)
# Base class2
class Father: # Driver's code
fathername = "" s1 = Son()
s1.fathername = "RAM"
def father(self): s1.mothername = "SITA"
print(self.fathername) s1.parents()
# Base class
class Grandfather:
# Intermediate class
class Father(Grandfather):
def __init__(self, fathername, grandfathername):
self.fathername = fathername
def print_name(self):
print('Grandfather name :', self.grandfathername)
print("Father name :", self.fathername)
print("Son name :", self.sonname)
# Driver code
s1 = Son('Prince', 'Rampal', 'Lal mani')
print(s1.grandfathername) s1.print_name()
© copyright 2024, RAJ SOFTWARE SOLUTION, All Rights Reserved
8. PYTHON CLASSES AND OBJECTS
4. Hierarchical Inheritance
# Python program to demonstrate Hierarchical inheritance
# Base class
class Parent:
def func1(self):
print("This function is in parent class.")
# Derived class1
class Child1(Parent):
def func2(self): # Driver's code
print("This function is in child 1.") object1 = Child1()
object2 = Child2()
# Derivied class2 object1.func1()
class Child2(Parent): object1.func2()
def func3(self): object2.func1()
print("This function is in child 2.") object2.func3()
© copyright 2024, RAJ SOFTWARE SOLUTION, All Rights Reserved
8. PYTHON CLASSES AND OBJECTS
5. Hybrid Inheritance
# Python program to demonstrate Hybrid inheritance
class School:
def func1(self):
print("This function is in school.")
class Student1(School):
def func2(self):
print("This function is in student 1. ")
class Student2(School):
def func3(self):
print("This function is in student 2.") # Driver's code
object = Student3()
class Student3(Student1, School): object.func1()
def func4(self): object.func2()
print("This function is in student 3.")
© copyright 2024, RAJ SOFTWARE SOLUTION, All Rights Reserved
8. PYTHON CLASSES AND OBJECTS
Encapsulation
Encapsulation describes the idea of wrapping data and the methods that work on data
within one unit. This puts restrictions on accessing variables and methods directly and can
prevent the accidental modification of data.
Protected members:-
Protected members (in C++ and JAVA) are those members of the class that cannot be
accessed outside the class but can be accessed from within the class and its subclasses. To
accomplish this in Python, just follow the convention by prefixing the name of the member
by a single underscore “_”.
class Derived(Base):
def __init__(self):
# Calling constructor of Base class
Base.__init__(self)
print("Calling protected member of base class: ",
self._a)
obj1 = Derived()
obj2 = Base()
# Calling protected member Can be accessed but should not be done due to
convention
print("Accessing protected member of obj1: ", obj1._a)
class USA():
def capital(self):
print("Washington, D.C. is the capital of USA.")
def language(self):
print("English is the primary language of USA.")
def type(self):
print("USA is a developed country.")
© copyright 2024, RAJ SOFTWARE SOLUTION, All Rights Reserved
8. PYTHON CLASSES AND OBJECTS
obj_ind = India()
obj_usa = USA()
for country in (obj_ind, obj_usa):
country.capital()
country.language()
country.type()
# Driver code
x = Poly_fun()
print(x.add(12, 3))
print(x.add(10,20,3))
© copyright 2024, RAJ SOFTWARE SOLUTION, All Rights Reserved
8. PYTHON CLASSES AND OBJECTS
Polymorphism with Inheritance:
Polymorphism lets us define methods in the child class that have the same name as the
methods in the parent class.
class Bird:
def intro(self):
print("There are many types of birds.")
def flight(self):
print("Most of the birds can fly but some cannot.")
class sparrow(Bird):
def flight(self):
print("Sparrows can fly.")
obj_bird = Bird()
obj_spr = sparrow()
obj_ost = ostrich()
obj_bird.intro()
obj_bird.flight()
obj_spr.intro()
obj_spr.flight()
obj_ost.intro()
obj_ost.flight()
© copyright 2024, RAJ SOFTWARE SOLUTION, All Rights Reserved
CHAPTER -9
DATA SCIENCE
USING
PYTHON
© copyright 2024, RAJ SOFTWARE SOLUTION, All Rights Reserved
CONCEPTS
DATA SCIENCE USING PYTHON
• Introduction to numpy
• Creating arrays
• Indexing Arrays
• Array Transposition
• Universal Array Function
• Array Processing
• Array Input and Output
• Python Matrix — Transpose, Multiplication, NumPy Arrays Examples
• SciPy in Python Tutorial — What is | Library & Functions Examples
Data Science is the area of study which involves extracting insights from vast amounts of data
using various scientific methods, algorithms, and processes. It helps you to discover hidden
patterns from the raw data. The term Data Science has emerged because of the evolution of
mathematical statistics, data analysis, and big data.
Data Science is an interdisciplinary field that allows you to extract knowledge from structured
or unstructured data. Data science enables you to translate a business problem into a
research project and then translate it back into a practical solution.
Arrays in NumPy
• It is a table of elements (usually numbers), all of the same type, indexed by a tuple of
positive integers.
• In NumPy, dimensions are called axes. The number of axes is rank.
In this example, we are creating a two-dimensional array that has the rank of 2 as it has
2 axes.
arr = np.array( [[ 1, 2, 3],
[ 4, 2, 5]] )
© copyright 2024, RAJ SOFTWARE SOLUTION, All Rights Reserved
9. DATA SCIENCE USING PYTHON
import numpy as np
import numpy as np
For example:
print(arr[1:5])
print(arr[4:])
print(arr[:4])
print(arr[-3:-1])
# Original matrix
original_matrix = np.matrix([[1, 2, 3], [4, 5, 6]])
# Transposed matrix
transposed_matrix = original_matrix.transpose()
print("Original Matrix:")
print(original_matrix)
print("\nTransposed Matrix:")
print(transposed_matrix)
NumPy Universal functions (ufuncs in short) are simple mathematical functions that operate
on ndarray (N-dimensional array) in an element-wise fashion.
It supports array broadcasting, type casting, and several other standard features. NumPy
provides various universal functions like standard trigonometric functions, functions for
arithmetic operations, handling complex numbers, statistical functions, etc.
Load()
import numpy as np
# load the saved NumPy array
loaded_array = np.load('file1.npy')
import numpy as np
from scipy import io as sio
array = np.ones((4, 4))
sio.savemat('example.mat', {'ar': array})
data = sio.loadmat(‘example.mat', struct_as_record=True)
data['ar']
To work with Numpy, you need to install it first. Follow the steps given below to install
Numpy.
Step 1)
The command to install Numpyis :
pip install NumPy
Step 2)
To make use of Numpy in your code, you have to import it.
import NumPy
Matrix Addition
To perform addition on the matrix, we will create two matrices using numpy.array() and
add them using the (+) operator.
import numpy as np
• Reading and Writing CSV Files in Python — Using Module & Pandas
Data visualization can be done with various tools like Tableau, Power BI, Python.
Matplotlib
Matplotlib is a low-level library of Python which is used for data visualization. It is easy to use
and emulates MATLAB like graphs and visualization.
plt.show()
Installation
To install the Python-mysql-connector module, one must have Python and PIP,
preinstalled on their system. If Python and pip are already installed type the below
command in the terminal.
dataBase = mysql.connector.connect(
host ="localhost",
user ="user",
passwd ="password"
)
print(dataBase)
# creating database
cursorObject.execute("CREATE DATABASE raj")
dataBase = mysql.connector.connect(
host ="localhost",
user ="user",
passwd ="password"
)
# creating database
cursorObject.execute("CREATE DATABASE raj")
dataBase = mysql.connector.connect(
host ="localhost",
user ="user",
passwd ="password",
database = "raj"
)
# preparing a cursor object
cursorObject = dataBase.cursor()
© copyright 2024, RAJ SOFTWARE SOLUTION, All Rights Reserved
12. PYTHON WITH MYSQL
# creating table
studentRecord = """CREATE TABLE STUDENT (
NAME VARCHAR(20) NOT NULL,
BRANCH VARCHAR(50),
ROLL INT NOT NULL,
SECTION VARCHAR(5),
AGE INT
)"""
# table created
cursorObject.execute(studentRecord)
dataBase = mysql.connector.connect(
host ="localhost",
user ="user",
passwd ="password",
database = "raj"
)
cursorObject.execute(sql, val)
dataBase.commit()
cursorObject.executemany(sql, val)
dataBase.commit()
© copyright 2024, RAJ SOFTWARE SOLUTION, All Rights Reserved
12. PYTHON WITH MYSQL
Fetching Data
We can use the select query on the MySQL tables in the following ways –
Order By Clause
SELECT column1, column2
FROM table_name
ORDER BY column_name ASC|DESC;
Update Data
The update query is used to change the existing values in a database. By using
update a specific value can be corrected or updated.
Drop Tables
Drop command affects the structure of the table and not data. It is used to delete an already
existing table.