0% found this document useful (0 votes)
1K views

Python Class 12 Notes by Anand SIr

Uploaded by

Vidma Recorder
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
1K views

Python Class 12 Notes by Anand SIr

Uploaded by

Vidma Recorder
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 443

PYTHON

CHAPTER – 1
REVISION TOUR - 1

Notes By: Anand Sir | YouTube Channel: CODEITUP


PYTHON
Introduction
Python is an Interpreted, high level, general purpose programming
language developed by Guido Van Rossum and its first version was released
in 1991.
The LATEST version of Python is 3.9.6 which keeps changing as and
when a new version comes us. You can check for latest version on Python’s
official website i.e. https://python.org

Notes By: Anand Sir | YouTube Channel: CODEITUP


PYTHON
Programming
Programming is a way to give instructions to the computer system. It is
a way to communicate with computer system and pass instructions to the
computer system.

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.

Notes By: Anand Sir | YouTube Channel: CODEITUP


PYTHON
Why to learn Python?
It’s growth is quite high. It is widely being used in many fields like:
1. Data Analysis
2. Machine Learning
3. Deep Learning
4. Artificial Intelligence
5. Desktop Application Development
6. Web Development etc.

Notes By: Anand Sir | YouTube Channel: CODEITUP


PYTHON
How to install python?
Python is an open source software which may easily be installed by
visiting the link:
https://www.python.org/
Here, under downloads section you may find the current version of Python
i.e. Python 3.9.4. Just download it and follow the steps to install.

Notes By: Anand Sir | YouTube Channel: CODEITUP


PYTHON
What is Python IDLE
After installing Python just goto start menu and find “IDLE (Python
3.9.0)”. IDLE stands for Integrated Development Learning Environment. This is
a by default Development Environment for Python. There are many more
development environments like Pycharm, Eclipse, Eric etc. We will learn
about this in next videos.

Notes By: Anand Sir | YouTube Channel: CODEITUP


PYTHON
Input & Output Operation on Python
We can do a lots of work directly on python command prompt. There are
two basic operations that is always performed irrespective of what
programming language you use and that are input and output operation.
For taking input we use input() function and for output we used print()
function.
Let’s discuss both the function in details.

Notes By: Anand Sir | YouTube Channel: CODEITUP


PYTHON
print()
➢This function is used to print message/ values. The string to be printed is
put inside single quotes/double quotes whereas the values are written
without single/double quotes.
Syntax:
a. print(“Hello”)
output: Hello
b. a=5
b=6
c=a+b
print(c)
output: 11

Notes By: Anand Sir | YouTube Channel: CODEITUP


PYTHON
print()
>>>print(“Anand Kumar\nNew
Delhi\nIndia”) >>>print(“*\n**\n***\n****\n*****”)
#\n takes you to next line. output:
output: *
Anand Kumar
**
New Delhi
India ***
****
*****

Notes By: Anand Sir | YouTube Channel: CODEITUP


PYTHON
print()
Till the previous examples, we have just printed the values stored in variables or
directly printed the message. Now what if we want to print message along with
values? Have a look on the code below:
a=5
b=10
c=a+b
print(“Addition=“,c)

Notes By: Anand Sir | YouTube Channel: CODEITUP


PYTHON
print()
If extending the previous program to know more about print method we
may extend it as:
Example:
a=5
b=10
c=a+b
print(“Addition of”,a,”and”,b,”=“,c)

Output: Addition of 5 and 10 = 15


So, here you can see what so ever message part is there, is placed inside
double quotes and the value without double quotes. The quotes used here
may be single quotes or double quotes as well.
Notes By: Anand Sir | YouTube Channel: CODEITUP
PYTHON
TOKEN
Tokens are smallest individual part of any programing language. These parts
altogether make a complete programming.
TOKEN is divided into following 5 Parts. To learn we can say that TOKEN are KILPO
or KILSO.
K - Keyword
I - Identifier
L - Literal
P/S – Punctuator / Seperator
o - Operator

Notes By: Anand Sir | YouTube Channel: CODEITUP


PYTHON
Keyword

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

Notes By: Anand Sir | YouTube Channel: CODEITUP


PYTHON
Identifier
Identifier is the name given to a variable, function, class or anything. There are some
certain rule for declaring any identifier in Python programming:

1. A keyword can’t be used as Identifier name.

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.

4. Space is not allowed between identifier name.

For Example:

myname – Valid 9p – Invalid break – Invalid int$rate - Invalid

Notes By: Anand Sir | YouTube Channel: CODEITUP


PYTHON
Literal/Constant

Literal/Constant are fixed values that can’t be changed during the


execution of the program. There are various types of constants/literals:

1. String Literal – To store string values.

2. Numeric Literal – To store numbers.

3. Boolean Literal – To store Boolean values i.e. True or False

4. Special Literal None – None literal is used to indicate absence of the


value.

Notes By: Anand Sir | YouTube Channel: CODEITUP


