Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
157 views

O_Level_Module_3_M3_R5_Programming_&_Problem_Solving_Through_Python

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

O_Level_Module_3_M3_R5_Programming_&_Problem_Solving_Through_Python

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

Search on TG: @apna_pdf

NIELIT(DOEACC) O'level Revision-V

O'level
Module-3[M3-R5]
Programming and Problem
Solving Through Python
Language
Study Material
&

Objective Question Bank


Chief Editor
A. K. Mahajan
Compiled and Edited by
Mahima Tripathi
Computer Graphics by
Balkrishna, Charan Singh, Anurag Pandey
Editorial Office
12, Church Lane Prayagraj-211002
Mob. : 9415650134
Email : yctap12@gmail.com
website : www.yctbooks.com / www.yctfastbook.com
© All rights reserved with Publisher
Publisher Declaration :
Edited and Published by A.K. Mahajan for YCT Publications Pvt. Ltd. and printed by Roop
Printing Press, Prayagraj. In order to Publish the book,
full care has been taken by the Editor and the Publisher,
still your suggestions and queries are welcomed. Rs. : 295/-
In the event of any dispute, the judicial area will be Prayagraj.
Search on TG: @apna_pdf
Contents
M3R5
Programming and Problem Solving Through Python
(xii) Algorithm for converting a decimal number to binary 22
1.INTRODUCTION TO PROGRAMMING
(xiii)A flowchart to check whether a number is Prime or
1.1 Basic Model of Computation ------------------------------ 6
not ---------------------------------------------------------22
1.2 Algorithm ------------------------------------------------------ 6
(xiv) Flowchart for printing the Fabonic Series ------------22
1.3 Flowchart ------------------------------------------------------- 7 (xv) Write an algorithm and draw flowchart to count and
(i) Rules for Creating a Flowchart ---------------------------- 7 sum (add) the total number of even numbers between
(ii) Flowchart Symbols ----------------------------------------- 7 1 and 100 ------------------------------------------------23
(iii) Characteristics of Flowchart ----------------------------- 7 (xvi) Algorithm, pseudo code and Flowchart for Tower of
1.4 Psuedo Code --------------------------------------------------- 8 Hanoi ------------------------------------------------------23
1.5 Programming Language ------------------------------------- 8 2.4 Types of Algorithm --------------------------------------------23
1.6 Compiler --------------------------------------------------------- 9 Practice Questions with Explanatory Solutions ---24-26
1.7 Interpreter ---------------------------------------------------- 10
1.8 Difference between Compiler and Interpreter ------- 11
3. INTRODUCTION TO PYTHON
1.9 Linker --------------------------------------------------------- 11 3.0 Introduction --------------------------------------------------27
1.10 Loader -------------------------------------------------------- 11 3.1 Characteristics of Python ----------------------------------27
1.11 Difference between Linker and Loader ------------- 11 3.2 History of Python --------------------------------------------27
1.12 Testing and Debugging ---------------------------------- 12 3.3 Technical Strength of Python ----------------------------27
1.13 Testing a Program ---------------------------------------- 12 3.4 Introduction to Python Interpreter and Program -----28
(i) Difference between Testing and Debugging ---------- 13 3.5 To Download and Install Python-------------------------28
(ii) Difference between Bug and Virus -------------------- 13 3.6 How to Start Python ----------------------------------------30
1.14 Documentation --------------------------------------------- 13 (i) Interactive Mode (Command-Line) ---------------------30
Practice Questions with Explanatory Solutions--- 14-15 (ii) IDLE-Script Mode ----------------------------------------31
2. ALGORITHM AND FLOWCHARTS (iii) Difference Between Interactive Mode and Script
2.1 Introduction ------------------------------------------------- 16 Mode -------------------------------------------------------31
2.2 Sequencial, Decision based & iterative processing 3.7 Creating Python Program ---------------------------------31
for flowchart ------------------------------------------------ 16 3.8 IDLE Menu ---------------------------------------------------33
(i) Sequencial Processing ------------------------------------ 16 3.9 Comments -----------------------------------------------------33
(ii) Decision Based Processing ----------------------------- 17
3.10 Python Character Set -------------------------------------33
(iii) How to Write a General Flowchart? ------------------ 18
3.11 Token ---------------------------------------------------------34
2.3 Sample Algorithms ---------------------------------------- 19
(i) Interchanging the Values of Two Variables (without 3.12 Identifiers ----------------------------------------------------34
using a temporary variable) --------------------------- 19 3.13 Keyword/Reserve Words --------------------------------34
(ii) Algorithm for computing simple interest ------------ 19 3.14 Literal ----------------------------------------------------------35
(iii) Algorithm to calculate area of triangle --------------- 19 3.15 Variable ------------------------------------------------------35
(iv) Flowchart to add two numbers entered by the user 19 (i) To Manipulate Variables ---------------------------------35
(v) Algorithm to print the factorial of an integer number - 20
(ii) Types of Variable -----------------------------------------36
(vi) Algorithm and flowchart to generate a table of a
(iii) Mutable and Immutable ---------------------------------36
number --------------------------------------------------- 20
(iv) Variable Assignment & Accepting Input -------------36
(vii) Write an algorithm that takes three numbers as input
and outputs largest number ---------------------------- 20 (v) Working with Dynamic Typing -------------------------36
(viii)Write an algorithm to accept the python language 3.16 Constant ------------------------------------------------------37
marks to print the respective grade [NIELIT 'O' 3.17 Data Types----------------------------------------------------37
LEVEL] -------------------------------------------------- 20
3.18 Print Statement ---------------------------------------------38
(ix) Palindrome ----------------------------------------------- 21
3.19 To Accept Input from Console -------------------------38
(x) Draw a flowchart and write algorithm to check and
(i) eval ( ) Function --------------------------------------------39
print an Armstrong number---------------------------- 21
(xi) Write an algorithm and draw flowchart to sum a set 3.20 Simple Python Programs ---------------------------------39
of numbers ----------------------------------------------- 22 Practice Questions with Explanatory Solutions ---40-42

2
Search on TG: @apna_pdf
4. OPERATORS, EXPRESSION & 5.8 Accessing List ------------------------------------------------65
(i) Indexing -----------------------------------------------------66
PYTHON STATEMENTS (ii) Slicing ------------------------------------------------------66
4.1 Operators ----------------------------------------------------- 43 (iii) Traversing -------------------------------------------------67
(i) Arithmetic Operators ------------------------------------- 43 5.9 List Operations -----------------------------------------------69
(ii) Relational Conditional Operators ---------------------- 44 (i) Joining List -------------------------------------------------69
(iii) Logical/Boolean Operators ----------------------------- 45 (ii) Repeating List ---------------------------------------------69
(iv) Assignment Operators----------------------------------- 45 (iii) Slicing List ------------------------------------------------69
(v) Bitwise Operators ---------------------------------------- 47 (iv) Comparing List -------------------------------------------69
(vi) Membership Operators ---------------------------------- 47
5.10 Object and Value -------------------------------------------69
(vii) Identity Operators --------------------------------------- 47
(i) Aliasing------------------------------------------------------70
4.2 Expression ---------------------------------------------------- 48
5.11 List Function and Methods-------------------------------70
4.3 Control Statement ------------------------------------------- 48
(i) len ( ) --------------------------------------------------------70
4.4 Conditional Statement ------------------------------------- 48 (ii) count ( ) -----------------------------------------------------70
(i) If Statement ------------------------------------------------ 48 (iii) append ( ) --------------------------------------------------70
(ii) If-else Statement ------------------------------------------ 48 (iv) extend ( ) ---------------------------------------------------71
(iii) If-elif-else Statement ------------------------------------ 49 (v) insert ( ) -----------------------------------------------------71
(iv) Nested If Statement -------------------------------------- 49 (vi) pop ( ) ------------------------------------------------------71
4.5 Nested If Statement (Iteration) -------------------------- 49 (vii) remove ( ) -------------------------------------------------71
(i) While Statement ------------------------------------------- 50 (vii) del ( ) ------------------------------------------------------71
(ii) For Statement --------------------------------------------- 50 (ix) reverse ( ) --------------------------------------------------72
(iii) do-while loop Statement -------------------------------- 51 (x) sort ( ) -------------------------------------------------------72
4.6 Range ( ) Function ------------------------------------------ 52 (xi) clear ( ) -----------------------------------------------------73
4.7 Nested Loop ------------------------------------------------- 52 (xii) max ( ) and min ( ) --------------------------------------73
4.8 Jump Statement --------------------------------------------- 52 5.12 Linear Search ------------------------------------------------73
4.9 Assert Statement -------------------------------------------- 53 5.13 Tuple -----------------------------------------------------------73
Practice Questions with Explanatory Solutions--- 54-57 (i) Difference between List and tuple -----------------------73
5. SEQUENCE DATA TYPE (ii) Tuple is Immutable ---------------------------------------73
5.0 Introduction -------------------------------------------------- 58 5.14 Creating, Initializing and Accessing of Elements in
5.1 String ---------------------------------------------------------- 58 Tuple------------------------------------------------------------74
(i) To Create String ------------------------------------------- 58 (i) Creating Tuple ----------------------------------------------74
5.2 Logical and Physical Line -------------------------------- 58 (ii) Tuple Assignment -----------------------------------------74
5.3 Working with Strings -------------------------------------- 59 (iii) Accessing Elements in Tuple ---------------------------74
(i) Strings are immutable ------------------------------------ 59 (iv) Membership Test in Tuples -----------------------------74
(ii) String Traverse-------------------------------------------- 59 (v) Identity Operator in Tuples ------------------------------74
(iii) Strings Formatting --------------------------------------- 60 5.15 Tuples Function ---------------------------------------------75
5.4 Special String Operators ---------------------------------- 60 (i) Tuples ( ) ----------------------------------------------------75
(i) Concatenation Operators --------------------------------- 60 (ii) len ( ) --------------------------------------------------------75
(ii) Application Operators ----------------------------------- 61 (iii) count ( ) ---------------------------------------------------75
(iii) Membership Operators (in) ---------------------------- 61 (iv) index ( ) ----------------------------------------------------75
(iv) Membership Operators (not in) ------------------------ 61 (v) Sorted ( ) ----------------------------------------------------75
(v) Comparison Operators ----------------------------------- 61 (vi) min ( ), max ( ) & sum ( ) -------------------------------75
5.5 String Slices -------------------------------------------------- 61 5.16 Tuple Operation---------------------------------------------75
5.6 String Functions and Methods --------------------------- 62 (i) Tuple Slicing -----------------------------------------------75
(i) Len ( ) ------------------------------------------------------- 62 (ii) Tuple Addition --------------------------------------------76
(ii) Capitlize ( ) ------------------------------------------------ 62 (iii) Tuple Multiplication -------------------------------------77
(iii) Find ( ) ---------------------------------------------------- 62 (iv) Deleting Tuple --------------------------------------------76
(iv) isalnum ( ) ------------------------------------------------ 62 5.17 Packing and Unpacking Tuple --------------------------76
(v) isalpha ( ) -------------------------------------------------- 63 5.18 Dictionary Initialization ----------------------------------77
(vi) isdigit ( ) -------------------------------------------------- 63 (i) Key:Value Pair ---------------------------------------------77
(vii) lower & islower ( ) -------------------------------------- 63 (ii) Characteristics of Dictionary ----------------------------77
(viii) Upper & isupper ( ) ------------------------------------ 63 (iii) To Create Dictionary ------------------------------------77
(ix) lstrip & rstrip ( )------------------------------------------ 63 (iv) Dictionary Initialization ---------------------------------77
(x) isspace, istitle, replace, join, swapcase & start ( ) ----- 63 (vi) Dictionary Traversing ------------------------------------79
(xi) Partition ( ) ------------------------------------------------ 64 (vii) To Update and Delete Values in Dictionary ---------79
5.7 List Manipulation ------------------------------------------- 64 5.19 Dictionary Functions and Method ---------------------80
(i) Creating List ----------------------------------------------- 64 (i) clear ( ) ------------------------------------------------------80
(ii) Mutable List ----------------------------------------------- 65 (ii) dict ( ) -------------------------------------------------------80
3
Search on TG: @apna_pdf
(iii) cmp ( )----------------------------------------------------- 80 (vi) write ( )--------------------------------------------------- 105
(iv) len ( ) ------------------------------------------------------ 80 (vii) writelines ( ) -------------------------------------------- 106
(v) get ( ) ------------------------------------------------------- 80 (viii) append ( ) ---------------------------------------------- 106
(vi) pop ( ) ----------------------------------------------------- 80 (ix) tell ( ) ----------------------------------------------------- 106
(vii) dict⋅popitem ( ) ------------------------------------------ 80 (x) seek ( ) ---------------------------------------------------- 106
(viii) keys ( ) --------------------------------------------------- 81 (xi) rename ( ) ------------------------------------------------ 106
(ix) values ( ) -------------------------------------------------- 81 (xii) remove ( ) ----------------------------------------------- 107
(x) items ( ) ---------------------------------------------------- 81
7.7 Working with Binary Files ----------------------------- 107
Practice Questions with Explanatory Solutions--- 81-83
7.8 Command Line Argument ------------------------------ 108
6. FUNCTIONS Practice Questions with Explanatory Solutions ---109-111
6.1 Top-Down approach for Problem Solving------------ 84
8. SCOPE AND MODULE
6.2 Bottom-Up approach for Problem Solving ---------- 84
8.1 Object and Name Scope --------------------------------- 112
6.3 Modular Programming ------------------------------------ 85
(i) Advantages of Modular Programming ----------------- 85 (i) Global Keyword ------------------------------------------ 112
6.4 Function ------------------------------------------------------- 86 (ii) Non-Local Keyword ------------------------------------ 113
(i) Advantage of Python Function ------------------------- 86 (i) Local ( ) & Globals ( ) ----------------------------------- 113
(ii) Difference between Module, Package and Library in 8.2 LEGB Rule ------------------------------------------------- 113
Python ----------------------------------------------------- 86 8.3 Module ------------------------------------------------------- 114
6.5 Types of Function ------------------------------------------ 87 8.4 Namespace -------------------------------------------------- 115
(i) Module------------------------------------------------------ 87 8.5 Import Module --------------------------------------------- 115
(ii) Built in Function------------------------------------------ 87
(i) To Create and Import Module -------------------------- 115
(iii) User Defined Function ---------------------------------- 87
(ii) Python Path --------------------------------------------- 115
6.6 To Define a Function -------------------------------------- 87
(i) Calling Function ------------------------------------------- 88 8.6 Package ------------------------------------------------------ 116
(ii) Return Statement ----------------------------------------- 88 8.7 Re-Loading Module -------------------------------------- 116
6.7 Python Program Structure -------------------------------- 88 Practice Questions with Explanatory Solutions --- 116-118
6.8 Docstring ----------------------------------------------------- 89 9. NUMPY BASICS
6.9 Function Parameter and Arguments ------------------- 89
6.10 Types of Arguments -------------------------------------- 89 9.1 Introduction of NumPy ---------------------------------- 119
6.11 Anonymous Function ------------------------------------ 91 9.2 nd Array ----------------------------------------------------- 120
6.12 Return Statement ----------------------------------------- 91 9.3 Data Types --------------------------------------------------- 120
6.13 Global and Local Variables ----------------------------- 92 9.4 Array Attribute -------------------------------------------- 120
6.14 Void Function --------------------------------------------- 92 (i) Ndim ------------------------------------------------------- 120
6.15 Library Function ------------------------------------------ 92 (ii) Shape------------------------------------------------------ 121
6.16 String Function -------------------------------------------- 93 (iii) Size ------------------------------------------------------- 121
6.17 Pattern Matching ------------------------------------------ 96 (iv) dtype------------------------------------------------------ 121
(i) Metacharacter ---------------------------------------------- 96 (v) item size -------------------------------------------------- 121
(ii) Special Sequence ----------------------------------------- 96 (vi) Re Shape ------------------------------------------------- 121
6.18 Numerical Function -------------------------------------- 97 9.5 Array Creation ---------------------------------------------- 121
6.19 Random Module ------------------------------------------ 98 (i) empty ( ) --------------------------------------------------- 121
Practice Questions with Explanatory Solutions 100-102 (ii) zero ( ) ---------------------------------------------------- 122
7. FILE PROCESSING (iii) ones ( ) --------------------------------------------------- 122
7.0 Concept of Files ------------------------------------------- 103 (iv) copy ( ) --------------------------------------------------- 122
(i) Types of Files --------------------------------------------- 103 9.6 Array Creation Routine ----------------------------------- 123
7.2 To Open file in Different Modes ---------------------- 103 9.7 Array from Existing Data -------------------------------- 123
7.3 To Open and Read files --------------------------------- 104 9.8 Array from Numerical Range -------------------------- 124
7.4 To Close a File --------------------------------------------- 104 (i) np⋅arange -------------------------------------------------- 124
7.5 To Write Files ---------------------------------------------- 104 (ii) np⋅linspace ----------------------------------------------- 124
7.6 File Function ----------------------------------------------- 105 (iii) numpy⋅logspace ---------------------------------------- 124
(i) open ( )----------------------------------------------------- 105 9.9Indexing and Slicing --------------------------------------- 124
(ii) close ( ) --------------------------------------------------- 105
9.10Joining and Spliting --------------------------------------- 125
(iii) read ( )---------------------------------------------------- 105
(iv) readline ( ) ----------------------------------------------- 105 9.11 Arithmetic Operation on Array ----------------------- 125
(v) readlines ( ) ----------------------------------------------- 105 Practice Questions with Explanatory Solutions --- 126-128
4
Search on TG: @apna_pdf
Detailed Syllabus NIELIT O level Python
(i) Introduction to Programming
The basic Model of computation, algorithms, flowcharts, Programming Languages, compilation, testing &
Debugging and documentation.
(ii) Algorithms and Flowcharts to Solve Problems
Flow Chart Symbols, Basic algorithms/flowcharts for sequential processing, decision based processing and
iterative processing. Some examples like: Exchanging values of two variables, summation of a set of
numbers, Decimal Base to Binary Base conversion, Reversing digits of an integer, GCD (Greatest Common
Division) of two numbers, Test whether a number is prime, factorial computation, Fibonacci sequence,
Evaluate ‘sin x’ as sum of a series, Reverse order of elements of an array, Find largest number in an array,
Print elements of upper triangular matrix, etc.
(iii) Introduction to Python
Python Introduction, Technical Strength of Python, Introduction to Python Interpreter and program execution,
Using Comments, Literals, Constants, Python’s Built-in Data types, Numbers (Integers, Floats, Complex
Numbers, Real, Sets), Strings (Slicing, Indexing, Concatenation, other operations on Strings), Accepting
input from Console, printing statements, Simple ‘Python’ programs.
(iv) Operators, Expressions and Python Statements
Assignment statement, expressions, Arithmetic, Relational, Logical, Bitwise operators and their precedence,
Conditional statements: if, if-else, if-elif-else; simple programs, Notion of iterative computation and control
flow –range function, While Statement, For loop, break statement, Continue Statement, Pass statement, else,
assert.
(v) Sequence Data Types
Lists, tuples and dictionary, (Slicing, Indexing, Concatenation, other operations on Sequence data type),
concept of mutability, Examples to include finding the maximum, minimum, mean; linear search on list/tuple
of numbers, and counting the frequency of elements in a list using a dictionary.
(vi) Functions
Top-down approach of problem solving, Modular programming and functions, Function parameters, Local
variables, the Return statement, DocStrings, global statement, Default argument values, keyword arguments,
VarArgs parameters.
Library function-input(), eval(),print(), String Functions: count(), find(), rfind(), capitalize(), title(), lower(),
upper(), swapcase(), islower(), isupper(), istitle(), replace(), strip(), lstrip(), rstrip(), aplit(), partition(), join(),
isspace(), isalpha(), isdigit(), isalnum(), startswith(), endswith(), encode(), decode(), String: Slicing,
Membership, Pattern Matching, Numeric Functions: eval(), max(), min(), pow(), round(), int(), random(),
ceil(), floor(), sqrt(), Date & Time Functions, Recursion
(vii) File Processing
Concept of Files, File opening in various modes and closing of a file, Reading from a file, Writing onto a file,
File functions-open(), close(), read(), readline(),readlines(),write(), writelines(),tell(),seek(), Command Line
arguments.
(viii) Scope and Modules
Scope of objects and Names, LEGB Rule
Module Basics, Module Files as Namespaces, Import Model, Reloading Modules.
(ix) NumPy Basics
Introduction to NumPy ,ndarray, datatypes, array attributes, array creation routines, Array From Existing
Data, Array From Numerical Ranges, Indexing & Slicing.

5
Search on TG: @apna_pdf

1 INTRODUCTION TO
PROGRAMMING

1.1 Basic Model of Computation: ● The output that will be obtained after following the
A computational model is a computer model that steps should also be defined in advance.
provides a scientific solution to a complex problem. In ● The process should be completely clear. An algorithm
general, it requires a mathematical model or that creates confusion can be a waste of time and
representation made for a particular problem. Software resources.
implementation of computational models often requires ● The algorithm should be simple, general and practical,
high performance computing. Programs are written in such that it can be executed with available resources.
computer language to perform a particular task in the ● The designed algorithm should be language
computer. For problem solving on computer, a step by independent i.e. it should only be explicit instructions
step solution has to be written using simple instructions that can be implemented in any language yet the output
for an operation and thus, the output is obtained. will be the same.
Following are the steps involved in a typical process Algorithms are written in different fields to perform
to solve a problem– different tasks and solve problems. Almost everything
● Understanding the problem becomes clear after writing it, then it is implemented by
● Creating a variable list coding in any programming language. An algorithm
● Output Design must contain a description of the computational process,
● Program Development conditions to input and output, a sequence of explicit
● Testing the Program instructions. The following are examples to understand
● Validating the data. how to design an algorithm:
There are six basic computational models such as
Turing, Von Neumann, Dataflow, Applicative, Object Example– (i) Algorithm for making tea
Based, Predicate Logic Based etc. These models are Step 1 First of all put water in a utensil and heat it.
known as basic models because they are declared using a Step 2: Add tea, sugar and milk to the water.
basic set of extractions. Step 3: Wait till the tea boils.
Step 4: Switch off the gas and strain the tea.
1.2 Algorithm:
Step 5: Tea is ready now you can drink it.
It is a set of instructions, which defines the entire
process of solving a problem. Its main goal is to get the
Example– (ii) Algorithm to find the square of a number;
desired result. There are many continuous steps in it,
Step 1: Begin
after the completion of which the output comes.
Step 2: Assume the variable as n and s.
Computer needs program or software to do any kind of
Step 3: Input the value is n.
work. A computer program is created by programming.
Step 4: Perform square and store in variables. or,
In programming, we have to write instructions step by
s←n*n.
step and these defined steps are called algorithms. It is
Step 5: Show the result.
prepared before coding and the code is written
Step 6: End the process.
accordingly. Flowcharts are also made from the
Following are the advantages of the algorithm–
algorithm itself, which represents the entire process in a
● Algorithm divides the solution of any problem in small
schematic way.
parts. Which makes it easy to understand.
Characteristics of Algorithm– To write a correct
● After creating the algorithm, you can represent it into a
algorithm, many things have to be kept in mind.
flowchart, also after that you can convert it into any
Following are some of the important features of the programming language.
algorithm– ● The list of items required to complete the task which is
● An algorithm must have a finite number of steps decided in advance.
always. The algorithm must terminate after a finite ● Makes decision making easier.
number of steps. ● It is independent of programming language.
● To solve a problem, we need somethings which is ● Debugging is easier because each step is arranged in a
called inputs. An algorithm can have 0 or more inputs. logical sequence.
6
Search on TG: @apna_pdf
1.3 Flowchart: 1.3(ii) Flowchart Symbols:
A flowchart is a graphical representation of an A flowchart is a graphical image that shows the
algorithm that shows the steps of a process. Many steps of a process. Symbols used in the flowchart are as
follows–
symbols are used in flowchart Such as- Square,
Rectangle, Diamond, Arrows, Oval etc. A flowchart is
made by connecting all these symbols to each other. In Start/End– That's an Oval
this, different symbols are used for different types of Symbol which is used to start/end and pause the process.
instructions. Through flowchart, it is easy to get This is the first and last symbol in the flowchart. It is also
called terminal.
communication information in any program and the
program can be easily understood. By looking at the Input/Output Symbol– Input / output
flowchart, the process of flowchart can be implemented is represented using this symbols. Its symbol is a
in any programming language. The graphical parallelogram.
presentation of an algorithm is called a flowchart.
Processing Symbol– This is a
Benefits of using flowchart–
● Flowchart becomes easy for communication. rectangular symbol that contains instructions for
processing. It is used to represent mathematical
● It becomes easy to understand the program which we
operations like addition, subtraction, multiplication and
are making or, the program in which we are solving division etc.
the problem.
● The order of data flow is also displayed.
● Best tool to design new software while creating any Decision Symbol– There is a decision
new programming. symbol. It consists of decisions like True/False or Yes /
● Flowcharts serve as a blueprint during system analysis No.
and program development. Flow Line Symbol– Flow Lines tells the
Disadvantages of using flowchart– flow direction of the flowchart i.e. the direction of the
flowchart. Its picture is Arrow (→), whose direction can
● Flowchart takes a lot of time, which is absolutely be up, down, right or left.
useless for people who are experts in software
development.
● Flowcharts are a bit difficult to produce and manage. Connector Symbol– Its picture is circle.
● Transformation can be a hassle when using flowcharts. The O symbol is used to connect two or more parts of the
● Flowchart symbols cannot be typed. flowchart.
1.3(i) Rules for Creating a Flowchart:
Hexagon Symbol– This symbol is also
There are some rules to make a flowchart, using
which we can easily make a flowchart. These rules also called Preparation Symbol. It is used to introduce for
make easy to understand the flowchart. These rules are loop, while loop or other loop. Its picture is a hexagon.
as follows–
● While making the flowchart all the symbols used are Document Symbol– Document Symbol
connected by arrows, so that we get to know in which is used to display the document.
direction the flowchart is leading. 1.3 (iii) Characteristics of Flowchart:
● All flowcharts have a starting and ending point. Following are the main characteristics of flowchart–
● When using some condition in the flowchart, it has ● Flowchart is a sequence of different steps of a
two exit points, which can be on the top, bottom or function.
● Flowchart is a graphical description of program logic.
side. It has two outputs– one if the condition is true
● It shows the relationship and logic flow between
and the other if the condition is false. different parts of the program.
● Not all the details should be given in the flowchart. ● It graphically depicts the various steps of the program
● Stick to precise and easy-to-understand detail in and hence is easy to understand.
flowchart symbols. ● Flowchart helps in correcting and modifying program
errors.
● While designing flowchart, it is necessary to have end
● It does not depend on any language.
points from left to right and top to bottom. ● It is a part of the program documentation.
7
Search on TG: @apna_pdf
1.4 Psuedo Code: The computer executes all the instructions written in
It is a way of designing program logic to solve a machine language directly without any translator because
problem or perform a task. In this, instead of using the computer understands only binary language, which is
symbols like flowchart, the program and its logic are in the format of 0 and 1, and in the assembly language,
written in the simple and concise language of colloquial some mnemonics codes are used instead of 0 and 1. In
speech. Pseudo code is written in simple English this, English words are used for programming, which the
language which can be converted into any programming computer does not understand, so a translator is required
language by the software engineer as per their to convert it into machine language, which is called an
requirement. It tells about the logic of the source code of assembler.
a computer program, which is more important for the Humans can easily understand high level
software developer. There is no need to compile and programming language and can create desired program
execute pseudo code. Its construction does not use the in computer because English language words are used in
syntax of any programming language, due to which it is it but computer understands only 0's and 1's language so
completely independent. translator (compiler or interpreter) is required to convert
The general rules used for writing pseudo code are it into machine language. Nowadays only high level
as follows– language is used to make any general program or
● Imperative Sentence– It is used to show action. Like- software.
display, result, sort list count etc. Machine Language– Machine language is a
● Operators– These are mostly used arithmetic programming language, it is the first language of
operators (+ – */etc) and relational operators (=, >, <,
computer development and for this reason, this language
= >, = < etc).
is known as the first language of the computer
● Decision– IF, THEN, ELSE, CASE, ENDCASE are
generation. (Computer can only understand machine
used for decision making.
codes. That's why the number of their codes are in 0 and
● Looping– The repetition of statement is shown using
1) Machine language is also called binary language. it
FOR, WHILE etc.
Example: Print whether the candidate can vote or not. has to translate the codes. There is no need to translate
● Declare a variable age of type int. the codes because the computer can easily understand
● Ask user to enter age. this type of language.
● Store the age entered by the user in the age variable.
● Check if user's age is greater than or equal to 18 Advantages of Machine Language– Following are
years (age > =18) the advantages of machine language–
● If the user's age is greater than or equal to 18, print (i) Machine languages require very less memory space
the message "You can vote." as compared to other high level programming
● If the user is under 18, print the message "You are languages like Python or Java. That is, there is no
not eligible to vote." need to keep track of many variables and data
1.5 Programming Language: structures while running a program on your
It is a computer language used by programmers to computer. Users can run multiple programs on a
communicate with the computer. It is a set of instructions computer using only a single processor because all
written in any specific language (C. C# Java, Python) to the different programs run on the same will share
perform a specific task. All software, apps, websites, memory space and address space.
games, etc. are created using programming languages. (ii) In this, the code can be easily edited to make it run
Programming language is such a tool by using which we faster than before or to improve its performance in
can give any instructions to the computer and the some way or the other can serve the purpose.
computer makes programs according to the instructions (iii) A computer does not need to translate the program
given by us. from one format to another every time it executes.
Programming languages are mainly of two types– Using machine language can get results more
Low Level Programming Language and High Level quickly.
Programming Language.
(iv) In machine language the instructions given to the
Low-level programming language is easily
understood by the computer and the programs written in computer are in such a way that the hardware
this language are executed directly in the computer, that interprets it correctly.
is, there is no need of any translator in it. It is also called (v) Machine languages are used in embedded system
machine language i.e. It has programmed as 0 and 1. robotics, industrial automation and robotic process
Low level languages are also of two types– machine and automation. They are also used in operating systems
assembly language. of microcomputers, mainframes and minicomputers.
8
Search on TG: @apna_pdf
Disadvantages of Machine Language– Its language programs because the program written in high
disadvantages are as follows– level language has to be translated into machine
(i) It is not easy to read and understand the code. language first. The need to translate high level language
(ii) Machine code instruction is essentially a simple program into low level machine language is required
instruction set for a particular microprocessor. it has because computer understands only machine language.
an operation limit. Some famous high level programming languages are
(iii) Code written in machine language is not portable. Python, Java, Javascript, PHP, C#, C++, Objective C,
Machine code instructions are specific to the Cobol, Perl, Pascal etc.
hardware, they run on. Therefore they cannot be Advantages of High level language–
transferred between machines without being ● High level language is programmer friendly.
translated into another language.
● It is easy to write and debug programs in high level
(iv) Machine code cannot be edited, only translated into
languages.
machine code by a compiler or translator.
Assembly Language– Assembly language is a type ● It is a machine independent language.
of low level programming language. The basis of which ● Easy to learn high level language.
are mnemonic codes. These codes can be easily read and ● There are less chances of error in high level language.
write. This language is used to write the program. From Disadvantages of High level language–
which the output can be obtained from the computer as ● It takes extra time to translate the source code of high
per its requirement. level language into machine code.
Assembly language is neither completely low-level ● Programs written in high level languages are slower
language nor completely machine language. At present, than programs written in low level languages.
assembly language is commonly used for hardware ● High level language programs require more memory
manipulation and to access stored databases.
than low level programs.
Microprocessors are also commonly programmed using
High level languages cannot communicate directly
assembly language.
with the hardware like low level languages.
Advantages of Assembly Language– These are as Python Programming Language– Python is an
follows– open source high level programming language. It is free
● It saves program time. to use for everyone and its source code is available to all,
● It minimizes errors in instructions. in which changes can be made accordingly. Compared to
● Errors can be checked very fast in this. other programming languages, it is a very simple
● Assembly language instructions can be changed faster language in which developers can easily translate its
than machine language. code because its syntax is quite different and User
● In this, the programmer does not need to remember the friendly. In this, the facility of dynamic type system and
number of storage location in the memory.
automatic memory management is available, due to
● Assembly language executes code faster.
which its development and maintenance cost is much
● Assembly language is hardware oriented.
less than other languages. Python language is being used
Disadvantages of Assembly Language– Its for web development, software development, app
disadvantages are as follows– development system scripting, big data processing,
● Despite being simpler than machine language, machine learning and artificial intelligence etc.
programming takes more time and programs are not 1.6 Compiler:
easy to understand. Compiler is such a language translator software,
● It is difficult to find errors in a program written in
which converts the program written in high level
assembly language.
● Assembly language is also based on machine language i.e. source code into machine code (0'S and 1'S)
language, so each computer has its own assembly or low level language. Compiler converts the source code
language, due to which different programs have to be into machine code only if there is no error in the source
prepared for each computer. code. If there is any error in the source code, without
● It is very difficult to remember the syntax of assembly correcting it, the compiler will not convert the source
language. code into machine code. Compiler uses a large amount of
● It requires more memory in the computer. memory while running and works very slowly because
High Level Language– High level programming first it checks the whole program and then translates it
languages are designed to create user friendly software into machine code if there is no error in the program.
programs and websites that are easy for a developer to
read, write, understand and use. Programs written in high
level languages cannot be run directly on the machine.
Compiler or Interpreter is required to run high level Figure 1.1 Compilation Process
9
Search on TG: @apna_pdf
Compilation– When programmers create software It is called these object codes contain instructions that
programs, first they convert the program into source code represent processor actions for a corresponding token.
which is written in a specific programming language (C, When he is encountered in the program.
Python, Java, etc.). These source code files are saved in a (ii) Synthesis Phase– In this phase, the equivalent
text base and human readable format which can be target program is created from the intermediate
opened and edited by programmers. The source code representation. The main parts of this phase are-
cannot be run directly by the computer. For the code to Intermediate Code Generator, Code Generator, Code
be recognized by the computer's CPU, it is converted Optimizer.
from source code (high-level language) to machine code ● Code Optimizer– It modifies the code so that it
(low-level language). This process is called compilation. consumes less resources and generates more speed.
The compilation process is handled by assembler, It returns the unnecessary line of code and
compiler, and interpreter utility programs in a few rearranges the code. It can be classified into two
different programming languages. types– machine dependent and Machine
independent.
● Code generator– Its main purpose is to write
individual code that the machine can understand and
register distribution, instruction selection, etc. This
is the last step of compilation. Finally it converts the
intermediate code into machine code.
1.7 Interpreter:
Interpreter is also a language translator software,
which does not translate together the entire statement of
the program written in high level language, interpreter is
used to convert the program written in languages like
Figure- 1.2 Block diagram of the functions performed
Python, Perl into machine language. Translates and
by the compiler
runs each line of it. Interpreter takes the code (source
The functions performed by the compilation process
code) written in high level language and first converts it
can be divided into two main categories–
into intermediate code and then converts that
(i) Analysis Phase
intermediate code into machine language. It takes a
(ii) Synthesis Phase
single instruction as input and converts it into machine
(i) Analysis Phase– It consists of the following
code. It does not generate any kind of object code and
tasks–
the interpreter takes more time to the program execution
● Lexical Analysis– The compiler converts sequences
as compared to compiler.
of characters into strings of characters (called
When there is an error in any line of the program,
tokens) that appear in the source code. Lexical
the interpreter stops its work and when the error is fixed,
analyzer uses a symbol table to store the words, it
it resumes its work and starts again. Interpreter is good
corresponds to the source code with the generated
for fast debugging of programs.
tokens.
● Syntactical Analysis– In this step, syntax analysis
involves preprocessing to determine whether the
tokens created during lexical analysis are in order
according to usage or not. The proper sequence of a
set of keywords that ultimately produces a desired The interpreter is loaded into memory before the
result is called syntax. In this, the compiler has to program is written. After this, we start writing the
check the source code to ensure syntactic accuracy. program and as soon as we write a statement or line, the
● Semantic Analysis– This step consists of several interpreter checks the error in it, if an error is found, the
intermediate steps. In this, the structure of the tokens interpreter immediately highlights it and we correct it,
is checked, along with their order is also checked and in case of no error, the interpreter translates that
whether they are according to the grammar of the statement into binary language and we write another line
given language or not. The meaning of the token or statement, again the interpreter checks the error in it.
structure is interpreted by the Parser and Analyzer so If there is an error, it will be highlighted, and if there is
that an intermediate code can be generated, called no error, it will convert to binary language, and so on
object code. until the last statement of the program, the interpreter
10
Search on TG: @apna_pdf
executes each statement by converting it into binary 1.10 Loader:
language. Every high level language (like BASIC
It is a special program that takes the input of
PASCAL etc.) uses interpreter, each language has its
executable files in the linker, loads it into the main
own fixed interpreter.
Advantages of Interpreter– Following are the memory and prepares the code for execution by the
major advantages of interpreter– computer. The loader allocates memory space to the
● It is easy to write an interpreter. program and it sets up symbolic references between
● Interpreter takes less memory space in the computer. objects. . It is in-charge of loading programs and libraries
● Interpreter examines the source program line by line.
into the operating system. Embedded computer systems
● It is easy to find and correct errors.
Disadvantages of Interpreter– Following are the do not have loaders. In them the code is executed
disadvantages of interpreter– through ROM. There are various loading schemes -
● It interprets the program after checking it line by line, Absolute loaders, Relocating loaders, Direct linking
hence it takes more time.
loaders, Bootstrap loaders.
● Programmers have to face a lot of problems in writing
large programs.
1.8 Difference between Compiler and
Interpreter:
The difference between compiler and interpreter is
as follows compiler–
Compiler Interpreter 1.11 Difference between Linker and Loader:
Compiler is a translator An interpreter is a Following are the differences between Linker and
which converts source program. Which works Loader–
code (high level to convert the program Linker Loader
language) into machine written in high level
language. language into machine Main function of linker is Main purpose of loader
language. to generate executable is to be loaded into main
If there is an error in the Interpreter translates line files. memory.
syntax of the program, it by line, if any line
Linker establishes the link Loader takes input to
shows that error later on. contains errors, displays
them one by one. by merging object code executable files,
It takes less processing Interpreter takes more which are generated by generated by Linker.
time to translate the time to translate source Compiler/Assemblers.
source code in the code. Linking can be defined as Loading can be defined
compiler. the process of combining as the process of loading
Intermediate object code No intermediate object executable code loading further executable codes
is generated in compiler code is generated in
various pieces of code in main memory.
so that memory is used. Interpreter so that it uses
into main and source
memory rarely.
memory in order to obtain
Debugging is not easy in Debugging is easy in
further code.
compiler. Interpreter.
C, ++, Java, etc. Programming languages There are two types of There are four types of
programming languages like python, ruby etc. uses linkers – editor linker and loaders– Absolute,
uses compiler. Interpreter. dynamic linker. Relocating, Direct
1.9 Linker: Linking, Bootstrap
Linker is a special program that combines object The linker is responsible The loader is also
files created by compiler, assembler and other pieces of for organizing the objects responsible for adjusting
code to create an executable file, which has .exe in the program's address the references that are
extension. In the object file, the linker searches and add space. used within the program.
all the libraries required for the execution of the file. It
Another use of the linker It helps in allocating
controls the memory space that will hold the code from
each module. It also merges two or more different object is to combine all object addresses to the
programs and establishes links between them. modules. executable code/files.

11
Search on TG: @apna_pdf
1.12 Testing and Debugging: (i) Syntax Error– It is displayed by the compiler
Software testing is a process, under which the when the general rules of the programming language are
system or system components are tested. The main goal not followed. Such programming s, are usually caused by
of this test is to verify that the system has been designed the inclusion of incorrect punctuation, undefined words,
as per the standards set by the company or the etc.
requirements of the company. The primary objective of Example– >> value = 9 ; >>
software testing is to find the software failure, if the new value = valu + 12;
software fails during testing, the reasons that caused the In the above example Value is written in the first
software failure are corrected. So that the software can column while only Valu is written in the second column.
work smoothly without any technical hindrance. Therefore the program does not execute and the syntax s
Software is prepared by the development team, after that will be displayed.
the designed software is sent to the testing team, the (ii) Logical Error– A logical error is an error in the

person doing the testing is called software testers. source code of a program by that an error appears in the
Software testing can be divided into two phases– output. This is a type of runtime error that produces

Verification–Verification is done by ensuring that incorrect output. The program may also crash when it is
the software implements a specific function as we intend run. Many different types of programming mistakes can
cause logic errors. For example, assigning a value to a
it to.
wrong variable or multiplying two numbers instead of
Validation– It is a set of tasks which ensure that the
adding them also results in wrong output.
software developed as per the requirement of the
(iii) Run Time Error– It is a program error, which
customers.
occurs during the running of the program. This is caused
Debugging– Debugging is the process of analyzing
by an invalid operation.
and finding bugs and errors in software code. It is fixed
If a program does not contain syntax errors, it will
by many steps in the process of debugging. First of all,
run by the Python interpreter. But program can exit
the bug is identified, after that the bug source is found
suddenly during execution. If it encounters a run time
and fixed so that the program works correctly without
error, then a problem is detected that was not detected
error. Debugger tools are used for debugging. With the
when the program was parsed. The runtime error is
help of debugging, programmers or developers remove
detected only when a particular line is executed.
unnecessary information from the program. Debugging
Examples of Python run– time errors are division by
also provides very important information about the data
zero, use of an undefined identifier, accessing a list
structure and can be easily interpreted. This saves the
element or dictionary value or object attribute that does
time taken to develop the software. There are different
not exit, etc.
steps in the process of debugging which are as follows-
1.13 Testing a Program:
Testing should be done to find out the logical error
Identify Find Error Analyze
→ → in the program. The purpose of testing is to determine
Error Location Error
whether the result is correct or not.

In general, the testing data selected for testing a
Fix and Cover Lateral Pr ove
← ← program should include–
Validate Damage Analysis
(i) Common data that will test commonly used program
The time spent on developing a computer program, paths.
testing and debugging, is often equal to or longer than (ii) Abnormal but valid data, which will test the
the time spent writing the program. program path used to handle the exception.
There are three types of errors in computer Sometimes such data may be encountered while
programs– running the program.
12
Search on TG: @apna_pdf
(iii) Incorrect, incomplete or invalid data, which shall 1.13 (ii) Difference between Bug and Virus:
test the error handling capability of the program. When a programmer inadvertently makes a mistake
used to see that the program how to respond in
while designing a program or software, it is called a bug.
unusual situations.
For example, any code is accidentally inserted in the
Principles of Testing–
program, due to which all the functions of the program
● All testing must meet customer requirements.
● Software testing should be done by a third party. do not work and the program crashes.
● Exhaustive testing is not possible. As we need the Virus is a type of program which is created with the
optimal amount of testing based on application risk purpose of harming the computer. It is often intentionally
evaluation. sent from one computer to another and can damage to the
● All testing to be conducted must be planned before it is computer.
implemented. A bug is a sudden problem in a program. Bug comes
● It follows the Pareto rule (80/20 rule) which states that in the program due to some mistake but virus
80% of the errors come from 20% of the program
intentionally sent to the computer. Viruses are intended
components.
to cause intentional harm.
● Start testing with small portions and expand it to larger
portions. 1.14 Documentation:
1.13(i) Difference between Testing and Documentation of a software system is the
Debugging: collection of a complete record of the programs and other
Following are the differences between Testing and documentation used during the various stages of the
Debugging–
development of the system. Program documentation is a
Testing Debugging continuous process. Program characteristics, algorithms,
• It is the process of • It is the process of representation and program etc. can be considered as part
finding errors and fixing bugs found of the documentation of a program but after successful
bugs. during testing. completion of the program it has to be ensured that the
• Testing is mostly • Debugging is documentation is eligible for a complete experiment.
performed by testers. performed by Documentation is an integral part of a program. Once a
devlopers or program is considered operational, it is used on a regular
programmers. basis. Documentation can be of two types–
• It is accomplished by • Debugging is done (i) User Documentation– It provides the
developers team and by the development information required in using a program. This
out side users. team only, it cannot information includes many different types of items. For
be done by outside example, the application area of the program, the input
users. data required for the program, the output produced by the
• It is based on different • It is based on program, the details of the commands required to start
testing levels like different types of the program, etc.
System Testing, bugs. (ii) Technical Documentation– In this type of
Integration Testing etc.
documentation is addressed to the programmers, who are
• Most of the testing is • Debugging is not required to program in some time. Editing work can be
done without design possible without found. To enhance the program after the program is in
knowledge. detailed design use or to add any new feature technical documentation is
knowledge.
required.

13
Search on TG: @apna_pdf
Practice Questions with Explanatory Solutions
1. The first machine based language is– 6. Debugging is used to–
(a) COBOL (a) Check the functionality of the program.
(b) PASCAL (b) To find out the error in the program.
(c) Machine Language (c) Black box testing.
(d) Assembly language (d) None of these
Ans. (c) Machine language is the language in which Ans. (b) Debugging is used by the developer to locate
only two digits 0 and 1 are used. It is the basic and correct errors present in the software. After taking
language of computer. Which the computer the test report of the bug present in any software from
understands directly. No language translator has to be the testing team or client, when the development team
used for this. Machine language is called low level fixes the bug available in that software, then this
language. process is called debugging.
2. Which of the following is a high level programming 7. Pictorial presentation of algorithms–
language? (a) Flow Chart (b) Pseudo code
(a) Perl (b) Ruby (c) Graph (d) Chart
(c) COBOL (d) all of the above. Ans. (a) Flowchart itself is a pictorial presentation of
Ans. (d) High level language is a programming an algorithm, that is, a flowchart is a graphical image
language designed to simplify computer that shows the steps of a process. Different symbols
programming. High level language is programmers are used for different types of instructions.
friendly and machine platform independent, due to 8. Step by step process to solve a problem is–
which it is quite portable. Most common programming (a) Flow chart (b) Algorithm
languages are considered high level languages. C#, C, (c) Chart (d) None of these
Cobol, Fortran, Java, Javascript, Pascal, Perl, PHP, Ans. (b) An algorithm is a set of instructions, which is
Python, Ruby etc. are high level programming a step by step process to solve a problem. Its main
languages. Each of these languages uses a different goal is to get the expected output. It consists of a
syntax. number of consecutive steps, only after the completion
3. How may types of programming languages are– of which the output comes.
(a) 2 (b) 3 9. The correct sequence to run a program is–
(c) 1 (d) 4 (a) Execute → Load → Link → Code → Compile
Ans. (b) Programming language can be mainly (b) Code → Compile → Link → Load → Execute
divided into three parts, machine language, assembly (c) Compile → Code → Load → Link → Execute
language and high level language. Machine language (d) All of the above.
is the language in which, only two digits 0 and 1 are Ans. (b) A computer program is a collection of
used. It is the basic language of the computer which instructions that can be executed by a computer to
the computer understands directly. Machine language perform a specific task. The correct sequence to run a
is written in binary code. Machine language was used program is–
in the first generation computers. Assembly language Code → Compile → Link → Load → Execute
is a computer programming language in which 10. The function of the compiler is–
mnemonic codes are used instead of numerical (a) To allow the user to type the program.
symbols and an assembler is required to convert it into
(b) Translating instructions into a form which is
machine language. Assembly language is used in the
second generation of computers. The language used in suitable for execution by the program
the computer which has English alphabets. Programs (c) Loading the executable code into memory
are written using numbers and symbols, it is called (d) All of the above.
high level programming language. Ans. (b) A compiler is a software program that
4. Objective of Manual Testing is to identifying.......- converts high level language code into binary code
(a) Bug (b) error that can be understood and executed by a computer.
(c) Both A and B (d) none of these The process of converting high level programming
Ans. (c) Manual testing is a type of software testing in into machine language is known as compilation.
which test cases are tested manually. The main 11. Which of the following software converts high
purpose of manual testing is to find bugs, errors in level language into machine level information line
software applications has to be identified. by line?
5. The latest high level language is– (a) Compiler (b) Interpreter
(a) Perl (b) Ruby (c) Assembler (d) none of these
(c) Delphi (d) Cobol Ans. (b) Interpreter is a program, which converts code
Ans. (c) Delphi is a latest high level language, which written in high level programming language into
supports object oriented design. It is used to develop machine language (binary code). It executes the
from database solution to mobile application. It is program line by line. It takes one statement at a time
used on Windows as well as Linux. as input.

14
Search on TG: @apna_pdf
12. The advantage of using flowchart is– 19. Which part of the memory does the system store
(a) Proper documentation (b) Effective analysis the parameter and local variables of a function
(c) Efficient coding (d) All of the above. call?
Ans. (d) It is easy to get communication information (a) Heap
in any program through flowchart and the program
can be easily understood. Efficient coding, proper (b) Stack
documentation, effective analysis, etc. are all benefits (c) Uninitialized data segment
of using flowcharts. (d) None of the above
13. Which of the following is called low level Ans. (b) By instruction, the Python interpreter loads
language– functions and variables into stack memory, also
(a) Machine language (b) Assembly language known as the stack. The heap segment (also known as
(c) Both A and B (d) None of these free store) keeps track of memory used for dynamic
Ans. (c) Low-level programming language is a memory allocation.
programming language created by combining special
instructions and binary language recognized by the 20. Which of the following executes programming
CPU of the computer. There are two types of low code line by line?
level programming language – machine language and (a) Compiler (b) Interpreter
assembly language. (c) Executor (d) Translator
14. Accuracy and suitability of .......... can be checked Ans. (b) Both compiler and interpreter are programs
easily. that convert source code (high level language) into
(a) Algorithm (b) Heuristic machine code. (so that the computer can understand
(c) Random (d) All of the above. them) Compiler analyzes all the language statements
Ans.(a) The process of solving a problem in a step-by- and gives an error if found, while Interpreter executes
step manner is called an algorithm. By this we solve the source code line by line
the problem by dividing it into small parts. The 21. A computer program that a computer's activity.
accuracy and suitability of the algorithms can be (a) Interpreter (b) Modem
checked very simply. (c) Compiler (d) Operating system
15. The first goal of the testing process is– Ans. (d) An operating system is a computer program
(a) Bug Prevention (b) Analysis that manages and controls the activities of the
(c) Testing (d) None of these computer. The operating system manages all the
Ans.(a) Software testing is the process of executing a resources of the computer such as memory, input and
program with the main objective of bug prevention. output devices.
Software testing is the process of finding errors in a 22. What will be the output of the following pseudo-
software application or program to ensure that the code?
application functions as per the requirements of the Integer a
end users.
Set a = 4
16. Which of the following language is understood by do
computer? print a + 2
(a) Machine language (b) Assembly language a=a–1
(c) High-level language (d) None of the above
while (a not equals 0)
Ans.(a) Machine language is the language understood end while
by the computer. It is represented in binary form i.e. 0 (a) 6 6 6 6 (b) 6 5 4 3
and 1. (c) 6 7 8 9 (d) 6 8 10 12
17. The process of finding errors in code is called– Ans. (b) : Inta-a-1 Output (a + 2)
(a) Compiling (b) Running
First loop 4 6
(c) Testing (d) Debugging
Second loop 3 65
Ans. (d) The process of finding errors in the code is Third loop 2 654
called debugging. A debugger is a program that helps Fourth loop 1 6543
you to find out, what is going on in the computer
program. You can also stop execution at a specified 23. What will be the output of the following
line number, print variables, continue execution, stop pseudocode, where ^ represent XOR operation?
again, execute statements one by one, and repeat such Integer a, b, c
actions until you track down the abnormal behavior Set b = 4, a = 3
and find a bug. c=a^b
18. Testing is known as.........– Print c
(a) A stage of all projects (a) 4 (b) 3
(b) Finding broken code (c) 5 (d) 7
(c) Evaluating deliverable to find errors Ans. (d) The XOR operation in Python sets each bit to
(d) None of the above 1 if only one of the two bits is 1. Therefore
Ans. (c) : Software testing is the process of evaluating Integer a, b, c Set b = 4, a = 3
and verifying that a software product or application Set b = 4, a = 3
does what it is supposed to do. The benefits of testing c=a^b
include preventing bugs, reducing development costs, Print c
and improving performance. The output of the given pseudo code will be 7.
15
Search on TG: @apna_pdf

2 ALGORITHM AND FLOWCHARTS

2.1 Introduction: Write the values


A flowchart is a graphical presentation of an contained in A &
algorithm that represents the steps of a process. Many B on a terminal
symbols are used in flowchart like Square, Rectangle, screen.
Diamond, Arrows, Oval etc. A flowchart is made by Add the value
connecting all these symbols to each other. In this, contained in B to
different symbols are used for different types of the value contained
instructions. Through flowchart, it is easy to get in A and place the
communication information in any program and program result in C.
can be easily understood. The process of flowchart can An entry in the
be implemented in any programming language. Flow chart is
The following are the symbols used in the made at the
flowchart– connecting point
1. Terminal. [ ]– It is an oval symbol which is used to
marked
start and end a process. The first and last symbol is
terminal in a flowchart. If condition is
2. Input / Output [ ]– It is the symbol of a satisfied then yes
parallelogram, which represents Input (Read) or Output path is to be
(Print) etc. followed otherwise
3. Processing [ ]– It is a rectangle symbol which No path is to be
contains instructions for processing. This box is used for taken
process, calculation or instruction. The arrows
4. Decision [ ]– It is a diamond shaped symbol which indicate the paths
is used to represent the condition in a process. of systematic
On the basis of this condition, decision can be taken in solution of the
programming. problem.
5. Flow Line [ ]– Flow lines show the direction of A transfer of
flow in a flowchart. Here flow means which step will problem solution
happen when? Flow lines are used to connect all the flow is made at the
chart processes together. connector point
6. Connector [ ]– If the flowchart is bigger than one marked in the
page, then it is added to the next page with the help of flowchart.
connector. The incoming line is shown at the end of the Figure- 2.1 Flowchart symbols and their functions
previous page while the outgoing line is shown at the 2.2 Sequencial, Decision based & iterative
beginning of the next page.
7. Comments/Explanations [ ]– This symbol is processing for flowchart:
used for any kind of comment and explanation in the They are as follows–
flowchart. This symbol can be used to give any kind of 2.2(i) Sequencial Processing:
comment or definition in the flowchart. Sequential processing means that the statements are
Symbol Example Description executed in order. This is the default flow of the
Start action here statement. Control structures allow the user to change the
sequence of instructions for execution. They also
implement decision and repetition in the program.
Stop action here. Decision-based (Conditional / Selection) controls allow
the computer to decide, which statement to execute next
Take two values
based on condition test. Iterative construction (looping)
from an external
allows to the computer to execute the statement group
source and assign
repeatedly until the condition is true.
them to A and B
Example– Determine whether the temperature is above
on a terminal.
or below the freezing point.
16
Search on TG: @apna_pdf
Step1: Input temperature.
Step2: If it is less than 32, then print
"Below freezing point"
Step3: Otherwise, print "above freezing point".

2.2(ii) Decision Based Processing:


Decision-based processing is used to make decisions
based on a particular situation in a program. It is used in
program logic to select the appropriate one from two or Example– Algorithm to generate a table of number
more alternative paths. This is represented as an inputted by user,
IF......THEN...ELSE or IF structure. Step-1: Begin
Example– On giving the input of two numbers, to Step-2: Declare n, a and b, set a = 1.
display the greater of them as output, Step-3: Input in n.
Step-4: b ← n * a
Step-6: Increase the value of a with 1. (i.e. a=a+1)
Step-7: Repeat Step-4, Step-5 and Step-6 till a becomes
10.
Step-8: End the process.
Flowchart–

Iterative Processing– Many tasks are repeated with


the help of computer, iterative processing is used in a
program to do these repetitive tasks easily. It runs in the
program making a loop until the particular condition is
true and when the condition becomes false, the program
ends by giving output.
Example– Flowchart to display all the even numbers
from 1 to 20,
17
Search on TG: @apna_pdf
2.2(iii) How to Write a General Flowchart?: Step-4: t = a
There are some rules to make a flowchart, which a=b
makes it easy to understand the flowchart. By using b=t
flowchart symbols we can display the process through a Step-5: Print the value of a and b.
graph. Following are some of the major flowcharting
Step-6: End the process.
rules–
• Every flowchart will have a starting and ending
point from where it will start and end. Flowchart–
• Each symbol in a flowchart is connected by a
symbol that represents the flow direction in the
diagram.
• A different symbol is used to represent different
processes.
• Only fully defined symbols can be used in diagrams.
• If the flowchart is based on a condition, it can have
two endings.
• Always go from Top to Bottom and Left to Right
while constructing flowchart.
Example– Draw a flowchart to draw the first 15
members of the Lucas series.
1,3,4,7, 11, 18, 29, 47.........

Example– Draw a flowchart that reads year as input and


checks whether it is a leap year or not.

Example– Algorithm to swap the values of two variables Example– Create a flowchart, which accepts a number
Step-1: Begin
and if that number is less than 5, calculates its cube
Step-2: Declare value a, b and t.
Step-3: Input value in a and b. otherwise, calculates the square.

18
Search on TG: @apna_pdf
Flowchart– 2.3(ii) Algorithm for computing simple
interest:
Algorithm to calculate Simple Interest when the
Principal Amount, Rate of Interest and Time are given as
input by the user.
Step-1 : Begin
Step-2 : Assume the variable as P,r,t and Si.
Setp-3 : Input Value in P,r and t.
Step-4 : Perform Calculation as (P*r*t)/100 and store
in Si.
Setp-5 : Print the value of si.
Step-6 : End the process.

2.3(iii) Algorithm to calculate area of


triangle:
Algorithm to calculate the area of a triangle:
 1 
∆ = 2 × b × h 
2.3 Sample Algorithms:  
An algorithm is a 'set of rules' that determine step by Step-1 : Begin
step how a particular task will be performed for the Step-2 : Assume Variable as a, b and h.
expected result. Step-3 : Input the base and height of traingle and store
in b and h.
2.3(i) Interchanging the Values of Two Step-4 : Perform Calculation as a = (b*h)/2
Variables (without using a temporary Step-5 : Print the value of a.
variable): Step-6 : End the process.
Step-1 : Begin
Step-2 : Declare Variable a, b. 2.3(iv) Flowchart to add two numbers
Step-3 : Input Value in a and b. entered by the user:
Step-4 : a = a + b Algorithm to add two numbers inputted by the user–
b=a–b Step-1 : Begin
a=a–b Step-2 : Assume variable as a, b and c.
Step-5 : Print a, b Step-3 : Input values in variable a and b.
Step-6 : Stop Step-4 : Perform addition on a and b store value in c.
Step-5 : Print the value of c.
Step-6 : End the process.

Flowchart–

19
Search on TG: @apna_pdf
2.3(v) Algorithm to print the factorial of an Step-3 : If a > = b & & a > = c then print a and go to
integer number: Step-6, Otherwise next Step.
Factorial to print the factorial of an integer number, Step-4 : If, b > = a & & b > = c, then print b
and go to step-6, Otherwise next step.
Step-1 : Begin
Step-5 : Print c
Step-2 : Assume values as n and f, set f = 1.
Step-6 : End the process.
Step-3 : Input value in n.
Flowchart–
Step-4 : Perform calculation as f = f * n.
Step-5 : Decrease the value of n with 1 (i.e. n = n – 1)
Step-6 : Repeat the Step-4 and Step-5, till n become 1.
Step-7 : Print the value of f.
Step-8 : End the process.
2.3(vi) Algorithm and flowchart to generate
a table of a number:
Algorithm to generate a table of a number inputted
by the user–
Step-1 : Begin
Step-2 : Declare n, a and b, set a = 1.
Step-3 : Input in n.
Step-4 : b ← n * a
Step-5 : Print b.
Step-6 : Increase the value of a with 1. (i.e. a = a + 1)
Step-7 : Repeat Step-4, Step-5 and Step-6 till a
becomes 10.
Step-8 : End the process.
Flowchart–

2.3(viii) Write an algorithm to accept the


python [NIELIT O'Level] language marks to
print the respective grade:
To Grading Criteria,
50 – 54 →D
55 – 64 →C
65 – 74 →B
75 – 84 →A
85 – above → S, otherwise F
Algorithm to display marks obtained as grade in Python
language of NIELIT 'O' level;
Step-1 : Begin
Step-2 : Input variable N.
Step-3 : If N > = 50 && N < = 54 then print 'D' and go
to step-9 Othterwise next step.
Step-4 : If N > = 55 && N < = 64 then print 'C' and go
to step-9, Otherwise Next step.
2.3(vii) Write an algorithm that takes three Step-5 : If N > = 65 && N < = 74 then print 'B' and go
to step-9, Otherwise Next step.
numbers as input and outputs largest Step-6 : If N > = 75 && N < = 84 then print 'A' and go
number: to step-9, Otherwise Next step.
Algorithm for taking three numbers as input and Step-7 : If N > = 85 then print 'S' and go to step-9,
gives output the largest number, Otherwise Next step.
Step-1 : Begin Step-8 : Print 'F'
Step-2 : Input a, b and c. Step-9 : End the Process.

20
Search on TG: @apna_pdf
Flowchart–

2.3(ix) Palindrome: 2.3(x) Draw a flowchart and write algorithm


An object (number or string) that is equal on both to check and print an Armstrong number:
sides is called a palindrome. Like-1234321 Algorithm to check and print an Armstrong number
Algorithm to check a number palindrome by Step-1 : Begin
accepting a number as input Step-2 : Declare n, s, r, c and a.
Step-1 : Begin Step-3 : Read n and set r = o.
Step-2 : Declare Variables as n, s, a and r. Step-4 : Store the value of n in s.
Step-3 : Input n and set r = o. Step-5 : Perform n % 10 and store in a.
Step-4 : Store the value s in n. (ie. s = n) Step-6 : Perform cube as a * a * a and store in c.
Step-5 : Perform Calculation as, a = n%10 Step-7 : n = n/10
Step-6 : r = r * 10 + a Step-8 : r = r + c
Step-7 : n = n/10 Step-9 : Repeat step-5, step-6, step-7 and step-8 till
Step-8 : Repeat the step-5, step-6 and step-7 till n > 0 n>0.
Step-9 : If r is equal to s than print "Palindrome" Step-10 : If r is equal to s then print "Armstrong"
Otherwise "Not a Palindrome". Otherwise" Not a Armstrong".
Step-10 : End the process. Step-11 : End the process.
Flowchart– Flowchart–

21
Search on TG: @apna_pdf
2.3(xi) Write an algorithm and draw 2.3(xiii) A flowchart to check whether a
flowchart to sum a set of numbers: number is Prime or not:
Algorithm to sum a set of numbers (three numbers);
Step-1 : Begin
Step-2 : Declare variable as a,b,c and s.
Step-3 : Input in a and b.
Step-4 : Perform addition as a+b+c and store in s.
Step-5 : Print the value of s.
Step-6 : End the process.
Flowchart–

2.3(xiv) Flowchart for printing the Fabonic


Series:
Flowchart to print the Fabonic series up to the term
inputted by the user;

2.3(xii) Algorithm for converting a decimal


number to binary:
To convert decimal number to binary number
algorithm;
Step-1 : Begin
Step-2 : Input the decimal number whose equivalent
binary you want.
Step-3 : Divide decimal number by 2.
Step-4 : Write the remainder.
Step-5 : Quotient of previous stage becomes the
dividend and again divide it by 2 at next stage.
Step-6 : Write the remainder to right hand side of
previous remainder.
Step-7 : Repeat the step-5 and step-6 till quotient is
zero.
Step-8 : Print the all remainder in reverse order.
Step-9 : Stop.

22
Search on TG: @apna_pdf
2.3(xv)Write an algorithm and draw Step-6 : Move n-1 disks from C to B.
flowchart to count and sum (add) the total Step-7 : Repeat step 3 to 5, by decrementing n by 1.
number of even numbers between 1 and 100: Step-8 : End the process.
Algorithm to count the total number of even and odd Pseudo code– The recursive pseudo code of the
numbers from 1 to 100, Tower of Hanoi is as follows–
Step-1 : Begin Start
Step-2 : Set a = 1, c = 0, s = 0 Procedure Hanoi (disk, A, B, C)
Step-3 : If a < = 100 && a % 2 = = 0 then c = c + 1, s If disk = = 1, THEN
= s + a and a = a + 1 move disk from A to B
Step-4 : Otherwise print "Total even no", and "Sum of ELSE
even No", s. Hanoi (disk-1, A,C,B) // Step 1
Step-5 : End the process. Move disk from A to B // Step 2
Flowchart– Hanoi (disk-1, C, B, A) // Step 3
END IF
END Procedure
STOP
Flowchart–

2.3(xvi) Algorithm, pseudo code and


Flowchart for Tower of Hanoi: 2.4 Types of Algorithm:
Tower of Hanoi– The Tower of Hanoi is a The systematic way of solving any mathematical
mathematical puzzle. It consists of three iron sticks and operation, data processing and other computer related
some discs of different sizes. In this puzzle all the discs problems is called Algorithm. There can be many
have to be transferred from one stick to another. possible solutions to any problem, so there can be many
Some rules for Hanoi Tower are as follows–
different algorithms for the same problem, but the best
• Only one disc can be moved at a time. algorithm is that, which provides a solution to the
• In all moves, you can remove the topmost disc from problem using the least amount of time and computer
one stick and place it on top of another stick. memory.
• The larger disc will never be on top of the smaller Following are the different types of algorithms–
disc. 1. Recursive Algorithm: This algorithm is used
Algorithm– when the problem can be broken into simpler or smaller
Step-1 : Begin problems of the same type. For example, if we want to
Step-2 : Let the three towers be the A.B and C. find the factorial of the number 5, then 5! = 5 × (5 – 1) ×
Step-3 : Read the number of disks, n from the user. (5 – 2) × (5 – 3) × (5 – 4) means 5 × 4 × 3 × 2 × 1 = 120.
Step-4 : Move n-1 disks from A to C. Recursive Alogrithm can be used to solve this type of
Step-5 : Move nth disk from A to B. problem.
23
Search on TG: @apna_pdf
2. Dynamic Programming Algorithm: In this 5. Greedy Algorithm: In this algorithm, without
algorithm, a large and complex problem is divided into worrying about the main problem, the emphasis is on
many small problems and the solution of the main finding the best answer at all the steps, this way of
problem is extracted by collecting all those small solving the problem sometimes leads to bad results.
problems together. For example, we can make the 6. Brute Force Algorithm: In this algorithm all
algorithm of Fibonacci series (0,1,1,2,3,5,8,13,21.....)
possible solutions to the problem are thought out in detail
with dynamic programming algorithm.
3. Backtracking Algorithm: In this algorithm, an without wasting time on any shortcut solution. For
attempt is made to find the Best Possible Solution by example, if the age of a person is to be determined
solving a part of a problem, and if the Best Possible through this Brute Force Algorithm, then without making
Solution is not found, then leaving that part, another part any guess, the number will be increased starting from
is solved. one until the real age of the person is known.
4. Divide and Conquer Algorithm: In this, a 7. Randomized Algorithm: In this algorithm a
problem is divided into two sub-problems, after that solution is derived by guessing. For example, if a
those problems are divided into smaller sub-problems person's age is to be known, then by looking at the
until a certain solution is found, after getting a certain
person's physical condition, an estimate will be made as
solution, the solution of the main problem is solved by
adding all the sub-problems scores. to how old that person may be.

Practice Questions with Explanatory Solutions


1. What is the value of 0! (factorial zero) equal to? Ans. (d) Greedy is a variant of the algorithm. In this
(a) 0 (b) 2 algorithm, the emphasis is on finding the best answer
(c) 1 (d) 3 for each step without worrying about the main
Ans. (c) To find the factorial of a number, that number problem. This method of solving the problem often
and all the numbers below it, are multiplied together leads to poor results.
such that the value of 10 will be 10 × 9 × 8 × 7 × 6 × 5
6. The GCD of two numbers is–
× 4 × 3 × 2 × 1 = 3628800.
(a) The smallest number which is a common factor
So 0! The value of is equal to 1.
of the given numbers.
2. What is the GCD of 120 and 60? (b) The greatest number which is a common factor
(a) GDC 10 (b) GDC 60
of the given numbers.
(c) GDC 30 (d) GDC 40
(c) 1 (for all numbers)
Ans. (b) Greatest Common Divisor of any two (d) None of these
numbers is that number which divides both the
numbers. The GCD of 120 and 60 is 60. Ans. (b) The greatest number which is a common
factor of two or more given numbers is called GCD
3. To interchange the values of two variables...........
(Greatest Common Factor Divisor). For example, the
Variable is required?
(a) Temporary (b) Certified GCD of 8 and 12 is 4. GCD is also known as HCF
(c) Valuable (d) None of these (Highest Common Factor).
Ans. (a) A temporary variable is needed to 7. The algorithm cannot be represented as–
interchange the values of two variables. For this, (a) Pseudo code (b) syntax
Storing the value of one variable in a temporary (c) Program (d) Flowcharts
variable and changing the value of another variable to Ans.(b) The set of instructions that define the entire
the first and then copying the value of the temporary process of solving a problem is called an algorithm.
variable to the second variable. Algorithms can be represented in the form of pseudo
4. Which symbol is used for condition statement in code, programs and flowcharts.
flowchart? 8. When an algorithm is written using a
(a) Rectangle (b) Diamond programming language it is called a …..
(c) Oval (d) Arrow (a) Pseudo code (b) Syntax
Ans. (b) Diamond symbol is used for condition (c) Program (d) Flowchart
statement in flowchart. To take a decision, it is entered Ans. (c) In computer programming, the algorithm is
in diamond (decision box). written before the program. A set of step-by-step
5. Which of the following is a type of algorithm– instructions defined to solve a problem is called an
(a) Flowchart (b) Pseudo code algorithm. When an algorithm is written using a
(c) Connector (d) Greedy programming language, it is called program.
24
Search on TG: @apna_pdf
9. The symbol is used at the beginning of the 15. Palindrome number is called–
flowchart. (a) Which is same on one side
(a) Oval (b) rectangle (b) Which is same on the other side
(c) Diamond (d) none of these (c) Which is same on both the sides
Ans.(a) Oval symbol is [ ] used to indicate the (d) Which has no order
beginning and end of a program in a flowchart. It is Ans. (c) An object (number or string) which is equal
the first and last symbol in the flowchart. on both the sides is called Palindrome number.
10. Which of the following represents two different 5678765 is a palindrome number.
conditions? 17. What is helpful in understanding the problem and
(a) Rectangle (b) Diamond finding a solution?
(c) Circle (d) Oval (a) Algorithm (b) factorial
Ans. (b) Decision box means diamond symbol is used (c) Flowchart (d) none of these
to display different conditions. It represents different Ans. (a) Algorithm divides the solution of any
condition. problem into small parts which makes it easy to
11. The product of all natural numbers from 1 to n understand. This step Provides step by step solution.
can be obtained by which of the following? Due to which clarity increases.
(a) n! (b) n×n 18. What is the process called of drawing a flowchart
(c) n" (d) none of these for an algorithm?
Ans. (a) The product of all natural numbers from 1 to (a) Factorial (b) Flowcharting
n can be obtained through n!. The factorial of a (c) Connector (d) algorithm
number is the product of that number and all the Ans. (b) A set of step by step instructions to solve a
integers below it. problem is called an algorithm and a pictorial
12. To arrange the numbers in ascending order– representation of an algorithm is called a flowchart.
(a) Put the largest number first and the smallest The process of drawing a flowchart is called
number last. flowcharting.
(b) Putting the smallest number first. 19. The base of the decimal number is–
(c) Enter the number as per your wish. (a) 5 (b) 2
(d) None of these (c) 10 (d) 0
Ans.(d) Writing the numbers in increasing order is Ans.(c) Decimal number system is a number system
called Ascending Order. In this, first the smallest in which a total of ten digits (0, 1, 2, 3, 4, 5, 6, 7, 8, 9)
number is arranged in increasing order and finally the are used for counting. It is the most commonly used
largest number is written. number system by humans. The base of a decimal
13. Prime numbers are– number is 10.
(a) Divided by 1 20. What will be the value of 5!–
(b) Divided by 1 and itself (a) 5 (b) 10
(c) Divided only by itself (c) 110 (d) 120
(d) none of these Ans. (d) To find the factorial of a number, multiply
Ans. (b) Prime numbers are those numbers which are that number and all the numbers below it.
completely divisible only by themselves or by 1 and 5 ! = 5 × 4 × 3 × 2 × 1 = 120
they are not divisible by any third natural number, are 21. What will be the output after the following
called prime numbers. For example- 2, 3, 5, 7, 11, 13, statements?
17 etc. are prime numbers. a=0
14. What are the numbers called with which, things b=0
can be counted? while a + b < 8:
(a) Whole numbers
a+=1
(b) Natural numbers
print(a, end=")
(c) Numbers perfect
(d) None of these (a) 0 1 2 3 4 (b) 1 2 3 4 5 6
(c) 1 2 3 4 5 (d) None of these
Ans. (b) The numbers with which objects can be
counted are called natural numbers. The counting of Ans. (c) a = 0
any item is positive. Natural numbers greater than 0 b=0
means starting from 1 and increasing till ∞ (infinite). while a + b < 8:
A natural number is also a whole number. The natural a+=1
numbers together with zero form the set of whole print (a, end =")
numbers. The given python code will provide the output 12345.

25
Search on TG: @apna_pdf
22. In a flow chart, which of the following is used to Ans. (a) In a flowchart, a process is expressed by an
test the condition? Rectangle.
(a) Terminal (b) Process
(c) Input / Output (d) Decision 29. What is the symbol used to represent start and
Ans. (d) In flowchart, decision is used to test the stop of a flowchart?
condition. It is represented by the diamond shape. (a) Oval (b) Rectangle
23. The process of drawing a flowchart for an (c) Arrow (d) Diamond
algorithm is called......... Ans. (a) Ovals or terminators are used to represent the
(a) Performance
beginning and end or termination of a process.
(b) Algorithmic Representation
(c) Evaluation 30. The way for solving a problem step by step is
(d) Flowcharting known as...........
Ans. (d) The process of making flowcharts for (a) Design (b) Making
algorithms is called flowcharting. A flowchart is a (c) Algorithm (d) Execution
graphical representation of any algorithm written to
solve a particular task. Ans. (c) The method of solving a problem step by step
25. What are the three different types of algorithm is called an algorithm. It is a set of steps to solve a
constructions? particular task or computation.
(a) Input/Output, Decision, Repeat 31. An algorithm that calls itself directly or
(b) Input, Output, Process
indirectly is called as ........... .
(c) Loop, Input/Output, Process
(d) Sequence, Selection, Repeat (a) Sub Function
Ans. (d) An algorithm is a step-by-step procedure to (b) Recursion
describing how to solve a problem that always gives a (c) Reverse Polish Notation
correct answer. An algorithm is made up of three basic (d) Traversal Algorithm
building blocks– indexing, selection, and repetition. Ans. (b) The process in which a function calls itself
Sequencing– an algorithm is a step by step process
directly or indirectly, is called recursion and the
and the order of those steps which are important to
ensure correctness. function concerned is called a recursive algorithm. By
Selection–algorithms can use to determine a this some problems can be solved quite easily.
different set of steps to execute based on a Boolean 32. Flowchart and algorithms are used for–
expression. (a) Better programming
Iterative–algorithms often use recursion to
(b) Easy testing and debugging
execute a certain number of steps or a certain
condition throughout. (c) Efficient Coding
26. A detailed flowchart is known as: (d) All
(a) Micro (b) Union Ans. (d) Algorithm– Algorithm means a step-by-step
(c) Macro (d) Stack procedure (representation) for solving a particular
Ans. (a): A detailed flowchart is known as a micro- task. A well defined set of instructions in order to
map: Macro flowchart, top-down flowchart, detailed solve a program is called an algorithm in
flowchart (also called process map or symbolic
flowchart), deployment flowchart (also called down- programming.
cross or cross-function flowchart), Sievret level Flowchart– A flowchart is a step-by-step
flowchart. diagrammatic representation that displays a solution
27. Algorithms cannot be represented by– model for a problem. A flowchart is a diagram that
(a) Pseudo codes (b) Syntax represents a process, workflow, or flowchart. Hence
(c) Fowcharts (d) Programs all the given options are correct.
Ans. (b) Algorithm cannot be represented by syntax
33. Which of the following symbol is used for input
because it required staement and steps to solve the and output operations in a flow chart?
particular problem and task. On the other hand it can (a) Rectangle (b) Parallelogram
also be represented by pseudo code, flowcharts and
(c) Circle (d) Diamond
programs.
Ans. (b) The parallelogram symbol represents the
28. A process is expressed in a flowchart by–
input and output in a flowchart. It also generally
(a) Rectangle (b) A Circle
(c) Parallelogram (d) Adiamond represents the data.

26
Search on TG: @apna_pdf

3 INTRODUCTION TO PYTHON

3.0 Introduction: 3.2 History of Python:


Python is an object-oriented, high level Python is an interpreted high-level and object-
programming language, which is used in tasks such as oriented programming language developed by Guido
website building, app development, machine learning, Von Rossum in the 1990s. It is a very good programming
data analysis, web scraping, and natural language language because it can develop applications very
quickly, Python provides dynamic typing and dynamic
processing. Python is also known as General Purpose binding options. Python was launched in 1991 and the
Programming Language. It started in the 1980s. Due to first version of Python, Python 1.0, was released in
the clear syntax and readability of the Python language, January 1994. Python 2.0 was released in 2000, followed
it has become the most famous programming language in by Python 3.0 in 2008. The latest version of Python is
the world. Python is also an interpreted language, which Python 3.7.17 which was released in June 2023.
means that programs written in Python, do not need to be The most prominent version of Python is Python 3,
compiled before running. Python programs can be which is not compatible with Python 2. It is available for
designed in a modular style and its code can be reused in most versions of Windows, Mac OS and Linux operating
systems. It is freely available at www.python.org.
a variety of other projects.
Python is derived from many other languages
3.1 Characteristics of Python: including ABC, Modula-3, C, C++, Algol-68, Small-
Following are some of the main features of Python– Talk and Unix-Shell and other scripting languages. Like
• Python is a simple language, it is easy to use means Perl, the Python source code is now available under the
GNU General Public License (GPL). Python is an
Python is programmer friendly language.
interpreted language, which means that programs written
• Python is very easy to learn, it is easy to code in in Python, do not need to be compiled first in order to
Python as compared to other popular programming run. Python allows programs to be designed in a modular
languages like Java and C++. style, and its code can be reused in a variety of other
• Python is freely available. It is open source, which projects. Python provides dynamic data types, ready-
means that source code is available for public. No made classes and interfaces for many system calls and
libraries. It can be extended using C or C++ language.
license is required to use python language.
Who Uses Python?– Python provides strong
• Python is a high level programming language. No need programming features and it is widely used. Python is
to take care of system architecture, memory used by many companies and organizations. Like–
management as a programmer. Yahoo and NASA etc. Python is mostly used for
• Python is an object oriented programming language. It programming video games, artificial intelligence, natural
follows the object and class concepts. language generation, etc. Many types of applications can
be developed in Python, such as web applications,
• Being open source, Python is available on many gaming applications, ERP applications, and graphical
platforms like Linux, Windows, Mac OS etc. It is applications. Python can be used to script Microsoft's
platform independent programming language. Its code Active Server Pages (ASP) technology. Python is used
runs on all platforms easily. for web development (server-side) software
• Python supports GUI programming. There are many development, mathematics and system scripting.
modules like PyQts, PyQt4, WxPython for creating 3.3 Technical Strength of Python:
graphical user interface in Python language. Following are some of the major technical strengths
• Python is an interpreted language and the code is of Python–
executed line by line. It is different from programs like • The syntax of Python programming is very simple, so
it is easy to write code in this language.
C, C++. It does not require a compiler.
• Python language is free and open source. You do not
• Python is dynamic language. In this, while writing the
need to pay any money nor need any license to work
code, we do not need to declare the variable type. It on this language.
finds out the data type at runtime. • Python is a high-level programming language, while
• Python provides interface to all major commercial writing code it is not needed to take care of system
databases. architecture and memory management.

27
Search on TG: @apna_pdf
• A great feature of Python is that it is an object oriented • Then byte code is sent to the Python Virtual
programming language and supports OOPS concepts Machine (PVM), which is the Python interpreter.
such as class, encapsulation, inheritance etc. PVM converts Python byte code to machine
• Python supports GUI programming. For creating executable code. If any error is detected during this
graphical user interface in Python language, There are interpretation process, the conversion is stopped by
many modules such as PyQts, PyQt4, Wxpython and it displaying an error message.
is preferred by the developers for GUI development.
• Python is an interpreted language and the code is
executed line by line. It does not require a compiler.
• Python is a portable language. By creating a program
in Windows, users can also run it on other platforms
like Linux, Mac.
• Python is Integrated Language. It can also be
integrated with programming languages like C, C++,
Java. 3.5 To Download and Install Python:
• Python is a highly dynamic language. While writing Python is a widely used high level programming
code in other programming languages, the data type of language. To write and execute code in Python, we first
each variable has to be specified. While there is no need to install Python on our system. Pycharm is a cross
need to declare data type in Python runtime. platform editor developed by Jet Brains. It gives you all
• Standard and powerful inbuilt tools are available in the tools that you need for productive development in
Python to process all kinds of object types. Like– Python.
Concatenation, Slicing, Sorting, Mapping etc. Follow these steps to install Python and Pycharm–
3.4 Introduction to Python Interpreter and How to Install Python IDE– To download and install
Program: Python on Windows follow the steps below.
Python is an object oriented programming language. Step 1: To download and install Python, visit the
Python is called an interpreted language. Python uses official website of Python https://www.python.org /Go to
code modules, which are interchangeable, rather than a downloads and select your version. (Here Python version
long list of standard instructions for functional 3.6.3 is selected).
programming languages. The standard implementation of
Python is called CPython. It is the default and widely
used implementation of Python. Python converts its code
into byte code instead of machine code. There is
compilation in Python, but it is compiled in byte code
(⋅Pyc or ⋅Pyo) instead of machine language, the CPU
cannot understand the byte code, so a Python interpreter
is required to execute the byte code.
Python can be programmed using an interactive
command line (or IDE) but the code is not saved.
⇒ To save the program;
• Type commands into a text file.
• Save it with ⋅py extension. Figure-3.1 Downloading Python
Step 2: After the download is complete, run the exe
⇒ To use the interpreter;
file to install Python. Now click on Install Now.
• Open Command Prompt.
• Type Python or Py at the command prompt to
launch the Python IDE. Python source code goes
through the following processes to generate an
executable code–
• The Python compiler reads the Python source code
or instructions, then verifies whether the code is
well-formatted or not. That is, it checks the syntax
of each line. If any error is found, it immediately
stops the translation by displaying an error message.
• If no error is found in the code and code is in the
correct format, the compiler converts it into byte
code. Fig-3.2 To Install

28
Search on TG: @apna_pdf
Step 3: At this point Python can be seen getting
installed.

Figure-3.3 Setup Progress


Step 4: When it is finished you can see a screen Figure-3.6 Pycharm Setup Wizard
which displays setup successful. Now click on Close
Step 3: On the next screen, change the installation
path if necessary and click Next.

Figure-3.4 Successful Setup

How to Install Pycharm– How to download and


install Pycharm IDE on Windows for;
Step l: To download Pycharm, go to the
website https://www.jetbrains.com/pycharm/ download/
and click on the download link under the community Fig- 3.7 Setting the installation path
section.
Step 4: On the next screen, you can create desktop
shortcut and click on Next.

Fig-3.5 Downloading Pycharm

Step2: After the download is complete, run the exe


to install Pycharm. Click on Next when the setup wizard
starts it.
Figure-3.8 Creating Desktop Shortcut

29
Search on TG: @apna_pdf
Steps 5: Select Start menu folder. By Selecting Steps 8: After clicking on Finish the following
JetBrains click on Install. screen will appear.

Fig-3.12 Pycharm Screen


3.6 How to Start Python:
Fig-3.9 To Install Pycharm Python is a programming language that allows you
to work faster and integrate systems more efficiently.
Step 6: Wait for the installation to finish. Python in programming language, there are two ways in
which we can run our code;
(i) Python Shell–Interactive Mode (Command Line)
(ii)Python Editor– Script Mode (Integrated
Development Learning Environment - IDLE )
Python shell is used to execute a single Python
command and get the result in the same window. It waits
for input commands from the user. As the user enters a
command, it executes and displays the result.
IDLE is a simple Integrated Development Learning
Environment that comes with Python. It allows users to
edit, run, browse, and debug Python programs from a
single interface.
3.6.(i) Interactive Mode (Command-Line):
Fig- 3.10 Installation An interactive mode of working means that you type
commands at a time and Python executes the given
Step 7: After the installation is finished you will get
commands and outputs them. Python's interactive
a message screen that Pycharm is installed. If you want
to run it, first click on the "Run Pycharm Community interpreter is also called the Python shell. To work in
Edition" box and click on Finish. interactive mode when using Python, one can use the
command prompt in Windows or the terminal in Linux.
Example– Type "Python" to run Python program in
the command prompt. Then type the Python statement on
>>> prompt. Perform addition on two numbers and
produce output. Declare two variables a & b and declare
a variable c to store the result and print.
# Python program to add two numbers
a=2
b=3
# Adding a and b and storing result
c=a+b
# Printing value of c
Figure-3.11 Successful pycharm install Print (c)

30
Search on TG: @apna_pdf

Figure-3.14 Compiled Program Example


Figure- 3.13 Python Command Prompt Screen In the above example we see that the complete
We can see the desired output on the screen. Such a program is compiled and the code is executed line by
small program is easily executed in interactive mode. line. Output to the shell is completely different from
interactive mode.
Interactive modes are not suitable for large
programs. It does not save the statement. After creating a 3.6.(iii) Difference Between Interactive Mode
program, that cannot be used again. To use again, it has and Script Mode:
to be retyped.
3.6.(ii) IDLE-Script Mode: Intractive Mode Script Mode
It is a way of executing In this the python
In script mode, a Python program can be written in a
the python program in program is written in a
file. This file can be saved and executed using the which statements are single file. Python
command prompt. Users can view the code at any time written in command interpreter deletes the file
by opening the file, and editing becomes much easier. prompt and the result is and execute it, provides
obtained on the same. the desired result. The
Because we can open the entire code as many times as
program is compiled in
we want. Script mode is very suitable for writing long command prompt.
code. The created file is saved in the Python installation Interactive mode is more Script mode is more
folder by default and the extension for saving the Python suitable for, writting suitable for writing long
very small programs. programs.
file is py.
Code editing can be done Code editing can be done
To run the code in script mode, follow these steps– but it is hard work. easily in script mode.
Step 1: Create a file using a text editor. Users can use We get the output of In script mode, the entire
any text editor of their choice. each line of the code in program is first compiled
interactive mode. That and then executed.
Step 2: After writing the code save the file using ⋅py
is, the result is obtained
extension. after each line of code is
Step 3: Now open command prompt and command executed.
directory where your file is stored. The code cannot be, The code can be saved
saved and used in the and used in future
Step 4: Type Python "filename ⋅py" and press Enter. future.
Step 5: You will see the output at the command prompt. It is more preferred by It is more preferred by
Example– We write code to multiply two numbers the beginners. experts.
and the numbers to be multiplied are taken as input by
the user. In interactive mode as soon as we type the 3.7 Creating Python Program:
IDLE consists of two windows, shell window and
command it asks for input in the next line but in script
editor window. The Python Shell Window is an
mode first we save the whole program code then run it in interactive interpreter. IDLE includes a text editor
command prompt. Python interpreter executes the code window to open, edit, and create modules and scripts.
line by line and gives the result accordingly. Here we will create and save the program using the
Pycharm editor. For this follow the following steps–
31
Search on TG: @apna_pdf
Step 1: Open Pycharm editor. An introductory
screen will be displayed. Click on "Create New Project
to" create a project".

Figure-3.18 Typing the Python File Name


Step 5: Now type a simple program. print ("Hello
World")!

Figure-3.15 PyCharm Introduction Screen


Fig- 319 Simple Program
Step 2: You have to select a location– Step 6: Now go to Run menu and select "Run" to
(i) Select the place where you want to create the run your program.
project. If you don't want to change the location, change
its name from 'Untitled' to "First Project" or something
else as per your choice.
(ii) Pycharm should find the Python interpreter
which you installed earlier.
(iii) Click on 'Create' button.

Figure-3.20 Running the program

Step 7: At the bottom of the screen you can see the


output of the program.

Figure-3.16 Selecting New Project

Step 3: Now go to File menu and select New and


then select "Python File".

Fig-3.21 Program Output


Step 8: If Pycharm editor is installed in your system
then enter correct path of the file in the command
prompt.

Fig-3.17 Selecting a Python File

Step 4: A new pop-up dialog box will appear. Now


type the file name as per your choice and press OK
button.
Fig-3.22 Entering file path in command prompt
32
Search on TG: @apna_pdf
The output of the code will be– • Options Menu (Shell and Editor Window)–
Configure IDLE. Code Context (toggle) (displays only
in the editor window)
• Window Menu (Shell and Editor)– Zoom Height
• Help Menu (Shell and Editor)– About IDLE, IDLE
help. Python Docs, Turtle Demo
• Context Menu– Right clicking on the window
displays the context menu which includes Cut, Copy,
Figure-3.23 Code Output Paste, Set Break Point, Clear Break Point, Go to file /
3.8 IDLE Menu: Line options.
IDLE is the Integrated Development and Learning
Environment for Python. It has the following features-
3.9 Comments:
• Coding can be using the TKinter GUI toolkit in Comments in Python are used to explain any
python. program code. In Python, any statement written with the
• Cross platform works same on Windows, Unix and # symbol is not interpreted as a comment. Comments are
Mac OS mostly. not part of the program, but they enhance the program's
• Shell window (interactive interpreter) with colorizing interactivity and makes the program readable. Python
of code input, output and error messages supports two types of comments-single line comment
• Multi window text editor Multiple undo, Python and multiline comment.
Colorizing, Smart indent, Call tips, Auto Completion Comments are lines that are present in a computer
and other features. program but ignored by the compiler and interpreter. In
• Search in any window, replace in editor window and general it is a good idea to write comments when writing
search through multiple files (grep). or updating a program.
• TAB Completion; start typing the code, and then press Comments in Python begin with a hash (#) mark and
Tab key. IDLE will suggest you to complete the a whitespace character and last until the end of the line.
statement. To see the IDLE list of complete
Use the # symbol for a single line of code or to add a
suggestions, on >>> prompt type pr and then TAB
key. short, one line comment to your program.
• Recalls the code statement, press Alt + P to enter the Example–
previous code statement in IDLE or for go to the next # Python program to demonstrate comments
code statement Press Alt + N. Combination of both can
be used to fast runs programs. # Sample comment
• The recall code can also be edited easily.
name = "youthcompetitiontimes"
IDLE Menu– It has two main window types, shell
window and editor window. It is possible to have print (name)
multiple editor windows at the same time. IDLE menus In the above example, the comments are ignored by
dynamically change depending on which, window is the interpreter during program execution.
selected currently. Each of the following menus indicates
from which window type it is associated– 3.10 Python Character Set:
• File Menu (Shell and Editor)– New File Open, A character set is a group of characters in scripting,
Recent Files, Open Module, Class Browser, Path accepted by a programming language. The Python
Browser, Save, Save As, Save Copy As, Print character set is a valid characters set by the Python
Window, Close, Exit options are available. language that we can use while writing scripts in Python.
• Edit Menu (Shell and Editor)– Undo, Redo Cut, Python supports all ASCII/Unicode characters.
Copy, Paste, Select All, Find, Find Again, Find Python language supports two types of character
Selection, Find in files, Replace, Show Call Tip etc.
sets–
options are available.
• Format menu (Only Editor Window)– Indent (i) Source character,
Region, Dedent region, Toggle Tabs, New Indent (ii) Execution character Escape sequence
width, Format Paragraph, strip trailing whitespace etc
options are available. (i) Source characters– The source text is created
• Run menu (Only Editor Window)– Python Shell, using source characters. The source characters are as
Check Module Run Module. follows–
• Shell Menu (Only Shell Window)– View Last restart, Letter:All capital letters (A–Z) and all small letters (a–z)
Restart shell, Interrupt execution. Digit: All digits (0–9)
• Debug menu (Only Shell Window)– Go to File/ line, Special Symbols: Python supports all types of special
Debugger (toggle), Stack viewer Auto-open stack characters. Like–" ' | ; ! ∼ @ # $ % ^ ` & * ( ) _ + – = { }
viewer. []\|
33
Search on TG: @apna_pdf
White Space: White space like tab space, blank space, Literal– Literals are fixed values or data items used
newline etc. in a source code. There are many types of Literals in
Other: All ASCII and UNICODE characters supported python– character literal, numeric literal, boolean literal,
by Python to make up the Python character set. special literal, literals collections etc.
(ii) Execution Character Escape Sequence– These Operators–Operators are responsible for
characters are interpreted at the time of execution. These performing an operation in an expression. Operators can
can be represented by displaying letter keys on the be binary or unary.
keyboard. But line feed, form feed, tabs cannot be Actuator–These are the symbols used to organize
displayed. In Python in \n, \r, \t, \f and \v are treated as structures, statements, and expressions in Python-Like– [
whitespace characters. ] { } ( ) @ – = + = * // = \ etc.
Execution Meaning Result at Execution
3.12 Identifiers:
character Time
A Python identifier is a name used to identify a
\n End of line Moves the active position
variable, function, class, module, or other object. An
to the initial position of
identifier begins with the letters A to Z or a to z
the next row.
underscore (_) and consists of (0 to 9). Python doesn't
\r Carries Moves the active position allow @, $ and punctuation marks within identifiers.
Return to the initial position of Python is a case sensitive programming language.
the next paragraph.
\p Create Moves the active position
Here are some rules for writing identifiers in
Feed to the initial position of
Python–
the next logical page.
(i) Idnentifier can be of any length.
\v Form feed Moves the active position
(ii) The Idnentifier may be a combination of uppercase
to the next vertical
and lowercase letters, numerals or underscore.
tabulation position.
(iii) We cannot start Idnentifier with a digit while
\t Vertical Moves the active position
Variable1 is valid, 1Variable is not valid.
Tab to the next horizontal
tabulation position. (iv) The first character of the Idnentifier must be a letter
of the alphabet or an underscore (_).
\b Backspace Moves the active position
(v) These variables can be class object, list, dictionary,
to the previous position at
the current position. etc.
(vi) The rest of the Idnentifier name may consist of
\a Alert Produces audible alert.
uppercase or lowercase, underscores (_) or digits (0–
Example– # Example: 9).
Print("Welcome \n to youth competition times") (vii) The Idnentifier is a long sequence of letters and
numbers.
Output: (viii)Keywords should not be used as Idnentifier.
Welcome (ix) Starting an Idnentifier with an underscore makes it
personal.
to youth competition times
(x) Python Case Sensitive means that home and Home
3.11 Token: are different names.
A token is the smallest unit in a Python program. All 3.13 Keyword/Reserve Words:
the statements and instructions are made with tokens. In Some of the keywords / reserved words are as
a program there are various tokens in Python– follows–
Keywords– Keywords are such words that have
• Computer programming language includes sets of
some special meaning or importance in the programming predefined words which are called keywords.
language. They cannot be used as variable names,
• The rules prescribed for the use of each keyword are
function names or any other purpose. They are used for
called Syntax.
their special characteristics. We have 33 keywords in
Python. Some of them are as follows- Try, False, True, • Keywords are special reserved words in Python.
Class, Break, Continue, and, except, or, not, if, elif, print • Each keyword has a special meaning and a specific
act. operation because the name of any keyword is used in
Identifier– It is the user defined name which is a Python program cannot be used for any identifier like
given to different parts like class, variable, object and variable, function, class name etc. There are about 33
function. keywords in Python.

34
Search on TG: @apna_pdf
The list of keywords available in Python is as ● Int (Signed integers): Numbers (both positive and
follows– negative) without fractions As–100
False def if raise ● Long (Long integers): Integers with lower case or
uppercase L are of unlimited size.
None del import return Example–87032845L
True elif in try ● Float (Floting Point): Real numbers with both
integers and fractionals. Example–26.2
and else is while ● Complex: In the form of a + bi where, it is formed real
and b is the imaginary part of a complex number. For
as except lambda with
example– 3.14
assert finally non local yield Boolean Literals– Boolean literals can have either
True or False value.
break for not
Special Literal– There is a special literal in Python
class from or None, it is used to specify that field which is not created.
It is also used for the end of lists in Python.
continue global pass
Example– val1 = 10
Following are the differences between keyword and >>>val2 = None
identifier–
>>>val1
(i) Keywords are reserved words of a language while
identifiers are user defined names of variables, 10
functions and labels. >>>val2
(ii) Keyword is used for specific type whereas identifier >>>Print val2
is used to identify the name of a particular entity. None
(iii) Keyword can contain alphabet letters while >>>
identifier can contain letters, underscore, digits. Literal Collection– Collections are used in Python
(iv) Keyword has only lower case while identifier has such as tuples, lists, and dictionaries.
both lower and upper case. 3.15 Variable:
(v) Special symbols and punctuation are not used in Variable is a storage area which is used to store data,
keywords and identifiers also do not have any
variable and keeps on containing the data which can be
specific character other than underscore symbol is
changed at any time during program execution.
not used.
After declaring the variable, it is given a value, its
(vi) Keywords can not be classified while identifiers can
be classified into internal and external names. value is given by equal sign (=) such as– x = 5; or a = 10;
(vii) Keyword should always be started with lower case before using any variable, it has to be declared. For
while identifier should be started with uppercase, example, suppose we have to store the name of a student
lower case or underscore. and his roll number in a variable, for this we take two
variables. In one variable, store the name of the student
3.14 Literal:
while in other variable store the roll number. Variable
Literals can be defined as data in Python that is
initialization is the process that sets the initial value of a
passed to variables or constants. Python supports the
following literals– variable. The variable is set only once when it is created.
String literal– A string literal can be created by
enclosing text in quotes. We can use single (' ') as well as 3.15(i) To Manipulate Variables:
double quotes (" ") for strings. Like– "Python", 123456' Variable storage location name can given in
There are two types of strings in Python. Strings that computer memory. Using the equal sign (=) to assign a
end inside one line are called single line strings. value to a variable.
Example– >>> text1 = 'hello' Assigning the same value to more than one variable;
A string ending with multiple lines is called a Python allows assigning the same value to multiple
multiple line string. variables at once.
Example– Str2 = 'hello\ Example– a = b = c = 1
user' or, assigning the same text to multiple variables;
>>>str2 a = b = c = "Hello"
'hellouser' Print (a)
>>>
Print (b)
Numeric literals– All numeric literals are
Print (c)
immutable. Numeric literals can follow four different
numeric types– Assigning multiple values to multiple variables;

35
Search on TG: @apna_pdf
Multiple objects can also be assigned to multiple In Python, int, float, decimal, bool, string, tuple and
variables. Like- a, b, c = 6, #, yct where objects with the Range are immutable data types, their contents cannot be
values 6 and # are assigned to the variables a and b, a changed once it is created in memory.
string with the value "yct" is assigned to string object C. Example– #Python Code to text that
Example–Assigning multiple values to multiple # imutable
variables; number = 42
x, y, z = 5, 3.6, "Hello " print (id (number))
Print (x) number + = 1
Print (y) Print (id (number))
Print (z) Output:1657696608
Assigning none to a Variable; The None keyword is 1657696640
used to define a null variable or object. We can assign Example– #Python Code to text that lists are
"None" to any variable. None statement supports both is #mutable
and (= =) operators. Comparing none with anything Color = ["red", "blue", "green"]
returns False. Print (Color)
Example– Checking if a variable is "None" using "is" Color [0] = "Pink"
operator. Color [-1] = "Orange"
#Declaring a None Variable Print (Color)
Var = None Output: ['red', 'blue', 'green']
if Var is None : ['pink', 'blue', 'orange']
Print ("None")
else: 3.15(iv) Variable Assignment & Accepting
Print ("Not None") Input:
Example– Checking if a variable is "None" The assignment statement creates a variable and sets
Using = = Operator its value, or changes the value of an existing variable.
The value assigned to a given variable does not need to
# Declaring a None Variable
be specified in the program.
Var = None
if var = = None;
Example– #taking input from the user as integer
Print ("None")
num = int (input ("Enter a number:")
else:
add = num +1
Print ("Not None")
#output
3.15(ii) Types of Variable: print (add)
A variable has its own limit or boundary, outside Example– name = input ("Enter your name:")
which it does not work, that limit is called the scope of print (name)
the variable. Variable is of two types depending on its
#output:
scope which are as follows– 1. Global, 2. Local
#Enter your name: James
Global Variable– Global variable is a variable that
#James
is declared outside the functions. A global variable can
be used in all functions. 3.15(v) Working with Dynamic Typing:
Local Variable– Local variable is a variable that is Python uses dynamic typing. In dynamic typing, the
declared inside the function. Local variable is used only data type of a variable depends only on its value type. It
where the function is declared. does not know the type of the variable until the code is
3.15(iii) Mutable and Immutable: run. That's why there is no use of declaration. , It stores
the value at some memory location and then binds the
Mutable Data Type– Data objects are stored in the
variable name to that memory container and makes
computer's memory for processing. Some of these
accessible the contents of the container by that variable
objects can be modified during processing, called
name. So it understands the type of the value at run-time.
mutable objects.
Example– In the following Python statement;
Some mutable data types in python are data list,
dictionary set. It is possible to add, delete, insert and An integer value is assigned to Variable a. If the
rearrange. same variable is used to refer to a string, Python is used.
Immutable Data Type– Such objects stored in the a = 14
computer's memory for processing, which cannot be print (a)
modified during processing, are called immutable data a = "Orange"
types. Print (a)

36
Search on TG: @apna_pdf
Output:14 a list can do. The Concatenation Operator (+) and
Orange Repetition Operator (*) work with lists in the same way
This means that the variable a first holds the integer as with strings.
value 14 and then the string value Orange. This is the
reason why Python is called a dynamically typed Like– l = [1, "hi", "Python", 2]
language. Print (l[3:]);
\3.16 Constant: Print (l[0:2]);
Constants are items that represent direct values and Print (l);
whose values cannot be changed during program Print (l+l);
execution. Such values are called constants. Unlike other Print (l*3);
programming languages, there are no constants in
Output:
Python. Instead, Python provides us capitalized naming
[2]
convention method, thus it is treated as a constant.
numbers, Fixed values like letters and strings are called [1, 'hi']
constants. String constants uses single quotes (' ') or [1, 'hi', 'Python', 2]
double quotes (" "). [1, 'hi', 'Python', 2,1, 'hi', 'Python', 2]
Example– >>> print (25) [1, 'hi', 'Python', 2,1, 'hi', 'Python', 2,1, 'hi',
>>> print (90.2) 'Python', 2]
>>> print ('Welcome to Python World')
>>> name = "James" Tuple–Tuple is also similar to list. Like a list, a
>>> print (name) tuple contains a collection of contents of different data
type. Items are separated with commas (,) and written in
3.17 Data Types: parentheses ( ). Tuple is a 'read only data structure'
Data type is a classification of data items. It because the size and value of tuple objects cannot be
represents the type of value that tells what operations can modified.
be performed on a particular data. Everything is an Example– # tuple of strings
object in Python programming, data types are actually my-data = ("hi", "hello", "bye")
classes and arrays are objects of these classes.
Print (my–data)
A variable can hold values of different data types.
Output: ('hi', 'hello', 'bye')
Python is a dynamic language so there is no need to
define the variable type while declaring it. Variables can
be checked using Type ( ) in Python. Dictionary– Dictionary is an ordered set of key
value pairs of dictionary items. It is like an associative
Python supports the following data types–
array or hash table where each key stores a specific
Number– It stores the numeric value. Python
value. Keys can be any primitive data type while value is
supports four types of numeric data–
an arbitrary Python object. Items in a dictionary are
• int – Signed integer such as–10, 2, 29 etc. separated by commas (,) and written in curly brackets {}.
• Long– Long integer is used for higher range of values. Example–
Example– 908090800L >>> Capitals = {'Lucknow' 'Patna', 'Chennai':
• Float– Float is used to store floating point numbers. 'Bhopal', 'Mumbai' 'Jaipur}
Example– 19.9.902, 15.2 etc. >>>Print (Capitals)
• Complex– It is used to store complex numbers. Such
as– a+bi, 1.141, 2.31 etc. Tuple– It is such a structure of Python that defined
Python allows us to use lower case L with long once, cannot be changed. Tuples are a type of sequence
integer. but they are immutable like strings. Tuples are generally
String– A string can be defined as a sequence of used to represent a fixed collection of items. Such as–
characters enclosed in quotation marks. To define string Weekday, Name, Month Names, Calender Dates etc.
in python Single (' '), double (" ") or triple ("' "') quotes which are always fixed. Parenthesis is used to specify
can be used to define. Python has many inbuilt functions tuples and in tuples, we can store any type of data,
and operators. nesting any type of data and perform any kind of
In string handling, operators are used to concatenate operation, Which can be performed on any sequence. A
strings, because "Hello" + "Python" returns "Hello tuple is a read-only data structure because the size of the
Python" objects in a tuple and value cannot be modified.
List– list is similar to Array. The list can contain Example– # Create a tuple:
different types of data. Items stored in the list are this tuple = ("apple", "banana", "Cherry")
separated with commas (,) and written inside square Print (thistuple)
brackets. Using the Slice [:] operator to access the data in Output: ('apple', 'banana', 'Cherry')
37
Search on TG: @apna_pdf
3.18 Print Statement: When an input function executes, program flow is
In Python, we use the print ( ) function to print anypaused until the user has given input. When input, given
type of data output on the computer screen (console). To to the input function it converts in a string. Even when
inputting a numeric value, the input function converts it
print any message, enter that message in (' ') or (" ") and
print. to a string. You have to use typecasting to convert your
Print ( ) Function Syntax: code to integer.
print (objects (s), sep separator, end = end, file = Example– # input two integer values-
file, Fluse= flush) num1 = int (input ( ))
Print ( ) Function Parameters: num2 = int (input ( ))
In the print ( ) function, the elements written inside # Print sum in integer
the brackets are called parameters. All its parameters are Print (num1 + num2)
optional ie. It is completely up to the user whether you
want to pass any parameter to the print( ) function or not. Example: (i)–
Example– Program: # Python input ( ) function example
Print ("Welcome to yct.com") # Calling fuction
Print ("Hi! I am print ( ) function") Val = input ("Enter a value:")
Output: Welcome to yct.com # Displaying result
Hi! I am print ( ) function Print ("you entered:", val)
Output:
The text written in double quotes inside the print ( ) Enter a value : 45
function is received as output. If more than one line to be You entered : 45
printed, triple quotes should be used instead of double
quotes. Example:(ii)– Printing the user's name and age as input,
Example– print (’’ ’ Twinkle, Twinkle, little star # Taking name of the user as input
How I wonder what you are # and storing it in name variable
Up above the world so High name = input ("Please enter your Name:")
Like a Diamond in the Sky’’ ’) # taking age of the user as Input
Output: Twinkle, Twinkle, little star # Storing it into variable age
How I wonder what you are age = input ("Please Enter your Age")
Up above the world so High Print ("Name & Age : ", name, age)
Like a Diamond in the Sky. Output:
Please Enter your Name : Rohan
Please Enter your Age : 16
3.19 To Accept Input from Console:
Name & age : Rohan 16
In Python input is used to receive information from
the user and print is used to display the information on Example:(iii)– Taking two integers from the user and
the screen. A console (also known as a shell) is basically adding them,
a command line interpreter that interacts with the user. # Taking number 1 from user as int num 1 = int
Takes input and at the same time, interprets and provides (input ("Please Enter first Number:"))
expected output and displays error message in case of # Taking number 2 from user as int num 2 = int
error. (input ("Please Enter second number:"))
The primary prompt of the Python console is >>> # adding num 1 and num 2 and storing
Symbols (Three Greater than Symbols). # them in variable addition
Accepting Input from the Console–The user inputs addition = num 1 + num 2
values on the console and uses those values as per the # Printing
program. The in-built function input ( ) is used to take Print ("The sum of the two given numbers is { }".
input from the user. format (addition))
Input ( )– Input in Python is accomplished using an Output:
assignment statement combined with a special function Please Enter First Number : 10
called input ( ). Please Enter Second Number : 20

38
Search on TG: @apna_pdf
The sum of the two given numbers is 30 RUN
>>>
Example;(iv)– Taking two lists as input and adding
Please enter an integer value:
them,
35
# Taking list 1 input from user as list
list 1 = list (input ("Please Enter Elements of Please enter an other integer value:
list 1:")) 40
# Taking list 2 input from user as list 35 + 40 = 75
list 2 = list (input ("Please Enter Elements of >>>
list 2 :")) Program: 2– Program to convert the time inputted
# Appending list 2 into list 1 using by the user in hours and minutes,
# Append function # Program to Convert the time given in minutes in hour
for i in list 2 : and minutes
list 1⋅append (i) time = int (input ("Enter time in minutes:"))
# printing list 1 hour = time/60
Print (list 1) minutes = time% 60
Output: Print = ("Hour:", round(hours))
Please Enter of list 1 : 12345 Print = ("Minutes:", minutes)
Please Enter of list 2 : 6789
RUN
['1', '2', '3', '4', '5', '6', '7', '8', '9']
>>>
3.19(i) eval ( ) Function: Enter time in minutes: 90
The eval ( ) function is used to evaluate the value of
Hours: 1
a string. It takes string as argument and evaluates this
string as a number and gives a numeric result. It can also Minutes: 30
evaluate expressions, if it's a string. >>>
Example:(i)– x = 1
Print (eval ('x + 1') Programs: 3– Program to find the area of a circle;
Output: 2 # Python Program to find Area of circle using Radius.
Example:(ii)–Converting the temperature given in PI = 3.14
Celsius to Fahrenheit, radius = float (input ('Please Enter the radius of a
# program to convert temperature in celsius circle:'))
# into Fahrenheit area = PI * radius * radius
temp = eval (input ('Enter a temperature in Print ("Area of circle = % ·2f" % area)
celsius : ')) Output–
Print ('In Fahrenheit, that is', 9/5 * temp + 32) Please enter the radius of circle = 4
Output: Area of Circle = 43.96
Enter a temperature is celcius : 0
In Fahrenhiet, that is 32.0
Program: 4– Enter a number and display its cube
3.20 Simple Python Programs: value,
Program: 1– Program to add two numbers inputted
by the user, number = int (input ("Please Enter any integer
#Program to add two numbers given by user. numeric value : "))
Print ('Please enter an integer value:') cube = number * number * number
X = input ( )
Print ('Please enter an other integer value:') print ("The cube of a given number { 0 } = {1}".
Y = input ( ) format (number, cube)
num1 = int (x) Output:
num2 = int (y) Please Enter any numeric value : 5
Print (num1, '+' , num2, '=' , num1+ num2) The cube of a given number 5 = 125

39
Search on TG: @apna_pdf
Practice Questions with Explanatory Solutions
1. Who developed the Python programming 5. Which one of the following is an invalid variable?
language? (a) My-string-1 (b) foo
(a) Vic van Rossum (c) – (d) 1st-string
(b) Rasman Lerdorf Ans. (d) Underscore (–), my string-1, foo are valid
(c) Guido van Rossum variables while Ist-string is an invalid variable.
(d) Neon Stom Variables should not start with numbers in Python
programming.
Ans.(c) The Python programming language was
6. What is the maximum possible length of an
created by Guido Van Rossum in the 1980s. It was
identifier in Python?
started in the National Institute for mathematics and
(a) 31 characters (b) 79 characters
computer science netherlands. At present, Python is
(c) 63 characters (d) none of these
maintained by the Core development team, who add
new updates and features to the Python programming Ans.(b) Identifier is a name of a reserved memory
language. The first version of Python - Python 1.0 was location. To identify a variable, class, function, etc.
Identifier is used. The maximum possible length of an
introduced in the year 1994. After this many version
identifier is 79 characters in Python.
updates kept coming.
7. The speciality of Python program is–
2. What types of programming does Python
(a) Easy to learn and read
support?
(b) Interactive mode
(a) Object oriented
(c) Free and open source
(b) Structured programming (d) All of the above.
(c) Functional programming
Ans.(d) Python is a powerful high level programming
(d) All of the above language. It's easy to learn and use. It is easier to code
Ans.(a) Python is a general purpose, dynamic high in Python as compared to other popular programming
level and interpreted programming language. It languages like Java and C++. Python also supports an
supports object oriented programming to develop interactive mode in which you can interact with the
applications in which the code is contained inside the direct translator to execute the program and get the
object. output. Python is free and open source, meaning its
source code is available to the public. Anyone can
3. Function blocks begin with the keyword…....
download and use it.
(a) Function (b) Def
8. All keywords in Python occur in ............
(c) Fun (d) Define
(a) lower case (b) upper case
Ans. (b) Def keyword is used to declare a function in (c) capitalized (d) none of these
Python. The function is named after the def keyword.
Ans. (d) A computer programming language consists
It would have been better if the name of each function of pre-defined sets of words called keywords. The rule
was related to its statement. set for the use of each keyword is called Syntax. Each
4. Find the output of the following python program. keyword has a special meaning and a specific
a = "Meetmeafter party" operation because the name of a keyword cannot be
b = 13 used for an identifier like a variable, function, class
Print a + b name, etc. in Python. There are 33 keywords defined
in Python. Capital letter is used only in True, False
(a) 29 (b) 14
and None keywords, all other keywords are written
(c) Error in code (d) 15 using small letter, assert, non local pass, int, float else,
Ans.(c) The output of the program will be error in raise, import etc keywords are available in python.
code because a string has been assigned as the value in 9. Which one of the following is not a predefined
variable a. A and numeric value in variable B. Strings data type of Python?
cannot be concatenated with numeric values, so this (a) class (b) list
will display error. (c) dictionary (d) tuple

40
Search on TG: @apna_pdf
Ans.(a) Variable can hold different types of value in 13. Which of the following is false about the
Python. Python provides various standard data types interpreter?
which defines the storage method on each of them, (a) Interpreter produces an object program from the
predefined data types in Python- Number, String List, source program.
Tuple and dictionary. (b) Interpreter is a type of translator.
Number stores a numeric value. It supports four (c) Interpreter analyzes every source detail
types of numeric data int, long, float, complex. A
whenever it is executed.
string can be defined as a sequence of characters
enclosed in quotation marks. In Python we can use (d) None of these
single (' '), double ( ) or triple ( ) quotes to define a Ans. (d) When a Python program is written, the
string. Python interpreter reads each line of the program one
List; It can contain different types of data. Items by one. Interpreter is a type of translator. It analyzes
stored in the list are separated with commas and any source detail before executing it. Python does not
square brackets [ ] are inside. need to be converted to binary code in order to run it.
Tuple; It's almost like a list. The items of a tuple 14. Which of the following is correct about Python?
are separated by commas and enclosed in parentheses (a) It supports automatic garbage collection.
( ). Tuple read only data structure.
(b) It can be easily integrated with C C++, COM,
Dictionary; It is an ordered set of item's key value
Active X, CORBA and JAVA
pairs. It is like an associative array or hash table,
(c) Both of the above
where each key stores a specific value.
(d) None of these
10. The limitation of Python is–
(a) It is not the fastest language. Ans.(c) Python is a general purpose, dynamic high
(b) Fewer libraries level and interpreted programming language. It
(c) Both A and B supports object oriented programming to develop
(d) None of these applications in which the code is contained inside the
object. Python supports automatic garbage collection.
Ans.(a) Python is an interpreted language and it does
not use compiler so it executes slowly as compared to It can be easily integrated with C, C++, Com, Active
languages like C, C++. X, CORBA and Java.
Apart from this, the Python language consumes 15. Python is derived from many other languages
more memory. Due to this, advanced level mobile which include–
apps and games are not developed. Due to no-use of (a) ABC (b) Modula-3
compiler in this, error is not detected in compile time, (c) Algol-68 fice (d) All of the above.
by which the work of error detection becomes
Ans.(d) Python is derived from many other languages
difficult.
which include ABC, Modula-3. C. C++, Algol - 68
11. What does the comment start with in Python?
Smalltalk, Unix Shell and other scripting languages.
(a) ! (b) #
We don't need to take license to use python because
(c) & (d) *
python is available under the General Public License
Ans.(b) Comments are used to explain any program
(GPL). Python can be easily integrated into C, C++
code in Python. Any statement written with the #
and Java programming languages.
symbol in Python is known as a comment. Comment
is not part of the program but it adds to the 16. What is the process of setting the initial value of a
interactivity of the program. Python supports two variable called?
types of comments single line comment and multi line (a) Scripting (b) Initialization
comment. (c) Typecasting (d) None of these
12. Python is being used in the field of– Ans. (b) Initialization is the process that sets the initial
(a) Scripting (b) web application value of a variable. This can only be done once for
(c) GUI programming (d) All of the above.
each variable, when it is created.
Ans.(d) Python is an object oriented, high level
17. What is the conversion of one data type to
programming language, which is used in tasks like
website building, app development, machine learning, another data type called?
data analysis, GUI programming, scripting. Python is (a) Scripting (b) Initialization
also called a general purpose programming language. (c) Typecasting (d) None of these

41
Search on TG: @apna_pdf
Ans. (c) In typecasting one variable is converted to 23. How many arguments, a Python program can
another variable. For example, if an integer variable is accept from the command line?
converted to float or from float variable to integer, (a) One (b) Two
then it is called type casting. (c) Three (d) any
Ans. (d) A Python program can accept any number of
Syntax– (data type-name) Expression
arguments from the command line.
18. An immutable linear data structure is– 24. What is the output of >>> float ('12.6')
(a) Tuple (b) Multiline (a) 12.6 (b) 12.6'
(c) String (d) List (c) 12 (d) Syntax error
Ans.(a) An immutable linear data structure is called a Ans.(a) 'Float()' function returns a floating point
tuple. Tuple is another form of collection where number.
different types of data can be stored. It is similar to a Syntax– Float([ ])
list where the data is separated by commas (,). Example– print(float('12.6'))
Basically just this the difference is that a list uses The output will be 12.6.
square brackets [ ] and a tuple uses parentheses ( ). 25. What is the output of the following code?
x = 50
19. The notation used by the Python interactive
def func (x):
system is– x=2
(a) $ (b) (...) func (x)
(c) # (d) all of the above. print ('xis now' x)
Ans.(b) The (...) sign is used by the Python interactive (a) x is now 50 (b) x is now 2
system. When executing python code using python (c) x is now 100 (d) Error
interactive prompt, we have to type python codes Ans. (a) x = 50 is written as a global variable and x =
again and again because interactive prompt doesn't 2 is written inside the function, so outside the function
only the global value will be printed. The scope of a
save our codes in any way.
function variable is only inside the function, while the
20. By whom all the parameters (arguments) are scope of a global variable is throughout the program.
passed in the Python language? Output– 'x is now 50'
(a) Objects (b) List 26. Which of the following is not a keyword?
(c) Local variable (d) None of these (a) Eval (b) Nonlocal
Ans.(c) In Python language, if we want to use a (c) Assert (d) Finally
variable throughout the program or module, then we Ans. (a): In Python, eval is used as a variable. It is a
built-in function that is used in Python and evaluates it
can use that variable as Global variables are declared
as a Python expression. In simple words the eval
whereas local variables can be used only in a function evaluates a string like a python expression. It
particular function or method. Python all arguments in evaluates and returns the result as an integer.
the language are passed through local variables. 27. Which of the following is not a valid identifier?
21. Raw data assigned to a variable is called as (a) Student (b) s12
........... . (c) 123 (d) _123
(a) Variable (b) Literal Ans.(c) A variable name in Python should not start
(c) Identifier (d) Comment with a number.
A variable name must begin with a letter or an
Ans. (b) A literal is the raw data passed into a variable underscore character.
or constant. Basically, the data that we specifies to a Such as– students, s12_123 etc.
variable or constant is called literal. 28. Which symbol is used to write single line
22. What is the maximum possible length of an comment?
identifier? (a) * (b) #
(a) 16 (b) 32 (c) / (d) ?
(c) 64 (d) None of these above Ans. (b) # symbol is used for single line comment in
Python program. Comments are non-executable
Ans. (d) The maximum length of an identifier in
statements in Python. This means that neither the
Python can be 79 characters. Python is one of the most Python compiler nor the P.V.M. will execute them.
popular programming language. It is devloped by Comments are intended for human understanding and
Guido Vas Rossum. not for compilation.

42
Search on TG: @apna_pdf

4 OPERATORS, EXPRESSION AND


PYTHON STATEMENTS

4.1 Operators: • If any operand is a floating point number, the


An operator is a symbol that represents an operation result is converted to floating point.
and the values on which the operator operates are called • If both operands are integer, then result also
operands. Operators are used to perform mathematical or becomes integer. No conversion is required.
logical operations in a program. Operators can be unary, Example 1– Demo of Arithmetic operator:
binary and ternary. # Demo of arithmetic operator
For example, in expression a + b; # Subtraction (–) operator
The sign '+' is an operator and the two operands are
y=4
a and b. It has operator (+) which performs arithmetic
addition on a and b. Returns the sum of the two operands x=2
as the result, there are 7 types of operator in Python that Print (y – x)
you can use– # Multiplication (*) operator
x=2
y=4
Print (x * y)
# Addition (+) operator
y=2
x=2
Print (y + x)
# Modulus (%) operator
x=4
y=2
Print (x % y)
# Division ( / ) operator
4.1(i) Arithmetic Operators: y = 10
These operators are used to perform mathematical x=2
operations. Like addition, subtraction, multiplication,
Print (y/x)
division, modulus, exponent etc. Various arithmetic
calculations can be done in Python. # Exponentiation ( ** ) operator
+ (Addition); This operator joins two operands. Its x=2
syntax is X + Y. y=5
(–) (Substraction); This operator subtracts two Print (x**y) # same as 2*2*2*2*2
operands. Its syntax is x – y. # Floor Division ( / ) operators
(*) (Multiplication); This operator multiplies two y=5
operands. Its syntax is x * y. x=2
(/) (Division); This operator divides the left
Print (y // x)
operand by the right operand. Its syntax is x/y.
(%) (Modulus): This operator divides the left Hirarechy of Arithmetic Operators–In Python,
operand by the right operand and returns the remainder. calculations are performed in a specific order, called
Its syntax is x % y. operator precedence. Associativity means when an
(//) (Floor Division); This operator divides the left expression consists of two or more operators with same
operand by the right operand and returns the quotient. It precedence, in which order should they be executed. This
discards the decimal part. Its syntax is x//y. is usually in order from left to right. This means,
(**) (Exponential); Right hand operand becomes operators with the same precedence are evaluated in a
Power of left hand operand. Its syntax is x**y. left-to-right manner.
Arithmetic operators return the result type which Example–Precedence of multiply (*) and division
depends on the type of operands given below– (/) is same and their associativity are in order from left to
• If any operand is a complex number then the right. So, expression "100/10 * 10" would be executed in
result is also converted to complex. order of "(100/10) * 10.
43
Search on TG: @apna_pdf
Precedence of Arithmetic Operators– a=5
( ) (Parentheses) Highest b=6
Print (a = = b)
* * (Exponention)
Print (a = = 5)
– (Negation) Print ((a < b) = = (b > a))
/ (Division) and // Output:
( Integer divison), False
* (Multiplication) True
% (Modulus) True
Not equal to (! =) Relational Operator
+ (Addition) and – (Subtraction) Lowest Source Code:
The order of operation of arithmetic operators is as a=5
follows– b=6
(a) Parentheses have highest priority. Parentheses are Print (a! = b)
evaluated first while evaluating an expression. Print (a! = 5)
(b) Exponentiation has the next highest priority and Print ((a < b)! = (b < a))
evaluated from right to left. Output:
(c) Multiplication and division have same precedence True
greater than addition and subtraction which have the False
same precedence. True
(d) Operators with the same precedence are evaluated Less than (<) Relational Operator
from left to right (except in exponentiation). Source Code:
a=5
Example– 1 + ((3 + 1) / (8 – 4) –5) b=6
= 1 + (4 / (8 – 4) –5) Print (a < b)
= 1 + (4 / 4 – 5) Print (a > b)
= 1 + (1 – 5) Output:
=1+–4 True
= –3 False
4.1(ii) Relational Conditional Operators: Greater than (>) Relational Operator
Relational operators are also called comparison Source Code:
operators. It is used to compare two values. It returns a=5
b=6
TRUE or FALSE value depending on the condition.
Print (a > b)
Relational operators include the following operators–
Print (a < b)
(if x = 5 and y = 10)
Output:
= = (Equal to); This operator, returns TRUE if the
False
value of both operands is equal. Its syntax is x = = y.
True
(This condition is not true.)
Less than or Equal to (< =) Relational Operator
! = (Not Equal to); It returns TRUE if the values of
Source Code:
both the operands are not equal. Its syntax is x! = y is
a=5
(This condition is not true.)
b=6
> (Greater than); If the value of left operand is
c=5
greater than the right operand then it returns TRUE value Print (a < = b)
assuming condition. Its syntax is x > y. (This condition is Print (a < = c)
not true.) Output:
< (Less than); If the value of the right operand is
True
greater than operand, Returns TRUE as result. Its syntax
True
is x < y. (This condition is true.)
> = (Greater or equal to); If the value of left Greater than or Equal to (> =) Relational Operator
operand is greater than or equal to the right operand then Source Code:
the condition is true and Returns TRUE as the result. Its a=5
syntax is x > = y (the condition is not true.) b=6
< = (Less or equal to); If the value of the right c=5
operand is greater than or equal to the left operand, then Print (a > = b)
the condition is true. Its syntax is x < = y (this condition Print (a > = c)
is true. Output:
Example– Equal to (= =) Relational Operator False
Source code: True
44
Search on TG: @apna_pdf
4.1(iii) Logical/Boolean Operators: 4.1(iv) Assignment Operators:
Logical Operators– It is an operator that compares Assignment operators are used in Python to assign
Boolean expressions. It returns the Boolean result. values to variables. For left operand this Assigns the
Boolean expression returns, 1 as TRUE result and value of the right expression.
Returns 0 as the False result. Operators Description Example
Operators Description Example = It assigns the value to
AND If both operands 6>3 and 5<10 the expression on the X=5
are true then (condition is left side.
condition becomes true) += It adds the right
True. operand with the left x + 5 = 5 or,
OR If either of one 6>3 and 5<10 operand and assigns x=5+5
operand is true (condition is the result to the left
condition becomes true) operand.
true. –= It subtracts the right
NOT If the value of the not (5 < 2) operand from the left x – = 5 or,
operand is false (condition is operand and assigns x=x–5
the condition is true) the result to the left
true. operand.
Example– Logical AND (and) Logical Operator *= It multiplies the right
Source code: operand to the left x * = 5 or,
a=5 operand and assigns x=x*5
b=6 the result to the left
Print ((a < b) (b > a)) operand.
Output: /= It divides the left
True operand by the right x / = 5 or,
Logical OR (or) Logical Operator operand and assigns x=x/5
Source code: result to the left
operand.
a=5
b=6 %= It takes the modulus
of the two operands x % = 5 or,
Print ((a < b) or (b > a))
and assigns it to the x=x%5
Print ((a < b) or (b < a))
left operand.
Output:
**= It performs Power on
True
the operands and x ** = 5 or,
True assigns them to the x = x ** 5
Logical NOT (not) Logical Operator left operand.
Source code:
// = It performs floor
a=5 division on the x // = 5 or,
b=6 operands and assigns x = x // 5
Print (not (a > b)) it to the left operand.
Print (not (a < b)) Example:
Output: Assignment Operator
True Source code:
False a=3
b=4
Hierarchy of logical operator– c=a+b
not Highest Print (c)
and Output:
7
or Lowest Add Assignment Operator
The logial 'not' operator has higher precedence than Source Code:
the other two operators. Both logical operator and/or, has a=3
less precedence than the relational and airthmetic c=6
operators. c+=a #c=c+a

45
Search on TG: @apna_pdf
Print (c) Floor Divide Assignment operator
Output: Here 'c' variable is divided by the 'a' variable and
9 its floor value is stored in c variable.
Source code:
a=3
Subtract Assignment Operator c=6
Source Code: c // = a # c = c // a
a=3 Print (c)
c=6 # same as
c–= a # c=c–a import math
Print (c) a=3
Output (c) c=6
Output: c = math.floor (c/a)
3 Print (c)
Output:
2
Multiply Assignment Operator 2
Source Code: Bitwise AND (&) Assignment Operator
a=3 Source Code:
c=6 a=3
c* = a #c=c*a c=6
Print (c) c&=a #c=c&a
Output: Print (c)
18 Output:
2
Divide Assignment Operator Bitwise OR ( | ) Assignment Operator
Source Code: Source Code:
a=3 a=3
c=6 c=6
c/=a # c = c/a c|=a #c=c|a
Print (c) Print (c)
Output: Output:
2.0 7
Bitwise OR ( ^ ) Assignment Operator
Modulus Assignment operator Source Code:
Here 'C' variable is diveded by the 'a' variable and a=3
its remainder is returned and stored on the 'c' variable. c=6
Source Code: c^=a #c=c^a
a=3 Print (c)
Output:
c=6
5
c%=a #c=c%a Bitwise Left Shift ( < < ) Assignment Operator
Print (c) Source Code:
Output: a=3
0 c=6
c<<=a #c=c<<a
Exponent Assignment operator Output:
Here 'a' is the power of the variable 'c' and the 48
values are stored in 'c' variable.
Bitwise Right Shift ( > > ) Assignment Operator
Source Code:
Source Code:
a=3
a=3
c=6
c=6
c** = a # c = c**a
c>>=a #c=c>>a
Print (c)
Print (c)
Output:
Output:
216
0
46
Search on TG: @apna_pdf
4.1(v) Bitwise Operators: 4.1(vi) Membership Operators:
Bitwise operators operate on bits and perform bit- Python has membership operators, which test the
by-bit operations. membership of a sequence, such as strings, lists, or
tuples.There are membership operators which are as
Operators Meaning Example follows–
& Bitwise AND x&y in If element or value is found in Collection
(list, tuple, dictionary, String, set) returns
| Bitwise OR x|y
True.
∼ Bitwise NOT ∼x not in If the element or value is not found in the
^ Bitwise XOR x^y collection (list, tuple, dictionary, string, set)
returns, True.
>> Bitwise Right Shift x>>2 'in' Membership Operator
<< Bitwise Left Shift x<<2 source code:
The arranged precedence of bitwise operators in a = "Hello world"
descending order is as follows– Print ("11" in a)
list = [1, "0", 8, 5]
Bitwise NOT (~), Bitwise Shift Operators (<< >>),
Print (1 in list)
Bitwise AND ( &), Bitwise XOR (^), Bitwise OR (|). Output:
Left Shift Operator (<<) – This Shift the bits of the True
operand to the left. The number by which we have to True
shift the bits of an operand, we write that number after 'not in' Membership Operator
this operator. (Each number in memory is represented as source code:
a = "Hello world"
bits or binary digits.
Print ("LOL" not in a)
It is stored as– 60 << 2
list = [1, "0", 8, 5]
60 is represented in bits by 00111100 which returns Print (3 not in list)
11110000 (240) when left shifted by 2 bits. Output:
Right Shift Operator (>>) – This Shifts the bits of True
the operand to the right. We write the number after this True
operator as much as we have to shift the bits of an 4.1(vii) Identity Operators:
operand. Identity operators compares the memory locations of
two objects in Python.
Example– 11>>2
is If both operands share the same
11 is represented in bits by 1011, which returns identity then the condition will be x is y
0010 (2) when right shifted by 2 bits. true.
is not If both the operands does not share
# Python program to show bitwise operators the same identity condition will be x is
a = 10 true, otherwise it will be false. not y
b=4
'is' Identity Operator
# print bitwise AND operation source code:
print ("a & b = ", a & b) a=4
# print bitwise OR operation b=5
c=4
print ("a/b =", a/b)
Print (a is c)
# print bitwise NOT operation Print ((a < b) is (b > a))
print (" ∼ a = ", ∼ a) Output:
# print bit wise XOR operation True
True
print ("a ^ b =", a ^ b)
'is not' Identity Operator
Output: source code:
a&b=0 a=4
a/b = 14 b=5
∼ a = –11 Print (a is not b)
Output:
a ^ b = 14 True

47
Search on TG: @apna_pdf
4.2 Expression: Example– age = int (input ("enter age ....."))
An expression is a combination of symbols, if age > = 15;
operators and operands. For example, 100/10*5 is an Print ("you age above 15")
expression. Output:1. enter age..........16 # Condition is true
The result of an expression is always a value. An You are above 15
expression consists of one or more operands and one or Output:2. enter age..........12 # Condition is not true
more operators linked together to calculate a value.
In Python, only one statement is written in one line, Output in the above program, when the condition is
but if you want to define multiple statements in one line, true, we get the output while if the condition is not true,
then use semicolon (:). If you are writing a statement that no output is obtained.
comes in multiple lines, then the line continuation
character (\) is used for this. 4.4(ii) If-else Statement:
A Python statement is an instruction or a unit of The if-else statement is used to test a particular
code that the Python interpreter can execute. Commands condition. If the condition is TRUE, then if statement is
executed; if the condition is FALSE, then the else
are called statements in computer's language.
statement is executed.
Example– >>>Print (17 – 15)
2 Syntax: if (condition)
Since the command was given to the system to print {
the result of expression 17-15. Other examples; statement
>>>Print ("Welcome to the world of Python") }
4.3 Control Statement: else
In programming language, the statements or {
structures used to control the flow of execution of the statement
program are called control statements (structures). }
Control statements define the direction or flow according
to which the execution of a program should be.
Statement that execute one after the other, are common
flow-of-control statements in a program. There are
following two types of control statements–
1. Conditional Statements
2. Loop Statements
4.4 Conditional Statement:
In conditional statement, the program decides
whether to execute the next statement based on the result
value of the current statement. There are following types
of conditional statement–
4.4(i) If Statement:
It is a control statement which is used to test a
particular condition. In this, the condition is executed Figure- if-else flow chart
only once when the condition is true.
Syntax: if (Condition) Example–email = "abc@gmail.com"
{Statements Password = "123456"
} em = input ("enter email..........")
pa = input ("enter your password........")
if email = = em and password = = pa:
print ("log in.")
else: Print ("wrong email id..")
#Output:1.
enter email..........abc@gmail.com
enter your password.........123456
log in.
#Output:2.
enter email.......cba@gmail.com
enter your password.......123456
Figure- if flow chart
wrong email id.......

48
Search on TG: @apna_pdf
4.4(iii) If-elif-else Statement: else:
In this statement, if the condition of the If block is # If Condition 1 is False, then these false lines
True, then the statement of the if block will be printed, if executed
the condition of the If block is False, then the elif block Example–num = float (input ("Enter a number :")
will be checked. If elif is True, the statement in the elif if num > = 0:
block will be printed. If both if and elif are False then if num = = 0:
else block statement will be printed. Print ("Zero")
else:
Print ("Positive number")
Syntax: if Condition:
else:
Statement (s)
Print ("Negative number")
elif Condition:
Statement (s) 4.5 Nested If Statement (Iteration):
else: Any code that repeatedly executes until a particular
Statement (s) condition is TRUE, called iteration.
In Python programming, a code can be executed
multiple times through a loop. The statements which you
want to get executed through loop, They are written in
loop blocks. It is just like a function block.
Conditions are used to start and end a loop.
Normally the loop continues to execute as long as a
condition is TRUE and the loop terminates when that
condition becomes FALSE.
What is loop?– Through loop, we can execute any
one statement or many statements more than once till the
condition is not achieved. Following are the types of
loop statement–
(a) While loop– It is an entry-controlled loop. In
this, the statement continues to execute until a condition
becomes TRUE. It checks the condition first and then
executes the statement.
Syntax: While (condition)
{
Figure- if-elif-else Flow chart statement 1 ;
Example– a = int (input ("enter the Number:.........")) statement 2 ;
if 0 < = a < 100: ---------
Print ("Java") }
elif 100 < = a <150 (b) do-while loop–That is an exit-controlled loop.
This loop executes the first statement and then checks the
Print ("Python")
condition. This loop ensures that the program is executed
else: Print ("C++") at least once.
Output:1. Enter any Number:........111 Syntax: do
Python {
Output:2. Enter any Number:.........30 statement 1 ;
Java statement 2 ;
Output:3. Enter any Number:........210 --------------
C++ }
4.4(iv) Nested If Statement: while (condition) ;
When a variable is to be processed more than once (c) For loop– It is an entry-controlled loop. In this
the statement is executed until the condition becomes
i.e. if statement condition is to be true then a condition TRUE. This loop consists of three components
has to be checked again then it is called nested condition. initialization statement, boolean statement and
Syntax– if <Condition 1>: increment/decrement statement.
# Executes if condition 1 is true Syntax: for (initial condition, test condition ;
if <condition 2>: incrementor or decrementor)
# Executes if condition 2 is true {
else: statement 1 ;
# If condition 2 is False, then these false lines statement 2 ;
executed }

49
Search on TG: @apna_pdf
1. We print the hello world 10 times so that the
program will become lengthy.
2. Another way is, we can print the hello world
using loop which will make the program very simple.
i=1
While i < = 10:
Print ("hello world")
i=i+1
Step 1: First of all a variable i = 1 is initialized so
that it will be easy to understand how while loop works.
Step 2: Then we write the condition (while i < = 10)
with while keyword. If we wanted to execute the loop 10
Figure- Flow diagram of loop statement times, we would write (while i < 10:).
Step 3: Then we will write the statement which is to
Control Flow- By default, the statements in a script be printed.
are executed in order from first to last. But the sequence Step 4: Then the value of i will be incremented so
that value will keep changing until the condition i < = 10
flow can be replaced by conditional execution. Where a is False, and loop will continue to run and hello world
block of one or more statements will be executed if a will be printed.
certain expression is true or by repeated execution a 4.5(ii) For Statement:
block of one or more statements will be repeated as long In Python, for loop is used only to iterate a
as a certain expression is true. sequence. For example, sequences of lists, tuples,
dictionaries, and sets, etc., can be iterated through this
4.5(i) While Statement: loop. The for loop is different in Python from other
This is the simplest loop. It is defined very easily. programming languages. For loop acts like an iterator in
python.
While Condition
for < variable Name > in
Statments to be executed here... <sequence Name>
While Loop is defined by the While keyword. This Statements here....
is followed by the condition based on which the loop is For loop is defined by for keyword. After this the
executed. While loop runs until the defined condition variable is defined by which the members of the
becomes FALSE. sequence will be iterated. After this 'in' operator is
num = 0 defined and after that name of the sequence becomes
while num < 5 which you want to iterate.
Print ("Hello World") My List = ["Red", "Green", "Blue"]
for x in my List:
num = num + 1
{
In the above example num is a loop control variable. Print (x)
As long as the value of num is less than 5, the loop will }
continue to execute and Hello World will be printed. The In the above example my List is iterated by for loop.
loop will terminate as soon as the value of num is 5 or
more.

Figure- for statement


Example–fruits = ["apple", "banana", "cherry"]
for x in fruits:
Figure- Flow control of while statement Print (x)
Output: apple
Example– If we have to print "hello world" 10 times, banana
then there can be two ways. cherry
50
Search on TG: @apna_pdf
4.5(iii) do-while loop Statement: for <variable Name> in
It is an exit-controlled loop. This loop executes the <sequence Name>
first statement and then checks the condition. This loop Statements here....
ensures that the program is executed at least once. The for loop is defined by the 'for' keyword. After
Syntax-do this variable is defined by which the members of the
Syntax– do sequence will be iterated. After this 'in' operator is
{ defined and after that, name of the sequence becomes
statement 1 ; which you want to iterate.
statement 2 ; My List = ["Red", "Green", "Blue"]
-------------- for x in my List:
} {
while (condition) Print (x)
}
In the above example, My List is iterated through for
loop.
While Loop– This is the simplest loop. It is defined
very easily.
While Condition
Statments to be executed here...
While Loop is defined by the While keyword. This
is followed by the condition based on which the loop is
executed. While loop runs until the defined condition
becomes FALSE.
num = 0
while num < 5
Figure- do-while loop statement Print ("Hello World")
num = num + 1
Example– x = 0: In the above example num is a loop control variable.
do { As long as the value of num is less than 5, the loop will
x =1: continue to execute and Hello World will be printed. The
} while (x < 0): loop will terminate as soon as the value of num is 5 or
return x: more.
• Program to Calculate Simple Interest. Entry-Controlled Loop and Exit Controlled
# Program to Calculate Simple Interest. Loop– Difference between Entry Controlled Loop and
Exit Controlled Loop are the following–
P = int (input ("Enter any Principal amount:")
R = int (input ("Enter rate of Interest") Entry-Controlled Loop Exit-Controlled Loop
t = int (input ("Enter time:")) Test condition is checked Loop body is executed
Si = (P*R*T)/100 first and then loop body first then test condition
Print ("Simple Interest = ", Si) is executed. is checked.
RUN If the test condition is Even if the test
>>> false, then loop body is condition is false, the
Enter any Principal amount: 2000 not executed. loop body will be
Enter rate of Interest: 12 executed once.
Enter time : 5 For loop and while loop Do while loop is
Simple Interest = 1200 are examples of entry Example of exit control
>>> control loop. loop.
The difference between For Loop and While The entry control loop is Exit control loops are
Loop– used. When checking of used when checking of
For loop– In Python the for loop is used only to test condition is test conditions is
iterate a sequence such as sequence of list, tuples, mandatory before necessary after the
dictionary and set etc can be iterated by this loop. The
executing the while loop execution of the loop
for loop is different from other programming languages
body. body.
in Python. The for loop acts as an iterator in Python.
51
Search on TG: @apna_pdf
4.6 Range ( ) Function: 4.8 Jump Statement:
Python range( ) function creates a list of numbers, Statements that transfer program control from one
which is typically used for repetition with ends. The place to another within the program without any
most use of range( ) function is when we use for loop. condition are called jump statements. There are three
The range( ) function always returns a list. This is why types of jump statements in Python, which are as
we can use the range( ) function with a for loop. If it follows–
returns a dictionary, it can never be used with a for loop. (i) Break statement; The break statement is used to
Syntax: range (start index, end index, increment value) terminate a loop or statement. After that the control will
Start index: From there we have to start the number. pass to the statements that are present after the break
End index: Where we have to stop the number. statement. If break statements are available in nested
Increment Value: How much gap to keep between start loops, it terminates only those loops that contain break
index and end index. statements. Break is generally used in situations where
Note: we need to break the loop for a given condition.
(i) By default it will display the end point value as 1.
(ii) By default, the gap between start index and end
index in range ( ) is 1.

Example– for i in range (1, 5):


Print (i)
Output: 1
2
3
4

Example– for i in range (1, 9, 2):


Print (i)
Output: 1
3
5 Figure-break statement
7
Example– str = "Python"
4.7 Nested Loop: for i in str:
Nested loop means using another loop inside a loop. if i = = '0' :
We can use any type of loop inside any type of loop. We break
can use for loop inside while loop, while loop inside for Print (i) :
loop, for loop inside for loop, while loop inside while Output: p
loop; When creating nested loops, the inner loop must be
y
terminate before the termination of the outer loop.
t
Example– Program to print a pattern of numbers;
h
12345
12345
(ii) Continue Statement; In Python, Continue
12345 statement is used to bring the program control to the
#Print the pattern beginning of the loop. It skips the remaining lines of
for a in range (1, 4): code inside the loop and starts over with the next
for b in range (1, 6): iteration. It is mainly used for a particular condition
print (b, end = ") inside the loop so that we can skip some specific code for
print (" ") a particular condition.

52
Search on TG: @apna_pdf

Figure- Pass Statement

Figure- Continue Statement


Exmaple– for i in [1, 2, 3, 4, 5] :
Example– i = 1; # initializing a local variable
if i = = 3 :
# starting a loop from 1 to 10 Pass
for i in range (1, 11) : Print "Pass when value is", i
if i = = 5 : Print i
continue ; Output: >>>
12 Pass when value is 3
Print (" % d" % i) ;
345
Output : 1
>>>
2
4.9 Assert Statement:
3 Assert statement checks whether the given logical
4 expression is True, or False. The program executes only
5 if the expression is True otherwise an Assertion error is
6 raised.
Assertion– The Assert keyword is used as a
7
debugging tool in Python. It helps in smooth flow of
8 code. Assertions are the assumptions made by the
9 programmer and put them in the code in such a way that
10 if any error is found in the then that code does not
execute further. This work is done by writing Assert
keyword in Python programming. This statement takes a
(iii) Pass Statement; In Python pass keyword is
boolean input. It does nothing when the condition is
used for doing nothing i.e. when we do not want to
TRUE but displays an Assertion Error with an optional
execute code, Pass can be used to execute empty. This message when the condition is FALSE.
creates a control only to pass without executing. It is a
NULL operation because nothing happens when it is Example– a = 10
executed. b=0
It is used in those cases where statement needs to be Print ('a is dividing by zero')
designed syntactically but we don't want to use any assert b! = 0
executable statement. Pass is also used for empty control Print (a/b)
statement, function and classes. Output: Assertion Error

53
Search on TG: @apna_pdf
Practice Questions with Explanatory Solutions
1. A null statement in Python programming is– Ans.(b) In the given Python code, both t1 and t2 are
(a) Break (b) Continue tuples and they are assigned the same value. The <
(c) Pass (d) None of these (less than) operator has been used to compare tuple t1
Ans.(c) Pass is a null statement in Python and t2. In this, if the first operand is less than the
programming because nothing happens when it is second operand, then the condition is True. Otherwise
executed. It simply creates a control to pass without returns False since tuple t1 and t2 have the same value,
executing any code. It can be used by pass any code. value of t1 < t2 will be False.
2. Consider the following Python code: 5. Operator can be–
a = True (a) Unary (b) Binary
b = False (c) Ternary (d) All of the above
c = False Ans. (d) Operator is a symbol that represents an
if a or b and c: operation and the values on which the operator
Print "TRUE" operates are called operands. Operators are used to
else: perform mathematical or logical operations in a
program. Operator can be unary, binary and ternary.
Print "FALSE"
Unary operator operates on only one operand,
The output of this code is. binary operator on two operands and ternary operator
(a) False (b) True on three operands.
(c) Both (a) and (b) (d) None of these
6. Operator precedence determines that which
Ans. (b) Given Python code: operator–
a = True (a) works on the largest number.
b = False (b) is used first.
c = False (c) is most important.
if a or b and c: (d) none of these
Print "TRUE" Ans. (b) When more than one operator is used in an
else: expression, all the operators are given priority by
Print "FALSE" operator precedence. On the basis of operator
Considering the above code, we see that the code precedence, it is decided that while evaluating the
prints "TRUE" as the output since the if statement is expression, which operator to be used first.
true. 7. What is the proper operator for Power (X, Y )?
3. What will be the value of the expression 2**3**2? (a) X ^ Y (b) X**Y
(a) 312 (b) 412 (c) X^^Y (d) none of these
(c) 450 (d) 512 Ans. (b) The proper operator for Power (X,Y) would
Ans. (d) Calculating the expression 2**3**2, be ** (exponential). In this, the right hand operand
2**3**2 becomes the power of the left hand operand. Like-
= 32 **2 = 9**2 Power (X, Y) = x * *Y
= 29 = 512 8. What is the order of precedence in Python?
The final value of the expression 2-512 will be 512. (i) Parenthesis, (ii) Exponential,
4. Find the output of the following python (iii) Multiplication, (iv) Division
program– (v) Addition, (vi) Subtraction
X = ['ab' , 'cd'] (a) (i), (ii), (iii), (iv), (v), (vi)
for i in X : (b) (ii), (i), (iii), (iv), (v), (vi)
i·upper ( ) (c) (ii), (i), (iv), (iii), (v), (vi)
Print (x) (d) (i), (ii), (ii), (iv), (vi) (v)
(a) ab (b) cd
(c) ['ab', 'cd'] (d) ['cd' 'ab'] Ans. (a) Like any other programming language, the
mathematical expressions that are executed in Python,
Ans.(c) The output of the above python program will
be the given list ['ab', 'ed']. also have a fixed Execution Flow or Precedence of
X, This is a list of strings. List is not stored in any different types of operators. That decides which
variable after using Upper ( ), so the value of print(x) operator will work first and which operator after the
will remain ['ab', 'ed']. order of precedence in Python is as follows–
4. What will be the output of the following python Parenthesis, Exponential, Multiplication, Division,
code? Addition, Subtraction.
>>> t1 = (1, 2, 4, 3) 9. You can go to the beginning of the loop using–
>>> t2 = (1, 2, 3, 4) (a) Break (b) Pass
>>> t1 < t2 (c) Continue (d) none of these

54
Search on TG: @apna_pdf
Ans.(c) Python uses loops to automatically and repeat Ans.(a) Like most programming languages, in Python
tasks in an efficient way, but sometimes Situations also one loop can be defined inside another loop. The
may arise where you want to exit completely, these second loop defined inside the loop is called Nested
can be done by loop control statements. Python
supports three types of control statements– Break, Loop. For example, another while loop defined inside
Continue, and Pass. the while loop, is called nested loop.
The Continue statement in Python is used to bring 16. Which integer int(x) means that the variable is
program control to the beginning of a loop. converted to?
10. On evaluating, Expression i = 40*20+30; what (a) X (b) XX
would be the value of i ?
(a) 800 (b) 0 (c) (x) (d) none of these
(c) 830 (d) none of these Ans. (a) Variables can store values of different data
Ans.(c) The expression, i = 40 * 20 + 30 is calculated types. Python is a dynamic type language so it does
according to operator precedence– not need to define the types of variables while
i = 40 * 20 + 30 declaring them. int(X) means that the variable X is
i = 800 + 30 converted to an integer. int is used to store integer
i = 830
numbers like 9, 15 etc.
11. Which of the following operator gives absolutely
accurate result (including fraction part)? 17. Which function is used to verify the type of an
(a) // (b) % object?
(c) / (d) none of these (a) Type ( ) (b) Split ( )
Ans. (a) The // (Floor Division) operator gives the (c) Loop ( ) (d) None of these
most accurate result after dividing the first operand by Ans.(a) Type () function is used to verify the type of
the second operand.
variable used in Python programs which returns the
12. Which of the following is true about Python
operators? type of variable passed to the program.
(a) Operators must have one or more operations. 18. The unit of code executed by the Python
(b) The operators are either unary or binary. interpreter is called–
(c) Operators have some precedence. (a) nested (b) elif
(d) All of the above.
(c) pass (d) statement
Ans. (d) Operator can be defined as a symbol which
performs a particular operation between two operands. Ans. (d) The unit of code to be executed by the
Operators must have one or more operations. Python interpreter is called a statement. The code in a
Operators must be unary, binary or ternary and Python program can be of many types.
operators have some precedence.
19. Which statement is optional like else in Python?
13. On which bits does bitwise work?
(a) Operators bit (b) Browser bit (a) nested (b) elif
(c) Network (d) None of these (c) pass (d) none of these
Ans.(a) Bitwise Python operators operate on bits and Ans. (b) Like else in Python, the elif statement is
perform bit-by-bit operations. In bitwise operators, optional. There are three types of control statements in
there are bitwise AND (&), bitwise OR ( | ) bitwise Python if, if-else and if-elif-else.
NOT (-), bitwise XOR (^), Bitwise right shift (>>)
Bitwise left shift (<<) operators. These control statements do not execute their
14. How many types of control statements are there own statements until the given expression is TRUE. In
in Python, in if else and if elif-else? the if statement, when the expression is TRUE then it
(a) 1 (b) 2 executes its statement and if the expression is FALSE
(c) 3 (d) 4 then the flow goes to elif. If the expression of elif is
Ans.(c) In Python, elif statement like else is optional. TRUE then its statement is executed and the
There are three types of control statements in Python, expression of elif is FALSE then the else statement is
if, if-else and if-elif-else. These control statements do executed.
not execute their own statements until the given
expression is TRUE. In if statement when expression 20. What will the following code print?
is TRUE then it executes its statement and if if 2 + 5 == 8:
expression is FALSE then flow goes to elif – if print("TRUE")
expression of elif is TRUE then its statement is else:
executed and if expression of elif is FALSE then else
statement is executed. print("FALSE")
15. What is called, the second loop inside the loop? print("TRUE")
(a) Nested Loop (b) For Loop (a) TRUE (b) TRUE FALSE
(c) While Loop (d) None of these (c) TRUE TRUE (d) FALSE TRUE

55
Search on TG: @apna_pdf
Ans. (d): if Space 2+5== 8: 25. What does the following code print?
print("TRUE") x = 'mohan'
else: for i in range (len (x)):
print("FALSE") x[i].upper()
print("TRUE") print(x)
In the given value which is 2 + 5 = 8. The values (a) mohan
of both the sides have been compared, in which 7 = = (b) MOHAN
8 are wrong. So the condition will be false, and the (c) Error
second statement will be executed. With this last (d) None of these
statement will also be executed. Ans. (a): x= 'mohan'
Will get FALSE TRUE' in the output.
for i in range(len(x))
21. What will be the output of the following?
print((range (4))) x[i].upper()
(a) 0, 1,2,3 (b) [0, 1,2,3] print(x)
(c) range (0, 4) (d) (0, 1,2,3) 'mohan' will get only as the output.
Ans. (c): The 'range( )' function returns a range of 26. What will be the output after the following
numbers, starting from 0 by default, and increasing by statements?
1 (by default), and stops before a specified number of
times. for i in range (1, 6):
Example– print((range(4))) print(i, end=")
Output– range(0. 4) will be obtained. if i = 3:
break
22. What will be the output of the following (a) 12
expression? (b) 123
a=2 (c) 1234
b=8 (d) 12345
print(a|b)
print(a >> 1) Ans. (b): for i in range(1,6):
(a) 10 0 (b) 10 2 print(i, end=")
(c) 2 2 (d) 10 1 if i = 3:
Ans. (a) : a=2 break
b=8 Output–1 2 3
print(a|b) The given python code is written in a 'for' loop so,
print(a >> 1)
This will print the values from 1 to 6 respectively. But
Output– 10, 1
Bitwise/operator (1)– It returns 1 if any bit is 1 and 0 the loop will break on value 3. So only the value 1 2 3
a = 210 (binary) will be printed.
b = 81000 (binary) 27. What value does the following expression
a|b 1010 (binary) which would be the value of 10. evaluate to?
Bitwise Right Shift (>>)– It shifts the bits of the print(5 +8*((3*5 ) - 9)/10)
number to the right and fills the result with 0 left side. (a) 9.0 (b) 9.8
So, print(a>>1) (c) 10 (d) 10.0
will print output 1. Ans. (b): The expression in Python will be evaluated
23. What is the output of the following? in the following way–
print(int( )) (5 + 8 * ((3*5)–9)/10)
(a) Any random number
(5 + 8 * ((15–9)/10)
(b) 1
(5 + 8 * 6/10)
(c) 0
(d) Error (5 + 8 * 0.6)
Ans. (c) print (int( )) (5 + 4.8)
0 will be printed in output. Hence option (c) is true. 9.8
24. What is the output of the following code? So the output will be 9.8.
a = set('dcma') 28. Operations to be repeated a certain number of
b = set('mlpc') times are done by______.
print (a^b) (a) Selection (b) Sequential
(a) ('d', 'c', 'm', 'a', 'm', '1', 'p', 'c' (c) Simple (d) Loop
(b) {'m', 'l', 'p', 'c''} Ans. (d) : A fixed number of repeated operations are
(c) ('d', 'c', 'm', 'a')
performed by a loop. There are two primitive loop
(d) None
commands in Python–
Ans. (d) : The output of the given python code will be
{'d', '1' a', 'p'} which is not available in the option. 1. While loop
Hence option no. (d) is correct. 2. For loop

56
Search on TG: @apna_pdf
29. What will be the output of the following Python 33. What will the following code segment print?
code? a = True
def printMax(a, b):
b = False
if a > b:
print(a, 'is maximum') c = False
elif a == b: if not a or b:
print(a, 'is equal to', b) print(1)
else: elif not a or b and c:
print(b, 'is maximum') print(2)
print Max(3, 4) elif not a or b or not b and a:
(a) 3 (b) 4
(c) 4 is maximum (d) None of the mentioned print(3)
Ans. (c) : def printMax(a, b): else:
if a > b: print(4)
print(a, 'is maximum') (a) 1 (b) 3
elif a = = b: (c) 2 (d) 4
print(a, 'is equal to', b) Ans. (b) The Vlif keyword in Python is written as "if
else:
the previous condition is not true, try this condition."
print(b, 'is maximum')
print Max(3, 4) So the third statement in the given python code
In the output only the third statement will be executed will execute as it will return 'True'. Get 3 as output
as it will be true according to the condition. Hence 4 is will happen.
maximum' will be obtained as output. 34. What will be the output after the following
30. What value does the following expression statements?
evaluate to?
x=2
x=5
while x < 10: if x < 5:
print(x, end=' ') print(x)
(a) Closed loop (b) One time loop else:
(c) Infinite loop (d) Evergreen loop pass
Ans. (c) : The given python code will generate infinite (a) 2 3 4 (b) 1 2 3 4
loop, because no statement is given to increase or (c) 2 (d) None of these
decrease the value.
Ans. (0) x = 2
31. What will be the output of the following
expression? if x < 5:
X=4 print(x)
print(x<<2) else:
(a) 4 (b) 16
(c) 6 (d) 2 pass
Ans. (b): << left shift operator (zero fill left shift) Will get 2 as the output because the value of x is given
shifts left by pushing zero from the right side and as 2 which is less than 5 so the first statement will be
dropping the leftmost bits. So the given python code true and the value of x is value 2' will be printed.
will print 16. 35. ........... terminates the current loop iteration
X=4 immediately.
print(x<<2) (a) break (b) pass
output– 16
(c) continue (d) None of these
Binary of 4– 00000100 Ans. (a) By 'break' statement we can stop the loop
Shifting 2 bits left is 00010000 (which is 16 in binary) even if the condition is true–
32. What will be the output of the following Example–
expression? i=1
print (7//2)
print (-7//2) while i < 6 :
(a) 3-3 (b) 4-4 print (i)
(c) 3-4 (d) 33 if (i = = 3)
Ans.(c) : The floor division operator rounds the result break;
down to the nearest whole number. so get 3, 4 as
output will happen. Output– 1
Example– print(7//2)#3 2
print(–7//2)#–4 3

57
Search on TG: @apna_pdf

5 SEQUENCE DATA TYPE

5.0 Introduction: 5.1(i) To Create String:


The sequence data type is used in Python language Strings can be created by enclosing characters
to store data in containers. The containers for storing within single quotes or double quotes. Triple quotes can
data are list, tuple and string. Lists are mutable that can also be used in Python but it is usually used to represent
store any type of data while Strings are immutable that multiline strings and doc strings. We just needs to
can store only str type data. Tuples are immutable data specify the string, to a variable to store a string inside the
types that can store any type of value. variable.
Example: # defining strings in python
# all of the following are equivalent
my–string = 'Hello'
print (my–string)
my–string = "Hello"
print (my–string)
my–string = '"Hello"'
print (my–string)
# triple quotes string can extend
# multiple lines.
my–string = " " " Hello, welcome to the world
of python " " "
Print (my–string)
5.1 String: Output: Hello
A string is a set of characters that can be letters, Hello
numbers, or special symbols. Strings are written inside Hello
Single (' ') or double (" ") in python. String handles Hello, Welcome to the world of Python
textual data. Forward indexing of a Python string starts Docstrings–Docstring or documentation string
with 0, 1, 2, 3.... while backward indexing starts with –1, provides a convenient way to associate documentation
–2, –3. ......... with Python modules, functions, classes and methods. It
Example: Str1 = "Hello World" is specified in the source code, which is used as a
Str2 = 'Hello Python' comment in a specific segment of code to document.
Print (Str1) Unlike traditional source code, a docstring describes
Print (Str2) what a function does, not how it works.
Output: Hello World All functions must have a docstring, this allows the
program to inspect these comments at run time, for
Hello Python example as an interactive help system or as metadata.
A docstring line must begin with a capital letter and
In most programming languages, the string is printed end with a period. Docstrings are declared using triple or
at the index; similarly in Python, the string is printed by double quotes immediately below the class or function
index. The first character of the string starts with index declaration. All functions must have a docstring.
'0' and the last character of the string starts with index '– 5.2 Logical and Physical Line:
1'. A Python program is divided into several logical
lines and each logical line is terminated by a new line
token (\n). A logical line is created from one or more
physical lines. A line containing only space, tab,
formfeed and a comment is considered as blank line.
Python interpreter ignores it.
When you write a program, a physical line is
displayed. A logical line is what Python interprets as a
Example: Str = "Hello World" single statement. Each physical line corresponds to a
Print ("First letter in string:", str [0]) logical line. An example of a logical line is a statement
Print ("Last letter in string:", str [–1] like print ("Hello Python") if it is on a line by itself (as it
Print ("Second last letter in string:", str [–2]) appears in editor) then it also follows a physical line. If
Output: First letter in string : H you have a long line of code, you can break it into
multiple physical lines using a backslash (\). In a string
Last letter in string : d backslash makes the string continue to the next line
Second last letter in string: l without a line. This is called clear line joining.

58
Search on TG: @apna_pdf
Example: Str1 = 'This is a string.\ On running the above program, we will get the
This continues the string.' following output–
Print (Str) str [0] = "M"
Output: Type Error : 'str' object does not support item
This is a string. This continues the string. assignment.
The above text is considered continuous even after We can further verify this by checking the memory
written it in two lines. location addresses of the positions of the letters of the
5.3 Working with Strings: string.
An array of characters is called a string. Strings are x = 'banana'
always represented by single commas (' ') or double for id x in range (0, 5):
commas (" ") and triple commas (" " " " " "). The Print x [id x]; = " = " , id (x [id x])
easiest way to identify a string is that If any word or You can assign a string to another string or to an
characters have above comma, then it is called a string. expression that returns a string using assignment.
Example: 'Aone Computer' Example: >>>strl = 'youth'
"Aone Computer" 5.3(ii) String Traverse:
" " "Aone Computer" " " Traversing a string means accessing all the elements
'10', "10", " " "10" " ", '@#$' of the string one by one using subscripts. A string is
traversed in a for loop or during a loop.
By considering at the above example, you can Example: A = 'Python'
understand that if any word or number is written inside i=0
the comma then it is a string. while i < len (A):
String is not only used to store textual information Print A [i]
but also to store the contents of a textual or binary file i=i+1
like Collection of Bytes. That is, a sequence of characters Output:
in Python can be called a string, which can contain P
alphanumeric and symbolic characters as well as binary
y
characters. String's index starts at 0 and the last index is
–1. t
str = "Hello World" h
print (str [0]) o
print (str [-1]) n
>>> H In the above program each character of python will
be accessed one by one. In each iteration of the for loop,
d
the next character in the string is assigned to the variable.
Colons (:) are used in square brackets ([ ]) to create The loop continues to run as long as there are characters
a sub-string from a string in Python. If only the starting left.
index is given, the entire string is displayed from the Example: Finding the length of an inputted string.
starting index. #program to find the length of entered string
str [start_Index:end_Index(optional default (-1 )]
str = input ('Enter any string : ')
If only the adding index is given the string from 0 print ('Length of the string is', len (str))
index to end index is displayed. print ('Done')
str [start_Index(optional default '0'):end_Index] ) Output:
Source Code: Enter any string : YouthCompetitionTimes
str = "Hello World" Length of the string is 21
print (str [3:]) Done
Enter any string : Hello
print (str [:8])
Length of the string is 5
print (Str [3:8]) Enter any string : quit
>>> lo world Done
Hello wo In the above program, it takes input from the user
lo wo repeatedly and prints the length of each input string. The
5.3(i) Strings are immutable: length of the input string can be found using the built-in
len ( ) function.
The string data type is immutable, in Python which Example: character in a string with a special symbol
means that a string value cannot be updated. We can # python program to replace character in
verify by trying to update a part of the string that gives # string with a special symbol
us an error. input-string = input ("Enter a string : ")
# Can not reassign str = input ("Enter a character you want to change in
str = "YouthcompetitionTimes" the entered string : ")
Print type (str) symbol = input ("Enter the symbol you want to
str [0] = "M" replace with:")
59
Search on TG: @apna_pdf
changed-str = input-string. replace (str, symbol) f = 'competition', l =" times')
print ("Modified string is : "changed-str) print ("\n string in order of keywords:")
Output: print (str 1)
Enter a string : Youth Competition Times # Formatting of Integers
Enter a character you want to change in the str 1 = "{0 : b}".format (12)
entered string : t print ("\n Binary representation of 12 is")
Enter the symbol you want to replace with : # print (str 1)
Modified string is : you #hCompe#i#ions#imes # Formatting of floats
5.3(iii) Strings Formatting: str 1 = "{0 : e}". format (154.6347)
Python string format ( ) is a function which is used print("\n Exponent representation of 154.6347 is")
to convert or replace a string with place holders print (str 1)
containing valid values in the final string. This is an in- # Rounding of Integers.
built function of the Python string class which returns a str 1 = "{0 : 2f}".format (1/4)
formatted string as output. print ("\n one-fourth is: ")
Place holders are defined in curly brackets inside the print (str1)
string. The Python string format ( ) method scans # string alignment
original string for place holders. Placeholders can be
blank curly brackets ({}), positional elements, ie str 1 = "|{:<10}1{:^10}{:>10}|".format
placeholders with index 0, 1 in the string. Like– (0) (1) ('youth', 'competition' : 'times')
etc. The variable name for the keyword argument is print ("\n Left : center and right alignment with
provided inside curly brackets. Like– (name}, {age}. Formatting : ")
For keyword items, when you use a variable inside print (str 1)
your placeholder, you can have a sequence of values
inside the format as you required. Output:
The order does not matter here as the values will be String is default order:
converted based on provided variable name in format. youth competition Times
string in positional order:
Example: num 1 = int (input ("Enter first number:")) competition youth times
num 2 = int (input ("Enter second number:")) string in order of keywords:
sum = num 1 + num 2 times competition youth
Print ('The sum of', num1, 'and', num2, 'is', sum) Binary representaion of 12 is
Output: 1100
Enter first number : 50 Exponent representation of 154.6347 is
Enter second number : 25 1.546347e + 02
The sum of 50 and 25 is 75 One-fourth is:
Example: num 1 = int (input ("Enter first number:")) 0.25
num 2 = int (input ("Enter second number:")) Left, center and right alignment with
product = num 1 * num 2 Formatting:
mul = print (mul.formate (num1, num2, |Youth Competition Times|
product))
Output:
5.4 Special String Operators:
Enter first number : 11 In Python, string operators represent a variety of
operations that can be performed on variables of string
Enter second number : 13 type in a program. Python allows several string operators
The product of 11 and 13 is 143 that can be applied to Python strings, such as–
The assignment operator (=), the concatenation
Example: Program for formatting of strings operator (+), the string repetition operator (*), and the
string slicing operator [ ], String comparison operators (=
# program for formating of strings
=) (!), membership operators (in and not in), escape
# Default order
sequence operators (\) string format operators (% and {})
str 1 = "{} {} {}".format ('youth', 'competition',
'Times') 5.4(i) Concatenation Operators:
print ("string in default order:") In Python, + is known as the concatenation operator.
print (str 1) Using this, two strings can be concatenated or added.
# positional formatting
str 1 = "{1} {0} {2}".format ('youth', 'competition', Example– srt 1 = "hello"
'times') str 2 = "world"
print ("\n string is positional order:") Final_String = str 1 + str 2
print (str 1) Print (Final_String)
# keyword formatting Output:
str1 = "{l} {f} {g}".format (g = 'youth', helloworld

60
Search on TG: @apna_pdf
To add white space between two words, put a space 5.5 String Slices:
before the end of the first string inside the quotes. In the Python programming language, a small part of
Example–'hello' + 'world' a string is called a slice. The process of printing a portion
>>> hello world of a string using the slice operator is called slicing. Slice
The interpreter returns the string with single quotes operator is represented by [: : :]. Python provides us
whether you enter the string with single quotes or double another method called slicing, through which we can also
quotes. The + operator must have both operands of the access any particular range of the string. The syntax of
same type. It cannot take one operand as a number and python slice is as follows–
other as a string. The + operator can work with different Syntax– strobj [begin: end: step]
numbers and strings for concatenation and addition but The process of printing a portion of a string using a
you cannot concatenate numbers and strings with an range value is called slicing.
operator as operands. This will generate an error. Begin: The begin value specifies at which index of
5.4(ii) Application Operators: the string, creation of the slice will begin.
During programming, if you want to set a task to End: It specifies at which index of the string,
automate, then Python is required for this replicate * creation of slice will stop.
(multiply) returns the multiple of two numbers and Step: It is also called increment value. It is needed,
returns the string that is repeated the number of times. When we want to print slices except some index inside
>>> 10 * 5 Begin and End value.
50 Example– >>> a = "Python"
>>> "Hello!" * 3 >>> Print (a[0:5])
'Hello! Hello! Hello!' 'Pytho'
>>>Print(a[0:5:2])
5.4(iii) Membership Operators (in): 'Ph'
Membership operator is used to test membership in a
Following are some rules of slicing–
sequence. Sequence can be a list a string or a tuple.
(i) If we do not specify the end index value, then
For string and bytes types, x is True in y. and only if
our PVM (Python Virtual Machine) defaults it to print
x is a substring of y. That is, it returns True if the
the slice till the last character of the string.
sequence with the specified value is available in the
object. Example– >>> a = "Python"
Example:1. x = ["badal", "web dev"] >>> Print (a [2:])
Print ("web dev" in x) 'thon'
Output:
(ii) If we do not specify a Begin index value, our
True
PVM prints the slice from the beginning of the string.
Example– >>> a = "Python"
Example:2. >>> str = "Green Parrot"
>>> Print (a[:5])
'green' in str
'Pytho'
False # because g of Green is in small case.
(iii) If both begin and end index are not specified,
5.4(iv) Membership Operators (not in): PVM prints the entire string.
Membership operator is not true if membership is Example–>>> a = "Python"
not available in the given string. >>>Print (a[:])
Example: >>> x = ["badal", "web dev"] 'Python'
>>> Print ("design" not in x) (iv) If the end index value is greater than its
True maximum value, PVM prints only up to the last position
character.
Example: >>> str = "Red Tomato" Example– >>> a = "Python"
>>> 'R' not in str >>> Print (a[1:100])
False 'ython'
5.4(v) Comparison Operators: (v) If the value of step value is positive, then the
Basically, comparison operators compare two begin index must always be less than end index.
operands and return a boolean value, True or False. All otherwise error is displayed.
comparison operators (<, < =, >, > =, ! =, = =) are also Example– >>> a = "Python"
applied to strings. Using these operators follows the >>> Print (a[1:6:2])
standard character-by-character comparison rules for 'yo'
ASCII and Unicode. (vi) If the value of step value is given negative, then
At a basic level, computer stores all information in always the value of begin index has to be kept smaller
the form of numbers. To represent the character data, a than end index. Negative step value prints the slice in
translator is used, which maps each character to its backward direction.
representative number. Example– >>> a = "Python"
Normal strings are stored internally as 8-bit ASCII >>> Print (a[–2 : –7 : –1])
while Unicode strings are stored as 16-bit Unicode in 'nothy'
Python. Example: # python program to demonstrate.
61
Search on TG: @apna_pdf
# string slicing >>> London_Coordinates = (51.50722,–0.1275)
string = 'ASTRING' >>> len (London_Coordinates)
# Using slice constructor 2
S1 = slice (3) You can use len ( ) function in the same way when
finding the string greeting, listing office days, and the
S2 = slice (1, 5, 2) length of the tuple london_coordinates is a valid element
S3 = slice (-1, –12, -2) for all three data types. The len( ) function always returns
print ("string slicing") an integer because it is counting the number of items in
print (string [S1]) that object to whom you pass it. The function returns if
print (string [S2]) the argument is a blank sequence.
print (string [S3]) >>> len (" ")
Output: String slicing 0
AST >>> len ( [ ] )
0
SR
>>> len ( ( ) )
GITA 0
In the above examples, you get an empty string
Example: # python program to demonstrate. length, an empty list, and an empty tuple.
# string slicing 5.6(ii) Capitalize ( ):
string = "YouthCompetitionTimes' The capitalize ( ) function returns a copy of the
# prints string in reverse string. in which only the first character is capital and the
print (string [: : –1]) rest is lower case.
Output: semitnoititepmochtuoy Syntax– String Capitalize ( )
Example: txt = "hello, and welcome to my world."
5.6 String Functions and Methods: x = txt.Capitalize ( )
Python provides built-in functions and methods. It Print (x)
allows us to manipulate strings. Every String object Output: Hello and welcome to my world.
created in Python is actually an instance of the String 5.6(iii) Find ( ):
class. The Find ( ) function is used to find the position of a
String manipulation is performed using the <string given substring within a string. It returns –1 if the
object> <method name> syntax. substring search fails.
5.6(i) Len ( ): Syntax– String.find (value, start, end)
This function returns the number of items in an value– The value to be searched.
object. When object is a string then len ( ) function start– Optional, where to start the search, defaults to 0.
returns the number of characters in string. end– Optional, where to end the search. Defaults to the
Syntax– len (object) end of the string.
>>> x = 'Hello' Example: txt = "Hello, welcome to my world."
>>> len (x) x = txt.find ("e")
print (x)
5
Sequence is a container that holds the ordered items Example: txt = "Hello, welcome to my world."
Lists, Tuples and Strings. This supports Unicode x = txt.find ("e", 5, 10)
extensively including Unicode characters within strings. Print (x)
Python provides a set of built-in functions that allow >>> 8
switching back and forward between characters and their 5.6(iv) isalnum ( ):
corresponding ASCII and Unicode values. The isalnum ( ) function returns True if all
The ord ( ) function returns the "ordinal" code of a characters are alphanumeric, meaning alphabetic letters
single character string. Char ( ) returns a single character (a–z) and numbers (0–9). It returns False if the string
string, Describing a given ordinal code. contains any special characters (Space #% & ? etc.)
>>> ord ("z") # ord ( ) function will Syntax- String.isalnum ( )
return numeric values Example: txt = "company 12"
90 x = txt.isalnum ( )
>>> char (90) # chr ( ) returns an integer Print (x)
to a character Output: False
"Z" (Because it contains space which is a special character.)
There are inbuilt sequences. You can find the length >>> str 1 = "Hello"
of a sequence by calling the len( ) function. >>> str 1⋅isalnum( )
>>> greeting = "Good Day!" True
>>> len (greeting) >>> txt 2 = "Python3"
9 >>> txt2 ⋅ isalnum( )
True
>>> office_days=["Tuesday", "Thursday", "Friday"] >>> txt 3 = "856324"
>>> len (office_days) >>> txt 3⋅isalnum( )
31 True
62
Search on TG: @apna_pdf
5.6(v) isalpha ( ): isupper ( )– This returns the boolean value (True or
The isalpha ( ) function returns True if the character False) by checking whether the given string or character
or string is alphabetic, and returns False if it is not. in the isupper function is in uppercase or not. The syntax
Syntax: Str.isalpha ( ) for isupper function is as follows–
Example: str1 = "Hello 123" Syntax– str·upper ( )
str1. isalpha ( )
Example–Source code :
Output: False
>>> str2 = "Hello" Print ("Hello"·isupper ( ))
>>> str2⋅isalpha ( ) Print ("HELLO 123"·isupper ( ))
True Print ("123 HELLO"·isupper ( ))
>>> str3 = "python3" Output: False
>>> str3⋅isalpha ( ) True
False True
5.6(vi) isdigit ( ): 5.6(ix) lstrip & rstrip ( ):
This function returns True if the character or string lstrip ( )– This function returns a copy of the string by
is a digit, otherwise it returns False.
Syntax: Str.isdigit ( )) stripping the given character from the left side (leading
Example: >>> str1 = "1234" character).
>>> str1⋅isdigit ( ) Syntax– str-rstrip (char)
True Char : It is an optional Parameter.
>>> str2 = "1234 Hello" The characters to be stripped in the string are
str2⋅isdigit ( ) given here.
False Source code:
str = "Hello World"
5.6(vii) lower & islower ( ): Print (" Hello World"·lstrip ( ))
lower ( )– In the function, the uppercase character or
string is converted to lowercase. The syntax of lower ( ) Output : Hello World
function is–
Syntax– str⋅lower ( ) rstrip ( )– rstrip ( ) function returns a copy of the
There is no parameter for the lower ( ) function. string by stripping the given character from the right side
Example: Source code : (trailing characters).
Print ("Hello World"·lower ( )) Syntax– str-rstrip (char)
char: It is an optional parameter. The characters to be
Print ("HELLO WORLD"⋅lower ( ))
stripped in the string are given here.
Output: The syntax of is space ( ) function is as follows–
hello world Syntax– Strrisspace ( ) the is space function does not
hello world have a parameter.
islower ( )– It returns a boolean value (True or Example–Source code:
False) by checking whether the given string or character str = "Hello World"
in the islower ( ) function is in lower case. The syntax for
islower ( ) is as follows– Print ("Hello World ")
Syntax: str⋅islower ( ) Print ("Hello World"⋅rstrip( ))
islower ( ) function does not require parameters. Print (str·rstrip ("ld"))
Example: Source code : Output: Hello World
Print ("Hello"·islower ( )) Hello World
Print ("hello"·islower ( )) Hello Wor
Output: False 5.6(x) isspace, istitle, replace, join,
True swapcase & start ( ) function:
5.6(viii) Upper & isupper ( ): isspace ( )– The isspace ( ) function checks whether
Upper ( )– This function converts a lowercase the given string or character is just a space or not and
character or string to uppercase. Syntax of Upper ( ) is as returns a Boolean value (True or False).
follows– The syntax of isspace ( ) function is as follows–
Syntax– str·isupper ( ) syntax– str⋅isspace ( )
There is no parameter for the Upper ( ) function. The isspace function does not have a parameter.
Example– Source code: Example– Source code:
Print ("Hello World"⋅Upper ( )) Print ("Hello World"·isspace ( ))
Print ("Hello World"⋅Upper ( )) Print ("\t"·isspace ( ))
Print ("hello 123"⋅Upper ( )) Print (" " ·isspace ( ))
Output: HELLO WORLD Output: False
HELLO WORLD True
HELLO 123 True

63
Search on TG: @apna_pdf
istitle ( )– This returns a boolean value (True or Program to find the largest word in a string
False) by checking whether the given string is a title entered by the user–
string in the istitle ( ) function. The syntax of istitle ( ) is #Program to find the largest word in the string
as follows– entered by user.
Syntax– str⋅istitle ( )
s = input ("Enter string:")
The stitle ( ) function does not have a parameter.
s = s·split ( )
Example– Source code:
lar = s·[0]
Print ("Hello World"·istitle ( ))
Print ("Hello world"·istitle ( )) max_len = len (s [0])
Output: True for i in s:
False
if len (i) > max _ len :
replace ( )– The replace ( ) function returns a copy max_len = len (i)
of the string by replacing all occurrences of the given
substring with the new substring. The syntax of replace lar = i
( ) function is Print (lar)
Syntax-str-replace (oldsubstr, newsubstr, max)
RUN
Join ( )– In the join ( ) function, the sequence of
given elements is joined with an operator and the string >>>
is returned. Enter string : youth competition Times
Syntax– str⋅join ( )
The join ( ) function does not require parameters. Competition
Example– Source code: >>>
sep = "$" 5.7 List Manipulation:
str = "Hello" List is an important data type of Python. Many
Print (sep·join (str)) values are kept in it. Each value is separated by a comma
Output: H $ e $ l $ l $ o (,) and all values are enclosed in square brackets [ ].
In Python programming, not only data items of other
Swapcase ( )– The Swapcase ( ) method returns a data types can be nested as list items but also data items
string that converts all uppercase characters of the string of the list data structure itself. A list that is an element of
to lowercase and all lowercase characters to uppercase. another list is called a nested list. Various types of data
Syntax for swapcase ( ), function is as follows– items like string, integer, float, dictionary, tuple, list etc.
Syntax– str⋅swapcase ( ) can be stored in a list object by creating it.
The swapcase ( ) function takes no parameters and Example– >>> list = ['Amit 25, 22.53, "GOA"]
returns a swapcased string as the return value. >>Print (list)
Example– Source code: Output: ['Amit', 25, 22·53, 'GOA']
Print ("Hello World" Swapcase ( )) Indexing of a list is similar to indexing of a string.
Print ("hello 123"-Swapcase ( ) The indexing of the list also starts from 0, it is easy to
Output: hELLO wORLD update the values of the list. You can add the new value
HELLO 123 to the list or replace old value with its new value.
5.6(xi) Partition( ): Following are the main features of Python list–
This function returns the tuple for the given string • Python list is mutable. This means, we can add values
by placing the separator between the first occurrence and to the list or replace an old value with a new value.
the tuple. The syntax of Partition ( ) is as follows– • Duplicate values can be entered.
Syntax: str⋅partition (sep) • Any element of the list can be accessed by index.
Here the parameter sep becomes a separator. With • Different type of data types can be stored in the same
its help, three parts of the string are returned in a tuple. list.
Return Value: The returned tuple contains the three • The list is dynamic, as users can increase or decrease
the size of the list as per their requirement.
elements of the string returned.
• Elements in a list are placed with square brackets [ ]
Example– Source code: and comma (,) separators.
string = "Programming is good" • Forward indexing starts from zero while backward
Print (string·partition ('computer')) indexing starts from-1 in a list.
#computer is not found 5.7(i) Creating List:
Print (string·partition ('Pro')) Lists are like arrays in Python. List is mutable, its
#Pro is found items can be changed as required. A single list holds data
Output : types such as- int, string and object. List is useful way to
('Programming is good', " , ") implement stacks and queues. Elements of a Python list
(' ' , 'Pro', 'gramming is good') called items.
64
Search on TG: @apna_pdf
We write the items of the list inside square brackets languages. Mutable lists do not need to be homogeneous
([ ]) and separate each item with a comma (,). always. Python has a fixed number of mutable lists and
syntax– <list name> = [item 1, item 2, item3, item n] they are also ordered. Apart from this, the index of the
Example– # blank list list elements is according to a certain sequence. The
list = [ ] index of a list is the first index from 0.
# string list >>> num = [10, 20, 30]
list 1 = ["hello", "python", "india"] >>> num [1] = 40
# integer list >>> print (num)
list 2 = [15, 24, 38, 54] [10, 40, 30]
# float list The second element of the list which was 20, is
changed to 40. This can be thought of as the relation
list3 = [5.5, 4.8, 9.8, 4.4, 5.7]; between the indices and elements of a list. This is called
# Mixed Data Type List mapping. 'Maps one of each indices' elements.
list 4 = [1, 28, "Python", 45.5]; Mutable List Functions– The different functions of
# Nested list mutable list are as follows–
list 5 = [21, [15, 2], 4.5] append ( )– Adds an element to the end of the list.
extend ( )– Appends all the elements of a list to another
Single or double quotes can be used with comma (,) list.
separator for string values but numeric values are insert ( )– Inserts an item at the defined index.
separated by commas only. remove ( )– Removes an item from a list.
A list within a list is called a nested list. A nested list pop ( )– To remove an element as well as return it at the
within a list is also counted as an element. A list that given index.
does not contain any item is called an empty list. Empty clear ( )– removes all items from the list.
or blank lists can be made with empty brackets. You can index ( )– Returns the index of the first matched item.
also create a long list that contains many elements by count ( )– Returns a count of the number of items passed
breaking it into multiple lines. as an argument.
sort ( )– Sorts the items of the list in ascending order.
Odd numbers = [1, 3, 5, 7, 9, 11, 13, 15, 17, 19, 21, 23,
reverse ( )– reverses the order of items in a Python list.
25, 27, 29, 31, 33, 35, 37] copy ( )– returns a copy of the list.
You can also create a list of single characters or sum ( )– adds the numbers in a list.
digits by inputting from the keyboard. ord ( )– Returns an integer representing the code point of
Example– list 1 = list (input ('Enter elements of list :')) a specified Unicode character.
Enter elements of list : 1357 emp ( )– This function returns 1 if the first list is greater
>>> list 1 than the second list.
['1', '3', '5', '7'] max ( )– returns the maximum element of a specified list.
Example–creating a list with more than one specific or min ( )– Returns the minimum element of a specified list.
duplicate elements. all ( )– Returns True if all elements are True or if the list
# Creating a list with the use of Numbers is empty.
len ( )– Returns the length or size of the list.
# (Having duplicate Values) any ( )– Returns True if any element of the list is True.
List = [1, 2, 4, 4, 3, 3, 3, 6, 5] But returns False if the list is empty.
Print ("\n List with the use of Numbers:") filter ( )– Tests each list element to see if it is true.
Print (List) enumerate ( )– returns the enumerated object of the list.
# Creating a list with mixed type of values Mutable List Example–
# (Having Number and strings) >>> List = [1, 2, 3, 4, 5, 6, 7]
List = [1, 2, 'youth', 4, 'competition', 6, 'Times'] >>> Print (List)
Print ("\n List with the use of mixed values:") [1, 2, 3, 4, 5, 6, 7]
Print (List) >>> List [2] = 20
>>> Print (List)
Output: [1, 2, 20, 4, 5, 6, 7]
List with the use of Numbers: >>> a = [1, 2, "Hello", 3.6]
[1, 2, 4, 4, 3, 3, 3, 6⋅5] >>> Print (a)
List with the use of mixed values: [1, 2, "Hello", 3.6]
[1, 2, 'youth', 4, 'competition', 6, 'Times'] >>> print a[2] = "World"
>>>Print (a)
5.7(ii) Mutable List: [1, 2, 'World', 3.6]
A list refers to a data structure in Python, which is
an ordered sequence of elements that can be swapped. 5.8 Accessing List:
Python mutable lists can contain various data types such The index number inside the index operator [ ] is
as objects, integers, and strings. Lists can also be used to access the list items. The index number should
changed after they are created due to their mutable always be an integer and nested index is used to access
nature. the nesting list. The syntax to access the list item is as
The properties of mutable lists are similar in Python follows–
to those of dynamically sized arrays declared in other Syntax– list [index]
65
Search on TG: @apna_pdf
Example– Source code Example– Negative Indexing
list = [27, 52.36, "Rakesh", "M26@"] >>> List = [20, 40, 60, 80, 100]
Print (list [0]) >>> Print (List)
Print (list [1]) [20, 40, 60, 80, 100]
Print (list [2]) >>> List [–1]
Print (list [3]) 100
Output: >>> List [–2]
27 80
52.36 >>> List [–3]
Rakesh 60
M26@ >>> List [–4]
5.8(i) Indexing: 40
In the Python programming language, whenever any >>> List [–5]
string data is stored in a variable, each character of the 20
string has a certain value. 5.8(ii) Slicing:
There is an index so, by using that index we can A part of a list is a sub-list of that list. Just as
access that character. The process of accessing a specific indexing is used to access individual elements, similarly
character in string data using a numeric index or key slicing is used to print a particular range of elements in a
value, it is called Indexing. The syntax of indexing is as Python list. The slice operation is followed by a colon
follows– (:). List slicing is an operation that selects a particular
Syntax– String-object [numeric index] element from a list. This Creates a second list by
Index is of two types– removing the elements. The syntax for list slicing is as
(i) Positive index– Positive index is in forward follows–
direction starting from 0, which becomes till the last of Syntax– Seq = L [start: stop: step]
the string. Like– >>> x = [1,2,3,4]
>>> x [0: 2]
[1.2]
When we use the slicing feature, the beginning of
the range is considered from the index number 0 only,
but the number specified to indicate the end of the range,
the index number is one less than the number of that
specified range.
Example–>>> a = "Python"
In the Python programming language, a small part of
>>> Print (a[4]) a string is called a slice. The process of printing a portion
'o' of a string using the slice operator is called slicing. Slice
(ii) Negative Indexing– This index is in backward operator is represented by [: : :]. Python provides us
direction and becomes till the beginning of the string. another method called slicing, through which we can also
access any particular range of the string. The syntax of
python slice is as follows–
Syntax–strobj [begin : end : step]
The process of printing a portion of a string using a
range value is called slicing.
Begin: The begin value specifies at which index of
Example–>>> a = "Python" the string the creation of the slice will begin.
>>>Print (a[–4]) End: It specifies at which index of the string,
'T' creation of slice will stop.
Example– Positive Index Step: It is also called increment value. It is needed,
#Positive indexing when we want to print the slices except some index
>>> List = [20, 40, 60, 80, 100] inside Begin and End value.
Like– >>> a = "Python M
>>> Print (List)
>> > Print (a[ 0:5])
[20, 40, 60, 80, 100] 'Pytho' >>>Print(a[0:5:2])
>>> List [0] 'Ph'
20 Following are some rules of slicing–
>>> List [1] (i) If we do not specify the end index value, then our
40 PVM (Python Virtual Machine) defaults it to print the
>>> List [2] slice till the last character of the string.
60 Like– >>> a= "Python"
>>> List [3] >>> print (a [2])
80 'thon'
>>> List [4] (ii) If we do not specify a Begin index value, our
100 PVM prints the slice from the beginning of the string.
66
Search on TG: @apna_pdf
Like– >>> a = "Python" Print ("\n Sliced Lists : ")
>>> Print (a[:5]) # Display Sliced list
'Pytho' Print [List [: : –1])
# Display Sliced list
(iii) If both begin and end indexes are not specified, Print (List [: : –3])
PVM prints the entire string. # Display Sliced list
like– >>> a = "Python" Print (List [: 1 : –2])
>>>Print (a[:]) Output: Original list :
'Python'
['Youth', 11, 'Times!']
(iv) If the given end index value is more than its
maximum value then PVM prints only till the last Sliced lists :
position character. ['Times!', 11, 'Youth']
like– >>> a = "Python" ['Times!']
>>> Print (a[1: 100]) ['Times!']
'ython'
Example– List slicing can also be used to modify lists or
(v) If the value of step value is given positive, then remove elements from a list.
always the value of begin index has to be given less than # Initialize list
end index. Otherwise we get error is displayed. List = [1, 2, 3, 4, 5, 6, 7, 8, 9]
Like– >>> a= "Python" # Show original list
>>> Print (a[1:6:2]) Print ("\n original list : \n", List)
'yo' Print ("\n sliced List : ")
# Creating new list
(vi) If the value of step value is given negative, then new List = List [: 3] + List [7 :]
always the value of begin index has to be smaller than # Display sliced list
end index. A negative step value prints the slice in the Print (new List)
backward direction. # List = List [: : 2] + List [1 : : 2]
Like– >>> a = "Python" # Display Sliced list
>>> Print (a[-2:-7:-1]) Print (List)
'nothy' Output: Original list :
[1, 2, 3, 4, 5, 6, 7, 8, 9]
Negative index means traversal till the end of the Sliced List:
list. Accessing segments is called slicing. [1, 2, 3, 8, 9]
Example– # Initialize list [1, 3, 5, 7, 9, 2, 4, 6, 8]
List [50, 70, 30, 20, 90, 10, 50] 5.8(iii) Traversing:
# Display list Lists are basically equivalent to arrays in other
Print (List [1:5]) languages but have the advantage of being dynamic in
Output: [70, 30, 20, 90] size. In Python, lists are a type of container in data
structures. Sequential access to each element of a list is
Example– list slicing in python called traversing. This can be done by using for or while
# Initialize list loop statement.
List = [1, 2, 3, 4, 5, 6, 7, 8, 9] 'in' operator uses each element of a list for loop.
# Show original list Example– # Python code to iterate over a list
Print ("\n Original List:\n", List) list=[2, 4, 6, 8, 10]
Print ("\n Sliced List:") # using for loop
# Display Sliced list for i in list:
Print (List [3:9:2]) print (i)
# Display Sliced list Output: 2
Print (List [: : 2]) 6
# Display Sliced list 8
Print (List [: :]) 10
Output: [70, 30, 20, 90] for / in can also be used to operate on a string. A
string acts like a list of its characters, prints all characters
Original list: in the string.
[1, 2, 3, 4, 5, 6, 7, 8, 9] Example– str = "Welcome"
Sliced Lists: for ch in str.
[4, 6, 8] Print (ch)
[1, 3, 5, 7, 9]
[1, 2, 3, 4, 5, 6, 7, 8, 9] >>> W
e
Example– # Initialize list l
List = ['youth', 11, 'Times!'] c
# Show original list o
print ("\n Original List : \n", List) m
67
Search on TG: @apna_pdf
e 4
>>> for ch in ['p', 'y', 't', 'h', 'o', 'n']: 5
Print (ch) 6
>>> P 7
y 8
t 9
h 10
o >>>
n This can be converted to a list using list ( ).
>>>
In this, each letter is accessed and displayed until all Like– Print (list (range (1.5)))
the elements are traversed and displayed. An element to Print (list (range (10)))
check whether a list is displayed or not, Print (list (range (0)))
flower = ['Rose', 'Lotus', 'Sunflower', 'lily', Print (list (range (2, 12, 2)))
'Marigold', 'Daisy'] >>> [1,2,3,4]
if 'Rose' in flower : [0,1,2,3,4,5,6,7,8,9]
Print ("yes") []
>>> [2,4,6,8,10]
Yes >>>
Other examples to understand traversing are as Example– while loop, and traversing a list using len ( )
follows– function.
for fast food in ['Pizza', 'Burger', 'Maggi', 'Spring # List traversing
Roll', 'Momos']: fruits = ["apple", "Banana", Cherry", "Orange"]
Print ("I like", fast food) i=0
>>> while i < len (fruit):
I like Pizza Print (fruit [i])
I like Burger i=i+1
I like Maggi Output: apple
I like Sping roll banana
I like momos cherry
>>> orange
e-commerce = ['Amazon', 'Flipcart', 'Myntra',
'Ajio', 'Snapdeal'] Example– Traversing a list using for loop.
for x in e-commerce: # traversing list using for loop
print ("Welcome to" , x) numbers = [1,2,3,4,5,6,7,8,9,10]
>>> for i in numbers:
Welcome to Amazon Print (i, end = " ")
Welcome to Flipcart >>>
Welcome to Myntra 1,2,3,4,5,6,7,8,9,10
Welcome to Ajio Example– Traversing a list using while loop.
Welcome to Snapdeal # List traversing using while loop
>>> numbers = [2,4,6,8,10,12,14,16,18,20]
for fruit in ['apple', 'banana', 'mango'] i=0
Print ("I like", fruit) while i < 10:
>>> I like Apple print (numbers [i], end = " ")
I like banana i=i+1
I like Mango >>>
Using range ( ) function– This returns a sequence 2,4,6,8,10,12,14,16,18,20
of numbers between two given integers. for loop and the Example– Printing the odd number.
combination of the range ( ) function allows you to # Traversing list and printing odd
create a traditional numeric for loop.
numbers = [0,1,2,3,4,5,6,7,8,9,10,11,12]
# print the numbers from 0 through 10 i=1
for i in range (11): while i < len (numbers):
print (i) print (numbers [i], end = " ")
>>> i=i+2
0 >>>
1 1,3,5,7,9,11
2 Example– Print the elements of the list with their indices
3 # Program to print elements of list along
68
Search on TG: @apna_pdf
# with their indices 5.9(iii) Slicing List:
ch = ['p', 'y', 't', 'h', 'o', 'n'] Slicing is a flexible tool for creating a new list from
length = len (ch) a list. Python supports slide notation for any sequential
for i in range (length): data type, such as lists, strings, tuples, bytes, arrays, and
print ("At positive index", i, "and negative ranges. The slice operator also works on lists. If you omit
index", (i-length), "element is:", ch [i])
the first index, the slice starts at the beginning. If you
>>>
omit the second index, the slice moves to the end. If both
At positive index 0 and negative index –6 element
is : P are omitted, slice returns a copy of the entire list.
At positive index 1 and negative index –5 element Example– # Initialize list
is : y List = [1,2,3,4,5,6,7,8,9]
At positive index 2 and negative index –4 element # show original list
is : t Print ("\n original list : \n", List)
At positive index 3 and negative index –3 element Print ("\n sliced lists : ")
is : h # Display sliced list
At positive index 4 and negative index –2 element Print (List [3 : 9 : 2])
is : o
Print (List [ : : 2])
At positive index 5 and negative index –1 element
is : n Print (List [ : :])
Example– Programming to sum the elements of a list. Output: Original list :
# To find sum of the elements in a list [1,2,3,4,5,6,7,8,9]
a = [40, 20, 25, 15] Sliced Lists :
s=0 [4,6,8]
i=0 [1,3,5,7,9]
while (i < len (a)) : [1,2,3,4,5,6,7,8,9]
s = s + a [i]
i=i+1 5.9(iv) Comparing List:
Print ("SUM : " , s) You can also compare the contents of two or more
RUN lists. Using Comparing Operators to Compare Lists.
>>> Example– <<< [2, 6] = = [2, 6]
SUM : 100 True
>>> >>> [2, 6] = = [2, 5]
5.9 List Operations: False
Lists are used to store different types of data in >>> [2, 6] > [2, 5]
sequence in Python. There are many operations that
apply to lists. Some of the major operations are as True
follows– >>> [2, 6] < [2, 5]
5.9(i) Joining List: False
Adding another list on a list is called joining. Plus 5.10 Object and Value:
operator applied on two lists, which creates a new list. Python objects are created just like variables. From
Like– >>> a = [2, 4, 6] that variable we use to call the function. Similarly, store
>>> b = [3, 9, 12] that class on the variable as a function.
>>> c = a + b
If you execute these assignment statements–
>>> print (c)
x = 'Hello'
[2, 4, 6, 3, 9, 12]
y = 'Hello'
When '+' operator is used with list, both the If you know that both x and y refer to a string but do
operands must be of list type, else this error will be not know that they refer to the same string then there are
displayed. two types of possibilities–
Like– >>> li = [2, 4, 6] (i) First, x and y refer to two different objects that
>>> li + 10 have the same value.
Type Error : Can only concatenate list (ii) Second, operator is used to find out that they
5.9(ii) Repeating List: refer to the same object.
Multiplying by an integer n creates a new list that repeats >>> x = 'Hello'
the original list n times. *Operators to the list of given >>> y = 'Hello'
numbers repeats. >>> x is y
Like– >>> [1] * 5
True
[1,1,1,1,1]
But creating two lists gives two objects–
>>> [2,4,6] * 3 >>> x = [2,4,6]
[2,4,6,2,4,6,2,4,6] >>> y = [2.4,6]
The above example [1] repeats 5 times. The second >>> x is y
example [2,4,6] iterates the list 3 times. False
69
Search on TG: @apna_pdf
5.10(i) Aliasing: x = fruits.count ("banana")
When the value of one variable is assigned to print (x)
another variable i.e. a condition where two or more >>> 1
variables refer to the same object, it is called aliasing. If Example 3– python.list count example
a refers to an object and assigned to a and b then both # define tuple
variables refer to the same object. vowels = ('a', 'e', 'i', 'o', 'i', 'o', 'e', 'i', 'u')
>>> x = [2, 4, 6] # count element 'i'
>>> y = x x = vowels.count ('i')
>>> y is x print (x)
True >>> 3
The association of a variable with an object is called
a reference. In the above example there are two Example 4– #python 3 program to count the number
references to the same object. # of Times
Having more than one name in an object with more # an object appears in the list using count ( )
than one reference is called an object alias. Since other method
objects are mutable, changes made to one object affect
other. list = ['Cat', 'Bat', 'Sat', 'Cat', 'Mat', 'Cat', 'Sat']
>>> y[2] = 11 # To get the numbers of occurrences
>>> print (x) # of each item in a list
[2, 4, 11] print ([[l, list.count (l)] for l in set (list)])
# To get the number of occurrences
# of each item in a dictionary
5.11 List Function and Methods: print (dict(l, list.count (1)) for l in set (list)))
The manipulation can be using the list function >>> [['Mat', 1], ['cat', 3], ['sat', 2], 'Bat', 1]]
available in Python. All methods are function in python
whereas all functions are not method. There is an {'Bat' : 1, 'Cat' : 3, 'Sat' : 2, 'Mat' : 1}
important difference between Python's functions and 5.11(iii) append ( ):
methods. Functions take objects as input, while methods Objects can be added to a list using the built-in
operate on objects on the contrary. Every List object that function append ( ). Using append ( ) method only one
you create in Python is actually an instance of the List element can be added at a time but loop is used to add
class. Its syntax is as follows– multiple elements using append ( ) method only. A tuple
<list object>⋅<method name> ( ) can also be added to a list using the append ( ) method
5.11(i) len ( ): and a list can also be added to another list.
The len ( ) function is used to find the length of a # Python program to demonstrate addition of element
list. This is an in-built function that returns the length of # in a list
an object. The len() function takes only one parameter. In # Creating a list
that parameter you can use string, tuple, dictionary, List = [ ]
character list, byte set. Print (" Initial blank list : ")
Example–<<< list 1= [ ] Print (List)
>>> len (list 1) # Addition of Elements in the List
0 List·append (1)
>>> list 2 = [1,2,3] List·append (2)
>>> len (list 2) List·append (4)
3 Print ("\n List after Addition of Three Elements : ")
Example with nested list– Print (List)
>>> list = [2, 3] # Adding Elements to the list using Iterator.
>>> list1= ['Red', 'Green', list, 'blue'] for i in range (1, 4) :
>>> len (list 1) List·append (i)
4 Print ("\n List after Adding of elements from 1–3 : ")
5.11(ii) count ( ): Print (List)
By using count function, we can count any value, # Adding Tuples to the list
word, character, list, dictionary and tuple etc. List 2 = ['For', 'Python']
Example 1– # define string List · append (List 2)
string = "masterprogramming" Print ("\n List after addition of a List: ")
count = string.count ( ) Print (List)
# print count Output :
print ("The string count is :", count) Initial blank List:
Output: The string count is 1 []
List after Addition of Three elements:
Example 2– # python.list count example [1, 2, 4]
fruits = ['apple', 'banana', 'mango'] List after Addition of elements from 1–3:
70
Search on TG: @apna_pdf
[1, 2, 4, 1, 2, 3] # use methods
List after Addition of a Tuple: list – 1.append (a)
[1, 2, 4, 1, 2, 3, (5, 6)] list – 2.insert (3, a)
List after Addition of a List: list– 3.extend (a)
[1, 2, 4, 1, 2, 3, (5, 6), ['For', 'Python']] # display lists
5.11(iv) extend ( ): print (list – 1)
Elements can also be added using the extend ( ) print (list – 2)
method. Extend ( ) method adds multiple elements to the print (list – 3)
end of the list at a time. The append ( ) and extend ( ) >>> [1, 2, 3, [2, 3]]
methods can only add elements to the end of a list. [1, 2, 3, [2, 3]]
# Python Program to demonstrate adding of elements [1, 2, 3, 2, 3]
# in a list 5.11(vi) pop ( ):
# creating a List This method is used to remove and return an
List = [1, 2, 3, 4] element from the given set. It is used to remove the given
Print ("Initial List : ") index and print the remaining list. The syntax of POP ( )
Print (List) is as follows–
# Addition of multiple elements to the list at the end Syntax– list·POP (index)
# (using extend method) Removes the item of the index given in this method.
List·extend[8, 'Python', 'Programming'] If the index passed in POP( ) method is not in range, it
Print ("\n List after performing extend operation :") displays error. The parameter passed to POP ( ) is
optional. If no parameter is passed, the default index-1 is
Print (List)
passed as an argument which returns the last item.
Output :
Example– Source code :
Initial List :
list = [10, 20, 30]
[1, 2, 3, 4]
Print = (list)
List after performing extend operation:
list·POP (2)
[1, 2, 3, 4, 8, 'Python', 'Programming']
Print (list)
5.11(v) insert ( ): Output :
The append ( ) method only works to add elements [10, 20, 30]
to the end of the list. The insert ( ) method is used to add [10, 20]
an element at the desired position. append ( ) method
takes only one item but the insert ( ) method takes two 5.11(vii) remove ( ):
arguments (position, value). This method is used to remove an item from the list.
This method searches the given element in the list. and
# Python program to demonstrate addition of elements removes the first matching element. If the item exists
multiple times, removes only the first occurrence of the
# in a List
item. This method removes only one element at a time,
# Creating a List an iterator is used to remove a series of elements. It
List = [1, 2, 3, 4] displays an error if the element is not available in the set.
Print ("Initial List : ") remove ( ) method does not return any value. remove ( )
Print (List) of the syntax is as follows–
# Addition of Element at Specific Position (using insert Syntax– list.remove (item)
# method) Here the item is given as a parameter to be removed.
List·insert (3, 12) Example– Source code:
List·insert (0, 'Python') list = ["P", "Y", "T", "H", "O", "N"]
Print ("\n List after performing Insert operation : ") list·remove ("O")
Print (List) Print list
Output: list·remove ("Y")
Initial List: Print (list)
[1, 2, 3, 4] Output : ['P', 'Y', 'T', 'H', 'N']
List after performing Insert operation: ['P', 'T', 'H', 'N']
['Python', 1, 2, 3, 12, 4]
Example 2– Append ( ), insert () and extend ( ) Methods 5.11(viii) del ( ):
program The del keyword is used to delete objects.
# python program to demonstrate Everything is an object in python so del keyword can
# comparison between the three method also be used to delete variable, list or parts of list etc. To
# assign lists delete a single element from python list, use its index and
list-1 = [1, 2, 3] delete slice the slicing operator is used for.
list-2 = [1, 2, 3] Example– Class My Class :
list-3 = [1, 2, 3] name = "John"
a = [2, 3] del My Class
71
Search on TG: @apna_pdf
Print (My Class) else :
>>> Print ("The string is not a Palindrome")
Traceback (most recent call last): RUN
File "demo–ref–keyword–del⋅py", line 6 >>>
in <modulegt; Enter string : Python
print (My Class)
The string is not a palindrome
NameError : name 'My Class' is not defined
>>>
Example– X = "hello" Enter string : Madam
del X The string is a Palindrome
print (X) >>>
Output : NameError : name 'X' is not defined 5.11(x) sort ( ):
In Python, the sort ( ) function is used to sort a list.
Example– X = ["apple", "banana", "cherry"] The sort function is used to sort the list in ascending,
del X [0] descending or user-defined sequence.
print (X) Example– sorting a number list in ascending order.
>>> ['banana', 'cherry']
# program to sorting numbers in ascending order
Example– Delete variable, list and dictionary numbers = [1,3,4,2]
my-var = 5 # sorting list of integer in ascending order
my-tuple = ('sam', 25) numbers⋅sort ( )
my-dict = {'name' : 'sam', 'age' : 25} print (numbers)
del my-var >>> [1,2,3,4]
del my-tuple Example– Sorting a number list in descending order.
del my-dict # program to sort List in descending order
# Error : my-var is not defined # creating list
print (my-var) strs = ["Rohan", "is", "going", "to", market"]
# Error : my-tuple is not defined # sorting list
print (my-tuple) strs⋅sort (reverse = True)
# Error : my-dict is not defined print (strs)
print (my-dict) >>> ["to", "market", "is", "going", "Rohan"]
5.11(ix) reverse ( ): Example– Sorting a list using user defined order.
Python list reverse ( ), is an inbuilt method in the # sorts the array in ascending order.
Python programming language that reverses the objects # program to return the second element of
of a list. It doesn't use any extra space but it just modifies # the two element passed as the parameter
the original list.
def sortsecond (val):
syntax–list–name⋅reverse ( )
No parameter is used in this. reverse ( ) method does return val
not return any value but the given object from list to # list 1 to display the use of second key
reverse. list 1= [(1,2), (3,3), (1,1)]
Example– To reverse a list by using reverse ( ) unction. # to second element
# program to demonstrate the use of reverse ( ) list 1⋅sort (key = sortsecond)
# a list of numbers print (list 1)
list 1 = [1,2,3,4,1,2,6] # sorts the array in descending order
list 1⋅reverse ( ) # according to second element
print (list l) list 1⋅sort (key = sortsecond, reverse = True)
# a list of characters print (list 1)
list 2 = ['a', 'b', 'c', 'd', 'a', 'a'] >>> [(1,1), (1,2), (3,3)]
list 2⋅reverse ( ) [(3,3), (1,2), (1,1)]
print (list 2)
Example– Sorting a list by the length of the values.
Output : [6,2,1,4,3,2,1] # A function that returns the length of
['a', 'a', 'd', 'c', 'b', 'a'] # the value:
def my Func (e):
Example– #Program to check the word is palindrome or return len (e)
not. cars = ['Ford', 'BMW', Mitsubishi', 'VW']
string = input ("Enter string : ") cars.sort (key = my Func)
if (string == string [: : –1] : print (cars)
Print ("The string is a Palindrome") >>> ['VW', 'BMW', 'Ford', 'Mitsubishi']

72
Search on TG: @apna_pdf
5.11(xi) clear ( ): # list which contain both string and numbers
This function removes all the data from the list. It is list = [1, 2, 'Mohan', 5, 'Python', 6]
equivalent to del. clear ( ) method does not take any # Driver code:
parameter. It does not give any return value. n = 'Python'
Example– # declaring a list if search (list, n) :
Print ("Found")
my–list = [{1, 2}, ('xyz'), ['3.66', '2.2']]
else:
# clearing the list Print ("Not Found")
my–list⋅clear ( ) Output: Found
print ('The list after using the clear 5.13 Tuple:
function :', my–list) Python has a tuple data-structure. Tuple is a
Output : The list after using the clear sequence of elements and it is immutable. List and tuple
function : [ ] are same in python but items of list can be changed or its
5.11(xii) max ( ) and min ( ): items can be deleted and items of tuple cannot be
The max ( ) function is used to calculate the changed or deleted. Tuples can only be read. Tuple is
maximum value passed as its argument. used to store multiple objects in a single variable. Tuples
syntax : max (a, b, c,...........key⋅default) are written with round brackets ( ). Each item of the tuple
parameters: is separated by a comma (,) and all items are enclosed in
a, b, c, .........: Same data type parentheses ( ). Mixed data types can also be used in
key– Key function where iteration is passed and tuple.
comparison is done by default. Example– # Examples of tuple
Example– # program to display max ( ) tup 1 = ('Physics', 'chemistry', '2020', '1995');
print ("maximum of 4, 12, 43.3, 19 tup 2 = ( 1, 2, 3, 4, 5);
and 100 is : "end = " ") tup 3 = "a", "b", "c", "d";
print (max (4, 12, 43.3, 19, 100)) tup 4 = ( ) ;
>>> maximum of 4,12, 43.3, 19 and 100 is : 100 tup 5 = (50,) ;

min ( ) function is used to count the minimum value 5.13(i) Difference between List and tuple:
passed in its argument. Following are the differences between list and
syntax: min (a,b,c.........key, default) tuple–
Parameters: List Tuple
a, b, c........: same data type
The list is written inside Tuples are written inside
key– The key function where the authorization is a square bracket [ ] parentheses ( ) separated
passed and the default. separated by a comma. by commas.
Example– # program to display min ( ) The element and size of Tuple cannot be updated.
print ("minimum of 4, 12, 43.3, 19 the list can be changed.
and 100 is: ", end = " ") List is slower than tuple Tuple is faster than list.
print ("min (4, 12, 43.3, 19, 100) for repetition.
>>> minimum of 4, 12, 43.3, 19 and 100 is 4 List objects are Tuple Objects are
5.12 Linear Search: mutable. Immutable
The simple way of linear search in a list or tuple is– Contents that keep Tuple is used for a fixed
• Start with the leftmost element of the list and compare changing, means they content which is not be
X to each element one by one. are not fixed List is changed later.
• Returns True if X matches with any element. used for them.
• Returns False if X does not match with any element. List takes up a lot of Tuple takes less memory
memory. as compared to list.
List has many inbuilt Tuple have not an in-built
method. method.
Unexpected changes There is no possibility of
and errors are more change and error in tuple.
likely to happen.
Example–1 Linear search in list List is better for Tuple data type is
# search function with Parameter list and the value to operations like insertion suitable for accessing
# be searched and deletion. elements.
def search (list, n) :
for i in range (len(list)):
5.13(ii) Tuple is Immutable:
if list [i] = = n : Tuple is a data structure, used to store data. Tuples
return True are immutable, that is, once a tuple is created, it cannot
else: be updated or modified. Tuple is used only when we
return False need a data you don't have to change.

73
Search on TG: @apna_pdf
Example– >>> tuple 1 = (1, 2, 33, 44, 6) print (new–tuple [6])
>>> tuple 1 [4] = 10 # index Error : list index out of the range.
Type Error : 'tuple' object does not # nested tuple
support item assignment. n–tuple = ("Cursor", [8,4,6], (1,2,3))
5.14 Creating, Initializing and Accessing of # nested index
Elements in Tuple: print (n–tuple [0] [3]) # '5'
To create a tuple with one element, a comma is used. print (n–tuple [1] [1]) # 4
A tuple is created by enclosing all the elements within
parentheses ( ), separated by commas (;). The
parentheses are optional. A tuple can contain any number Negative Indexing: Python allows negative
of items and they can be of different types (integer, float, indexing for its sequences. With an index of –1 refers to
list string, etc.) the last item, –2 to second last............
5.14(i) Creating Tuple: Example– # Negative indexing for Accessing tuple
A tuple is created by placing all the elements inside elements
parentheses separated by commas. A tuple can contain new–tuple = ('p', 'y', 't', 'h', 'o', 'n')
any number of items. It is not necessary to put a semi- print (new–tuple [–1])
colon (:) at the end of the tuple. # output : 'n'
Example– tuple 1 = (1, 2, 3, 4, 5) print (new–tuple [–6])
# Integer tuple # output : 'p'
# Float tuple
tuple 2 = (1.5, 2.4, 3.8, 4.4, 5.7);
Slicing: You can access a range of items in a tuple
# Mixed data type tuple
by using the slicing operator colon.
tuple 3 = (1, 2, "Hello", 4.5);
# Accessing tuple elements using tuple slicing
# Nested tuples
new-tuple = ('p', '1', 'o', 'g', 'r', 'a', 'm', '', '2)
tuple 4 ( 1, 2, (1, 2), 4.5);
# elements second to fourth
Tuples can also occur without parentheses.
# output: ('r', 'o', 'g')
tuple = "H", "e","T", "T", "o"
print (new–tuple [1:4])
Print (type (tuple))
# elements begining to second
# output: <class 'tuple'>
# output: ('p', 'r')
Tuple can also be created empty ie without any
print (new-tuple [: -7])
element.
# elements eight to end
# zero-element/empty tuple
# output: ('i', 'z' )
tup 4 = ( )
Print (new-tuple [7: ])
>>> len (tup 4)
# elements begining to end
0
# output : ('p', 'r', 'o', 'g', 'r', 'a', 'm', 'i', 'z')
5.14(ii) Tuple Assignment: # print (new tuple [:])
All the elements can be specified using a single 5.14(iv) Membership Test in Tuples:
assignment statement in a tuple. Tuple assignments are
Python has two membership operators to check
parallel rather than sequential. A temporary variable is
membership of a value or to check membership of two
used to swap the values of two variables.
values- in and not in
To swap a and b,
It tests membership in sequence. Such as– strings,
temp = a lists, and tuples.
a=b The membership operators "in" and "not in" check
b = temp whether the given element is contained in the tuple.
5.14(iii) Accessing Elements in Tuple: Example– # python program to illustrate
Tuple items can be accessed by giving the index # finding common member in list
numbers inside the square brackets. There are many # using 'in' operator list 1 = [1, 2, 3, 4, 5]
methods by which we can access the elements of a tuple. list 2 = [6, 7, 8, 9]
Like– for item in list 1:
Tuple Indexing: We can use the index operator [ ] if item in list 2:
to access an item in a tuple, wherever the index starts print ("overlapping")
from 0. So a tuple with 6 elements will have indices from else:
0 to 5. Accessing an index outside the tuple index range print ("not overlapping")
will cause a range of index error. Nested tuple is Example– >>> 4 in ( 2, 4, 6, 8 )
accessed using nested indexing. True
>>> 4 not in (2, 4, 6, 8 )
Example– # Accessing of tuple elements using tuple False
indexing 5.14(v) Identity Operator in Tuples:
new–tuple = ('p', 'e', 'r', 'm', 'i', 't') Identity operators are used to compare objects if
print (new–tuple [0]) # 'p' both objects actually contain the same type of data and
print (new–tuple [5]) # 't' share the same memory space.
74
Search on TG: @apna_pdf
The 'is' operator evaluates to True if both the 5.15(iv) index ( ):
variables of the operator point to the same object, Tuple index ( ) method helps us to find the index or
otherwise it returns False. occurrence of an element in a tuple. Basically, This
Example– >>> python program to illustrate serves two functions.
# of 'is' identity operator Returns the first occurrence of an element in the
x=5 tuple. Raising an exception if the specified element is not
y=5 found in the tuple.
print (x is y) Example 1– Finding the index of an element.
>>> True >>> tup = (22, 3, 45, 4, 2.4, 2, 56, 890, 1)
'is not' operator; Returns True if both variables are
>>> print (tup.index (45))
not the same object.
x = [" Youth", "Competition", "Times"] >>> print (tup.index (890))
y = ["Youth", "Competition", "Times"] # pritn the index of elements 45 and 890
z=x 2
# Returns False because z is the same object as x 7
print (x is not z) Example 2–
# Returns True because x is not the same object as y >>> tup = (22, 3, 45, 4, 2.4, 2, 56, 890, 1)
# even if they have the same content print(x is not y) >>> print (tup.index (3.2))
# difference between "is not" and "! = " : # gives an error because the element is not
print (x ! = y) present in the tuple.
5.15 Tuples Function: Value Error : tuple.index (x) : x not in tuple
Unlike a pyhon list, functions like append ( ), 5.15(v) Sorted ( ):
remove ( ), extend ( ), insert ( ) and pop ( ) can not be This method takes a tuple as input and returns a
used in it due to the mutable nature of tuple. Count ( ), sorted list as output. Other than that it doesn't make any
sort ( ), len ( ), max ( ) and min ( ) etc inbuilt functions changes to the original tuple.
can be used with tuple. These functions help in For example,
performing a variety of tasks. Such as finding the length >>> tup = (22, 3, 45, 4, 2.4, 45, 56, 890, 1)
of a tuple, searching an element in a tuple, etc. >>> sorted (tup)
5.15(i) Tuples ( ): [1, 2.4, 3, 4, 22,45, 45, 56, 890]
To create a tuple, you can use the tuple ( ) function. 5.15(vi) min ( ), max ( ) and sum ( ):
It basically serves two functions.– min ( ) : Returns the smallest element in the tuple as
Creating an empty tuple if we don't pass an item and output.
a tuple with elements if we pass an item. For example,
Example– >>> tup = tuple ((22, 45, 23, 78, 6.89)) >>> tup = (22, 3, 45, 4, 2.4, 2, 56, 890, 1)
>>> tup >>> min (tup)
(22, 45, 23, 78, 6.89) 1
max ( ) : Returns the largest element in the tuple as
>>> tup2 = tuple ( ) output.
>>> tup 2 ( ) For example,
>>> tup = (22, 3, 45, 4, 2.4, 2, 56, 890, 1)
5.15(ii) len ( ): >>> max (tup)
This function returns the number of elements present 890
in the tuple. Also, it is necessary to provide a tuple to the sum ( ) : Returns the sum of the elements present in
len ( ) function. the tuple as output.
For example,
Example– >>> tup = (22, 45, 23, 78, 22, 22, 6.89) >>> tup = (22, 3, 45, 4, 2, 56, 890, 1)
>>> tup⋅count (22) >>> sum (tup)
3 1023
>>> tup⋅count (54) 5.16 Tuple Operation:
0 While working with tuple in Python, there are some
5.15(iii) count ( ): methods by which tuple can be manipulated, these are as
follows–
This function will help us to get the number of
occurrences of an element in a tuple. Also we have to
5.16(i) Tuple Slicing:
mention the element whose count needs to be found Slicing in a tuple works the same way as it works for
string slicing or any other sequence of elements. Slice is
inside the function. an operator that allows you to get a sub-tuple, from tuple.
Example– >>> tup = (22, 45, 23, 78, 22, 22, 6.89) It is represented by slicing it's start index and stop index.
>>> tup⋅count (22) slice syntax: Str [start stopstep]
3 start: The starting index of the string at which the
>>> tup⋅count (54) slicing operation is to be performed. This determines
0 when slicing of the string will begin.

75
Search on TG: @apna_pdf
stop: The stopping index of slicing, till the slicing 5.16(iii) Tuple Multiplication:
operation to be performed i.e. produces all tuples Index A tuple item can also be repeated in another tuple.
is excluded. Multiple operation provides iteration of tuple items
step: It is an optional argument that defines the steps according to given terms.
to be taken while iterating the list.
Example– Slice operation is used to slice a tuple. numbers 1 = (1,2,3,4,5)
We also use negative indexing method to slice the tuple– numbers × = Numbers 1*3
tuple = ('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j') print (numbers ×)
Print (tuple [0:6]) The new tuple will be created with the items of the
Print (tuple [1:9:2]) first tuple thrice.
Print (tuple [–1: –5: –2]) Output: (1,2,3,4,5,1,2,3,4,5,1,2,3,4,5)
The above code produces the following output. 5.16(iv) Deleting Tuple:
('a', 'b', 'c', 'd', 'e', 'f') Unlike a list, tuple items cannot be removed using
('b', 'd', 'f', 'h') the Del keyword because tuples are immutable. To delete
('j', 'h') the entire tuple, we can use the Del keyword with the
Indexing is used to retrieve individual objects while tuple name but individual items of the tuple cannot be
slicing is used to retrieve a subset of objects. deleted.
>>> tup = (22, 3, 45, 4, 2.4, 2, 56, 890, 1) Example– tuple 1 = (1,2,3,4,5,6)
>>> print (tup [1:4]) print (tuple 1)
# prints 2nd to 4th element del tuple 1 [0]
(3, 45, 4) print (tuple 1)
If we do not specify the start value, then by default del tuple 1
the series starts from the first element–
print (tuple 1)
>>> tup = (22, 3, 45, 4, 2.4, 2, 56, 890, 1)
Output: (1,2,3,4,5,6)
>>> print (tup [:4])
# prints 1st to 4th element Traceback (most recent call last):
(22, 3, 45, 4) File "tuple⋅py", line 4, in <module>
If we do not specify a stop value, the range defaults Print (tuple 1)
to the last term. Name Error : name 'tuple 1' is not defined
>>>tup (22, 3, 45, 4, 2.4, 2.56, 890, 1) = 5.17 Packing and Unpacking Tuple:
>>> print (tup [4]) In Python tuples are used to store immutable objects.
# prints 5th to the last element Python tuples are similar to lists except with a few
(2.4, 2.56, 890, 1) conditions. Python tuples are immutable which means
If we do not specify both the start and end values,
the series starts from the first element by default and they cannot be edited throughout the program.
ends on the last element. Python has a very powerful tuple assignment feature
>>> tup = (22, 3, 45, 4, 2.4, 2, 56, 890, 1) that assigns the value of the left side to the right side. In
another way, this is called unpacking a tuple of values
>>> print (tup [:])
into a single variable. In packing, we put the values into
# prints First to the last element a new tuple while in unpacking, we extract those values
(22, 3, 45, 4, 2.4, 2, 56, 890, 1) into a variable. That is, tuple packing specifies multiple
5.16(ii) Tuple Addition: values in a tuple. Unpacking refers to assigning a tuple to
In Python programming, you can combine two or multiple variables.
more tuples. Tuples can be combined to form a new When we create a tuple, we usually assign a value to
tuple. it. This is called a packing tuple.
fruits = ("apple", "banana", "cherry")
Example– tuple1 = (1, 2, 3, 4, 5) print (fruits)
tuple2 = (10, 20, 30) But in Python it allows us to extract the variable by
tuple3 = (102, 205, 308) value. This is 'Unpacking' called.
# Combining three tuples to form a New tuple. Tuple Unpacking
New tuple = tuple1 + tuple2 + tuple3 fruits = ("apple", "banana", "cherry")
Print (Newtuple) (green, yellow, red) = fruits
The output of the python code will be (1, 2, 3, 4, 5, Print (green)
10, 20, 30, 102, 205, 308) after combining all the three Print (yellow)
tuples into one tuple. Print (red)
Example– Creating a new tuple by adding two different The number of variables must match the number of
tuples. values in the tuple. If not then an Asterisk (*) sign must
car1 = ("BMW", "Mercedes", "Audi") be used to collect the rest of the volumes as a list.
car2 = ("Astom Martin", "Porche", "Jaguar") If the number of variables is less than the number of
cars = car1 + car2 values, you can add one to the Asterisk variable name
print (cars) and one to the value will be listed.
Output: ('BMW', 'Mercedes', 'Audi', 'Astom Martin', Example– Assign the rest of the values as a list called
'Porche', 'Jaguar') "red":
76
Search on TG: @apna_pdf
fruits = ("apple", "banana", "cherry", The comma is optional after the last pair when
"strawberry", "raspberry") creating a Python dictionary. Python does not store
(green, yellow, * red) = fruits dictionary elements in any particular order. If you enter
print (green) elements in one order, they can be stored in another order
print (yellow) inside Python. The order of the elements when creating
Print (red) the dictionary is different from that in which they are
Output: apple actually stored.
banana 5.18(ii) Characteristics of Dictionary:
['cherry', 'strawberry', 'raspberry'] The main features of Python dictionaries are as
follows–
5.18 Dictionary Initialization: (i) Dictionary element (key : value) pairs are not in
Dictionary is a data structure which is a group of ordered form.
elements having a pair of key and value. Dictionary is (ii) With same name but different case are considered as
unordered collection in python. Each key value pair is different keys in python dictionary.
separated by a comma (,) and the key and value are (iii) No duplicate keys are allowed. When duplicate key
separated by a colon (:). All the keys and values of the is found during assignment, then only the last
dictionary are written in curly brackets. The syntax of the
dictionary is as follows– assignment is considered.
(iv) Keys should be immutable, we can use strings,
Syntax– dict_name = {key:value, key1:value1} numbers or tuples as dictionary keys.
Example–Source Code (v) The dictionary may be Shrink or Grow, as required.
dict = {1 : "H", 5 : "e", 7 : "l", 8 : "I", 9 : "e"} (vi) Dictionaries can be nested.
Print (dict [5]) (vii) Dictionary is an unordered collection of objects.
Print (dict [9]) 5.18(iii) To Create Dictionary:
Output: e A dictionary in Python is made up of key: value
o pairs. We can create a dictionary in two ways, using sets
Dictionary is mutable data type but values can be of brackets { } and using the built-in dict ( ) function.
changed in dictionary and key can also be changed by To create an empty dictionary in Python, first create
Pop ( ) method but duplicate key cannot be given. The a variable name that will be the name of the dictionary.
keys in square brackets are used to access the values of Then, assign a variable to an empty set for curly bracket.
the dictionary. The key error occurs exception when an Example– # create an empty dictionary
invalid key is used. my-dictionary = { }
Unique key name and its value are given in square Print (my-dictionary)
brackets to add an element to the dictionary and del'
operator is used to delete the element in the dictionary. # to check the data type use the type ( )
5.18(i) Key:Value Pair: function
Python dictionary is used to store data of key: value print (type (my-dictionary))
type. Key is used to extract a particular value/item from # output
the dictionary. Dictionaries are written in curly brackets #{}
{ } to store data in key: value pairs and if there is more # <clas 'dict'>
than one item, they are separated by commas. Another way to create an empty dictionary is to use
Example– d = { the dict ( ) function without any arguments. This serves
'name' : 'Aryendra Kumar', as constructor and creates an empty dictionary.
'age' : 25,
'city' : 'Agra' Example– # create an empty dictionary
'country' : 'India' my-dictionary = dict ( )
} print (my-dictionary)
Print (d) # to check the data type use the type ( ) function
Output: C:\users\Mahima Ji\Desktop\Python>Python Print (type (my-dictionary))
dict_ex.py # output
{'name' : 'Aryendra Kumar', 'age' : 25, 'City' : #{}
'Agra', 'Country' : 'India'}
# <class 'dict'>
Some things should be considered creating the keys 5.18(iv) Dictionary Initialization:
of the dictionary– Initialization means the process of making
(i) You can take keys to strings (Like- 'name', 'age') something ready to start.
boolean (Like- True False), numeric (eg: 0, 1, 1.5) there are many ways to initialize dictionary in python –
type. A Dict ( ) Constructor– To Initialize a Dictionary in
(ii) Empty string (Like- " " , ' ' , " ") can also be taken, Python, A dictionary can be initialized by passing
here empty string single space, double space will be arguments as value pairs to the dict ( ) constructor.
counted separately. Example– my-dict = dict (Australia = 200,
(iii) But you cannot take set (Like- {3}), list (Like- [4]), Newyork = 300, Srilanka = 600)
tuple (Like- (5)) as a key but can be taken as a value. Print ("Initialize Dictionary", mydict)

77
Search on TG: @apna_pdf
First of all in above code we will create a tuple and my dictionary [2]⋅append ('Watson')
pass parameter in Dict ( ) constructor. Print ("Initialize dictionary : " +
str (dict (my-dictionary)))

Figure- 5.1 Dict ( ) constructor

B Using the setdefault ( ) function– Dictionaries in


Python are initialized by the setdefault ( ) method. This Figure- 5.4 Defaultdict ( ) Method
method returns the value within a list. 5.18(v) Dictionary Initialization:
Example– my-dictionary = { } Adding Objects to a Dictionary;
[my-dictionary⋅setdefault(i,[ ])for i in range(4)] To add an object to a Python dictionary, you must
specify a value for a new index key in your dictionary.
my-dictionary [0]⋅append ('George') Unlike lists and tuples, there is no add ( ) insert or
my-dictionary [1]⋅append ('John') append ( ) method that you can use to add items to your
print ("Initialize dictionary:" + data structure. In addition, you will need to create a new
str (dict (my-dictionary))) index key that will be used to store the values which you
want to store in the dictionary. Syntax to add a value is in
dictionary–
dictionary-name [key] = value
Example– scones = {
"Fruit" : 22,
"Plain" : 14,
"Cinnamon" : 4,
"Cheese" : 21
}
scones ["cherry"] = 10
print (scones)
Output: {'Fruit : 22, 'Plain' : 14, 'Cinnamon' : 4, 'Cheese'
fig.-5.2 Setdefault ( ) : 21, 'Cherry' : 10]
C Using Fromkeys ( ) Method– If you want to create As you can see, our code has added a 'cherry' key to
all keys in a dictionary with same value then you can the dictionary, which has been assigned the value 10. . In
easily use fromkeys ( ) method. the code, first a dictionary named 'scones' is declared.
Example– new-key = ["James", "Potter", "Mathew"] Which stores information about how many scones are
ini-dic = dict⋅fromkeys (new-key, 0) available at the cafe for ordering. Next, we add the key
print ("Dictionary Initialization", ini-dic) "cherry" to our dictionary and assign it the value 10, and
finally output of update the dictionary version has been
taken.
In the output of our code, our dictionary is not
ordered. This is because the data stored in a dictionary,
unlike the data stored in a list, is not in particular order.
Same notation can be used to update the value in the
dictionary.

Example– scones = {
"Fruit" : 22,
"Plain" : 14,
Fig.- 5.3 Formkeys ( ) Method
"Cinnamon" : 4,
D Using Defaultdict ( ) method– Defaultdict ( ) "Cheese" : 21
function can be used in Python dictionary if user
}
provides a default value for a key which is not available
then it evaluates the operation and starts key-value Scones ["Cinnamon"] = 14
element. print (scones)
Example– my-dictionary = Default Dict (list) Output: {'Fruit : 22, 'Plain' : 14, 'Cinnamon' : 14,
'Cheese' : 21,]
my-dictionary [0]⋅append ('Kane') The code sets the value associated with the
my dictionary [1]⋅append ('Pollard") "Cinnamon " key in our dictionary to 14.

78
Search on TG: @apna_pdf
5.18(vi) Dictionary Traversing: Print (t [0])
Traversing a dictionary means visiting each element Print (t [1])
of the dictionary to display its value on the screen. With Print ( '.......' )
a for loop, to iterate over the dictionary (dict) key (), # ('key1', 1)
values ( ), items ( ) method can be used. You can get a # <class⋅'tuple'>
list of keys and values in a dictionary by using list ( ) and # key 1
these methos. # .......
• Iterates over the keys in the dictionary (dict) : keys ( ) # ( 'key 2', 2)
• Iterates over the values in the dictionary(dict):values( ) # <class 'tuple'>
• Iterates the key-value array in the dictionary ( dict): # key 2
items ( ) #2
Example–d= {'key 1' : 1, 'key2' : 2, 'key 3' : 3} # ......
In a for loop, you can iterate over the keys using a # ('key3', 3)
dictionary object. # < class 'tuple'>
for k in d : print (k) # key 3
# key 1 #3
# key 2 # ......
# key 3 item ( ) method returns dict items. This can be
keys ( ) method returns dict-keys. This can be converted to a List using list ( ).
converted to a list using list ( ). item = d⋅items ( )
Example– keys = d⋅keys ( ) print (items)
print (keys) print (type (items))
print (type (keys)) # dict-items ([('key1', 1), ('key2', 2)
# dic-keys (['key 1', 'key 2' 'key 3']) # ('key3', 3)])
# <class 'dict-keys'> # <class 'dict-items'>
k-list = list (d⋅keys ( )) i-list = list (d⋅items( ))
print (k-list) print (i-list)
print (type (k-list)) print (type (i-list))
# ['key 1', 'key 2', 'key 3'] # [('key1', 1), ('key2', 2), 'key3', 3)]
# <class 'list'> # <class⋅'list'>
print (i-list [0])
(dict) : values ( ) Iterates over the values in the print (type (i-list [0]))
dictionary– Using the values method, you iterate over the # ('key1', 1)
values in the dictionary. # <class 'tuple'>
for v in d-values (): 5.18(vii) To Update and Delete Values in
Print (v) Dictionary:
#1 Unique key name and its value are given in square
#2 brackets [ ] to add elements to the dictionary.
#3 Source code:
values ( ) method returns dict-values which can be dict = {"name1" : "Rakesh", "name2" : "Ramesh",
converted to list using list ( ). "name3": "kamlesh"}
values = d⋅values ( ) Print ("Before Adding Element : ")
print (values) Print (dict)
print (type (values)) dict ["name4"]="Rajesh"
# dict-values ([1, 2, 3]) Print ("After Adding Element: ")
# <class 'dict-values'> Print (dict)
v-list = list (d⋅values ( )) Output:
print (v-list) Before Adding Element:
print (type (v-list)) {'name1': 'Rakesh', name2': 'Ramesh', 'name3' :
# [1, 2, 3] 'Kamlesh'}
# <class 'list'> After Adding Element :
{'name1' : 'Rakesh', 'name2' : 'Ramesh', 'name3':
(dict) = items ( ) You can iterate over key-value 'Kamlesh', 'name4' 'Rajesh'}
pairs in a dictionary using the items ( ) method. • The 'del' operator is used to delete an element in the
for k, v in d⋅items ( ) : dictionary.
Print (k, v) Source code:
# key 1 1
dict = {"name1" : "Rakesh", "name2" : "Ramesh"
# key 2 2
# key 3 3 "name3" : "Kamlesh"}
Print ("Before Deleting Element : ")
This can also be obtained as a tuple of (key, value). Print (dict)
for t in d⋅items ( ) : del dict ["name2"]
Print (t) Print ("After Deleting Element : ")
Print (type (t)) Print (dict)
79
Search on TG: @apna_pdf
Output: dict 2 = {'Place' : 'Agra', 'distance' : 41, 'Temp:' 25};
Before Deleting Element : print ("Length of dict 1", len (dict 1))
{'name1' : 'Rakesh', 'name2' : 'Ramesh', 'name3' : print ("Length of dict 2", len (dict 2))
'Kamlesh'} >>> Length of dict 1 2
After Deleting Element : Length of dict 2 3
{'name1' : 'Rakesh', 'name3' : 'Kamlesh'} 5.19(v) get ( ):
5.19 Dictionary Functions and Method: This method returns a value for the given key.
Python dictionary is like a map which is used to Returns the default value None if the key is not available.
store data in the form of key value pairs. Inbuilt Syntax: dict⋅get (key, default = None)
functions are available in Python dictionary which are as Key– This is the key that is to be searched in the
follows– dictionary.
5.19(i) clear ( ): Default– This is the value returned in case the key
This method removes all objects from the dictionary. does not exist.
>>> d = { } Example– dict 1 = {'Name' : 'Zara', 'Age' : 27}
>>> d ['name'] = 'John' print ("value: % S" % dict⋅get('Age'))
>>> d ['age'] = 20 print ("value: % S" % dict⋅get(Gender; "NA"))
>>> d >>>
{'age' : 20, 'name' : John'} value : 27
>>> returned-value = d⋅clear ( ) value : NA
>>> d 5.19(vi) pop ( ):
{} This method assigns value correspondents first to
>>> (print returned-value) the given keys and then removes the dictionary value
None pairs from the dictionary.
5.19(ii) dict ( ): Syntax: dictionary⋅pop (key, defaultvalue)
This function creates a dictionary. Dictionary is a Under keys which is to be searched to extract. By
collection which is unordered, mutable and indexed. default is the value that is returned when the keys are not
Syntax– dict (Keyword arguments) in the dictionary.
Example– # random sales dictionary
Parameter– keyword arguments is optional, you sales = {'apple' : 2, 'orange' : 3, 'grapes' : 4}
can pass multiple arguments in it. element = sales⋅pop ('apple')
Example– x = dict (name = "John", age = 36, country = print ('The popped element is:', element)
"Norway") print ('The dictionary is':, sales)
print (x) >>>
>>> {'name' : 'John', 'age' : 36, 'country' : 'Norway'} The popped element is : 2
5.19(iii) cmp ( ): The dictionary is : {"orange': 3, 'grapes': 4}
This method compares two dictionaries based on 5.19(vii) dict⋅popitem ( ):
keys and values. It is helpful in identifying duplicate This method removes and returns the last element
dictionaries as well as performing relational comparisons (key, value) pair inserted in the dictionary.
between dictionaries. Syntax: dict⋅popitem ( )
Syntax: cmp (dict1, dict2) It doesn't take any parameters. This is done by removing
Where dict1 and dict 2 are the two input (Key, Value) pairs from the dictionary in Last In, First
dictionaries. out (LIFO) order returns.
Example– dict 1 = {'Place' : 'Delhi', 'distance' : 137}; Syntax: dict⋅popitem ( )
dict 2 = {'Place' : 'Agra', 'distance' : 41}; Example–
dict 3 = {'Place' : 'Bangaluru', 'distance' : 1100}; man = {'name' : 'zubi', 'age' : 23, 'salary' : 85000.0}
print "Comparison Result:%d" % cmp(dict 1, dict 2) # ('salary', 85000.0) is inserted at the last,
print "Comparison Result:%d" % cmp(dict 2, dict 3) # so it is removed.
print "Comparison Result:%d" % cmp(dict 3, dict 4) result = man⋅popitem ( )
>>>
Comparison Result : 1 print ('Return value =', result)
Comparison Result : –1 # inserting a new element pair
Comparison Result : 0 print (man =', man)
In the above example we observe pair of dictionaries # inserting a new element pair
comparing with each other. Result is 0 if they are equal. man ['Profession'] = 'Engineer'
If the result is 1 then the value of the first dictionary is # now ('Man', 'Engineer') is the latest element
greater and if the result is 1 then the value of the first result = man⋅popitem ( )
dictionary is less. print ('Return value =', result)
5.19(iv) len ( ): print ('man =', man)
This method returns the total length of the dictionary Output:
which is equal to the number of items. An item is a key Return value = ('Salary', 85000.0)
value pair. man = {'name' : 'Zubi, 'age' : 23}
Syntax: len (dict) Return value = ('Profession', 'Engineer')
Example– dict 1 = {'Place' : 'Delhi', 'distance' : 137}; man = {'name' : 'Zubi', 'age' : 23}
80
Search on TG: @apna_pdf
5.19(viii) keys ( ): Syntax: dictionary_name⋅values ( )
This method returns all the keys in the dictionary as There is no parameter.
a sequence of keys. It does not return in any particular Example– marks = {'Physics' : 67, 'Maths' : 87}
order. print (marks⋅values ( ))
Syntax: dict⋅keys ( ) # output:dict_values ([67, 87])
Example– >>> emp = 5.19(x) items ( ):
{'name' : 'Manish', 'age':30, 'designation': 'Teacher'} The Python dictionary method item ( ) returns a list
>>> emp⋅keys ( ) of dictionary (keys, value) tuple payer.
dict_keys (['name', 'age', 'designation']) Syntax: dict items ( )
5.19(ix) values ( ): takes no parameters.
That is an inbuilt method in Python programming Example–dict = {'Name' : 'Zara', 'Age' : 7}
that returns a View object. Dictionary value as List in print "value : % S" % dict⋅items ( )
view object are involved. >>> value : [('Age', 7), ('Name', 'Zara')]

Practice Questions with Explanatory Solutions


1. Splits a string into substrings– (c) Print (max (1) ) (d) Print (Len (t))
(a) split (b) Numbers Ans. (b) 1 = (1, 2, 4, 3), it is a tuple, which is an
(c) data (d) string immutable data type i.e. its value cannot be changed.
Ans.(a) split ( ) function splits the string into Option [1][3] = 45 is wrong because the value of
substrings. List by splitting the string with the a tuple cannot be changed. To assign value to tuple
separator given in this function returns in (sequence). once after that no change is possible.
Example– >>>S1 "Welcome to Python World" 6. Replication (*) means–
>>> Words = S1·split ( ) (a) It gives the product of two numbers.
>>> Words (b) Repeats the string up to the specified number of
['Welcome', 'to', 'Python', 'World'] times.
2. A string is a sequence of characters and a list the (c) Both A and B
sequence of ........ (d) none of these
(a) numbers (b) Data Ans. (b) *(product) operator operates with number it
(c) Values (d) none of these returns the product of two numbers as output and
Ans.(c) A string is a sequence of characters that can when used with * (replication) string it returns the
contain numbers, alphabets, special characters, etc. product of two numbers as output. Makes a copy. To
and a list there is a sequence of values. In Python, the use the replication operator, one operand must be a
elements (values) of a list are called items. string and the other must be a number, otherwise it
3. What is Index? will display an error.
(a) Data Integer (b) Values Integer Like– >>> "Python!" * 3
(c) List (d) All of the above 'Python! Python! Python!'
Ans. (d) Index ( ) method returns the index of the 7. What will be the output of the following program
given item in the. Key value is integer. List index segment?
starts from 0 in Python programming. Python starts at >>>str1 = 'Computer world'
the last index of the list. >>> only (str1)
4. Find the output of the following python code– (a) 14 (b) 10
def gfg (x, l = (J) : (c) 13 (d) 12
for i in range (x) : Ans.(a) In the given program segment, a string strl =
l·append ( i * i ) 'Computer world' is given. Then str1 is passed as a
Print (l) parameter using the len function. len ( ) is a built-in
gfg (2) function that outputs the number of characters in a
(a) [3.2.1.0.1.4] (b) [0.1] string. 14 will be displayed as the value of len (str1).
(c) [0.1.0.1.4] (d) error in code 8. Empty list............ is indicated by.
Ans. (b) append ( ) method is used to add further (a) { } (b) [ ]
values. to print the value of and call gfg ( ) in which
the parameter value 2 is passed. It will be stored in (c) ( ) (d) None of these.
value because the value of the list is not passed. On Ans. (b) Python list is a data structure. It is a sequence
starting the range X function, it will start from and run of elements, which is mutable i.e. the values of the list
till 2, so the given code def gfg (x. 1= [ ]) : can be changed. The elements in a Python list are
for i in range (x) : called items. Each item in the list is separated by a
l ·append (i * i) comma (,) and the entire item is enclosed in square
Print (l) brackets [ ]. Mixed data types can also be used in
gfg (2)
When run, the output will be [0, 1]. Python list.
5. Let t = (1, 2, 3, 4) then which of the following is 9. Which type of list can we make–
wrong? (a) string list (b) Mixed value type list
(a) Print (1[3]) (b) 1 [3] = 45 (c) number list (d) all of the above.
81
Search on TG: @apna_pdf
Ans. (d) List is one of the simplest and most 16. The difference between tuple and list is that
important data structure in Python. list contains any tuples use ........... unlike lists while lists use
number of items can while creating list we can use square brackets.
string, number, mixed value type etc. in item. (a) Parenthesis (b) list
10. If you skip the first index, the slice starts at– (c) Values (d) none of these
(a) Beginning (b) end Ans. (a) The difference between tuple and list is that
(c) Middle (d) none of these the value of objects stored in list can be changed
Ans. (a) Like every programming language, Python whereas tuple is immutable so the value of objects
has an index 0 of the first item of the list. In Python stored in tuple cannot be changed. Each item of the
the last index of the list starts from –1. The colon (:) tuple is separated by a comma (,) and the entire item is
for slicing is called the slicing operator. Where to start enclosed within parentheses ( ). Square brackets [ ] are
slicing is given on the left side of the colon (:) and used in lists.
where to end on the right side of the colon (:). even 17. Adds all the elements of a list taking it as an
skipping the first index the slice starts from the argument.
beginning. (a) extaend ( ) (b) split ( )
11. >>> Maximum (('Hi', 'hi', Hello')) will output– (c) count ( ) (d) none of these
(a) Hi (b) Hello Ans. (a) extend () method is used to extend the list. It
(c) hi (d) none of these adds all the elements of a list by taking it as an
Ans. (b) In Python programming, the max() function argument. For this list-extend (sequence) syntax is
returns the largest value present in the list as output. used. Here as a parameter of the syntax. The sequence
When the string is stored in the list, it returns the and collection which is to be extended with the main
largest string as output based on character count. >> list under sequence in sequence is given here.
maximum (('Hi', 'hi', 'Hello')) will return Hello as an 18. Converts a list to tuple–
output. (a) integer value (b) sequence
12. min ( ) returns– (c) immutable (d) none of these
(a) the largest item in the tuple Ans. (b) Tuple is a data structure of Python which
(b) the number of objects in the tuple cannot be changed after it is defined. Tuples are a type
(c) the smallest item in the tuple of sequence but they are immutable like strings.
(d) none of these Convert a list to a tuple using tuple (seq).
Ans.(c) In Python programming, the min ( ) function 19. >>> nums = [4, 8, 12 ] >> Print len (nums ) .....?
is used to find the smallest value present in a list. If a (a) 1 (b) 5
string is stored as a value in a pivot list, it will output (c) 3 (d) 7
the smallest string based on characters. Ans.(c) len ( ) is used to extract the length in Python
13. The index value in the dictionary can be any of programming. Using len ( ) you can find the length of
the following– any character, number, string, list, tuple or dictionary
(a) integer (b) any data type etc.
(c) float (d) none of these >>>nums = [4, 8, 12]
Ans. (d) Python dictionary is a data structure, which is >>>Print len (nums)
an unordered collection of items in key value pair. A Output : 3
dictionary is like a hash, it consists of pairs of keys 20. What counts the number of times a specified
and values. In dictionary, key and value are separated value appears in a tuple?
by colon and their pair is separated by comma (.). (a) append ( ) (b) split ( )
Indexing of values in a dictionary cannot be done. In (c) extend ( ) (d) count ( )
this, keys are used in square brackets to access the Ans. (d) count ( ) is used to count any value word
values. character list, dictionary and tuple etc. Returns the
14. Which of the following dictionary function gets occurrences of the given item in the list. For this list-
all the keys from the dictionary? count (item) syntax is used. Counts the number of
(a) getkeys ( ) (b) key times a specified value appears in the tuple.
(c) keys ( ) (d) none of these 21. Istrip ( ) method is used for:
Ans.(c) The keys ( ) method on a Python dictionary (a) delete all the trailing characters
returns a View object, which displays an insertion (b) delete all the leading characters
order list of all the keys in the dictionary in insertion (c) delete all the leading and trailing characters
order. It doesn't have any parameters. Returns a View (d) delete upper case characters
object that displays all the keys. This view object Ans. (b) Istrip ( )) function is used to delete all the
changes according to changes in the dictionary. leading characters.
15. What is a tuple? 22. Suppose a list with name arr, contains 5 elements.
(a) mutable data (b) Data Structure You can get the 2nd element from the list using:
(c) both (a) and (b) (d) none of these (a) arr[-2] (b) arr[2]
Ans. (b) Tuple is a data structure which is used to (c) arr[-1] (d) arr[1]
store data. tuple immutable are i.e. Once a tuple is Ans. (d) List items are ordered mutable and allow
duplicate values. List items are indexed, first item has
created, it cannot be updated or modified. Tuple is index [0], second item has index [1] etc.
used only when we need in data no change has to be Example– arr = ['A', 'B', 'C', 'D', 'E']
made. To access the second item 'arr[1]' has to be written.
82
Search on TG: @apna_pdf
23. Assume q=[3, 4, 5, 20, 5, 25, 1, 3], then what will (a) {"Joey":1,"Rachel":2,"Phoebe":2}
be the items of q list after q-pop ( 1 ) ? (b) {"Joey":1,"Rachel":2}
(a) [3, 4, 5, 20, 5, 25, 1, 3] (c) {"Joey":1,"Phoebe":2}
(b) [1, 3, 3, 4, 5, 5, 20, 25] (d) Error
(c) [3, 5, 20, 5, 25, 1, 3] Ans. (a) The 'updae ( )' function in Python appends the
(d) [1, 3, 4, 5, 20, 5, 25] value to the 'dict' data type/data structure. So, the output
Ans.(c): The 'pop( )' method in Python removes the of the given python code will be–
element at the specified position. {"Joey" : 1, "Rachel" : 2, "Phoebe" :2}
Example– q = [3, 4, 5, 20, 5, 25, 1, 3] 30. What is the output of the following code?
q-pop(1) def disp(*arg):
print(q) for i in arg:
Will get [3,5, 20, 5, 25, 1, 3] as output. print(i).
24. In which of the following data type, duplicate disp(name+"Rajat", age="20")
items are not allowed? (a) TypeEror (b) Rajat 20
(a) list (b) dictionary (c) Name age (d) None of these
(c) set (d) None of the above Ans. (a) def disp (* arg):
Ans. (b) Dictionary is used to store values to key : value for i in arg :
pairs. A dictionary is a collection that is mutable and print (i)
does not allow duplicates. disp (name + "Rajat", age = "20")
25. What is the output of the following code? Output will be obtained as–
ms = ('A', 'D', 'H', 'U', 'N', 'I', 'C') Type Error : disp ( )
print(ms[1:4]) got an unexpected keyword argument 'name'
(a) ('D', 'H', 'U') So, option (a) is correct answer.
(b) ('A', 'D', 'H', 'U', 'N', 'I', 'C') 31. What is the return type of following function?
(c) ('D', 'H', 'U', 'N', 'I', 'C') def func1( ):
(d) None of these return 'mnp',22
Ans. (a) The given python code is given in tuple, so ms (a) List (b) dictionary
[1 : 4], 1, 2, 3 value will pint that hence utput ('D', 'H', (c) string (d) tuple
'U') will be obtained. Ans. (a) The return type of the function will be tuple as
26. What is the output of >>>'2' + '3' it is returning both string and integer values.
(a) 2 3 (b) '2+3' 32. What is the output of the following code?
(c) '23' (d) None of these a = {1: "A", 2: "B", 3: "C"}
Ans. (a) Print ('2' + '3') ⇒ 23 b = {4: "D", 5: "E"}
23 will be obtained as output because this a.update(b)
python code concatenates two string characters. print(a)
27. What will be the output of the following Python (a) {1: "A", 2: "B", 3: "C"}
program? (b) {1: "A", 2: "B", 3: "C", 4: 'D', 5: 'E'}
def addltem(listParam): (c) Error
listParam += [1] (d) {4: "D", 5: "E"}
mylist = [1, 2, 3, 4] Ans. (b) Update (⋅) method will append the value pair
addItem(mylist)
of dictionary b key with that of dictionary A.
print(len(mylist))
(a) 5 (b) 8 So, output will be recived as–
(c) 2 (d) 1 {1: "A", 2: "B", 3: "C", 4: 'D', 5: 'E'}
Ans. (a) def addItem (list Param): 33. How can we create an empty list in Python?
list Param + = [1] (a) list = ( ) (b) list.null
my list = [1, 2, 3, 4] (c) null.list (d) list = [ ]
addItem (mylist) Ans. (d) The list is like array. Lists declared in other
print (len (mylist)) languages do not always need to be homogeneous
The output will print 5 because the length of the list which makes this a most powerful tool in Python. List
can be created simply by placing sequences inside
is 5. One element has already been placed and four square brackets. To declare an empty list, specify a
elements are being added later. variable with square brackets.
28. What is the output of the following statement? 34. Which one of the following is a mutable data
print ((2, 4) + (1, 5)) type?
(a) (2, 4), (4, 5) (b) (3, 9) (a) set (b) tuple
(c) (2, 4, 1, 5) (d) Invalid Syntax (c) string (d) None of these
Ans. (c) The given python code will add the value score Ans. (a) Mutable and Immutable data type in Python–
like a string. so (2, 4, 1, 5) will be obtained as output. • List of some mutable (changable) Dat Type– List,
Hence option numbers C is correct answer. Dictionary, set and user–defined classes.
29. What is the output of the following code? • On the other hand there is some Immutable
dic={"Joey":1,"Rachel":2} (Unchangable) data type. As– int, float, Decimal,
dict.update({"phoebe".2:})
bool, string, Tuple & Range.
print(dict)
83
Search on TG: @apna_pdf

6 FUNCTIONS

6.1 Top-Down approach for Problem Disadvantages–


Solving: • Specifications change over time and in a top-down
Top-down approach basically divides a problem into approach all decisions made from the beginning of
many small parts (modules). These modules are further project are directly or indirectly dependent on the high
decomposed as long as the resulting modules are simple level specifications.
to understand and ideal to program. Each submodule • In dynamic programming, the top-down approach is
performs only one task. slower than the bottom-up approach, because of the
Top-down approach is a stepwise process of recursion involved.
breaking down large program modules into simpler and 6.2 Bottom-Up approach for Problem
smaller modules in order to organize and code program
in an efficient manner. In this approach the flow of Solving:
control is always in downward direction. In this, any In bottom up approach, we do not know the main
problem is broken into small problems and a function is tasks that we have to do but we know that these tasks
written to solve each small problem and at each level it ishave to be done to solve the main problem. In this
seen whether the problem is solved. In this way, each approach, we reach the main problem by solving all the
design level gets completed by the above process at each problems. We don't know what the main problem is until
level. we reach the main problem. This approach works from
Some of the advantages of the top-down approach the bottom up. In this approach, we only solve all the
are as follows– problems and reach our main problem and problem or
• Problem solving can be done by more than one person process is not given much attention. In this, attention is
by breaking down the problem into smaller parts. paid to data and data security. Some programming
• Problem solving always proceeds from the top most languages that follow this approach are C++, Java vb-
level to downward.
net, C#, Python
• Reduces debugging time.
Unlike top-down approaches, bottom-up
• Unnecessary low level details are removed.
programming focuses on starting at a very basic level
and designing an algorithm as you proceed. In this
approach, modules are designed individually and then
integrated together to form a complete algorithmic
design. This approach is more suitable when there is a
need to build a system from available components.
Some of the major advantages of bottom up
approach are as follows–
• Creating test conditions is easy.
• Easy to view testing results.
• Codes can be reused.
In this, first the main problem is defined, then • Redundancy is reduced due to the presence of data
considering main problem, the problem is further solved. encapsulation and data hiding.
Some programming languages that follow the top- Bottom-up approach also has some disadvantages
down approach are C, visual basic, Pascal, Fortran. The which are as follows–
advantages and disadvantages of the top-down approach • In a bottom-up approach, we solve all the subproblems
are as follows– (even if some solutions to the subproblems are not
Advantages– required to be solved), which requires additional
• Each module of the code is to be tested separately. calculations.
• By dividing a problem into small parts, it becomes • In a bottom-up approach, sometimes it is difficult to
very easy to understand and solve it. identify the overall functionality of the system in the
• Testing and debugging becomes easier. early stages.
84
Search on TG: @apna_pdf
Difference between Top Down and Bottom-up Approach: Following are the important differences between
top-down and bottom-up approach–
S.No. Key Top-Down Approach Bottom-Up Approach
1. Focus It focuses on breaking down a large It focuses on identifying and solving the
problem into smaller problems and smallest problems and then integrating them
then repeating each process. together to solve the larger problem.
2. Language Top down approach is followed by Bottom-up approach is mainly used by
structured programming languages object oriented programming languages like
like C, Fortron etc. Java, C++ etc.

3. Redundancy As the size of the project increases, The redundancy in the bottom-up approach.
the top-down model is better suited and focuses on reusability.
because it ensures minimum data The bottom up model is better suited as it
redundancy over. ensures minimal span redunancies and
focuses on reusability.
4. Interaction The top-down model has tight Bottom-up modules have high interactivity
coupling issues and less interactivity between different modules.
between different modules.

5. Approach The top-down model is based on the The bottom-up model is based on
decomposition approach. composition approach.
6. Issues It may not be possible to divide a It is difficult to identify the overall
problem into a set of smaller problems functionality of the system in early stages of
in a top-down approach. Bottom-up approach.
7. Process The sub-modules are analyzed in This Checks which data need to encapsulate.
depth.
• Programs can be designed more easily. Because a
6.3 Modular Programming:
If a program is large and complex, then it is a small team works with only a small part of the entire
difficult task for the programmer to design the program, code is related. Modular programming supports a
Modular programming is used for this. In modular single application from multiple programmers.
programming, the program is divided into small pieces, • The code is stored in several files. The code is short,
which are called modules, and the process is called simple and easy to understand. Errors can be easily
module programming. Each module is designed, tested identified. Because they are local to the subroutine or
or developed to be simple and reliable for the user. It is
function.
easier to design or test a single program than an entire
program. • The same code can be used in multiple applications.
Modular design is an approach that breaks down a • The scoping of variables can be easily controlled.
system into smaller parts called modules that can be
created independently and then used in different systems.
Through this we can customize, repair, upgrade and
reuse the design.
In other words, "it takes a design and divides it into
smaller parts and then assembles these smaller parts to
form a larger system," modular design is very beneficial
and reliable due to reusability. By using module design
and reusable patterns in the design workflow, we can
improve the consistency and quality of the platform.
6.3(i) Advantages of Modular Programming:
Following are the advantages of modular design–
• It saves time and reduces the cost.
• This design is very safe as the risks are less.
• Its quality is very high. Due to reusability, we can use
it in different systems which are very beneficial. Modular design
85
Search on TG: @apna_pdf
6.4 Function: There are some major differences between function
It is a set of instructions that perform a specific task and method, which are as follows–
that can be processed independently. There is a function (i) Function and Method both look similar as they
in every program, where the statement of the function is perform almost in the same way but the main difference
required, the function is called there. The code written in is the concept of 'class and its object'.
the function does not have to be written again and again. (ii) Function can be called by its name only because
Large programs can be divided into smaller functions. it is defined as independent. But the method cannot be
called by its name only. We need to call a class in the
The function saves programmer time, program space and
context of class in which it is defined i.e. method being
memory. When an error occurs in the program, it can be
defined inside a class is class dependent.
easily removed with the help of the function.
Basic Function Syntax–
Python allows us to break down a large program into
def function Name (arg1, arg2, ...........):
basic building blocks known as functions. The set of
programming statements in a function is enclosed by { } ........,
(proper indentation). The function can be called multiple # Fuction body
times to make Python programs reusable and modular. ........,
Function helps programmer to break the program into Example– def sum (num1 num2 ) :
smaller parts. It organizes the code very effectively and return (num1 + num2)
avoids code repetition, function makes the program more Output: >>>sum (5, 6)
organized. Python provides us with various inbuilt 11
functions like range ( ) or print ( ). However, the user can Basic Method Syntax–
also create their own functions, which are called user Class Class Name:
defined functions. def method_name ( ):
Functions are mainly of two types– .......,
(i) User-defined function: These are defined by the # Method_body
user to perform a specific task. .......
(ii) Built-in function: Those functions which are Example– Class Nationality (object) :
already defined in Python. def my_method ( ) :
6.4(i) Advantage of Python Function: print ("I am Indian")
Following are some of the major advantages of Indian⋅my_method ( )
Python Function– Output: I am Indian
Code Reusability: The biggest advantage of using 6.4(ii) Difference between Module, Package
function is that, we can re-use the code, once we define a
function for the same processing, we can use it for and Library in Python:
anything and any number of times. Module– Module is a simple python file which
Less Code: Since we use functions for the same contains a collection of functions and global variables. It
code, the length of the program is reduced. is an executable file and to organize all the modules we
Minimum Coding Time: Using functions reduces have a concept called package in python.
coding time, which is important for any developer. Easy Examples of modules– Date and Time, Regex,
to understand code makes it easy to fill in. Random etc.
Example– Save the code in a file named Demo-modul-p.
Easy to maintain, with the time we have to update
the code, we can maintain it easily with the help of def my module (name):
functions. print ("This is my module : " + name)
In Python, functions are defined differently. In PHP Import-module named
Javascript, Java, C etc functions are defined using the Demo-module and call the my module function
function keyword, but this is not in case of Python. inside it.
In Python, functions are defined using the def import demo-module
keyword and the function body begins with a colon (:) demo-module⋅my module ("Math")
deadline increases. Output: This is my Module : Computer
(i) By creating functions, we can divide a very large Package– A package is a simple directory
program into blocks so that the program can be containing a collection of modules. This directory
understood easily. contains the Python modules and also contains
(ii) We can call the function in program as many times the_init_py file that translator interprets as a packages.
as per our choice. Package is just a namespace. It also contains sub
(iii) There is no limitation in calling a function. packages inside package.
(iv) Debugging becomes easier by creating a function.
(v) By dividing the program into functions, it can be Examples of packages in the package Numpy,
easily maintained. Pandas etc.
86
Search on TG: @apna_pdf
Example– Student (Package) Output: 12
| _init_⋅py (constructor) 4
| details⋅py (module) 5.0
| marks⋅py (module) 7.9
| college Details⋅py (module) 6.5.3
Library– A library is a collection of related 6.5(iii) User Defined Function:
functionality in code that allows you to perform many
tasks without writing your own code. It is a reusable Such functions which we define ourselves to
piece of code that we can import and use in our program. perform a specific task they are known as User Defined
We can use it by simply importing that library and Function. The library functions that come with Python
calling the method of that library with a period (⋅). It is are called built-in functions. If we use a function written
often assumed that a package is a collection of modules by others in the form of a library, it can be called a
and a library is a collection of packages. Examples of library function. All other functions we write ourselves,
libraries are mtplotlib, pytorch, py game, seaborn etc. that is called user defined functions, so our user defined
Example– Importing Pandas library and calling function can be a library function for someone else.
read_csv method using alias (⋅pd) of Pandas. Benefits of User Defined Function–
import pandas as pd (i) User defined functions help in decomposing a large
df = pd⋅read_csv ("file_name⋅csv") program into smaller blocks which makes the
6.5 Types of Function: program easier to understand, maintain and debug.
A function is a set of code in any programming (ii) If the code occurs repeatedly in a program. Function
language. The name of a function block is unique can be used to contain those codes and execute them
throughout the program. Function Performs specific task when required by calling that function.
and can be processed independently. Function is used (iii) Programmers working on large projects can divide
when there is a need to write a group of statements the workload by creating separate functions.
repeatedly. Through function, we can divide a large
Example–# Program to illustrate
program into small sub-programs.
There are three types of functions in Python # the use of user-defined functions
programming– def add-numbers (x, y):
(i) Built in function sum = x + y
(ii) User defined function return sum
(iii) Module num 1 = 5
6.5(i) Module: num 2 = 6
A module is a type of Python file with the extension print ("The sum is", add-numbers (num1, num2))
⋅py or⋅pyw. These Python files contain different classes, Output: Enter a number : 2.4
functions, variables so that we can use them again. In Enter another number : 6.5
Python, we can use both predefined modules and The sum is 8.9
external modules. We get more than 200 predefined
modules in Python. Predefined modules are already
6.6 To Define a Function:
installed whereas we have to install external modules. Function is defined to provide the required
some predefined names of the modules are given below. functionality, some of its rules are as follows–
Example– random, math, abc, zipfile etc. We can ● To define a function, def keyword is used along with
use these modules in our program with the help of import the function name.
keyword. ● Identifier must follow the rules of Function name.
● Function accepts parameters (arguments) and they can
6.5(ii) Built in Function: be optional.
Built in functions are functions that do not need to ● Function block is started with colon (:) and block
be defined, they are built in to Python. It returns the statements should be on same indentation.
output according to its definition. ● Return statements are used to return a value. A
Type ( ), int ( ), float ( ), bool ( ), list ( ), tuple ( ), set function can have only one return.
( ), etc are all built in functions.
Syntax for Function Definition
Example– a = 12
def function-name (parameter (s)):
b = –4
"function-docstring"
c = 3 + 4j
function-body
c = 3 + 4j
return statement
d = 7.90
def: To create a function in Python, the keyword
print (abs (a)) 'def' is used at the beginning.
print (abs (b)) function-name: The name of function is given after
print (abs (c)) def keyword. If the name of each function is related to its
print (abs (d)) statement then it becomes perfect.
87
Search on TG: @apna_pdf
(parameter (s)) : optional- parameters are optional, Call 2
parenthesis (( )) are not used parenthesis is given after This is a docstring
the function name (( )), one or more parameters are given 10
in those parenthesis. parameters; are optional. In Python, when the function is called by calling the
: : It is mandatory to give Colon (:) after the data type whose value is given as argument, then its data
parenthesis. After giving Colon, automatic code is type becomes fixed.
indented by Python Interpreter. Source Code:
"function-docstring" : optional, Documentation
def fun (num, str):
string is given here.
print (num)
function-body : optional, This is the body of the
function which may contain some local variables and print (str)
statements. The variables given in the body can also be print ("function call 1:")
made global. fun ("Hello", 2)
return statement : Optional, This is the return print ("function call 2:")
statement. The 'return' keyword is used for the return func (2, "Hell")
statement. Function ends with these statements. If return Output:
statement is not given then default 'Name' is returned. Function Call 1:
Example for Function Definition Hello
Source Code: 2
# fuction definiton Function Call 2:
def fun (param) : # function 2
name, parameters and colon Hello
"This is a docstring" # docstring
6.6(ii) Return Statement:
print (fun–doc–) # function body
Return statement is used at the end of the function
return param # return which returns the result of the function. It ends function
statement execution and transfers the result to where the function is
On example func' is the name of the function. called. The return statement cannot be used outside a
After that a parameter named param' is given in ( ) function.
(parentheses) and colon (:) outside the parenthesis. The Syntax
docstring is given first in the indent code of the function.
return [expression-list]
After that the docstring is printed with the help of class
attribute in the body of the function and finally the It can contain an expression which is evaluated and
param' parameter is printed in the return statement. the value is returned to the caller function. It returns no
object if the return statement has no expression or this is
6.6(i) Calling Function: not present in the function itself.
In a function, only the name of the function and the Call by reference in Python
value of call parameter (if the function has parameters)
Call by reference in Python means passing the actual
are given. The code in a function does not execute until
value as an argument to the function. All functions are
the function is called.
called by reference, that is, all changes made to the
Example–
reference inside the function are returned to the original
Source Code: value by the reference.
# function definition
6.7 Python Program Structure:
def func (param): # function
A typical Python program consists a lot of text files,
name, parameter and colon
which contain Python statements. The program is
"This is a docstring" # docstring
designed as a single main, top file with one or more
print (fun - doc -) # function body suppliment files.
return param # return In the Python top-level file, the key path of your
statement program file's control is where you can start your
print ("call 1") application. Library tools are also known as module files.
print (fun (5)) # function call These tools are implemented to collect top level files.
print ("call 2") Top level files use tools that are defined in module files
print (func (10)) # function call and module files will apply tools that are defined in other
Output: modules–
Properties and Imports:
Call 1
Structure of Python program includes three files
This is a docstring namely- a.py, b.py, and c.py. File model a.py is choosen
5 for high level file. It is known as a simple text file of
88
Search on TG: @apna_pdf
statements and can be run from bottom to top when A parameter is a variable listed inside parentheses in
launched. The files are b.py and c.py modules. They also a function definition. This argument is the value that are
count as text files of statements. But they usually don't sent when function is called.
start directly. These characteristics similarly define the By default, a function must be called with the exact
programming structure of Python. In Python, all function
number of arguments. This means that if your function
definitions are given at the top, after which the statement
is also called the top level statement. Python gives a accepts two arguments, you must call the function with
special name to the top level statement as _main_. two arguments, no more or no less.
Python starts program execution from this top level Example–def my-function (frame, Iname):
statement. This is how the statement is executed in print (fname+ " " + Iname)
Python. my-function ("John", "Smith")
• The first statement of a function can be an optional >>> John Smith
statement-function or document string of docstring. If you try to call a function with one or three
Python starts execution from the first line, but if this arguments, you will get an error.
line is a remark, it is ignored by the browser. Example– def my function (fname, Iname):
• The def statement is also read but ignored until called. print (fname+ " " + Iname)
• The actual program execution starts with the first my-function ("Jhon")
statement of the _main_ block.
>>> Traceback (most recent call last):
• When a function is called, the function call passes
function control to the function definition and from File "demo-function-args-error-py",
_main_ the value is passed. lin4, in <module>
• Now the statements in the function body are executed Type Error: my-function ( ) missingl required
and with the return statement or the last statement of positional argument: 'Iname'
the function body, control returns to the statement Following are some points about function criteria–
from which the function was called. • A function can have any number of parameters or may
• Print statement executes and displays the result. not have any parameters at all.
Example– # program for exponent (power) • Default values can be defined for any or all
# calculation parameters.
def calculate power (N, X) : • While defining a function, its parameters have to be
P=1 defined as well.
for i in range (1, x + 1) : Some important information to define the arguments
P = P*N are as follows–
return P • The arguments are passed to the function call.
N, X = 2, 3 • If the parameter has a default value, no argument has
Print (Calculate Power (N,X)) to be given.
N, X = 3, 4
• Can pass an argument as a literal or name.
Print (Calculate Power (N,X))
Output: 6.10 Types of Arguments:
8 Arguments are the types of information that can be
81 passed to a function. Arguments are specified in
parentheses. We can give any number of arguments as
6.8 Docstring: per our choice but they have to be separated by commas.
Docstring or documentation string provides a
Example–a function that accepts a string as an argument.
convenient way to associate documentation with Python
modules, functions, classes, and methods. It is specified # defining the function
in the source code, to be used as a comment to document def function (name):
a specific segment of code. Unlike traditional source print ("Hi", name)
code, a docstring describes what a function does, not # Calling the function
how. All functions must have a docstring, this allows the func ("Devansh")
program to inspect these comments at run time, for Output: Hi Devansh
example in the form of an interactive help system or There can be many types of arguments in Python
metadata. function which can be passed at the time of function
A docstring line must begin with a capital letter and call–
end with a period. Docstrings are declared using triple or (i) Default Arguments– In Python, when we assign
double quotes immediately below the class or function a default value to the parameter while creating the
declaration. All functions must have a docstring. function then it is called Default Argument. The
6.9 Function Parameter and Arguments: assignment operator is used to assign default values to
In Python parameter and argument can be defined to the parameters. While calling the function, if we do not
do same thing. Information passed to a function is called pass the value to the parameters given in the function
a parameter or argument. definition, then it takes the default value.
89
Search on TG: @apna_pdf
Example– Source Code Output: Call 1
def func (name = "Python", Module = 3) : 5
# default argument Hello World
Print (name) Call 2
Print (module) Hello World
Print ("Call 14 Function : ") 5
func ( ) If the argument is not given on the Python function
Output: call, then the exception of Type Error displays.
st
Call 1 Function: Source Code:
def Reg Arg (num, str):
Python
print (num)
3 print (str)
(ii) Keyword Argument– Keyword argument is Reg Arg ( )
used to change the position of parameter like if we have Output:
passed two parameters to the function then we can Reg Arg ( )
change their position at the time of function calling. Type Error : Reg Arg ( ) Missing 2
Argument value can be passed by a keyword. Both Required positional arguments 'num' and 'str' even if
positional and keyword arguments can be used together. two argument values are passed to the function it
But first positional argument and then keyword argument displays Type Error exception.
should be taken, otherwise error message is displayed. Source Code:
def Reg Arg (num, str):
Example– Source Code: print
def keyArg (int, float, str) : print (str)
Print ("int : ", int) Reg Arg (5)
Print ("float : ", float) Output:
Reg Arg (5):
Print ("string : ", str) Type Error: Reg Arg ( ) missing 1
Print ("call 1") required positional argument :
keyArg (int = 10, float = 1.5, str = "H") Variable Argument– The importance of arguments'
increases significantly when 'Number of arguments' is to
Print ("call 2")
be used as arguments on the definition of the function.
keyArg (float = 2.8, int = 20, str = "G") At some point of time it is not known how many
Print ("call 3") 'Number of arguments' to pass to the function. At such
keyArg(str = "R", float = 8.6, int = 5) times '*' (asterisk) is used before.
Output : The argument given on Function definition is like
'tuple'.
Call 1
Source Code:
int : 10 def Multi Arg (* arg Tuple):
float : 1⋅5 print (argTuple)
string : H print (argTuple [0])
Call 2 print (argTuple [1])
int : 20 print (argTuple [2])
float : 2.8 for i in arg Tuple:
string : G print (i)
Call 3 MultiArg (5, 10, "Hello")
Output: (5, 10, "Hello")
int : 5
5
float = 8.6 10
string = R Hello
(iii) Required Argument– In this, it is mandatory 5
to pass arguments on the function call. When an 10
argument is pass at a function definition, then it is Hello
required to give its value at a function call. Source Code:
Example– Source Code: def Multi Arg (* arg Tuple):
def Reg Arg (num, str) : print (argTuple)
print (num) print (argTuple [0])
print (str) print (argTuple [1])
print ("call 1") print (argTuple [2])
Reg Arg (5, "Hello World") for i in arg Tuple:
Print ("Call 2") print (i)
Reg Arg ("Hello World", 5) MultiArg (5, 10, "Hello")
90
Search on TG: @apna_pdf
Output: (5, 10, "Hello") Instead of creating an entire function whenever you
5 need a single expression logic, you can create a lambda
10 function. For example, you want to calculate and assign
Hello the value of an object. In this case, you can evaluate that
5 value by lambda function and after that its object can be
assigned.
10
Can be Pass as an Argument to Another
Hello
Function, since a lambda is a function object, you can
6.11 Anonymous Function: also pass a lambda function as an argument to another
The concept of anonymous function is available in function. In such a case the value returned by the
almost all popular programming languages. In many expression and held by the object will act as an
programming languages, they are also called Lambda argument.
Expressions. In any programming language, it is not Lam Obj = Lambda ×1, ×2: ×1+2 def
necessary that Lambda Function and Anonymous my function (Lam Obj) :
Function are the same thing. An Anonymous Function Print ("Sum is" + Lam Obj)
belongs Lambda category only when that function Lambda functions in Python is mostly used in filter
returns an Object and can be passed as an argument. ( ), Map ( ) and reduce ( ) fuction as arguments.
Lambda functions and anonymous functions are the same Filter ( ) Function– Filter is a function in Python
thing in Python. which is used to filter and extract data from a list on the
Defined Anonymously– Lambda Functions are basis of logic. In this function, you pass a function and a
defined anonymously without any name. You assign list as arguments. The logic is performed with all the
them to an object and they are used by the same object items in the list. The item that conforms to that logic is
name. This eliminates the need to write functions with stored.
arguments using multiple keywords. Thus all items that satisfy that logic are returned. For
Lambda Keyword– In Python, the normal function example you want to list all list items which are multiple
is defined by the def keyword, the lambda function is of 3, then in this case by lambda function this can be
defined by the Lambda keyword. done in this way;
Lambda <arguments>: My List = (2, 3, 4, 6, 8, 9, 10, 12)
expression result-List = list(filter(lambdax:x%3= = 0, My List))
After many changes to the lambda keyword, more // return 36912
methods can be defined which is similar to a normal Here lambda function will be more fit than normal
function in Python. You can pass any number of function. Because you will not need to create a function
arguments to the lambda function as per your choice. separately. Where ever you can need it, you can define it
lambda <×1, ×2, ×3, ×4.....×N>. in a single line.
<Expression>: 6.12 Return Statement:
Expressions can be defined by placing a colon (:) # python program to demonstrate return statement
after only single expression arguments, to this expression def add (a,b):
you understand like the body of the function. # returning sum of a and b
lambda <×1, ×2, ×3,......×N:<single expression> return a + b
Only a single expression can be defined in a lambda
def is _ true (a):
function. Syntax of lambda function does not allow to
# returning boolean of a
use multiple expressions. This is the reason why lambda
return bool (a)
function is also called one line function.
No Return Statement– Like a normal function, # calling functon
there is no return statement in the lambda function. res = add (2, 3)
defined single expression is evaluated and its result is Print ("Result of add function is {}". format (res))
automatically returned. Output:
When a function object is required, an object is Result of add function is 5
assigned by defining a lambda function. After this, you Result of is _ true function is True
use the lambda function through that object itself and The return statement is used at the end of a function,
there is a function object. which returns the result of the function. It ends function
Obj = lambda <×1, ×2, ×3,......×N>: execution and transfers the result to where the function is
<expression> called. return statement is not used outside the function.
In this way, you can use lambda function wherever Syntax– return [expression-list]
you need a function object. It can contain an expression which is evaluated and
Single Use Function– Lambda functions are single the value is returned to the caller function. It does not
use functions. So you create them only where you need return an object if the return statement has no expression
them. These are also called Throwaway Functions. or not present in the function itself.
91
Search on TG: @apna_pdf
Call by reference initialized, it stores if the global variable is
Call by reference in Python means passing the actual garbage value. not initialized.
value as an argument to the function. Reference all It is created when the It is created before the
functions that is, all changes made to the reference inside execution of the function global execution of the
the function are returned to the original value by starts and ends when the program and gets
reference. function terminates. destroyed when the
6.13 Global and Local Variables: program terminates.
Variable scope is a part of any variable where it can The data of a local Multiple functions can
be accessed after it is defined. There are two types of variable can be accessed access the same global
variables in Python– by only one function. variable.
(i) Local variables are inside the function, their Passing parameters is Passing parameter is
visibility is only inside the function, by moving outside necessary to access the not necessary as it
the function get destroyed. value in a local variable to remains visible
Source Code: another fuction. throughout the
def fun (c) : program.
a=5 # local variable Modifying the value of a Modifying the value of
print (a) local variable in one a global variable in a
func (c) function does not affect function affects the
print (a) the other function. entire program.
Output: 5
Trace back (most recent call last): Local variables are stored The global variable is
Print (a) on the stack, unless stored at a fixed
Name Error : name 'a' is not defined specified. location decided by the
compiler.
(ii) Global variables are outside, function. Their 6.14 Void Function:
visibility is inside and outside the function. Their is Void functions are those which do not return any
scope on the whole program of Global variables. value after completion of their computation. This type of
Source Code: function is used when the calculation is not required in
a = 10 # global variable the actual program. These types of functions perform
def func ( ): tasks that are important for the successful running of the
print (a)
program, but do not provide any specific value to be used
func ( )
in the program.
print (a) Example– def add (num1, num 2):
Output: 10 print ("sum is", num1 +num 2 )
10 return-val = add (300, 500) print (return-val)
In the example both local and global variables are Output: sum is 800
declared. Variables outside the function are global and None
variables inside are local. The scope of the global 6.15 Library Function:
variable is inside and outside the function, but due to the The standard library in Python is a set of built-in
separate variable declaration inside the function, the modules that are part of the core programming language.
value of the variable changes as soon as func ( ) is called. Python functions can be used for common programming
Source Code: tasks.
a = 10 # global variable input ( )– In Python programs, input ( ) is used to
def func ( ) : take any kind of data input from the user through the
a = 5 # local variable keyboard. This function reads the data entered by the
print (a) user and assigns it to the variable. If you want to show a
func ( ) # print local message to take input from the user, then for that the
print (a) # print global prompt string (message) has to be written in the
Output: 5 parenthesis ( ) of input function. Writing prompt in input
function is optional.
10
This function only reads strings. User can input data
Following are the differences between global and of any type (int, float etc.) but all input function takes the
local variables– input value as a string only.
Local variable Global variable Example– Source code:
It is declared inside the It is declared outside a = input ("Enter a number : ")
function. the function. Print ("your number : ", a)
If a local variable is not Stores zero by default b = input ("Enter your name : ")
92
Search on TG: @apna_pdf
Print ("your Name : ", b) Output: 2
c = input ("Enter your height :") find ( )– In the find ( ) function, the given substring
Print ("your height : ", C) is searched in the main string and its first index is
Print ( )–To print (output) any type of data on the returned. The syntax of find ( ) is as follows–
computer screen (console) in Python, use the print () Syntax: str find (substr, start, end)
function. Message can be a string or any other object, the substr– Here is the sub string, which will be found
object is converted to a string before being written to the in the main string.
screen. Example– Source code:
The syntax for print function is as follows– Source code:
Syntax : Print (Value1, Value 2........,sep = ' ' , str = "Hello World"
end = '\n', file = Sys·Stdout, flash = False) Print (str·find ("0"))
Values– Those values, variables or expressions are Print (str·find ("0", 6))
written which want to be printed. Print (str·find ("0", 2, 5))
Sep– When printing more than one value, all those Output: 4
values are separated by space because the default value
of Sep parameter is space. If you want to separate all the 7
values by any value other than space, then it is necessary 4
to specify Sep parameter in print ( ). rfind( )– In the rfind ( ) function, the given substring
end– The value given in this parameter will be is found in the main substring and its last index is
appended to the end of the last value that you are printing returned. syntax of rfind ( ) is as follows–
on the screen. Its default value is 'n', due to which your Syntax– str⋅rfind (substr, start, end)
output ends with a new line. substr– Here is a sub string, which will be found in
Next print ( ) Function's output is printed in newline. the main string.
Example– a = 5 Start– Here is the starting index, if no value is given
b=2 then it is 0 by default.
c = "Python" end– Here is the ending index, defaults to the length
Print (a, b, c, sep = '_', end = '@\n') of the string (len (str)) if no value is given.
Print (a, b, c sep = ' , ', end = 'Hello') Example– Source code:
Output : str = "Hello World"
5_2_Python@ Print (str·rfind ("l"))
5,2, Python Hello Print (str.rfind ("l", 2, –3))
eval ( )–This function converts a string into an Output: 9
object with a valid expression. Syntax for the eval 9
function is in this type– 3
Syntax: eval (expression, globals, locals) Capitalize ( )– It is used to convert the first
expression–It takes a string that is to be evaluated as character of the first word of the string to upper case.
a Python expression. The syntax of capitalize ( ) is as follows–
Globals–This is an optional parameter. It is a Syntax: str capitalize ( )
dictionary to specify global values and variables. It doesn't have any parameters.
Local– that is also an optional parameter. We use Example– Source code:
another dictionary to specify the available local methods str= "hello world"
and variables. Print (str.capitalize ( ))
Example– x = 5 Output: Hello world
Print (eval ('x + 1') title ( )– The method returns a normal string
Output : 6 converted to a title string in which the first character of
6.16 String Function: each word is uppercase. The syntax for title string
Python has several in-built functions that are function is as follows–
associated with the string data type. They provide the Syntax– str-title ( )
facility to manipulate strings. Some of the string The title function takes no parameters.
functions available in Python are as follows– Example– Source code:
Count ( )– The Count ( ) method is used to return str 1 = "hello world"
the occurrences of the given item in the list. The syntax Print (str 1-title ( ))
for Count ( ) is as follows– Output: Hello World
Syntax: list count (item).
item–The item whose occurrences are to be returned lower ( )– In the lower ( ) function, the uppercase
in number is given here. character or string is converted to lowercase. The syntax
Example– Source code: of lower ( ) is–
list = ["H", "e", "l", "l" "O"] Syntax– str.lower ( )
Print (list·count ("l")) There is no parameter for the lower( ) function.
93
Search on TG: @apna_pdf
Example– Source code: istitle ( )– Returns a boolean value (True or False)
Print ("Hello World"·lower ( )) by checking whether the given string is a title string in
Print ("HELLO WORLD"⋅lower ( )) the istitle ( ) function. The syntax of istitle ( ) is as
Output: follows–
hello world Syntax– str.istitle ( )
hello world istitle ( ) function does not take a parameter.
Upper ( )–This function converts a lowercase Example– Source code:
character or string to uppercase. The syntax of upper ( ) Print ("Hello World"·istitle ( ))
is as follows– Print ("Hello world"·istitle ( ))
Syntax– str-Upper ( ) Output: True
There is no parameter for the Upper ( ) function. False
Example– Source code:
replace ( )– The replace ( ) function returns a copy
Print ("Hello World"-Upper ( ))
of the string by replacing all occurrences of the given
Print ("Hello World"-Upper ( ))
Print ("hello 123". Upper ( )) substring with the new substring. The syntax of replace()
Output: HELLO WORLD function is as follows–
HELLO WORLD Syntax– str⋅replace (oldsubstr, newsubstr, max)
HELLO 123 oldsubstr–The substring to be replaced in the
oldsubstr string is given here.
Swapcase ( )– The Swapcase ( ) method returns a Newsubstr– The substring to be replaced with the
string that converts all uppercase characters of the string replaced substring is given here.
to lowercase and all lowercase characters to uppercase. max– This is an optional parameter. The maximum
Syntax for swapcase ( ), number of replacements to be made from the beginning
Syntax: str-swapcase ( ) of the string is given here.
The swapcase ( ) function takes no parameters and Example – Source code:
returns the swapcased string as the return value. str = "Hello World Hello Ramesh "Hello Friends"
Example– Source code: Print (str-replace ("ello", "ii"))
Print ("Hello World" · Swapcase ( )) Print (str-replace ("ello", "ii", 2))
Print ("hello 123"·Swapcase ( ) Output: Hii World Hii Ramesh Hii Friends
Output: hELLO wORLD Hii World Hii Ramesh Hello Friends
HELLO 123 strip ( )– strip ( ) function strips the given character
from left side (leading characters) and right side (trailing
islower ( )– Returns the boolean value (True or character), returns a stripped copy of the string.
False) by checking whether the given string or character Syntax– str⋅strip (char)
in the islower ( ) function is in lower case. The syntax for char : This is an optional parameter. The characters
slower ( ) is as follows–
to be stripped in the string are given here.
Syntax : The str⋅lower ( ) Example– Source code:
islower ( ) function does not require parameters.
str 1 = "Hello World"
Example– Source code:
Print (strl+strip ( ))
Print ("Hello"·islower ( ))
Print (str1 *strip ("He"))
Print ("hello"·islower ( ))
Output: Hellow World
Output: False
Hello World
True lstrip ( )– lstrip ( ) function returns a copy of the
isupper ( )– Whether the string or character given in string after stripping the given character from the left
the function is in upper case or not. It checks and returns side (leading character)
a boolean value (True or False) The syntax for isupper is
Syntax– str·lstrip (char)
as follows–
char : (Same as strip)
Syntax: str upper ( ).
There is no parameter for the isupper ( ) function. Example–Source code:
Example– Source code: str = "Hello World"
Print ("Hello"·isupper ( )) Print (" Hello World"·lstrip ( ))
Print ("HELLO 123"·isupper ( )) Output: Hello World
Print ("123 HELLO"·isupper ( )) o World
Output: False rstrip ( )– rstrip ( ) function copies the string by
True stripping the given character from the right side (trailing
True characters)
94
Search on TG: @apna_pdf
Syntax– str⋅rstrip (char) Example– Source code:
char : This is an optional parameter. The characters Print ("Hello 123"⋅ isalnum ( ))
to be stripped in the string are given here. Print ("@" ⋅ is alnum ( ))
Example– Source code: Output: True
str = "Hello World" False
startswith ( )– Returns the boolean value by
Print ("Hello World ")
checking the given Profit at the end of the string in the
Print ("Hello world rstrip( )) startswith ( ) function.
Print (str·rstrip ("ld") Syntax– str⋅startswith (prefix, start, end)
Output: Hello World Prefix– Here Prefix is given in Prefix or tuple.
Hello Wor Start: It is an optional parameter. This is the starting
Hello World position from where the prefix is checked in the string.
join ( )– In the join ( ) function, the sequence of end: This is also an optional parameter, it is the last
given elements is returned to the string by any operator. position. As far as Prefix is checked in the string.
Syntax– str join ( ) startwith ( ) function is case sensitive.
join ( ) function Example– Source code:
Example– Source code: str = "Hello World"
sep = "$" Pre Tup + ("Hello", "World")
str = "Hello" Print (str·starts with (Pre·Tup))
Print (sep·join (str)) Output: True
Output: H $ e $ l $ l $ 0 endswith ( )– Returns a boolean value by checking
isspace ( )– The isspace ( ) function returns a the given Suffix at the end of the string in the endswith( )
Boolean value (True or False) is returned. function.
Syntax–str⋅isspace ( ) Syntax– str·endswith (Suffix, Start, end)
No parameter is required for the isspace ( ) function. Suffix– Here Suffix is given in Suffix / Tuple.
Example– Source code: Start: It is an optional parameter. This is the starting
Print ("Hello World"·isspace ( )) position from where the suffix is checked in the string.
Print ("\t"·isspace ( )) end: It is also an optional parameter, it is the last
Print (" " · isspace ( )) position. As far as the Suffix in the string is checked.
Output: False Example– Source code:
True str = "Hello World"
True Suf Tup = ("Hello", "World")
isalpha ( )– returns true if the character or string in Print (Str·ends with (Suf Tup))
isalpha ( ) is alphabetic, otherwise it returns False. Output: True
Syntax– str·isalpha ( ) encode ( )– The encode ( ) function encodes a string
using the specified encoding. If no encoding is specified,
The str isalpha ( ) function does not take a
UTF-8 is used.
parameter.
Syntax– string·encode (encoding = encoding, errors =
Example–Source code:
errors)
Print ("Hello 123" · isalpha ( ))
encode– This is an optional parameter, but UTF-8 is
Print ("Hello" · isalpha ( )) used if no encoding is specified.
Outpu: False errors : This is also an optional parameter. The string
True specifies an error method whose value–
isdigit ( )– If character or string is a digit in the 'backslashreplace'– uses a backslash instead of a
isdigit ( ) function, it returns True, otherwise it returns character that cannot be encoded.
False. ignore'– Ignores characters that cannot be
Syntax– str⋅isdigit ( ) encoded.errors)
isdigit does not have a parameter. name replace– replaces the character with text that
Example– Source code: explains the character.
Print ("1234"·isdigit ( )) 'Strict'– default, returns an error on failure.
Print ("1234 Hello"·isdigit ( )) replace– replaces the character with a question mark.
'Xmlcharrefreplace'– replaces the character with an
Output: True
Xml character.
False
Example– Source code:
isalnum ( )– isalnum ( ) function, if the character or
str 1 = "Hello World"
string is alphanumeric or alphabet or numeric, it returns
True, otherwise it returns False. Print (String encode (encoding = "ascii",
Syntax– str·isalnum ( ) errors = 'backslashreplace'))
The isalnum ( ) function does not take parameters. Output: b 'Hello W \\xe5nr/d
95
Search on TG: @apna_pdf
decode ( )– The decode ( ) function is opposite of Metacharacter Description
encode. It takes the encode of the encoding string to
decode it. This function accepts encode and returns the [] It represents the set of characters
original string. \ It represents the special sequence
Syntax– decode (encoding, error) ⋅ It singals that any characters is
Example– Source code: present at some specific place
str = "geeksforgeeks"
str_ene = str·encode (encoding = 'UTF 8') ^ It represents the Pattern present at
Print ("The encoded string in base 64 format is the begining of the string.
: ",) $ It represents the pattern present at
Print (str_enc) the end of the string
Print ("The decoded string is : " ,)
* It represents zero or more
Print (str_enc·decode('utf8','strict'))
occurrences of a pattern in the
Output:
string
The encoded string in base 64 format is :
z2vla3Nmb3JnZW Vrcw = = + It represents one or more
The decoded string is : geeks for geeks occurrences of a pattern in the
6.17 Pattern Matching: string
Pattern matching means to find whether the inputted {} The specified number of
substring is available in another string or not. For this, occurrences of a pattern string.
each character of an array has to be matched with each | It represents either this or that
character of the substring. Regular expressions are a character is present
method used for matching text patterns in the Python
programming language. Regular expressions are called () Capture and group
REs or regexes, or regex patterns. A Matches a single character, except
The 're' module provides regular expression support a newline
that is embedded in every Python installation. Syntax for
\t, \n, \r, \f Tab, newline, return, form feed
regular expression is search as follows–
match = re·search (Pattern, string) {m, n} Matches the preceding characters
re·search ( ) method takes two arguments– A regular minimum m times and maximum n
expression pattern and a string. If pattern is found in times
string, then search ( ) returns the match object otherwise ? Checks for exactly zero or one
it returns none.
character to its left.
Example– # Need Module 're' for regular Expression
# import re Example– # Demo of ⋅metacharacter
Search_string = "Youth Competition import re
Times" str1 = "Hello world"
Pattern = "Youth" if re⋅search (r".....", str1):
match = re·match (pattern, search ( ) print (str1 + "has length > = 5")
tets if it Succeeded else:
if match : print (str1 + "has length < = 5")
Print ("regex matches:", RUN
match·group ( )) >>> Hello world has length > = 5
else : 6.17(ii) Special Sequence:
Print ("Pattern not found) Python also gives us the facility that we can use any
Output: escape sequence character in any string. When Python
regex matches : Youth displays that string, it interprets all escape sequences and
Many methods are available in Pattern object like– replaces them with their original values. This means "\t"
match ( ), search ( ), findall ( ), finditer ( ) for Tab, "\n" for Newline, "\0" for Null, etc.
6.17(i) Metacharacter: Special
Meta characters are considered as the building Sequence Description
blocks of regular expressions. Regular expressions are Character
patterns that are used to match character combinations in \A Returns a match if the specified
strings. Every character in a regular expression is either a characters are at the beginning of the
metacharacter or a regular character. Metacharacters
string.
have a special meaning. They are not used to match a
pattern but to define some rules to search for a specific \b Returns a match where the specified
pattern in the statement. Metacharacters are also known characters are at the beginning or at the
as operators, signs, or symbols. end of a word.
96
Search on TG: @apna_pdf
\B Returns a match where the specified Syntax– math⋅pow (x,y)
characters are present, but NOT at the x– number is given
beginning (or at the end) of a word. y– number is given.
\d Returns a match where the string Example– Source code:
contains digits (numbers from 0-9) import math
\D Returns a match where the string DOES Print (math·pow ( 3, 2))
NOT contain digits. Print (math·pow (5, 3))
\s Returns a match where the string Output : 9.0
contains a white space character. 125.0
\S Returns a match where the string DOES round ( )– The round ( ) function normally rounds a
NOT contain a white space chaacter. floating point number to the nearest integer number and
returns that result as a float.
\w Returns a match where the string
Syntax– round (number, digits)
contains any word characters
number– The number to be rounded.
(characters from a to z, digits from 0-9
digit– This is optional. The decimal number used
and the underscore character)
when rounding the number off. It's default is 0.
\W Returns a match where the string DOES Example– Source code:
NOT contain any word characters. Print (round (10.00,1));
\Z Returns a match if the specified Print (round (23.2323;3));
chaacter are at the end of the string. Output: 10
6.18 Numerical Function: 23.232
Python has some in-built modules like– math int ( )– This ( ) function converts the specified value
module, math module contains some functions related to to an integer number.
mathematics. like– sin, cos, sqrt, power ( ) etc. Syntax– int (value, base)
Many mathematical operations can be perform Value– A number or string that can be converted to
easily in Python by importing the math module. an integer number.
The numeric functions available in Python are as Base– A number representing the number format,
follows– the default value is 10.
eval ( )– This function converts a string into an Example– Source Code:
object with a valid expression. Syntax for eval function x = int ("182")
is as follows– Print (x)
Syntax: eval (expression, globals, locals)
Output: 182
ceil ( )– This function returns the ceiling value of the
max ( )– The max ( ) function is used to return the
number given in the math function.
max value from a set.
Syntax– max ( ) Syntax– math⋅ceil (x)
There is no parameter for max ( ) function. x– Number is given here. When given a floating
Example– Source code: point number, it is rounded to an integer value greater
than that.
str = {"H", "e", "l", "l", "O", " ", "W", "O",
"r", "l", "d"} Example– Source code:
Print (max (set)) import math
Output: r Print (math·ceil (4.49))
Print (math·ceil (–4.51))
min ( )– min ( ) function is used to return the min Output: 5
character from a string. –4
Syntax– min (str) floor ( )– The floor ( ) function returns the floor
str : The string from which the character to be value of the given number. If a floating point value is
returned is given here. given then the smallest value is returned.
Example– Source code: Syntax– math⋅floor(x)
str = "Hello World" x– Number is given here.
Print (min (str)) Example– Source code:
⇒ The min ( ) and max ( ) functions return the character import math
according to the ASCII value. Print ("(0.49) : " , math·floor (0.49))
Print ("10.99) : ", math·floor (–0.99))
POW ( )– The POW ( ) function returns x**y. The Output: 0
value of y is the power of the value of x. –1
97
Search on TG: @apna_pdf
SQRT ( )–This function returns the square root of seed ( ) It is used to initialize the random
the given number. number generator.
Syntax– math⋅sqrt (x) shuffe ( ) It can be used for sequence (list,
x– Number is given here. tuple) for allowing the item's position
Example– Source code:
to change randomly
import math
Print (math⋅sqrt (4)) uniform ( ) Floating between two numbers point
Print (math⋅sqrt (5.6)) returns a random value.
Output: 2.0 Example– import random
2.3664319132398464 number_list = [111, 222, 333, 444, 555]
abs ( )– Returns the absolute value of the given # random item from list
argument. Example of using abs ( ) built-in function as print (random choice (number_list))
follows– # Output 222
>>> abs (–4) Example– random . randint ( ) example of generating
4 random number import random.
>>> abs (5.0) # random integer from 0 to 9
5.0 num1 = random . randint (0, 9)
6.19 Random Module: Print (num1)
Random Module is used by Python to generate # Output 5
random numbers. There are some functions to generate # Random integer from 10 to 100
random numbers like Choice ( ), randint ( ), random ( ), num2 = random.randint (10, 100)
uniform ( ) etc.
Print (num2)
random ( ) function returns a random number
between 0 and 1, in floating point value. # Output 84
import random
Syntax of random ( ) module function– # random integer from 0 to 9
random⋅random ( ) num1 = random.randint (0, 9)
It takes no parameters and returns a random number Print (num1)
between 0 and 1 in floating point value. # Output 5
Example– import random
# Random integer from 10 to 100
print (random⋅random ( ))
num2 = random.randint (10, 100)
Output: 0.97326431
Print (num2)
# Output 84
Example– Printing a random value from a list. Example–Simple implementation of sample ( ) function.
# import random
# python3 program to demonstrate the use of sample
import random
( ) function.
# print a random value from the list
# import random.
list1 = [1, 2, 3, 4, 5, 6]
from random import sample
Print (random⋅choice (list1))
# prints list of random items of given length
Output: 2
list1 = [1, 2, 3, 4, 5]
Random Description Print (sample (list 1, 3))
Function Output:
choice ( ) Returns a random number from the [2, 3, 5]
given sequence (list, tuple). import random
randint ( ) Returns a random number between random . seed (10)
given beg (inclusive) and end. Print (random . random ( ))
random ( ) Returns a floating point value: a random . seed (10)
random number between 0 and 1. Print (random . random ( ))
randrange ( ) Returns a random number from the Output:
middle of the given range (beg to 0.5714025946899135
end). 0.5714025946899135
sample ( ) Returns a random item from the list
with the given sequence and length. import random
98
Search on TG: @apna_pdf
def my function ( ): 'time'
return 0.1 Module Description
my list = ["apple", "banana", "cherry"] Function
random . shuffle (my list, my function) epoch local time (Jan 1, 1970 5:30:00
Output: ctime ( ) ctime ( )) and the given seconds are
["banana", "cheery", apple"] added to it and that time is returned in
Example–#python 3 code to demonstrate the working of the string.
# uniform ( ) local epoch local time (Jan 1, 1970 5:30:00)
# for using uniform ( ) time ( ) and the given seconds are added to it
import random and that time is returned in struct-time.
# initializing bounds mktime ( ) Returns the floating-point value of the
a=4 given time-tuple or struct-time in
b=9 seconds.
# printing the random number sleep ( ) Use this function calling thread used to
print ("The random number generated between suspend.
4 and 9 is :", end ="") strptime ( ) According to the given format, the
print (random.uniform (a, b)) string is parsed and returned in struct
Output : time.
The random number generated between 4 and 9 is: strf time ( ) The struct-time returned from time-
7.49493168830411 tuple or gm time ( ) and time' from the
Date and Time Function– Python has a module given format.
called date and time to work with date and time. Some Recursion– Recursion is a method of programming
modules have to be imported for date and time. Some of in which a function calls itself one or more times in its
the modules available in Python are as follows– body.
Time Module: It contains functions, classes and That is, the function in which the same function is
constants related to date and time. called by itself, is called recursion. Recursion is a
Date time Module: In this module also there are process that works like a loop. Recursion requires a
constants, classes, related to date and time. These satisfied condition so that the recursive function stops
modules date and time Object oriented programming is working. The recursive function keeps on calling until
built in to work with. there is no satisfaction and there is a possibility of
Calendar Module: It contains some functions and infinite loop.
classes related to calendar. Example– Source code:
time ( )– The time module contains time ( ) to return def factorial (x) :
the elapsed seconds since January 1, 1970 12:00am. This # This is a recursive function to find the
time ( ) function returns the elapsed seconds in a floating # factorial of an integer
point number. if x = = 1 :
Example– import time return 1
Print ("Timestamp/tick:",time-time ( )) else :
# output: return (x * factorial (x – 1))
# Timestamp:1497628217, 2675047 num = 3
gmtime ( )– epoch is always 12.00am January Print ("The factorial of", num "is",
1,1970. Returns the epoch from gmtime ( ) of the time Output: The factorial of 3 is 6.
module in Python.
Example– import time Recursion is a process in which a function calls
Print ("epoch", time-gmtime ( ))) itself repeatedly. This function is called recursive
Output: function. There are many recursive calls in recursion so
epoch: it is necessary to have a terminate condition to terminate
time⋅strict_time ( it. We cannot apply recursion to all problems, but by
tm_year = 1970, using it we can easily solve some problems.
tm_mon = 1, Advantages of recursion–
tm_mday = 1, (i) It reduces unnecessary function calls.
tm_hour = ( ), (ii) By this we can solve problems easily because
tm_min = 0, iterative solution is very large and difficult.
tm_sec = 0, (iii) It makes our code clean.
tm_wday = 3,
im_yaday = 1, (iv) With the help of recursion, a difficult problem can
tm_isdst = 0) be divided into smaller problems.
asetime ( )– This function returns the current time in
a readable format. Disadvantages of recursion–
Example– Source Code: (i) Programs written using recursion are difficult to
import time understand and debug.
Print (time asetime ( )) (ii) For this we require more memory space.
Output:
Sat Jun 17 23:38:53 2017 (iii) It takes more time to execute the program.
Some other important functions of the time module (iv) Recursive calls are very inefficient as they consume
are as follows– more memory and time.
99
Search on TG: @apna_pdf
Practice Questions with Explanatory Solutions
1. The code block inside each function starts with a Ans. (d) A function is said to be recursive if it calls
............ itself. When working with recursion, we must define a
case. We use base case in a recursive function so that
(a) def keyword (b) Colon (:) the function stops calling itself when it reaches the
(c) parenthesis ( ) (d) None of these base case. Without a base case, the function keeps
Ans. (b) A function is a block of code that contains calling itself until the call is undefined. Recursion
function is easy to write. It is easy to read and
one or more Python statements and used to perform a
understand the code. Every recursive function have
specific task. The code block within each function not need return value, it may or may not return a
begins with a colon (:). function block begins with def value.
keyword, followed by a parenthesis ( ) with the
6. Function is defined as–
function name.
(a) in module (b) in class
2. By using which can we avoid writing the same (c) another function (d) all of the above.
code again and again in program?
Ans. (d) A Python function is a group of statements.
(a) Keyword (b) Macro Every program has a function, where the function is
(c) Function (d) All of the above required, the function is called. A function is defined
Ans.(c) Using functions can avoid writing the same in a class in a module and in another function.
code again and again in a program. The function saves 7. Built-in function is–
programmer time, program space and memory. The (a) len ( ) (b) input ( )
function can be called repeatedly if needed. (c) type ( ) (d) all of the above
3. Which method is it? Which gets all the values Ans. (d) Built-in functions are those functions which
from the dictionary? are pre-defined. Python 3.6 has 68 built-in functions.
(a) Value ( ) (b) swapcase ( ) Like- abs ( ), all ( ), any ( ), bool ( ), bin ( ), bytes ( ).
input ( ), len ( ). type ( ) etc are all built-in functions.
(c) froxenset (s) (d) Unichar (x)
8. Which of the following keyword is used for
Ans. (a) The value ( ) method of a dictionary is a function–
function that retrieves all the values from the (a) Fun (b) Define
dictionary. value method Returns a view object that (c) def (d) all of the above.
displays a list of all the values in the dictionary. It
doesn't take any parameters. Ans.(c) def keyword is used to declare a function in
Python.
4. Find the output of the following Python program. Example– def my_fume(a.b) :
Class ACC: c=a+b
def_init_() : Print (c)
self·id = id Self, id my_func (10, 20)
id = 555 Output : 30
acc = Acc (111) 9. Standard Library Module–
Print acc.id (a) Math module (b) random module
(a) 111 (b) 555 (c) Both (a) and (b) (d) none of these
(c) 666 (d) Error in code Ans.(c) Module is a file which contains collection of
related functions and other definitions. Python has
Ans. (d) The given Python code will output a syntax some in-built modules that you can use or create your
error, which will be missing parenthesis in the call to own modules. Python modules that preloaded with
print. Python are called standard library modules. Three
5. Which of the following statements about such standard library modules are Math module, the
recursion is incorrect? Random module, and Statistics module.
(a) Every recursive function must have a base case. 10. Module files are saved with ........ extension.
(b) Infinite recursion can occur if the base case is not (a) mod (b) ⋅Py
specified appropriately. (c) both (a) and (b) (d) all of the above.
(c) A recursive function makes the code easier to Ans.(b) Module is a file with ⋅py extension that
understand. contains Python definitions, functions, variables,
(d) Every recursive function must have a return classes and statements that users can reuse in different
value. codes of their programs.
100
Search on TG: @apna_pdf
11. math⋅sqrt(121) returns– Ans.(c) The statement invokes a function call. A
(a) 7.0 (b) 8.0 function in a programming language is a group of
(c) 11.0 (d) none of these statements. The name of a function block is unique
throughout the program. If we have to execute any
Ans.(c) math-sqrt ( ), This match function returns the code repeatedly in a program, then instead of writing
square root of the given number. Its syntax is math- that code again and again, that code is written in a
sqrt(x). where the number is given in parameter x. function block so that whenever that code is needed in
math-sqrt(121) will return 11.0. the program, you can make direct function calls. This
12. Capitalize ( ) method returns a string containing– increases the readability of the program and consumes
less memory space.
(a) first character upper case
(b) entire string uppercase 18. Which method returns a string where the first
character in each word is upper case?
(c) last character upper case
(a) title ( ) (b) Capitalize ( )
(d) none of these
(c) Zip ( ) (d) bin ( )
Ans. (a) Capitalize function is used to convert the first
character of the first word of the string to uppercase. Ans.(a) title ( ) method returns a normal string
converted to a title string in which the first character
For this str⋅capitalize ( ) syntax is used. There is no
in each word is upper case. The syntax for title string
parameter for capitalize ( ).
function is as follows–
The Capitalize ( ) function returns the complete
Syntax– str-title ( ) The title function takes no
string by converting the first character of the first
word of the string to uppercase as the return value. If parameters.
the first character of the string word is an uppercase or 19. What are the functions of input ( ) eval ( ) and
numeric value or special symbol, returns original print ( )?
string value. (a) lambda (b) non recursive
13. Which of the following removes the space on the (c) iterator (d) library
right side of the string– Ans.(d) Python has a large library of standard
(a) Strip (b) lstrip functions that can be used for common programming
(c) rstrip (d) none of these tasks. inputs ( ). eval ( ) and print ( ) are library
Ans. (c) In rstrip ( ) function, strip the given character functions.
from the right side (trailing characters) and return the 20. Recursive functions generally take up ……
copy of the string. The str-rstrip (char) syntax is used memory space as compared to non-recursive
for the rstrip ( ) string function. It strips the given functions.
character from the right side of the string and returns a (a) less (b) more
copy of strip. If there is no strip, it returns the original (c) equal (d) none of these
value.
Ans.(b) Recursive functions generally consume more
14. Which method takes a string as an argument and memory and time than non-recursive functions.
returns its equivalent string? debugging is also difficult recursion functions.
(a) str ( ) (b) Value ( ) 21. What is the output of the following code?
(c) SwapCase ( ) (d) Froxenset ( ) def add (a, b):
Ans.(a) The str ( ) function takes an argument and return a + 5, b+5
returns a string equal to it.
result = add(3,2)
15. Which function converts an integer to an octal print(result)
string in Python?
(a) 15 (b) 8
(a) Unichar (x) (b) Sub ( )
(c) (8,7) (d) Error
(c) Value ( ) (d) oct (x)
Ans. (c) def add(a, b):
Ans. (d) oct(x) function is used to convert an integer
return a+5, b+5
to octal.
result = add(3,2)
16. Converts a value to integer-
print(result)
(a) Value ( ) (b) int ( )
a will print (8, 7) in the output as the value of a is 3
(c) Sub ( ) (d) none of these and the value of b is 2, after adding 5 to both the
Ans. (b) int ( ) converts a value to an integer. Integer values the values are 8 and 7.
data type is normal numeric values. Integer numbers 22. How is a function declared in Python?
do not have a fractional part. (a) def function function_name ( ):
17. What does the statement function invoke? (b) declare function function_name ( ):
(a) network (b) message (c) def function_name ( ):
(c) call (d) data (d) declare function_name ( ):
101
Search on TG: @apna_pdf
Ans. (c) The function keyword begins with 'def' (c) Hello
followed by the function name and the quotation World, World,World, World, World
marks ( ) and the input parameters or arguments in
parentheses inside should be placed and also define (d) Hello HelloHelloHelloHelloHello
the parameters inside these parentheses. Ans. (a) : Output on running the given python code
23. How many numbers will be printed by the Hello
following code? WorldWorldWorldWorldWorld
def fun(a, b): Hence, option number (a) is the correct answer.
for x in range(a,b+1): 26. What is the output?
if x%3==0: def calc(x):
print(x, end+" ") r=r*x**2
return r
fun(100, 120)
print(calc(5))
(a) 7 (b) 8
(a) Error (b) 50
(c) 6 (d) 9 (c) 100 (d) 20
Ans. (a) : def fun(a, b): Ans.(a) The given python code will generate error-
for x in range(a,b+1): Unboundlocal error: Local variable r referenced before
if x%3==0: assignment.
print(x, end+" ") 27. What is the output of the following code?
fun(100, 120) def fun (a, b=6):
Output–102, 105, 108, 111, 114, 117, 120 a=a+b
Therefore, seven numbers will be obtained. print(a)
fun(5, 4)
24. What is the output of below program?
(a) 11 (b) 9 (c) 5 (d) 4
def maximum(x, y):
Ans. (b) : def fun (a, b=6):
if x > y: a=a+b
return x print(a)
elif x == y: fun(5, 4)
return 'The numbers are equal' The given python code will store 5 in variable a and 4 in
else: variable b so will get 9 as output.
return y 28. Function defined to achieve some task as per the
print(maximum(2,3)) programmer's requirement is called a_______.
(a) 2 (a) user defined function
(b) 3 (b) Library function
(c) built in functions
(c) The numbers are equal
(d) all of the above
(d) None of the options
Ans. (a) User defined function is declared by the
Ans. (b) : def maximum(x, y): programmer to achieve some task as per the
if x > y: requirement of the task.
return x Built in functions– Built in functions are those
elif x == y: functions which are already present in that language,
return 'The numbers are equal' user can use it by proper syntax.
else: Library Function – It is a function which is found in a
return y particular library.
print(maximum(2,3)) 29. What will be the output of the following?
The output of the given step code will be 3, because def iq(a,b):
only the 3rd statement will be executed. if(a==0):
return b
25. What is the output of below program? else:
def say(message, times = 1): return iq(a-1, a+b)
print(message * times) print(iq(3, 6))
say('Hello') (a) 9 (b) 10
say('World', 5) (c) 11 (d) 12
(a) Hello Ans. (d) The given Python code will return (print) 12 in
WorldWorldWorldWorldWorld the output. In this the iq() function will act like a
(b) Hello recursive function, which will call itself until the first
World 5 statement of the function is not executed.
102
Search on TG: @apna_pdf

7 FILE PROCESSING

7.1 Concept of Files: 7.2 To open file in Different Modes:


When any data is written on the computer then it is Python also provides support for file handling, like
first stored on its RAM (Random Access Memory) and all popular programming languages, there are many
when the computer is turned off then all the data is methods available in Python for this.
destroyed and when that data is saved then that computer There are many advantages to file handling ability
gets stored permanently on the secondary storage device. provided by Python. You can access and modify the files
A file system is a location on storage that records available on the disk.
data for later access. It is used to store data permanently A lot of data which is not possible to be enter
for future use by performing various file operations like manually, can be read as input directly from file. A lot of
read, write, open etc. The unique file name and path are data which is not possible to see on the screen can be
used by the users to access the file for reading, writting easily stored in a file and can be analyzed later.
and modification.
The access mode in a Python file determines the
File processing in Python occurs in following order–
mode in which the file can be opened, read, or write,
• Open the file.
appended. File open modes of Python are as follows–
• Use the handle to perform read or write operations.
• Close the file.
Access Description
7.1(i) Types of Files: Mode
There are two types of files in Python–
• Text File It creates a new file with the specified
• Binary File Û name. When a file exists with the
Text files are those files which we can easily same name, it displays an error.
understand. These are usually in form of alphabetic b b mode, opens the file in binary mode
numbers and special characters or symbols. Text files (Binary)
include rich text files and plain text files. w mode opens a file to only write. If a
Binary files store data in sequences of bytes. Binary file exists, then it will write the file.
w
files store data in the form of 0 and 1's, which is, Pointer is at the beginning of the file.
machine readable format. (write)
Following are the differences between text and
binary files– ab+ 'ab+' access mode opens a file for both
(append read and write in binary format. If the
Text File Binary File
and Read file exists, the pointer remains at the
Displays bit characters in Bit represents custom data in binary) end of the file. If the file does not exist,
a text file. in the binary file. it creates a new file for read and write.
a in 'a' access mode file is opened for
Text files are not prone The binary file gets
to corruption and small corrupted even with a (append) appending. if file first exists reaches
changes in it, do not small bit change. then without removing the data it
make any difference. reaches to the end of file and if the file
no longer exist a new file is created.
In a text file data is Data can be stored in a rb+ rb + (read and write in Binary), opens
stored in the form of different way in a binary file for reading and writing in binary
plain text only. file. (read and
write in format. The file pointer is present at the
⋅txt and ⋅rtf is most Any application extension binary) beginning of the file.
commonly used as an can be used in binary. r r(read) access mode is default. Opens
extension in text files.
(read) the file for reading. It starts reading
the file from the beginning i.e. the
pointer is at the starting position of the
Text file is helpful for The binary file is not file.
the user to read. helpful in reading for
user. ab file is opened for appending in binary
(append in format. If the file already exists, then it
Examples of text files Examples of binary files binary) reaches the end without removing the
are Python source code, are executable files, data and if the file does not exist, a
HTML files, etc. images, audios, etc. new file is created.
103
Search on TG: @apna_pdf
a+ The file is opened for appending and File name: Along with the file name, its extension is
(append reading. If the file already exists, it also given here. If there is a file at same location then
and read) reaches to the end without deleting the there is no need to povide path to it.
data and if the file does not exist, a mode: Here the mode is given to open the file like -r,
new file is created. rb, rb+, w wb, a etc. If mode is not given, the default
(reading) mode is used.
rb The file is opened for reading in binary
Example– file = open ('textfile·txt') # default mode is r
(read in format. This happens at the beginning
of the file. # or
binary)
file = open ('textfile·txt', 'r')
r+ The file is opened for reading and
(read and writing. Pointer becomes at the Example– # opens the file youth⋅txt in read mode
write) beginning of the file.
f = open ("youth⋅txt", "r")
wb The file is opened for writing in binary print ("file is opened successfully")
(write in format. If the file already exists then it # output
binary) is overwritten and if the file does not File is opened Successfully
exist then a new file is created.
w+ Opens the file for reading and writing The method is used to read the data of the file. The
(write in if file already exists then it is syntax used for this is as follows–
binary) overwritten else if file does not exist, Syntax– fileObj⋅read (Size)
new File is created. The parameter Size is optional. The size of data to
wb+ The file is opened for reading and be taken is given here. If size is not specified, data is
(write in writing in binary format. If the file read till EoF (End of File). Even if invalid value is given
Binary) already exists, it is overwritten and if on size, it will read data till End of File.
the file does not exist, a new file is Example– Source Code:
created. File = open ("textfile·txt", 'r')
Print (file·read ( ))
7.3 To Open and Read files:
file·close ( )
Like all popular programming languages, Python
output :
also provides support for file handling. For this there are
Hello Python # file content
many methods available in python. There are many
In the above example the file is opened in read mode
advantages to the file handling ability provided by and read ( ) method is used to read the data of the opened
Python. For example, you can view access and modify file and later the file is closed.
the files available on the disk. Lots of data which is not The read (n) readline (n) and readlines ( ) methods
possible to insert manually can be read as input directly are used to read a file in Python. Where n is the number
from the file, a lot of data which is not possible to see on of bytes to be read.
screen can be easily stored in file and analyzed later. 7.4 To Close a File:
Before Python can perform any operations (read, write, The file is opened, then by doing some operations on
etc) on disk files, the files must be loaded into memory. the file, it is also closed. Once all the operations on the
It is also called opening the file. For this open ( ) file are done, it can be closed using dose ( ) method.
function is available in Python. Open ( ) is the only When the close method is called with the help of file
function in Python file handling. The rest of the object, the hidden data is flashed while being written to
operations that will be performed by object methods. the file. When closing a file, Frees all the resources
When a file is opened by the open ( ) function, then this assigned to it. The syntax for closing a file is as follows–
function loads that file into the memory in the form of an Syntax– fileobj⋅close ( )
object, which is also called a file object. There is no parameter for the close ( ) method.
Once the file is available as an object, there are Example– file = open ("textfile·txt", 'a') # opening file
many methods automatically available with it that you file·close ( ) # closing file.
can call through that object and perform different 7.5 To Write Files :
operations. Python file is written by write ( ) function. If the file
The file is opened to manipulate the data. To open a
is not already created then it is created. Write ( ) method
file in Python, Python's in-built open ( ) method is used.
writes any string to an open file.
The syntax of open ( ) method to open the file is as
Syntax– write (file, "string", length_in_bytes)
follows– In the above syntax, the file on which the file is to
Syntax– fileObj = open (file Name, mode) be written is opened. The string which has to be written
under the string is given here. length_in_bytes is
Parameters– There are two important parameters optional, here it returns the number of bytes and the
for the Open ( ) method– length in bytes.
104
Search on TG: @apna_pdf
Example– f = open ("pythonprogramming⋅txt", "w") Example– Source Code:
f⋅write ("Hello World") File = open ("textfile·txt", 'r')
f⋅close ( ) Print (file·read ( ))
f = open ("pythonprogramming⋅txt", "r") file·close ( )
print (f⋅read ( )) Output :
f⋅close ( ) Hello Python # file content
When mode w is used, the first content of the file is In the above example the file is opened on read
removed and the new content that is written is saved. mode and read ( ) method is used to read the data of the
Output: Hello World opened file and later the file is closed. To read the file in
To write some content to a file in Python, the user python read (n), readline (n) and readines ( ) methods are
has to enter the file name along with the file extension used.
e.g. file⋅txt. Where, n: is the number of bytes to read.
7.6 File Function: 7.6(iv) readline ( ):
There are many methods available with the File • This method reads only one line in the file.
object. Some of the major file functions are as follows– • There is a new line character (\n) at the end of the
string and it is ignored for the last line.
7.6(i) open ( ): • This method reads till the end of line with readlines ( )
and returns a list, which is saved in memory.
The file is opened to manipulate the data in the file.
Example– # open the file for read operation
to open file in python, The in-built open ( ) method is
used. fl = open ('Pythonfile⋅txt')
The syntax of open ( ) method to open the file is as # reads line by line
follows– 1n = f1⋅readline ( )
Syntax– fileObj = open (file Name, mode) while 1n! = " " :
Print (1n)
Parameters– Here are the 2 important parameters 1n = f1 ⋅readline ( )
for the Open ( ) method– # close the file
File name: Along with the file name, its extension is f1⋅close ( )
also given here. If there is a file at the same location, 7.6(v) readlines ( ):
path is not needed. • This method loads the contents of the entire file at
mode: Here the mode is given to open the file like– once.
r, rb, rb+, w, wb, a etc. If mode is not given, the default • This method reads the entire file content and stores it
'r' (reading) mode is used. in a list.
Example– file = open ('textfile·txt') # default mode is r • This method reads to the end of line with readline ( )
# or and returns a list.
file = open ('textfile·txt', 'r') Example– #open the file for read operation
7.6(ii) close ( ): f1 = open (·Pythonfile·txt')
The file is opened, then by doing some operations on #reads line by line and store them in list
the file, it is also closed. Once all the operations on the for 1n in f1·readlines ( ):
file are done, it can be closed using close ( ) method. Print (1n)
When the close method is called with the help of file #close the file
object, the hidden data is flashed while being written to f1·close ( )
the file. When closing a file, Frees all the resources
assigned to it. The syntax for closing a file is as follows–
7.6(vi) write ( ):
Write ( ) method takes a string as argument and
Syntax– fileobj⋅close ( )
writes it to the file. Then this method returns the number
There is no parameter for the close ( ) method.
of characters that have been written to the file. Write ( )
Example– file = open ("textfile·txt", 'a') # opening file
method types a specified text in the file. Write ( )
file·close ( ) # closing file. actually writes the data to a buffer, not a file. The syntax
7.6(iii) read ( ): to use the Write ( ) method is as follows–
The read ( ) method is used to read the data of the syntax: fileObj⋅write (str))
file. The syntax used for this is as follows– str: The string to be written to the file is given here
Syntax– fileObj-read (Size) as a parameter.
The parameter Size is optional. The size of the data Write ( ) method overwrites the file and data is
to be taken is given here. If size is not specified, data is written from the beginning.
read till EoF (End of File). Even if invalid value is given textfile·txt
on size, it reads the data till End of File. Hello World
105
Search on TG: @apna_pdf
Example– Source Code: The syntax for using the tell() file method is as
file = open ("textfile·txt", 'w+') follows–
file·write ("Hello") syntax: fileObj⋅tell ( )
file·close ( ) There is no parameter for the tell ( ) method.
file⋅txt
Output :
Hello World
Hello
Example– Source Code:
7.6(vii) writelines ( ): file = open ("file·txt" , 'r+')
The writelines ( ) file method is used to write a Print (file·tell ( ))
given sequence or list of items to a file. The syntax for Output: 0
using the Writelines ( ) method is as follows–
7.6(x) seek ( ):
syntax: fileObj⋅writelines (seq)
This is used to set the current position of the file at
Here sequence (list, tuple) is given in seq.writelines
an offset. It returns the value in integer according to the
( ) method returns None. given offset or position.
The syntax for using seek ( ) file method is as
Example– file = open ("file·txt", 'W') follows–
list = ['Hello World', 'Hello World\n', 'Hello Syntax: fileObj⋅seek(offset, fromwhere)
World']
file·writelines (list) offset: Here the position of the file is given in integer.
file·close ( ) Negative value can not be pass in this.
Output : from where: Any one value out of 0, 1 or 2 is given in
Hello world Hello World this.
0; This is the default. This is the starting position.
Hello World
The operation is performed from the beginning of
7.6(viii) append ( ): the file.
append ( ) method is used to add a single item to the 1; This is the current position. The operation on the file
list. In this method only one item can be added at a time is performed from the current position of the file.
at the end of the list i.e. at 1st index place. Offset must be 0.
syntax: list⋅append (item) 2; This is the ending position. The operation on the file
Parameter: is performed from the ending position of the file.
item : Which item is to be added to the list, that item Offset must be 0.
is given here. example–file⋅txt
Returning value Hello Friends! How are you?
The append ( ) method returns 'None'. Source Code:
Example for append ( ) List Method in python file = open ("file⋅txt",'r')
source code: file⋅seek(0) # current position is 0
list = ["H", "e", "l", "l"] Print (file⋅read ( ))
list⋅append ("o") file⋅seek (2) # current position is 2
print (list) Print (file⋅read ( ))
['H', 'e', 'l', 'l', 'o'] file⋅seek (7) # current position is 7
Example: Adding list to a list file⋅close ( )
Output:
# animal list
Hello friends ! How are you?
animal = ['cat', 'dog', 'rabbit'] llo friends! How are you?
# list of wild animals riends ! How are you?
wild_animals = ['tiger', 'fox'] 7.6(xi) rename ( ):
# appending wild_animals list to animals Python provides an OS module which has some in-
animals.append (wild_animals) built methods which help us to perform file operations
print ("Updated animals list:", animals) like file renaming, deleting etc. To use this module, the
Output: Updated animals list : ['cat', 'dog', 'rabbit', OS module has to be imported in the program.
['tiger', 'fox']] rename ( ) method is used to rename a file. The
7.6(ix) tell ( ): syntax for using the rename ( ) method is as follows–
By this function the current position of the file is Syntax– OS⋅rename (file name, new file name)
returned to read or write the data on the file. This Given as parameter, under name of the file whose
name is to be renamed is given.
function returns the position in bytes that represents the
New File name: The new name is given to the
distance from the beginning of the file to that position.
written file.
106
Search on TG: @apna_pdf
If the file does not exist present in the first parameter # the first occurrence of 1 is removed from the list 1
(file name), then file not found Error is displayed. If the list 1= [1, 2, 1, 1, 4, 5]
file exists in the second parameter, File Exist Error is list.remove (1)
displayed. print (list 1)
Example–import OS # removes 'a' from list 2
OS rename ("textfile⋅txt", "myfile⋅txt") list 2 = ['a', 'b', 'c', 'd']
# rename text file⋅txt to myfile⋅txt list 2.remove ('a')
Python provides an OS module which has some in- Print (list 2)
built methods which help us to perform file operations Output :
like renaming, deleting etc. To use this module, the OS
[2, 1, 1, 4, 5]
model has to be imported into the program.
['b', 'c', 'd']
rename ( ) method is used to rename a file to use the
rename ( ) method the syntax is as follows– 7.7 Working with Binary Files:
Syntax– OS⋅rename (file name, new file name) "Text files are composed of binary data consisting of
Given as a parameter, under file name is given the octets or bytes, with each byte representing a character,
name of the file whose name is to be renamed. and the end of the file is marked by a special byte pattern
New File name: The new name is given to the file is commonly referred to as EOF (End of File)." A binary
written file. file contains orbital binary data and thus the end of file
If the file dose not exist in the first parameter (file cannot be detected, thus a different mode operation is
name), then file not found Error is displayed. If the file required to read these files. The open ( ) function opens a
file in text format by default. To open the file in binary
exists in the second parameter, 'File⋅Exist Error' is
format b' is added to the mode parameter.
displayed.
Example–import OS Example– bin_file = ("Binary File⋅bin", "b')
Apart from this you can also use any other mode.
OS⋅rename ("textfile-txt", "myfile⋅txt")
# rename text file⋅txt to myfile⋅txt
The b mode opens the file in binary mode while the
# importing the os module import os
w mode opens the file for writing only. If a file exists, it
# Source
will overwrite the file. The file pointer is at the beginning
sc = 'textfile.text'
of the file.
# Destination The 'ab+' access mode opens a file in binary format
dest = 'myfile.txt' for both reading and writing. If the file exists, the file the
# Renaming the file pointer resides at the end of the file. If the file does not
os.rename (src, dest) exist, it creates a new file for read and write.
print ("The file has been renamed.") Read write mode is also called updating mode
Output: because in this the data is updated by reading and writing
The file has been renamed. the data. The r+, rb+, w+, wb+, a+ and ab+ access modes
7.6(xii) remove ( ): are read write modes available in Python.
remove ( ) method is used to remove an element Binary files store data in the same format as
from the set. computer memory. Examples of binary files are
syntax: executable files, images, audios, etc. Binary files store
set, remove (element) data in 0 and 1. All binary files follow a specific format.
returning value When a file is opened in binary mode, it changes the
remove ( ) method; returns 'None'. If the given encoding parameters accepts.
element is not found on element ; set key error exception. If you want to write a list, dictionary like structure
Example– Source Code: and also want to do that then you have to import a
module in python known as pickling.
set = {4, 5, 7, 9}
Pickling means converting the object structure into a
set.remove (4) byte stream before writing the data to the file, that is, the
print (set) process of converting any type of Python object (list,
Output: {9, 5, 7} tuple, dictionary, etc.) into a byte stream is called
Example: Remove element from the list pickling. Modules can be used to store objects of any
# python program to demonstrate the use of remove type in a file because it allows users to store Python
objects along with their structures. Pickle module is used
( ) method
for data storing format.
107
Search on TG: @apna_pdf
Unpickling is the process of retrieving the original # 3.read tuple from binary file 'my file 5.bin'
Python object from the stored string representation, that # 3.1. open file for reading
is, from the pickle file. It is the process of converting a f = open ('my file 5.bin', 'rb')
byte stream to a Python object. # 3.2. A new tuple
To create a binary file, we will use pickle-dump ( ) T2 = ( )
to write objects to a file that has been opened in binary
# 3.3. Read data from file
access mode. After storing the data using dump ( ), it can
for line in f:
be used to read it.
s = line.decode ( ) # convert
# python.work with binary files
bytes = > str
# open binary file for reading
S = s [:-1] # Remove the last character
f = open ('my file 1. bin', 'rb')
T2 = T2 + (s,) # Add strings to tuple
# get a string from binary file
# 3.4 print the tuple
d = f.read ( )
print ("T2 = ", T2)
# Display this string
# 3.5.close file
# The output will be as a string of characters
f.close ( );
Print ("d =", d) # d = [b\ × 80\ × 03] q\ × 00 (k\ ×
The result of the program
01\ ×88G @\ × 07\n = p\ × a3\ × d7\ ne.
T2 = ('abc', 'def', 'ghi', 'jk lmn')
# if print as a separate character,
7.8 Command Line Argument:
# then the character code will be displayed as an
integer Command line arguments are the flags given to a
program/script at runtime. In order to execute the
print ("d = [5] = ", d [5]) # d[5] = 40
program, there is additional information. This allows the
print ("d = [0] = ", d [0]) # d[0] = 128
user to provide different inputs without changing the
# Use bin function for single character print
code. This is a way to read the user's input. There is
(bin (d[2])) # 0b1011101 f.close ( )
another way. Almost all modern programming languages
The result of the program support command line arguments.
d = [b\ × 80\ × 03] q\ × 00 (k\ × 01\ × 88G@ × 07\ n This is a very important feature because it allows
= p\ × a3\ × d7\ ne users to have dynamic input, whether they have written
d [5] = 40 the program or not.
d [0] = 128 Python comes with a number of different libraries,
0b1011101 which allow the user's Python code to take input from the
Example: command line Sysargv, getopt and argparse is mainly
# Binary files.writing/reading a tuple containing used.
character strings The sys module plays an important role in
# 1.The specfied tuple with strings processing command line arguments. argv of the
T = ('abc', 'def', 'ghi', 'jk lmn') command line document sys module attributes are stored
# 2.write tuple T to file 'my file 5.bin' as lists. The length of sys-argv is the number of augment
+ 1.
# 2.1⋅ Open file for writing
The getopt module processes command line
f = open ('my file 5.bin', 'wb')
arguments based on UNIX conversions. This is useful for
# 2.2⋅ Tuple bypass cycle for item in T:
parsing command line arguments where you want the
bt = (item + '\n'), encode ( ) # convert user to enter some options as well.
(str + '\n') = > bytes The Python argparse module is a popular choice for
f.write (bt) # write bt to file parsing command line arguments. This provides many
# 2.3. close file options like positional argument default value, help
f.close ( ); message, specifying the data type of the argument, etc.

108
Search on TG: @apna_pdf
Practice Questions with Explanatory Solutions
1. Which method tells you the current position 7. What is the length of sys⋅argv?
within the file? (a) Number of arguments
(a) file ( ) (b) open ( ) (b) Number of argument +1
(c) tell ( ) (d) close ( ) (c) Number of arguments –1
Ans. (c) The current position of the file is returned to (d) None of these
read or write data on the file by the tell ( ) method. Ans. (b) Sys module plays an important role in
This function returns the position in bytes that processing command line arguments. Command line
represents the distance from the beginning of the file documents are stored as a list in the argv attribute of
to that position. the sys module. The number of sysargy's length
augments is +1.
2. Which method is used to display the entire
contents of the file? 8. What is the output of the following program?
(a) readlines ( ) (b) open ( ) a=2
(c) close ( ) (d) seek ( ) b = '3.77'
c = –8
Ans. (a) All the lines of a file i.e. the entire content str ='{0:4f}{0:3d}{2}{1}'⋅format(a,b.c)-print(str)
can be read in the list by readlines ( ) method. This (a) 2.00002–83.77 (b) 23.77–83.77
method reads one line at a time from the file. The line (c) 2.0003–83.77 (d) 2.000283.77
is read as a string and the newline character (\n) is
Ans. (a) a, b and a are assigned three values 2, '3.77'
automatically added to its end. By default, the readline and –8 respectively. strl is taken as a variable in which
( ) method returns only a single line. The content of the range '{10:41} {0:3d} {2} {1}' is taken. Format
the file can also be read using read ( ). function is used and the value of str is to be printed.
3. What does the Seek ( ) method set to the current Range starts at 0 : 4f So it will start from 0 itself. The
file in a file stream? index value of a, b and c will be 01 and 2 respectively.
(a) Rename (b) position It will display the value of 0 index up to 4 points
(c) line (d) none of these {0:4f} as 2.0000 and {0:3d} as 2 and {2} as 8 and 13
Ans. (b) The seek ( ) file method is used to set the as 3.77. So its output will be 2.00002–83.77.
current position of the file at an offset. It returns the 9. The access mode supported by Python is–
value in integer according to the given offset or (a) read (b) write
position. (c) append (d) all of the above.
4. What else is read-write mode called? Ans. (d) Python supports all access modes, read write
(a) readline (b) access and append.
(c) position (d) updating The read ( ) method is used to read the contents of
Ans. (d) Read write mode is also called updating the file. A document can be pass in it, which there is
mode because in this the data is updated by reading only one number. Indicates how many bytes you want
and writing the data. rb+, r+, w+, wb+, at and ab+ to read from the file. This argument is optional.
access modes available in Python are read write mode. The write ( ) method takes a string as an argument
5. Which method file frees up the associated and writes it to a file. After this method characters
resources? returns the number of keys that have been written to
(a) open ( ) (b) close ( ) the file.
(c) string ( ) (d) none of these In append ( ) mode, the file pointer is placed at the
Ans. (b) Close ( ) method is used to close the file. end of the existing file. It appends data to the end of
When the Close ( ) method is called with the help of the file. This mode is also used to create non-exiting
the File object, then the hidden data written on the file files.
is flushed and the resources associated with the file 10. What is unpickling?
are freed. (a) The byte stream is converted back to an object
6. Which of the following is true to identify the hierarcy.
correct way to close a file? (b) A process that converts a byte stream into a
(a) Close (file) (b) File-close ( ) Python object hierarchy
(c) File-close (d) None of these (c) Both A and B
Ans. (b) File obj-close is used to close a file. The (d) None of these
hidden data written on the file is flushed when the Ans. (b) Unpickling is the process of retrieving the
close ( ) method is called with the help of the File original Python object from the stored string
object. Where the file is closed after that no operation representation, that is, from the pickle file. It is the
can be done on that file without opening the file. process of converting a byte stream to a Python object.

109
Search on TG: @apna_pdf
11. Which of the following is not a characteristic of a Ans.(a) A file system is a location on the storage that
file? records data for later access. It is used to store data
(a) closed (b) soft space permanently for various file operations like read,
(c) rename (d) none of these write, open etc. for future use. The unique file name
Ans. (c) When we store data in the computer system, and path are used by the users to access the file for
the OS stores them in the form of files. A file can be read, write and modification.
defined as a set of related data or information. Closed, 18. Which method flushes the write buffer of a file
Soft Space, Name, Extension, Date & Time, Length stream?
etc are the attributes of the file. (a) isatty ( ) (b) flush ( )
(c) function ( ) (d) none of these
12. The correct syntax of File writelines ( ) is–
(a) file writelines (sequence ) Ans. (b) Flush ( ) file method is used to flush the
(b) file object-writelines ( ) writing buffer from the file stream. To use the flush ( )
(c) file object-writelines (sequence) file method, the fileobj⋅flush ( ) syntax does not
(d) none of these require any parameters. It returns 'None' as output.
The buffer is automatically flushed from the file
Ans. (c) Writelines are used to write the given
stream when the file is closed. User can choose file
sequence to the correct syntax is file. file⋅writelines ( ) closing as per his choice. You can already flush the
method of object⋅writelines (sequence). buffer using the flush ( ) method.
13. Creates a new file with a specified name– 19. Which is used to handle non text files?
(a) Û (b) rb+ (a) file pointer (b) readline
(c) rt (d) r (c) binary mode (d) all of the above
Ans.(a) Û it creates a new file with the specified Ans.(c) A binary file is a file that stores data in a
name. When a file exists with the same name, it sequence of bytes, which is 8 bits and sometimes 16
displays error. bits. Binary mode is used to handle this type of non
14. Which module is in the Python Standard Library text file.
parse option obtained from the command line? 20. Which command line returns the number of
(a) getopt (b) os parameters?
(c) getarg (d) main (a) fileObj⋅readlines (b) fileobject isatty();
Ans. (a) The getopt module processes command line (c) len (sysargv) (d) none of these
arguments based on Unix conversion. This is useful Ans.(c) The sys module provides functions and
for parsing command line arguments where you want variables used to manipulate various parts of the
the user to enter some options as well. Python runtime environment. The len (sys-argv)
function is used to count the number of parameters
15. f⋅seek(0) is used for– passed to the command line. iteration starting at 0, it
(a) Bringing the file cursor to the starting position. also counts the program name as an argument.
(b) To get the current file position.
21. Which of the following is the basic I/O connection
(c) Reading the entire file.
in file?
(d) none of these
(a) Standard Input (b) Standard Output
Ans. (a) Seek method enables the file pointer position (c) Standard Errors (d) All of the mentioned
to be modified externally. f⋅seek (0) points to the Ans. (d) In computer programming, standard streams
starting position of the file while f⋅seek (1) points to are pre-connected input and output communication
the current position of the file and f⋅seek (2) points to channels between a computer program and its output
the end of the file. when it begins execution. The three input/output
16. Opens a file in binary format for reading and connections are called standard input (adin-keyboard),
writing– standard output (stdout basically a printer) and
(a) r (b) An standard error (stder-monitor).
(c) rb+ (d) none of these 22. Which function returns the strings?
Ans. (c) tb + (read and write in Binary), in access (a) readline ( ) (b) read ( )
mode the file is opened for reading and writing in (c) Both of the above (d) None of the above
binary format. The file pointer is present at the Ans. (b) : 'read ( ) method is used to read the data of
beginning of the file. the file. It returns the string in the output.
17. What is the named location of the stored 23. What will be the output of the following code?
information on the disk called? f=open("demo.txt","w+")
(a) file (b) memory f.write("Welcome to Python")
(c) Reader (d) RAM f.seek(5)
110
Search on TG: @apna_pdf
a=f.read(5) 27. Which of the following is not a correct mode to
print(a) open a file?
(a) Welco (a) ab (b) rw
(b) me to (c) a+ (d) r+
(c) Welcome to Python Ans. (b) 'rw' mode is not the correct mode to open any
(d) e to file in python as given in the option.
Ans. (b) r+ –opens a file for reading and writing, placing the
f=open("demo.txt","w+") pointer at the beginning of the file.
f.write("Welcome to Python") a+ –opens a file for both reading and appending.
f.seek(5) ab – opens the file to append in binary mode.
a=f.read(5)
28. Thy syntax used to rename a file:
print(a) (a) os.rename (existing_name, new_name)
On running the given code, the output "me to" is (b) fp.name='new_name.txt'
obtained. Option number (b) is the correct answer. (c) os.rename (fp. new_name)
24. The syntax of seek( ) is: file_object.seek(offset | (d) os.set_name(existing_name.new_name)
reference_point)] What does the reference point Ans. (a) Python rename() file is a method used to
represent? rename a file or directory in the Python programming
(a) reference_point indicates the current position of language.
the file object Syntax– os.rename(src,dst)
(b) reference_point indicates the starting position of src means the name of the file or directory must
the file object already exist.
(c) reference_point indicates the ending position of dst stands for the new name of the file or directory
the file object you want to replace.
(d) None of these 29. If we open a file in write mode and file does not
Ans. (c) The seek( ) method is used to locate the file exist, which of the error will generate?
object at a particular location in the file. The syntax of (a) File Found Error
seek( ) is– (b) File Not Exist Error
File_object.seek(offset[.reference_point]) (c) File Not Found Error
In the above syntax, the reference_point points to the (d) None of these
end position of the file object. Ans. (d) If we open a file in write mode and the file
25. Which one is not attribute of a file? does not exist, it creates the file or overwrites the
(a) Softspace (b) mode existing file. Write mode creates a file for writing the
(c) closed (d) rename contents and places the pointer at the beginning. If the
file exists, truncate (clean) any existing information.
Ans. (d) : Rename is not a feature of the Python file
system. Following are the file object attributes– 30. Which is the function to read the remaining lines
of the file from a file object infile?
• File.closed→ Returns true if the file is closed (a) infile.read (2) (b) infile.read ( )
otherwise false. (c) infile.readlines ( ) (d) infile.readline ( )
• File.mode→ Returns the access mode with which Ans. (b) infile.read ( ) is used to read the remaining
the file was opened. lines of the file from the file object.
• File.name→ Returns the name of the file. 31. Which function is used to read all the characters?
• File.softcopy→ Returns false if the space is (a) readall ( ) (b) read ( )
explicitly required with print, true otherwise. (c) readcharacters ( ) (d) readchar ( )
26. Which of the function takes two arguments? Ans. (b) 'read ( )' function reads all the characters. The
(a) dump ( ) (b) load ( ) read ( ) method returns a specific number of bytes
(c) both of the above (d) None of the above from the file, default–1. Which means the whole file.
Ans. (a) The 'dump( )' function takes two positional Syntax– file⋅read ( )
arguments– 32. Which of the following is an invalid mode?
1. The data object to be initialized and (a) a (b) ar+
2. The file-like object to which the bytes will be (c) r+ (d) w
written. Ans. (b) The ar+ mode is an invalid one in Python. a,
Syntax– json.dump(data.write_file) w and r+ are valid modes.
111
Search on TG: @apna_pdf

8 SCOPE AND MODULE

8.1 Object and Name Scope: Example–


Python is an object-oriented programming (object) def get_addition ( ) :
language. Along with this, it is also a Procedural def get_addition ( ) :
Oriented Programming (Function) language. Most a = 390
b = 90
programming languages have the concept of ODP.
Print ('Addition is:', a + b)
Python's objects contain variables, functions or methods.
get_addition ( )
Object scope specifies the coding area from which a
Output:
particular Python object can be accessed. Therefore one c:
cannot access a particular object from anywhere in the \users\yct\desktop\python>python
code unless access is allowed from the object scope. local_variables.py
Example– Addition is : 480
# python program showing a scope of object The difference between global and local variables is
def some func ( ): as follows–
Print("Inside some_func") Local Variable Global Variable
def some_inner_func ( ) It is declared inside the It is declared outside
var = 10 function. the function.
Print ("Inside inner function, value of var:", var) If a local variable is not Stores zero by default
some_inner_func ( ) initialized, it stores a if the global variable
Print("Try printing var from outer function:", var) garbage value. is not initialized.
Some_func ( )
It is created when the It is created before the
The scope of a variable determines the part of the execution of the function global execution of
program where any variable can be accessed after it is starts and ends when the the program and gets
defined. There are mainly two variable scopes in Python function terminates. destroyed when the
– Global variable, Local variable. program terminates.
Global variables are those variables which are Data can be accessed Multiple functions can
accessible from anywhere i.e., after defining, they can be only by one function in a access the data of
accessed anywhere in the entire script file or even inside local variable. same global variable.
a function. Passing parameters is Passing parameter is not
Example– necessary in a local necessary for a global
a = 390 variable to access the variable as it remains
b = 90 value to another function. visible throughout the
def_addition ( ): program.
print ('Addition is:', a + b) Modifying the value of a Modifying the value
get_adition ( ) local variable in one of a global variable in
Output: function does not affect a function affects the
c: the other function. entire program.
\users\yct\desktop\python>python global
Local variables are stored Global variables are
variables.py
on the stack, unless stored at a fixed
Addition is: 480
specified. location specified by
the compiler.
In the example, we can see that the variables (a, b)
defined outside the function can be easily accessed inside 8.1(i) Global Keyword:
the function. The global keyword is used to make a function's
Local variables are variables that are defined within variable global to a module. This is useful when you
a block of code (e.g., a function) and stored within a want to change the value of a variable through a
function. function–
These variables are accessible only inside the x = 10
function, but these variables will not be accessible def change (4) :
outside that function. global x # global keyword
112
Search on TG: @apna_pdf
x=4 nonlocal var
change (11)
var = 10
print (x)
RUN print ("sub func:", var)
>>> sub func ( )
11
Example– using global, to change global variable from print ("main func", var)
inside a function main func ( )
# global variable
c=1 print ("global:", var)
def add ( ) : Output:
# use of global keyword
sub func : 10
global c
# increment cby 2 main func : 10
c=c+2 global : 2
print (c)
add ( )
8.1(iii) Local ( ) & Globals ( ):
Output: 3 The globals ( ) and locals ( ) functions return the
names present in the global and local namespaces,
8.1(ii) Non-Local Keyword : respectively, depending on the location in which the user
The non local keyword is used for nested functions. exists.
'Non-local' variables are not global. If they are taken in Calling locals ( ) from inside a function will return
the inner function, then their values will be change in the all names that can be accessed as local.
outer function. When globals ( ) is called from inside a function, it
returns all the names of globals that can be accessed.
without non local The return type of locals ( ) and globals ( ) functions
source code : is dictionary, so the names can be retrieved with the help
of keys ( ) function.
var = 2
8.2 LEGB Rule:
def main func ( ) : Before using a variable in a program, it is necessary
var = 5 to define it. How and where was this variable defined,
depending on this, a variable has to be accessed in
def sub func ( ) : different ways. The LEGB rule in Python states that the
scopes and namespaces are searched in which order for
var = 10
resolution. The full form of LEGB is
print ("sub func:", var) Local⋅Enclosed⋅Global and Built-in.
sub func ( )
print ("main func", var)
main func ( )
print ("global:", var)
Output:
sub func : 10 In Python, a namespace is a container where each
object has a unique name. Python maintains itself the
main func : 5 namespace as a dictionary. There are four valid
namespaces in Python– local namespace, enclosed
global : 2
namespace, global namespace and built-in namespace.
with non local Local Namespace– Variables that are defined inside
the body of a function and can be used only inside the
source code :
function in which the variable has been declared are
var = 2 called local variables. Its scope is local.
Enclosed Namespace– When a function is defined
def main func ( ) :
inside another function, it creates an enclosed
var = 5 namespace. It has the same life time as the local
namespace.
def sub func ( ) :
113
Search on TG: @apna_pdf
Global Namespace– This is related to the Python from math import pi
script or current module. Global means the scope of the
# pi = 'global pi variable'
Upper Most. If you define a variable at the top of your
script, it will be a global. It is available everywhere in the def outer ( ):
script.
Built-in Namespaces– Built-in namespaces are # pi = 'outer pi variable'
special names that Python reserves for itself. Built-in def inner ( ):
means functions that are already defined in Python. The
built-in namespace is created when the Python interpreter # pi = 'inner pi variable'
starts and never deleted. print (pi)

# Local Scope inner ( )


pi = 'global pi variable' outer ( )
def inner ( ):
pi = 'inner pi vaiable' Output: 3.141592653589793
print (pi) 8.3 Module:
inner ( ) A module is a file that contains Python definitions
and statements. A module can define functions, classes
Output: inner pi variable and variables. Module files can be saved with the
extension ⋅Py.
Local and Global Scpes Python modules are simple text files in which
# Global Scopes Python code statements are written. The benefits of using
pi = 'global pi variable' the module are as follows–
def inner ( ): • It provides a medium to reuse program code.
pi = 'inner pi variable' • It provides a medium of dividing tasks.
print (pi) • It provides a medium to testing individual parts of a
inner ( ) program.
print (pi) • Helps a team to work on large applications with proper
collaboration.
Output: inner pi variable
The Python Standard Library includes over 200
global pi variable modules. The standard modules of Python are as
follows–
_main_ Environment for running top
Local, Enclosed and Global Scopes level scripts
# Enclosed Scope colorsys Color conversion function
between RGB and other color
pi = 'global pi variable'
systems
def outer ( ): date time Basic date and time types
pi = 'outer pi variable' fractions Rational numbers
def inner ( ): math Mathematical function
re Regular Expression Operations
# pi = 'inner pi variable'
socket low-level networking interface
non local pi types Names for built-in types
print (pi) telnetlib Telnet client class
inner ( ) unicode data Unicode Database Access
Following are the benefits of Python modules–
outer ( )
(i) Module provides the facility to re-use the code.
print (pi) (ii) Modules allow Python code to be organized
logically.
Output: outer pi variable
(iii) Similar types of features can be classified and placed
global pi variable in a single module.
Local, Enclosed, Global and Built-in Scopes (iv) Placing related codes in a single module makes the
code easier to understand and use.
# Built-in Scope (v) This makes easier to debug the code.
114
Search on TG: @apna_pdf
A module allows Python code to be organized To create a package–
logically. A module can define functions, classes and • First create a directory named Package.
variables. When you import a module, the Python • Create an empty file _init_⋅py inside the directory.
interpreter searches for the module in the following • Create three more files modulel⋅py, module2⋅py and
order:
module 3⋅py.
• In the current directory
• If a module is not found, Python searches each
module 1⋅py
directory in the shell variable PYTHONPATH.
def mod 1_func 1 ( ):
• If the module is not found even with both above
Print ("Welcome to module 1 function 1")
methods, then Python checks the default path. In
UNIX this path is usually /usr/local/lib/python def mod 1_func 2 ( ):
The search path of the module is stored in the Print ("welcome to module 1 function 2")
sys⋅path variable in the system module sys. The sys-path module 2⋅py
variable contains the current directory, PYTHONPATH, def mod 2_func1 ( ):
and default installation depend on. Print ("welcome to module 2 function 1")
There are many versions of a Python def mod 2_func 2 ( ) :
package/module/file. Renaming a module during import Print ("welcome to module 2 function 2")
is called module aliasing. You can import an entire module 3⋅py
module under an alternative name. The syntax for this def mod3_func 1 ( ) :
is– Print ("welcome to module 3 function 1")
Syntax– import < module Name (S) > as <aliasing> def mod 3_func2 ( ) :
import example as e Print ("welcome to module 3 function2")
8.4 Namespace:
In Python, a namespace is a container where each The package is ready to import. Now the package
object has a unique name. Python maintains itself can be imported in any file.
namespace as a dictionary. Python has four namespaces Here my package module 1 has been imported and
and built in namespaces. an alias name mod 1 has been given.
Local– defined inside the function/class. import my package-module 1 as mod 1
Enclosed– remains defined inside the enclosing Print (mod 1⋅mod 1_fune 1 ( ))
function (nested function concept) Print (mod 1⋅mod 1_func2 ( ))
Global– Defined at the uppermost level. Output:
Built-in– Reserved keywords in Python built-in Welcome to module 1 function 1
modules. None
8.5 Import Module: Welcome to module 1 function 2
The Python import statement imports code from one None
module into another program. By using import keyword Similarly other modules module 2⋅py and module
with module, you can import all the code of a module. 3⋅py can also be imported.
The import statement is located below the comments at The Python path is an environment variable that you
the top of a text file. can set to add additional directories. It is used to set path
The syntax for the import statement is as follows– for a user defined so that it can be imported directly into
Syntax– import [module] a Python program.
Using import statement we can import a module and The only reason to set the python path is to keep
access the functions contained in it using the dot directories of custom Python libraries which you don't
operator. want installed in the global default place. The Python
Example– # import statement example PATH variable holds a string with the names of various
standard module math directories that need to be added to the sys⋅path directory
import math list by Python.
Print ("The value of pi is", math.pi)
Output:
8.5(ii) Python Path:
The value of pi is 3.141592653589793 Python path is an environment variable that you can
set to add additional directories. It is used to set the path
8.5(i) To Create and Import Module: for a user-defined module so that it can be directly
A package is a collection of Python modules i.e. a imported into a Python program.
package is a directory of Python modules that contains The only reason to set python path is to keep
an additional_init_⋅py file. _init_⋅py differentiates a directories of custom Python libraries that you don't want
package from a directory that contains only a group of installed in the global default place. The python PATH
Python scripts. Packages can be nested to any depth, but variable holds a string with the names of various
must have their own _init_⋅py file in the respective directories that need to be added to the sys-path directory
directories. list by Python.
115
Search on TG: @apna_pdf
8.6 Package: import phone
A Python package is a hierarchical file directory phone⋅pots ( )
structure that defines a single Python environment. phone⋅Isdn ( )
Python packages contain modules and sub-packages phone⋅G3( )
respectively. When the above code is executed the output will be
Packages contain an additional_init_⋅Py file. displayed–
_init_⋅Py differentiates a package from a directory that I'm Pots Phone
simply contains a group of Python scripts. I'm 3G Phone
Suppose there is a file Pots⋅Py, which is available in I'm ISDN Phone
the phone directory. This file contains the following 8.7 Re-Loading Module:
source code lines– Module reloading is done to reuse available modules
#!/usr/bin/python instead of creating a new module object. In python when
def pots ( ) : the module's function or class is executed by the
Print "I'm pots phone" interpreter, its value can not be changed as long as the
Similarly, we have two other files which have session is open. In Python, modules can be imported only
different functions with the above names– once during a session. reload ( ) is used to refresh or
• Phone/Isdn Py file having function Isdn ( ) reload the module. This function restarts the session of
• Phone/G3⋅Py file having function G3 ( ) the module.
Now create a file named _init_⋅Py in the phone It reloads previously imported modules. When a module
directory. is imported into the script, the top level part of the
• Phone/_init_Py module is executed only once, the reload ( ) function is
To ensure that all functions are available when used to execute the top level of the module again.
importing Phone, explicit import statements will have to When a module source file has been edited using an
be written in _init_Py. external editor and you want to use the new version
from pots import pots without leaving the Python interpreter. The syntax of
from Isdn import Isdn reload ( ) function is as follows–
from G3 import G3 Syntax– reload (module_name)
By adding these lines in init_⋅Py, all these classes Here module_name is the name of the module which
will be available when you import the phone package. you want to reload. For example, to reload the Welcome
# !/usr/bin/python module, write–
# Now import your phone package. reload (welcome)

Practice Questions with Explanatory Solutions


1. Using which a variable can be declared in a Ans. (a) The _name_variable (two underscores—one
function? before, one after) is a special Python variable. its
(a) Keyword (b) Local value depends on how the script is executed. To
(c) Keyword global (d) None of these identify whether a program is executed directly or as a
Ans. (c) Global variable means it is available module, name variable is used. Sometimes users write
everywhere in the script, which also includes a scripts with functions that may be useful in other
function. Global variables are usually defined at the scripts. In Python, users can import that script as a
top of the script or outside a function. The global
module in any other script.
keyword is a keyword that allows the user to modify a
variable outside the current scope. There is no need to 4. A module that is imported like a user defined
use the global keyword outside the function. The module is–
global keyword is used to access a global variable in a (a) script (b) Standard Module
function. (c) function (d) none of these
2. In Python a ............... is container where objects Ans. (b) The standard library is a set of built-in
names are mapped. modules in Python that are part of the core
(a) Fonction (b) namespace
(c) file (d) command programming language it. Standard modules can be
Ans. (b) Namespace is a naming system in Python imported in the same way as user defined modules.
which is used to map object names. Python itself Generally three types of module are used–
maintains the namespace in the form of a dictionary. (i) Created by the programmer.
There are four valid namespaces in Python - local (ii) Created by a third party (programmer /
namespace, enclosed namespace, global namespace organization).
and built-in namespace.
(iii) Available in standard library.
3. A variable used to identify whether a program is
executed directly or as a module is– 5. To import all the attributes of a module is–
(a) _name_ (b) Help ( ) (a) # (b) ^
(c) you ( ) (d) none of these (c) @ (d) *
116
Search on TG: @apna_pdf
Ans.(d) The import command is used to import a 10. Import * Description module Imports all names
module in a Python program. All functions and classes that begin with.........
of the module that is imported and can be used on the (a) Underscore (–) (b) &
current program. Multiple modules can be imported (c) % (d) none of these
with the same import command, with modules are set Ans.(a) Import * statement imports all the names in
off by commas. all in one module. To import all the module that starts with underscore (–)
attributes in one module * syntax is used. 11. Which of the following is not an advantage of
6. Which of the following is not a valid namespace– using modules–
(a) Global namespace (b) Public namespace (a) Provides a medium of reusing program code.
(c) built-in namespace (d) local namespace (b) Provides a medium of dividing the task.
Ans. (b) In Python, namespace is a container where (c) Provides a medium of reducing the size of the
each object has a unique name. Python maintains itself program.
the namespace as a dictionary. There are four valid (d) Provides a medium of testing individual parts of
namespaces in Python - local namespace, enclosed the program.
namespace, global namespace and built-in namespace. Ans.(c) Python modules are simple text files in which
Python code statements are written. The benefits of
7. Modules are saved with extension. using the module are as follows–
(a) ⋅txt (b) ⋅py • It provides a medium to reuse program code.
(c) Both A and B (d) All of the above.
• Provides a medium of dividing tasks.
Ans. (b) A module is a file that contains Python • Provides a medium of testing individual parts of a
definitions and statements. A module can define program.
functions, classes and variables. Module files can be • Helps a team to work on large applications with
saved with the extension Py. proper collaboration.
8. Python variable name should be– 12. The code of a program that uses a given module
(a) Begin with an alphabetic character or an is called the .......... of the module.
underscore. (a) client (b) docstring
(b) It can contain alphanumeric characters and (c) interface (d) modularity
underscores. Ans.(a) The program code that uses a given module is
(c) The name of the variable should not be with called the client of the module. A Python program (a
dictionary. script or a module) that calls a function defined in the
(d) All of the above. module⋅py file name is called a client of the module.
Ans. (d) Variable is a name used to specify a memory 13. Which of the following statements call a
location. Variable is also known as identifier. function?
Identifier is used for the program. Some rules for (a) Function header (b) Function definition
declaring the name of the identifier are as follows– (c) Function cell (d) none of these
• The first character of a variable must be an alphabet Ans. (c) The function cell statement calls the function.
or an underscore. Cell objects are used to implement variable references
• Except the first letter all letters can be Lower Case across multiple scopes. For each variable, a Cell
(a – z), Upper Case (A – Z) an underscore or a digit object is created to store the value.
(0 – 9). 14. PyPI stands for–
• The identifier name should not contain any white (a) Python Package Index
space or special character ( @, #, %, 4 & ). (b) Python Package Installer
• The identifier name is case sensitive i.e. python and (c) Both A and B
PYTHON mean different. (d) None of these
• The name of the variable should not match with the Ans.(a) PyPI means; Python Package Index. The
dictionary. Python Package Index is a repository of software for
9. LEGB is– the Python programming language. PyPI helps users
(a) Local Enclosed Global Built-in to search and install software developed and shared by
(b) Logical Enclosed Global Built-in the Python community. Package authors use PyPI to
(c) Logical Enclosed Global Built-in distribute their software.
(d) None of these. 15. Which of the following can have multiple lines of
text–
Ans.(a) The full form of LEGB is Local Enclosed, (a) docstring (b) Python package index
Global, Built-in. The LEGB rule in Python specifies (c) both a and b (d) none of these
the order in which namespaces should be searched for Ans. (a) Docstrings or documentation strings provide
scope resolution. a convenient way of associating documentation with
Local– It can be defined inside the function/class. Python modules, functions, classes, and methods. The
Enclosed– It is defined inside the enclosing function docstring can contain multiple lines but if it is on more
(nested function concept) than one line, every other line must be blank.
Global– This remains defined at the uppermost level. 16. Built-in function is–
Built-in– Reserved keywords in Python built-in (a) Dir ( ) (b) Open ( )
modules. (c) File ( ) (d) Help ( )
117
Search on TG: @apna_pdf
Ans.(a) Built-in functions are those functions which Ans. (a) import sys
are already defined. There are 68 built in functions in sys.stdout.write('Welcome\n')
Python 3.6. These functions are part of the Python sys.stdout.write(All\n')
standard library. The Dir ( ) function returns a list of Output– Welcome
all the names defined in the module in ascending All
order. The sys module provides various functions and
17. The function to get help from any module is– variables in Python that can be used to manipulate
(a) Dir ( ) (b) Open ( ) various parts of the Python runtime.
(c) File ( ) (d) Help ( ) 24. Which of the following is false about "from.........
Ans. (d) help ( ) is used to get help from a module. import......... "form of import?
The dir ( ) function returns a list of Callable Methods (a) The syntax is: from modulename import
to find out what action they perform. You can use the identifier
help ( ) function of the restriction to know about the (b) This form of import does not import anything.
working of any string method. It is passed as a (c) The namespace of imported module becomes
parameter to the help ( ) function. part of importing module.
18. An environment variable containing a list of (d) The identifiers in module are accessed directly
directories– as identifier.
(a) variable (b) Standard module
(c) Python path (d) none of these Ans. (d) Identifiers are accessed directly as identifiers
in the module. This option is false.
Ans. (c) Python path is an environment variable that
you can set to add additional directories. It is used to 25. A function used for writing data in the binary
set the path for a user-defined module so that it can be format:
directly imported into a Python program. (a) write (b) output
19. What is the only package of Python modules? (c) send (d) dump
(a) file (b) directory Ans. (d) : dump ( ) function is used to write the data
(c) script (d) none of these in binary format. It takes two arguments 'file object'
Ans. (b) Package is simply a directory of Python and 'file' as parameters. It returns object representation
modules. Any Python file is a module while a package in byte mode. dump ( ) function belongs to pickle
is a collection of Python modules. The package module.
contains an additional_init_py file, to distinguish the 26. What will be the output of the following Python
package from a directory that contains a group of code?
Python scripts. (a) Nothing is printed (b) 8
20. What is non-local keyword useful for? (c) Error, method pow doesn't exist in math module
(a) Tuple function (b) split function (d) Error, the statement should be: print(pow(2,3))
(c) nested function (d) All of the above Ans. (d): The given python code will return output an
Ans.(c) Non-local keyword is useful in nested error as the code should be print (pow (2.3)). Therefore
function. This will prevent trying to bind the variable Option number (d) will be correct.
in the local scope first and forces it to go 'higher up'. 27. Which module is to be imported for using randint
Non local is similar to global and used to work with a ( ) function?
variable inside a nested function (a) random (b) raindrops
21. The conversion function between RGB and other (c) andomrange (d) rand
color systems is–
(a) rgb_color (b) Color_rgb Ans.(a) 'randint ( )' is a built-in function of 'random
(c) Colorsys (d) All of the above module' in Python. randint ( ) function of random
Ans.(c) The conversion function between RGB and module's is used to access various functions such as
other color systems in Python programs is Colorsys. generating random numbers. Before using the randint ( )
The Python Standard Library contains over 200 function we need to import the random module into
modules. Python's standard modules allow users to python.
organize Python code logically. Python standard 28. Which statement is correct to import all modules
libraries simplify the programming process. Colorsys from the package?
module is important for color conversion. (a) from package import all
22. What will be the output of the following Python (b) from package import *
code? (c) from package include all
from math import* (d) from package include
floor(37) Ans. (b) From package import* statement is used to
(a) 3 (b) 4 import all the modules from a package in Python.
(c) 3.0 (d) None of these Python code in one module accesses code in another
Ans. (a) from math import* module by the process of importing it. Import details are
floor (3.7) the most common way to implement import machinery.
Will get 3 as output because the floor ( ) function in 29. A Python module is a file with the ............ file
Python rounds the number to the nearest bottom. extension that contains valid Python code.
23. What will be the output of the following? (a) ⋅py1m (b) ⋅pymodule
import sys (c) ⋅module (d) ⋅py
sys.stdout.write('Welcome\n') Ans. (d) Modules in Python are simply Python files
sys.stdout.write(All\n') with a⋅py extension. The name of a module may contain
(a) Welcome All (b) Welcome All a set of functions, classes or variables defined and
(c) Compilation Error (d) Runtime Error implemented.
118
Search on TG: @apna_pdf
×e¹keâkeâkeâkeâkeâkeâkeâkeâkeâkeâ

9 NUMPY

9.1 Introduction of NumPy: Type:<class 'numpy⋅ndarray'>


Numpy is a library for the Python programming As you can see in the example, the array method of
language that allows more data storage with less numpy module returns an object of ndarray class. To
memory. Along with a multidimensional array and other create an array, it is not necessary to pass only a list in
the Array ( ) method, you can pass any array-like object
resources Numpy, allows Python programmers to store
as– list, tuple or set. But the return will be ndarray only.
numbers efficiently. It is an open source module of
Example–
Python, which provides fast mathematical calculations # import numpy module
on arrays and matrix. Arrays and matrix are an essential import numpy as np
part of the machine learning ecosystem, arr_list = np⋅array [[12, 23, 34, 45]]
Matplotlib, Tensor Flow, Scilcit-learn, Pandas etc.
arr_tuple = np⋅array ((12, 23, 34, 45))
complete the machine learning ecosystem. Numpy is also
useful in linear Alzebra, random number capability etc. arr_set = np⋅array ({12, 23, 34, 45})
To use numpy, the user has to import his module using a print ('List Arrray Type:', type (arr_list))
print ('Tuple Array Type:', type (arr_tuple))
statement. print ('Set Array Type:', type (arr_set))
Numpy is a library for the Python programming Output:
language that supports large, multi-dimensional indices C:\Users\YCT\Desktop \ python > python
and matrix. NumPy (Numeric Python) is an open source module_numpy⋅py
core Python library for scientific calculations. Various
List Array Type : <class 'numpy⋅ndarry'>
Features of Numpy Array are the following–
(i) High performance N-dimensional array object Tuple Array Type : <class 'numpy⋅ndarray'>
(ii) It includes tools for integrating code from C/C++ Set Array Type : <class 'numpy⋅ndarray'>
and Fortran.
(iii) It contains a multi-dimensional container for general Array Dimensions– All the above examples were
data. one dimensional Array. You can create an array of
dimensions as per your requirement.
(iv) Additional Linear Algebra, Fourier Transform and
0-Dimensional Array– Created with single value.
Random Number Capability. The array is called 0-dimensional. A single value in any
(v) Refined work array is itself a 0-dimensional array.
(vi) Data type definition capability to work with For Example;
different databases. import numpy as np
Numpy array is simply a grid that contains values of arr = np⋅array (90)
Homogeneous type. Numpy array becomes in two print (arr)
forms– One Dimensional and Multi-dimensional (2D, 3D //output : 90
etc) (i) Uni-Dimensional Array–The array which has 0-
dimensional array as an element. It is called Uni-
dimensional Array.
import numpy as np
arr = np⋅array ([12, 23, 3, 423, 2])
print (arr)
Output :
c:\user\YCT\Desktop\python>python
file⋅py
[12 23 3 423 2]

(ii) 1-Dimensional Array– Such an array which has


1-dimensional arrays as a elements, means every array
To create an array object in NumPy, the array element is a 1-dimensional array.
import numpy as np
method is used which returns an ndarry object.
To create Numpy array, arr = np⋅array ([12, 23, 3], [43, 2, 45], [2, 3, 4])
# import numpy module. print (arr)
import mumpy as np arr = np⋅array ( [12.23, 34.45])
Output:
# print it's type
c:\user\YCT\Desktop\python>python
print (Type:', type (arr))
file⋅py
Output:
[[12 23 3]
C:\User\YCT\Desktop\python>python
[43 2 45]
module_numpy⋅py [2 3 4]]
119
Search on TG: @apna_pdf
(iii) 2-Dimensional Array– Such an array which Numpy array objects have a property dtype, which
has 2-dimensional arrays as a elements, this is the most returns the data type of the index;
rare array structure. Example–
import numpy as np import numpy as np
arr = np⋅array ([[[12, 23, 3], [43, 2, 45]], [[2, 3, 4]
[23, 34, 23]]]) arr = np⋅array ([1, 2, 3, 4 ])
print (arr) print (arr⋅dtype)
output (arr) Output:
Output: Int 64
C:\Users\YCT\Desktop\python>python 9.4 Array Attribute:
file⋅py A Numpy array contains a set of attributes that you
[[12 23 3] can access. These characteristics include the size, shape,
[[43 2 45]]
[[2 3 4] number of dimensions and data type. The important
[23 34 23]] features of Numpy object are as follows–
9.2 nd Array: (i) Ndim: represents the number of dimensions of the
The Numpy array data structure is called ndarray, array.
which is short form of N dimensional array. Numpy (ii) Shape: returns an integer indicating the size of
works with Python objects which are called multi array.
dimensional. In ndarray, 1-dimensional array is called (iii) Size: Returns the total number of elements in the
vector and 2-dimensional array is called matrix. Numpy array.
The main objects of Numpy are multi-dimensional (iv) Dtype: Returns the type of the element in the array
arrays. This is a table of elements, all indexed by positive eg– float 5.4
integers of the same type. In Numpy, dimensions are (v) Item: Returns the length of each element at index in
called axes.
Following are the differences between Numpy Array bytes.
and List– (vi) Reshape: resets to Numpy.
(i) Numpy array has elements of Homogeneous type 9.4(i) Ndim:
and Python list has Homogeneous and Heterogenous ndim represents the number of dimensions (Axes) of
type elements. the ndarray. For example, for this two-dimensional index
(ii) After creating an array, its size cannot be changed [[3, 4.6] [0, 8.1]] the value would be ndim2. This ndarray
whereas the size of a list can be changed. has two dimensions– rows (axis = 0) and (Column (axis)
(iii) Numpy array consumes very liltle space and
memory than Python list. = 1).
(iv) n⋅dimensional array can be created using Example 1–
numpy⋅array ( ) function. Python list is # an array of evenly spaced numbers
one_dimensional by default but n-dimensional list import numpy as np
can also be created in it. a = np⋅arange (24)
9.3 Data Types: print a
The data type of any value decides where that value Output:
can be used in the program. Data types specify what type [0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
of data is to be stored in a variable or a Python object. 18 19 20 21 22 23]
An object of data type is an instance of the numpy.dtype
class that describes how to interpret the bytes Example 2–
corresponding to an array item into a fixed-sized block of
memory. # this is one dimensional array
Numpy has some additional data types and see data import numpy as np
types with a character eg- I for integer, 'U' for unsigned a = np⋅range (24)
interger etc. a⋅ndim
The list of all the data types in Numpy and the # now reshape it
characters used to represent them are given below– b = a = reshape (2, 4, 3)
i – integer print b
b – boolean # b is having three dimensions The output is as
u – unsigned integer follows–
f – float Output: [[[0, 1, 2]
c – complex float [3, 4, 5]
m – time delta [6, 7, 8]
M – date time [9, 10, 11]]
O – object [[12, 13, 14]
S – string [15, 16, 17]
U – unicode string [18, 19, 20]
V – fixed chunk of memory for other type (void) [21, 22, 23]]]
120
Search on TG: @apna_pdf
9.4(ii) Shape: shape: [integer or integer tuple]
Shape is a tuple of integers representing the shape of order : This is optional.
the ndarray in each dimension. It displays the reshaped array without changing the
For example, for this two-dimensional array [[3, 4, data.
6], [0, 8, 1]] the value would be shape ( 2, 3) because this Example–
ndarray has two dimensions– rows and columns and the # python program for reshape ( ) method
number of rows is 2 and the number of columns is 3. import numpy as np
This array attribute returns a tuple consisting of the array a = np⋅array([[1, 2], [3, 4], [5, 6]])
dimensions. It can also be used to change the size of an Print ("original array")
array. Print (a)
Example 1– a = a⋅reshape (2, 3)
import numpy as np Print ("reshaped array")
a = np⋅array ([[1, 2, 3], ( 4, 5, 6]]) Print (a)
print a⋅shape RUN
Output: (2, 3) >>>
Example 2– Original array
# this resizes the ndarray [[1 2]
import numpy as np [3 4]
a = np·array ([[1, 2, 3], [4, 5, 6]]) [5 6]]
a⋅shape = (3, 2) reshaped array
print a [[1 2 3]
Output:[[1, 2] [4 5 6]]
[3, 4] >>>
[5, 6]] 9.5 Array Creation:
Example 3– Numpy also provides a reshape⋅function to An array can be created in many ways in Numpy.
resize an array. Like– np⋅array,np⋅zeros, np.ones etc. A new ndarray
import numpy as np object can be created using any array creation routine or
a = np⋅array ([[1, 2, 3], [4, 5, 6]]) low level ndarray constructor. The syntax to create an
b = a⋅reshape (32) array of a Numpy object with important attributes is–
print b Syntax– numpy⋅array (object, dtype = none, copy =
Output: [[1, 2] True, Order = k, Subok = False, ndim = 0)
[3, 4] Parameter–
[5, 6]] Object: An array, anything that exposes the array
9.4(iii) Size: interface.
Size is the total number of elements in nd array. It is Dtype : desired data type array
equal to the product of elements of size. For example, for Copy : If True (Default), then the object. Copy has
this two-dimensional array [[3, 4, 6] (0, 8, 1)] Shape (2, been created order 'K', 'A', 'C' 'F' : specifies
3), the product of Size 2 and 3 will be i.e. (2 * 3) = 6 array's memory layout
Hence, the size is 6. Subok : If True, sub classes will be passed, otherwise
Example– # dtype of array is int 8 (1 byte) return such base class array.
import numpy as np ndmin : specifies the minimum dimensions of the
x = np⋅array ( [1, 2, 3, 4, 5], dtype = np⋅int8) resulting array.
print x⋅item size The simplest way to create an array in Numpy is to
Output: 4 use Python List–
mypythonlist = [2, 4, 6, 8]
9.4(iv) dtype: To convert a Python list to a Numpy array using
dtype specifies the data type of the elements of object np⋅array–
array. All elements in a Numpy array have the same data numpy–array–from–list = np⋅array (myPythonList)
type. For example, for this Numpy array [ ] 3, 4, 6], [0, 8,
1]], dtype would be int64. Some of the main methods to create Numpy array
9.4(v) item size: are as follows–
item size returns the size (in bytes) of each element
of the Numpy array. For example the item size for this
Numpy array [[3, 4, 6] [0, 8, 1]] will be 8, because this 9.5(i) empty ( ):
array contains integers and the size (in bytes) of integers If you don't have any element to create a Numpy
is 8 bytes. array, you can still create an empty array. Function is
used to create an empty array and an array of specified
9.4(vi) Re Shape: size and dtype into which the actual data can be stored
The reshape ( ) method is used to reshape an array. when required, empty ( ) function is an array created
The reshape ( ) function associated with the Nd array is with random garbage value.
used to revisit the arrays. The syntax of reshape ( ) # syntax of the empty function empty (shape, dtype)
function of Numpy array in Python is as follows–
Syntax– numpy⋅reshape (array⋅shape order = 'c') # python programming illustrating
Parameter– # numpy⋅empty method
array : [array_like] input array import numpy as yct
121
Search on TG: @apna_pdf
b = yct⋅empty (2, dtype = int) whether to store the multi-dimensional array in row-
print ("\n matrix b: \n", b) major (C-style) or column-major (Fortran-style) order in
a = yct⋅empty ([2, 2], dtype = int) memory.
print ("\n matrix b:\n", b) Example– import numpy as np
a = yct⋅empty ([2, 2], d type = int) array_1d = np⋅ones (3)
print ("\n matrix a:\n", a) print (array_1d)
c = yct⋅empty ([3, 3]) Output:
print ("\n matrix c : \n", c) [1.1.1]
Output: Example– Numpy array with int data type
Matrix b: import numpy as np
[ 01079574528] array_2d_int = np⋅ones ((2.3), dtype= int)
Matrix a: print (array_2d_int)
[[00] Output:
[00]] [[1 1 1]
[1 1 1]]
Matrix a:
[[0.0.0.] 9.5(iv) copy ( ):
[0.0.0.] When assigning a part of an array to another array,
[0.0.0]] the array you create specifies the original array in
memory. So any change in the new array will be
9.5(ii) zero ( ): reflected in the original array as well. To avoid this, you
The Python numpy⋅zeros ( ) function returns a new can use the copy () function, which returns a copy of the
array of the given size and type, with the element's value array.
as 0. mumpy zero ( ) function syntax is as follows– syntax– numpy-ndarray-copy (order = 'c')
zero (shape, dtype = None, order = 'c') size is an int parameter– order controls the memory layout of the
or tuple of ints to define the size of the array. dtype is an copy.
optional parameter with default value as float. It is used
to specify the data type of the array, for example, int Example– # python program explaining
order defines whether a multi-dimensional array is stored # numpy⋅ndarray⋅copy ( ) function
in row-major (c-style) or column major (fortran-style) import numpy as yct
order in memory whether to do or not. x = yct⋅array ([[0,1,2,3], [4,5,6,7]], order = 'F')
(1) Creating One dimensional array with zeros– print ("x is : \n", x)
import numpy as np # copying x to y
array_1d = np⋅zeros (3) y = x⋅copy ( )
print (array_1d) print ("y is : \n", y)
Output: print (" \n x i copied to y")
[0.0.0] Output:
x is
The element has the default data type as float so, It [[0 1 2 3]
is zero (0). [4 5 6 7]]
y is
(2) To create Multi_dimensional array– [[0 1 2 3]
import numpy as np [4 5 6 7]]
array_2d = np⋅zeros ((2, 3)) x is copied to y
print (array_2d)
Output: Example– # python program explaining
[[0.0.0] # numpy⋅ndarray⋅copy ( ) function
[0.0.0]] import numpy as yct
x = yct⋅array ([[0, 1], [2, 3]])
(3) Numpy zero arrays with int data type– print (" x is : \n", x)
import numpy as np # copying x to y
array_2d_int = np⋅zeros (( 2, 3))
dtype = int print (array_2d_int) y = x⋅copy ( )
Output: # filling x with 1's
[[000] x⋅fill (1)
[000]] print ("\n Now x is : \n", x)
print ("\n y is : \n", y)
9.5(iii) ones ( ): Output: X is
The Python numpy⋅ones ( ) function returns a new [[0 1]
array of the given shape and data type, with the element's [2 3]]
value set to 1. Now x is :
syntax– ones (shape, dtype = None, order = 'c') [[1 1]
Shape is used to define the shape of the array. dtype [1 1]]
y is
is an optional parameter with a default value of float. It
[[0 1]
specifies the data type of the array and the order defines
[2 3]]
122
Search on TG: @apna_pdf
9.6 Array Creation Routine: import numpy as np
arrange ( ) is a function based on a numerical range. x = [1, 2, 3]
For this, there is numpy⋅arrange (start, stop, step, dtype) a = np⋅asarray (x)
syntax. In this; print a
start– Represents the starting value of the array.
stop– It defines the end of the array and Not Output:
included in array. [1 2 3]
step− This is the number that defines the difference
between every two consecutive values in the Example 2–
array. # dtype is set
dtype– It specifies a data type for the Numpy array.
import numpy as np
It creates an instance of ndarray with evenly spaced x = [1, 2, 3]
values and returns a reference to it. a = np⋅asarray (x, dtype = float)
Providing One Range Argument– At least one print a
argument must be provided. Output:
>>> np.arrange (start = 0, stop = 10, step = 1)
array ([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]) [1. 2. 3]
>>> np.arrange (0, 10, 1)
arrary ([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]) Example 3–
>>> np⋅arrange (start = 0, stop = 10) # nd array from tuple import numpy as np
array ([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]) x = (1, 2, 3)
>>> np⋅arrange (0, 10) a = np⋅as array (x)
array [(0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
print a
Providing Negative Argument– If you provide a Output:
negative value for Start or both Start and Stop and Step is [1 2 3]
positive, arrange ( ) will behave like all positive
arguments. Example 4–
Example– >>> np⋅arrange (–5, –1)
array ([–5, –4, –3, –2]) # ndarray from list of tuples import
>>> np⋅arrange (–8, –2, 2) numpy as np
array ([–8, –6, –4]) x = [(1, 2, 3), (4, 5)]
>>> np⋅arrange (–5, 6, 4) a = np⋅asarray (x)
arragy ([–5, –1, 3]) print a
In the above example you can see that the counting Output:
starts from the start value and increments step by step
and ends at stop. [(1, 2, 3) (4, 5)]
Counting Backwards– Sometimes you want an
array with values decreasing from left to right. In such numpy.from buffer− This function interprets a
cases you can use negative values for step and start for buffer as a one dimensional array. Any objects that make
arrange ( ). up the buffer interface are used as parameters to return
Example– >>> np⋅arrange (5, 1, –1) the ndarray.
array ([5, 4, 3, 2]) numpy.from buffer (buffer, dtype = float, count =
>>> np⋅arrange (7, 0, –3) –1,offset = 0)
array ([7, 4, 11])
9.7 Array from Existing Data: The constructor takes the following parameters.
Array is created from the existing data using these
functions. Buffer– any object that represents the buffer
numpy⋅marray ( )– This function is similar to interface.
numpy array except for the fact that it has fewer dype– return data type of ndaray defaults to float
parameters. This routine is useful for converting a Counting– the number of items to read,
Python sequence to an ndarray. Default– means all data
mumpy⋅asarray (a, dtye None, Order = None) Offset– from the starting position defaults to 0 for
The constructor takes the following parameters– reading
a- Input data in any form like list, list of tuples, tuple Example–
of tuples or tuple of list. By default the data type of input import numpy as np
data is applied to the resulting ndarray. s = 'Hello.world'
Order– C (row-major) or F (column-major) C is the a = np.from buffer (s, dtype= '1']
default. print a
Output:
Example 1–
# convert list to ndarray ['H' 'e' 'l' 'l' 'o' 'w' 'o' 'r' 'l' 'd']
123
Search on TG: @apna_pdf
9.8 Array from Numerical Range: Stop– The final value of the sequence is base stop.
Numerical Range: np⋅arrange, np⋅linspace, np⋅log, num– The number of values within the range. Default
space. is 50.
end point− If True, Stop is the last value of the range.
9.8(i) np⋅arange: Base− The base of the log space, default is 10.
arrange ( ) is a function based on a numerical range. dtype– The data type of the output array, if not
For this, there is numpy-arrange (start, stop, step, dtype) specified, depends on the other input arguments.
syntax. In this, Example– import numpy as np
start– Represents the starting value of the array. # default base is 10
stop– It defines the end of the array and not
a = np⋅logspace (1.0, 2.0, mum = 10)
included in the array.
step– This is the number that defines the difference print a
between every two consecutive values in the Output:
array. [10. 12.91549665 16.68100537 21.5443469
dtype– It specifies a data type for the Numpy array. 27.82552402 35.93813664 46.41588834
59.94842503 77.42636827 100.]
9.8(ii) np⋅linspace: Example– # set base of log space to 2 import
This function is similar to the arrange ( ) function. In numpy as np
this function, instead of step size, equally spaced values
are used between intervals. The number is specified. The a = np.logspace (1, 10, num =10, base =2)
usage of this function is as follows– print a
Syntax– numpy-linspace (start, stop, num, end point. Output:
ret step, dtype) [2. 4. 8. 16. 32. 64. 128.
Parameter– 256. 512. 1024.]
Start– sequence's starting value 9.9 Indexing and Slicing:
Stop– The last value of the sequence, included in the Numpy creates an appropriate scale index when the
sequence if stop point is set to True. number is created. To access single or multiple items of
num– The number of equally spaced samples to be an array, a sequential array is passed in square brackets.
generated defaults to 50. 2D dimensional array contains a pair of values in
end point– True by default so the Stop value is included which the first value is a row index and the second is a
in the sequence. If False then does not include. column index. To analyze and manipulate array objects,
ret step– If True, returns the sample and returns the step it is necessary to know the basics of array indexing. It is
between the consecutive numbers. necessary to know Numpy array.
dtype– Output ndarray of type Numpy provides several methods for array
Example 1– import numpy as np indexing–
x = np⋅linspace (10, 20, 5) Integer Array Indexing– In this method, a list is
print x given for indexing for each dimension. A new arbitrary
Output: array is created by mapping the corresponding elements
[10. 12.5 15. 17.5 20.] one by one.
Boolean Array Indexing– This method is used
Example 2– # end point set to false when we want to index the elements created on the basis
import numpy as np of satisfied condition.
x = np.linspace (10, 20, 5 end point = false) Slicing in Numpy arrays is a way of removing a
print x series of elements from an array. Slicing in the array is
Output: performed same as in Python arrays. It cannot be used to
[10. 12. 14. 16. 18.] extend the size of any Array⋅ Array can be multi
dimensional, you need to specify slice for each
Example 3– # find retstep value dimension of array, on multiple dimensions slicing. The
import numpy as np syntax for slicing is as follows–
x = np⋅linspace (1, 2, 5, ret step = True) Syntax– Array name [<start> : <stop> : <step>]
print x
# retstep here is 0.25 When values are not specified for <start>, <stop> or
Output: <step>, Python assumes its default values.
(array ([1. , 1.25, 1.5, 1.75, 2.]), 0.25) Example– Indexing:
9.8(iii) numpy⋅logspace: import numpy as np
This function returns an ndarray object containing arr = np.arange (1, 10, 2)
numbers that are evenly spaced on a log scale. The start print (" Elements of array: " , arr)
and stop points of the scale are the indices of the base, arr1 = arr [np⋅array ([4, 0, 2, –1, –2])]
default 10. print ("Indexed Elements of array arr : " ;
arr1)
Syntax– numpy⋅logspace (start, stop, num, end point,
Output:
Parameter– Elements of array : [1 3 5 7 9]
Start– The starting point of the sequence is base start. Indexed Elements of array arr : [9 1 5 9 7]
124
Search on TG: @apna_pdf
Example– 1D Indexing Joining array using stack;
import numpy as np Stacking is used to join arrays of the same
arr 1 = np⋅arange (4) dimension along a new Axis. There are three types of
print ("Array arr 11 : " , arr 1) stack– Horizontal stack (hstack), Vertical stack
print ("Element at index 0 of arr 1 is:" (vstack), Height stack (dstack)
arr 1 [0]) Horizontal stack is done with Rows.
print ("Element at index 1 of arr 1 is:", Example– import numpy as np
arr 1 [1]) arr 1 = ([1, 2, 3, 4])
Output: arr 2 = ([5, 6, 7, 8])
Array arr 1 : [0 1 2 3] arr = np⋅hstack ((arr 1, arr2))
Element at index 0 of arr 1 is : 0 print (arr)
Element at index 1 of arr 1 is : 1 >>> [1 2 3 4 5 6 7 8 ]
Example–2D Indexing Vertical stack is done with columns.
arr = np⋅arange (12)
arr1 = arr⋅reshape (3, 4) Example– import numpy as np
print ("Array arr 1:\n", arr 1) arr 1 = np⋅array ([1, 2, 3, 4])
print ("Element at 0th row and 0th column of arr 2 = np⋅array ([5, 6, 7, 8])
arr 1 is :", arr 1 [0, 0]) arr = np.v stack ((arr 1, arr 2))
print ("Element at 1st row and 2nd column of print (arr)
arr 1 is", arr 1 [1, 2]) >>> [[1 2 3 4]
Output: [5 6 7 8]]
Array arr 1 :
[[0 1 2 3] Height stacking is used to stack with height.
[4 5 6 7] Example– import numpy as np
[8 9 10 11]] arr 1 = ([1, 2, 3, 4])
Element of 0th row and 0th column of arr 1 is:0 arr 2 = ([5, 6, 7, 8])
Element of 1st row and 2nd column of arr 1 is:6 arr = np⋅dstack (arr 1, arr 2)
Example– Slicing print (arr)
import numpy as np >>> [[[1 5]
a = np⋅arrange (10) [2 6]
s = slice (2, 7, 2) [3 7]
print a [s] [4 8]]]
Output: [2 4 6] Split functions are the exact opposite of join
operations. Join function joins multiple arrays into one
Example– # slice single item whereas Stack breaks one array into multiple arrays. To
import numpy as np split array use array_stack ( ).
a = np⋅arange (10) import numpy as np
b = a[5] arr 1 = ([1, 2, 3, 4, 5, 6])
print b arr = np.array_split (arr1, 3)
Output: 5 print (arr)
>>> [array ([1, 2]), array ([3, 4]), array ([5, 6])]
Example– # slice items starting from index
import numpy as np If the array has less elements than required then it
will adjust the end accordingly.
a = np⋅arange (10)
print a [2 :]
Output: [2 3 4 5 6 7 8 9] 9.11 Arithmetic Operation on Array:
Numpy provides efficient data storage as well as
Example– # slice items between indexes arithmetic operations as– add ( ), subtract ( ), multiply ( )
import numpy as np and divide ( ) the input array must either be of equal size
a = np⋅arange (10) or follow the array broadcasting rules.
print a [2:5] Example– import numpy as np
Output: [2 3 4] a = np⋅arrange (9⋅dtype = np⋅float_)⋅reshape (3, 3)
9.10 Joining and Spliting: print first array ∵
Joining an array means adding two or more array
contents into a single array. We do this using print a
Concatenate ( ) along the axis. If the axis is not passed print '\n'
then it is taken as 0 (zero). print 'seond array:'
Example– # import numpy as np b = np⋅array ([10, 10, 10])
arr 1 = ([1, 2, 3]) print b
arr 2 = ([4, 5, 6]) print '\n'
arr = np⋅concatenate (arr 1, arr 2) print 'Add the two arrays:'
print (arr) print np⋅add (a, b)
Output: [1 2 3 4 5 6] print '\n'
125
Search on TG: @apna_pdf
print 'multiply the two arrays:' [13. 14. 15.]
print np⋅multiply (a, b) [16. 17. 18.]]
print '\n' subtract the two arrays:
print 'Divide the two arrays:' [[–10. –9. –8.]
print np⋅divide (a, b) [–7. –6. –5.]
Output: First array: [–4. –3. –2.]]
[[0.1. 2.] multiply the two arrays:
[3. 4. 5.] [[0. 10. 20.]
[30. 40. 50.]
[6. 7. 8.] [60. 70. 80.]]
second array: Divide the two arrays:
[10 10 10] [[0. 0.1 0.2]
Add the two arrays: [0.3 0.4 0.5]
[[10. 11. 12.] [0.6 0.7 0.8]]
Practice Questions with Explanatory Solutions
1. What is Standard for Database Interfaces in 5. The correct syntax of reshape ( ) function in
Python? Most Python database interfaces follow numpy array python is–
this standard: (a) reshape (shape)
(a) SB-API (b) BD-API (b) reshape (array,shape)
(c) reshape (shape, array)
(c) DB-API (d) BS-API (d) all of the above.
Ans.(c) The Python standard for database interfaces is Ans. (b) reshape ( ) method is used to re-open an
the Python DB–API. Most Python database interfaces array. The reshape ( ) function associated with the
follow this standard. ndarray object is used to reshape the array. The correct
2. What do we install into system by numpy to syntax for the reshape ( ) function in Python is reshape
install pip? (array⋅shape)
(a) numpy (b) split 6. Which of the following attributes should be used
(c) ipython (d) none of these while checking for input combinations and
Ans.(a) Numpy (Numerical Python) is an open source outputs?
(a) ⋅types (b) ⋅class
library for the Python programming language. The
(c) ⋅type (d) All of the above.
easiest way to install Numpy is to install Numpy using
Ans. (a) ⋅types attribute should be used when
pip, a package manager for installing and managing
checking for input combinations and outputs.
Python software packages. Unlike Python, pip doesn't
7. Determines the attributes of the array–
come preinstalled on most operating systems so you'll (a) size shape (b) memory consumption
need to set up a package manager that matches the (c) data type of array (d) All of the above.
version of Python which you have. If you have both Ans. (d) Numpy array contains a set of attributes that
versions of python then install both pip versions as you can access. Some important features of Numpy
well. object are–
3. Dividing an array into several parts is called– • Ndim– Displays the dimensions of the array.
(a) splitting (b) Numpy • Size– Returns a set of integers indicating the size
(c) string (d) operating of the array.
Ans. (a) Splitting is the reverse operation of Joining. • Shape− Returns the total number of elements in the
Numpy array.
Splitting an array into multiple parts is called array
• Dtype– Returns the element type in the array, like
splitting. Single array to split an array into multiple float 3.6
arrays, np split, np⋅hsplit and np vsplit are used. • Item– Returns the length of each element at index
4. What will be the output of the following python in bytes.
code? 8. Numpy array is used on List because–
import functools (a) Numpy array contains contiguous memory
l = [1,2,3,4,5] locations
m =functools⋅reduce (lambdax, y:x if x>y else y,1) (b) They are quicker to work together.
Print (m) (c) They are more convenient to deal with.
(d) All of the above.
(a) Error (b) Address of m
Ans.(d) Numpy array is used over list because Numpy
(c) 1 (d) 5
array has memory location. Together they work faster
Ans. (d) The function has been imported into the and are more convenient to deal with. NumPy is
code. Executing the given code will yield output 5. 'Numeric Python'. It is an open source module for
A module in Python is simply a file containing Python that performs fast mathematical operations on
Python definitions and statements. arrays and matrices.
126
Search on TG: @apna_pdf
9. The number in ndarray is called its………….. Ans. (b) When a part of an array is assigned to
axes– another array, the new array refers to the original array
(a) rank (b) dtype in memory. That is, if any change is made in the new
(c) shape (d) none of these
array, this change will be visible in the original array
Ans. (d) The Numpy array data structure is also called
ndarray, which is short for n-dimensional index. In also. To avoid this, the Copy ( ) method is used. The
this 1-A one-dimensional index is called a vector and copy method makes a complete copy of the array and
a 2-dimensional array is called a matrix. its data.
The number of ndarray is called its dimension axes. 16. Returns the element type in the array–
10. Getting and setting the values of individual array (a) ndtype (b) numpy
elements– (c) dtype (d) stack
(a) Indexing (b) slicing Ans. (c) Array attribute contains Ndim, Shape, Size,
(c) Re-shaping (d) none of these Dtype, item and reshape in which Dtype returns the
Ans.(c) Getting and setting the value of individual type of the element in the array like int32, float 6.4
array element is called re-shaping for Reopen an array
you can use reshape ( ) method. 17. What is random garbage value?
11. Which of the following keywords are used to use (a) empty ( ) (b) copy ( )
the numpy module in Python? (c) numpy ( ) (d) none of these
(a) form (b) access Ans. (a) empty ( ) returns a new one of the given
(c) import (d) none of these shape and type without initializing the entries. In
Ans. (c) Numpy is 'Numeric Python' It is an open which you can store real data anytime as per
source module of Python, which performs fast requirement. empty ( ) are arrays created with random
mathematical operations on arrays and matrices. To garbage values.
use the numpy module in Python, you have to import
your module with a using statement. For this import 18. Numpy array........... specifies a named group of
keyword is used. elements.
12. Which of the following functions joins a 1D array (a) slicing (b) Homogeneous
into a 2D array in the form of columns? (c) array splitting (d) none of these
(a) row-stack (b) com_stack Ans. (b) Numpy array specifies a named set of
(c) column_stack (d) none of these elements, usually Homogeneous. Each item stored in
Ans.(c) Column Stack is used to add 1-D array as an array is called an element. Each position of an
column to 2D array. It takes a sequence of ID arrays element in an array has a numeric index that is used to
and stacks them as columns to form a single 2D array. identify the element.
The syntax used for this type is–
19. What is Numpy array data structure called?
Syntax– numpy⋅column_stack (tup)
(a) ndarray (b) copy
13. Which of the following is contained in Numpy (c) numpy (d) Scipy
Library?
(a) n-dimensional array object Ans. (a) The Numpy array data structure is called
(b) C Integrating Tools / C++ and Fortron code ndarray, which is short for N–dimensional array.
(c) Fourier transform Numpy works with Python objects which are called
(d) All of the above. multi dimensional. In ndarray, 1–dimensional array is
Ans.(d) The features inherent in Numpy array are as called vector and 2–dimensional array is called matrix.
follows– 20. Which function returns its argument with a
• A powerful N dimensional array object modified shape
C Integrated Tools / C++ and Fortron code (a) copy (b) reset
• Fourier transform (c) Nampay (d) Reshape
• Useful for sophisticated linear algebra and random Ans.(d) The reshape function returns its argument
number capabilities. with a modified shape. To re-open an array, you can
use the reshape ( ) method.
14. Axes are always counted for ndarray on– 21. What will be output for the following code?
(a) 0 (b) 1 import numpy as np
(c) 3 (d) 5 a = np.array([[1,2,3],[0,14],[11,22,33]])
Ans. (a) Numpy specifies the dimensions of its index print (a.size)
as axes. Numpy are always numbered at 0. The size of (a) 1 (b) 3
an array depends on the integer list along each (c) 9 (d) 4
dimension giving the size of the array. Ans.(c) This feature counts the total number of
15. The copy method makes a complete copy of the elements present in the Numpy array.
array and its data. Which method is used to avoid import numpy as np
this? a = np.array([[1,2,3][0,1,4],[11,22,33]])
(a) reshape ( ) (b) Copy ( ) print (a.size)
(c) split ( ) (d) none of these Will get 9 as output.
127
Search on TG: @apna_pdf
22. What is the purpose of zeros ( ) function used in 27. What is the output of the following code?
Numpy array? import numpy as np
(a) To make a Matrix with all diagonal element a = np.array([[1,2,3]])
(b) To make a Matrix with first row 0 print(a.shape)
(c) To make a Matrix with all element 0/ (a) (2, 3) (b) (3, 1)
(d) None of the above (c) (1, 3) (d) None of these
Ans.(c): 'zeros ( )' function is used to get a new array Ans.(c): Generally, shape( ) method is used in Python
of size and type filled with zeros.
to get the dimensions of Padas and Numpy type
Syntax–
objects. That's why (1, 3) will be obtained as output.
numpy.zeros(a, dtype = One, order = 'k', subok= True)
Hence option (c) would be the correct answer.
23. NumPy stands for?
(a) Numbering Python 28. What will be the output of the following?
(b) Number in Python import numpy as np
(c) Numerical Python a = np.arrya([1,5,4,7,81)
(d) Number for Python a=a+1
Ans. (e) NumPy stands for Numerical Python, and is a print(a[1])
major scientific computing library in Python. It (a) 4 (b) 5
provides efficient multidimensional array object. (c) 6 (d) 7
24. Which of the following variable declaration is Ans. (c): import numpy as np
incorrect? a= np.array ([1,5,4,7,8])
(a) a_ = 3 (b) _a = 3 a=a+1
(c) a? = 3 (d) All of these print(a[1])
Ans.(c) In Python, The output will be 6 because '1' will be added to = [1,
• The name of a variable must start with a letter or an 5, 7, 8] which is [2, 6, 8, 9] will be obtained. So
underscore character. according to the code a [1] = 6 will be obtained.
• A variable name cannot start with a number. 29. What will be the output of the following?
• A variable name can only be alpha-can contain import numpy as np
numeric characters and underscores (such as A-Z, 0- print(np.maximum ([2, 3, 4], [1, 5, 2]))
9 and more). (b) [154] (a) [152]
• The name of a variable is case sensitive (e.g. 'age', (c) (234) (d) (254]
'Age' and 'AGE' are three different types of Ans. (d): import numpy as np
variables.)
print(np.maximum([2, 3, 4], [1, 5,2]))
25. What will be the output of the following? will output as 254]. The 'maximum ( )' function
import numpy as np returns the maximum of the given array.
a = np.array([[1,2,3,4], [5,6,7,8], [9,10,11,12]])
print(a[2,2]) 30. What will be the output of the following?import
(a) 7 (b) 11 numpy as np
(c) 10 (d) 8 a = np.array([2, 3, 4, 5])b = np.arange(4)
Ans. (b): import numpy as np print(a+b)
a= np.array([[1,2,3,4], [5,6,7,8], [9,10,11,12]]) (a) [2345] (b) 3456]
print(a[2,2]) (c) [1234] (d) [2468]
as output Will get '11'. Ans. (d) : 'arange()' function is used to get equally
26. What will be the output of the following code? spaced values within a given interval. [2 4 6 8] will be
import numpy as np obtained as output.
a = np.array([1,2,3,5,8]) 31. What is the output of the following code?
b = np.array([0,1,5,4,2]) import numpy as np
c = a+b y = np.array([[11, 12, 13, 14], [32, 33, 34, 35]])
print (c[2]) print(y.ndim)
(a) 6 (b) 24 (a) 1 (b) 2
(c) 0 (d) None of these (c) 3 (d) 0
Ans. (b) a = [1,2,3,5,8] Ans. (b) Numpy is a Python library used to work with
b = [0,1,5,4,2] arrays. It also contains functions for working in the
c=a+b domain of linear algebra, the Courier matrix
c = [1,3,8,9,10] transform.
c = c*a ndim–Numpy arrays provide the ndim attribute that
c = [1,6,24,45,80] returns an integer that tells us how many dimensions
So [2] will be 24 as output. the array has.

128

You might also like