Python Class 12 Notes by Anand SIr
Python Class 12 Notes by Anand SIr
CHAPTER – 1
REVISION TOUR - 1
Programming Language
There are a lots of languages using which we can communicate with
computer system and all those languages are called programming
language.
For Example: C, C++, Java, Python etc.
Keywords are reserved words that are used for some specific purpose.
These words have some special meaning and it can be used only for the
same purpose for which it has been created. There are a lots of keywords:
and. or , if, else, not, break, def, True, False, while, for, is, in, None, pass,
elif etc
2. Variable names can only contain alphabets, numbers and underscore sign.
3. Variable name can only begin with alphabet or an underscore. It can’t start with a
number or any special symbol.
For Example:
For Example:
‘ “ , () [] {} @ : etc
Variables are used to store values. But the best thing in Python is that, unlike
other programming languages, Python has no command for declaring a
variable. A variable is created as soon as we assign a value to it.
myvar = "Himaksh"
my_var = "Himaksh"
_my_var = "Himaksh"
myVar = "Himaksh"
MYVAR = "Himaksh"
myvar2 = "Himaksh"
#Illegal variable names:
2myvar = "Himaksh"
my-var = "Himaksh"
my var = "Himaksh“
my@var=“Himaksh”
Example Datatype
a=“Python Programming” str
a=20 int
a=20.5 float
a=1i complex
a=[“apple”,”boy”,”cat”] list
a=(“apple”,”banana”,”cat”) tuple
a=range(5) range
a={“name”:”amit”,”age”:32} dict
Notes By: Anand Sir | YouTube Channel: CODEITUP
PYTHON DATATYPE
Example Datatype
a={“apple”,”boy”,”cat”} set
a=True boolean
For Example:
x=5
print(type(x))
# Output: int
Conversion of one data type into another type is called type casting.
Casting in python is done using constructor functions:
Conversion of one data type into another type is called type casting.
Casting in python is done using constructor functions:
Conversion of one data type into another type is called type casting.
Casting in python is done using constructor functions:
After writing this program save the program and run it. All the statement
inside it will be executed one by one.
Like we did earlier, after writing this program save the program and run it.
All the statement inside it will be executed one by one and area of
rectangle will be calculated accordingly.
n=int(input(“Enter Number:”))
if n>=0 and n<10:
print(“Single Digit Number:”)
elif n>=10 and n<100:
print(“Double Digit Number:”)
elif n>=100 and n<1000:
print(“Three Digit Number:”)
else:
print(“Four or more digit number:”)
Notes By: Anand Sir | YouTube Channel: CODEITUP
PYTHON
Loops are used to Execute a single statement or a block of statement
n times till the condition is true.
In Python, looping may be done by two ways:
1. while loop
2. for loop
initialization
while condition:
statement(s)
....................
increment/decrement
sum=0 sum=0
Solution: Solution:
while(i<=n): print(i)
print(i)
i=i+2
Notes By: Anand Sir | YouTube Channel: CODEITUP
PYTHON
Ques 8: Write a program to print only Ques 8: Write a program to print only
even numbers between 1 to n. even numbers between 1 to n.
(Second Method Using While Loop) (Second Method Using For Loop)
Solution: Solution:
n=int(input(“Enter Number upto which
n=int(input(“Enter Number upto which
you want to print”))
you want to print”))
i=1
for i in range(1,n+1):
while(i<=n):
if i%2==0:
if i%2==0:
print(i)
print(i)
i=i+1
Notes By: Anand Sir | YouTube Channel: CODEITUP
PYTHON
Ques 9: Write a program to find sum of Ques 9: Write a program to find sum
even numbers from 1 to n. (First Way of even numbers from 1 to n. (First
Using While Loop)
Way Using For Loop)
n=int(input(“Enter Number upto which
you want to add even numbers”)) n=int(input(“Enter Number upto which
you want to add even numbers”))
i=2
sum=0 sum=0
sum=sum+i if (i%2==0):
i=i+1 sum=sum+i
print(“Sum of Even numbers=“,sum)
print(“Sum of Even numbers=“,sum)
Notes By: Anand Sir | YouTube Channel: CODEITUP
PYTHON
Ques 10: Write a program to find sum of Ques 10: Write a program to find sum of
first n even numbers. (Using While Loop) first n even numbers. (Using For Loop)
n=int(input(“How many even n=int(input(“How many even
numbers you want to add :”)) numbers you want to add :”))
i=1 sum=0
sum=0 i=2
count=1 for count in range(1,n+1):
while (count <=n): sum=sum+ i
if (i%2==0): i=i+2
sum=sum+ i print(“Sum of first”,n,”Even
numbers=“,sum)
count=count+1
i=i+1
print(“Sum of first”,n,”Even
numbers=“,sum)
Notes By: Anand Sir | YouTube Channel: CODEITUP
Program List:
PYTHON
Level – 2 Question
Ques 1: Write a program to find sum of digits of a given number.
Quest 2: Write a program to find sum of square of digits of a given number.
Quest 3: Write a program to find sum of cube of digits of a given number.
Quest 4: Write a program to check whether a given number is Armstrong or not.
Ques 5: Write a program to find product of digits of a given number.
Ques 6: Write a program to find sum of even digits and product of odd digits of a given
number.
Ques 7: Write a program to reverse a given number.
Ques 8: Write a program to check whether a given number is palindrome number or not.
Ques: 9: Write a program to print all the factors of a given number.
Ques 10: Write a program to count total factors of a given number.
Quest 9: Write a program to check whether a given number is prime or not.
Ques 10: Write a program to print factorial of a given number.
Ques 11: Write a program to print fibonacci series up to a given number.
Ques 12: Write a program to find x raised to the power y.
Notes By: Anand Sir | YouTube Channel: CODEITUP
PYTHON
Ques 1: Write a program to find sum of digits of a given number.
x=int(input("Enter Number:"))
y=int(input("Enter Number:"))
pro=1
while y>0:
pro=pro*x
y=y-1
print("Value=",pro)
a. * b 1 c 1
** 12 22
*** 123 333
**** 1234 4444
***** 12345 55555
b. * 1 1
*** 222 123
***** 33333 12345
******* 4444444 1234567
********* 555555555 123456789
******* 4444444 1234567
***** 33333 12345
*** 222 123
* 1 1
for i in range(5): *
for j in range(i+1): **
print("*",end="") ***
print() ****
*****
1
for i in range(5): 22
for j in range(i+1): 333
print(i+1,end="") 4444
print() 55555
1
for i in range(5):
12
for j in range(i+1): 123
print(j+1,end="") 1234
print() 12345
Notes By: Anand Sir | YouTube Channel: CODEITUP
PYTHON
Program List:
Level – 3 Question
Ques 1: Draw the following shapes.
for i in range(5):
for b in range(5-i):
print(" ",end="") *
for j in range(i+1): **
print("*",end="") ***
print() ****
*****
for i in range(5):
for b in range(5-i): 1
print(" ",end="") 22
for j in range(i+1): 333
print(i+1,end="") 4444
print()
55555
for i in range(5):
for b in range(5-i): 1
print(" ",end="")
for j in range(i+1):
12
print(j+1,end="") 123
print() 1234
12345
Notes By: Anand Sir | YouTube Channel: CODEITUP
PYTHON
Program List:
Level – 3 Question
Ques 1: Draw the following shapes.
0 1 2 3 4 5
str P Y T H O N
-6 -5 -4 -3 -2 -1
Backward Indexing
For Example:
name=“Shyam”
name[0]=“A”
// results to an error:
TypeError: ‘name' object does not support item assignment
Example 1:
name=“Shyam”
print(name) output: Shyam
Example 2:
name=“Shyam”
for i in name:
print(i) OR print(i, end=“”)
2. Replication Operator *
The * operator requires two types of operands – a string and a number. It replicates the
given string, to given number of times.
3*”hello”
OUTPUT: hellohellohello
1. a=“Hello World”
print(a[4:-2])
=> will print “o Wor”
2. a=“Hello World”
print(a[6:],a[:6])
=> will print “World Hello”
Notes By: Anand Sir | YouTube Channel: CODEITUP
STRING
String Slicing
0 1 2 3 4 5 6 7 8 9 10
H E L L O W O R L d
>>>str=“HELLO WORLD”
>>>str[6:10] output=_______________________
>>>str[6:] output=_______________________
>>>str[3:-2] output=_______________________
>>>str[:5] output=_______________________
Notes By: Anand Sir | YouTube Channel: CODEITUP
STRING
String Slicing
0 1 2 3 4 5 6 7 8 9 10
H E L L O W O R L d
3. find() => This function returns the lowest index in the string where the
substring is found. If the string is found, it returns the index where it
is found and if not found it returns -1.For example:
a=“RAM IS GOING TO MARKET.”
b=“TO”
a.find(b,0,(len(a)-1)
=>output: 13
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
R A M I S G O I N G T O M A R K E T
4. isalnum()
This returns true if the characters in the string are alphanumeric (alphabets or
numbers) and there is at least one character otherwise it returns False. For Example:
>>>a=“ram123” >>>b=“hello” >>>c=“123456” >>>d=“”
>>>a.isalnum() >>>b.isalnum() >>>c.isalnum() >>>d.isalnum()
=> true =>true =>true =>false
6. isdigit()
This returns true if all the characters in the string are digits and there is at
least one digit otherwise it returns False.
>>>a=“ram123” >>>b=“hello” >>>c=“123456” >>>d=“”
>>>a.isdigit() >>>b.isdigit() >>>c.isdigit() >>>d.isdigit()
=> false =>false =>true =>false
5. isspace()
This returns true when there are only white spaces in the string and there
is at least one character. Otherwise it returns False.
>>>a=“ “ >>>a=“”
>>>a.isspace() >>a.isspace()
=>True =>false
First Way Using String Slicing Concpt Second way using programming logic
a=input("Enter String:") a=input("Enter String:")
print(a[-1::-1]) for i in range(len(a)-1,-1,-1):
print(a[i])
a=[“ram”,10,”shyam”,12.5]
0 1 2 3 Forward Indexing
ram 10 shyam 12.5
-4 -3 -2 -1 Backward Indexing
0 1 2 3 Forward Indexing
ram 10 shyam 12.5
-4 -3 -2 -1 Backward Indexing
0 1 2 3 Forward Indexing
ram 10 shyam 12.5
-4 -3 -2 -1 Backward Indexing
a[0:] = [ram,10,shyam,12.5]
a[:]=[ram,10,shyam,12.5]
a[1:3]=[10,shyam]
a[:3]=[ram,10,shyam]
Second way
a=[“ram”,10,”shyam”,12.5]
for i in range(len(a)):
print(a[i])
a=[“ram”,10,”shyam”,12.5]
print(a[1])
a[1]=“Ramesh”
print(a[1])
a=[“ram”,10,”shyam”,12.5]
print(a)
del a[1]
print(a)
Example Program:
a=[“ram”,10,”shyam”,12.5]
b=len(a)
print(“Length of the list=“,b)
============================
OR
============================
a=[“ram”,10,”shyam”,12.5]
print(“Length of the list=“,len(a))
Notes By: Anand Sir | YouTube Channel: CODEITUP
LIST METHODS
2. max(list) => This method is used to find max value
present in the list.
Example Program:
a=[10,20,30,40,50]
b=max(a)
print(“Max value in the list=“,b)
============================
OR
============================
a=[10,20,30,40,50]
print(“Max value in the list=“,max(a))
Notes By: Anand Sir | YouTube Channel: CODEITUP
LIST METHODS
3. min(list) => This method is used to find min value present in the list.
Example Program:
a=[10,20,30,40,50]
b=min(a)
print(“Min value in the list=“,b)
============================
OR
============================
a=[10,20,30,40,50]
print(“Min value in the list=“,min(a))
Notes By: Anand Sir | YouTube Channel: CODEITUP
LIST METHODS
Case 1: What if we have a list of string and integer values and we
want to use max function. In this case this will produce an error
message stating that string and integer value comparison is not
possible.
Syntax: cmp(list1,list2)
Returns: return 1 if list1 is greater than list2
return 0 if both the lists are equal
returns -1 if list2 is greater than list1
list1=[2,4,6,8]
list2=[2,4,6,9]
list3=[2,4,6,9,11]
list4=[2,4,6,8]
print(“Comparing list1 and list2:”)
print(cmp(list1,list2))
print(“Comparing list2 and list3:”)
print(cmp(list2,list3))
print(“Comparing list1 and list4:”)
print(cmp(list1,list2))
list1=[2,4,6,8]
list2=[2,4,6,’a’]
list3=[‘a’,’b’,’c’]
list4=[‘a’,’c’,’b’]
print(“Comparing list2 and list1:”)
print(cmp(list2,list1)) => output: 1
print(“Comparing list2 and list3:”)
print(cmp(list2,list3)) => output: -1
print(“Comparing list3 and list4:”)
print(cmp(list3,list4)) => output: -1
Example:
a=[“ram”,”shyam”,”ram”,”gita”]
x=a.count(“ram”)
print(“Frequency=“,x)
output: Frequency=2
Note: You have to specific that what type of data you are
going to search for counting frequency. The type of input in
the list determines the type of value whose frequency you
want to get.
Notes By: Anand Sir | YouTube Channel: CODEITUP
LIST METHODS
7. index() =>This method is used to find the index of the object/element.
This function returns the first index of the object/index if it is found
otherwise it returns an exceptions showing that the element is not found.
Syntax: list.index(obj)
Example:
a=[“ram”,”shyam”,”ram”,”gita”]
x=a.index(“ram”)
print(“Index of ram=“,x)
output: index=0
c=a.reverse()
print(c)
c=a.sort()
print(c)
a=[]
size=int(input("How Many Elements You Want to Enter?"))
for i in range(size):
val=int(input("Enter Number:"))
a.append(val)
even=0
odd=0
for i in range(size):
if(a[i]%2==0):
even=even+1
else:
odd=odd+1
print("Total Even=", even, "Total Odd=",odd)
Notes By: Anand Sir | YouTube Channel: CODEITUP
PROGRAMMING WITH LIST USING LIST METHODS
3. Program to find sum of even numbers and product of odd number in List.
a=[]
size=int(input("How Many Elements You Want to Enter?"))
for i in range(size):
val=int(input("Enter Number:"))
a.append(val)
sum=0
pro=1
for i in range(size):
if(a[i]%2==0):
sum=sum+a[i]
else:
pro=pro*a[i]
print("Sum of Even Numbers=",sum,"\nProduct of Odd
Numbers=",pro)
Notes By: Anand Sir | YouTube Channel: CODEITUP
PROGRAMMING WITH LIST USING LIST METHODS
4. Program to search a number in the List.
a=[]
size=int(input("Enter Size of the List:"))
for i in range(size):
val=int(input("Enter Number:"))
a.append(val)
key=int(input("Enter Number to Search:"))
flag=0
for i in range(size):
if(a[i]==key):
flag=1
pos=i+1
break
if(flag==1):
print("Element found at:",pos,"position.")
else:
print("Element not found.")
Notes By: Anand Sir | YouTube Channel: CODEITUP
PROGRAMMING WITH LIST USING LIST METHODS
5. Program to count frequency of a given number.
a=[]
size=int(input("Enter Size of the List:"))
for i in range(size):
val=int(input("Enter Number:"))
a.append(val)
key=int(input("Enter Number to Find Frequency:"))
count=0
for i in range(size):
if(a[i]==key):
count=count+1
print("Frequency=",count)
a=[]
size=int(input("Enter Size of the List:"))
for i in range(size):
val=int(input("Enter Number:"))
a.append(val)
max=a[0]
for i in range(size):
if(a[i]>max):
max=a[i]
print(“Max Number=",max)
a=[]
size=int(input("Enter Size of the List:"))
for i in range(size):
val=int(input("Enter Number:"))
a.append(val)
min=a[0]
for i in range(size):
if(a[i]<min):
min=a[i]
print("Min Number=",min)
a=[]
size=int(input("Enter Size of the List:"))
for i in range(size):
val=int(input("Enter Number:"))
a.append(val)
i=0
j=size-1
while(i<j):
t=a[i]
a[i]=a[j]
a[j]=t
i=i+1
j=j-1
print("List after reverse=")
for i in range(size):
print(a[i])
Notes By: Anand Sir | YouTube Channel: CODEITUP
PROGRAMMING WITH LIST USING LIST METHODS
9. Program to find max/min number 9. Program to find max/min number
of the List. (Using Built in Function) of the List. (Without using Built-in
Function)
a=[]
size=int(input("Enter Size of the List:")) a=[]
for i in range(size): size=int(input("Enter Size of the List:"))
val=int(input("Enter Number:")) for i in range(size):
a.append(val) val=int(input("Enter Number:"))
maxval=max(a) a.append(val)
minval=min(a) max=min=a[0]
print("Max Number=",maxval) for i in range(size):
print("Min Number=",minval) if(a[i]>max):
max=a[i]
if(a[i]<min):
min=a[i]
Notes By: Anand Sir | YouTube Channel: CODEITUP
print(“Max=",max,”Min=“,min)
PROGRAMMING WITH LIST USING LIST METHODS
10: Program to Find Min and Second 10: Program to Find Min and Second Min Number in
Min Number in the list. (Using Built-in the list. (Without Using Built-in Function)
a=[]
Function)
size=int(input("Enter Size of the List:"))
a=[] for i in range(size):
size=int(input("Enter Size of the List:")) val=int(input("Enter Number:"))
a.append(val)
for i in range(size): min=a[0]
val=int(input("Enter Number:")) for i in range(size):
if(a[i]<min):
a.append(val) min=a[i]
print("Min Number=",min)
minval=min(a)
a.remove(min)
print("Min value in the list is:",minval) min=a[0]
for i in range(size-1):
a.remove(minval) if(a[i]<min):
smin=min(a) min=a[i]
print(“Second Min Number=",min)
print("Second Min=",smin)
Notes By: Anand Sir | YouTube Channel: CODEITUP
PROGRAMMING WITH LIST USING LIST METHODS
11: Program to Find Max and Second 10: Program to Find Max and Second Max Number
Maxx Number in the list. (Using Built-in in the list. (Without Using Built-in Function)
a=[]
Function)
size=int(input("Enter Size of the List:"))
a=[] for i in range(size):
size=int(input("Enter Size of the List:")) val=int(input("Enter Number:"))
a.append(val)
for i in range(size): max=a[0]
val=int(input("Enter Number:")) for i in range(size):
if(a[i]>max):
a.append(val) max=a[i]
print("Max Number=",max)
maxval=max(a)
a.remove(max)
print("Max value in the list is:",maxval) max=a[0]
for i in range(size):
a.remove(maxval) if(a[i]>max):
smax=max(a) max=a[i]
print(“Second Max Number=",max)
print("Second Max=",smaxx)
Notes By: Anand Sir | YouTube Channel: CODEITUP
PROGRAMMING WITH LIST USING LIST METHODS
12. Program to insert a number at given index in an List.
a=[]
size=int(input("Enter Size of the list:"))
for i in range(size):
val=int(input("Enter Size of the list:"))
a.append(val)
a.append(None)
print("Original List:",a)
key=int(input("Enter Value to Insert:"))
pos=int(input("Enter position to insert:"))
for i in range(size-1,pos-2,-1):
a[i+1]=a[i]
a[pos-1]=key
print("List after insertion:",a)
Notes By: Anand Sir | YouTube Channel: CODEITUP
PROGRAMMING WITH LIST USING LIST METHODS
13. Program to remove a given number from
13. Program to remove a given the List (Without Using Built-in Function).
number from the List (Using Built-in (First Way)
Function). a=[]
size=int(input("Enter Size of the List:"))
for i in range(size):
a=[] val=int(input("Enter Number:"))
size=int(input("Enter Size of the List:")) a.append(val)
value=int(input("Enter Value to Delete:"))
for i in range(size): flag=0
val=int(input("Enter Number:")) for i in range(size):
a.append(val) if a[i]==value:
flag=1
value=int(input("Enter Value to for j in range(size):
Delete:")) a[j-1]=a[j]
a.remove(value) a.pop()
size=size-1
print(a) if flag==0:
print(“Element not found”)
else:
print(“Element After Deletion=“,a)
Notes By: Anand Sir | YouTube Channel: CODEITUP
PROGRAMMING WITH LIST USING LIST METHODS
13. Program to delete a given element from the list. (Second Way)
a=[]
size=int(input("Enter Size of the List:"))
for i in range(size):
val=int(input("Enter Element:"))
a.append(val)
print("The original List is:",a)
key=int(input("Enter Number to Delete:"))
flag=0
for i in range(size):
if a[i]==key:
pos=i
flag=1
break
if flag==0:
print("Element Not Found")
else:
for i in range(pos,size-1):
a[i]=a[i+1]
a.pop()
print("List after deletion:",a)
Notes By: Anand Sir | YouTube Channel: CODEITUP
PROGRAMMING WITH LIST USING LIST METHODS
14. Program to shift each element one step right.
a=[]
size=int(input("Enter Size of the List:"))
for i in range(size):
val=int(input("Enter Size of the List:"))
a.append(val)
print("Original List is:",a)
last_element=a[size-1]
for i in range(size-2,-1,-1):
a[i+1]=a[i]
a[0]=last_element
print("Modified List is:",a)
a=[]
size=int(input("Enter Size of the List:"))
for i in range(size):
val=int(input("Enter Size of the List:"))
a.append(val)
print("Original List is:",a)
first_element=a[0]
for i in range(1,size):
a[i-1]=a[i]
a[size-1]=first_element
print("Modified List is:",a)
a=[]
size=int(input("Enter Size of the List:"))
n=int(input("How Many Times You Want to Left Shift?"))
for i in range(size):
val=int(input("Enter Element:"))
a.append(val)
print("Original List is:",a)
for i in range(n):
last_element=a[size-1]
for i in range(size-2,-1,-1):
a[i+1]=a[i]
a[0]=last_element
print("Modified List is:",a)
Notes By: Anand Sir | YouTube Channel: CODEITUP
PROGRAMMING WITH LIST USING LIST METHODS
17. Program to shift each element left by given number of step right.
a=[]
size=int(input("Enter Size of the List:"))
n=int(input("How Many Times You Want to Right Shift?"))
for i in range(size):
val=int(input("Enter Element:"))
a.append(val)
print("Original List is:",a)
for i in range(n):
first_element=a[0]
for i in range(1,size):
a[i-1]=a[i]
a[size-1]=first_element
print("Modified List is:",a)
Notes By: Anand Sir | YouTube Channel: CODEITUP
PYTHON
Tuples in Python
Notes By: Anand Sir | YouTube Channel: CODEITUP
TUPLE
A tuple is a collection which is ordered and unchangeable. In Python tuples
are written with round brackets. Tuples in Python are very similar to list which
contains different types of elements with the following major differences.
It is declared as
tuple1=(1,2,3,“ram”,”shyam”)
The list is created using square brackets whereas tuples are created using
round brackets.
list1=[1,2,3,”ram”,”shyam”]
tuple1=(1,2,3,“ram”,”shyam”)
list1=[1,2,3,”ram”,”shyam”]
list1[2]=10
print(a)
Output: 1,2,10,ram,shyam
tuple1=(1,2,3,“ram”,”shyam”)
tuple1[2]=10
print(a)
Output: Error
Notes By: Anand Sir | YouTube Channel: CODEITUP
TUPLE
Difference 3
Program Implementation
import sys
list1=[1,2,"ram","shyam",True,"ravi"]
tuple1=(1,2,"ram","shyam",True,"ravi")
print("Size of List=",sys.getsizeof(list1))
print("Size of Tuple=",sys.getsizeof(tuple1))
Program Implementation
import timeit
listtime=timeit.timeit(stmt="[1,2,3,4,5,6,7,8,9]",
number=1000000)
tupletime=timeit.timeit(stmt="(1,2,3,4,5,6,7,8,9)",
number=1000000)
print("List takes time:",listtime)
print("Tuple takes time:",tupletime)
tuple1=(1,2,3,4) tuple1=(1,2,3,4)
for t in tuple1: for i in range(len(tuple1)):
print(t) print(tuple1[i])
Joining Tuple
tuple1=(1,2,3,4,5)
tuple2=(6,7,8)
tuple3=tuple1+tuple2
print(tuple3)
tuple1=(1,2,3)
tuple2=tuple1*3
print(tuple2)
Output: (1,2,3,1,2,3,1,2,3)
This method returns length of the tuple, i.e. the total counting of elements in
the tuple.
Syntax : len(<tuple>)
Example: >>>employee=(‘Ram’,’Shyam’,101,1.56)
>>>len(employee)
4
Syntax : max(<tuple>)
Example: >>>a=(10,20,30,45,20,15)
>>>max(a)
45
Syntax : min(<tuple>)
Example: >>>a=(10,20,30,45,20,15)
>>>min(a)
10
Syntax : tuple(<sequence>)
Example:
1. Creating empty tuple 2. Creating tuple from a list
>>>tuple() >>> t=tuple([1,2,3])
>>>t
(1,2,3)
3. Creating tuple from string 4. Creating tuple from key of dictionary
>>>tuple1=tuple(“xyz”) >>>tuple1=tuple({1:”m”,2:”n”})
>>>tuple1 >>>tuple1
(‘a’,’b’,’c’) (1,2)
Example
• You need to Convert the tuple into a list to be able to change it:
x = ("apple", "banana", "cherry")
y = list(x)
y[1] = "kiwi"
x = tuple(y)
print(x)
Example:
tuple1=(“ram”,”shyam”,”sita”,”gita”)
if “ram” in tuple1:
print(“Yes the Element is present in the Tuple.”)
else:
print(“No the Element is not present in the Tuple.”)
• Once a tuple is created, you cannot add items to it. Tuples are unchangeable.
• You cannot add items to a tuple:
tuple1 = ("apple", "banana", "cherry")
tuple1[3] = "orange" # This will raise an error
print(tuple1)
• You can access the items of a dictionary by referring to its key name, inside
square brackets.
OR
brand Suzuki
model Dzire
year 2020
For Example:
dict1 = {‘brand’:’Suzuki’,’model’:’Dzire’,’year’: 2020}
dict1[‘year’] = 2018
print(dict1)
Output:
‘brand:’Suzuki’, ‘model’:’Dzire’, ‘year’:’2018’
Output:
{‘brand’:’Maruti’, ‘moel’:’Dzire’, ‘year’:2020} {‘brand’:’Maruti’, ‘model’:’Dzire’,
‘year’:2020,‘color’:’White’}
Program implementation
Output:
Length of the Dictionary=3
Example:
Output:
{‘brand’:’Maruti’, ‘model’:’Dzire’, ‘year’:2020}
Error
Notes By: Anand Sir | YouTube Channel: CODEITUP
DICTIONARY
4. pop()
This method removes the element with specified key name.
Output:
{‘brand’:’Maruti’, ‘model’:’Dzire’, ‘year’:2020}
{‘brand’:’Maruti’,‘year’:2020}
Output:
{‘brand’:’Maruti’, ‘model’:’Dzire’, ‘year’:2020}
{‘brand’:’Maruti‘,model’:’Dzire’}
Output:
{‘brand’:’Maruti’, ‘model’:’Dzire’, ‘year’:2020}
{‘brand’:’Maruti‘,model’:’Dzire’}
Example:
dict1 = {’brand’: “Maruti",’model’: “Dzire",’year’: 2020}
print(dict1)
del dict1
print(dict1)
Output:
{‘brand’:’Maruti’, ‘model’:’Dzire’, ‘year’:2020}
Error
brand Suzuki
model Dzire
year 2020
brand Suzuki
model Dzire
year 2020
The fromkeys() method returns a dictionary with the specified keys and the specified value.
• The setdefault() method returns the value of the item with the specified key.
• If the key does not exist, it inserts the key, with the specified value.
For Example:
Output: Since “brand” key is already present so it will return the value of this key.
Suzuki
Now since the “place” key is not present in the dict1, it will insert this key with value and
then the respective value i.e. “New Delhi” will assigned to x and so “New Delhi” will get
printed.
Important points:
1. For defining a function we use “def” keyword followed by the function
name. The syntax is :
def function_name(argument_list):
function body
2. A function body is executed only then, when it is called. In simple terms
we can say that a function body is not executed until it is called (invoked).
A function is invoked by its name.
For Example:
1. If we want to write a program to add two number, then in this case the input
from the user will be that two numbers and hence these two numbers will be
called as argument.
2. If we have to check whether a given number is odd or even in such case the
number whose input we will take for whether the number is odd or even, is the
argument.
3. If we have to check whether a number is prime/Armstrong whatever, then the
number which has to be checked will be the argument.
Notes By: Anand Sir | YouTube Channel: CODEITUP
FUNCTIONS IN PYTHON
Argument
4. If we have to perform list related operation, then that list will be the argument for
that particular question.
Now, till here we know that argument is nothing but the values upon which we
have to perform functionality. To understand we can say that the value whose
input is taken from the user is called argument. Let’s understand the concept using
a program.
Explanation
def add(a,b):
Here a and b is the argument and obviously the value
c=a+b
upon which we have to work. Since we have to add
print(“Addition=“,c) two numbers then in this case a & b will be the value
#__main__ which is the input and obviously the argument. Now
since we have already a & b then just we have to
add(5,6) add them and print the output.
In the main section here (the point from where the
Output: execution of the program starts), we have passed
anonymous values i.e. 5 and 6 and first value 5 will be
Addition=11 copied to a and the value 6 will be copied to b. Now
the addition will be stored to c and addition will be
printed.
Notes By: Anand Sir | YouTube Channel: CODEITUP
FUNCTIONS IN PYTHON
Ques: Add two numbers using with argument no return option.
Explanation
def add(a,b):
Here a and b is the argument and obviously
c=a+b the value upon which we have to work. Since
we have to add two numbers then in this
print(“Addition=“,c) case a & b will be the value which is the input
and obviously the argument. Now since we
#__main__ have already a & b then just we have to add
a=int(input(“Enter First Number:”)) them and print the output.
In the main section here (the point from
b=int(input(“Enter Second Number:”)) where the execution of the program starts),
add(a,b) we have taken the input of a & b which has
been passed as argument to the function and
there as well the same named variable a & b
will store the value passed from main function
and will store the sum in “c” variable and print
that.
Explanation
def add(a,b):
The same program has been explained in
c=a+b
the previous slide. In this slide, want to
print(“Addition=“,c) explain that it is not mandatory that the
#__main__ variable name will be same in the
__main__ section and “def add(a,b)”. The
x=int(input(“Enter First Number:”)) name of the variable may be different.
y=int(input(“Enter Second Number:”)) You can find here that in __main__
section the variable has name x & y and
add(x,y) in the function definition the name is a
and b. Now This x & y is called the Actual
Argument and a & b is called Formal
Argument.
For Example:
1. Suppose we are writing a program to add two numbers in such case the
addition of these two numbers will be the return.
2. Suppose we have to write a program to check whether a given number is odd
or even, then in such case the number is odd or even is the final answer and
hence as a result we will return “even” or “odd”.
3. Suppose we have to write a program to check a number is prime/Armstrong or
not, in such case the result i.e. “Prime”, “Not Prime”, “Armstrong”, “Not
Armstrong”
Notes is Channel:
By: Anand Sir | YouTube the return
CODEITUP value.
FUNCTIONS IN PYTHON
Return
For Example:
4. Suppose we have to count total odd or even number in a list, then in such case
total counting of “odd” and “even” will be the return.
Now, till here, we have completed the theoretical concept of return statement
and now we will see this using programming approach.
Output:
Value of Local variable a=5
Notes By: Anand Sir | YouTube Channel: CODEITUP
FUNCTIONS IN PYTHON
Local & Global Variable
Local Variable:
Local Variables are those which are declared inside a function. In such case it’s visibility is
only upto the function in which it has been declared. It has no existence outside the
function scope. For example consider the following code snippet:
def example():
a=5 # Here “a” is a local variable
print(“Value of Local variable a=“,a)
#__main__
example()
print(“The value of a=“,a)#this statement will raise an error because variable “a” is a local
variable and its visibility is only upto the function in which it has been declared.
Output:
Value of Local variable a=5
After
Notes By: Anand Sir |this it will
YouTube display
Channel: CODEITUP an error
FUNCTIONS IN PYTHON
Local & Global Variable
Global Variable:
Globale Variables are those which are declared not inside a function. It is either declared
at the top of code window or inside __main__
These variables can be used anywhere in the program as it’s visibility is entire
program and hence it can be accessed from any section of the program.
For Example:
a=5
def example():
print(“Using Global variable a Inside a Function=“,a) # Allowed as “a” is global.
#__main__
example()
print(“The value of a=“,a) # Allowed as “a” is global
Output:
Using Global variable a inside a Function=5
Notes By: Anand Sir | YouTube Channel: CODEITUP
The value of a=5
FUNCTIONS IN PYTHON
Local & Global Variable
Global Variable: The global variable can be declared in __main__ section as well.
def example():
print(“Using Global variable a Inside a Function=“,a) # Allowed as “a” is
global.
#__main__
a=10
example()
print(“The value of a=“,a) # Allowed as “a” is global
Output:
The value of a=10
Using Global variable a inside a Function=10
Notes By: Anand Sir | YouTube Channel: CODEITUP
FUNCTIONS IN PYTHON
What if same name local & global variable is there?
For an instance suppose we have same name variable in local as well as global
scope.
Please make it clear that if the same name variable is present in local &
global scope then, whenever that variable will be used inside the local function, it
will take the local variable, and if outside any function, it will use global variable.
For Example consider the following code:
Output:
Value of Global a=20
Value of local a=10
Notes By: Anand Sir | YouTube Channel: CODEITUP
FUNCTIONS IN PYTHON
What if same name local & global variable is there?
Now, it is clear that if same name variable is there in local as well global scope,
then both exists that means memory allocation is done for both variables. Now
when it comes to access the variable, so if you are using any variable inside a
local function, first this watches that variable inside it and if it is found inside the
function itself, it uses the same.
Now, if that variable is not found inside the local function then it searches for
the global variable and uses it.
So, now this is clear to all of you that local searches the values first inside itself, if
found operate upon it and if not found, it searches the global scope and uses it.
a=10
def example():
global a #now this function can’t create local variable with name a
a=a+10 #any changes will be done in global variable
#__main__
print(“Value of Global a=“,a)
example()
print(“Value of Global a after increment=“,a)
Notes By: Anand Sir | YouTube Channel: CODEITUP
FUNCTIONS IN PYTHON
Default Argument
Default argument is a concept which is used to give some default values to the
function arguments. In case of default arguments, we get an option to pass value
for that variable.
We can pass it, we can’t pass it all upto us. If we will pass the value, the
argument will take the value that we will pass otherwise the default value.
For example:
def example(a,b=5):
print(“Addition=“,(a+b))
#__main__
example(12,20) # in this case both values are passed so in the function section a
will be initialized with 12 and b will be initialized with 20.
example(10) # in this case only on value is passed i.e. the value for a only so a will
take the value 10 and b will be initialized with default value which is 5.
Notes By: Anand Sir | YouTube Channel: CODEITUP
FUNCTIONS IN PYTHON
Default Argument
Rule for default argument:
There is just one rule for default value that, once you start giving default value all
the arguments after that must contain default value. For example:
def example(a,b):
print(“Value of a=“,a,”Value of b=“,b)
#__main__
example(5,10) #in this case a will contain 5 and b will contain 10 i.e. sequentially.
example(b=15,a=40) #here we have passed values through its name and hence a
b will contain 15 and a will contain 40
2. Numpy Library: This library provides some advance math functionality along with
tools to create and manipulate arrays.
4. tkinter library: This is basically used for GUI interface for different types of
calculations.
5. Matplotlib library: This is basically used for producing quality output in variety of
formats such as plots, charts, graphs etc.
Notes By: Anand Sir | YouTube Channel: CODEITUP
PYTHON MODULE
Ques: What is Module?
A python module is (.py file) containing variables, class definitions, statements and
functions related to a particular task. The major feature of having module is that its
content can be reused in other programs, without having to rewrite or recreate
them.
>>>import time
>>>import decimals, fractions
After importing a module, you can use any function/definitions inside it as per the
following syntax:
<module name>.<function name>()
For Example:
>>>import tempconversion
>>>tempconversion.to_celcius(98.6)
Notes By: Anand Sir | YouTube Channel: CODEITUP
PYTHON MODULE
The name of the module is stored inside a constant __name__
You can get the name of the module by using the following command:
>>>import time
>>>print time.__name__
We can also give an alias to the the package which we are importing.
For Example:
>>>import numpy as np
Here now np is the name of the package called numpy.
>>>import tempconversion as tc
>>>tc.to_celcius( 98.6)
>>>import math
>>>math.sqrt(25)
5.0
Note: If your program has already a variable with the same name as the imported
module then the variable of your program will hide the variable of the module.
For Example:
>>>import temperature
>>>FREEZING_C=15.0
>>>print(FREEZING_C)
15.0
Here, the value of FREEZING_C variable of your program will override the constant
present in the temperature module.
Note: We should avoid using from <module> import * as it may lead to name
clashes.
Notes By: Anand Sir | YouTube Channel: CODEITUP
PYTHON MODULE
Using Python Standard Library Function & Modules
Python’s standard library is very extensive that offers many built in functions that
you can use without having to import any library. Python’s standard library is by
default available, so you need not to import it separately.
We have been using many python built in functions viz input(), int(), float(), type(),
len() etc. are all built in functions. For using these functions you never import any
module.
(ii) If you provide a string or a character as an argument to split(), then the given
string is divided into parts considering the given string/character as separator and
the separator character/string is not included in the split string.
In[]: “Python Rocks”.split(“o”)
Out[]: [‘Pyth’,’n R’,’cks’]
enstr=input(“Enter String:”)
enkey=input(“Enter Encryption key”)
enstring=encrypt(enstr,enkey)
print(“Encrypted String=“,enstring)
delist=decrypt(enstring,enkey)
destring=“ “.join(delist)
print(“Decrypted String=“,destring)
Notes By: Anand Sir | YouTube Channel: CODEITUP
PYTHON MODULE
Random Module
To generate random numbers we may use the Random module of python. To use
random number generators, we need to first import random module.
>>>import random
Two most common random number generator function of random module are:
i) random() – it returns a random number floating point number N in the range
[0.0, 1.0]. We can also use the same to generate floating point number between
a given lower and upper range. In this case only lower range is inclusive and not
the upper range.
ii) randint(a,b) – it returns a random integer N in the range a and b(both values
inclusive). In this case both the values are inclusive i.e. the upper range and the
lower range.
i. In order to get the path of site-package type the following two commands:
import sys
print(sys.path)
ii. Now copy your folder and paste to the path as mentioned in the path. Now,
the folder will become a package.
A text file stores information in ASCII or Unicode character. In text file, each line of
text is terminated with a special character known as EOL (End of Line). By default,
this EOL character is the newline character (‘\n’).
So, working on files is as easy as you work on any other file like notepad, ms-word
etc. For working on a file either you need to open a new file first and then you
type something (here the same will be called as writing) and save it and close it.
Another way may be you might be opening a pre-existing file and either you
may read the content of the file or may edit/add some new information to it and
close it.
Similarly, when we will work with File Handling / Data File Handling, we will adopt
the same.
Notes By: Anand Sir | YouTube Channel: CODEITUP
DATA FILE HANDLING
Opening a File
So, the first task become to open a file either a new file or a pre-existing file. To
work with file the first step is to open the file. We may open the file for the
following purposes:
1. Reading data from file
2. Writing data to file
3. Appending data to file
There are many other modes but most of them are of no use as per our syllabus.
Closing a file
A file can be closed by just calling the close function using the file object. For
example: file1.close()
Output:
t to start
Explanation:
In str variable initial 10 bytes of data will
be read and in the very next line in str1
next 10 bytes of data will be read and
hence the answer will from 11th byte data
to 20th byte.
Notes By: Anand Sir | YouTube Channel: CODEITUP
DATA FILE HANDLING
Code Snippet 3 story.txt
myfile = open(r’E:\story.txt’,’r’) If you want to start, it’s never late.
str=myfile.read() If you are thinking to quit, think why
print(str) you started.
I have not failed. I have just found
10000 ways that won’t work.
Output:
If you want to start, it’s never late.
If you are thinking to quit, think why you
started.
I have not failed. I have just found 10000
ways that won’t work.
Explanation:
without any argument, read() function
reads the whole content of a file.
Notes By: Anand Sir | YouTube Channel: CODEITUP
DATA FILE HANDLING
Code Snippet 4 story.txt
myfile = open(r’E:\story.txt’,’r’) If you want to start, it’s never late.
str=myfile.readline() If you are thinking to quit, think why
print(str) you started.
I have not failed. I have just found
10000 ways that won’t work.
Output:
If you want to start, it’s never late.
Explanation:
readline() function reads one line from
the file at a time.
Output:
['If you want to start, it’s never late.\n', 'If
you are thinking to quit, think why you
started.\n', 'I have not failed. I have just
found 10000 ways that won’t work.\n’]
Explanation:
readlines() reads the data in List format.
Output:
160
Explanation:
read() function will read the whole content of
the file and at last len(s) will give the size of
the list which is 160 bytes/characters.
Notes By: Anand Sir | YouTube Channel: CODEITUP
DATA FILE HANDLING
Code Snippet 8 story.txt
Program to Count total number of Lines in a file If you want to start, it’s never late.
called story.txt
If you are thinking to quit, think why
you started.
myfile = open(r’E:\story.txt’,’r’)
I have not failed. I have just found
s=myfile.readlines() 10000 ways that won’t work.
size=len(s)
print(“Number of lines=“,size)
myfile.close()
Output:
Number of lines=3
So, the first function is “write()” function which writes/stores given string to the file. There is
the second function called “writelines()” which is used to write list of string (a list
containing string elements) to the file. We will be looking into it programmatically in
coming slides.
Here in the above code snippet, a file abc.txt will be opened and the string “Hello this is
file handling.” will be written/stored inside that. Now the major question arises here that
what will be the location of the file “abc.txt” simply means where the file abc.txt will be
created?
So, the answer is the file abc.txt will be created at the same place where you will save
this program.
f=open("abc.txt","w")
name=input(“Enter Your Name:”)
f.write(name)
f.close()
Program 4
f=open(“student.txt”,”w”)
for i in range(5):
name=input(“Enter Name:”)
f.write(name) #will simply write the content without adding any character
f.close()
Now, this will create a file student.txt in which 5 names as entered by the user will be
stored conineously.
Program 5
f=open(“student.txt”,”w”)
for i in range(5):
name=input(“Enter Name:”)
f.write(name)
f.write(‘\n’) # Every time we put “\n” so that the name appears in the next line.
f.close()
Append mode just keep the previous data of the previous file and then appends the
new data at the end of the same file.
Program 9
f=open(“student.txt”,”w”)
list1=[]
for i in range(5):
name=input(“Enter Name:”)
list1.append(name+’\n’)
f.writelines(list1) #after the loop list1 has been written to the file student.txt
print(“Data Stored Successfully...”)
f.close()
In other words, when we write some data to a file, it is usually written at the same time
but sometimes, it could not be written. Usually, when the file is closed all the data is
written in the file and saved. Now, if you want in between the program to make sure
that whatever you want to write, is definitely written to the file then in such case you will
use the Flush() function.
f=open("student1.txt","r")
data=f.read()
print("Length=",len(data))
f=open("student1.txt","r")
data=f.readlines()
print(data)
print("Length=",len(data))
def abc():
--------------------
--------------------
abc() #so here you can say that the function abc() has been called inside
itself, so it is the concept of recursion. So, it can be said that the recursion is of two types:
a. Direct recursion – It is the case when a function calls itself from its function body.
b. Indirect recursion – It is the case when a function calls another function, which calls its
caller function.
b. def abc():
.........
xyz()
def xyz():
........
abc()
def sum(num):
if num==1:
return 1
else:
return(num+sum(num-1))
n=int(input("Enter Number:"))
print("Sum=",sum(n))
ii) Plagiarism
Plagiarism is stealing someone else’s intellectual work and representing it like your
own work. If I say straightforward, Plagiarism refers to “stealing someone’s idea/work”.
The following work would be termed as Plagiarism:
a. Using someone’s work without giving credit to the creator.
b. Using someone’s work in incorrect form.
c. Modifying someone’s production viz video/music
d. Giving incorrect information
How to avoid Plagiarism:
One must give credit to the creator/author for using his idea/opinion/work.
Back-end part of the software development refers to the database application which we
are going to use for storing various data. This can be MongoDB/MySQL/SQL+/MS-ACCESS
and many more. Here, according to our syllabus, we need to take MySQL as our back-
end.
If, it is working that means during the installation of Python, you have ticked on the check
box “Add python to path”.
See the next slide for the thing which you need to tick while installing python so that path
is automatically set. If you missed it, you can uninstall and then install the same after
selecting “Add python to path” button.
Notes By: Anand Sir | YouTube Channel: CODEITUP
INTERFACE WITH MYSQL
Now after following these steps, you have now successfully added Python to path. So, now you
have python installed with path and mysql.
The next step is to download and install “MySQL Connector” which acts as a bridge between
Python and MySQL.
query="insert into
import mysql.connector as c
emp(code,name,desig,salary)values({},'
con=c.connect(host="localhost", {}','{}',{})".
user="root", format(code,name,desig,salary)
passwd="123456", cursor.execute(query)
database="school") con.commit()
cursor=con.cursor() if choice==2:
name=input("Enter Name:") break
desig=input("Enter Designation:") print("Data Inserted.")
salary=int(input("Enter Salary"))
query="insert into
import mysql.connector as c emp(code,name,desig,salary)values({},'{}','{}',{})".
con=c.connect(host="localhost", format(code,name,desig,salary)
user="root", cursor.execute(query)
passwd="123456", con.commit()
database="school") choice=int(input("1->Yes\n2-No\nDo you wish to
cursor=con.cursor() Continue?"))
while True: if choice==2:
code=int(input("Enter Employee break
Code:")) print("Data Inserted Successfully...")
name=input("Enter Name:")
desig=input("Enter Designation:")
salary=int(input("Enter Salary"))