0% found this document useful (0 votes)
910 views99 pages

Python NOTES FOR O LEVEL - 03 - Mar - 2022 PDF

The document provides information about Python programming language including how to install Python, advantages and disadvantages of Python, uses of Python in various domains like web development, data science, artificial intelligence etc. It also discusses career options and top companies using Python. The document further explains concepts like algorithms, flowcharts, pseudocode, programs, programming languages, types of errors in programs, software testing and debugging.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
910 views99 pages

Python NOTES FOR O LEVEL - 03 - Mar - 2022 PDF

The document provides information about Python programming language including how to install Python, advantages and disadvantages of Python, uses of Python in various domains like web development, data science, artificial intelligence etc. It also discusses career options and top companies using Python. The document further explains concepts like algorithms, flowcharts, pseudocode, programs, programming languages, types of errors in programs, software testing and debugging.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 99

Chapter-1(Introduction to Programming)

Python is a widely used general-purpose, high level programming


language. It was initially designed by Guido van Rossum in 1991 and
developed by Python Software Foundation. It was mainly developed for
emphasis on code readability, and its syntax allows programmers to
express concepts in fewer lines of code.
Python is a programming language that lets you work quickly and
integrate systems more efficiently.

Advantages of Python

1. Easy to Read, Learn and Write

2. Improved Productivity

3. Interpreted Language

4. Dynamically Typed

5. Free and Open-Source

6. Vast Libraries Support


7. Portability

WWW.JAWAHARCOMPUTEREDUCATION.COM Page 1 of 99
Disadvantages of Python

1. Slow Speed

2. Not Memory Efficient

4. Database Access

5. Runtime Errors

Uses of Python in Real World


1. Web Development

2. Data Science

3. Artificial Intelligence and Machine Learning

4. Enterprise Applications
WWW.JAWAHARCOMPUTEREDUCATION.COM Page 2 of 99
5. Education Sector

6. Web Scraping Applications

7. Game Development

8. Software Development

9. Desktop GUI

10. Operating Systems

WWW.JAWAHARCOMPUTEREDUCATION.COM Page 3 of 99
Career Options after Python Programming

Types of Python Jobs

1. Software Engineer

2. Senior Software Engineer

3. DevOps Engineer

4. Data Scientist

5. Senior Data Scientist

WWW.JAWAHARCOMPUTEREDUCATION.COM Page 4 of 99
FUTURE OF PYTHON

TOP COMPANIES USING 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.

Write a PSEUCODE to find the greater of two numbers


Step 1: Start
Step 2: Declare variables n1, n2
Step 3: If n1 is greater than n2,
Display "n1 is Maximum"
else
Display "n2 is Maximum"

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.

What was the first program?


Tom Kilburn wrote the first software program to hold in electronic
memory. It was successfully executed at the University of Manchester,
England, on 21 June1948. This program was computed as the greatest
factor of the integer 218 = 262,144. The computer was called the mall
Scale Experimental Machine (SSEM), which was known as the
Manchester Baby. This occurrence is considered as the birth of the first
software.

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:

What are Computer Translator?


A translator is a programming language processor that modifies a
computer program from one language to another. It takes a program
written in the source program and modifies it into a machine program.
It can find and detect the error during translation.
There are various types of a translator which are as follows –

Compiler − A compiler is a program that translates a high-level language


(for example, C, C++, and Java) into a low-level language (object
program or machine program).
Pre-Processor − Pre-Processor is a program that processes the source
code before it passes through the compiler.
Assembler − An assembler is a translator which translates an assembly
language program into an equivalent machine language program of the
computer.

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?

What is Software Testing?


The testing is a collection of techniques to determine the accuracy of
the application under the predefined specification but, it cannot
identify all the defects of the software.
What is Debugging?
Debugging is the action where the development team or a developer
implements after receiving the test report related to the bugs in the
software from the testing team.

Testing and debugging are vital step in developing computer program.