PYTHON
Operator
Operators are used to perform operations. In python there are different
types of operators:
1. Arithmetic Operator (+,-,*,/,//,**,%)
2. Relational Operator(<,>,<=,>=,==,!=)
3. Identify Operator (is, is not)
4. logical operator( and, or)
5. Membership Operator (in, not in)
6. Bitwise Operator (^, &, | )
Notes By: Anand Sir | YouTube Channel: CODEITUP
PYTHON
Punctuator/Separator

Punctuator / Separator are the symbols that are used in programming to


separate an element from the other element.

For Example:

‘ “ , () [] {} @ : etc

Notes By: Anand Sir | YouTube Channel: CODEITUP


VARIABLE
VARIABLE

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.

For Example: x=110 # Here x is a variable of integer type ( int )


z=100.56 # Here z is a variable of float type (float)
y=“Ram Kumar” # Here y is the type of string ( str )
print(x)
print(y)

Notes By: Anand Sir | YouTube Channel: CODEITUP


VARIABLE
VARIABLE
A variable name can not be anything as we want. There are some rules
which has to be taken care while declaring a variable:
1. A variable name must start with a letter or the underscore character.
2. A variable name cannot start with a number.
3. A variable name can only contain alpha-numeric characters and
underscores (A-z, 0-9, and _ ).
4. Variable names are case-sensitive (age, Age and AGE are three different
variables).
5. There can’t be a space among variable name.

Notes By: Anand Sir | YouTube Channel: CODEITUP


VARIABLE
#Legal variable names:

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”

Notes By: Anand Sir | YouTube Channel: CODEITUP


VARIABLE
Static Typing Vs Dynamic Typing

Static Typing is a type of variable declaration where a datatype is also


attached and before using a variable we need to declare it.

In the contrary Dynamic Typing is a type of variable declaration where we


may use a variable anywhere without declaring it earlier with a datatype.
Python supports the concept of Dynamic Typing.

Notes By: Anand Sir | YouTube Channel: CODEITUP


VARIABLE
Multiple Assignment in Python

Python also provides us the facility to do multiple assignment together.


1. Assigning same value to multiple variables:
a=b=c=10 # Here a,b,c all three will be assigned 10.

2. Assigning multiple values to multiple variables:


a,b,c=5,10,15 #Here a will contain 5, b will 10 and c will 15

3. Swapping can be done like this:


a,b=b,a

Notes By: Anand Sir | YouTube Channel: CODEITUP


PYTHON DATATYPE
Datatype defines the type of data a variable will store. In python, there is no
strict rule for declaring variable. Datatype is auto defined in Python. In
Python, the data type is set when you assign a value to a variable:

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

If we want to know the type of a variable we use “type” function.

For Example:
x=5
print(type(x))

# Output: int

Notes By: Anand Sir | YouTube Channel: CODEITUP


PYTHON DATATYPE
Core Data Types
1. Numbers
a. Integer b. Floating Point c. Complex
2. None
3. Sequences
a. String b. Tuple c. List
4. Mappings
a. Dictionary

Notes By: Anand Sir | YouTube Channel: CODEITUP


TYPE CASTING
Type Casting

Conversion of one data type into another type is called type casting.
Casting in python is done using constructor functions:

int() - Converts the argument into integer type.


x = int(1) # x will be 1 as integer of 1 is 1.
y = int(2.8) # y will be 2 as integer o 2.8 is 2.
z = int("3") # z will be 3 as integer of string 3 is 3.

Notes By: Anand Sir | YouTube Channel: CODEITUP


TYPE CASTING
Type Casting

Conversion of one data type into another type is called type casting.
Casting in python is done using constructor functions:

float() - Converts the argument into float type.

x=float(1) # x will be 1.0


y = float(2.8) # y will be 2.8
z = float("3") # z will be 3.0
w = float("4.2") # w will be 4.2

Notes By: Anand Sir | YouTube Channel: CODEITUP


TYPE CASTING
Type Casting

Conversion of one data type into another type is called type casting.
Casting in python is done using constructor functions:

str() - Converts the argument into string type.


x = str("s1") # x will be 's1’
y = str(2) # y will be '2’
z = str(3.0) # z will be '3.0'

Notes By: Anand Sir | YouTube Channel: CODEITUP


PYTHON
Writing Python Program
Python provides us the facility to write Python Program in one file that will be
executed line by line sequentially. Steps for writing Python Program:
1. Open Python IDLE (Integrated Development & Learning Environment).
2. Click on “File Menu” and then choose “New File”.
3. A new screen/window will appear.
4. Here Type the python program and save the program.
5. To run the program click on “Run” menu and click on “Run Module”
6. The Python code will start running.

Notes By: Anand Sir | YouTube Channel: CODEITUP


PYTHON
Datatypes in Python
Datatype defines the type of data a variable will store. Python support the
following datatypes:

1. Text Type : str


2. Numeric Type : int, float, complex
3. Sequence Type : list, tuple, range
4. Mapping Type : dictionary
5. Set Type: set, frozenset
6. Boolean: bool
7. Binary Type: bytes, bytearray
Notes By: Anand Sir | YouTube Channel: CODEITUP
PYTHON
Variable in Python
Variable is used to store values. In python there is no command for variable
declaration. A variable is automatically created as soon as you assign a
value to it.
For example:
1. a=5 # here a variable a has been created with int datatype
2. a=“ram” # here a variable a has been created with str datatype
3. a=5.5 # here a variable a has been created with float datatype
4. a=True # here a variable a has been created with bool datatype
5. According to above example, it is clear that a variable datatype is
decided as per the value assigned to it.
Notes By: Anand Sir | YouTube Channel: CODEITUP
PYTHON
Python program for Adding two numbers.

a=int(input(“Enter 1st Number:”))


b=int(input(“Enter 2nd Number:”))
c=a+b
Print(“Addition=“,c)

After writing this program save the program and run it. All the statement
inside it will be executed one by one.

Notes By: Anand Sir | YouTube Channel: CODEITUP


PYTHON
Python program for finding area of rectangle.
len=int(input(“Enter Length:”))
wid=int(input(“Enter Width”))
area=len*wid
print(“Area of rectangle=“,area)

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.

Notes By: Anand Sir | YouTube Channel: CODEITUP


CONTROL STATEMENT IN PYTHON
The programs what we have done till now follows a sequential manner to
execute the statement. That means all the statements are executed step
by step in the same order they appear. Now there may be some situation
where we may need to execute a single statement or a block of
statement as per a given condition as well as till a given condition is true.

Control Statement is basically of two types:

1. Selection Control Statement


2. Looping/Iterative Statement

Notes By: Anand Sir | YouTube Channel: CODEITUP


If statement
If statement is a conditional control statement which is used to check a
condition and work according to the given condition. If the given
condition is true then some other statement(s) is executed while if the
condition is false some other statement(s) is executed.
Syntax:
if condition: if condition: if condition:
statement(s) statement(s) statement(s)
else: elif condition:
statement(s) statement(s)
else:
statement(s)
Notes By: Anand Sir | YouTube Channel: CODEITUP
Program Implementation

Question: Write a program to check whether a given number is odd or even.

a=int(input(“Enter Number to check for odd or even:”))


if a%2==0:
print(“Even Number”)
else:
print(“Odd Number”)

Notes By: Anand Sir | YouTube Channel: CODEITUP


Program Implementation

Question: Write a program to check whether a given number is positive,


negative or zero.
a=int(input(“Enter 1st Number:”))
if a>0:
print(“The number is positive”)
elif a<0:
print(“Number is negative”)
else:
print(“Zero”)

Notes By: Anand Sir | YouTube Channel: CODEITUP


Program Implementation
Question: Write a program to check max number between three
numbers.
a=int(input(“Enter 1st Number:”))
b=int(input(“Enter 2nd Number:”))
c=int(input(“Enter 3rd Number:”))
if a>b and a>c:
print(“Max Number=”,a)
elif b>a and b>c:
print(“Max Number=”,b)
else:
print(“Max Number=”,c)
Notes By: Anand Sir | YouTube Channel: CODEITUP
Program Implementation
Question: Write a program to find the middle number in a group of
three numbers.
Solution:
a=int(input(“Enter first Number:”))
b=int(input(“Enter first Number:”))
c=int(input(“Enter first Number:”))
if (a>b and a<c) or (a<b and a>c):
print(“Middle number=”,a)
elif (b>a and b<c) or (b<a and b>c)
print(“Middle number=”,b)
else
print(“Middle number=“,c)
Notes By: Anand Sir | YouTube Channel: CODEITUP
If statement
Question: Write a program to calculate total marks in 5 subjects (Full marks = 100) as well as
percentage of marks and division as per the following condition:
percentage>=80 – Grade A percentage>=60 – Grade B
percentage>=40 – Grade C percentage<40 –Grade D
Solution:
a=int(input(“Enter 1st Number:”))
b=int(input(“Enter 2nd Number:”))
c=int(input(“Enter 3rd Number:”))
d=int(input(“Enter 4th Number:”))
e=int(input(“Enter 5th Number:”))
total=a+b+c+d+e
percent=(total/500)*100
print(“Total Marks=“,total,”Percetage=”,percent)
if percent>=80:
print(“You have got Grade A”)
elif percent>=60:
print(“You have got grade B”)
elif percent>=40:
print(“You have got Grade C”)
else
print(“You have got Grade D”)
Notes By: Anand Sir | YouTube Channel: CODEITUP
Ques: Write a program to check whether an integer number is a single
digit or double digit or three digit number or more than three digit.

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

Notes By: Anand Sir | YouTube Channel: CODEITUP


PYTHON
For any looping, there are three essential parts. All these three parts
are quite important in order to
1. Initialization of counter variable
2. Condition
3. Increment/Decrement

Notes By: Anand Sir | YouTube Channel: CODEITUP


PYTHON
While Loop:
While loop is used to execute a single statement or a block of
statement n times till the condition is true. The syntax of while loop is:

initialization
while condition:
statement(s)
....................
increment/decrement

Notes By: Anand Sir | YouTube Channel: CODEITUP


PYTHON
For Loop:
For loop is used to execute a single statement or a block of statement
“n” times till the condition is true. In for loop the counter automatically
starts with 0 and goes to “end-1” and there is a default increment of 1.
Syntax of For loop:
for variable in range(start_val,end_val,step_value):
statement(s)
.....................
Note: We will be doing while loop programming first to understand the
concept of while loop and then I will let you know the

Notes By: Anand Sir | YouTube Channel: CODEITUP


PYTHON
Program List Level – 1 Question (Playing with Numbers)
Ques 1: Write a program to print from 1 to 10.
Ques 2: Write a program to print from 1 to n.
Ques 3: Write a program to print from 10 to 1.
Ques 4: Write a program to print from n to 1.
Ques 4: Write a program to print sum of n to 1.
Ques 5: Write a program to print sum from 1 to n.
Ques 6: Write a program to print sum of SQUARE from 1 to n.
Ques 7: Write a program to print sum of CUBE from 1 to n.
Ques 8: Write a program to print only even number between 1 to n.
Ques 9: Write a program to find sum of even numbers from 1 to n.
Ques 10: Write a program to find sum of first n even numbers.
Notes By: Anand Sir | YouTube Channel: CODEITUP
PYTHON
Ques 1: Write a program to print from Ques 1: Write a program to print from
1 to 10. (Using While Loop) 1 to 10. (Using For Loop_
Solution: i=1 Solution:
While(i<=10): for i in range(1,11):
print(i) print(i)
i=i+1

Notes By: Anand Sir | YouTube Channel: CODEITUP


PYTHON
Ques 2: Write a program to print from 1 Ques 2: Write a program to print from 1
to n (Using while loop) . to n (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): print(i)
print(i)
i=i+1

Notes By: Anand Sir | YouTube Channel: CODEITUP


PYTHON
Ques 3: Write a program to print from Ques 3: Write a program to print from
10 to 1. (Using While Loop) 10 to 1. (Using For Loop)
Solution: i=10 Solution:
While(i>=1): for i in range(10,0,-1):
print(i) print(i)
i=i-1

Notes By: Anand Sir | YouTube Channel: CODEITUP


PYTHON
Ques 4: Write a program to print from Ques 4: Write a program to print from
n to 1. (Using While Loop) n to 1. (Using For Loop)
Solution: n=int(input(“Enter Solution:
Number:”)) n=int(input(“Enter Number:”))
While(n>=1): for i in range(n,0,-1):
print(n) print(i)
n=n-1

Notes By: Anand Sir | YouTube Channel: CODEITUP


PYTHON
Ques 5: Write a program to find sum from 1 Ques 5: Write a program to find sum
to n. (Using While Loop)
from 1 to n. (Using For Loop)
Solution:
Solution:
n=int(input(“Enter Number upto which you
want to sum”)) n=int(input(“Enter Number upto which
you want to sum”))
i=1

sum=0 sum=0

while(i<=n): for i in range(1,n1):


sum=sum+i sum=sum+i
i=i+1 print(“Sum =“,sum)
print(“Sum =“,sum)
Notes By: Anand Sir | YouTube Channel: CODEITUP
PYTHON
Ques 6: Write a program to find sum Ques 6: Write a program to find sum
of square from 1 to n. (Using While of square from 1 to n. (Using For Loop)
Loop) Solution:
Solution: n=int(input(“Enter Number upto
n=int(input(“Enter Number upto which you want to sum”))
which you want to sum”)) sum=0
i=1 for i in range(1,n+1):
sum=0 sum=sum+(i*i)
while(i<=n): print(“Sum =“,sum)
sum=sum+(i*i)
i=i+1
print(“Sum =“,sum)

Notes By: Anand Sir | YouTube Channel: CODEITUP


PYTHON
Ques 7: Write a program to find sum of Ques 7: Write a program to find sum
cubes from 1 to n. (Using While Loop) of cubes from 1 to n. (Using For
Solution: Loop)
n=int(input(“Enter Number upto which Solution:
you want to sum”))
n=int(input(“Enter Number upto
i=1
which you want to sum”))
sum=0
while(i<=n):
sum=0

sum=sum+(i*i*i) for i in range(1,n+1):


i=i+1 sum=sum+(i*i*i)
print(“Sum =“,sum) print(“Sum =“,sum)

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. (First even numbers between 1 to n. (First
Method, Using While Loop) 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=2 for i in range(2,n+1,+):

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

while (i<=n): for i in range(2,n+1,2):


sum=sum+i sum=sum+i
i=i+2 print(“Sum of Even numbers=“,sum)
print(“Sum of Even numbers=“,sum)
Notes By: Anand Sir | YouTube Channel: CODEITUP
PYTHON
Ques 9: Write a program to find sum of even
numbers from 1 to n. (Second Way Using While Ques 9: Write a program to find sum of even
Loop) numbers from 1 to n. (Second Way Using For
n=int(input(“Enter Number upto which you Loop)
want to add even numbers”))
n=int(input(“Enter Number upto which
i=1
you want to add even numbers”))
sum=0
sum=0
while (i<=n):

if (i%2==0): for i in range(1,n+1):

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.

i=int(input(“Enter Number to find sum of digits”))


sum=0
While (i>0):
sum=sum+i%10
i=i//10
Print(“Sum of digits=“,sum)

Notes By: Anand Sir | YouTube Channel: CODEITUP


PYTHON
Ques 2: Write a program to find sum of square of digits of a given number.

i=int(input(“Enter Number to find sum of square of digits”))


sum=0
while (i>0):
sum=sum+(i%10)*(i%10)
i=i//10
print(“Sum of Square of each digits=“,sum)

Notes By: Anand Sir | YouTube Channel: CODEITUP


PYTHON
Ques 3: Write a program to find sum of cube of digits of a given number.

i=int(input(“Enter Number to find sum of cube of digits”))


sum=0
while (i>0):
sum=sum+(i%10)*(i%10)*(i%10)
i=i//10
print(“Sum of cube of each digits=“,sum)

Notes By: Anand Sir | YouTube Channel: CODEITUP


PYTHON
Ques 4: Write a program to check whether a given number is Armstrong Number
or not.
i=int(input(“Enter Number to check for Armstrong”))
orig=i
sum=0
while (i>0):
sum=sum+(i%10)*(i%10)*(i%10)
i=i//10
if orig==sum:
print(“Number is Armstrong”)
else:
print(“Number is not Armstrong”)

Notes By: Anand Sir | YouTube Channel: CODEITUP


PYTHON
Ques 5: Write a program to find product of digits of a given number.
i=int(input(“Enter Number :”))
prod=1
while (i>0):
prod=prod*(i%10)
i=i//10
print(“Product of digits=“,prod)

Notes By: Anand Sir | YouTube Channel: CODEITUP


PYTHON
Ques 6: Write a program to find sum of even digits and product of odd digits of a
given number.
i=int(input(“Enter Number :”))
Sum=0
Prod=1
while (i>0):
d=i%10
if d%2==0:
sum=sum+d
else:
prod=prod*d
i=i//10
print(“Sum of digits=“,sum,“Product of digits=“,prod)
Notes By: Anand Sir | YouTube Channel: CODEITUP
PYTHON
Ques 7: Write a program to find reverse of a given number.
i=int(input(“Enter Number :”))
rev=0
while (i>0):
rev=(rev*10)+i%10
i=i//10
print(“Reverse=“,rev)

Notes By: Anand Sir | YouTube Channel: CODEITUP


PYTHON
Ques 8: Write a program to check whether a number is palindrome or not?

i=int(input(“Enter Number :”))


rev=0
x=i
while (i>0):
rev=(rev*10)+i%10
i=i//10
If(x==rev):
print(“Palindrome Number”)
else:
print(“Not Palindrome”);

Notes By: Anand Sir | YouTube Channel: CODEITUP


PYTHON
Ques 9: Write a program to print factors of a given number?

i=int(input(“Enter Number :”))


n=1
while (n<=i):
if i%n==0:
print(n)
n=n+1

Notes By: Anand Sir | YouTube Channel: CODEITUP


PYTHON
Ques 10: Write a program to count total factors of a given number?

i=int(input(“Enter Number :”))


n=1
count=0
while (n<=i):
if i%n==0:
count=count+1
n=n+1
print(“Total Number of a Factors=“,count)

Notes By: Anand Sir | YouTube Channel: CODEITUP


PYTHON
Ques 11: Write a program to check whether a number is prime or not?
n=int(input(“Enter Number :”))
count=0
i=1
while (i<=n):
if (n%i==0):
count=count+1
i=i+1
if(count==2):
print(“Prime Number”)
else:
print(“Composite Number”);

Notes By: Anand Sir | YouTube Channel: CODEITUP


PYTHON
Ques 12: Write a program to print factorial of a given number?

i=int(input(“Enter Number :”))


fac=1
while (i>0):
fac=fac*i
i=i-1
print(“Factorial =“,fac)

Notes By: Anand Sir | YouTube Channel: CODEITUP


PYTHON
Ques 13: Write a program to print fibonacci series upto a given number?

n=int(input(“Enter Number :”))


x=0
y=1
z=0
while (z<=n):
print(z)
x=y
y=z
z=x+y

Notes By: Anand Sir | YouTube Channel: CODEITUP


PYTHON
Ques 14: Write a program to find x raised to the power y?

x=int(input("Enter Number:"))
y=int(input("Enter Number:"))
pro=1
while y>0:
pro=pro*x
y=y-1
print("Value=",pro)

Notes By: Anand Sir | YouTube Channel: CODEITUP


PYTHON
Program List:
Level – 3 Question
Ques 1: Draw the following shapes.
a. * b 1 c 1
** 12 22
*** 123 333
**** 1234 4444
***** 12345 55555

a. * b 1 c 1
** 12 22
*** 123 333
**** 1234 4444
***** 12345 55555

c. ***** b 12345 c 11111


**** 1234 2222
*** 123 333
** 12 44
* 1 5
Notes By: Anand Sir | YouTube Channel: CODEITUP
PYTHON
Program List:
Level – 3 Question
Ques 2: Draw the following shapes.
a. * 1 1
*** 222 123
***** 33333 12345
******* 4444444 1234567
********* 555555555 123456789

b. * 1 1
*** 222 123
***** 33333 12345
******* 4444444 1234567
********* 555555555 123456789
******* 4444444 1234567
***** 33333 12345
*** 222 123
* 1 1

Notes By: Anand Sir | YouTube Channel: CODEITUP


PYTHON
Program List:
Level – 3 Question
Ques: Draw the following shapes.

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.

for i in range(5): *****


for b in range(i):
print(" ",end="") ****
for j in range(5-i): ***
print("*",end="") **
print()
*
for i in range(5): 11111
for b in range(i):
print(" ",end="") 2222
for j in range(5-i): 333
print(i+1,end="") 44
print()
5
for i in range(5):
for b in range(i):
12345
print(" ",end="") 1234
for j in range(5-i): 123
print(j+1,end="")
print() 12
1
Notes By: Anand Sir | YouTube Channel: CODEITUP
PYTHON
CHAPTER – 2
REVISION TOUR - 2

Notes By: Anand Sir | YouTube Channel: CODEITUP


STRING
• String in Python are stored as individual characters i.e. indexed wise. The
index by default starts with 0.
Forward Indexing

0 1 2 3 4 5
str P Y T H O N
-6 -5 -4 -3 -2 -1
Backward Indexing

• So, here P will be represented by str[0] or str[-6], Y will be represented by


either str[1] or str[-5] and so on…

Notes By: Anand Sir | YouTube Channel: CODEITUP


STRING
Note
Strings are immutable and hence you can not change the individual letters of
string using assignment operator.

For Example:
name=“Shyam”
name[0]=“A”
// results to an error:
TypeError: ‘name' object does not support item assignment

Notes By: Anand Sir | YouTube Channel: CODEITUP


STRING
Initializing and printing a String:

Example 1:
name=“Shyam”
print(name) output: Shyam

Example 2:
name=“Shyam”
for i in name:
print(i) OR print(i, end=“”)

Notes By: Anand Sir | YouTube Channel: CODEITUP


STRING
String Operators
1. Concatenation Operator +
The + operator concatenates two different strings.
 Like “Every+”day” turns to Everyday
 x=“Every"+“day"
print(x)
OUTPUT: Everyday

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

3. Membership Operator ( in/not in )


The syntax is: <string> in <string>
<string> not in<string>
Example: >>>”a” in “ram” => will output true
>>>”a” not in “ram” => will output false

Notes By: Anand Sir | YouTube Channel: CODEITUP


STRING
String Operators
4. Comparison Operators:
All relational operators (>,<,>=,<=,==,!=) apply to strings also.
For Example:
Comparison Output
“a”==“a” True
“ram”==“ram” True
“a”!=“ram” True
“a”!=“A” True
“ram”==“Ram” False
“ram”==“RAM” False

Notes By: Anand Sir | YouTube Channel: CODEITUP


STRING
String Slicing
String slicing returns the characters falling between indices n and m:
Starting at n, n+1, n+2 … till m-1. The Syntax is:
string[start:end:step_value]

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

>>>str[::-1] => Reverse the string

Notes By: Anand Sir | YouTube Channel: CODEITUP


STRING
String Built-in Functions

Python provides some built in functions. Some of the important are:


1. len() => This function returns the length of the string. For Example:
a=“ram kumar”
print(len(a))
=> Output: 9

Notes By: Anand Sir | YouTube Channel: CODEITUP


STRING
String Built-in Functions

Python provides some built in functions. Some of the important are:


2. capitalize() => This function returns a copy of the string with its first
character capitalized. For Example:
a=“shyam kumar”
print(a.capitalize())
=> Output: Shyam kumar

Notes By: Anand Sir | YouTube Channel: CODEITUP


STRING
String Built-in Functions

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

Notes By: Anand Sir | YouTube Channel: CODEITUP


STRING
String Built-in Functions

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

Notes By: Anand Sir | YouTube Channel: CODEITUP


STRING
String Built-in Functions

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

Notes By: Anand Sir | YouTube Channel: CODEITUP


STRING
String Built-in Functions

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

Notes By: Anand Sir | YouTube Channel: CODEITUP


STRING
Program to count total vowel and consonants in a String

a=input("Enter Your Name:")


vowel=0
cons=0
for i in range(0,len(a)):
if(a[i]!=' '):
if(a[i]==“a” or a[i]==“e” or a[i]==“I” or a[i]==“o” or a[i]==“u”
a[i]==‘A’ or a[i]==‘E’ or a[i]==“I” or a[i]==“O” or a[i]==“U”):
vowel=vowel+1
else:
cons=cons+1
print("Total Vowels=",vowel)
print("Total Consonents=",cons)

Notes By: Anand Sir | YouTube Channel: CODEITUP


STRING
Program to find reverse of a string Program to find reverse of a string

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])

Notes By: Anand Sir | YouTube Channel: CODEITUP


STRING
Program to check a string is palindrome or not. Program to check a string is palindrome or not.
(Using Slicing Technique) (Without Using Slicing Technique)
a=input("Enter String:")
a=input("Enter String:")
i=0
b=a[-1::-1]
j=len(a)-1
if(a==b):
flag=0
print(“Palindrome String”) while i<j and flag==0:
else: if a[i]!=a[j]:
print(“Not Palindrome String”) flag=1
break
i+=1
j-=1
if(flag==0):
print(“Palindrome String”)
else:
print(“Not Palindrome String”)
Notes By: Anand Sir | YouTube Channel: CODEITUP
STRING
Program to find reverse of a string Program to find reverse of a string

a=input("Enter String:") a=input("Enter String to


for i in range((len(a)-1),-1,-1): Reverse:")
print(a[i],end="") b=""
for i in range(len(a)-1,-1,-1):
b=b+a[i]
print(b)

Notes By: Anand Sir | YouTube Channel: CODEITUP


LIST IN PYTHON
1. List is a collection of different values or different types of items. If you
want to store multiple values in a single variable then in such scenario
we use the concept of List.
2. Unlike array (which is called list in Python) in c/c++/java a List in
Python is capable of storing different types of values under one roof.
3. The items in the list are separated with the comma (,) and enclosed
with the square brackets [].
4. List provides us the facility to store multiple types of values in a single
unit.

Notes By: Anand Sir | YouTube Channel: CODEITUP


LIST IN PYTHON
How to define a list?
A list can be defined by giving a name and assigning values to it.
Example:
a=[] # Initializes a blank list.
a=[“ram”,1,”shyam”,12.5]
b=[1,2,3,4,5]
c=[1,22.5,15,16.5]

Notes By: Anand Sir | YouTube Channel: CODEITUP


LIST IN PYTHON
How to define a list?

a=[“ram”,10,”shyam”,12.5]

0 1 2 3 Forward Indexing
ram 10 shyam 12.5
-4 -3 -2 -1 Backward Indexing

Notes By: Anand Sir | YouTube Channel: CODEITUP


LIST SLICING IN PYTHON
Same as string, we have the concept of List slicing in Python.
For Example:
a=[“ram”,10,”shyam”,12.5]

0 1 2 3 Forward Indexing
ram 10 shyam 12.5
-4 -3 -2 -1 Backward Indexing

a[0] = ram a[-4]=ram


a[1] = 10 a[-3]=10
a[2] = shyam a[-2]=shyam
a[3] = 12.5 a[-1]=12.5
Notes By: Anand Sir | YouTube Channel: CODEITUP
LIST SLICING IN PYTHON
Slicing Example:
a=[“ram”,10,”shyam”,12.5]

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]

Notes By: Anand Sir | YouTube Channel: CODEITUP


LIST TRAVERSAL IN PYTHON
0 1 2 3 Forward Indexing
ram 10 shyam 12.5
-4 -3 -2 -1 Backward Indexing
First way:
a=[“ram”,10,”shyam”,12.5]
for i in a:
print(i)

Notes By: Anand Sir | YouTube Channel: CODEITUP


LIST TRAVERSAL IN PYTHON
Before going to second method of traversing the string, we need to
understand one method of string i.e. “len” function.
Len function is used to find the length of the list.
For example:
a=[1,2,3,”ram”,”shaym”,9.2]
print(len(a))
output:
6

Notes By: Anand Sir | YouTube Channel: CODEITUP


LIST TRAVERSAL IN PYTHON
0 1 2 3 Forward Indexing
ram 10 shyam 12.5
-4 -3 -2 -1 Backward Indexing

Second way
a=[“ram”,10,”shyam”,12.5]
for i in range(len(a)):
print(a[i])

Notes By: Anand Sir | YouTube Channel: CODEITUP


UPDATING LIST IN PYTHON
0 1 2 3 Forward Indexing
ram 10 shyam 12.5
-4 -3 -2 -1 Backward Indexing

a=[“ram”,10,”shyam”,12.5]
print(a[1])
a[1]=“Ramesh”
print(a[1])

Notes By: Anand Sir | YouTube Channel: CODEITUP


UPDATING LIST IN PYTHON
0 1 2 3 Forward Indexing
ram 10 shyam 12.5
-4 -3 -2 -1 Backward Indexing

a=[“ram”,10,”shyam”,12.5]
print(a)
del a[1]
print(a)

Notes By: Anand Sir | YouTube Channel: CODEITUP


LIST METHODS
1. len(list)
2. Max(list)
3. Min(list)
4. cmp(list1,list2)
5. list.append(obj)
6. list.count(obj)
7. list.index(obj)
8. list.insert(index,obj)
9. list.remove(obj)
10. list.reverse()
11. list.sort()
12. list.pop()
Notes By: Anand Sir | YouTube Channel: CODEITUP
LIST METHODS
1. len(list) => This method is used to find total length of the list.

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.

Case 2: What if string value comparison is there. In such case, it will


be compared as a to z in ascending order.

For Example: a=[“ram”,”shyam”]


print(max(a))
Output: shyam

Notes By: Anand Sir | YouTube Channel: CODEITUP


LIST METHODS
4. cmp(list1,list2) => This method is used to compare two lists.

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

Notes By: Anand Sir | YouTube Channel: CODEITUP


LIST METHODS
There are some certain cases for comparison for two lists:
Case 1:
a. If both the list contains integers, then the comparison is
done from left to right. If we get a larger number at any
particular index, that list becomes greater and further
comparison is stopped.
b. If all the elements in both the list are similar and one list
is larger in size the larger size list is greater.
c. And if both contains same value then the lists are
equal.

Notes By: Anand Sir | YouTube Channel: CODEITUP


LIST METHODS
Program implementation for Case 1:

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

Notes By: Anand Sir | YouTube Channel: CODEITUP


LIST METHODS
There are some certain cases for comparison for two lists:
Case 2:
a. When list contains multiple datatypes, in such case string is
considered to be greater than integer.
b. The comparison in case of multiple datatypes is done with
the sorted case of comparison.

Notes By: Anand Sir | YouTube Channel: CODEITUP


LIST METHODS
Program implementation for Case 2:

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

Notes By: Anand Sir | YouTube Channel: CODEITUP


LIST METHODS
5. append() => This method is used to append (add) a passed
object at the end of the list. Note that the object is added to the
last of the list.
Syntax: list.append(obj)
Example: a=[“ram”,”shyam”,”sita”,”gita”]
a.append(“mita”)
print(a)
output: ram, shyam, sita, gita, mita

Notes By: Anand Sir | YouTube Channel: CODEITUP


LIST METHODS
Program to implement append() method.
a=[]
for i in range(10):
x=input(“Enter Item to add in the list:”)
a.append(x)
print(a)
OR
for i in range(10):
print(a[i])
OR
for i in a:
print(i)
Notes By: Anand Sir | YouTube Channel: CODEITUP
LIST METHODS
6. count() => This method is used to count the frequency of a given
object.
Syntax: list.count(obj)

Example:
a=[“ram”,”shyam”,”ram”,”gita”]
x=a.count(“ram”)
print(“Frequency=“,x)

output: Frequency=2

Notes By: Anand Sir | YouTube Channel: CODEITUP


LIST METHODS
Ques: Program to implement count() method.
a=[]
for i in range(10):
x=input(“Enter Item to add in the list:”)
a.append(x)
x=input(“Enter value whose frequency you want:”)
f=a.count(x)
print(“Frequency of “,x,” is=“,f)

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

Notes By: Anand Sir | YouTube Channel: CODEITUP


LIST METHODS
8. insert(index,object)
This method is used to insert an object/value at the given index.
Syntax: list.insert(index,object)
Example:
a=[5,”ram”,10]
a.insert(2,“shyam”)
print(a)
output: 5, ram, shyam, 10

Notes By: Anand Sir | YouTube Channel: CODEITUP


LIST METHODS
Ques: Program to implement insert() method.
a=[]
for i in range(5):
x=input(“Enter Item to add in the list:”)
a.append(x)
val=input(“Enter value which you want to
insert:”)
pos=input(“Enter Position:”)
a.insert(pos,val)
print(a)

Notes By: Anand Sir | YouTube Channel: CODEITUP


LIST METHODS
9. remove(object)
This method is used to delete an object/value from the given list.
Note that it removes/deletes the first occurrence of the list.
Syntax: list.remove(object)
Example:
a=[5,”ram”,10,”ravi”,10]
a.remove(10)
print(a)
output: 5, ram, ravi, 10

Notes By: Anand Sir | YouTube Channel: CODEITUP


LIST METHODS
Ques: Program to implement insert() method.
a=[]
for i in range(5):
x=input(“Enter Item to add in the list:”)
a.append(x)
val=input(“Enter value which you want to remove:”)
a.remove(val)
print(a)

Notes By: Anand Sir | YouTube Channel: CODEITUP


LIST METHODS
10. reverse()
This method is used to reverse the elements present in the list in
place. Here the word, in place means that the list gets reversed itself.
Syntax: list.reverse()
Example:
a=[5,”ram”,10,”ravi”,10]
a.reverse()
print(a)
output: 10,ravi,10,ram,5

Notes By: Anand Sir | YouTube Channel: CODEITUP


LIST METHODS
Ques: Program to implement reverse() method.
a=[]
for i in range(5):
x=input(“Enter Item to add in the list:”)
a.append(x)
a.reverse()
print(a)

// Note: if you write here like:

c=a.reverse()
print(c)

The output will be None.


Notes By: Anand Sir | YouTube Channel: CODEITUP
LIST METHODS
11. sort()
This method is used to sort the elements present in the list in either
ascending order or in descending order. The list gets sorted itself. Note that the
sorting is done with the similar data type. That means your list should have
similar types of data otherwise it will show error. By Default the sorting is done in
ascending order.
Syntax: list.sort(reverse=False)
list.sort(reverse=True)
Example:
a=[5,2,8,3,7]
a.sort()
print(a)
output:
Notes By: Anand Sir | YouTube Channel: CODEITUP 2,3,5,7,8
LIST METHODS

Notes By: Anand Sir | YouTube Channel: CODEITUP


LIST METHODS
Ques: Program to implement sort() method.
a=[]
for i in range(5):
x=input(“Enter Item to add in the list:”)
a.append(x)
a.sort()
print(a)

// Note: if you write here like:

c=a.sort()
print(c)

The output will be none.


Notes By: Anand Sir | YouTube Channel: CODEITUP
LIST METHODS
12. pop()
This method is used to delete the last element from the list. Note that this
function deletes the last element from the list one by one.
Syntax: list.pop()
Example:
a=[5,2,8,3,7]
a.pop()
print(a)
output: 5,2,8,3

Notes By: Anand Sir | YouTube Channel: CODEITUP


LIST METHODS
a=[10,10,5,15,10,25]#creation of the list a.reverse()
print("Length of the list=",len(a))#finds the print("List after reversing the elements:",a)
length of the list
print("List after sorting in Ascending Order:")
print("Max Element of the list=",max(a))#finds a.sort()
the max value of the list
print("Min Element of the list=",min(a))#finds the print(a)
min value of the list print("List after sorting in Descending
print("Original List Elements are:",a) Order:")
a.append(35)#adds the value at the end of a.sort(reverse=True)
the list. print(a)
print("List Elements after appending 35:",a) print("List elements are removing the last
print("Frequency of 10=",a.count(10)) element:")
a.insert(2,100) a.pop()
print("After Inserting 100 at 2nd Index the list print(a)
is:",a) print("List elements are removing the last
a.remove(10) element again:")
print("After removing 10 from the list:",a) a.pop()
print(a)
Notes By: Anand Sir | YouTube Channel: CODEITUP
PROGRAMMING WITH LIST USING LIST METHODS
Programs List:

1. Program to find sum of elements of the List.


2. Program to count total number of odd and even numbers in the List.
3. Program to find sum of even numbers and product of odd number in List.
4. Program to search a number in the List.
5. Program to count frequency of a given number.
6. Program to find max number of the List.
7. Program to find min number in the List.
8. Program to reverse the List itself.
9. Program to find max/min in a list.
10. Program to find min & second min in a list.
11. Program to find max & second max in a list.
12. Program to insert a number at given index in an List.
13. Program to remove a given number from the List.
14. Program to shift each element one step right.
15. Program to shift each element one step Left.
16. Program to shift each element left by given number of steps.
17. Program to shift each element right by given number of steps.
Notes By: Anand Sir | YouTube Channel: CODEITUP
PROGRAMMING WITH LIST USING LIST METHODS
1. Program to find sum of elements of the 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
for i in range(size):
sum=sum+a[i]
print("Sum of List Elements=",sum)

Notes By: Anand Sir | YouTube Channel: CODEITUP


PROGRAMMING WITH LIST USING LIST METHODS
2. Program to count total number of odd and even numbers in the 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)
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)

Notes By: Anand Sir | YouTube Channel: CODEITUP


PROGRAMMING WITH LIST USING LIST METHODS
6. Program to find max number of the List.

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)

Notes By: Anand Sir | YouTube Channel: CODEITUP


PROGRAMMING WITH LIST USING LIST METHODS
7. Program to find min number of the List.

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)

