Core Python Notes - Reference For Teachers Eshwar Computers
Core Python Notes - Reference For Teachers Eshwar Computers
For teachers
eshwar computers
CORE
Eshwar K 4/24/20
CORE PYTHON NOTES – REFERENCE FOR TEACHERS ESHWAR COMPUTERS
About language
Depends on the programming style the computer languages are mainly
classified into 3 major categories
They are like: -
A. High level language
B. Low level language
C. Middle level language
High - level language: -
This type of language developed foe humans. It is also called as
business-oriented language. The format of this language is universal English
language.
Now a days we are having so many high-level languages.
They are like: -
1. C-language
2. Basic
They are not using from 2000 because they not work in
main frame computers
3. Cobol
4. Python & other languages
Low level language: -
It is developed for the computer the format of this language is [0,1]. In this
reason it is also called binary language (or) machine level language
Middle level language: -It is the combination of high level and low-level
languages it is also called assembled languages.
ii. It converts high level to low level format (0,1). After this
process we can run our program.
Note: - it is very fastest translator because at the time of execution it
never stops the process
Now a days we are having so many compilers-oriented languages
they are like c, c++, java etc.,
2. Interpreter: -it is another famous translator using this translator we can
perform following operations at the time of program execution.
ABOUT
PYTHON
Python is general purpose of high-level language with interpreter
technology.
Applications of Python
Where we can use python?
We can use everywhere. The most common important application areas
are: -
4) Platform independent
Once we write a python program it can run on any platform without
rewriting again. Initially python virtually machine is responsible to convert
into machine understandable form. Python programs can migrate.
5) Portability
It is migrated easily
6) Dynamically Typed
In python we are not required to declare any type for variables.
Whenever we are assigning the value, based on value type will be located
automatically. Hence python is considered as dynamically typed language.
But JAVA, C,C++ are statically typed languages because we have to
provide type at beginning only.
7) Both procedure oriented and object oriented
Python supports both procedures oriented like C, PASCAL etc…. and
object oriented like C++, JAVA features. Hence, we can get benefits of both
like security and reusability.
8) Interpreted
10) Embedded
We can use python programs in any other language’s . We can
embed python programs anywhere.
Drawbacks of Python
1. Performance wise it is not up to the mark because it is interpreted
language
2. Not using mainly for mobile applications.
4) Ruby Python
It is used mainly for the ruby platforms.
5) Anaconda python
It is specially designed for handling large volume of data
processing.
Available Versions
The first official version of python is python 1.0 in January 1994. Later it
contains so many other versions. It is mainly divided into two versions like,
Python 2.0 and python 3.0
The python- 2.0 is limited version it is not continued after 2020. The
current version is python 3.10.0
Python 3.10.0 – OCT-4th, 2021
Note that Python 3.10.0 cannot be used on Windows XP or earlier
Identifiers: -
A name in python program is called identifiers. It can be a class
name or function name or modules name or a variable name
Rules to define identifiers in python
1. The only allowed characters in python are
I. Alphabet symbols (either lower case and upper case)
II. Digits (0 to 9)
III. Underscore symbol (_)
By mistake if we are using any other symbol like $ then we will get
syntax error
Cash = 20 (write)
Ca$h = 20 (wrong)
2. Identifiers should not start with digits
123total=100 (wrong)
Total123=100 (write)
3. Identifiers are case sensitive. Of course, python language is case sensitive
language
total=10
TOTAL = 999
Print (total) #10
Print (TOTAL) #999
4. We cannot use reserved words as identifiers
Eg: - def = 10 (wrong)
5. There is no length limit for python identifiers
6. If identifiers are start with underscore (_) then it indicates it is private
7. If identifiers start with __ (two underscore symbols) indicates that
strongly private identifiers
8. If the identifiers start and ends with two underscore symbols then the
identifier is language defined special name, which is also known as magical
method or constructor method
Ex: __ abc __
Ex: - 1
>>> s = “Lakshman \n Kumar”
>>> print (s)
>>> Lakshman
>>> Kumar
Ex: - 2
>>> s = “This is symbol \” Lakshman\””
>>> print (s)
>>> This is symbol “Lakshman”
Ex: - 3
>>> a = 10
>>> b = 3
>>> print (“A is: “, a,” \n”,” b is:”, b,” \n”,” the sum is”, (a + b),” \n”)
13
1) Write a program to print a message called “Welcome to Python”?
Print ("\”Welcome to python\”")
Type (): -By using this function we can display data type of particular variable
sno=1
sname="Lakshman"
avg=85.666
print ("stuno is:", sno)
print ("stu name is:", sname)
print ("stu Avg is:", avg)
print ("stu No data type is:", type(sno))
print ("stu Name data type is:", type(sname))
print ("stu Avg data type is:", type(avg))
output: -
stuno is: 1
stu name is: Lakshman
stu Avg is: 85.666
stuno data type is: <class 'int'>
stu data type name is: <class 'str'>
stu data type Avg is: <class 'float'>
a, b, c=10,20,30
print ("A is ", a)
print ("B is ", b)
print ("C is ", c)
output: -
A is 10
B is 20
C is 30
Program for variables swapping
By using third variable concept
a, b=10,20
print ("Values Before swapping")
print ("A value is:", a)
print ("B value is:", b)
c=a
a=b
b=c
print ("Values After swapping")
print ("A value is:", a)
print ("B value is:", b)
ord (): -By using this function we can display ASCII value of particular letter
ASCII: - American standard code information interchange
Example: -
ch='A'
print("The ASCII value of A letter is:",ord(ch))
Input (): - it is one of the data input function. By using this function, we can
enter any type of information through keyboard. The complete data treated
as string format means unable to perform mathematical operations
To ratify this problem, we have to convert data into numerical
format by using conversation functions like: -
Int
Eval
Syntax: -
Var _ name= input(“message”)
3) Write a program enter any two integer values then display the sum of two
numbers.
num1=input("Enter first number:")
num2=input("Enter second number:")
add=num1+num2
print("Addition=",add)
Example 2: -
num1=input("Enter first number:")
num2=input("Enter second number:")
add=int(num1)+int(num2)
print("Addition=",add)
Example 3: -
num1=input("Enter first number:")
num2=input("Enter second number:")
add=eval(num1)+eval(num2)
print("Addition=",add)
Try This: -
1) Write a program enter any two integer values then perform all arithmetical
operations?
2) Write a program enter student number, name and address then display the
accepted data?
3) Write a program enter student number, name and Three subjects’ marks then
find total and average marks?
By using compound Assignment concept to print employee number, name &
salary
empno,empname,salary=1,"BL",50000
print("Emp number:",empno,"\nEmp name:",empname,"\nEmp salary:",salary)
Percentage operations: -
In print function we can apply C language percentage operators
for printing information. the available operators are
1. % d to print integer values
2. % g to print floating values
3. % s to print string values
4. % c to print single letter
Example: -
empno,empname,salary=1,"Deva",5000.65
print ("Emp number: %d\n Emp name: %s\n Emp salary: %g"% (empno, empname,
salary))
Example 2: -
empno, empname, esal=101,"lucky",50000.45
print ("Emp no: {0} \n Emp name: {1} \n Emp sal: {2}". Format (empno, empname, esal))
FUNCTIONS
User defined functions: -
In this concept we can develop our own functions these functions are
accessible anywhere of the program to create UDFs function we have to use a
keyword called def (definition).
Syntax: -
def fun_name():
pro state 1
Types of UDFs:
Depends on the programming style the UDFs are mainly classified
into followings categories
1. Function without parameters and without return value
2. Function with parameters
3. Function with return values
4. Function with parameters and with return values
5. Function with default arguments
6. Function with named arguments
7. Function overloading (no need to implement)
8. Function With “N” of arguments
9. Return More Than 1 Value.
10.Call By Value
11.Call By Ref
Syntax: -
def disc ():
print (“Hi BL”)
print (“Hi Lucky”)
disc () # function calling
output: -
Hi BL
Hi Lucky
Example: -
def show():
sname="Lakshman"
sno="4"
addr="tenalli"
print("Student name:",sname)
print("student numner:",sno)
print("Address:",addr)
show()
Try This: -
4) Create a function called emp in this function enter employee number,
name, salary, total days and present days then display net salary?
net salary= (salary/total days) * present days
5) Create a function called emp in this function enter employee number,
name, department, salary and address then display the expected
information with format option?
6) Create a function called stu in this function enter student number, name,
course, and three subject marks then find total and average marks (display
complete information with in percentage mode)?
Try This: -
7) In the main program enter two integers to pass these two values into a
function called swap this function performs swapping by using compound
assignment?
8) In the main program enter student number, name, course, to pass these
three values into a function called show the function will display all values?
9) In the main program enter employee number, name, salary, allowances,
deductions to pass salary, allowances and deductions into a function called
show and find out following things?
I. Gross salary + allowances
II. Net salary gross – deductions
Named arguments: -
It is one of the new concepts of python in this concept we can pass
function parameters values by using variables and the parameters order is not
important
Example: -
def mgs (id, name):
print ("Emp id is", id)
print ("Emp name is”, name)
mgs (1,'lucky')
mgs (name='BL', id=2) # named arguments
Syntax: -
Example 2: -
def emp():
eno=input("enter emp number:")
ename=input("Enter emp name:")
sal=input("Enter salary:")
td=input("Enter total days:")
pd=input("Enter present days:")
print("emp no:",eno)
print("emo name",ename)
print("emp sal",sal)
print("emp td",td)
print("emp pd",pd)
net=int(sal)/int(td)*int(pd)
return(net)
net=emp()
print("Net salary is:",net)
Try This: -
10) Create a function called info in this function Enter any two integer values then find out
sum, subtraction, multiplication, division return all values and display the function out
put?
Function with parameters and with return value: -
Example 2: -
def sum(a,b):
c=a+b
return(c)
a=int(input("Enter A number:"))
b=int(input("Enter B number:"))
print("A is :",a)
print("B is :",b)
c=sum(a,b)
print("The sum is:",c)
Try This: -
11) In the main program enter Employee number, name, salary, total days, present days
into a function called info this function return net salary?
12) In the main program Enter student number, name and three subject marks to pass
three subject marks into a function called info it returns total, average marks and
grade?
Example: -
def show (a=1, b=25):
print ("a is:", a)
print ("b is:", b)
show (12,16)
show (12)
show ()
Function overloading: -
The meaning of function overloading is redeclaration of existing
function. Because in other languages the function performs single task. Means
unable to perform more than one option. To implement this function
overloading concept, but in python we are not having this concept because by
default python supports multiple operation.
Example: -
def sum (a, b):
c=a + b
return(c)
a=eval (input ("Enter A value:"))
b=eval (input ("Enter B value:"))
c=sum (a, b)
print ("The sum is:", c)
Conditional operations
By using python, we can implement all types of conditional
operations. To implement this concept, we are having following statements
1. If
2. If…. else
3. If… elif... else
If: - it is also called simple if statement by using this statement we can check only
true condition.
Syntax: -
If Cond:
Stat 1
Q: Write a program enter an integer value check whether it positive only?
a=int(input("Enter A number"))
if a>0:
print("A is Positive")
Model2:
a=int(input(“Enter A number:”))
out=“A is positive” if (a>0) else “A is Negitive”
print(out)
Model3:
a=int(input(“Enter A number:”))
print(“A is positive” if (a>0) else “A is Negitive”)
Try This: -
1) Enter one integer check weather even or odd?
2) Enter any two integer values then find out highest value?
3) Enter student number, name and three subject marks then find out total,avg
and check student is pass or fail? (avg >=35 then pass)
Note: - In the above program we are generating grade without checking of subject wise
pass or fail to ratify this problem we nested if
sno=input("Enter Student number")
sname=input("Enter student name")
s1=eval(input("enter S1 marks:"))
s2=eval(input("enter S2 marks:"))
s3=eval(input("enter S3 marks:"))
tot=s1+s2+s3
avg=tot/3.0
print("total marksks:",tot)
print("average marks:",avg)
if (s1>=35 and s2>=35 and s3>=35):
if (avg>=60):
print("grade is A")
elif (avg>=50):
print("Grade is B")
elif (avg>=35):
print("Grade is C")
else:
print("Student is FAIL")
Enter any two integers values and also enter choice depends in the choice perform
Arithmetical operations the program output as follows
Enter A no: 10
Enter B no: 3
Menu
1. Sum
2. Sub
3. Mul
4. Div
Enter choice [1…4]: 1
Sum is: 13
a=int(input("Enter A no:"))
b=int(input("Enter B no:"))
print("Menu \n ----- \n 1.Sum \n 2.Sub \n 3.Div \n 4.Mul")
c=int(input("Enter Choice[1..4]:"))
if c==1:
print("The sum is:",a+b)
elif c==2:
print("The sub is:",a-b)
elif c==3:
print("The sum is:",a/b)
elif c==4:
print("The sum is:",a*b)
else:
print("Error choice")
Try This: -
15) Enter Employee number, name and experience depends on experience find salary and
remaining?
experience salary
1–5 5000
6 - 10 10000
11 – 15 15000 Allowances 20% on salary
else 25000 Gross salary + allowances
Deductions 5% on gross
Net salary gross - deductions
16) In the main block enter student number, name and three subject marks into a function
called total it returns total marks to pass total marks into a function called average it
returns Average marks to pass average marks into a function called grade it returns
student grade?
Looping controls
The concept of looping is re-execution particular statement
into specified times to implement this concept we are having the following
statement
1. Single looping statements
2. Multiple looping statements
Single looping statements: -
Example 2: -
For x in range (1,10):
print(x)
Try This: -
17) Write a program to print 1 to 10 numbers and sum of 10 numbers?
18) Enter a number then display corresponding factorial value?
For…else: - the else part is executed whenever the for loop is closed without any
interruption.
Example 1: -
for i in range (1,5):
print(i)
else:
print("The loop is over")
Example 2: -
for i in range (1,10):
print(i)
if i==5:
break
else:
print ("The loop is over")
Note: - the above program loop cycle is 10 numbers but we are closing for loop
in the middle of the process. In this reason the else part will not be executed.
Write a program to identify even and odd numbers from 1 to 10?
for i in range (1,11):
if i%2==0:
print("Even numbers:",i)
else:
print("odd numbers:",i)
String Iteration: -
In python we can perform all types of string related operations. To
implement this concept, we have to use for in statement. By using this concept,
we can access letter by letter .
Ex: -
s='Lakshman Kumar'
for i in s:
print(i)
Write a program Enter a string then count number of upper case and lower case?
s=input ("Enter a string:")
l=0
u=0
for i in s:
if i>'Z':
l=l+1
else:
u=u+1
print("Lower Letters Are:",l)
print("upper Letters are:”,u)
Try This: -
2. Strip (): -By using this function we can remove un necessary spaces of a string
(left side and right side)
Example: -
s=" Lucky "
n=len (s)
print ("the string is:", s)
print ("The string length is:", n)
n=len (s. strip ())
print ("The string without spaces on both side:", n)
3. lstrip: - By using this function we can remove left side spaces of a string
Example: -
s=" Lucky"
n=len(s)
print ("the string is:", s)
print ("The string length is:", n)
n=len (s. lstrip ())
print ("The string without spaces on left side:", n)
4. rstrip: - By using this function we can remove right side spaces of a string
Example: -
s="Lucky "
n=len(s)
print ("the string is:", s)
print ("The string length is:", n)
n=len (s. rstrip ())
print ("The string without spaces on Right side:", n)
Note: - By using lstrip () and rstrip () function we can remove unnecessary data
also
Example: -
s="1216Lucky"
print ("String is:", s)
print ("String length is:", s. lstrip ("1216"))
s="Lucky 121"
print ("String is:", s)
print ("String length is:", s. rstrip ("121”))
is: - With the help of this keyword we can compare two memory location are
similar or not.
Example: -
s1=input ("Enter A Sting1:")
s2=input ("Enter A Sting2:")
If s1 is s2:
print ("String1 and string2 memory location same")
else:
print ("String1 and string2 memory location NOT same")
equals (==): -By using this operator, we can compare data between two
memory variables
Example: -
s1=input ("Enter A string:")
s2=input ("Enter A string:")
if s1==s2:
print ("They Are Equal")
else:
print ("They Are Not Equal")
Not equals (! =): -It will perform revers operation of equals to operater.
Example: -
s1=input ("Enter A string:")
s2=input ("Enter A string:")
if s1! =s2:
print ("S1 and S2 are not same")
else:
print ("S1 and S2 are same ")
in: - By using this keyword we can perform data searching operation, In the
format of letter by letter.
Example: -
s1=input ("Enter string1:")
s2=input ("Enter string2:")
if s2 in s1:
print ("s2 is available in s1")
else:
print ("s2 is not available in s1")
10. enumerate (): - To display the given string information in the format of an
array with index number.
Example: -
s1="python"
print ("old string is:", s1)
print (enumerate (s1))
11. Split (): -With the help of this function we can split the given string based
on given separator, by default the string will be separate by using spaces.
Example: -
s1="my name is Lakshman"
print("old string is:",s1)
print(s1.split())
print()
s1="my-name-is-Lakshman kumar"
print("old string is:",s1)
print(s1.split("-"))
print()
s1="my*name*is*Lakshman*kumar"
print("old string is:",s1)
print(s1.split("*"))
print()
12. Count (): - By using this function we can count particular data, it supports
two options.
I. Count from beginning
II. Count from specific index
Example: -
s1="My name is Lakshman"
print ("Old string is:", s1)
13. startswith (): - it checks the given string starts with particular data or not
Example: -
s1="my name is Lakshman Kumar"
print ("old string is:", s1)
print (s1. startswith ("my"))
print (s1. startswith ("ravi”) )
14.endswith (): - it checks the given string ends with particular data or not
Example: -
s1="my name is Lakshman Kumar and"
print ("old string is:", s1)
print (s1. endswith ("and"))
print (s1. endswith ("my"))
15.find (): - By using this function we can search particular data and it will
display location index number otherwise it will display -1.
Example: -
s1="my name is Lakshman and my friend name is arjun"
print ("old string is:", s1)
17. swapcase (): - By using this function we can convert upper case data into
lowercase and lower case to upper case
Example: -
s1="Lakshman Kumar"
print ("old string is:", s1)
print ("New string is:", s1. Swapcase ())
s1="LakshmanKumar"
19.Isalnum (): - By using this function to check the given variable contains
Alphabets And Number
Example: -
s1="Lakshman Kumar"
print("old string is:",s1)
print("New string is:",s1.isalnum())
print()
s1="Lakshman1216"
print("old string is:",s1)
print("New string is:",s1.isalnum())
s1=1234
print("old string is:",s1)
print("New string is:",s1.isdigit())
21.Islower (): - to check the given variable contains only lowercase data or
not
Example: -
s1="Lakshman Kumar"
print("old string is:",s1)
print("New string is:",s1.islower())
print()
s1="lucky"
print("old string is:",s1)
print("New string is:",s1.islower())
22.Isupper (): - to check the given variable contains only uppercase or not
Example: -
s1="Lakshman Kumar"
print("old string is:",s1)
print("New string is:",s1.isupper())
print()
s1="LUCKY"
print("old string is:",s1)
print("New string is:",s1.isupper())
Try This: -
22) Write a program to print 1 to 10 numbers and their sum?
23) Write a program to print A to Z alphabets in any case?
24) Enter a number then display its factorial value?
25) Enter a number then display arithmetical table?
26) To display first Fibonacci number means 1,1,2,3, 5, ……………55?
While with else: - The else part is executed whenever the while loop is closed
without any abnormal termination.
Ex: -
a=1
while a<=10:
Print (a)
a=a+1
else:
Print (“process done”)
Continue: - By using this key we can skip unnecessary looping value. We can use
this keyword in for loop and while loop.
Ex: -
For I in range (1, 11):
If (I == 4):
Continue
Print (I)
Example 2: -
for l in "Lakshman":
if l=='a' or l=='h':
continue
elif l=="s":
break
print("current letter:",l)
Multi loops: - Using python we can generate information in the form of rows
and columns. To implement this concept, we have to specify minimum of two for
loops or while loop in sub for loop we have to use end statement under print
function
Ex: -
For x in range (1, 4):
For y in range (1, 7):
Print (“INDIA”, end=” “)
Print ()
i=1
while(i<=3):
j=1
while(j<=6):
print(a,end=" ")
j=j+1
print()
i=i+1
Example 2: -
a=1
for i in range(1,4):
for j in range(1,i+1):
print(a,end=" ")
print()
Try This: -
27) Write necessary programs to print following series?
Example: -
S= “LAKSHMAN”
-8 -7 -6 -5 -4 -3 -2 -1
L A k S H M A N
0 1 2 3 4 5 6 7
Negative
Str = “Lakshman”
Print (str [-3]) # m
not to
List change
(immutabl
e)
not to
Tuple create
duplicate
By us this
sets we losed
Indexing
It does all
Dictionaries but i need
keys for
every value
l1=[10,20,30]
l2=[10,20,30]
print("list1 is:",l1)
print("list2 is:",l2)
print(id(l1))
print(id(l2))
l1=[10,20,30]
l2=l1
print("list1 is:",l1)
print("list2 is:",l2)
print(l1 is l2)
print(l1==l2)
n=[10,20,30,40]
print(“List Values Are:”,n)
print(len(n))
n=[1,2,2,2,3,3,3,4]
print(n.count(1))
print(n.count(2))
print(n.count(3))
print(n.count(4))
24. index (): - This function will display location number of first occurrence
of given value. If it is un available it will displays error message.
example: -
n=[1,2,2,7,8,2,3,4,5,3]
print(n.index(1))
print(n.index(2))
print(n.index(2,2))
print(n.index(2,3))
print(n.index(3))
print(n.index(3,7))
print(n.index(4))
25. append (): - With the help of this function we can append particular
data into a specified list object
Example: -
list=[“vinay”]
list.append("A")
print(list)
list.append(12.45)
print(list)
list.append(25)
print(list)
list.append(True)
print(list)
Try This: -
28) Write a program to append following series into list object by using for loop
[0, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100]?
26. insert (): - By using this option we can insert particular value into
specific index.
Example: -
n=[1,2,3,4,5]
print("Values Before insert")
print(n)
n.insert(1,1216)
print("Values After insert")
print(n)
27.extend (): - With the help of this function we can add or append N
number of values into existing list object
Example: -
n=['chicken','Motton','Fish']
n1=['Pappu','sambar','Rasam']
print("Values Before extend")
print("first Values")
print(n)
print("second Values")
print(n1)
n.extend(n1)
print("Values After extend")
print(n)
30. reverse (): - It will display given list values in the order of reverse
without any modifications
Example: -
n=[10,20,10,30,40]
print("Values Before Reverse")
print(n)
n.reverse()
print("Values After Reverse")
print(n)
31. Sort (): - it will sort the particular list values in the format of ascending
order the list values should be homogeneous only[similar data type
values only].
Example: -
n=[20,5,10,0,15]
print("Before Sort")
print(n)
n.sort()
print("After Sort")
print(n)
copy (): - by using this function we can create Xerox object means after creation
there is no data communication between original and duplicate object
Example: -
a=[1,2,3]
a1=a
print(a) 1 2 3
print(a1) 1 2 3
a[1]=200
print(a) 1 200 3
print(a1) 1 200 3
l1=[1,2,3,4,5]
l2=l1.copy()
print("L1 Data:")
print(l1)
print("L2 Data:")
print(l2)
l1[1]=100
print("Values After modification")
print("L1 Data:")
print(l1)
print("L2 Data:")
print(l2)
del (): -It is similar to remove function by using this function we can remove
values depends on indexing and slicing
Example: -
Ex1:
a=[10,20,30,40,50]
print(a)
del a[0]
print(a)
del a[2:4]
print(a)
ex2:
a=[10,20,30,40,50]
print(a)
del a[:1]
print(a)
ex3:
a=[10,20,30,40,50]
print(a)
del a[1:]
print(a)
ex4:
a=[10,20,30,40,50]
print(a)
del a[:]
print(a)
Clear (): - By using this function we can clear all elements of particular list object
means object is available but it is empty.
Example: -
fruits=["Apple","Orange","Mango","bananna"]
print(fruits)
fruits.clear()
print(fruits)
t1=(10,)
print(type(t1))
t8=tuple("Lakshman")
print(t8)
Unpacking: -
t=(10,20.5,"Lucky")
a,b,c=t
print(a)
print(b)
print(c)
print(type(a),type(b),type(c))
Nested Tuple: -
t=((10,20),(30,40,50))
print(t[0])
print(t[1])
print(t[1][1])
print(t[0][1])
print(t[1][2])
print()
print("UN PACKING NESTED TUPLE")
t=((10,20),(30,40,50))
a,b=t
print(a)
print(type(a))
print(b)
print(type(b))
Comparison operations: -
i. Printing memory address by using id () function
ii. is, is not used for memory comparison
iii. ==, != used for data comparison
iv. in, not in checks data is available or not
Example: -
t1=(10,20,30)
t2=(40,50,60)
t3=t1
t4=(10,20,30)
print("T1 Data is:",t1)
print("T2 Data is:",t2)
print("T3 Data is:",t3)
print("T4 Data is:",t4)
print("id's are:")
print(id(t1))
print(id(t2))
print(id(t3))
print(id(t4))
print("Memory comparison")
print(t1 is t2)
print(t1 is t3)
print(t1 is not t2)
print(t1 is not t3)
print("Data comparison")
print(t1 == t2)
print(t1 == t3)
print(t1 == t4)
print(t1 != t2)
print(t1 != t3)
print(t1 != t4)
print("checking data ")
print(10 in t1)
print(100 in t1)
print(10 not in t2)
print(100 not in t3)
t=(10,10,10,20,30,40)
print(t.count(10))
print(t.index(10))
print(t.index(10,1))
print(t.index(10,2))
print(len(t))
sorted (): - This function works only tuple by using this function we can sort the
values at the time of printing only means original data cannot be affected
Example: -
t=(10,4,5,100)
print("Before sort:",t)
print(sorted(t))
print("After sorting:",t)
Operation’s on sets: -
set={1,2,5,4,3,8,7,6,"Arjun","lucky",1,2,3}
print(set)
print(type(set))
Example: -
s={}
print(s)
print(type(s))
x=set()
print(type(x))
Example: -
s={1,2,3}
print(s)
s.add(4)
print(s)
33. update (): - With the help of this function we can append other data type
values
Example: -
s={1,2,3}
print(s)
s.update([4,5],{1,6,8},(11,22))
print(s)
34.copy (): - by using this function we can create Xerox object means after
creation there is no data communication between original and duplicate
object
Example: -
s={1,2,3}
print(s)
a=s.copy()
print("copy set")
print(a)
s.add(200)
print(s)
print(a)
Clear (): - By using this function we can clear all elements of particular set object
means ,the object is available but it is empty.
Example: -
s={1,2,3,4,5}
print(s)
s.clear()
print(s)
s3={"vinay","kumar"}
s4=s3
print(id(s1))
print(id(s2))
print(id(s3))
print(id(s4))
print(s1 is s2)
print(s1 is not s2)
print(s1 == s2)
print(s1 != s2)
print(s1 in s2)
print(s1 not in s2)
Unpacking of set: -
s1={10,"Lucky",(10,20)}
a,b,c=s1
print("s1 data is:")
print(s1)
print(id(s1))
print("data from A:")
print(a)
print(id(a))
print("data from B:")
print(b)
print(id(b))
print("data from C:")
print(c)
print(id(c))
print(type(a),type(b),type(c))
print(l2)
print(l3)
eng=set(l1+l2+l3)
print(eng)
Example: -
x={10,20,30,40}
y={30,40,50,60}
print(x.intersection(y))
print(x&y)
III. Difference (): It will display all elements of first object which
is not available in second object. By using “- “ also we can
perform this concept
Example: -
x={10,20,30,40}
y={30,40,50,60}
print(x.difference(y))
print(y.difference(x))
print(x-y)
print(y-x)
Example: -
a=set("vinay_techno")
print(a)
b=set("techosoft")
print(b)
print(b-a)
print(a|b)
print(a&b)
print(a^b)
print()
b1={"Orange","Apple","Pear","banana"}
b2={"Pear","Orange","banana"}
print(b1-b2)
print(b1|b2)
print(b1&b2)
print(b1^b2)
print(phonebook1["vinay"])
print()
stu={1:'sai',2:'Harsha',3:'Lakshman'}
print("student Data")
print(stu)
print(stu[1])
stu[1]="Lucky"
print(stu)
print()
stu={1:'sai',2:'Harsha',3:'Lakshman'}
print("stu Data")
print(stu)
print(d1.keys())
print(d1.values())
Data conversions:
d1={1:'Vinay',2:'Mani',4:'tarun',3:'kumar',5:’Sadhiya’}
print("lists")
print(list(d1.keys()))
print(list(d1.values()))
print("tuple")
print(tuple(d1.keys()))
print(tuple(d1.values()))
print("sets")
print(set(d1.keys()))
print(set(d1.values()))
Data Sorting:
d1={1:'Vinay',2:'Mani',4:'tarun',3:'kumar'}
print("sorted")
print(sorted(d1.keys()))
print(sorted(d1.values()))
print(id(d1))
print(id(d2))
print(id(d3))
print(id(d4))
print()
print(d1 is d2)
print(d1 is d3)
print(d1 is not d2)
print(d1 is not d3)
print()
print(d1 == d2)
print(d1 == d3)
print(d1 != d2)
print(d1 != d3)
print()
print(1 in d2)
print('ratan' not in d2)
41. items (): - By using this function the dict information will display in the
format of list and tuple concept
example: -
d1={1:'Lakshman',2:'Kumar',3:'Lucky'}
print(d1.items())
46.Update: - It is similar to extend key word, means we can append all data
from second dict object into first dict object.
Example 1: -
print("UPDATING")
mydict={"mani":28,"tarun":25,"durga":30}
print(mydict)
mydict["durga"]=35
print(mydict)
Example 2: -
d1={1:"vinay",2:"Kumar"}
d2={3:"Mani",4:"Turan"}
print(d1)
print(d2)
d1.update(d2)
print(d1)
Copy (): - it is a common copy () of all data types the advantage of this function is
we can create xerox object means there is no internal proportion between two
objects
Example: -
d1={1:"vinay",2:"Kumar",3:"Mani",4:"Turan"}
print("data fron d1 to d2")
print(d1)
d2=d1
print(d2)
print("After updating")
d1[4]="Lucky"
print(d1)
print(d2)
d3={1:"vinay",2:"Kumar",3:"Mani",4:"Turan"}
print("data fron d3 to d4")
print(d3)
d4=d3.copy()
print(d4)
print("After updating by using copy")
d3[4]="Lucky"
print(d3)
print(d4)
47. zip (): - By using this function we can convert given two list components
into zipped format. To implement zip operations, we need two list
components and the list object having similar length values
48. dict (): - This function converts zipped data into dict format
TYPES OF VARIABLES
In every programming language the memory variables are mainly
classified into two major categories
They are like
1) Local variables
2) Global variables
Local variables: - These variables are also called private variables because it is
restricted within the functions only means we are unable to access outside of the
function
Example: -
def show ():
name=’Lucky’
print (“sname is:”, name)
show ()
Example 2: -
def show():
name="vinay"
print("Stuname is:",name)
show()
print("Stuname is:",name)
Example: - -
name="Lucky"
def show ():
print ("Stu name is:", name)
show ()
print ("Stu name is:", name)
Example 2: -
cname="python"
def show():
name="Lakshman"
print("Stuname is:",name)
print("course name is:",cname)
def show1():
name="Kumar"
print("Stuname is:",name)
print("course name is:",cname)
show()
show1()
global: -
basically, the life time of local variables within the function means we are
unable to access outside of the function
to rectify this problem, we can declare a variable as global under function
level
example: -
def show ():
global name
name="Kumar"
print ("Stu name with in the function:", name)
show ()
print ("Stu name outside the function:", name)
Example 2: -
name="lakshman"
def show():
global name
name="Kumar"
print("Stu name with in the function:",name)
show()
print("Stu name out side the function:",name)
show1()
print("Stu name with in the function :",name)
show()
non local: - with the help of this keyword we can override function level global
variable. We have to specify this key word within the sub function only
Example: -
def show():
name="Kumar"
print("Stu name with in the function:",name)
def show1():
nonlocal name
name="Lakshman"
print("Stu name with in the function 1:",name)
show1()
print("Stu name with in the function :",name)
show()
f1(a [:])
print ("outside function a=", a)
Call by reference: -
To ratify call by value problem we are implementing this concept
To perform this concept, we have to pass only object name(variable name).
Example: -
def f1(x):
print ("The values in the given list:", x)
print ("Total no of elements is:", len(x))
x [1] =2000
x [2] =3000
x.append (4000)
print(x)
a= [10,20,30]
f1(a)
print ("outside function a=", a)
Recursive function: -
It is also similar concept of other languages, in the concept The
function calls same function it self
Example: -
def sum(n):
if n==0:
res=0
else:
res=n+ sum (n-1)
return res
i=10
print ("sum of 1 to {} numbers is {}.". format (i, sum (i)))