There are three types of errors that occur in a computer program. These
are:
1. Syntax Error: An error that occurs when a compiler or
interpreter cannot understand the source code statement in order
to generate. Typically involved incorrect punctuation, incorrect
word sequence, and undefined terms.
WWW.JAWAHARCOMPUTEREDUCATION.COM Page 13 of 99
2. Run-Time Errors: A runtime error in a program is an error
that occurs while the program is running after being successfully
compiled. Runtime errors are commonly called referred to as
“bugs” and are often found during the debugging process before
the software is released.

3. Logical Errors: A logic error is a bug in a program that causes it


to operate incorrectly, but not to terminate abnormally (or crash).
A logic error produces unintended or undesired output or other
behavior, although it may not immediately be recognized as such.

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

IMPORTANT THINKS TO DO:

1. Python Shell is an interactive window where we can type python


code directly and see the output.
Open Python Shell window and type
Ex: >>> print (“JCESS”) or
Ex: >>> 2+3 you will get 5.
2. TAB: When you press the tab button while typing the program, it
will get suggestions related to keywords on the screen.

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.

To run program type


>>>goldenlines ()

PROGRAM-3
Assigning Values to Variables
Example: 1

Example: 2

WWW.JAWAHARCOMPUTEREDUCATION.COM Page 17 of 99
Example: 3

PYTHON CHARACTER SET


Characters set are valid characters that a language can recognize. There are 2
types of character sets in python.

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)

# jcess and aru are identifier


jcess=2
aru=’aadriti’
print(jcess)
print(aru)

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 :

The operator can be defined as a symbol which is responsible for a particular


operation between two operands.
1. Arithmetic operators 2. Comparison operators
3. Assignment Operators 4. Logical Operators
5. Bitwise Operators 6. Membership Operators
7. Identity Operators
PROGRAM-6
(Use Of Arithmetic Operator)

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

we assigned integer literals


(0b10100, 50, 0o320, 0x12b) into
different variables. Here, ‘a‘ is binary
literal, ‘b’ is a decimal literal, ‘c‘ is an
octal literal and ‘d‘ is a hexadecimal
literal. But on using print function to
display value or to get output they
were converted into decimal.

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

print (e, f) output:24.8 45.0

Example: Complex Literal:


The numerals will be in the form of a + bj, where ‘a‘is the real part and
‘b‘is the complex part.

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.

True represents the value as 1 and False represents the value


as 0. In the above example ‘a‘ is True and ‘b‘ is False because 1
equal to True.

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

A tuple is a collection of different data-type. It is enclosed by the