Notes By: Anand Sir | YouTube Channel: CODEITUP


PROGRAMMING WITH LIST USING LIST METHODS
8. Program to reverse the List itself.

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)

Notes By: Anand Sir | YouTube Channel: CODEITUP


PROGRAMMING WITH LIST USING LIST METHODS
15. Program to shift each element one step left.

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)

Notes By: Anand Sir | YouTube Channel: CODEITUP


PROGRAMMING WITH LIST USING LIST METHODS
16. Program to shift each element right by given number of step.

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”)

Notes By: Anand Sir | YouTube Channel: CODEITUP


TUPLE
Difference 1

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”)

Notes By: Anand Sir | YouTube Channel: CODEITUP


TUPLE
Difference 2

The list is mutable whereas tuples are immutable.

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

List occupies more memory space as compared that tuple.

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

Notes By: Anand Sir | YouTube Channel: CODEITUP


TUPLE
Difference 4

List takes more time to execute as compared to tupels.

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)

Notes By: Anand Sir | YouTube Channel: CODEITUP


TUPLE
Creating Tuple

1. Using tuple display construct


tuple1=()
tuple2=(val1,val2,...)

2. Creating Empty Tuple


tuple1=tuple()

3. Creating single element tuple:


tuple1=(2) => this will not be a tuple but an integer class.
tuple2(2,) => this will be a tuple class.
#Here after the element you need to give , (Comma).

Notes By: Anand Sir | YouTube Channel: CODEITUP


TUPLE
Creating Tuple from Existing Sequences
We can also use a built-in tuple type object(tuple()) to create tuples from
sequences as per the syntax:
tuple1=tuple(<sequence>)

Sequence can be of any type like strings, lists and tuples.


#Creating tuple from strings.
>>>t1=tuple(‘world’)
>>>t1
(‘w’,’o’,’r’,’l’,’d’)

#Creating tuple from list


>>>list1=[1,2,3,4,5]
>>>tuple1=tuple(list1)
>>>tuple1
(1,2,3,4,5)
Notes By: Anand Sir | YouTube Channel: CODEITUP
TUPLE
Different types of tuple

Ways to create tuple The type of tuple


() This is an empty tuple
(7,) Tuple with one element
(1,2,3) Tuple of integers
(1,2,3.4,5) Tuple of numbers
(‘a’,’n’,’d’) Tuple of characters
(‘a’,1,2,3.5,’ram’) Tuple of mixed data type
(‘ram,’shyam’,’sita’) Tuple of string

Notes By: Anand Sir | YouTube Channel: CODEITUP


TUPLE
Traversing Tuple

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)

Notes By: Anand Sir | YouTube Channel: CODEITUP


TUPLE
Repeating or Replicating Tuples

tuple1=(1,2,3)
tuple2=tuple1*3
print(tuple2)
Output: (1,2,3,1,2,3,1,2,3)

Notes By: Anand Sir | YouTube Channel: CODEITUP


TUPLE
Slicing the Tuples Example 2:
tuple1=(10,11,12,13,14,15)
The syntax is: tuple2=tuple1[0:5:2]
T=[start:stop:step] print(tuple2)
Output: (10,12,14)
Example 1:
tuple1=(10,11,12,13,14,15)
tuple2=tuple1[3:5]
print(tuple2)
Output: (13,14)
Note: By default the step value is 1.

Notes By: Anand Sir | YouTube Channel: CODEITUP


TUPLE METHOD
1. len()

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

Notes By: Anand Sir | YouTube Channel: CODEITUP


TUPLE METHOD
2. max()

This method returns max value from the tuple.

Syntax : max(<tuple>)
Example: >>>a=(10,20,30,45,20,15)
>>>max(a)
45

Notes By: Anand Sir | YouTube Channel: CODEITUP


TUPLE METHOD
3. min()

This method returns min value from the tuple.

Syntax : min(<tuple>)
Example: >>>a=(10,20,30,45,20,15)
>>>min(a)
10

Notes By: Anand Sir | YouTube Channel: CODEITUP


TUPLE METHOD
4. index()

It returns the index of an existing element in the tuple.

Syntax : <tuple name>.index(<item>)


Example: >>>a=(10,20,30,45,20,15)
>>>a.index(30)
2

Notes By: Anand Sir | YouTube Channel: CODEITUP


TUPLE METHOD
5. count()

count() method returns the frequency of given element.

Syntax : <tuple name>.count(<item>)


Example: >>>a=(10,20,30,45,20,30)
>>>a.count(30)
2

Notes By: Anand Sir | YouTube Channel: CODEITUP


TUPLE METHOD
6. tuple()

This method is used as a constructor which is used to create tuples from


different types of values.

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)

Notes By: Anand Sir | YouTube Channel: CODEITUP


PYTHON
Tuples MANIPULATION in Python
Notes By: Anand Sir | YouTube Channel: CODEITUP
TUPLE MANIPULATION
Change Tuple Values
• Once a tuple is created, you cannot change its values because Tuples
are unchangeable, or immutable.
• But there is another way to achieve this. You can convert the tuple into a list,
change the list, and convert the list back into a tuple.

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)

Notes By: Anand Sir | YouTube Channel: CODEITUP


TUPLE MANIPULATION
Check if Item Exists

To determine if a specified item is present in a tuple use the “in” keyword.

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

Notes By: Anand Sir | YouTube Channel: CODEITUP


TUPLE MANIPULATION
Add Items

• 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)

Notes By: Anand Sir | YouTube Channel: CODEITUP


TUPLE MANIPULATION
Delete Tuple Elements
• Removing individual elements of the tuple is not possible. To remove entire
tuple, just use the del statement.
For example −
tuple1=(‘ram’,’shyam’,’sita’,’gita’)
print(tuple1)
del(tuple1)
print(“After Deleting Tuple:”)
print(tuple1)

Notes By: Anand Sir | YouTube Channel: CODEITUP


PYTHON
dictionary in Python
Notes By: Anand Sir | YouTube Channel: CODEITUP
DICTIONARY
A dictionary is a collection of elements which is unordered, changeable and
indexed. In Python dictionaries are written within curly brackets, and they have keys
and values. Means the dictionary contains two things first is the key and the second is
the Value.

Create and print a dictionary:

dict1 = {"brand": “Suzuki", "model": “Dzire", "year": 2020}


print(dict1)

Notes By: Anand Sir | YouTube Channel: CODEITUP


DICTIONARY
Accessing Items

• You can access the items of a dictionary by referring to its key name, inside
square brackets.

dict1 = {‘brand’: ’Suzuki’, ‘model’: ’Dzire’, ‘year’: 2020}


print(dict1)
x = dict1["model"]
print(x)

