O_Level_Module_3_M3_R5_Programming_&_Problem_Solving_Through_Python
O_Level_Module_3_M3_R5_Programming_&_Problem_Solving_Through_Python
O'level
Module-3[M3-R5]
Programming and Problem
Solving Through Python
Language
Study Material
&
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
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.
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–
20
Search on TG: @apna_pdf
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–
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–
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
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.
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.
30
Search on TG: @apna_pdf
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
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.
52
Search on TG: @apna_pdf
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
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)))
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')]
6 FUNCTIONS
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
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
9 NUMPY
128