Python NOTES FOR O LEVEL - 03 - Mar - 2022 PDF
Python NOTES FOR O LEVEL - 03 - Mar - 2022 PDF
Advantages of Python
2. Improved Productivity
3. Interpreted Language
4. Dynamically Typed
WWW.JAWAHARCOMPUTEREDUCATION.COM Page 1 of 99
Disadvantages of Python
1. Slow Speed
4. Database Access
5. Runtime Errors
2. Data Science
4. Enterprise Applications
WWW.JAWAHARCOMPUTEREDUCATION.COM Page 2 of 99
5. Education Sector
7. Game Development
8. Software Development
9. Desktop GUI
WWW.JAWAHARCOMPUTEREDUCATION.COM Page 3 of 99
Career Options after Python Programming
1. Software Engineer
3. DevOps Engineer
4. Data Scientist
WWW.JAWAHARCOMPUTEREDUCATION.COM Page 4 of 99
FUTURE OF PYTHON
WWW.JAWAHARCOMPUTEREDUCATION.COM Page 5 of 99
Chapter-2(Flowcharts & Algorithms to solve problems)
PROCEDURE FOR PROBLEM SOLVING
WHAT IS ALGORITHMS?
The word Algorithm means “a process or set of rules to be followed in
calculations or other problem-solving operations”. Therefore Algorithm
refers to a set of rules/instructions that step-by-step define how a work
is to be executed upon in order to get the expected results.
Example:
Algorithm to find the greater of two numbers
• Ask the user to enter two integer values.
• Read the two integer values in num1 and num2 (integer variables).
• Check if num1 is greater than num2.
• If true, then print 'num1' as the greatest number.
• If false, then print 'num2' as the greatest number.
WWW.JAWAHARCOMPUTEREDUCATION.COM Page 6 of 99
WHAT IS FLOWCHART?
A flowchart is simply a graphical representation of steps. It shows steps
in sequential order and is widely used in presenting the flow of
algorithms, workflow or processes. Typically, a flowchart shows the
steps as boxes of various kinds, and their order by connecting them
with arrows.
Example:
Write a flow chart to find the greater of two numbers
WWW.JAWAHARCOMPUTEREDUCATION.COM Page 7 of 99
WHAT IS PSEDOCODE?
Pseudo code: It’s simply an implementation of an algorithm in the form
of annotations and informative text written in plain English.
General Rules used for writing codes are as follow.
1. Imperative Sentence: these sentences are used to show actions.
For example Add x to sum, display result, sort list, calculate etc.
2. Operators: Mostly arithmetic operators (+ , - , *, /) and relational
operators (= , => , <=, > , <) are used.
3. Decision: IF, THEN, ELSE, CASE, ENDCASE, is used for decision
making.
4. Looping: The looping or repetition of statements is shown by FOR,
WHILE.
WWW.JAWAHARCOMPUTEREDUCATION.COM Page 8 of 99
WHAT IS A PROGRAM?
A computer program is a set of instructions. it is used as a process of
creating a software program by using programming language. An
application, program, or application software is used to perform a
specific task on the computer. For example, Microsoft PowerPoint is an
application, which provides a way to create documents related to the
presentation. Furthermore, a browser is also an application, which
allows us to browse any website.
Difference between Applications and programs
All applications can be called a program, but a program cannot be an
application. An application is a collection of programs that are
designed to help the end-users to achieve a purpose. These programs
communicate with each other to perform tasks or activities.
Whereas, a program is a collection of instructions that describes the
computer what task to perform.
What is the purpose of a program?
The program enables the computer to perform a particular operation.
As without application software (programs), a computer is able to
operate with the operating system, but it cannot perform any specific
task. For example, if you want to create a Word document, you have to
install Microsoft Word on your computer. It is a program or application
software that instructs the computer how to create, edit, and save a
document or a file.
WWW.JAWAHARCOMPUTEREDUCATION.COM Page 9 of 99
Basic functions of a program
The function of a program depends upon the type of program. For
example, the function of the Microsoft Excel program is to create, edit,
and view documents related to calculation and data analysis, etc. The
function of an internet browser is to find information on the World
Wide Web and display it on the screen. Basically, a program is designed
to execute a particular task or function. For example, an Excel program
is able to create a document, but it cannot find the information on the
World Wide Web like a browser.
PROGRAMMING LANGUAGE
A Computer can only do what a program can make it do. To perform a
particular task, the programmer writes a sequence of instruction called
program. In programming language, a complete command is called a
“statement”.
Example: Each natural language has a systematic method. In English
language, the method is given by the rules of grammar. Similarly in
WWW.JAWAHARCOMPUTEREDUCATION.COM Page 10 of 99
computer language must also be used as per the set of rules which are
known as the “syntax rules” of the language.
Computer languages can be classified into three broad categories.
1. Machine Language:
2. Assembly Language:
3. High-Level Language:
WWW.JAWAHARCOMPUTEREDUCATION.COM Page 11 of 99
Interpreter − An interpreter is a program that executes the
programming code directly rather than only translating it into another
format. It translates and executes programming language statements
one by one.
Linker − Linker is a computer program that connects and combines
multiple object files to create an executable file. All these files might
have been compiled by a separate assembler.
Loader − the loader is an element of the operating framework and is
liable for loading executable files into memory and implement them.
WWW.JAWAHARCOMPUTEREDUCATION.COM Page 12 of 99
What is testing and debugging?
WWW.JAWAHARCOMPUTEREDUCATION.COM Page 14 of 99
Chapter-3(Introduction to python)
HOW TO INSTALL PYTHON
Step 1 − Download Python Executable Installer
Official site of python (www.python.org) move to the Download for
Windows section. Choose the Python 3.9.1 version. Download and
Install in your PC.
Step 2 – How to start python
We can start python in the following ways.
1. Python Shell (Command-line) : Start ->> python 3.2 ->> All
Programs->>Python(command-line)
2. Python Editor (IDE) : Start ->> All Programs ->>python 3.2 ->>IDLE
(Python GUI)
PROGRAM-1
Print “Your Name”
Step-1 Open Python IDLE
Step-2 Two windows will open (untitled window & python shell)
1. Untitled window (where you will write your program)
#my first program {the line after # (hash) is a comment}
Print (“Jawahar Computer Education”)
1.1 Save Program file name prg1.py (any file name).
To run program: Run ->> Run module or press F5
WWW.JAWAHARCOMPUTEREDUCATION.COM Page 15 of 99
2. Output will show on Python shell window
WWW.JAWAHARCOMPUTEREDUCATION.COM Page 16 of 99
PROGRAM-2
Write Multiline code and print the statement(using function)
Step-1 Write this code to python shell window
goldenlines is a
user defined
function.
PROGRAM-3
Assigning Values to Variables
Example: 1
Example: 2
WWW.JAWAHARCOMPUTEREDUCATION.COM Page 17 of 99
Example: 3
1. Source Character
a. Alphabets : A to Z , a to z and _(underscore)
b. Numbers : 0 to 9
c. Special Character :~ ! # % ^ & * () \ / : ; ? ‘ ‘ { } |=+ -.
2. Execution Character or Escape Character
a. \n End of line
b. \r Carriage return
c. \f Form feed Moves one to next page (used only printing hard copy)
d. \v Vertical tab
e. \t Horizontal tab
f. \b Backspace
g. \a alert
WWW.JAWAHARCOMPUTEREDUCATION.COM Page 18 of 99
What is Token?
Python breaks each logical line into a sequence of elementary lexical
components known as tokens. Each token corresponds to a substring of the
logical line. The normal token types are identifiers, keywords, operators,
delimiters, and literals, as covered in the following sections.
1. Identifiers: Identifiers are the names given to any variable, function, class,
list, methods, etc. for their identification.
a. As stated above, Python is case-sensitive. So case matters in naming
identifiers. And hence jcess and Jcess are two different identifiers.
b. Identifier starts with a capital letter (A-Z) , a small letter (a-z) or an
underscore( _ ). It can’t start with any other character.
c. Except for letters and underscore, digits can also be a part of identifier
but can’t be the first character of it.
d. Any other special characters or whitespaces are strictly prohibited in
an identifier.
e. An identifier can’t be a keyword.
PROGRAM-4
(Example of identifier)
WWW.JAWAHARCOMPUTEREDUCATION.COM Page 19 of 99
2. Keyword: Keywords are words that have some special meaning or
significance in a programming language. They can’t be used as
variable names, function names, or any other random purpose.
They are used for their special features. In Python we have 33
keywords some of them are: try, False, True, class, break, continue,
and, as, assert, while, for, in, raise, except, or, not, if, elif, print,
import, etc.
PROGRAM-5
(Example of Keyword)
# for is keyword
for x in range(1, 9):
print(x)
#if is a keyword
score_theory = 40
score_practical = 45
if(score_theory + score_practical > 100):
print("Please check the input. Score exceeds total possible score.")
else:
print("Score validated. Your total is: ", score_theory + score_practical)
WWW.JAWAHARCOMPUTEREDUCATION.COM Page 20 of 99
3. Operators :
WWW.JAWAHARCOMPUTEREDUCATION.COM Page 21 of 99
PROGRAM-7
(Use Of Assignment operators)
Assignment operators are used to assign values to variables:
WWW.JAWAHARCOMPUTEREDUCATION.COM Page 22 of 99
PROGRAM-8
(Use Of Comparison Operators)
WWW.JAWAHARCOMPUTEREDUCATION.COM Page 23 of 99
PROGRAM-9
(Use Of Logical Operators)
Logical operators are used to combine conditional statements:
WWW.JAWAHARCOMPUTEREDUCATION.COM Page 24 of 99
PROGRAM-10
(Use Of Identity Operators)
Identity operators are used to compare the objects, not if they are equal, but if
they are actually the same object, with the same memory location:
WWW.JAWAHARCOMPUTEREDUCATION.COM Page 25 of 99
PROGRAM-11
(Use Of Membership Operators)
Membership operators are used to test if a sequence is presented in an object:
WWW.JAWAHARCOMPUTEREDUCATION.COM Page 26 of 99
4. Literals : Python Literals can be defined as data that is given in a variable or
constant.
Ex: x=5,y=6.5
Print(x+y);
5 & 6.5 are literals.
Python supports the following literals:
1. String literals
2. Numeric literals
3. Boolean literals
4. Literal Collections
5. Special literals
PROGRAM-12
1. STRING LITERAL:
A string literal can be created by writing a text(a group of Characters )
surrounded by the single(”), double(“”), or triple quotes. By using triple quotes
we can write multi-line strings or display in the desired way.
WWW.JAWAHARCOMPUTEREDUCATION.COM Page 27 of 99
PROGRAM-13
2. NUMERIC LITERAL:
Numeric literals
They are immutable and there are three types of numeric literal :
1. Integer
2. Float
3. Complex.
• Integer :
Both positive and negative numbers including 0. There should not be any
fractional part.
Example: Integer Literal
WWW.JAWAHARCOMPUTEREDUCATION.COM Page 28 of 99
Example: Float Literal
These are real numbers having both integer and fractional parts.
# Float Literal
e = 24.8
f = 45.0
z = 7 + 5j
# real part is 0 here.
k = 7j
print(z, k) output: (7+5j) 7j
WWW.JAWAHARCOMPUTEREDUCATION.COM Page 29 of 99
PROGRAM-14
3. BOOLEAN LITERAL:
There are only two Boolean literals in Python. They are true and false.
WWW.JAWAHARCOMPUTEREDUCATION.COM Page 30 of 99
PROGRAM-15
4. LITERAL COLLECTIONS:
There are four different types of literal collections
1. List literals
2. Tuple literals
3. Dict literals
4. Set literals
1. List literals :
List contains items of different data types. The values stored in
List are separated by comma (,) and enclosed within square
brackets([]). We can store different types of data in a List. Lists
are mutable.
# List literals
number = [1, 2, 3, 4, 5]
name = ['Amit', 'kabir', 'bhaskar', 2]
print(number)
print(name)
Output
[1, 2, 3, 4, 5]
['Amit', 'kabir', 'bhaskar', 2]
2. Tuple literals
Example:
# Tuple literals
even_number = (2, 4, 6, 8)
odd_number = (1, 3, 5, 7)
print(even_number)
print(odd_number)
Output
(2, 4, 6, 8)
(1, 3, 5, 7)
PROGRAM-17(Dictionary literals)
3. Dictionary literals
# Dict literals
alphabets = {'a': 'apple', 'b': 'ball', 'c': 'cat'}
information = {'name': 'amit', 'age': 20, 'ID': 20}
print(alphabets)
print(information)
WWW.JAWAHARCOMPUTEREDUCATION.COM Page 32 of 99
Output
{'a': 'apple', 'b': 'ball', 'c': 'cat'}
{'name': 'amit', 'age': 20, 'ID': 20}
PROGRAM-18(Set literals)
4. Set literals
Set is the collection of the unordered data set. It is enclosed by the {}
and each element is separated by the comma (,).
Example:
we can create a set of vowels and fruits.
# Set literals
vowels = {'a', 'e', 'i', 'o', 'u'}
fruits = {"apple", "banana", "cherry"}
print(vowels)
print(fruits)
Output
{'o', 'e', 'a', 'u', 'i'}
{'apple', 'banana', 'cherry'}
WWW.JAWAHARCOMPUTEREDUCATION.COM Page 33 of 99
PROGRAM-19(Special literals)
5. Special literals
Python contains one special literal (None). ‘None’ is used to define a
null variable. If ‘None’ is compared with anything else other than
a ‘None’, it will return false.
Example:
# Special literals
water_remain = None
print(water_remain)
Output
None
5. Variable:
# An integer assignment
age = 45
# A floating point
salary = 1456.8
# A string
name = "John"
WWW.JAWAHARCOMPUTEREDUCATION.COM Page 34 of 99
print(age)
print(salary)
print(name)
WWW.JAWAHARCOMPUTEREDUCATION.COM Page 35 of 99
PROGRAM-21(Input string,integer,float)
WWW.JAWAHARCOMPUTEREDUCATION.COM Page 36 of 99
eval()
eval function is used to evaluate the value of a string. It takes a
string as an argument, evaluates this string as number, and returns
the numeric result. It can evaluate expressions, provided the input is
a string.
PROGRAM-22(How to use eval function)
>>> eval("2 ** 8")
256
>>> eval("1024 + 1024")
2048
>>> eval("sum([8, 16, 32])")
56
>>> x = 100
>>> eval("x * 2")
200
WWW.JAWAHARCOMPUTEREDUCATION.COM Page 37 of 99
Chapter-4 Operators, Expressions and statements
In Page no: 21 See Operators
Do it yourself:
Program no 1: Program to calculate simple interest.
Program no 2: Program to calculate are and perimeter of
parallelogram.
Formula: area of parallelogram=l*h
Perimeter of parallelogram= 2*l + 2*w
-:Expressions:-
Expressions consist of combination of values which can be constant
values.
Ex : 10 – 4 or 11 *(4+5).
>>>float(22) result : 22.0
>>>int(4.8) result : 4
-:Statement:-
Statement: A python statement is an instruction or a unit of code
that the python interpreter can execute. In computer language,
complete command is called statement.
Ex:
>>>print(12+13)
>>>print(“welcome in jcess”)
>>>print(“sum of 2+5=”,2+5)
WWW.JAWAHARCOMPUTEREDUCATION.COM Page 38 of 99
Chapter-5 Conditional and iterative statements
What is Conditional Statement?
Conditional statement is used for decision making.
1. If statement. 2. If else statement 3. Nested if statement.
4. If…Elif ladder
PROGRAM-23 (IF Statement)
It has a code body that only executes if the condition in the if
statement is true.
Note=conditional statement use ‘tab’ for conditions.
Note= (:) is compulsory used with “if” and “else.”
WWW.JAWAHARCOMPUTEREDUCATION.COM Page 40 of 99
PROGRAM-25 ( Nested if Statement)
A Nested IF statement is one in which an If statement is nestled
inside another If statement. This is used when a variable must be
processed more than once.
num = 15
if num >= 0:
if num == 0:
print("Zero")
else:
print("Positive number")
else:
print("Negative number")
WWW.JAWAHARCOMPUTEREDUCATION.COM Page 42 of 99
# enter marks to show the grade
ch=int(input('Enter your marks(%)='))
if(ch>=90):
print('A+')
elif(ch>=80):
print('A')
elif(ch>=70):
print('B+')
elif(ch>=60):
print('B')
elif(ch>=50):
print('C')
else:
print('D')
WWW.JAWAHARCOMPUTEREDUCATION.COM Page 43 of 99
#Program to calculate electric bill
units = int(input(" Please enter Number of Units you Consumed : "))
if(units < 50):
amount = units * 2.60
surcharge = 25
elif(units <= 100):
amount = 130 + ((units - 50) * 3.25)
surcharge = 35
elif(units <= 200):
amount = 130 + 162.50 + ((units - 100) * 5.26)
surcharge = 45
else:
amount = 130 + 162.50 + 526 + ((units - 200) * 8.45)
surcharge = 75
WWW.JAWAHARCOMPUTEREDUCATION.COM Page 44 of 99
Loops
A loop statement allows us to execute a statement or group of
statements multiple times. The following diagram illustrates a loop
statement. There are 3 loops in python
1. While loop 2. Do-while loop 3. For loop
WHILE:
WWW.JAWAHARCOMPUTEREDUCATION.COM Page 45 of 99
Program-27 (Example of While Loop)
i=1
while i<6:
print(i)
i+=1
n=2
while(n<=10):
print(n)
n=n+2
n=5
while(n>=1):
print(n)
n=n-1
f=2
n=int(input(‘enter any no:-“))
while(n>1);
f=f*n
n=n-1
print(‘factorial is =’,f)
WWW.JAWAHARCOMPUTEREDUCATION.COM Page 46 of 99
DO-WHILE:
#reverse range
for i in range(5,2,-1):
Print(i)
WWW.JAWAHARCOMPUTEREDUCATION.COM Page 49 of 99
Program-32Check whether the entered number is prime or not
A positive integer greater than 1 which does not have other factors except 1 and
the number itself is called a prime number. The numbers 2, 3, 5, 7, etc. are prime
numbers as they do not have any other factors. To find a prime number in
Python, you have to iterate the value from start to end using a for loop and for
every number, if it is greater than 1, check if it divides n. If we find any other
number which divides, print that value.
num = int(input('enter any number:'))
if num > 1:
for i in range(2, num//2):
if (num % i) == 0:
print(num, "is not a prime number")
break
else:
print(num, "is a prime number")
else:
print(num, "is not a prime number")
WWW.JAWAHARCOMPUTEREDUCATION.COM Page 50 of 99
Nested Loop A loop may also contain another loop within its body, is called
nested loop. In nested loop, the inner loop must terminate before the ending the
outer loop.
Program-33 Print number series
# ROW=Row Never Increment on Its Value. It Print Same Value In Same Row.
#COL=Always Print Increment Value. #When We Will Print Row, Column Will
Provide Space. # When We Will Print Col, Row Will Provide Space.
for row in range(1,6):
for col in range(1,6) :
print(row, end=' ')
print(" ")
for i in range(5):
for s in range(-6, -i):
print(" ", end="")
for j in range(i+1):
print("* ", end="")
print()
WWW.JAWAHARCOMPUTEREDUCATION.COM Page 52 of 99
for i in range(5):
for s in range(i):
print(" ", end="")
for j in range(i, 5):
print("* ", end="")
print()
WWW.JAWAHARCOMPUTEREDUCATION.COM Page 53 of 99
def pattern(n):
k=2*n-2
for i in range(0, n):
for j in range(0 , k):
print(end=" ")
k=k-1
for j in range(0 , i + 1 ):
print("* ", end="")
print("\r")
k=n-2
for i in range(n , -1, -1):
for j in range(k , 0 , -1):
print(end=" ")
k=k+1
for j in range(0 , i + 1):
print("* ", end="")
print("\r")
pattern(5)
for i in range(5):
for j in range(5):
if i + j == 2 or i - j == 2 or i + j == 6 or j - i == 2:
print("*", end="")
else:
print(end=" ")
print()
WWW.JAWAHARCOMPUTEREDUCATION.COM Page 54 of 99
JUMP STATEMENTS: those statement which transfer the program
control unconditionally within the program, from one place to another
place is called jump statement.
We have 3 types of jump statement.
1. break
2. continue
3. pass
Program-34 (Example Break Statement)
Break statement: the break is used for immediate exit from the
innermost loop structure.
for a in range(1,11):
if(a==6):
break
print(a)
for a in ‘jawahar’:
if(a==’h’):
break
print(a)
WWW.JAWAHARCOMPUTEREDUCATION.COM Page 55 of 99
Program-35 (Example Continue Statement)
WWW.JAWAHARCOMPUTEREDUCATION.COM Page 56 of 99
Pass function: The pass statement is a null statement. But the difference
between pass and comment is that comment is ignored by the interpreter
whereas pass is not ignored.
The pass statement is generally used as a placeholder i.e. when the user does
not know what code to write. So user simply places pass at that line.
Sometimes, pass is used when the user doesn’t want any code to execute. So
user can simply place pass where empty code is not allowed, like in loops,
function definitions, class definitions, or in if statements. So using pass
statement user avoids this error.
Program-36 (Example Pass function)
n=input(‘enter name=’)
if(n==’aru’):
print(‘welcome’)
elif(n==’ramesh’):
pass
elif(n==’ram’):
print(‘not find’)
WWW.JAWAHARCOMPUTEREDUCATION.COM Page 57 of 99
Chapter-6 Strings in Python
Python string is the collection of the characters surrounded by single quotes,
double quotes, or triple quotes. The computer does not understand the
characters; internally, it stores manipulated character as the combination of the
0's and 1's. Strings are immutable.
Each character is encoded in the ASCII or Unicode character. So we can say that
Python strings are also called the collection of Unicode characters.
Strings indexing
The indexing of the Python strings starts from 0.
str = "JCESS"
print(str[0]) #print J
print(str[1]) #print C
print(str[2]) #print E
print(str[3]) #print S
print(str[4]) #print S
# It returns the IndexError because 5th index doesn't exist
print(str[5])
WWW.JAWAHARCOMPUTEREDUCATION.COM Page 58 of 99
Strings splitting/slicing
str = "JAWAHARCOMPUTER"
print(str[0:]) # Start 0 th index to end
print(str[1:5]) # Starts 1 th index to 4th index
print(str[2:4]) # Starts 2 nd index to 3rd index
print(str[:3]) # Starts 0 th to 2nd index
print(str[4:7]) #Starts 4 th to 6th index
Negative Range
str = 'JAWAHARCOMPUTER'
print(str[-1]) #negative starts with 1 not with 0
print(str[-3])
print(str[-2:])
print(str[-4:-1])
print(str[-7:-2])
Reverse Order
str = 'JAWAHARCOMPUTER'
#Print string in reverse order
print(str[::-1])
p='JAWAHAR'
print(p)
del p
print(p)
WWW.JAWAHARCOMPUTEREDUCATION.COM Page 59 of 99
String Operators
Operator Description
not in It is also a membership operator and does the exact reverse of in. It
returns true if a particular substring is not present in the specified string.
WWW.JAWAHARCOMPUTEREDUCATION.COM Page 60 of 99
Ex
WWW.JAWAHARCOMPUTEREDUCATION.COM Page 61 of 99
STRING OPERATOR:
WWW.JAWAHARCOMPUTEREDUCATION.COM Page 62 of 99
Program-42
4. COMPARISON OPERATOR: All the comparison operators
(< , <=, >, >=, !=, ==).
s= ‘jcess’
s1= ‘JCESS’
print(s>s1) #it will show false, because letter is different
str='JAWAHAR'
print('character 1 to 3 is',str[1:3])
print('character 1 to 3 is',str[2:])
print('character 1 to 3 is',str[1:-1])
print('character 1 to 3 is',str[:-3])
print('character 1 to 3 is',str[-3:-1])
print('character 1 to 3 is',str[-5:-3])
print('character start to end is',str[:])
WWW.JAWAHARCOMPUTEREDUCATION.COM Page 64 of 99
Chapter-7 List Manipulation
1. Lists are used to store multiple items in a single variable.
2. Lists are one of 4 built-in data types in Python used to store collections of
data, the other 3 are Tuple, Set, and Dictionary, all with different qualities
and usage.
3. Lists are created using square brackets.
4. List items are ordered, changeable, and allow duplicate values.
5. List items are indexed, the first item has index [0], the second item has
index [1] etc
6. The items have a defined order, and that order will not change.
7. If you add new items to a list, the new items will be placed at the end of
the list.
8. The list is changeable, meaning that we can change, add, and remove items
in a list after it has been created.
9. Lists allow duplicate values:
List Length:
fruits = ["apple", "banana", "cherry"]
print(len(fruits)) OUTPUT : 3
WWW.JAWAHARCOMPUTEREDUCATION.COM Page 65 of 99
List Items - Data Types
List items can be of any data type: String, int and Boolean data types:
Program-43
WWW.JAWAHARCOMPUTEREDUCATION.COM Page 66 of 99
list_varible(start:stop:step)
Program-44
list = [1,2,3,4,5,6,7]
print(list[0])
print(list[1])
print(list[2])
print(list[3])
print(list[0:6])
print(list[:])
print(list[2:5])
print(list[1:6:2])
#negative indexing
print(list[-1])
print(list[-3:])
print(list[:-1])
print(list[-3:-1])
WWW.JAWAHARCOMPUTEREDUCATION.COM Page 67 of 99
Python List Operations
Iteration The for loop is used to iterate over the for i in l1:
list elements. print(i)
Output
1
2
3
4
Length It is used to get the length of the list len(l1) = 4
Iterating a List
A list can be iterated by using a for - in loop. A simple list containing four
strings, which can be iterated as follows.
Program-45
list = ["Jcess", "Anju", "Puneet"]
for i in list:
print(i)
output : Jcess
Anju
Puneet
WWW.JAWAHARCOMPUTEREDUCATION.COM Page 68 of 99
Adding elements to the list
l =[]
n = int(input("Enter the number of elements in the list:"))
for i in range(0,n):
l.append(input("Enter the item:"))
print("printing the list items..")
for i in l:
print(i, end = " ")
list = [0,1,2,3,4]
print("printing original list: ");
for i in list:
print(i,end=" ")
list.remove(2)
print("\nprinting the list after the removal of second element...")
for i in list:
print(i,end=" ")
WWW.JAWAHARCOMPUTEREDUCATION.COM Page 69 of 99
Python List Built-in functions
SN Function Description Example
WWW.JAWAHARCOMPUTEREDUCATION.COM Page 70 of 99
Chapter-8 Tuple
Python Tuple is used to store the sequence of immutable Python objects. The tuple is similar to
lists since the value of the items stored in the list can be changed, whereas the tuple is
immutable, and the value of the items stored in the tuple cannot be changed.
Creating a tuple
A tuple can be written as the collection of comma-separated (,) values enclosed with the small
() brackets. The parentheses are optional but it is good practice to use. A tuple can be defined
as follows.
Note: The tuple which is created without using parentheses is also known as tuple packing.
A tuple is indexed in the same way as the lists. The items in the tuple can be accessed by using
their specific index value.
Program-46
tuple1 = (10, 20, 30, 40, 50, 60)
print(tuple1)
count = 0
for i in tuple1:
print("tuple1[%d] = %d"%(count, i)) #%d ---to convert string into number
count = count+1
WWW.JAWAHARCOMPUTEREDUCATION.COM Page 71 of 99
Program-47
A tuple is indexed in the same way as the lists. The items in the tuple can be
accessed by using their specific index value.
Tuple indexing and slicing
The indexing and slicing in the tuple are similar to lists. The indexing in the tuple
starts from 0 and goes to length(tuple) - 1.
The items in the tuple can be accessed by using the index [] operator. Python also
allows us to use the colon operator to access multiple items in the tuple.
WWW.JAWAHARCOMPUTEREDUCATION.COM Page 72 of 99
tup = (1,2,3,4,5,6,7)
print(tup[0])
print(tup[1])
print(tup[2])
# It will give the IndexError
print(tup[8])
Program-48
tuple = (1,2,3,4,5,6,7)
print(tuple[1:])
print(tuple[:4])
print(tuple[1:5])
print(tuple[0:6:2])
tuple1 = (1, 2, 3, 4, 5)
print(tuple1[-1])
print(tuple1[-4])
print(tuple1[-3:-1])
print(tuple1[:-1])
print(tuple1[-2:])
WWW.JAWAHARCOMPUTEREDUCATION.COM Page 73 of 99
Deleting Tuple
Unlike lists, the tuple items cannot be deleted by using the del keyword as tuples
are immutable. To delete an entire tuple, we can use the del keyword with the
tuple name.
Program-49
tuple1 = (1, 2, 3, 4, 5, 6)
print(tuple1)
del tuple1[0]
print(tuple1)
del tuple1
print(tuple1)
WWW.JAWAHARCOMPUTEREDUCATION.COM Page 74 of 99
Membership It returns true if a particular item exists in print (2 in T1)
prints True.
the tuple otherwise false
Iteration The for loop is used to iterate over the tuple for i in T1:
print(i)
elements.
Output
1
2
3
4
5
SN Function Description
WWW.JAWAHARCOMPUTEREDUCATION.COM Page 75 of 99
List vs. Tuple
SN List Tuple
1 The literal syntax of list is shown by the []. The literal syntax of the tuple is shown by the ().
3 The List has the a variable length. The tuple has the fixed length.
4 The list provides more functionality than The tuple provides less functionality than the list.
a tuple.
5 The list is used in the scenario in which The tuple is used in the cases where we need to
we need to store the simple collections store the read-only collections i.e., the value of
with no constraints where the value of the items cannot be changed. It can be used as
the items can be changed. the key inside the dictionary.
6 The lists are less memory efficient than a The tuples are more memory efficient because of
tuple. its immutability.
WWW.JAWAHARCOMPUTEREDUCATION.COM Page 76 of 99
Python Set
A Python set is the collection of the unordered items. Each element in
the set must be unique, immutable, and the sets remove the duplicate
elements. Sets are mutable which means we can modify it after its
creation.
Program-50
Creating a set
WWW.JAWAHARCOMPUTEREDUCATION.COM Page 77 of 99
Program-51
Using set() method
Python provides the add() method and update() method which can be
used to add some particular item to the set. The add() method is used
to add a single element whereas the update() method is used to add
multiple elements to the set.
WWW.JAWAHARCOMPUTEREDUCATION.COM Page 78 of 99
Program-52
WWW.JAWAHARCOMPUTEREDUCATION.COM Page 79 of 99
Using update() function
WWW.JAWAHARCOMPUTEREDUCATION.COM Page 80 of 99
Chapter-9 Dictionaries
Python Dictionary is used to store the data in a key-value pair format. The
dictionary is the data type in Python, which can simulate the real-life data
arrangement where some specific value exists for some particular key. It is the
mutable data-structure. The dictionary is defined into element Keys and values.
• Keys must be a single element
• Value can be any type such as list, tuple, integer, etc.
• In other words, we can say that a dictionary is the collection of key-value
pairs where the value can be any Python object. In contrast, the keys are
the immutable Python object, i.e., Numbers, string, or tuple.
Creating the dictionary
The dictionary can be created by using multiple key-value pairs enclosed with
the curly brackets {}, and each key is separated from its value by the colon (:).
Dict = {"Name": "Aru", "Age": 3}
Python provides the built-in function dict() method which is also used to
create dictionary. The empty curly braces {} is used to create empty
dictionary.
Program-53
# Creating an empty Dictionary
Dict = {}
print("Empty Dictionary: ")
print(Dict)
# Creating a Dictionary
# with dict() method
Dict = dict({1: 'Aru', 2: 'tiwari', 3:'jcesst'})
print("\nCreate Dictionary by using dict(): ")
print(Dict)
# Creating a Dictionary
# with each item as a Pair
Dict = dict([(1, 'Devansh'), (2, 'Sharma')])
print("\nDictionary with each item as a pair: ")
print(Dict)
WWW.JAWAHARCOMPUTEREDUCATION.COM Page 81 of 99
Using pop() method
The pop() method accepts the key as an argument and remove the associated
value.
Program-54
# Creating a Dictionary
Dict = {1: 'JavaTpoint', 2: 'Peter', 3: 'Thomas'}
# Deleting a key
# using pop() method
pop_ele = Dict.pop(3)
print(Dict)
WWW.JAWAHARCOMPUTEREDUCATION.COM Page 82 of 99
Python File Handling
The file handling plays an important role when the data needs to be stored
permanently into the file. A file is a named location on disk to store related
information. We can access the stored information (non-volatile) after the
program termination.
The file-handling implementation is slightly lengthy or complicated in the other
programming language, but it is easier and shorter in Python.
In Python, files are treated in two modes as text or binary. The file may be in the
text or binary format, and each line of a file is ended with the special character.
Hence, a file operation can be done in the following order.
• Open a file
• Read or write - Performing operation
• Close the file
Python provides an open() function that accepts two arguments, file name and
access mode in which the file is accessed. The function returns a file object which
can be used to perform various operations like reading, writing, etc
Program-55
WWW.JAWAHARCOMPUTEREDUCATION.COM Page 83 of 99
Access
SN Description
mode
It opens the file to read-only mode. The file pointer exists at the beginning. The file
1 r
is by default open in this mode if no access mode is passed.
It opens the file to read-only in binary format. The file pointer exists at the
2 rb
beginning of the file.
It opens the file to read and write both. The file pointer exists at the beginning of the
3 r+
file.
It opens the file to read and write both in binary format. The file pointer exists at the
4 rb+
beginning of the file.
It opens the file to write only. It overwrites the file if previously exists or creates a
5 w new one if no file exists with the same name. The file pointer exists at the beginning
of the file.
It opens the file to write only in binary format. It overwrites the file if it exists
6 wb previously or creates a new one if no file exists. The file pointer exists at the
beginning of the file.
It opens the file to write and read both. It is different from r+ in the sense that it
overwrites the previous file if one exists whereas r+ doesn't overwrite the previously
7 w+
written file. It creates a new file if no file exists. The file pointer exists at the
beginning of the file.
It opens the file to write and read both in binary format. The file pointer exists at the
8 wb+
beginning of the file.
It opens the file in the append mode. The file pointer exists at the end of the
9 a previously written file if exists any. It creates a new file if no file exists with the
same name.
It opens the file in the append mode in binary format. The pointer exists at the end
10 ab of the previously written file. It creates a new file in binary format if no file exists
with the same name.
It opens a file to append and read both. The file pointer remains at the end of the file
11 a+
if a file exists. It creates a new file if no file exists with the same name.
It opens a file to append and read both in binary format. The file pointer remains at
12 ab+
the end of the file.
WWW.JAWAHARCOMPUTEREDUCATION.COM Page 84 of 99
Closing a file close() method
Once all the operations are done on the file, we must close it through our Python
script using the close() method. Any unwritten information gets destroyed once
the close() method is called on a file object.
# open the file.txt in append mode. Create a new file if no such file exists.
fileptr = open("aru.txt", "w")
# appending the content to the file
fileptr.write('''''Python is the modern day language. It makes things so simple.
It is the fastest-growing programming language''')
# closing the opened the file
fileptr.close()
To Open txt file after modification. Goto c:>>computer>>python 32>>open txt file.
You can see , the file data has been changed.
WWW.JAWAHARCOMPUTEREDUCATION.COM Page 85 of 99
Read Lines of the file readline() method
#open the file.txt in read mode. causes error if no such file exists.
fileptr = open("aru.txt","r");
#stores all the data of the file into the variable content
content = fileptr.readline()
content1 = fileptr.readline()
#prints the content of the file
print(content)
print(content1)
#closes the opened file
fileptr.close()
WWW.JAWAHARCOMPUTEREDUCATION.COM Page 86 of 99
Removing the file
The os module provides the remove() method which is used to remove the
specified file. The syntax to use the remove() method is given below.
mkdir(directory name)
WWW.JAWAHARCOMPUTEREDUCATION.COM Page 87 of 99
The file related methods
The file object provides the following methods to manipulate the files on various
operating systems.
SN Method Description
It closes the opened file. The file once closed, it can't be read or
1 file.close()
write anymore.
2 File.fush() It flushes the internal buffer.
It returns the file descriptor used by the underlying
3 File.fileno()
implementation to request I/O from the OS.
It returns true if the file is connected to a TTY device, otherwise
4 File.isatty()
returns false.
5 File.next() It returns the next line from the file.
6 File.read([size]) It reads the file for the specified size.
It reads one line from the file and places the file pointer to the
7 File.readline([size])
beginning of the new line.
It returns a list containing all the lines of the file. It reads the file
8 File.readlines([sizehint])
until the EOF occurs using readline() function.
It modifies the position of the file pointer to a specified offset
9 File.seek(offset[,from)
with the specified reference.
10 File.tell() It returns the current position of the file pointer within the file.
11 File.truncate([size]) It truncates the file to the optional specified size.
12 File.write(str) It writes the specified string to a file
13 File.writelines(seq) It writes a sequence of the strings to a file.
WWW.JAWAHARCOMPUTEREDUCATION.COM Page 88 of 99
Chapter-10 Functions
Defining a Function
1. Function is block of code that is also called by its name. (independent)
2. Function does not deal with Class and its instance concept.
Program-57
Defining a Method
1. Method is called by its name, but it is associated to an object (dependent).
2. A method can operate on the data (instance variables) that is contained by
the corresponding class
# User-Defined Method
class ABC :
def method_abc (self):
print("Hello world ")
class_ref = ABC() # object of ABC class
class_ref.method_abc()
WWW.JAWAHARCOMPUTEREDUCATION.COM Page 89 of 99
# inbuild method
import math
ceil_val = math.ceil(15.25)
print( "Ceiling value of 15.25 is : ", ceil_val)
Function Vs Method
Function can be called only by its name, as it is defined independently.
Method can’t be called by its name only, Method is defined within a class and
hence they are dependent on that class.
All Methods are Functions, but not all functions are methods.
Program-58
Type of Function
1. Module (Chapter 12 covered)
2. Built in Function (Chapter 12 covered)
3. User Defined Function (Chapter 12 covered)
Module: A module is a file that contains a collection of related function. Python
comes with some pre-loaded, pre-defined modules also called “Standard Library
Module”. A python module is a file containing python codes- including
statements, variables, functions and classes. It shall be saved by:modulename.py
(like : jcess.py) it should be unique.
WWW.JAWAHARCOMPUTEREDUCATION.COM Page 90 of 99
There are 3 Module:
1. Math Module : Contain Mathematical Function (factorial,
Logarithmic, power, trigonometric, degree, radians.
2. Random Module : Making random selection, random numbers used
for games, simulations, testing, security, and privacy
applications.
3. Statistics Module : Mathematical statistics of number data, like-
mean(), median(), mode().
We can also create module.
WWW.JAWAHARCOMPUTEREDUCATION.COM Page 91 of 99
Step -2 Write a code and save file name anju.py
WWW.JAWAHARCOMPUTEREDUCATION.COM Page 92 of 99
LEGB Rule: Variable can be defined in locally, globally, Enclosed, and buit.in.
L for Local E for Enclosed G for Global B for built-in
WWW.JAWAHARCOMPUTEREDUCATION.COM Page 93 of 99
Example: Global variable (user defined function)
x=5
def num():
def num1():
print(x)
num1()
print(x)
num()
If you define variable before the function, is called global variable. It means it
can accessible anywhere in the program.
x=len(“jcess”)
print(x)
print(x)
WWW.JAWAHARCOMPUTEREDUCATION.COM Page 94 of 99
Program-61 Return FUNCTION
def add_num(x,y):
sum = x + y
return sum
num1=2
num2=5
print("The Sum is :”,add_num(num1,num2))
Void Function: A function that doesn’t return a value is called void function or non-
fruitful function. A Function that return the value is called a fruitfull function
Defining a Method
A method in python is somewhat similar to a function, except it is associated
with object/classes. Methods in python are very similar to functions except for
two major differences.
• The method is implicitly used for an object for which it is called.
• The method is accessible to data that is contained within the class.
WWW.JAWAHARCOMPUTEREDUCATION.COM Page 95 of 99
Chapter-13 Python NumPy
What is NumPy
NumPy stands for numeric python which is a python package for the
computation and processing of the multidimensional and single
dimensional array elements.
NumPy Ndarray
The ndarray object can be created by using the array routine of the
numpy module. For this purpose, we need to import the numpy.
>>> a = numpy.array
>>> a = numpy.array([1, 2, 3])
Finding the dimensions of the Array
The ndim function can be used to find the dimensions of the array.
Example
import numpy as np
a = np.array([[1,2,30],[10,15,4]])
print("The array:",a)
print("The maximum elements of columns:",a.max(axis = 0))
print("The minimum element of rows",a.min(axis = 1))
print("The sum of all rows",a.sum(axis = 1))
Output:
The array: [[1 2 30]
[10 15 4]]
The maximum elements of columns: [10 15 30]
The minimum element of rows [1 4]
The sum of all rows [33 29]
WWW.JAWAHARCOMPUTEREDUCATION.COM Page 97 of 99
In the following example, the arithmetic operations are performed on
the two multi-dimensional arrays a and b.
Example
import numpy as np
a = np.array([[1,2,30],[10,15,4]])
b = np.array([[1,2,3],[12, 19, 29]])
print("Sum of array a and b\n",a+b)
print("Product of array a and b\n",a*b)
print("Division of array a and b\n",a/b)
Array Concatenation
Example
import numpy as np
a = np.array([[1,2,30],[10,15,4]])
b = np.array([[1,2,3],[12, 19, 29]])
print("Arrays vertically concatenated\n",np.vstack((a,b)));
print("Arrays horizontally concatenated\n",np.hstack((a,b)))
Output:
Arrays vertically concatenated
[[ 1 2 30]
[10 15 4]
[ 1 2 3]
WWW.JAWAHARCOMPUTEREDUCATION.COM Page 98 of 99
[12 19 29]]
Arrays horizontally concatenated
[[ 1 2 30 1 2 3]
[10 15 4 12 19 29]]
WWW.JAWAHARCOMPUTEREDUCATION.COM Page 99 of 99