Notes By: Anand Sir | YouTube Channel: CODEITUP


DICTIONARY
Accessing Items

• There is also a method called get() for the same task.


dict1 = {‘brand’: ’Suzuki’, ‘model’: ’Dzire’, ‘year’: 2020}
print(dict1)
x = dict1["model"]
print(x)
y=dict1.get(“model”)
print(y)

Notes By: Anand Sir | YouTube Channel: CODEITUP


DICTIONARY
Loop through a dictionary

dict1 = {‘brand’: ’Suzuki’, ‘model’: ’Dzire’, ‘year’: 2020}


for x in dict1:
print(x)

This will print the index values.

OR

dict1 = {‘brand’: ’Suzuki’, ‘model’: ’Dzire’, ‘year’: 2020}


for x in dict1:
print(dict1[x])

This will print the values.


Notes By: Anand Sir | YouTube Channel: CODEITUP
DICTIONARY
We can use the values() function to return values of dictionary.

dict1 = {‘brand’: ’Suzuki’, ‘model’: ’Dzire’, ‘year’: 2020}


for x in dict1.values():
print(x)

It will print the values in the dictionary

While this print the keys:

dict1 = {‘brand’: ’Suzuki’, ‘model’: ’Dzire’, ‘year’: 2020}


for x in dict1:
print(x)

Notes By: Anand Sir | YouTube Channel: CODEITUP


DICTIONARY
We can also use items() function to return values of dictionary.

dict1 = {‘brand’: ’Suzuki’, ‘model’: ’Dzire’, ‘year’: 2020}


for x,y in dict1.items():
print(x,y)

It will print the values in the dictionary along with keys.

brand Suzuki
model Dzire
year 2020

Notes By: Anand Sir | YouTube Channel: CODEITUP


DICTIONARY
students_DB={}
#ask input from user or 'q' to exit
while True:
line = input('Please input the ID and name separated by comma or q to exit: ')
if line == 'q':
break
id, name = line.split(',')
students_DB.update({id:name})
#output
for x,y in students_DB.items():
print(x,y)
#Searching a key
key=input('Enter ID to search:')
if key in students_DB:
print('Key=',key,'Value=',students_DB[key])
else:
print('Key
Notes By: Anand Sir |not found:')
YouTube Channel: CODEITUP
DICTIONARY
Change Values
You can change the value of a specific item by referring to its key name:

For Example:
dict1 = {‘brand’:’Suzuki’,’model’:’Dzire’,’year’: 2020}
dict1[‘year’] = 2018
print(dict1)

Output:
‘brand:’Suzuki’, ‘model’:’Dzire’, ‘year’:’2018’

Notes By: Anand Sir | YouTube Channel: CODEITUP


DICTIONARY
Checking Whether a Key exists in the Dictionary

dict1 = {’brand’: ’Maruti’,’model’: ’Dzire’,’year’: 2020}


if ’model’ in dict1:
print("Yes, 'model' is one of the keys in the dictionary“)
else:
print(“No, ‘model’ is not one of the key in the dictionary.”)

Notes By: Anand Sir | YouTube Channel: CODEITUP


DICTIONARY
Adding new element in the Dictionary

dict1 = {’brand’: “Maruti",’model’: “Dzire",’year’: 2020}


print(dict1)
dict1[‘color’]=’White’
print(dict1)

Output:
{‘brand’:’Maruti’, ‘moel’:’Dzire’, ‘year’:2020} {‘brand’:’Maruti’, ‘model’:’Dzire’,
‘year’:2020,‘color’:’White’}

Notes By: Anand Sir | YouTube Channel: CODEITUP


DICTIONARY
Dictionary Functions
1. len()
2. get()
3. clear()
4. pop()
5. popitem()
6. values()
7. items()
8. copy()
9. fromkeys()
10. keys()
11. setdefault()
12. update()
Notes By: Anand Sir | YouTube Channel: CODEITUP
DICTIONARY
1. len()
This function is used to find Length of the Dictionary.

Program implementation

dict1 = {’brand’: “Maruti",’model’: “Dzire",’year’: 2020}


x=len(dict1)
print(“Length of the Dictionary=“,x)

Output:
Length of the Dictionary=3

Notes By: Anand Sir | YouTube Channel: CODEITUP


DICTIONARY
2. get()
There is a method called get() accessing the dictionary data.
dict1 = {‘brand’: ’Suzuki’, ‘model’: ’Dzire’, ‘year’: 2020}
print(dict1)
x = dict1["model"]
print(x)
y=dict1.get(“model”)
print(y)

Notes By: Anand Sir | YouTube Channel: CODEITUP


DICTIONARY
3. clear()
This keyword is also used to delete all the elements of the Dictionary. Note that it just
deletes the content of the dictionary so the dictionary is there but without an element.

Example:

dict1 = {’brand’: “Maruti",’model’: “Dzire",’year’: 2020}


print(dict1)
dict1.clear()
print(dict1)

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.

dict1 = {’brand’: “Maruti",’model’: “Dzire",’year’: 2020}


print(dict1)
dict1.pop(‘model’)
print(dict1)

Output:
{‘brand’:’Maruti’, ‘model’:’Dzire’, ‘year’:2020}
{‘brand’:’Maruti’,‘year’:2020}

Notes By: Anand Sir | YouTube Channel: CODEITUP


DICTIONARY
5. popitem()
This method removes the last element of the dictionary. But the in the versions before
3.7 it was used to remove the

dict1 = {’brand’: “Maruti",’model’: “Dzire",’year’: 2020}


print(dict1)
dict1.popitem()
print(dict1)

Output:
{‘brand’:’Maruti’, ‘model’:’Dzire’, ‘year’:2020}
{‘brand’:’Maruti‘,model’:’Dzire’}

Notes By: Anand Sir | YouTube Channel: CODEITUP


DICTIONARY
4. del keyword
This keyword removes the item with specified key name.

dict1 = {’brand’: “Maruti",’model’: “Dzire",’year’: 2020}


print(dict1)
del dict1[‘year’]
print(dict1)

Output:
{‘brand’:’Maruti’, ‘model’:’Dzire’, ‘year’:2020}
{‘brand’:’Maruti‘,model’:’Dzire’}

Notes By: Anand Sir | YouTube Channel: CODEITUP


DICTIONARY
5. del keyword (To Delete Whole Dictionary)
This keyword is also used to delete the dictionary itself.

Example:
dict1 = {’brand’: “Maruti",’model’: “Dzire",’year’: 2020}
print(dict1)
del dict1
print(dict1)

Output:
{‘brand’:’Maruti’, ‘model’:’Dzire’, ‘year’:2020}
Error

Notes By: Anand Sir | YouTube Channel: CODEITUP


DICTIONARY
6. values()
This function is used to print the key values in the dictionary.

dict1 = {‘brand’: ’Suzuki’, ‘model’: ’Dzire’, ‘year’: 2020}


for x in dict1.values():
print(x)

It will print the values in the dictionary

While this print the keys:

dict1 = {‘brand’: ’Suzuki’, ‘model’: ’Dzire’, ‘year’: 2020}


for x in dict1:
print(x)

Notes By: Anand Sir | YouTube Channel: CODEITUP


DICTIONARY
7. items()

dict1 = {‘brand’: ’Suzuki’, ‘model’: ’Dzire’, ‘year’: 2020}


for x,y in dict1.items():
print(x,y)

It will print the values in the dictionary along with keys.

brand Suzuki
model Dzire
year 2020

Notes By: Anand Sir | YouTube Channel: CODEITUP


DICTIONARY
8. copy()

dict1 = {‘brand’: ’Suzuki’, ‘model’: ’Dzire’, ‘year’: 2020}


x=dict1.copy()
print(x)

It will print the values in the dictionary along with keys.

brand Suzuki
model Dzire
year 2020

Notes By: Anand Sir | YouTube Channel: CODEITUP


DICTIONARY
9. fromkeys()

The fromkeys() method returns a dictionary with the specified keys and the specified value.

x = (‘firstkey', ‘secondkey', ‘thirdkey')


y=0
dict1 = dict.fromkeys(x, y)
print(dict1)

Notes By: Anand Sir | YouTube Channel: CODEITUP


DICTIONARY
10. setdefault()

• 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:

dict1 = {‘brand’: ’Suzuki’, ‘model’: ’Dzire’, ‘year’: 2020}


x = dict1.setdefault(“brand”,”Toyota”)
print(x)

Output: Since “brand” key is already present so it will return the value of this key.
Suzuki

Notes By: Anand Sir | YouTube Channel: CODEITUP


DICTIONARY
dict1 = {“brand”: ’Suzuki’, “model”: ”Dzire”, “year”: 2020}
x = dict1.setdefault(“place”,”New Delhi”)
print(x)

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.

Notes By: Anand Sir | YouTube Channel: CODEITUP


DICTIONARY
11. Update()

The update() method inserts the specified items to the dictionary.

dict1 = {‘brand’: ’Suzuki’, ‘model’: ’Dzire’, ‘year’: 2020}


dict1.update(“color”,”white”)
print(dict1)

Notes By: Anand Sir | YouTube Channel: CODEITUP


PYTHON
CHAPTER – 3
FUNCTIONS

Notes By: Anand Sir | YouTube Channel: CODEITUP


FUNCTIONS IN PYTHON
Functions are sub-programs i.e. part of the program that is used to perform
some special type of work.
Functions is usually divided into two parts:
1. Built in Functions / Library Functions
These are the functions that are already defined and we just use those
function for that particular work for which they have been made.
For Example: input(), int(), print() etc.

2. User defined function


These are the functions which is defined by the user for a specific meaning.
The code for this type of function is written by the user and every activity is
coded by the user and hence it is called user defined function.

Notes By: Anand Sir | YouTube Channel: CODEITUP


FUNCTIONS IN PYTHON
1. Built in Functions / Library Functions
The functions that we learnt in List / Tuples / Dictionary / Set that was just
used for the purpose for which they have been created are called Built-in or
Library functions.
For Example: len, max, min, insert, pop and many more.
Since we have already covered all the important list function in previous
chapter we will not cover it here and if you want to learn more about the built
in functions you may refer it from the chapter – 2 i.e. Py.thon Revision Tour 2

Notes By: Anand Sir | YouTube Channel: CODEITUP


FUNCTIONS IN PYTHON
2. User Defined Function
These are the functions which are created by the user for performing a
specific task. In other words we can say a function defined and used by the
user for some specific task is called user defined function.

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.

Notes By: Anand Sir | YouTube Channel: CODEITUP


FUNCTIONS IN PYTHON
Ques: Write a program to add two numbers using function
def add(): Let’s explain this program step
a=int(input(“Enter First Number:”)) by step:
1. The first line is used to
b=int(input(“Enter Second Number:”))
declare a function and here
c=a+b the name of the function is
print(“Addition=“,c) add().
2. Inside the add(), we have
#__main__ Here, __main__ (read as written the code to add two
add() underscore underscore main numbers.
underscore underscore ) is the
3. After completing the
section from where the
function, in order to execute
execution of the code starts.
the code inside the function
we need to call the function
which has been called using
add().
Notes By: Anand Sir | YouTube Channel: CODEITUP
FUNCTIONS IN PYTHON
Any user defined functions can be created using four ways:
1. No Argument No Return
2. With Argument No Return
3. No Argument With Return
4. With Argument With Return
Now, here the program that we have written in the previous slide is written using
No Argument No Return concept.

In order to understand further concept, we need to understand the concept of


argument and return.

Let’s discuss the concept of Argument first.

Notes By: Anand Sir | YouTube Channel: CODEITUP


FUNCTIONS IN PYTHON
Argument
Argument is the values which is passed to the function to operate upon.
In simpler words we can say that an argument is the value upon which the
functionality has to be performed. (Indirectly – The input in the question)

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.

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

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

Notes By: Anand Sir | YouTube Channel: CODEITUP


FUNCTIONS IN PYTHON
Ques: Write a program to check whether a given number is odd or even using
function with argument.
def check(a): Explanation
if a%2==0: Here a is the argument and obviously the
value upon which we have to work and
print(“Even”) check whether the number is odd or
even.
else:
In the main section here (the point from
print(“Odd”) where the execution of the program
#__main__ starts), we have taken the input of the
number to be checked for odd or even
num=int(input(“Enter Number:”)) and has stored in the variable num. Now,
check(num) the num variable has been passed to the
function where it’s copy has been stored
in variable named “a” and has been
checked for odd or even.

Notes By: Anand Sir | YouTube Channel: CODEITUP


FUNCTIONS IN PYTHON
Ques: Write a program to check whether a given number is prime or not using function with
argument.
def check(a): Explanation
count=0
Here a is the argument and obviously the
for i in range(1,a+1): value upon which we have to work and
if a%i==0: check whether the number is prime or
not.
count+=1
In the main section here (the point from
if count==2: where the execution of the program
print(“Prime Number”) starts), we have taken the input of the
else: number to be checked for prime and has
stored in the variable num. Now, the num
print(“Not Prime Number”) variable has been passed to the function
#__main__ where it’s copy has been stored in
num=int(input(“Enter Number:”))
variable named “a” and has been
checked for prime and the result will be
check(num) displayed.
Notes By: Anand Sir | YouTube Channel: CODEITUP
FUNCTIONS IN PYTHON
Ques: Write a program to find sum of elements of a list using function with argument.
def sum(a,size):
sum=0 Explanation
for i in range(size): Here list “a” is the argument and
obviously the value upon which we have
sum=sum+a[i]
to work and find the sum of the list
print(“Sum=“,sum) elements.
#__main__ In the main section here (the point from
a=[] where the execution of the program
size=int(input(“Enter size of list:”)) starts), we have taken the input of the size
of the list and stored in variable named
for i in range(size): “size” and then accepted the list called
val=int(input(“Enter Value”)) “a”. Now this list “a” and it’s size is being
a.append(val) passed to the function to operate upon
and find the size of the list.
sum(a,size)
Notes By: Anand Sir | YouTube Channel: CODEITUP
FUNCTIONS IN PYTHON
Return
Now after clearing the concept of “Argument”, we will move towards the “return”
concept.
Definition: Return is the value which a function return to it’s calling place. In simpler
words, we can say that return is the final calculated value that means the result.

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.

Notes By: Anand Sir | YouTube Channel: CODEITUP


FUNCTIONS IN PYTHON
Ques: Write a program to find addition of two numbers using function with return.
def addition():
Explanation
a=int(input(“Enter First Number:”))
Here we have no argument that
b=int(input(“Enter Second Number:”)) means the value upon which we
c=a+b have to work and hence the values
of a and b is being input. After that
return c the sum is being stored in c and
since this is the final answer, we are
#__main__ returning this.
value=addition() In __main__ section, we have just
print(“Addition=“,value) called the addition function and
since the function will return a value,
we are storing that value to value
variable and in the very next line we
are printing the value of variable
“value”.
Notes By: Anand Sir | YouTube Channel: CODEITUP
FUNCTIONS IN PYTHON
So, till now, we have learnt everything about argument and return. Now as we
have already done lots of program, we now, will be doing the same program in
the four ways i.e.
a) No argument No return
b) With argument No return
c) No argument with return
d) With argument With return

Notes By: Anand Sir | YouTube Channel: CODEITUP


FUNCTIONS IN PYTHON
Ques: Program to add two numbers using function. (All Four Ways)

#No Argument No Return #With Argument No Return


def add(): def add(a,b):
a=int(input(“Enter First Number:”)) c=a+b
b=int(input(“Enter Second Number:”)) print(“Addition=“,c)
c=a+b #__main__
print(“Addition=“,c) a=int(input(“Enter First Number:”))
#__main__ b=int(input(“Enter Second Number:”))
add() add()

Notes By: Anand Sir | YouTube Channel: CODEITUP


FUNCTIONS IN PYTHON
#No Argument With Return #With Argument With Return
def add(): def add(a,b):
a=int(input(“Enter First Number:”)) c=a+b
b=int(input(“Enter Second Number:”)) return c
c=a+b #__main__
return c a=int(input(“Enter First Number:”))
#__main__ b=int(input(“Enter Second Number:”))
addition=add() addition=add()
print(“Sum of Numbers=“,addition) print(“Sum of Numbers=“,addition)

Notes By: Anand Sir | YouTube Channel: CODEITUP


FUNCTIONS IN PYTHON
Ques: Program to check whether a number is odd or even. (All Four Ways)

#No Argument No Return def check(a):