parentheses ‘()‘ and each element is separated by the comma(,). It is
immutable.
WWW.JAWAHARCOMPUTEREDUCATION.COM Page 31 of 99
PROGRAM-16 (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

Dictionary stores the data in the key-value pair. It is enclosed by


curly-braces ‘{}‘ and each pair is separated by the commas(,). We
can store different types of data in a dictionary. Dictionaries are
mutable.
Example:

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

Variable is a name that is used to refer to memory location. Python


variable is also known as an identifier and used to hold value.
Ex : x=5 or x=y=z=1

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

Mutable Variable: List and Dictionary (Literals are mutable variable).


Immutable Variable: int, float, bool, complex, strings, tuples, sets.

VARIABLE ASSIGNMENT AND ACCEPTING INPUT


Taking input is a way of interact with users, or get data to provide
some result. Python provides two built-in methods to read the data
from the keyboard. These methods are given below.
• input(prompt)
• raw_input(prompt) older version (not in use)
PROGRAM-20(Input by user and print welcome msg)
input()
It takes the input from the user and then evaluates the expression.
The Python interpreter automatically identifies the whether a user
input a string, a number, or a list.
# Python program showing
# a use of input()

name = input("Enter your name: ")


print("hello" + name + "welcome in JCESS")

WWW.JAWAHARCOMPUTEREDUCATION.COM Page 35 of 99
PROGRAM-21(Input string,integer,float)

# Python program showing


# a use of input()
name = input("Enter your name: ") # String Input
age = int(input("Enter your age: ")) # Integer Input
m1 = float(input("Enter your M1.R5 marks: ")) # Float Input
m2 = float(input("Enter your M2.R5 marks: ")) # Float Input
m3 = float(input("Enter your M3.R5 marks: ")) # Float Input
m4 = float(input("Enter your M4.R5 marks: ")) # Float Input
total_marks= m1 + m2 + m3 +m4
print("The name is:", name)
print("The age is:", age)
print("Your Total marks are:", total_marks)

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

a = int (input(‘Enter any no’))


if(a%2==0):
print(‘even’)

PROGRAM-24 (IF else Statement)


This statement is used when both the true and false parts of a given
condition are specified to be executed. When the condition is true,
the statement inside the if block is executed; if the condition is false,
the statement outside the if block is executed.

n=input(‘Enter any number=‘)


if(n%2==0):
print(‘even’)
else:
print(‘odd’)
WWW.JAWAHARCOMPUTEREDUCATION.COM Page 39 of 99
#Program for tax calculation, and
print net salary after tax deduction
s=float(input("Enter the salary="))
if(s>50000):
tax=0.10*s
net=s-tax
print('total tax is=',tax)
print('The net salary of=',net)
else:
net=s
print('No taxable Amount')

#Print larger number using swap


x=y=0
x=int(input('Enter the first no.:'))
y=int(input('Enter second no.:'))
if(x>y):
x,y=y,x # swap (interchange)
print('The larger number is:',y)
print('The smallest no. is:',x)
else:
print('The larger number is:',y)
print('The smaller number is:',x)

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

# Python program to demonstrate


# nested if statement
i = 13
if (i == 13):
# First if statement
if (i < 15):
print ("i is smaller than 15")
# Nested - if statement
# Will only be executed if statement above
# it is true
if (i < 12):
print ("i is smaller than 12 too")
else:
print ("i is greater than 12 and smaller than 15")
WWW.JAWAHARCOMPUTEREDUCATION.COM Page 41 of 99
PROGRAM-26 (if ….elif Statement)
In this case, the If condition is evaluated first. If it is false, the Elif
statement will be executed; if it also comes false, the Else statement
will be executed.
# Print week name
ch=int(input('Enter your choice(1 to7)='))
if(ch==1):
print('sun')
elif(ch==2):
print('mon')
elif(ch==3):
print('tue')
elif(ch==4):
print('wed')
elif(ch==5):
print('thu')
elif(ch==6):
print('fri')
elif(ch==7):
print('sat')
else:
print('invalid option')

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

total = amount + surcharge


print("\nElectricity Bill = %.2f" %total)

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:

First it evaluated the condition; if the condition is met then it


executes a single or a block of statements. After the execution, it
again checks the condition and if the condition is found to be true
them it again executes. This means that these statement are
executed continuously unite the conditions false.

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:

Python doesn't have do-while loop.


Program-28 (Example For Loop)
for loop statement is used to repeat a statement or block of statements a
specified number of times.
for i in [1,2,3,4,5]:
print(i)

name = ["anju", "puneet", "jcess"]


for x in name:
print(x)

#printing letters of word


letter = input('enter any word:')
for word in letter:
print(word)

#printing Fibonacci series.


number=int(input("enter no="))
num1=0;num2=1
print(num1)
print(num2)
for i in range(1,number):
num3=num1+num2
print(num3)
num1,num2=num2,num3
WWW.JAWAHARCOMPUTEREDUCATION.COM Page 47 of 99
Range function: The range () is an in-built function in Python. It returns a
sequence of numbers starting from zero and increment by 1 by default and stops
before the given number.
Syntax: range (start, stop, step)

Program-29 (Example Range function)

#(one parameter) only start number


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

#(two parameter) start & stop


for i in range(3,6):
Print(i)

#(Three parameter) start, stop, step


for i in range(2,10,2):
Print(i)

#reverse range
for i in range(5,2,-1):
Print(i)

#print sum of all even numbers


Sum=0
for i in range(2,12,2):
sum=sum+i
Print(“sum of all even no=”,i)
WWW.JAWAHARCOMPUTEREDUCATION.COM Page 48 of 99
Program-30 find the sum of natural numbers using for loop
Natural numbers are the numbers that are used for counting and are a part
of real numbers. The set of natural numbers include only the positive integers,
i.e., 1, 2, 3, 4, 5, 6, ……….∞.

num = int(input("Please enter the number: "))


sum = 0
for value in range(1, num + 1):
sum = sum + value
print(sum)

Program-31 Print all prime numbers within a given range

r=int(input("Enter upper limit: "))


for a in range(2,r+1):
k=0
for i in range(2,a//2+1):
if(a%i==0):
k=k+1
if(k<=0):
print(a)

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 row in range(1,6):


for col in range(1,6) :
print(col, end=' ')
print(" ")

for row in range(1,6):


for col in range(1,row+1) :
print(col, end=' ')
print(" ")

for row in range(1,6):


for col in range(1,row+1) :
print(row, end=' ')
print(" ")
WWW.JAWAHARCOMPUTEREDUCATION.COM Page 51 of 99
Program-33 Print (*) series
for row in range(1,6):
for col in range(1,row+1) :
print(“*”, end=' ')
print("* ")

for row in range(5,-1,-1):


for col in range(1,row+1) :
print("*", end=' ')
print("* ")

for row in range(1,4):


for col in range(1,6) :
print("*", 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()

print("Pattern of Numbers: ")


num = 1
for i in range(5):
for j in range(i+1):
print(num, end=" ")
num = num+1
print()

print("Inverted Half Pyramid of Numbers: ")


decr = 8
for i in range(5):
count = 0
for k in range(decr):
print(end=" ")
decr = decr - 2
for j in range(i+1):
count = count + 1
num = count
for j in range(i+1):
print(num, end=" ")
num = num - 1
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)

Continue statement: It is used to skip the condition. We cannot


use continue statement with switch.
#3 is not available in list.
for a in range(1,6):
if(a==3):
continue
print(a)

#H is not available in list.


for a in 'JAWAHAR':
if(a=='H'):
continue
print(a)

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

Assert statement: The assert statement checks if a given logical expression is


true; or false. Program executes only if the expression is true and otherwise it
will give an assert error.
x = 10
assert x > 0
print('x is a positive number.')

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.

Program-37 (Example String, String Indexing ,Slicing)

#Creating String in Python


str1 = 'Hello JCESSian'
print(str1)
#Using double quotes
str2 = "You are Learning PYTHON"
print(str2)

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

Deleting the String


As we know that strings are immutable. We cannot delete or remove the
characters from the string. But we can delete the entire string using
the del keyword.

p='JAWAHAR'
print(p)
del p
print(p)

WWW.JAWAHARCOMPUTEREDUCATION.COM Page 59 of 99
String Operators
Operator Description

+ It is known as concatenation operator used to join the strings given


either side of the operator.

* It is known as repetition operator. It concatenates the multiple copies of


the same string.

[] It is known as slice operator. It is used to access the sub-strings of a


particular string.

[:] It is known as range slice operator. It is used to access the characters


from the specified range.

in It is known as membership operator. It returns if a particular sub-string is


present in the specified string.

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.

% It is used to perform string formatting. It makes use of the format


specifiers used in C programming like %d or %f to map their values in
python. We will discuss how formatting is done in python.

WWW.JAWAHARCOMPUTEREDUCATION.COM Page 60 of 99
Ex

str = "AADRITI "


str1 = " TIWARI"
print(str*3)
print(str+str1)
print(str[4])
print(str[2:4]);
print('w' in str)
print('WA' not in str1)
print(r'C://python37')
print("The string str : %s"%(str))

Program-38 (Replace to replace character in a string with symbol)

name=str(input("enter your name= "))


ch=str(input("Enter a character you want to change in the entered
string= "))
sy=input("enter the symbol which you want to replace with= ")
ch_name=name.replace(ch,sy)
print("Your name after modification= ",ch_name)

WWW.JAWAHARCOMPUTEREDUCATION.COM Page 61 of 99
STRING OPERATOR:

Program-39 (Join 2 strings)


1. CONCATENATION (+) OPERATOR: Join 2 or more strings.

Example : join string


name1=str(input("enter your name= "))
name2=str(input("enter your surname= "))
join=name1 + name2
print("i am joining your name with surname= ",join)

Program-40 (Repeating strings)


2. REPLICATION (*) OPERATOR: Repeating the string several times.
Example: Repeat string

name1=str(input("enter your name= "))


repeat=name1 * 3
print("I am repeating your name= ",repeat)
Program-41 (Repeating strings)
3. MEMERSHIP (in) OPERATOR: This operator returns true if a character is
available in the given string.
name1=str(input("enter your name= "))
print((‘I’) in name1 Enter jcess you will get TRUE

name1=str(input("enter your name= "))


print((‘I’) in name1 Enter aru you will get FALSE

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

5. STRING SLICES: Slicing is a mechanism used to select a range of items


from sequence. You can retrieve a slice(sub-string) of a string.

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

STRING FUNCTION AND METHODS

Python provides built-in functions and methods that allow us to do string


manipulation.

1. >>>str = ‘jcess’ >>>len(str) output : 5


2. >>>str=”Jcess” >>>print(str.count(“s”) output:2
3. >>>str=”jcess” >>>str.capitalize() output:JCESS
4. >>>str=”come to jcess” >>>str.find(‘jcess’) output=8
WWW.JAWAHARCOMPUTEREDUCATION.COM Page 63 of 99
5. >>>str=’jcess’ >>>str.isalnum() output : true
6. >>>str=’jcess’ >>>str.isalpha() output: true
7. >>>str=’jcess1’ >>>str.isalpha() output:false
8. >>>str=’90’ >>>str.isdigit() output:true
9. >>>str=’JCESS’ >>>str.lower() output:jcess
10. >>>str=’JCESS’ >>>str.islower() output:false
11. >>>str=’jcess’ >>>str.upper() output:JCESS
12. >>>str=’jcess’ >>>str.isupper() output:false
13. >>>str=’ jcess’ >>>str.Istrip() output:jcess
14. >>>str=’jcess ‘ >>>str.rstrip() output:jcess
15. >>>str=’jcess’ >>>print(str.isspace()) output:false
16. >>>str=’we are in lucknow’ >>>str.replace(‘lucknow’,’kanpur’)
Output: we are kanpur
17. >>>str=”we are jcess’ins”
>>>words=str.split()
>>>words
Output : [‘we’,’are’,’jcessians’]
18. >>>str1=('we','are','jcessians')
>>> str=' '
>>> str.join(str1)
Output :'we are jcessians'
19. >>>str=’JCESS’ >>>print(str.swapcase()) output:jcess
20. >>>str=”we are jcessians” >>>str.partition(‘jcess’)
Output=(‘we’, ‘are’, ’jcess’, ‘ians’)

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:

Ex: fruits = ["apple", "banana", "cherry"]


print(fruits)
Duplicate value:
Ex: fruits = ["apple", "banana", "cherry", "apple", "cherry"]
print(fruits)

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

list1 = ["apple", "banana", "cherry"]


list2 = [1, 5, 7, 9, 3]
list3 = [True, False, False]
list4 = ["abc", 34, True, 40, "male"]
print(list1)
print(list2)
print(list3)
print(list4)

Access List Items


List items are indexed and you can access them by referring to the index
number:

WWW.JAWAHARCOMPUTEREDUCATION.COM Page 66 of 99
list_varible(start:stop:step)

• The start denotes the starting index position of the list.


• The stop denotes the last index position of the list.
• The step is used to skip the nth element within a start:stop

Consider the following example:

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

Operator Description Example

Repetition The repetition operator enables the list L1*2 = [1, 2, 3,


elements to be repeated multiple times. 4, 1, 2, 3, 4]
Concatenation It concatenates the list mentioned on l1+l2 = [1, 2, 3,
either side of the operator. 4, 5, 6, 7, 8]

Membership It returns true if a particular item exists print(2 in l1)


in a particular list otherwise false. prints True.

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

Removing elements from the list


Python provides the remove() function which is used to remove the element from the list.

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

1 cmp(list1, It compares the This method is not used in the Python


list2) elements of both the 3 and the above versions.
lists.
2 len(list) It is used to calculate L1 = [1,2,3,4,5,6,7,8]
the length of the list. print(len(L1))
8

3 max(list) It returns the L1 = [12,34,26,48,72]


maximum element of print(max(L1))
72
the list.

4 min(list) It returns the minimum L1 = [12,34,26,48,72]


element of the list. print(min(L1))
12

5 list(seq) It converts any str = "Johnson"


sequence to the list. s = list(str)
print(type(s))
<class list>

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

tuple1 = tuple(input("Enter the tuple elements ..."))


print(tuple1)
count = 0
for i in tuple1:
print("tuple1[%d] = %s"%(count, i))
count = count+1

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)

Basic Tuple operations


Operator Description Example

Repetition The repetition operator enables the T1*2 = (1, 2, 3,


4, 5, 1, 2, 3, 4,
tuple elements to be repeated multiple
5)
times.

Concatenation It concatenates the tuple mentioned on T1+T2 = (1, 2, 3,


4, 5, 6, 7, 8, 9)
either side of the operator.

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

Length It is used to get the length of the tuple. len(T1) = 5

Python Tuple inbuilt functions

SN Function Description

1 cmp(tuple1, It compares two tuples and returns true if tuple1 is greater


tuple2) than tuple2 otherwise false.

2 len(tuple) It calculates the length of the tuple.

3 max(tuple) It returns the maximum element of the tuple

4 min(tuple) It returns the minimum element of the tuple.

5 tuple(seq) It converts the specified sequence to the tuple.

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

2 The List is mutable. The tuple is immutable.

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

Days = {"Monday", "Tuesday", "Wednesday", "Thursday", "Friday",


"Saturday", "Sunday"}
print(Days)
print(type(Days))
print("looping through the set elements ... ")
for i in Days:
print(i)

WWW.JAWAHARCOMPUTEREDUCATION.COM Page 77 of 99
Program-51
Using set() method

Days = {"Monday", "Tuesday", "Wednesday", "Thursday",


"Friday", "Saturday", "Sunday"}
print(Days)
print(type(Days))
print("looping through the set elements ... ")
for i in Days:
print(i)

Adding items to the set

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

months = set(["January","February", "March", "April", "May",


"June"])
print("\nprinting the original set ... ")
print(months)
print("\nAdding other months to the set...");
months.add("July");
months.add ("August");
print("\nPrinting the modified set...");
print(months)
print("\nlooping through the set elements ... ")
for i in months:
print(i)

WWW.JAWAHARCOMPUTEREDUCATION.COM Page 79 of 99
Using update() function

Months = set(["January","February", "March", "April", "May",


"June"])
print("\nprinting the original set ... ")
print(Months)
print("\nupdating the original set ... ")
Months.update(["July","August","September","October"]);
print("\nprinting the modified set ... ")
print(Months);

Using remove() function

months = set(["January","February", "March", "April"])


print(months)
months.remove("January");
months.remove("March");
print("\nPrinting set after remove...");
print(months)

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

Opening a file open() method

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

#opens the file file.txt in read mode.


#save the file in same folder.
fileptr = open("aru.txt","r")
if fileptr:
print("file is opened successfully")

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.

# opens the file file.txt in read mode


fileptr = open("aru.txt","r")
if fileptr:
print("file is opened successfully")
#closes the opened file
fileptr.close()

Writing the file


To write some text to a file, we need to open the file using the open method
with one of the following access modes.
w: It will overwrite the file if any file exists. The file pointer is at the beginning of
the file.
a: It will append the existing file. The file pointer is at the end of the file. It
creates a new file if no file exists.
Program-56

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

Renaming the file


The Python os module enables interaction with the operating system. The os
module provides the functions that are involved in file processing operations like
renaming, deleting, etc. It provides us the rename() method to rename the
specified file to a new name. The syntax to use the rename() method is given below.
import os To see the file name change
#rename file2.txt to file3.txt C:>>computer>>python32>>see file
os.rename("aru.txt","aadriti.txt") name

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.

import os; File deleted.


#deleting the file named file3.txt To see :
C:>>computer>>python32
os.remove("file3.txt")

Creating the new directory


The mkdir() method is used to create the directories in the current working
directory. The syntax to create the new directory is given below.
Syntax:

mkdir(directory name)

import os File deleted.


#creating a new directory with the To see :
name new C:>>computer>>python32
os.mkdir("jcess")

Get Current working directory

import os File deleted.


os.getced() To see :
C:>>computer>>python32

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

def sum(num1, num2):


return (num1 + num2)

def Subtract (a, b):


return (a-b)
print( Subtract(10, 12) ) # prints -2
print( Subtract(15, 6) ) # prints 9

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

# Example Function & Method


a="jcess"
print(len(a)) #function
print(a.upper()) #method

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.

Writing and importing modules: we can import modules like this


1. Import math
2. Import os.sys
3. From math import sqrt, pi, exp, log, sin
4. Import os as operatingSystem

Program-59 (Create Module)-user defiined


Step -1 Write a code and save file name area.py

# to create area module area.py


import math
def area_circle(radius):
return math.pi*radius*radius
def area_square(side):
return side*side
def area_rectangle(length,breadth):
return length*breadth

WWW.JAWAHARCOMPUTEREDUCATION.COM Page 91 of 99
Step -2 Write a code and save file name anju.py

#importing module area.py(user defined) in math.py(which is predefined)


import area
print(area.area_circle(2)) # area is module name
print(area.area_square(5))
print(area.area_rectangle(8,4))

Step-3 Run this code.

Program-60 (Call specific function from module)

We can call specific function module from module.


Ex :
from area import area_circle
print(area_circle(3))

We can call all sub modules from module


from area import *
print(area_circle(2))
print(area_square(5))
print(area_rectangle(8,4))

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

Example: Local (user defined function)


def num():
x=5 # x is local to num function
print(x)
num()
print(x) # outside of the num function
The local namespace is deleted when the function or the code block finished its
execution.

Example: Enclosed (User Defined function)


def num():
x=5
def num1():
print(x)
num1()
print(x)
num()
If one function is defined inside another function is called enclosed.
If the variable name is same, python does not find variable in local scope. It will
examine the enclosing scope to find the same variable.

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.

Example: Built-in function (len function)

x=len(“jcess”)
print(x)
print(x)

Example: Anonymous function)


We can use the lambda keyword to create small anonymous functions. These
functions are not declared in the standard manner by using def keyword.
1. Lambda forms can take any number of arguments but return just one value
in the form of an expression.
Return Statement : A return function is optionally return a value. it will return to
function.

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

Creating a ndarray object

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.

>>> import numpy as np


>>> arr = np.array([[1, 2, 3, 4], [4, 5, 6, 7], [9, 10, 11, 23]])
>>> print(arr.ndim)
import numpy as np
a = np.array([1,2,3,10,15,4])
print("The array:",a)
print("The maximum element:",a.max())
print("The minimum element:",a.min())
print("The sum of the elements:",a.sum())
WWW.JAWAHARCOMPUTEREDUCATION.COM Page 96 of 99
NumPy Array Axis

A NumPy multi-dimensional array is represented by the axis where


axis-0 represents the columns and axis-1 represents the rows. We can
mention the axis to perform row-level or column-level calculations like
the addition of row or column elements.

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]

Arithmetic operations on the array

The numpy module allows us to perform the arithmetic operations on


multi-dimensional arrays directly.

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

The numpy provides us with the vertical stacking and horizontal


stacking which allows us to concatenate two multi-dimensional arrays
vertically or horizontally.

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

You might also like