def check(): if a%2==0:
a=int(input(“Enter Number To Check:”)) print(“Even”)
if a%2==0: else:
print(“Even”) print(“Odd”)
else:
print(“Odd”) #__main__
#__main__ a=int(input(“Enter Number to Check:”))
check() check(a)

Notes By: Anand Sir | YouTube Channel: CODEITUP


FUNCTIONS IN PYTHON
Ques: Program to check whether a number is odd or even. (All Four Ways)

#No Argument with Return def check(a):


def check(): if a%2==0:
a=int(input(“Enter Number To Check:”)) return “even”
if a%2==0: else:
return “even” return “odd”
else:
return “odd” #__main__
#__main__ a=int(input(“Enter Number to Check:”))
answer=check() answer=check(a)
print(“The Number is:”,answer) print(“The Number is:”,answer)

Notes By: Anand Sir | YouTube Channel: CODEITUP


FUNCTIONS IN PYTHON
Ques: Program to check whether a number is prime or composite. (All Four Ways)

#No Argument No Return #With Argument No Return


def check(): def check(a):
a=int(input(“Enter Number To Check:”)) count=0
count=0 for i in range(1,a+1):
for i in range(1,a+1): if a%i==0:
if a%i==0: count+=1
count+=1 if count==2:
if count==2: print(“Prime”)
print(“Prime”) else
else print(“Composite”)
print(“Composite”) #__main__
#__main__ a=int(input(“Enter Number to Check:”))
check() check(a)
Notes By: Anand Sir | YouTube Channel: CODEITUP
FUNCTIONS IN PYTHON
Ques: Program to check whether a number is prime or composite. (All Four Ways)

#No Argument With Return #With Argument With Return


def check(): def check(a):
a=int(input(“Enter Number To Check:”)) count=0
count=0 for i in range(1,a+1):
for i in range(1,a+1): if a%i==0:
if a%i==0: count+=1
count+=1 if count==2:
if count==2: return “Prime”
return “Prime” else
else return “Composite”
return “Composite” #__main__
#__main__ a=int(input(“Enter Number to Check:”))
answer=check() answer=check(a)
print(“The Number is”,answer)
Notes By: Anand Sir | YouTube Channel: CODEITUP
print(“The Number is”,answer)
FUNCTIONS IN PYTHON
Ques: Program to find sum of list element. (All Four Ways)

#No Argument No Return #With Argument No Return


def sum(): def sum(a,size):
a=[] sum=0
size=int(input(“Enter size of list:”)) for i in range(size):
sum=0 sum+=a[i]
for i in range(size): print(“Sum of List Element=“,sum)
val=int(input(“Enter Number:”)) #__main__
a.append(val) a=[]
for i in range(size): size=int(input(“Enter size of list:”))
sum+=a[i] for i in range(size):
print(“Sum of List Element=“,sum) val=int(input(“Enter Number:”))
#__main__ a.append(val)
sum() sum(a,size)
Notes By: Anand Sir | YouTube Channel: CODEITUP
FUNCTIONS IN PYTHON
Ques: Program to find sum of list element. (All Four Ways)

#No Argument with Return #With Argument With Return


def sum(): def sum(a,size):
a=[] sum=0
size=int(input(“Enter size of list:”)) for i in range(size):
sum=0 sum+=a[i]
for i in range(size): return(sum)
val=int(input(“Enter Number:”)) #__main__
a.append(val) a=[]
for i in range(size): size=int(input(“Enter size of list:”))
sum+=a[i] for i in range(size):
return(sum) val=int(input(“Enter Number:”))
#__main__ a.append(val)
result=sum() result=sum(a,size)
print(“Sum of list element=“,result)
Notes By: Anand Sir | YouTube Channel: CODEITUP
print(“Sum of list element=“,result)
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()

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:

Notes By: Anand Sir | YouTube Channel: CODEITUP


FUNCTIONS IN PYTHON
What if same name local & global variable is there?
def example():
a=10
print(“Value of local a=“,a) # it will print the value of local variable a
#__main__
a=20
print(“Value of Global a=“,a) # it will print global variable a
example()

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.

Notes By: Anand Sir | YouTube Channel: CODEITUP


FUNCTIONS IN PYTHON
What if we want to strict local function not to create same name variable in local
scope?
If we want to restrict a function to create same name variable and use the global
variable then we use the keyword “global” inside the function. For example:

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=5): #correct


def example(a,b=5,c=10) #correct
def example(a,b=5,c) #incorrect as b has default argument so c must
have default argument as per the rule.
def example(a,b,c=5,d=5) #correct
def example(a,b=5,c,d=10) #incorrect all the variables starting from b must
have default argument
def example(a=1,b=4,c=30,d) #incorrect as d should also have default
argument
Notes By: Anand Sir | YouTube Channel: CODEITUP
FUNCTIONS IN PYTHON
Named Argument
We know that argument are sequential i.e. the first passed value goes to first
variable, second passed value goes to second and so on i.e. sequential. Now
suppose, we have to send the argument not sequentially but as per our wish. In this
case we used the concept of Named Argument. Program implementation:

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

Notes By: Anand Sir | YouTube Channel: CODEITUP


FUNCTIONS IN PYTHON
Actual Argument Vs Formal Argument
When we call a function and from there we pass the values, then at that place
these are called actual argument. Now when these values are accepted in
function, the same is called formal arguments.

def example(a,b): #here a & b are formal argument


print(“Value of a=“,a,”Value of b=“,b)
#__main__
example(5,10)#here 5 and 10 are actual argument, even we had taken input in
some variable viz x and y and calling the function, that time as well x and y will be
called as actual argument.

Notes By: Anand Sir | YouTube Channel: CODEITUP


PYTHON
chapter 4
python modules

Notes By: Anand Sir | YouTube Channel: CODEITUP


PYTHON MODULE
Ques: What is a library?
Ans: A library is a collection of modules that is used to cater specific type of need or
application.
Some commonly used Python libraries are as below:
1. Python standard library: This library comes in-built with python distribution. Some
commonly used modules of python standard library are:
a. math module
Provides mathematical functions to support different type of calculation.
b. cmath module
Provides math mathematical functions related to complex number.
c. random module
Provides functions for generating random numbers.

Notes By: Anand Sir | YouTube Channel: CODEITUP


PYTHON MODULE
d. statistics module: Provides mathematical statistic functions.
e. Urllib module: Provides URL handling functions.

2. Numpy Library: This library provides some advance math functionality along with
tools to create and manipulate arrays.

3. SciPy Library: This is basically used for scientific calculations.

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.

Structure of Python Module:


➢ docstring: triple quoted string for documentation purpose.
➢ variable and constants
➢ classes: template/blueprint to create object
➢ object: Instance of class.
➢ statement: Instructions
➢ functions: to perform task.

Notes By: Anand Sir | YouTube Channel: CODEITUP


PYTHON MODULE
#tempconversion.py
“““Module to convert temperature from Celcius to Fahrenheit and vice verse.”””
#functions
def to_celcius(x):
“““returns: x converted to centigrade”””
return 5*(x-32)/9.0
def to_fahren(x):
“““returns: x converted to fahrenheit”””
return 9*x/5.0+32
#constants
FREEZING_C=0.0
FREEZING_F=32.0

Notes By: Anand Sir | YouTube Channel: CODEITUP


PYTHON MODULE
To get help for a module, you first need to import that and then use help command
to get help for that module.
>>>import tempconversion
>>>help(tempconversion)

General docstring conventions are:


➢ First letter of the first line is a capital letter.
➢ Second line is blank line.
➢ Rest of the details begin from third line.

Notes By: Anand Sir | YouTube Channel: CODEITUP


PYTHON MODULE
Importing Module
The import statement can be used in tow forms:
a. to import entire module
import <module>
b. to import selected object from a module
from <module> import <object>

Notes By: Anand Sir | YouTube Channel: CODEITUP


PYTHON MODULE
a. Importing Entire Module
statement can be used to import entire modules and even for importing
selected items. For importing entire module we write following statement.
For Example:

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

Notes By: Anand Sir | YouTube Channel: CODEITUP


PYTHON MODULE
b. Importing Selected objects from a Module
We have also provision for importing some selected items from the module
instead of everything.
For Example:
>>>from <module> import <object_name>

To import single object:


>>>from math import pi
Now, the constant pi can be used directly without prefixing
it with module name.
>>>print(pi)
will work and not
>>>print(math.pi)
Notes By: Anand Sir | YouTube Channel: CODEITUP
PYTHON MODULE
b. Importing Selected objects from a Module
To import multiple objects:
>>>from math import sqrt,pow
Now you can write statements without prefixing module name.
>>>pow(2,3)
8.0
>>>sqrt(25)
5.0

If you want to import all the objects from the module:


>>>from math import *
Now the advantage is that you need not to prefix the module
name for using the resources.
Notes By: Anand Sir | YouTube Channel: CODEITUP
PYTHON MODULE
Namespace
A namespace is a space that holds a bunch of names. To understand the
concept of namespace we may see the following example.
Suppose we have three same name student in class 10, 11 and 12 and
suppose the name of student is “Ravi”. When they are on their classes, there is
no problem when we call their name but during the school prayer time, when
we will call their name then the ambiguity starts and the now the question is
Ravi from which class???
For every module, Python creates a namespace having its name similar to that
of module’s name. That is the name of module time’s namespace is also time.
While using import <module>, a new namespace is created and hence we
need to use <module>.<object> whereas in case of from<module>
import<object> no new namespace is created and hence we can directly
use the resource.

Notes By: Anand Sir | YouTube Channel: CODEITUP


PYTHON MODULE
Namespace

>>>import math
>>>math.sqrt(25)
5.0

>>>from math import sqrt


>>>sqrt(25)

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.

Notes By: Anand Sir | YouTube Channel: CODEITUP


PYTHON MODULE
Namespace

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.

Notes By: Anand Sir | YouTube Channel: CODEITUP


PYTHON MODULE
Maths Functions
1. oct(<integer>) – returns octal string for given number i.e. 00+octal equivalent.
2. hex(<integer>) – returns hex string for given numbers i.e. 0x+hex equivalent.
3. int(<number>) – truncates the fractional part from the number and returns the
whole number only. It is also used to convert the input to integer format.
For Example: int(“1234”) will convert the string 1234 to integer format.
4. round(<number>,no of digits) – returns number rounded to given number of
digits.
Let’s do it programmatically:

Notes By: Anand Sir | YouTube Channel: CODEITUP


PYTHON MODULE
Maths Functions Program Demonstration
a=int(input(“Enter Number”))
print(“The number entered by you is”,a)
oc=oct(a)
he=hex(a)
print(“Value in Octal=“,oc)
print(“Value in Hexadecimal=“,he)
b=int(input(“Enter a real number”))
val=int(b)
val1=round(b,2)
print(“Value entered by you is”,b)
print(“Value after removing fractional part=“,val)
print(“Value after rounding off=“,val1)
Notes By: Anand Sir | YouTube Channel: CODEITUP
PYTHON MODULE
String Function
1. <str>.join(<string iterable>) – Joins a string or character after each member of
string iterator.
2. <str>.split(<string/char>) – splits a string based on given string or character and
returns a list containing split strings as members.
3. <str>.replace(<word to be replace>,<replace word>) – replaces a word or
part of the string with another in the given string.

Notes By: Anand Sir | YouTube Channel: CODEITUP


PYTHON MODULE
<str>.join()
(i) If the string bases iterator is a string the n the <str> is inserted after every
character of the string. For example:
In[]: “*”.join(“Hello”)
Out[]: ‘H*e*l*l*0’
In[]: “***”.join(“Hello”)
Out[]: ‘H***e***l***l***o’
(ii) If the string based iterator is a list or tuple of strings then, the given
string/character is joined with each member of the list or tuple. But the tuple of list
must have all member as strings otherwise Python will raise an error.
In[]: “$$”.join([“hello”,”world”])
Out[]: ‘hello$$world’
In[]: “$$”.join((“hello”,”to”,”python”)
Out[]: ‘hello$$to$$python’
Notes By: Anand Sir | YouTube Channel: CODEITUP
PYTHON MODULE
<str>.split()
(i) If you do not provide any argument to split then by default it will split the given
string considering whitespace as separator.
In[]: “Python is incredible”.split()
Out[]: [‘Python’, ’is’, ‘incredible’]
In[]: “Python is incredible”.split(“ “)
Out[]: [‘Python’, ’is’, ‘incredible’]

(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’]

Notes By: Anand Sir | YouTube Channel: CODEITUP


PYTHON MODULE
<str>.replace()
This function replaces one string with another string.
For Example:
In[]: “Python is incredible”.replace(“Python”,”Programming”)
Out[]: ‘Programming is incredible’

Notes By: Anand Sir | YouTube Channel: CODEITUP


PYTHON MODULE
Encryption and Decryption
def encrypt(str,key):
return key.join(str)
def decrypt(str,key):
return str.split(key)

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.

Notes By: Anand Sir | YouTube Channel: CODEITUP


PYTHON MODULE
Random Module
Example:
Generate random floating point number between 0.0 to 1.0.
>>>import random
>>>print(random.random())
2. Generate a random floating point number between range lower to upper. For
this you need to multiply random() with (upper-lower)+lower
To generate a number between 50 – 100.
>>>import random
>>>print(random.random()*(100-50)+50)
3. Generate random integer between 30-50.
>>>import random
>>>print(random.randint(30,50))
Notes By: Anand Sir | YouTube Channel: CODEITUP
PYTHON MODULE
Output Question
1. What will be the output of the following code:
import random
print(15+random.random()*5)
(i)17.dddd, 19.dddd, 20.dddd, 15.dddd
(ii)15.dddd, 17.dddd, 19.dddd, 18.dddd
(iii) 14.dddd, 16.dddd, 18.dddd, 20.dddd
(iv)15.dddd, 15.dddd, 15.dddd, 15.dddd

Notes By: Anand Sir | YouTube Channel: CODEITUP


PYTHON MODULE
Output Question
2. What could be the minimum possible and maximum possible numbers by the
following code?
import random
print(random.randint(3,10)-3)

Notes By: Anand Sir | YouTube Channel: CODEITUP


PYTHON MODULE
Output Question
3. In a school fest, three randomly chosen students out of 100 students(having roll
number 1-100) have to present bouquets to the guests. Help the school
authorities choose three students randomly.
import random
student1=random.randint(1,100)
student2=random.randint(1,100)
student3=random.randint(1,100)
print(“3 students are”,student1,student2,student3)

Notes By: Anand Sir | YouTube Channel: CODEITUP


PYTHON MODULE
Using urllib and webbrower modules
Python offers you module urlib using which you can send http requests and
receive the result from withing your python program.
The functions are:
Name of Function Work
urllib.request.urlopen(<URL>) Opens a website
<urlopen’s returnval>.read() returns the html or the source code of the
given url opened via urlopen()
<urlopen’ return val>.getcode() returns HTTP status code where 200 – All
Okay,301,302 means some kind of
redirection.
<urlopen’s return val>.headers Stores metadata about the opened URL
<urlopen’s return val>.info() returns same information as stored by
headers
<copy>.geturl() retruns the url string
Notes By: Anand Sir | YouTube Channel: CODEITUP
PYTHON MODULE
Program to open a website along within your Python Program
import urllib
import webbrowser
weburl=urllib.request.urlopen(‘https://www.facebook.com/’)
html=weburl.read()
data=weburl.getcode()
url=weburl.geturl()
hd=weburl.headers
inf=weburl.info()
print(“The URL is:”,url)
print(“HTTP status code is:”,data)
print(“Headers returned is:”,hd)
print(“The info() returned :”,inf)
print(“Now opening the url”,url)
webbrowser.open_new(url)
Notes By: Anand Sir | YouTube Channel: CODEITUP
PYTHON MODULE
Creating Library/Package
1. Most of the times library and package terms are used interchangeably.
2. A package is a collection of Python modules under a common namespace,
created by placing different modules on a single directory along with some
special file (such as __init__.py).
3. In order to make a Library/package, a special file namely __init__.py must also
be stored in the same folder, even if the file __init__.py is empty.
4. A library may have one or more packages/sub-packages.

Notes By: Anand Sir | YouTube Channel: CODEITUP


PYTHON MODULE
Structure of a Package
Python packages are basically collections of modules under common
namespace. This common namespace is created via a directory that contains all
related modules. Note that Python files in the directory/folder must contain a file
__init.py__ in order to be recognized as packages.

Notes By: Anand Sir | YouTube Channel: CODEITUP


PYTHON MODULE
Procedure for Creating Packages
In order to create a package, we need to follow the steps:
Decide the basic structure of the package. So lets the structure of our package is:
computer_science_syllabus
__init__.py
details.py
Python
__init__.py
csclass11.py
csclass12.py
IP
__init__.py
ipclass11.py
ipclass12.py
Notes By: Anand Sir | YouTube Channel: CODEITUP
PYTHON MODULE
Procedure for Creating Packages
2. Create the directory structure having folders with names package and sub-
packages. Inside this folder, crate the files/modules. But note that until we create
__init__.py file, this won’t become a package.
3. Now create __init__.py file in package and sub-package folders. This files
needs to be replicated in every folder/sub-folder.
4. Now we need to associate this package with Python’s site-package folder of
current python installation.

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.

Notes By: Anand Sir | YouTube Channel: CODEITUP


PYTHON
chapter 5
file handling

Notes By: Anand Sir | YouTube Channel: CODEITUP


DATA FILE HANDLING
Introduction
What so ever programming we did so far, we just write the program see the
output and done. These output we never store. So, if you just close your IDLE and
come back to IDLE, you won’t find the output. Now, moving ahead and if you
want to store the output of your program in a form of file, it can be done using
the concept of File Handling/Data File Handling. File Handling / Data File
Handling is used to store the output of the program in a file so that it could be
used at a later date.
The data files are the files that store data pertaining to a specific application, for
later use.
The three types of file are:
1. Text File
2. Binary File
3. CSV file
We will be learning all the above type of files in coming slides.
Notes By: Anand Sir | YouTube Channel: CODEITUP
DATA FILE HANDLING
Text Files

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

Notes By: Anand Sir | YouTube Channel: CODEITUP


DATA FILE HANDLING
Opening a File
So we know that we have to open a file first to operate upon. Here in Data File
Handling, we first need to open a file and even we need to decide earlier that
what has to be done with the file. There are many mode i.e. the reason why you
open a file. There are following file opening modes using which we can open a file.
r – read mode
w – write mode
a – append mode
r+ - read and write both (In this case file must be there other it will show error)
w+ - both reading and writing operation
a+ - write and read (appending)

There are many other modes but most of them are of no use as per our syllabus.

Notes By: Anand Sir | YouTube Channel: CODEITUP


DATA FILE HANDLING
Opening a File
Syntax: fileobj=open(“file_name”,mode)

Example: file1=open(“data.txt”) – If no mode is given, it is Read mode.

file1=open(“data.txt”,”r”) – Opening a file in read mode.

file1=open(“data.txt”,”w”) – Opening a file in write mode

file1=open(“data.txt”,”a”) – Opening a file in append mode

Notes By: Anand Sir | YouTube Channel: CODEITUP


DATA FILE HANDLING
Opening a File
Syntax: fileobj=open(“file_name”,mode)

Example: file1=open(“data.txt”,”r”) – Opening a file in read mode.

file1=open(“c:\\mydata\\data.txt”,”r”) – Opening file with path

file1=open(r“c:\mydata\data.txt”,”r”) – Opening a file in read mode

Closing a file
A file can be closed by just calling the close function using the file object. For
example: file1.close()

Notes By: Anand Sir | YouTube Channel: CODEITUP


DATA FILE HANDLING
Reading a File Content
So if we want to read the contents from a file then we use the following three methods to
read a file’s content (text file). Reading the file content means that we will open a file
and read the content (whatsoever is written/stored in the file).
1. read() – This method reads entire file / given number of bytes from a file.
Syntax: 1. f=open(“abc.txt”,”r”)
x=f.read(5) # Here now x is a string with 5 character
from the file
2. f=open(“abc.txt”,”r”)
x=read() # Here x is a string containing everything
from the file.
So, from the above example, it is clear that when you provide argument to read function
i.e. the number of bytes, then only that number of bytes are read from the file whereas if
you are not providing the number of arguments then it read all the characters from the
file. We will be doing it programmatically in the coming slides.

Notes By: Anand Sir | YouTube Channel: CODEITUP


DATA FILE HANDLING
Reading a File Content
We have three methods to read a file’s content (text file).
2. readline() – This method reads a line of input, or max n number of bytes if specified.
Syntax: 1. f=open(“abc.txt”,”r”)
x=f.readline() # Here now x is a string, containing 1
line from the file
The function readline, reads one line of the text at a time if no arguments are passed. In
case we pass the number of argument, that number of bytes from that line will be read.

Notes By: Anand Sir | YouTube Channel: CODEITUP


DATA FILE HANDLING
Reading a File Content
We have three methods to read a file’s content (text file) all at once in list format
separated with \n i.e. end of the line. Simply means that every sentence will be one list
item.
3. readlines() – This method reads all line from the file but in list format.
Syntax: 1. f=open(“abc.txt”,”r”)
x=f.readlines() # Here now x is a list, containing all
lines from the file

Notes By: Anand Sir | YouTube Channel: CODEITUP


DATA FILE HANDLING
Code Snippet 1 story.txt
myfile = open(r’E:\story.txt’,’r’) If you want to start, it’s never late.
str=myfile.read(10) If you are thinking to quit, think why
you started.
print(str)
I have not failed. I have just found
10000 ways that won’t work.
Output:
If you wan

Notes By: Anand Sir | YouTube Channel: CODEITUP


DATA FILE HANDLING
Code Snippet 2 story.txt
myfile = open(r’E:\story.txt’,’r’) If you want to start, it’s never late.
str=myfile.read(10) If you are thinking to quit, think why
you started.
str1=myfile.read(10)
I have not failed. I have just found
print(str1)
10000 ways that won’t work.

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.

Notes By: Anand Sir | YouTube Channel: CODEITUP


DATA FILE HANDLING
Code Snippet 5 story.txt
Program to read whole file using If you want to start, it’s never late.
readline method. 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
10000 ways that won’t work.
str=“ “
while str:
str=myfile.readline()
print(str,end=‘ ‘)
myfile.close()

Notes By: Anand Sir | YouTube Channel: CODEITUP


DATA FILE HANDLING
Code Snippet 6 story.txt
myfile = open(r’E:\story.txt’,’r’) If you want to start, it’s never late.
s=myfile.readlines() If you are thinking to quit, think why
print(s) you started.

myfile.close() I have not failed. I have just found


10000 ways that won’t work.

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.

Notes By: Anand Sir | YouTube Channel: CODEITUP


DATA FILE HANDLING
Code Snippet 7 story.txt
Program to print length of a file called If you want to start, it’s never late.
story.txt
If you are thinking to quit, think why
myfile = open(r’E:\story.txt’,’r’) you started.
s=myfile.read()
I have not failed. I have just found
size=len(s) 10000 ways that won’t work.
print(“Size=“,size)
myfile.close()

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

Explanation: readlines() function reads the data in


list format with every element ending with \n i.e.
new line. So, s is a list containing 3 elements(as
story.txt contains 3 lines)
Notes By: Anand Sir | YouTube Channel: CODEITUP
DATA FILE HANDLING
Writing data into files
Writing data to file refers to storing some textual information (as of now we are using text
file that’s why I have written textual information) to a file. For the same purpose we have
the following two built-in function.
a. write() : Writes a string to the file.
Syntax: <filehandler>.write(str1)
b. writelines(): Writes all string in the list as lines to the file.
Syntax: <filehandler>.writelines()

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.

Notes By: Anand Sir | YouTube Channel: CODEITUP


DATA FILE HANDLING
Code Snippet Demo to show the use of write() function
Program 1
f=open("abc.txt","w") #here we are opening a file abc.txt in write mode
f.write(“Hello this is file handling.”) #this string will be written to the file abc.txt
print(“File Created Successfully”) #this message will be displayed to the user
f.close() #here we are closing the file.

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.

Notes By: Anand Sir | YouTube Channel: CODEITUP


DATA FILE HANDLING
Code Snippet Demo to show the use of write() function
Program 2
In the example just before this, we stored a string as per our wish. Now, we will ask a
string from the use, store it to a variable and then will write this to the file i.e abc.txt
Simply means that the name given by use will be stored to the variable and then stored
in the file. The code for the same is:

f=open("abc.txt","w")
name=input(“Enter Your Name:”)
f.write(name)
f.close()

Notes By: Anand Sir | YouTube Channel: CODEITUP


DATA FILE HANDLING
Demo Program for write() function
Like in the previous code we inputted just name in the same manner, we can input multiple
variables from user and can store it to the file. But we have to keep this in our mind that using
write() function we can write only string data, so if we are inputting some other types of data,
we need to convert that to string format and as well we have to combine all the input as a
single string before writing it to the file. See the code below and you will get everything.
For example:
Program 3
f=open("abc.txt","w")
roll=int(input("Enter Your Roll:"))
name=input("Enter Your Name:")
marks=int(input("Enter Marks:"))
f.write(str(roll)+"\n"+name+"\n"+str(marks)) #here all the input has been converted to sting as
well clubbed into a single unit.
print("File Created Successfully..")
f.close()
Notes By: Anand Sir | YouTube Channel: CODEITUP
DATA FILE HANDLING
So, as of now, we have stored string and variable’s value to the text file. Now, if you
want, we can add multiple values in the file by just using loop concept. Refer the
program below

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.

Notes By: Anand Sir | YouTube Channel: CODEITUP


DATA FILE HANDLING
In program 4 the name will be stored one after other without any space or not in the
next line. Every time we can store ‘\n’ to put everything in the next line.

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

Notes By: Anand Sir | YouTube Channel: CODEITUP


DATA FILE HANDLING
Program to Write roll, name and marks of 5 students in a file called student.txt
Code Snippet 6
f=open(“student.txt”,”w”)
for i in range(5):
roll=int(input(“Enter Roll:”))
name=input(“Enter Name:”)
marks=float(input(“Enter Marks:”))
rec=str(roll) + ”,” + name + ”,” + str(marks) + ”\n”
f.write(rec)
f.close()

Notes By: Anand Sir | YouTube Channel: CODEITUP


DATA FILE HANDLING
Code Snippet 7
#Appending data to a pre-existing file.
f=open(“student.txt”,”a”)
for i in range(5):
roll=int(input(“Enter Roll:”))
name=input(“Enter Name:”)
marks=float(input(“Enter Marks:”))
rec=str(roll) + ”,” + name + ”,” + str(marks) + ”\n”
f.write(rec)
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.

Notes By: Anand Sir | YouTube Channel: CODEITUP


DATA FILE HANDLING
Program to Input roll,name & marks “n” times and store to that in a file student.txt.
Program 8
def writetofile():
f=open(r"f:\student.txt","w")
while True:
roll=int(input("Enter Roll Number:"))
name=input("Enter Your Name:")
marks=int(input("Enter Marks:"))
f.write(str(roll)+"\t"+name+"\t"+str(marks)+"\n")
choice=input("Y->Enter More\nN->No\nEnter Your Choice:")
if choice=='n' or choice=='N':
break
print("File Created Successfully..")
f.close()
#__main__
Notes By: Anand Sir | YouTube Channel: CODEITUP
writetofile()
DATA FILE HANDLING
As till now, we have completed the write() function. Now the next function for the same
task is writelines() function which write the list of string to the file. Refer the program
below for the same:

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

Notes By: Anand Sir | YouTube Channel: CODEITUP


DATA FILE HANDLING
The Flush() function
Python automatically flushes the files when closing them that means flush() function is
automatically called when close() function is called. The flush function forces the writing
of data on disc .

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.

Notes By: Anand Sir | YouTube Channel: CODEITUP


DATA FILE HANDLING
strip()/rstrip()/lstrip()
1. Removing EOL ‘\n’ character
f=open(“story.txt”,”r”)
line=f.readline()
line=line.rstrip(‘\n’)

2. Removing leading whitespaces


f=open(“story.txt”,”r”)
line=f.readline()
line=line.lstrip()

Notes By: Anand Sir | YouTube Channel: CODEITUP


DATA FILE HANDLING
Count total number of Characters in a file

f=open("student1.txt","r")
data=f.read()
print("Length=",len(data))

Count total number of words

f=open("student1.txt","r")
data=f.readlines()
print(data)
print("Length=",len(data))

Notes By: Anand Sir | YouTube Channel: CODEITUP


DATA FILE HANDLING
Binary File
So far we have gone through the text files and now we will move forward with
Binary Files. The files which are present in the form or 0 & 1 (internally) are referred to as
Binary Files. Binary consist of only two digits 0 & 1.
When you will open any picture / any image / any video in notepad, you will find
a strange format. This format is called Binary Format.
Now, we will be learning about the next format i.e. Binary format. Binary files are
usually faster and can store different variety of data.
So, now we will be learning that how we store binary format data to a file and
how to extract the data as well.
We have two concepts here, first one is Pickling and second one is Unpickling.

Notes By: Anand Sir | YouTube Channel: CODEITUP


DATA FILE HANDLING
Pickling and Unpickling
Pickling refers to the process of converting structure (Such as list, dictionary etc.)
to a byte stream before writing to the file.

Structure Pickling Byte Stream

Notes By: Anand Sir | YouTube Channel: CODEITUP


DATA FILE HANDLING
Pickling and Unpickling
UnPickling refers to the process of converting byte stream to structure (Such as list,
dictionary etc.) before writing to the file.

Byte Stream UnPickling Structure (List or Dictionary)

Notes By: Anand Sir | YouTube Channel: CODEITUP


DATA FILE HANDLING
Pickle Module
Python provides a module called Pickle Module which consist two function which is used
to read or write data to the file.
1. dump() : This function is used to dump (write) the content to the file.
Syntax: structure = pickle.dump(<structure>,fileobject)

2. load(): This function is used to read data from a file.


Syntax: structure=pickle.load(fileobject)

Notes By: Anand Sir | YouTube Channel: CODEITUP


DATA FILE HANDLING
Program Implementation
Ques: Write list elements in a file called abc.data
import pickle
def write():
f=open(“abc.dat”,”wb”)
list1=[‘Computer Science’,’Math’,’Physics’,’Chemistry’]
pickle.dump(list1,f)
f.close()
#__main__
write()
print(“Data Successfully Inserted”)

Notes By: Anand Sir | YouTube Channel: CODEITUP


DATA FILE HANDLING
Program Implementation
Ques: Write list/dictionary elements in a file called abc.data
import pickle
def write():
f=open(“abc.dat”,”wb”)
l=[‘Computer Science’,’Math’,’Physics’,’Chemistry’]
d={‘Name’:’Ram’,’Marks’:100,’Subject’:’Computer Science’}
pickle.dump(l,f)
pickle.dump(d,f)
f.close()
#__main__
write()
print(“Data Successfully Inserted”)
Notes By: Anand Sir | YouTube Channel: CODEITUP
DATA FILE HANDLING
if flag==0: def read():
print("Roll Number Not Found...") f=open("abc.dat","rb")
def maxnumber(): r=pickle.load(f)
max=0 for i in r:
x=[] print(i)
f=open("abc.dat","rb") f.close()
r=pickle.load(f) #__main__
for i in r: write()
if i[2]>max: print("Data Written Successfully...")
max=i[2] read()
x=i print("Program Ends Now...")
print("The student with Maximum search()
Number is:",x) maxnumber()
Notes By: Anand Sir | YouTube Channel: CODEITUP
DATA FILE HANDLING
Pickle Module
Program to Store / Writing data to a Binary File [One Student’s Data]
import pickle
f=open(“student.dat”,”wb”)
data=[]
roll=int(input("Enter Roll Number:"))
name=input("Enter Your Name:")
marks=int(input("Enter Your Marks:"))
data=[roll,name,marks]
pickle.dump(data,f) #dump function is used to write data to binary file.
print(“Data Written Successfully..”)

Notes By: Anand Sir | YouTube Channel: CODEITUP


DATA FILE HANDLING
Pickle Module
Program to Store / Writing data to a Binary File [Multiple Student’s Data]
import pickle
f=open(“student.dat”,”wb”)
record=[]
data=[]
while True:
roll=int(input("Enter Roll Number:"))
name=input("Enter Your Name:")
marks=int(input("Enter Your Marks:"))
data=[roll,name,marks]
record.append(data)
choice=int(input(“Do you wish to continue \n1->Yes\n2->No :”))
if choice==2:
break
pickle.dump(record,f) #dump function is used to write data to binary file.
print(“Data Written Successfully..”)

Notes By: Anand Sir | YouTube Channel: CODEITUP


DATA FILE HANDLING
Program Implementation def read():
Ques: Write list/dictionary elements in a file f=open(“abc.dat”,”rb”)
called abc.data as well as read them
lst=pickle.load(f)
back.
dct=pickle.load(f)
import pickle
print(lst)
def write():
print(dct)
f=open(“abc.data”,”wb”)
f.close()
l=[‘Computer Science’, ’Math’,
’Physics’,’Chemistry’] #--main__
d={‘Name’:’Ram’,’Marks’:100,’Subj write()
ect’:’Computer Science’} print(“File written Successfully...”)
pickle.dump(l,f) read()
pickle.dump(d,f) print(“File reading done successfully...)
f.close()

Notes By: Anand Sir | YouTube Channel: CODEITUP


DATA FILE HANDLING
Program Implementation if ch==‘n’ or ch==‘N’:
Ques: Appending records in a file called break;
abc.data
pickle.dump(record,f)
import pickle
def read():
record=[]
f=open(“abc.dat”,”rb”)
def write():
s=pickle.load(f)
f=open(“abc.dat”,”ab”)
for i in s:
while True:
print(i)
rno=int(input(“Roll:”))
#__main__
name=input(“Name:”)
write()
marks=int(input(“Marks:”))
print(“Data written Successfully....”)
data=[rno,name,marks]
read()
record.append(data)
print(“Program Over....”)
ch=input(“Y->Yes\nN->No”)
Notes By: Anand Sir | YouTube Channel: CODEITUP
DATA FILE HANDLING
Program to Write/Search/Find Max in a if ch=='n' or ch=='N':
Binary file. break
import pickle
pickle.dump(record,f)
record=[] f.close()
def write(): def search():
f=open("abc.dat","wb")
rno=int(input("Enter Roll Number to
while True: Search:"))
rno=int(input("Enter Roll Number:")) f=open("abc.dat","rb")
name=input("Enter Your Name:") flag=0
marks=int(input("Enter Marks:")) r=pickle.load(f)
data=[rno,name,marks] for i in r:
record.append(data) if i[0]==rno:
ch=input("Y->Yes\nN->No\nEnter print(i)
Your choice:") flag=1
Notes By: Anand Sir | YouTube Channel: CODEITUP break
DATA FILE HANDLING
Program to Update Data in Binary File else:
def update(): f.seek(0)
rno=int(input("Enter Roll to Update:")) pickle.dump(r,f)
f=open("abc.dat","rb+") print("Record Updated Successfully...")
flag=0 f.close()
r=pickle.load(f) read()
for i in r:
if i[0]==rno:
i[1]=input("Input New Name:")
flag=1
break
if flag==0:
print("Roll Number Not Found...")
f.close()
Notes By: Anand Sir | YouTube Channel: CODEITUP
DATA FILE HANDLING
CSV Files
➢ CSV stands for Comma Separated Value.
➢ A CSV (Comma Separated Values) format is one of the most simple and common ways
to store tabular data i.e in the form of rows or columns.
➢ To represent a CSV file, it must be saved with the .csv file extension. When you will open
this file in Ms-Excel, it will be shown in the format of rows and columns whereas when
opening the same file in text editor viz notepad, the data will be represented with
comma (,) as a separator.
➢ It is used to handle large amount of data and this data can be imported to any other
application.
➢ CSV module is used to read/write in csv files.
➢ So, the first line of the program becomes: import csv
➢ To write to a CSV file in Python, we can use the csv.writer() function.
The csv.writer() function returns a writer object that converts the user's data into a
delimited string. This string can later be used to write into CSV files using
the writerow() function. Let's take an example.
Notes By: Anand Sir | YouTube Channel: CODEITUP
DATA FILE HANDLING
Program to write data into a csv file “data.csv”. Explanation
import csv Here, in this program we have written a
def write(): function called write() in which first of all we
have opened a file called “data.csv”. Now
with open("data.csv","w") as fobj: after that we have created a writer object
obj=csv.writer(fobj) so as to write data to csv file.
obj.writerow(["Roll","Name","Marks"])
while True: Now, using the writerow() heading of the csv
roll=int(input("Enter Roll Number:")) file has been created and the heading are
roll, name and marks and all will appear as
name=input("Enter Name:") the headings
marks=int(input("Enter Marks:"))
data=[roll,name.upper(),marks]
Now, an infinite loop i.e. while True has been
obj.writerow(data) created which will be terminated by the
choice=int(input("\1->More Record\n2->End ?")) user when he/she doesn’t want to enter
more records.
if choice==2:
break
write() Now, one by one records are being asked
and being written to csv file using writerow
print("Data Written
Notes By: Anand Successfully...")
Sir | YouTube Channel: CODEITUP
method.
DATA FILE HANDLING
Program to write and read data from a file “data.csv”. def read():
import csv with open("data.csv","r") as fobj:
def write(): obj=csv.reader(fobj)
with open("data.csv","w“, newline=“”) as fobj: for i in obj:
obj=csv.writer(fobj) print(i)
obj.writerow(["Roll","Name","Marks"]) write()
while True: read()
roll=int(input("Enter Roll Number:")) print("Data Written Successfully...")
name=input("Enter Name:")
marks=int(input("Enter Marks:"))
data=[roll,name.upper(),marks]
obj.writerow(data)
choice=int(input("\1->More Record\n2->End ?"))
if choice==2:
break
Notes By: Anand Sir | YouTube Channel: CODEITUP
DATA FILE HANDLING
def read():
import csv
with open("abc.csv","r") as f:
def write():
obj=csv.reader(f)
with open("abc.csv","w",newline='') as f:
for i in obj:
obj=csv.writer(f)
print(i)
obj.writerow(['Roll','Name','Marks'])
def searchroll():
while True:
roll=int(input("Enter Roll to Search:"))
roll=int(input("Enter Roll Number:"))
flag=0
name=input("Enter Name:")
with open("abc.csv","r") as f:
marks=int(input("Enter Marks:"))
obj=csv.reader(f)
data=[roll,name,marks]
next(obj)
obj.writerow(data)
for i in obj:
choice=int(input("1->Yes\n2->No\nEnter Your Choice:"))
if int(i[0])==roll:
if choice==2:
print(i)
break
flag=1
print("File Created Successfully...")
if flag==0:
Notes By: Anand Sir | YouTube Channel: CODEITUP
print("Roll Number Not Found")
DATA FILE HANDLING
def max(): Explanation:
with open("abc.csv","r") as f: This is the whole and sole of CSV file handling program as
in this program we have seen:
obj=csv.reader(f)
a. How to write data to CSV file.
maximum=0
b. How to read data from CSV file.
next(obj)
c. How to search for a data in CSV file.
for i in obj:
d. How to find Max value in a CSV file.
if int(i[2])>maximum:
maximum=int(i[2])
maxdata=i
print("Student with Max Number\n",maxdata)
#__main__
write()
read()
searchroll()
max()

Notes By: Anand Sir | YouTube Channel: CODEITUP


PYTHON
chapter 6
recursion
Notes By: Anand Sir | YouTube Channel: CODEITUP
RECURSION
Introduction
Recursion is a programming technique in which a function calls itself directly or
indirectly.
To understand the concept of recursion, please go through the example as below:

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.

Notes By: Anand Sir | YouTube Channel: CODEITUP


RECURSION
Introduction
a. Direct Recursion
def abc():
..........
..........
abc()

b. def abc():
.........
xyz()
def xyz():
........
abc()

Notes By: Anand Sir | YouTube Channel: CODEITUP


RECURSION
Introduction
Recursion is a technique for solving a large computational problem by repeatedly
applying the same procedure(s) to reduce it to successively smaller problems. A recursive
procedure has two parts: one or more base cases and a recursive step.

Right or Sensible Recursive code:


Right or Sensible Recursive code is the one that fulfills the following requirements:
a. It must have a case, whose result is known or computed without any recursive calling –
It is called the base case. The Base Case must be reachable.
b. It also have Recursive case, where by function calls itself.

* Recursion limit is platform dependent and can be set via sys.setrecursionlimit(limit)

Notes By: Anand Sir | YouTube Channel: CODEITUP


RECURSION
Introduction
Recursion is a technique for solving a large computational problem by repeatedly
applying the same procedure(s) to reduce it to successively smaller problems. A recursive
procedure has two parts: one or more base cases and a recursive step.

Not Right or Not Sensible Recursive code:


Consider a case:
def func1():
print(“Hello Func2”)
func2()
def func2():
print(“Hello Func1”)
func1()

Notes By: Anand Sir | YouTube Channel: CODEITUP


RECURSION
Ques 1. Print from 1 to n. Ques 2. Print from 1 to n.

def compute(i,n): sum=0


if i==n+1: def compute(i,n):
return global sum
else: if i==n+1:
print(i) return
compute(i+1,n) else:
n=int(input("Enter Number:")) sum=sum+i
compute(1,n) compute(i+1,n)
n=int(input("Enter Number:"))
compute(1,n)
print("Sum from 1 to n=",sum)

Notes By: Anand Sir | YouTube Channel: CODEITUP


RECURSION
Ques 3. Print from 1 to n (Alternate way)

def sum(num):
if num==1:
return 1
else:
return(num+sum(num-1))
n=int(input("Enter Number:"))
print("Sum=",sum(n))

Notes By: Anand Sir | YouTube Channel: CODEITUP


PYTHON
chapter 17
society law & ethics

Notes By: Anand Sir | YouTube Channel: CODEITUP


SOCIETY LAW & ETHICS
Introduction
Today’s era is information age as most of our work is technology influenced, no
matter whether what we are doing, we are definitely technologically influenced. For
example whether we are booking hotel online, reserving tickets, purchasing items online,
making online payment etc. This rapid increase in technological influenced society issues
and problems related to society, ethics and law.
With the increase of technology concentric activities many new terms has came
into existence viz intellectual property rights, plagiarism, cybercrime, cyberlaw, e-waste
management etc.

Notes By: Anand Sir | YouTube Channel: CODEITUP


SOCIETY LAW & ETHICS
Ethical Issues
Today’s era is information age as most of our work is technology influenced.
Information is the means to acquire knowledge. Information is created by someone and it
takes a lots of efforts for the same. There are many ethical issues involved:
Some common ethical issues are:
i) Intellectual property rights
ii) Plagiarism
iii) Digital property rights

Notes By: Anand Sir | YouTube Channel: CODEITUP


SOCIETY LAW & ETHICS
Ethical Issues
i) Intellectual property rights
Information is created by someone with lots of efforts and he/she is called the
owner of the information. Even while creating the information it may cost a certain
amount to develop that. Hence, the owner of the information is the real owner of the
information and hence the owner has the right to protect his/her intellectual property
rights. In order to protect one’s intellectual property rights one can get the information
copyrighted or patented or use trademark.
Intellectual property right gives the following advantages: Encourages the creator
to generate/create new idea without a fear of stealing. In such a way, all will be creating
new ideas/concepts without worrying the issue of stealing of information.

Notes By: Anand Sir | YouTube Channel: CODEITUP


SOCIETY LAW & ETHICS
Ethical Issues

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.

Make a note of it that Plagiarism is an “Offence”.


Notes By: Anand Sir | YouTube Channel: CODEITUP
SOCIETY LAW & ETHICS
Ethical Issues

iii) Digital Property Rights


Digital Property (called as Digital Asset as well) is any information regarding you or
created by you which is present in the digital form either online or in any electronic
storage device. For example: your email account, fb account, insta account (any social
media account), shopping account, photo or video sharing account, gaming account,
online storage account, website or blogs pertaining to you etc.
Digital property rights lie with the owner and only he/she can decide who all and
in what form can his/her digital asset may be used by other, whether by making payments
or by buying the license.

Threats to Digital Property:


a. One can use crack tool to use your digital asset without paying.
b. Stealing and plagiarizing codes of your digital properties.

Notes By: Anand Sir | YouTube Channel: CODEITUP


SOCIETY LAW & ETHICS
Open Source & Software Licence
Open Source Software is used to refer to those software whose licenses do not impose
much conditions. It give us the free to use the software for any purpose as well as
redistribute it.

Free Software / Open Source Software


Free Software
Free software means the software which is freely accessible and can be freely used,
distributed and no payments are needed to be made for free software.

Notes By: Anand Sir | YouTube Channel: CODEITUP


PYTHON
chapter 16
Interface with mysql

Notes By: Anand Sir | YouTube Channel: CODEITUP


INTERFACE WITH MYSQL
Introduction
Before coming to this chapter make sure that you know Python well as well as
MySQL well as we are going to combine the features of both the things together to create
a project.
First of all we need to understand what is a project? So, a project is a kind of small
application/software we will be creating in order to evaluate our knowledge and logical
capability/understanding to create a project/application in future using the Python &
MySQL.
So, if you are ready to start creating a project these three things should be installed
on you computer:
a. Python IDLE
b. MySQL
c. Python MySQL Connector
In order to cerate a database connectivity between Python and MySQL, we first
need to install Python IDLE, then MySQL and then MySQL connector. MySQL connector is
used to connect Python with MySQL so that we can store/retrieve the data from Python as
front-end and MySQL as back-end.
Notes By: Anand Sir | YouTube Channel: CODEITUP
INTERFACE WITH MYSQL
Introduction
Before creating a project, you must be aware about the concept of software
development. Whenever, you are going to create a software, there are always two parts
there:
a. Front-end
b. Back-end
Front-end part of the software development refers to the programming language you are
going to choose for the software development like c/c++/java/python/.net technologies
and many more. Here according to our syllabus, we need to take Python as our front-end.

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.

Notes By: Anand Sir | YouTube Channel: CODEITUP


Setting MySQL Path
Before installing MySQL, you must ensure the following:
1. Python is installed and your computer is connected with Internet.
2. Python is present on System’s PATH. This is done while installing Python IDLE, that time a
check box is shown for whether you want to include that into the path or not. So, you
need to check that on.
3. Now, if you don’t remember it, just to check whether python is on system’s path or not
follow the step:
Just go to command prompt (cmd) and type python. If >>> appears, means
python is already there in the path.

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

Notes By: Anand Sir | YouTube Channel: CODEITUP


INTERFACE WITH MYSQL
Setting MySQL Path
So, when you checked and found that python’s path is not set, there are two ways
using which you can se it.
1. By uninstalling Python and re-installing with “Add Python to Path” button ticked.
2. You need to include your python to the System Path and Steps for Adding the same is :
a. In the Windows search bar, type in python.exe, but don’t click on it in the menu.
Instead, right-click on it, and select Open file location.
b. Now Open File location and copy the address.
c. Now right click on This PC > Properties > Advanced System Settings > Advanced
> Environment variable.
d. Here under “User Variable” section there will be a variable called Path. Click on
it and then click on edit.
e. Now another window will appear and in this window you have to click on
“New” and then paste the address you just copied.

Notes By: Anand Sir | YouTube Channel: CODEITUP


INTERFACE WITH MYSQL
Setting MySQL Path
f. Now you need to add “scripts” as well, so here again you have to click on “New” and
paste the path as:
C:\Users\anand\AppData\Local\Programs\Python\Python39
And in the same add \scripts, so it will become like:
C:\Users\anand\AppData\Local\Programs\Python\Python39\scripts\
and now click on OK to all opened dialog boxes.

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.

Notes By: Anand Sir | YouTube Channel: CODEITUP


INTERFACE WITH MYSQL
Installing MySQL Connector
Now after confirmation path Python is available in the Path variable, we can now
proceed to install MySQL connector.
1. Now you have to find the path of “python” by searching “Python.exe” and then
right click and then click on “Open File Location”.
2. Now copy the path, and paste to file explorer.
3. Here, Just find Script folder and open that.
4. Now here, you have to hold shift button and then right click and then you will find
an option, “Open PowerShell window here” and then run the following one
command and it will be installed automatically.
pip install mysql-connector-python

Notes By: Anand Sir | YouTube Channel: CODEITUP


INTERFACE WITH MYSQL
1. Writing a Program to Check whether connection was successful or not?
import mysql.connector as c
con=c.connect(host=“localhost”, user=“root”, passwd=“pass”, database=“dname”)
if con.is_connected():
print(“Successfully Connected...”)
Explanation:
1st Line - In order to connect python with mysql we need a package called
“mysql.connector”. So the first line would be importing the same.
import mysql.connector as c
2nd Line – Here we need to create a connection object using the built-in function
connect. This requires host, user, password and database name. (It is the syntax of
connect function and we have to follow it.)
Here for host you have to use “localhost” (always), for user “root” (always), now
the password here is the password for opening your MySQL and database name is the
name of database which you have created in MySQL and want to get connected with.
3 rd Line – It is used for checking that whether we have successfully connected to the
Notes By: Anand Sir | YouTube Channel: CODEITUP
database or not.
INTERFACE WITH MYSQL
1. Inserting data in table

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"))

Notes By: Anand Sir | YouTube Channel: CODEITUP


INTERFACE WITH MYSQL
2. Inserting data in table (Insertion till User
wants to insert)

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"))

Notes By: Anand Sir | YouTube Channel: CODEITUP


INTERFACE WITH MYSQL
3. Updating Data of Table
import mysql.connector as c
con=c.connect(host="localhost",
user="root",
passwd="123456",
database="school")
cursor=con.cursor()
query="update emp set salary=75000 where code=103"
cursor.execute(query)
con.commit()
print("Data Updated Successfully...")

Notes By: Anand Sir | YouTube Channel: CODEITUP


INTERFACE WITH MYSQL
4. Deleting data from table
import mysql.connector as c
con=c.connect(host="localhost",
user="root",
passwd="123456",
database=“anand")
cursor=con.cursor()
query="delete from emp where code=104"
con.execute(query)
con.commit()
print("Updation Successfull..")

Notes By: Anand Sir | YouTube Channel: CODEITUP


INTERFACE WITH MYSQL
Extracting Data from Database
To extract data from the table there are three functions provided by Python:
a. fetchone() = Fetches one record at a time
b. fetchmany() = Fetches given number of records, if the given number of records
is more than the rows available in the table, then it returns all the data otherwise just
given number of rows.
c. fetchall() = Fetches all the data from the table.

Notes By: Anand Sir | YouTube Channel: CODEITUP


INTERFACE WITH MYSQL
5. Selecting Data (Fetchall)
import mysql.connector as c
con=c.connect(host="localhost",
user="root",
passwd="123456",
database="school")
cursor=con.cursor()
cursor.execute("select * from emp")
record=cursor.fetchall() #record here is a tuple, so it can be printed using iteration.
for i in record:
print(i)
print("Total Number of records=",cursor.rowcount)

Notes By: Anand Sir | YouTube Channel: CODEITUP


INTERFACE WITH MYSQL
5. Selecting Data (Fetchmany)
import mysql.connector as c
con=c.connect(host="localhost",
user="root",
passwd="123456",
database="summerproject")
cursor=con.cursor()
cursor.execute("select * from employee")
data=cursor.fetchmany(2)
for i in data:
print(i)
print("Total number of rows=",cursor.rowcount)
data=cursor.fetchmany(2)
for i in data:
print(i)
print("Total number of rows=",cursor.rowcount)
Notes By: Anand Sir | YouTube Channel: CODEITUP
MYSQL
mcq test
Notes By: Anand Sir | YouTube Channel: CODEITUP
MYSQL TEST

Ques 1: Define Database in One Line?

Notes By: Anand Sir | YouTube Channel: CODEITUP


MYSQL TEST

Ques 2: What is the Full Form of RDBMS ?

Notes By: Anand Sir | YouTube Channel: CODEITUP


MYSQL TEST

Ques 3: MySQL is a type of which DBMS ?

Notes By: Anand Sir | YouTube Channel: CODEITUP


MYSQL TEST

Ques 4: In RDBMS a table is called .......... ?

Notes By: Anand Sir | YouTube Channel: CODEITUP


MYSQL TEST

Ques 5: In RDBMS rows are called as


.........?

Notes By: Anand Sir | YouTube Channel: CODEITUP


MYSQL TEST

Ques 6: In RDBMS columns are called as


........ ?

Notes By: Anand Sir | YouTube Channel: CODEITUP


MYSQL TEST

Ques 7: Give example of two RDBMS ?

Notes By: Anand Sir | YouTube Channel: CODEITUP


MYSQL TEST
Ques 8: What is the Cardinality in the
following table ?
Roll Name Father’s Name Address Date of Birth
01 A AA AAA 08-Feb-2021
02 B BB BBB 08-Feb-

Notes By: Anand Sir | YouTube Channel: CODEITUP


MYSQL TEST
Ques 9: What is the Degree in the following
table ?
Roll Name Father’s Name Address Date of Birth
01 A AA AAA 08-Feb-2021
02 B BB BBB 08-Feb-

Notes By: Anand Sir | YouTube Channel: CODEITUP


MYSQL TEST

Ques 10: SQL Commands are divided into


how many parts?

Notes By: Anand Sir | YouTube Channel: CODEITUP


MYSQL TEST

Ques 11: Name three different types of SQL


Commands.

Notes By: Anand Sir | YouTube Channel: CODEITUP


MYSQL TEST

Ques 12: What is the Full Form of DDL?

Notes By: Anand Sir | YouTube Channel: CODEITUP


MYSQL TEST

Ques 13: What is the Full Form of DML?

Notes By: Anand Sir | YouTube Channel: CODEITUP


MYSQL TEST

Ques 14: What is the Full Form of DCL?

Notes By: Anand Sir | YouTube Channel: CODEITUP


MYSQL TEST

Ques 15: What is the Full Form of TCL?

Notes By: Anand Sir | YouTube Channel: CODEITUP


MYSQL TEST

Ques 16: Give Example of any 2 DDL


Commands?

Notes By: Anand Sir | YouTube Channel: CODEITUP


MYSQL TEST

Ques 17: Give Example of any 2 DML


Commands?

Notes By: Anand Sir | YouTube Channel: CODEITUP


MYSQL TEST

Ques 18: Give Example of any 2 DCL/TCL


Commands?

Notes By: Anand Sir | YouTube Channel: CODEITUP


MYSQL TEST

Ques 19: What is Constraint?

Notes By: Anand Sir | YouTube Channel: CODEITUP


MYSQL TEST

Ques 20: What is Primary Key Constraint?

Notes By: Anand Sir | YouTube Channel: CODEITUP


MYSQL TEST

Ques 21: What is Unique Key Constraint?

Notes By: Anand Sir | YouTube Channel: CODEITUP


MYSQL TEST

Ques 22: What is NOT NULL Constraint?

Notes By: Anand Sir | YouTube Channel: CODEITUP


MYSQL TEST

Ques 23: What is Default Constraint?

Notes By: Anand Sir | YouTube Channel: CODEITUP


MYSQL TEST

Ques 24: What is Check Constraint?

Notes By: Anand Sir | YouTube Channel: CODEITUP


MYSQL TEST

Ques 25: What is Foreign Key Constraint?

Notes By: Anand Sir | YouTube Channel: CODEITUP


MYSQL TEST

Ques 26: Which command is used to create


a database?

Notes By: Anand Sir | YouTube Channel: CODEITUP


MYSQL TEST

Ques 27: Which command is used to open a


database / go inside a database?

Notes By: Anand Sir | YouTube Channel: CODEITUP


MYSQL TEST

Ques 28: Which command is used to see


the list of databases?

Notes By: Anand Sir | YouTube Channel: CODEITUP


MYSQL TEST

Ques 29: Which command is used to see


the list of tables?

Notes By: Anand Sir | YouTube Channel: CODEITUP


MYSQL TEST

Ques 30: Which command is used to create


a table?

Notes By: Anand Sir | YouTube Channel: CODEITUP


MYSQL TEST

Ques 31: Which command is used to delete


a table?

Notes By: Anand Sir | YouTube Channel: CODEITUP


MYSQL TEST

Ques 32: Which command is used to modify


/ make changes in a table structure?

Notes By: Anand Sir | YouTube Channel: CODEITUP


MYSQL TEST

Ques 33: Which command is used to modify


/ make changes in a table data?

Notes By: Anand Sir | YouTube Channel: CODEITUP


MYSQL TEST

Ques 34: Which command is used to insert


rows into tables?

Notes By: Anand Sir | YouTube Channel: CODEITUP


MYSQL TEST

Ques 35: Which command is used to show


the structure of the table?

Notes By: Anand Sir | YouTube Channel: CODEITUP


MYSQL TEST

Ques 36: Which command is used to delete


rows from a table?

Notes By: Anand Sir | YouTube Channel: CODEITUP


MYSQL TEST

Ques 37: What is the difference between


DROP & Delete command?

Notes By: Anand Sir | YouTube Channel: CODEITUP


MYSQL TEST

Ques 38: What is the of char datatype if no


size is given?

Notes By: Anand Sir | YouTube Channel: CODEITUP


MYSQL TEST

Ques 39: Alter table command uses


............. keyword for adding a new field.

Notes By: Anand Sir | YouTube Channel: CODEITUP


MYSQL TEST

Ques 40: Alter table command uses


............. keyword for removing field.

Notes By: Anand Sir | YouTube Channel: CODEITUP


MYSQL TEST

Ques 41: Alter table command uses


............. keyword for renaming a field.

Notes By: Anand Sir | YouTube Channel: CODEITUP


MYSQL TEST

Ques 42: Alter table command uses


............. keyword for resizing/changing the
datatype of a field.

Notes By: Anand Sir | YouTube Channel: CODEITUP


MYSQL TEST

Ques 43: Which clause is used to sort the


data while extracting the data using select
command?

Notes By: Anand Sir | YouTube Channel: CODEITUP


MYSQL TEST

Ques 44: Which clause is used to extract


data in a range of values with select
command?

Notes By: Anand Sir | YouTube Channel: CODEITUP


MYSQL TEST

Ques 45: Which clause is used to extract


data in from a set of values with select
command?

Notes By: Anand Sir | YouTube Channel: CODEITUP


MYSQL TEST

Ques 46: For pattern matching we use


............... clause?

Notes By: Anand Sir | YouTube Channel: CODEITUP


MYSQL TEST

Ques 47: For pattern matching we two


characters ............ & ..............

Notes By: Anand Sir | YouTube Channel: CODEITUP


MYSQL TEST

Ques 48: In pattern matching % represents


...................... character.

Notes By: Anand Sir | YouTube Channel: CODEITUP


MYSQL TEST

Ques 49: In pattern matching _ represents


...................... character.

Notes By: Anand Sir | YouTube Channel: CODEITUP


MYSQL TEST

Ques 50: To extract data from multiple


tables, we use the concept of .............

Notes By: Anand Sir | YouTube Channel: CODEITUP


MYSQL TEST

Ques 51: What are Aggregate functions?

Notes By: Anand Sir | YouTube Channel: CODEITUP


MYSQL TEST

Ques 52: Give 2 examples of Aggregate


Functions.

Notes By: Anand Sir | YouTube Channel: CODEITUP


MYSQL TEST

Ques 53: What is the difference between


count() and count(*)?

Notes By: Anand Sir | YouTube Channel: CODEITUP


MYSQL TEST

Ques 54: To group similar types of data we


use which clause?

Notes By: Anand Sir | YouTube Channel: CODEITUP


MYSQL TEST

Ques 55: When using group by clause,


which clause is used to impost a condition?

Notes By: Anand Sir | YouTube Channel: CODEITUP


MYSQL TEST

Ques 56: A .................. is a logical unit of


work on the database that must succeed or
fail entirely?

Notes By: Anand Sir | YouTube Channel: CODEITUP


MYSQL TEST

Ques 57: Cartesian Product is also known


as .............. join ?

Notes By: Anand Sir | YouTube Channel: CODEITUP


MYSQL TEST

Ques 58: How much storage space does


DATETIME requires?

Notes By: Anand Sir | YouTube Channel: CODEITUP


MYSQL TEST

Ques 59: Which function is used to count


total number of rows in a table?

Notes By: Anand Sir | YouTube Channel: CODEITUP


MYSQL
mcq test
Notes By: Anand Sir | YouTube Channel: CODEITUP
MYSQL TEST

Ques 01: Can we have multiple primary key


in one table?

Notes By: Anand Sir | YouTube Channel: CODEITUP


MYSQL TEST

Ques 02: Can we have multiple unique key


in one table?

Notes By: Anand Sir | YouTube Channel: CODEITUP


MYSQL TEST

Ques 03: What is candidate key?

Notes By: Anand Sir | YouTube Channel: CODEITUP


MYSQL TEST

Ques 04: What is alternate key?

Notes By: Anand Sir | YouTube Channel: CODEITUP


MYSQL TEST

Ques 05: Storing same data in many places


is called ..................?

Notes By: Anand Sir | YouTube Channel: CODEITUP


MYSQL TEST

Ques 06: To create a foreign key ..............


keyword is used.

Notes By: Anand Sir | YouTube Channel: CODEITUP


MYSQL TEST

Ques 07: In RDBMS relationship between


tables are created by using ............ key.

Notes By: Anand Sir | YouTube Channel: CODEITUP


MYSQL TEST

Ques 08: Marks of a student can not be


greater than 100, is implemented using .......
constraint.

Notes By: Anand Sir | YouTube Channel: CODEITUP


MYSQL TEST

Ques 09: Which command is used to delete


entire database?

Notes By: Anand Sir | YouTube Channel: CODEITUP


MYSQL TEST

Ques 10: A primary key is selected from the


list of .................. keys?

Notes By: Anand Sir | YouTube Channel: CODEITUP


MYSQL TEST

Ques 11: Maximum length of a varchar


column is ............ Bytes?

Notes By: Anand Sir | YouTube Channel: CODEITUP


MYSQL TEST

Ques 12: Maximum length of a char column


is ............ Bytes?

Notes By: Anand Sir | YouTube Channel: CODEITUP


MYSQL TEST

Ques 13: Father of MySQL is .................... ?

Notes By: Anand Sir | YouTube Channel: CODEITUP


MYSQL TEST

Ques 14: In MySQL view is a .....................?

Notes By: Anand Sir | YouTube Channel: CODEITUP


MYSQL TEST

Ques 15: In MySQL to give a permission we


use ................ command?

Notes By: Anand Sir | YouTube Channel: CODEITUP


MYSQL TEST

Ques 16: In MySQL to take away a


permission we use ................ command?

Notes By: Anand Sir | YouTube Channel: CODEITUP


MYSQL TEST

Ques 17: Database is broadly categorized


into ......... parts.

Notes By: Anand Sir | YouTube Channel: CODEITUP


MYSQL TEST

Ques 18: To combine similar types of data


we use ............ clause?

Notes By: Anand Sir | YouTube Channel: CODEITUP


MYSQL TEST

Ques 19: When using Group By Clause we


use ............ clause to implement condition.

Notes By: Anand Sir | YouTube Channel: CODEITUP


MYSQL TEST

Ques 20: When more than one attribute is


used to extract data uniquely, it is called
.............. key.

Notes By: Anand Sir | YouTube Channel: CODEITUP


MYSQL TEST

Ques 21: To extract unique values from a


column containing duplicate fields, we use
............. keyword.

Notes By: Anand Sir | YouTube Channel: CODEITUP


MYSQL TEST

Ques 22: To extract data in reverse order of


column “salary” i.e. max to min from table
employee we will use the following SQL
Statement...

Notes By: Anand Sir | YouTube Channel: CODEITUP


MYSQL TEST

Ques 23: To extract record of highest paid


employee we will use statement ..... (assuming
“salary” as a column in the table “emp”)?

Notes By: Anand Sir | YouTube Channel: CODEITUP


MYSQL TEST

Ques 24: To extract data of all those


employees whose surname is “singh”, we
will use the query...?

Notes By: Anand Sir | YouTube Channel: CODEITUP


MYSQL TEST

Ques 25: Which datatype is used to hold


image in sql?

Notes By: Anand Sir | YouTube Channel: CODEITUP


MYSQL TEST

Ques 26: The query ‘SELECT NOW()’


shows the current _____________

Notes By: Anand Sir | YouTube Channel: CODEITUP


MYSQL TEST

Ques 27: The special database that


always exists after setting up MySQL in a
computer is __________

Notes By: Anand Sir | YouTube Channel: CODEITUP


MYSQL TEST

Ques 28: Is MySQL is freely available and


is open source.

Notes By: Anand Sir | YouTube Channel: CODEITUP


MYSQL TEST

Ques 29: In MySQL databases, the


structure representing the organizational
views of the entire databases is called
......?

Notes By: Anand Sir | YouTube Channel: CODEITUP


MYSQL TEST

Ques 30: Datatype “float(4,2)” represents


....... digits before decimal and ........... digits
after decimal.

Notes By: Anand Sir | YouTube Channel: CODEITUP


MYSQL TEST

Ques 31: MySQL date format is ..........

Notes By: Anand Sir | YouTube Channel: CODEITUP

You might also like