Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Python Basics (Notes)

Download as pdf or txt
Download as pdf or txt
You are on page 1of 92

PPS Unit-I DIT,Pimpri

Dr. D. Y. PATIL INSTITUTE OF TECHNOLOGY, PIMPRI, PUNE-18


Department of First Year Engineering
Programming and Problem Solving
Unit- 1 Notes

Unit I: Problem Solving, Programming and Python Programming

1.1 General Problem Solving Concepts

1.1.1 Problem Solving in Everyday Life:

Q.1. Define Problem. What are steps in problem solving?


Definition of problem
Problem is defined as a situation or issue or condition which needs to be solve
to achieve a specific goal.
Steps in problem solving
1. Identify the problem - You need to be clear about what exactly the problem
is. If the problem is not identified then it cannot be solved. example- when
you want to learn a language then first identify which language do you want to
learn
2. Understand the problem - Here problem should be defined properly so that
it helps in understanding the problem more. It helps to understand knowledge
base of the problem. It helps in finding a target for what you want to achieve.
3. Identify alternative ways to solve the problem - This step is very crucial
because until and unless we explore all options, finding a correct solution is
next to possible. This involves the process to create a list of solutions.
4. Select the best way to solve the problem - Identify and evaluate pros and
cons of each possible solution and then select the best solution. Selecting
proper way from alternatives require a lot of study and need to study con-
sequences as well.
5. List instructions that enable you to solve the problem using
selected solution - Here we need to list out the steps which should
1
PPS Unit-I DIT,Pimpri

be followed so that anyone can solve the problem. This should be in


detail and precise at the same time.
6. Evaluate the solution - It mean to test the solution and check if the
result is satisfactory or not.
Example: I am always late for college
(i) Identification: getting late for college.
(ii) Understanding: (List out probable reasons of or getting late)
(Sleeping late, waking up late, Transportation, etc.)
(iii) List out alternative ways – (Solutions)
(a). Sleeping early at home.
(b). Waking up early.
(c). Waking alarm.
(d). Resolving travelling issue.
(iv) Select the best way – Sleeping early in night.
(v) List out the procedure
(a). Having dinner as early as possible.
(b). Avoid use of mobile phones in night.
(c). Completing homework as early as possible. (d). Then going early to bed.
(vi) Evaluate the solution: Reached College on time.

1.1.2 Types of problems:

Q. 2. Explain types of problems in detail?


Ans:
Problem can be categorized into two types depending on how the solution is found out or
the approach which is followed to get that solution.
(i) Algorithmic solution
(a) These problems are solved by following some procedure or steps.
(b) For example: baking a cake. It can be done by following a series of instruction
And we can expect results.
(c) Here following some predefined process needs to be done.
(d) Here solution is quite straight forward.
(ii) Heuristic solution
(a) These types of problems solved using knowledge based i.e. by collecting
information about the problem.
(b) For example: Expanding one’s business.
2
PPS Unit-I DIT,Pimpri

(c) In this type of approach there is no straight forward defined path which we can
follow to solve a problem.
(d) We need to build that path based on trial and error.
(e) In this approach experience and knowledge is very important.

1.1.3 Problem Solving with computers:

Q. 3. Write a note on Problem solving with computers.


Ans: Computer is a multi-purpose electronic machine which is used for storing,
organizing and processing the data.
Computer is not able to find the solution by itself; rather the computer is a machine
which follows the instruction given by programmer to solve any problem.
So all the efforts required to understand the problem and define procedure to solve that
problem are taken by programmer ( a human being).

Problem Definition:
Before a program is written for solving a problem, it is important to define the
problem clearly.
Define problem: Problem is defined as a situation or issue or condition
which needs to solve to achieve the goal.
For most of the software projects, the system analyst approach system
users to collect user requirements and define the problem that the system
aims to solve.
System analyst typically looks at following issues:
o What input is required for achieving expected output?
o Expected output of the problem.
o Current method of solving the problem.
o Can the problem or part of the problem be more effectively solved by a
software solution?
o Computers are built to deal with algorithmic solutions, which are often
difficult or very time consuming for humans.

3
PPS Unit-I DIT,Pimpri

Solution:
o Solution means the instructions listed during problem solving – the instructions
that must be followed to produce the best results.
o The result may be: More efficient, faster, more understandable or reusable.
Results:
o The result is outcome or the completed computer assisted answer.
o May take any form: Printout, updated files, output to monitor speakers, etc.
Program:
o Program is the set of instructions that make up the solution after they have been
coded into a particular computer language.

1.1.4 Difficulties with problem solving:

Q.4. Explain the difficulties with Problem solving?


Ans:
o Some people may not have got training regarding how to solve problems.
o Some may not able to make a decision for fear it will not be the correct one.
o There may be inaccuracy in defining the problem correctly or may not generate
the sufficient list of alternatives.
o While selecting best alternative, they may skip better alternative due to urgency.
o The problem solving process is difficult. It takes practice as well as time to
perfect, but in the long run the process proves to be of great benefit.
o Illogical sequencing of instructions: In the process of problem solving on the
computer, one of the most complicated jobs for the problem solver is writing the
instructions. Example: Consider a task to find which number is the maximum
from a set of three numbers. Near about everyone is immediately able to tell
which is the largest but several of them are unable to explain the steps they
followed to get the result. Computer is nothing but a machine that will perform
only task that the user can explain.

4
PPS Unit-I DIT,Pimpri

1.1.5 Problem Solving Aspects:

Q.6. What is modularization? Explain different approaches to design an


algorithm.
Ans:
Modularization:
For a complex problem, its algorithm is often divided into smaller units called modules.
This process of dividing an algorithm into modules is called as modularization.

Top down design approach:


 A top-down design approach starts by dividing the complex algorithm into
one or more functions.
 These functions can further be decomposed into one or more sub-functions,
and this process of decomposition is iterated until the desired level of module
complexity is achieved.
 Top-down design method is a form of stepwise refinement where we
begin with the topmost module and incrementally add functions that it calls.
 Therefore, in a top-down approach, we start from an abstract design and then
at each step, this design is refined into more concrete levels until a level is
reached that requires no further refinement.
Diagram: Top Down Approach

5
PPS Unit-I DIT,Pimpri

Bottom up design approach:


 It is just reverse of top down approach.
 In bottom up design, we start with designing the most basic or concrete modules
and then proceed towards designing higher level modules.
 The higher level modules are implemented by using the operations performed by
lower level modules.
 Thus, in this approach sub-modules are grouped together to form higher level
module.
 All the higher level modules are clubbed together to form even higher level
modules.
 This process is repeated until the design of the complete algorithm is obtained.

Difference between Top down and Bottom up approach:

Top-Down Approach Bottom-Up Approach

Divides a problem into smaller units and then Starts from solving small modules and
solve it. adding them up together.

This approach contains redundant information. Redundancy can easily be eliminated.

Communication among steps is


A well-established communication is not required. mandatory.

Works on the concept of data-hiding


The individual modules are thoroughly analysed. and encapsulation.

Structured programming languages such as C use OOP languages like C++ and Java,
top-down approach. etc. uses bottom-up mechanism.

The modules must be related for


Relation among modules is not always required. better communication and work flow.

Primarily used in code implementation, test case


generation, debugging and module documentation. Finds use primarily in testing.

6
PPS Unit-I DIT,Pimpri

1.1.6 Problem Solving Strategies:

Q.5. Explain the problem solving Strategies?


Ans.
Computer is a very powerful and versatile machine and can do any task given to it
provided that the programmer has already fed correct instructions to direct what, how and
when the steps have to be done to solve a particular problem. For this he should work to
develop a step by step solution to problem. These steps can be given as:
 Clearly define the problem in very simple and precise language.
 Analyse the problem to find out different ways to solve problem and decide the
best possible solution.
 Define the selected solution in a detailed step by step manner.
 Write the steps in a particular programming language so that it can be executed
by the computer.
The entire software development process is divided into a number of phases where each
phase performs a well defined task. Moreover, the outputof one phaseprovides the input
for subsequent phase. The phases in the software development life cycle (SDLC) process
are summarized as follows:

Fig: Software Development Life cycle (SDLC)

7
PPS Unit-I DIT,Pimpri

 Requirement Analysis: In this phase, the user’s expectations are gathered to know
why the software has to be built. The gathered requirements are analyzed to
decide scope of software. The last activity in this phase includes documenting
every identified requirement of the users in order to avoid any doubts regarding
functionality of software. The functionality, capability, performance and
availability of hardware and software components are all analyzed in this phase.

 Design: The requirements documented in previous phase act as an input to the


design phase. In the design phase, core structure of the software is broken down
into modules. The solution of the program is specified for each module in the
form of algorithms or flowcharts.

 Implementation: In this phase, the designed algorithms are converted into


program code using any of the high level languages. The particular choice of
language will depend on the type of program, such as whether it is system or
application program. This phase is also called as construction phase as the code of
the software is generated in this phase. While constructing the code, the
development team checks whether the software is compatible with available
hardware that are mentioned in requirement specification document.

 Testing: In this phase all modules are tested together to ensure that the overall
system works well as a whole product. In this phase the software is tested using a
large number of varied inputs, also known as test data, to ensure the software is
working as expected by user’s requirements.

 Software development, training and support: After the code is tested and the
software or the program has been approved by the users, it is installed or
deployed in the production environment. In this phase it becomes very crucial to
have training classes for users of software.

8
PPS Unit-I DIT,Pimpri

 Maintenance: Maintenance and enhancement are ongoing activities that are done
to cope with newly discovered problems or new requirements. Such activities
may take a long time to complete as the requirement may call for the addition of
new code that does not fit original design or an extra piece of code, required to fix
an unforeseen problem.

1.2 Program Design Tools

1. Algorithm
2. Flowchart
3. Pseudocode

Q.7. Discuss algorithm with example. Also enlist characteristics of good algorithm.
Ans:
Definition of algorithm
o An algorithm is precise, step-by-step set of instructions for solving a
computational problem.
o It is a set of ordered instructions which are written in simple English
language.
o In this type of problem solving the required input and expected outputs
are identified and according to that the processing will be done.
o Algorithms helps the programmer to write actual logic of a problem on
paper and validate it with the help of paper and pencil, and correct it if
any fault is noticed.

Characteristics of algorithms:
Precision: The instructions should be written in a precise manner.
Uniqueness: The outputs of each step should be unambiguous, i.e., they
should be unique and only depend on the input and the output of the
preceding steps.
Finiteness: Not even a single instruction must be repeated infinitely.

9
PPS Unit-I DIT,Pimpri

Effectiveness: The algorithm should be designed in such a way that it should


be the most effective among many different ways to solve a problem.
Input: The algorithm must receive an input. Algorithm may accept zero or more
inputs.
Output: After the algorithm gets terminated, the desired result must be obtained.
Generality: The algorithm can be applied to various set of inputs.

Example: Algorithm to calculate area of circle.


Algorithm: Area of circle
Input: R=Radius
Output:
A=Area
Steps:
Step 1:BEGIN
Step 2: Accept the R
Step3: Find the square of R and store it in
A=R*R Step4: Multiply R with 3.14 and
store the result in A Step5 :Display the value
of A
Step6: END

Q.8. Explain control structures used in algorithms.


Ans:

Q. Explain control structures used in algorithm?

Algorithm has finite number of steps and some steps may involve in decision making and
repetition. Broadly algorithm may apply three decision making structures

1. Sequence:
 In sequence control structure each step of the algorithm is executed in the
specific order.
 Algorithm performs the steps in a purely sequential order.
 Example:
Step 1: Start
Step 2: Input first number as A
Step 3: Input Second number as B
Step 4: Perform sum=A+B
Step 5: Display sum
Step 6: Stop

10
PPS Unit-I DIT,Pimpri

2. Decision:
 Decision control structures can be used for making decisions and
branching of statements, where the outcome of the process depends on
some condition.
 A condition in this context is any statement that may evaluate either to a
TRUE or FALSE value.
 This form is commonly known as the if—else construct.
 Example:
Step 1: Start
Step 2: Input first number as A
Step 3: Input Second number as B
Step 4: IF A==B
Print Equal
ELSE
Print Not Equal
Step 5: Stop
3. Repetition:
 These control structures are used for executing one or more steps for a
number of times.
 It can be implemented using constructs such as for loop, while loop etc.
 Example:
Step 1: Start
Step 2: Initialize I=1, N=10
Step 3: Repeat Steps 3 and 4 while I<=N
Step 4: Print I
Step 5: Set I=I+1
Step: Stop

Q.9. Write an algorithm to swap two numbers.


Ans:
Algorithm: Swap two numbers
Input: Two numbers Output: Swapped numbers
Step 1 : Start
Step 2 : READ num1, num2
Step 3 : temp = num1
Step 4 : num1 = num2
Step 5 : num2 = temp
Step 6 : PRINT num1, num2
Step 7 : Stop

11
PPS Unit-I DIT,Pimpri

Q.10. Write an algorithm to find largest number amongst three numbers.


Ans: Algorithm
Algorithm: Greatest Number
Input: Three Numbers
Output: Greatest among three Numbers
Steps:
Step 1:BEGIN
Step2: Read values for NUM 1, NUM2 and NUM3
Step3: if NUM1>NUM2
Check if Num1>NUM3,if true then display NUM 1 is Largest
number
Else check if NUM2>NUM1
Check if Num2>NUM3 display NUM 2 is Largest number
Else check if NUM3>NUM1
Check if Num3>NUM2 display NUM 3 is Largest number
Step4: END

Q.11. Define term Flowchart. Explain Symbols used in flowchart.


 A Flowchart is a graphical representation of a Algorithm.
 The sequence of steps in algorithm is maintained and represented in the
flowchart by using some standard symbols such as rectangles and directed
lines.
 As flowchart uses the pictorial representation of an algorithm, it becomes
easier to understand what is going on.
 One of the most common ways to express algorithm with writing a program
is a flowchart.
 Symbols used in flowchart:
Sr. Symbol Name of Symbol Use of Symbol
No
1 Start/End Terminal Indicate start and end of the algorithm.
Represented as rounded rectangle.
2 Action or Process Indicate set of operations like
assignments, Initialization calculations
etc.
3 Decision Indicates the decision making
statements. It indicates a condition on
which decision are made.
4 Input/Output Indicate Input provided to algorithm
and outputs processed by algorithm. It
is represented by parallelogram.

12
PPS Unit-I DIT,Pimpri

5 Flow line Indicates the flow of algorithm.


Represented as arrow of line.

6 On page Connector To connect parts of algorithm. This


symbol is used if the parts are on same
page

7 Off Page Connector To connect parts of algorithm. This


symbol is used if the parts are on
different page

Q.12. Draw a flowchart to find greater number amongst two num0bers.

Q.13. Draw a flowchart to check whether a given number is even or odd.

13
PPS Unit-I DIT,Pimpri

Q. 14. Explain various program design tools.


Ans:
Algorithm:
Definition: An algorithm is precise, step-by-step set of instructions for solving a
computational problem.
Example:
Algorithm : To calculate area of circle
Input: R=Radius
Output: A=Area
Steps:
Step 1: Begin
Step 2: Accept R
Step3: Compute area= 3.14*R*R
Step4 :Display the value of area
Step5: End

Flowchart:
Definition: Flowchart is graphical representation of computation and
provides visual description of solution/algorithm step by step.
Example:
Flowchart for calculating area of circle

Pseudocode:
Definition: It is compact informal representation of algorithm. It is written in
natural language with description of the details and compact mathematical
notations.
Example:
Student is Pass or Fail
If student’s grade is greater than or equal
to 60 Print ”Passes”
14
PPS Unit-I DIT,Pimpri

Else
Print “Failed”

1.3 Features of Python

Q.15. Explain various features of python.


Ans.
1. Simple: Python is simple and small language. Reading a program written in
python feels like reading English.
2. Easy to Learn: Python programming is clearly defined and easily readable.
3. Versatile: Python supports wide variety range of applications ranging from text
processing to Web applications
4. Free and Open Source: Python software is freely available on internet
5. High Level Language: Programmers don’t have to worry about low level details
like managing memory used by program etc.
6. Interactive: Programs in python works in interactive mode
7. Portable (Platform Independent): Python is portable language. Program can
work similarly on different platform like window, Linux, Macintosh, Solaris etc.
8. Object Oriented: Python supports Object oriented style of programming like
C++, Java languages. It support features like C class, Objects, Inheritance etc.
9. Interpreted: Python is processed at run time by the interpreter. So no need to
compile program before executing it.
10. Scalability: Python support modular programming, so programmer can add
module at any stage of the program
11. Secure: Python programming environment is secure from tempering

1.4 History and Future of Python

 Python is a general purpose interpreted interactive object oriented and high level
programming language.
 It was first introduced in 1991 by Guido van Rossum, a Dutch computer
programmer.
 The language places strong emphasis on code reliability and simplicity so that the

15
PPS Unit-I DIT,Pimpri

programmers can develop applications rapidly


 Python is multi-paradigm programming language, which allows user to code in
several different programming styles.
 Python supports cross platform development and is available through open
source. Python is widely used for scripting in Game menu applications effectively

History of Python:

 Python is created by Guido Van Rossum in the 1980s.


 Rossum published the first version of Python code (0.9.0) in February 1991 at the
CWI (Centrum Wiskunde & Informatics) in the Netherlands , Amsterdam.
 Python is derived from ABC programming language, which is a general-purpose
programming language that had been developed at the CWI.
 Rossum chose the name "Python", since he was a big fan of Monty Python's
Flying Circus.
 Python is now maintained by a core development team at the institute, although
Rossum still holds a vital role in directing its progress.

Future of Python:

 Python’s userbase is vast and growing – it’s not going away any time soon.
 Utilized by the likes of Nokia, Google, and even NASA for it’s easy syntax, it looks
to have a bright future ahead of it supported by a huge community of OS developers.
 Its support of multiple programming paradigms, including object-oriented Python
programming, functional Python programming, and parallel programming models
makes it a highly adaptive choice – and its uptake keeps growing.

1.5 Writing and Executing Python Programs

 Open IDLE.
 Go to File > New.
 Write Python code in the file.

16
PPS Unit-I DIT,Pimpri

 Then save the file with .py extension. For example, hello.py, example.py etc.
You can give any name to the file. However, the file name should end with .py
 Run the program.

1.6 Literal Constants


The data that is provided in the variable are known as literals in Python. Python supports
the following literals:-

Types of literals with example


Python support the following literals:

4.1) Numbers:
Numbers as a name suggest, refers to a numeric value.
You can use three types of numbers in a python program. These include integers
floating point, and complex numbers.
 int- Number like 5 or other whole numbers are represented as integers.
 float- numbers like 3.23, 8.73 are termed as floating point numbers.
 Complex- numbers like a+bj form ( like 3+2j) are complex numbers

Remember that commas are never used in numeric literals or numeric values.
Although there is no limit to the size of integers that can be represented in python,
floating point numbers do have a limited range and limited precision. In python you
can have a floating point numbers in a range 10-308 to 10308 with 16 to 17 digits of
precision. In fact, large floating point numbers are efficiently represented in scientific
notation. For ex, 5.0012304*106 (6 digits of precision) can be written as
5.0012304e+6
Built-in format( ) function
Any floating point value may contain an arbitrary number of decimal places, so it is
always recommended to use the built-in format( ) function to produce a string version
of a number with a specific number of decimal places. Observe the difference
between the following outputs.

17
PPS Unit-I DIT,Pimpri

# Without using format( ) # using format( )


>>> float(16/(float(3))) >>> format(float(16/(float(3))),
5.333333333333333 '.2f')
'5.33'

Here .2f in the format() function round the result to two decimal places of accuracy in
the string produced.
For very large (or very small ) values, ‘e’ can be used as a format specifier.
The format() function can also be used to format floating point numbers in scientific
notation. Look at the result of the expression given below:
>>> format(3**50, '.5e')
'7.17898e+23'

The result is formatted in scientific notation with five decimal places


>>> format(123456,',')
'123,456'

Simple operations on numbers


Python can carry out simple operations on numbers. To perform calculation, simply
enter the numbers and the type of operations that need to be performed on them
directly into the python console, and it will print the answer, as shown in the
following examples.
>>> 10+7 >>> 5 * 3.0 >>> 12*10 >>> 152.78 // 3.0
17 15.0 120 50.0

4.2) String Literals:


A string is a group of characters. If you want to use text in python you have to use
string.
Single quotes, double quotes or triple quotes are used to define String literals.

18
PPS Unit-I DIT,Pimpri

There are two kinds of strings supported in Python, single line and multiline string
literals.

Example:
str1 = ‘Amit’
str2 = "Ricky Ponting"
str3 = '''Welcome to python '''

String Literal Concatenation:


Python concatenates two string literals that are placed side by side.

>>> print('Beautiful Weather' '....' 'Seems it would rain')


Beautiful Weather....Seems it would rain

Escape Sequences:
Some characters (like “ ‘ \ ) cannot be directly included in string. Such characters must
be escaped by placing a backslash before them.
For example,
>>> print( 'What's your name?' )
SyntaxError: invalid syntax

We got this error, as python got confused where the string starts and ends. So, we need to
clearly specify that this single quote does not indicate the end of the string . This
indication can be given with the help of escape sequence.
For example,
>>> print('What\'s your name?')
What's your name?

19
PPS Unit-I DIT,Pimpri

You can use the escape sequence for the newline character (\n). Character following the
\n are moved to the next line.
>>> print("Today is 15th August. \n India became independent on this day.")
Today is 15th August.
India became independent on this day.

Another useful escape sequence is \t which inserts tab in a string.


>>> print("Hello..\t Welcome to python")
Hello.. Welcome to python

Note that when specifying a string, if a single backslash ( \ ) at the end of the line is
added , then it indicates that the string is continued in the next line, but no new line is
added otherwise.
For example,
>>> print("I have studied many programming languages. \
But my favorite language is python")
I have studied many programming languages. But my favorite language is
python

The different types of escape sequences used in Python


Escape Purpose Example Output
sequence
\\ Print Backslash print(“\\”) \
\’ Print single- print(“ \’ ”) ‘
quote
\” Print double- print(“ \” ”) “
quote
\a Rings Bell print(“\a”) Bell rings
\n Print a newline print(“Hello\n World”) Hello
World
\t Print tab print(“Hello \t World”) Hello World

20
PPS Unit-I DIT,Pimpri

1.7 Variables and Identifiers

Variables:

 Variable are just part of computer memory where information is stored.


 To identify these memory easily, each variable is given an appropriate name.
 Every variable is assigned a name which can be used to refer to the value later in
the program.
 Further it can be defined as ‘Variables are reserved memory locations that stores
values’.

 Rules for an Variable


o An Variable can only have alphanumeric characters (a-z , A-Z , 0-9) and
underscore(_).
o The first character of an identifier can only contain alphabet (a-z , A-Z) or
underscore (_).
o Keywords are not allowed to be used as Variable.
o No special characters, such as semicolon, period, whitespaces, slash or
comma are permitted to be used in or as Identifier.
o Variable are also case sensitive. For example name and Name are two
different Variable.

counter = 100 # An integer assignment


miles = 1000.0 # A floating point
name = "John" # A string

print counter
print miles
print name

Identifiers:

Q. What is identifier? Explain rules of identifiers.


Identifiers
Identifier is a collection of alphanumeric character used to give name to the programming
elements like variables, arrays, functions, etc.

21
PPS Unit-I DIT,Pimpri

Rules for constructing identifiers.


 Each identifier starts with an alphabet or underscore and then followed by any
number of alphabets, digits or underscore.
 Identifier should not start with digit
 Identifier is the unique name given to the element of a program.
 Identifiers are case sensitive, so the max and MAX considered as two different
identifiers.
 An Identifier should not contain special symbols, comma, or blank space.
 Identifiers are user-defined words so they should not be same as of the keywords
otherwise compiler will generate an error.

1.8 Data Types

Q. Explain different data types supported by python?


Ans:
1. Numbers
 They are defined as int, float and complex class in Python.
o int: It consists of all integer numbers. Integers can be either positive or
negative. Buil in size of integers is unlimited. Ex: -5, 0, 890 etc
o float: Float point numbers are written as decimal numbers separated by
decimal point. It is expressed in the form of integer number and
fractional part sepaprated by decimal point. Ex: -5.2, 11.325 etc.
o complex: Complex numbers are expressed in the form of a+bi, where
a is real part and b is imaginary part. Ex: 3+2i etc

2. String
 String is sequence of Unicode characters.
 We can use single quotes or double quotes to represent strings.
 Multi-line strings can be denoted using triple quotes, ''' or """.

>>>s = "This is a string"


>>>s = '''a multiline
3.Python List
 List is an ordered sequence of items.
 List represents collection of data elements (items).
 These data items can be of different data types.
 Items in list are separated by commas are enclosed within brackets [ ].
 Ex: a = [1, 2.2, 'python']
22
PPS Unit-I DIT,Pimpri

4. Python Tuple
 Tuple is an ordered sequence of items same as list.The only difference is that
tuples are immutable. Tuples once created cannot be modified.
 It is defined within parentheses () where items are separated by commas.
 Ex: t = (5,'program', 1+3j)

5. Dictionary
 Dictionary is an unordered collection of items in key:value pair of any type. In
dictionary values are separated by comma inside braces { }. ·
 In dictionary, key should be unique.
 Ex: a = {‘name’:’Bob’,’Age’: 21}

1.9 Input and Output operation


input() and print() functions are widely used for standard input and output operations
respectively.

1.input()
To allow flexibility we might want to take the input from the user. In Python, we have
the input() function to allow this.

Syntax:
input (expression)

2.print()
We use the print() function to output data to the standard output device (screen).
print() evaluates the expression before printing it on the monitor. Print statement outputs
an entire (complete) line and then goes to next line for subsequent output (s). To print
more than one item on a single line, comma (,) may be used.

Syntax:
print (expression/constant/variable)

23
PPS Unit-I DIT,Pimpri

Example:

x = input("Enter any value: ")


# printing value
print("Entered value is: ", x)

1.10 Comments

Q. Explain comments in python.


Ans:
· The comments are ignored by the interpreter and are used to add additional
information about the program or its statements.
· They can be written anywhere in the program.
· Two way comments can be given in Pyhton
1. One line comments using (#)
2. Multi line comments using (‘’’ ‘’’)
· Comments in Python begins with ’ #’ character.
· A comment may appear at the beginning of a line or can be placed after
whitespace or code, but not within a string literal.

Example:1
#This is first Python Program
print(“Hello World”) # prints Hello World

Example: 2
''' program is written for addition
Of two numberd '''
x=10
y=20;
Print(x+y)

1.11Reserved Words
Q. Explain keywords (reserved words) in python.

 In python there are certain words which have predefined meaning. They are
called as reserved words.
 Reserved words are also called as keywords.
 Reserved words cannot be used for naming an identifier.
 Example:
for, int, while etc.

and del for is raise


24
PPS Unit-I DIT,Pimpri

assert elif from lambda return


break else global not try
class except if or while
continue exec import pass with
def finally in print yield

1.12Indentation

Q. Write a note on indentation.


Ans.
 White space at the beginning of the line is called indentation.
 These white spaces or the indentation are very important in python.
 In python program, the leading white space and tabs at the beginning of the
logical line determines the indentation level of logical line.
 All statements inside block should be at same indentation level.
 Python checks the indentation level very strictly and gives an error if
indentation is not correct.
Use of indentation:
 In most of the programming languages, indentation has no effect on program
logic. It is used to align statements to make the code readable.
 However, in python indentation is used to associate and group statements.
Example:
Program to find number is even or odd
num = int(input("Enter a number: "))
if (num % 2) == 0:
print("Number is even")
else:
print("Number is Odd")

1.12Operators and Expressions

Q. What is operator? Enlist and explain types of operators in python.


Ans.
Python operators are symbols that are used to perform mathematical or logical
manipulations. Operands are the values or variables with which the operator is applied to,
and values of operands can manipulate by using the operators.

25
PPS Unit-I DIT,Pimpri

Types of Operators with explanation

Python language supports the following types of operators.

 Arithmetic Operators
+, -, *, /, %, /,**

Example:
x = 15
y=4
print('x + y =',x+y)
print('x - y =',x-y)
print('x * y =',x*y)
print('x / y =',x/y)
print('x // y =',x//y)
print('x ** y =',x**y)
Output:
x + y = 19
x - y = 11
x * y = 60
x / y = 3.75
x // y = 3
x ** y = 50625

 Comparison (Relational) Operators


<, >, <= ,>=, !=, <, >
When two operands are compared evaluated as either true of false. If True the
binary value is 1 , if false the binary value is 0.
True : 1
False : 0

Example:
x = 10
y = 12
print('x > y is',x>y)
print('x < y is',x<y)
print('x == y is',x==y)
print('x != y is',x!=y)
print('x >= y is',x>=y)
print('x <= y is',x<=y)
Output:
x > y is False
x < y is True
x == y is False
x != y is True
x >= y is False
x <= y is True
26
PPS Unit-I DIT,Pimpri

 Assignment Operators
= ,+=, -=, *=, /= , //=, %=
Example:

Operator Example Equivatent to

= x=5 x=5

+= x += 5 x=x+5

-= x -= 5 x=x-5

 Logical Operators
and , or, not
non zero numbers are evaluated as true while zero as false.
Operates number as whole no binary conversion is required.
Example:
x = True
y = False
print('x and y is',x and y)
print('x or y is',x or y)
print('not x is',not x)
Output:
x and y is False
x or y is True
not x is False

 Bitwise operators
&, |, ^, ~, >>, <<
Bitwise operators process individual bits of data.
Numbers are converted into binary form and then processed by bitwise operators.

Example:

& Bitwise AND x& y = 0 (0000 0000)

| Bitwise OR x | y = 14 (0000 1110)

~ Bitwise NOT ~x = -11 (1111 0101)

27
PPS Unit-I DIT,Pimpri

^ Bitwise XOR x ^ y = 14 (0000 1110)

>> Bitwise right shift x>> 2 = 2 (0000 0010)

<< Bitwise left shift x<< 2 = 40 (0010 1000)

 Identity Operators
is, is not
These operators checks if given items are identical and equal.
In python following identity operators are used
(a) is – returns true if given elements are equal and identical (identical means
both objects are having same reference location or memory location).
(b) is not – returns true if given elements are neither equal nor identical.

Example:
x1 = 5
y1 = 5
x2 = 'Hello'
y2 = 'Hello'
x3 = [1,2,3]
y3 = [1,2,3]
print(x1 is not y1)
print(x2 is y2)
print(x3 is y3)
Output:
False
True
False

 Membership operators
in, not in
These operators are used to check presence of any value or data in given range.
(a) in – returns true if that item exists in a list or a range.
(b) not in – returns true if that item does not exists in given list or a range.

Example:
x = 'Hello world'
y = {1:'a',2:'b'}
print('H' in x)
print('hello' not in x)
print(1 in y)
print('a' in y)
28
PPS Unit-I DIT,Pimpri

Output:
True
True
True
False

Operators Meaning

() Parentheses

** Exponent

+x, -x, ~x Unary plus, Unary minus, Bitwise NOT

Multiplication, Division, Floor division,


*, /, //, % Modulus

+, - Addition, Subtraction

<<, >> Bitwise shift operators

& Bitwise AND

^ Bitwise XOR

| Bitwise OR

==, !=, >, >=, <, <=, is, is not, in, not
in Comparisions, Identity, Membership operators

not Logical NOT

and Logical AND

or Logical OR

29
PPS Unit-I DIT,Pimpri

1.13Expressions in Python
 An expression is any valid combination of symbols like variables, constants and
operators that represents a value.
 In python, an expression must have at least one operand and can have one or more
operators.

 An Example of valid expression:


o A+B*C-5
o X=A/B
o Y=A^B

 An example of invalid expression:


o A+
o A*

 Python supports different types of expressions can be classified as:


1. Based on the position of operators in an expression:
a. Infix expression:
 Example: a=b-c
b. Prefix expression:
 Example: a=+bc
c. Postfix expression:
 Example: a=bc+

2. Based on the data type of the result obtained on evaluating an expression:


a. Constant expression:
 Example: 8+2-3
b. Integral expression:
 Example: a=10
c. Relational expression:
 Example: c=a>b
d. Logical expression:
 Example: a>b and a>c

30
PPS Unit-II DIT,Pimpri

Dr. D. Y. PATIL INSTITUTE OF TECHNOLOGY, PIMPRI, PUNE-18


Department of First Year Engineering
Programming and Problem Solving
Unit- 2 Notes
-----------------------------------------------------------------------------------

Unit II: Decision Control Statements

2.1 Selection/conditional Statements:


Q. Explain selection/conditional statements with flowchart

• The selection control statements usually jump from one part of code to another
depending on whether a particular condition is satisfied or not.
• It allow us to execute statements selectively (branch wise) based on certain
decisions.
• Python language supports different types of selection/conditional/branching
statements.
1. If statements
2. If....else statements
3. If…elif….else statements
4. Nested if

2.1.1 if
1. If statements:
• If statement is a simplest form of decision control statements that is frequently
used in decision making.
• If statements may include one statement or N statements enclosed within the if
block
• If the expression is true the statements of if block get executed, otherwise these
statements will be skipped and the execution will be jump to statement just
outside if block.
• Syntax:
if (expression/condition):
Block of statements
Statements ouside if

1
PPS Unit-II DIT,Pimpri

• Flowchart:

✓ Example:
a=2
if (a<3):
print(a);
if (a>3):
print('Hi')

Output: 2

2.1.2 if-else
• In simple if statement, test expression is evaluated and if it is true the statements
in if block get executed, But if we want a separate statements to be get executed
if it returns false in this case we have to use if..else control statement.
• if else statement has two blocks of codes, each for if and else.
• The block of code inside if statement is executed if the expression in if statement
is TRUE, else the block of code inside else is executed.
• Syntax:
if (expression/condition):
Block of statements
else:
Block of statements

2
PPS Unit-II DIT,Pimpri

• Flowchart:

✓ Example:
x=5
if (x<10):
print (“Condition is TRUE”)
else:
print (“Condition is FALSE”)

output:
Condition is TRUE'

2.1.3 if-elif-else
• Python supports if..elif..else to test additional conditions apart from the initial test
expression.
• It work just like a if…else statement.
• The programmer can have as many elif statements/branches as he wants depending
on the expressions that have to be tested.
• A series of if..elif statements can have a final else block, which is called if none of
the if or elif expression is true.

• Syntax:
if (expression/condition):
Block of statements

3
PPS Unit-II DIT,Pimpri

elif (expression/condition):
Block of statements
elif (expression/condition):
Block of statements
else:
Block of statements

• Flowchart:

Example:
x=5
if (x == 2):
print (“x is equal to 2”)
elif (x < 2):
print (“x is less than 2”)
else:
print (“x is greater than 2”)

Output:
x is greater than 2

4
PPS Unit-II DIT,Pimpri

2.1.4 nested if
• A statement that contains other statements is called nested/compound statements.
• In nested if else statements, if statement is nested inside an if statements. So, the
nested if statements will be executed only if the expression of main if statement
returns TRUE.

• Syntax:
if (expression/condition):
if (expression/condition):
statements
else:
statements
else:
statements
• Flowchart

• Example
x=5
if (x<=10):
if(x==10):
print (“Number is Ten”)
else:
print (“Number is less than Ten”)
else:
print (“Number is greater than Ten”)

5
PPS Unit-II DIT,Pimpri

2.2 Basic loop Structures/Iterative statements:


Q. Explain looping statements with flowchart.

• Iterative statements are decision control statements that are used to repeat the
execution of a list of statements.
• Python language supports two types of statements while loop and for loop.

2.2.1 while loop


• The while loop provides a mechanism to repeat one or more statements while a
particular condition is True.
• Syntax:
while condition:
Statement block
Statement y

• As shown in the syntax above, in the while loop condition is first tested.
• If the condition is True, only then the statement block will be executed.
• Otherwise, if the condition is False the control will jump to statement y, that is the
immediate statement outside the while loop block.
• Flowchart:

6
PPS Unit-II DIT,Pimpri

• Example:
Program to print numbers from 0 to 10.

i=0
while (i<10):
print(i, end=” “)
i=i+1

Output: 0 1 2 3 4 5 6 7 8 9

2.2.2 for loop


• The for loop provide a mechanism to repeat a task until a particular condition is
True.
• The for loop is usually known as a determinate or definite loop because the
programmer knows exactly how many times the loop will repeat.
• The for loop in python is used to iterate through each item in a sequence.
• Here, by sequence we mean just an ordered collection of items.
• The sequence of for loop is tested; if it is satisfied then body of for loop is executed.
• When the last item in sequence is reached, then for loop exits.

• Syntax:
for loop_control_var in sequence:
statement block1
statement x

• The range() function: (Optional)


o The range() function is inbuilt function in python that is used to iterate over a
sequence of numbers.
o The syntax of range() is
range( beginning, end, [step])

7
PPS Unit-II DIT,Pimpri

The range( ) function produces a sequence of numbers starting with


beginning(inclusive) and ending with one less than the number end. The step
argument is optional

• Flowchart:

• Example:.

for i in range(1, 5): for i in range(1, 10, 2):


print(i, end=” “) print(i, end=” “)

Output: Output:
1 2 3 4 1 35 7 9

2.2.3 Selecting appropriate loop:


• Loops can be of different types such as entry controlled (also known as pre-test), exit
controlled (also known as post-test), counter controlled and condition controlled (or
sentinel-controlled) loops.

Pre-test and Post-test loops:


• While in an entry controlled loop, condition is tested before the loop starts, an exit-
controlled loop, tests the condition after the loop is executed.
8
PPS Unit-II DIT,Pimpri

• If condition is not met in entry-controlled loop, then the loop will never execute.
• However, in case of post-test, the body of the loop is executed unconditionally for
the first time.
• If the requirement is to have a pre-test loop, then choose a for loop or a while loop.
• The table below shows comparison between ore-test loop and post-test loop.
Feature Pre-test Loop Post-test Loop
Initialization 1 2
Number of tests N+1 N
Statements executed N N
Loop control variable update N N
Minimum Iterations 0 1

Condition-controlled and Counter-controlled loops:


• When we know in advance the number of times the loop should be executed, we
use a counter controlled loop.
• The counter is a variable that must be initialized, tested and updated for performing
the loop operations.
• Such a counter controlled loop in which the counter is assigned a constant or a
value is known as a definite repetition loop.
• When we do not know in advance the number of times the loop will be executed,
we use a condition-controlled (or sentinel-controlled or indefinite loop) loop.
• In such a loop, a special value called a sentinel value is used to change the loop
control expression from true to false.
• For example, when data is read from user, the user may be notified that when they
want the execution to stop, they may enter -1. This value is called sentinel value.
• If your requirement is to have a counter-controlled loop, then choose for loop, else,
if you need to have a sentinel controlled loop then go for a while loop.

9
PPS Unit-II DIT,Pimpri

Comparison between condition-controlled and counter controlled loop:


Attitude Counter-controlled loop Condition Controlled loop
Number of execution Used when number of times Used when number of times
the loop has to be executed is the loops has to be executed
known in advance. is not known in advance.
Condition Variable In counter-controlled loops, In condition-controlled
we have a counter variable. loops, we use a sentinel
variable.
Value and limitation of The value of the counter The value of the counter
variable variable and the condition variable and the condition
for loop execution, both are for loop execution, both are
strict. strict.
Example i=0 i=1
while (i<=10): while(i>0):
print(i,end= " ") print(i,end= " ")
i+=1 i+=1
if (i==10):
break

2.3 Nested loops


• Python allows its users to have a nested loop, that is, loops can be placed inside
another loop.
• This feature works with while as well as for loop.
• Nested loops are commonly used with for loop because it is easiest to control.
• Loops can be nested at any desired level.
• Loops should be properly indented to identify which statements are contained within
which loop.
• Example:
for i in range(0, 5):
for j in range(0, i+1):

10
PPS Unit-II DIT,Pimpri

print("* ",end="")
print("\r")

Output
*
**
***
****
*****

Example 2:
lastNumber = 6
for row in range(1, lastNumber):
for column in range(1, row + 1):
print(column, end=' ')
print("")

Output
1
12
123
1234
12345

2.4 else statement used with loops


• In for loop, the else keyword is used to specify a block of code to be executed after
completion of loop.
• If the else statement is used with a for loop, the else statement is executed when the
loop has completed iterating.
• But when used with the while loop, the else statement is executed when the
condition becomes false.

11
PPS Unit-II DIT,Pimpri

• Example 1 (For ‘for loop’): Print numbers from 0 to 10 and print a message when
the loop is ended.

for x in range(11):
print(x)
else:
print(“Loop is finished”)

• Example 2 (For ‘while loop”):


i=1
while(i<0)
print(i)
i=i-1
else:
print(i, “is not negative so loop did not execute”)

Output:

1 is not negative so loop did not execute.

2.5 Branching Statements:

Q. Write a note on Break, pass and continue.


2.5.1 break
• The break statement is used to terminate the execution of the nearest enclosing loop
in which it appears.
• The break is widely used with for and while loop.
• When the break statement is encountered inside a loop, the loop is immediately
terminated and program control is passed to next statement following the loop.
• The syntax of break is as shown below:
• Syntax:
break
• The break statement is used to exit a loop from any point within its body, bypassing
its normal termination expression.
• Example:
for i in "welcome":
12
PPS Unit-II DIT,Pimpri

if(i=="c"):
break
print(i)
Output:
w
e
l
2.5.2 continue
• Continue statement can appear only in the body of loop.
• When the continue statement encounters, then the rest of the statements in the loop
are skipped
• The control is transferred to the loop-continuation portion of the nearest enclosing
loop.
• Its syntax is simple just type keyword continue as shown below

continue

• Example:
for i in "welcome":
if(i=="c"):
continue
print(i)
Output:
w
e
l
o
m
e

• We can say continue statement forces the next iteration of the loop to take place,
skipping the remaining code below continue statement.

13
PPS Unit-II DIT,Pimpri

while(…): for(…):
… …
if condition: if condition:
continue continue
…. …
……. …

❖ Differentiate Between break & continue:


Break Continue
Task It terminates the execution of It terminates only the current iteration
remaining iteration of the loop. of the loop.
Control after When ‘break’ statement appears When ‘continue’ statement appears the
statement the control goes out of the loop. control goes at the beginning of the
loop.
Causes It causes early termination of It causes early execution of the next
loop. iteration.
Continuation Break stops the continuation of Continue do not stop the continuation of
loop. loop.
Syntax break continue
Example for i in ‘welcome’: for i in ‘welcome’:
if (i==’c’) if (i==’c’)
break continue
print(i) print(i)
Output: Output:
w w
e e
l l
o
m
e

2.5.3 pass
• It is used when a statement is required syntactically but you do not want any command
or code to execute.
• The pass statement is a null operation.
• Nothing happens when it executes.
14
PPS Unit-II DIT,Pimpri

• It is used as placeholder.
• In a program where for some conditions you don’t want to execute any action or what
action to be taken is not yet decided, but we may wish to write some code in future, In
such cases pass can be used.
• Syntax:
Pass

• Example:
for i in “welcome”:
if (i == 'c'):
pass
print (i)

Output:

w
e
l
c
o
m
e

2.6 Other data types

2.6.1 Tuples
Q. What is tuple? Explain how to access, add and remove elements in a tuple
• Tuple is a data structure supported by python.
• A tuple is a sequence of immutable objects. That means you cannot change the
values in a tuple.
• Tuples use parentheses to define its elements.

Accessing elements in a Tuple:

• Indices in a tuple start at 0.


• We can perform operations like slice, concatenate etc. on a tuple.

15
PPS Unit-II DIT,Pimpri

• For example, to access values in tuple, slice operation is used along with the index or
indices to obtain value stored at that index.
• Example:

Tup1=(1,2,3,4,5,6,7,8,9,10)

print(“Tup[3:6]=”,Tup1[3:6])

print(“Tup[:8]=”,Tup1[:4])

print(“Tup[4:]=”, Tup1[4:])

output:

Tup[3:6]=(4,5,6)

Tup[:8]=(1,2,3,4)

Tup[4:]=(5,6,7,8,9,10)

Adding Elements in a Tuple:

• Tuples are immutable means we cannot add new element into it.
• Also it is not possible to change the value of tuple.

Program:
tup1=(“Kunal”,”Ishita”,”Shree”,”Pari”,“Rahul”)
tup1[5]=”Raj”
print(tup1)
Output:
It will raise an error because new element cannot be added.

Removing/Deleting elements in Tuple:

• Since tuple is an immutable data structure, you cannot delete value(s) from it.

Program:

16
PPS Unit-II DIT,Pimpri

Tup1=(1,2,3,4,5)

del Tup1[3]

print(Tup1)

output: It will raise error as ‘tuple’ object doesn’t support item deletion.

• However, we can delete the entire tuple by using the “del” statement.

Example:

Tup1=(1,2,3,4,5)

del Tup1

Operations on Tuple
Q. Explain various operations on Tuple.
• Tuple behave like similar way as string when operators like concatenation (+),
and repetition (*) are used and returns new list rather a string.
• Tuple supports various operations as listed below:

Operation Description Example Output


Concatenation(+) -It joins two list and X=(10,11,12) (10,11,12,13,1
returns new list. Y=(13,14, “pune”) 4, “pune”)
Z=X+Y
print(z)
Repetition(*) -It repeats elements X=(10,11,12) (10,11,12,10,1
from the list. Z=X*2 1,12)
print(z)
Slice [] - It will give you Example: PPS
element from a List2 =
specified index. ('John','PPS',94)
print(List2[1])
Range slice[:] -It will give you X=(10,11,12,13,14, (10,11,12)
elements from 15)
specified range slice. Z=X[0:3]
-Range slice contains print(z)
inclusive and
exclusive slices

17
PPS Unit-II DIT,Pimpri

Memebership(in) -It will check whether X=(10,11,12,13,14, TRUE


given value present in 15)
list or not. – print(11 in X)
accordingly it will
return Boolean value
Length – len() -It will return length of X=(10,11,12,13,14, 6
given list 15)
print(len(X))
Maximum – -It will return X=(10,11,12,13,14, 15
max() maximum value from 15)
list print(max(X))
Minimum()- -It will return minimu X=(10,11,12,13,14, 10
min() value from list 15)
print(min(X))

2.6.2 Lists
Q. What is list? Explain how elements are accessed, added and removed from list.
• List is a data type in python.
• List is a collection of values (items / elements).
• The items in the list can be of different data types.
• The elements of the list are separated by comma (,) and written between square
brackets [].
• List is mutable which means the value of its elements can be changed.
• Syntax:
List = [value1, value2, …]
• Example1:
List1 = [1,2,3,4]
print(List1)

Output:
[1, 2, 3, 4]
• Example 2:
List2 = ['John','PPS',94]
print(List2)
18
PPS Unit-II DIT,Pimpri

Output:
['John','PPS',94]

➢ Accessing Values in List:


• Elements in the list can be accessed by their index.
• Starting index of list is 0 (zero).
• To access values in list, square brackets [] are used to slice and index is written
inside it.
• Example:
List2 = ['John','PPS',94]
print(List2[1])
print(List2[0:2])
Output:
PPS
['John', 'PPS']

➢ Adding elements / Updating Values in List


• One or more elements can be updated in the list by giving slice on the left hand
side of assignment operator.
• New values can be appended in the list using append().
• New element is given as parameter to append function.
• Example:
List2 = ['John','PPS',94]
List2.append('FE')
print(List2)
List2[0]="Sam"
print(List2)
Output:
['John', 'PPS', 94, 'FE']
['Sam', 'PPS', 94, 'FE']

➢ Removing / Deleting elements from List


• Element can be removed from list using del statement or remove().

19
PPS Unit-II DIT,Pimpri

• Here, index of element or name of element is provided as a argument to remov().


• Example:
List2 = ['John', 'PPS', 94, 'FE']
print(List2)
del List2[1]
print(List2)
List2.remove(List2[0])
print(List2)
List2.remove(94)
print(List2)

Output:
['Sam', 'PPS', 94, 'FE']
['Sam', 94, 'FE']
[94, 'FE']
['FE']

Operations on list
Q. Explain various operations on list.
• List behave like similar way as string when operators like concatenation (+), and
repetition (*) are used and returns new list rather a string.
• List supports various operations as listed below:

Operation Description Example Output


Concatenation(+) -It joins two list and X=[10,11,12] [10,11,12,13,1
returns new list. Y=[13,14, “pune”] 4, “pune”]
Z=X+Y
print(z)
Repetition(*) -It repeats elements X=[10,11,12] [10,11,12,10,1
from the list. Z=X*2 1,12]
print(z)
Slice [] - It will give you Example: PPS
element from a List2 =
specified index. ['John','PPS',94]
print(List2[1])

20
PPS Unit-II DIT,Pimpri

Range slice[:] -It will give you X=[10,11,12,13,14, [10,11,12]


elements from 15]
specified range slice. Z=X[0:3]
-Range slice contains print(z)
inclusive and
exclusive slices
Memebership(in) -It will check whether X=[10,11,12,13,14, TRUE
given value present in 15]
list or not. – print(11 in X)
accordingly it will
return Boolean value
Length – len() -It will return length of X=[10,11,12,13,14, 6
given list 15]
print(len(X))
Maximum – -It will return X=[10,11,12,13,14, 15
max() maximum value from 15]
list print(max(X))
Minimum()- -It will return minimu X=[10,11,12,13,14, 10
min() value from list 15]
print(min(X))

2.6.3 Dictionary
Q. What is dictionary? Explain how to create dictionary, access, add and remove
elements from dictionary.

• Dictionary is a data structure which stores elements as key: value pairs.


• Each key is separated from its value by a colon (:).
• Consecutive key: value pairs are separated by commas (,).
• The entire items in a dictionary are enclosed in curly brackets {}.
• Syntax:
Dict = {key1: value1, key2: value2, key3: value3}
• If there are many key: value pairs in dictionary, then we can write just one key:
value pair on one line to make code easier to read and understand.

Dict = {key1: value1, key2: value2, key3: value3………. keyN: valueN.}

21
PPS Unit-II DIT,Pimpri

• Keys can be of any data type.


• The keys in dictionary must be unique.
• Dictionary keys are case sensitive.

➢ Creating Dictionary
• The syntax to create an empty dictionary can be given as:
Dict = { }
• The syntax to create a dictionary with key value pair is:
Dict = {key1: value1, key2: value2, key3: value3}
• Example1:
Dict = { }
Print(Dict)
Output:
{}
• Example2:
Dict = {1: "PPS", 2: "PHY"}
print(Dict)
Output:
{1: 'PPS', 2: 'PHY'}

➢ Accessing values from Dictionary


• To access values in dictionary, square brackets are used along with the key to
obtain its value.
• Example:
Dict = {1: "PPS", 2: "PHY"}
print(Dict[1])
Output:
PPS
• Note that if you try to access an item with a key, which is not specified in
dictionary, a KeyError is generated.

22
PPS Unit-II DIT,Pimpri

➢ Adding and Modifying (Updating) an item in Dictionary


• Following syntax is used to add a new key: value pair in a dictionary.
• Syntax
Dict[key] = value
• Example
Dict = {1: "PPS", 2: "PHY"}
Dict[3] = "M-I"
print(Dict)
Output
{1: 'PPS', 2: 'PHY', 3: 'M-I'}
• To modify an entry, just overwrite existing value as shown below:
• Example
Dict = {1: "PPS", 2: "PHY"}
Dict[2] = "SME"
print(Dict)
Output
{1: 'PPS', 2: 'SME'}

➢ Deleting items from Dictionary


• One or more items of dictionary can be deleted using del keyword.
• To remove all items in dictionary in just one line, clear() is used.
• To remove entire dictionary from memory, del statement can be used as del Dict.
• Example:
Dict = {1: "PPS", 2: "PHY", 3: "SME"}
del Dict[2]
print(Dict)
Dict.clear()
print(Dict)
del Dict
Output

23
PPS Unit-II DIT,Pimpri

{1: 'PPS', 3: 'SME'}


{}

Operations on Dictionary:

Method Description

clear() Remove all items form the dictionary.

copy() Return a shallow copy of the dictionary.

items() Return a new view of the dictionary's items (key, value).

keys() Return a new view of the dictionary's keys.

values() Return a new view of the dictionary's values

24
PPS Unit-III DIT,Pimpri

Dr. D. Y. PATIL INSTITUTE OF TECHNOLOGY, PIMPRI, PUNE-18


Department of First Year Engineering
Programming and Problem Solving
Unit- 3 Notes
-----------------------------------------------------------------------------------
Unit III: Functions and Modules

3.1 Need for Functions


Q. Define Function and give its advantages.
Ans:
Function: A function is a block of organized and reusable program code that performs a
single, specific and well-defined task.

Advantages
• Reducing duplication of code
• Decomposing complex problems into simpler pieces
• Improving clarity of the code
• Reuse of code
• Information hiding

Q. Explain the use / need for functions?


Ans:
• Dividing the program into separate well defined functions facilitates each
function to be written and tested separately. This simplifies the process of
program development. Following fig. shows that function A calls other functions
for dividing the entire code into smaller functions.

Fig: Top-down approach of solving a problem

1
PPS Unit-III DIT,Pimpri

• Understanding, coding and testing multiple separate functions are far easier than
doing the same for one huge function.
• If big program has to be developed without the use of any function, then there
will be large number of lines in the code and maintaining that program will be a
big mess.
• All the libraries in Python contains pre-defined and pre-tested functions which the
programmers are free to use directly in their programs without worrying about
their code in detail.
• When a big program is broken into comparatively smaller functions, then
different programmers working on that project can divide the workload by writing
different functions.
• Like Python libraries, programmers can also make their own functions and use
them from different points in the main program or any other program that needs
its functionalities.
• Code Reuse: Code reuse is one of the prominent reason to use functions. Large
programs follow DRY principle i.e. Don’t Repeat Yourself principle. Once a
function is written, it can be called multiple times within the same or by different
program wherever its functionality is needed. Correspondingly, a bad repetitive
code abides by WET principle i.e. Write Everything Twice or We Enjoy Typing.
If a set of instructions have to be executed abruptly from anywhere within the
program code, then instead of writing these instructions everywhere they are
required, a better way is to place these instructions in a function and call that
function wherever required.

3.2 Function Definition


Q. What is user defined function? With the help of example illustrate how you can
have such functions in your program.
OR
Q. Explain with example how to define and call a function?
Ans:

How to define function


Function definition consists of a function header that identifies the function, followed by the
body of the function containing the executable code for that function.

User Defined Function


The user defined functions, are functions created by users in their programs using def
keyword.
2
PPS Unit-III DIT,Pimpri

To define user defined function following points must be considered:


• Function blocks start with the keyword def
• The keyword is followed by the function name and parenthesis ( ( ) ). The function
name is uniquely identifying the function.
• After the parenthesis a colon (:) is placed
• Parameters or arguments that function accepts are placed within parenthesis.
They are optional.
• The first statement of a function can be n optional statement-the documentation
string of the function or docstring describe what the function does.
• The code block within the function is properly indented to form the block code.
• A function may have a return[expression] statement. It is optional.

A function definition comprises two parts:


• Function header
• Function body

Syntax:
def function_name(variable1, variable2,..): Function Header
Documentation string
Statement block
return [expression] Function Boy

How to call a function


• The function call statements invoke the function. When a function is invoked, the program
control jumps to the called function to execute the statements that are part of that function.
• Once the called function is executed, the program control passes back to calling function.

Syntax of calling function:


function_name()

• Function call statement has the following syntax when it accepts parameters

function_name(variable1, variable2,..)

# Program that subtract two numbers using function


def diff(x, y): #function to subtract two numbers
return x-y
a=20
b=10
print(diff(a,b)) #function call

3
PPS Unit-III DIT,Pimpri

OUTPUT
10

3.3 Variable Scope and Lifetime


Q. Explain variable scope and lifetime.
Ans:
• Scope of the variable is the part of the program in which the variable is accessible.
• Lifetime of a variable is the period throughout which the variable exists in the
memory.
3.3.1 Local and Global variables:
• Local variables:
o Parameters and variables defined inside a function are not accessible from
outside. Hence, they have a local scope.
o The lifetime of variables inside a function is as long as the function executes.
o They are destroyed once we return from the function. Hence a function does
not remember the value of a variable from its previous calls.
• Global Variables:
o The variables which are defined in the main body of the program file.
Outside any function. Are called as global variables.
o They are visible throughout the program.
• Here is an example to illustrate the scope of a variable inside a function.
def var_scope():
x=5 # Here x is local variable
print(“Value inside function:”,x)
x=10 #Here x is Global variable
var_scope()
print(“value outside function:”, x)
Output:
Value inside function: 5
Value outside function: 10

4
PPS Unit-III DIT,Pimpri

• In this example, we can observe that the value of x is 10 initially.


• Then the var_scope() function is called, it has the value of x as 5, but it is only inside
the function.
• It did not affect the value outside the function.
• This happens since the variable x inside the function var_scope() is considered as
different (local to the function) from the one outside.
• Although they have same names, they are two different variables with different
scope.

Q. Differentiate between global and local variables


Ans:
Global variables Local variables
1. They are defined in the main body of the 1. They are defined within a function and is
program file local to that function.
2. They can be accessed throughout the 2. They can be accessed from the point of its
program file definition until the end of the block in which
it is defined

3.Scope of global variables is Throughout 3.Scope of local variables is Within a


the program. function, inside which they are declared.
4.Life of global variables: Remain in 4.Life of local variables: Created when the
existence for the entire time your program is function block is entered and destroyed upon
executing. exit.

3.3.2 Using the global statement:


• To define a variable defined inside a function as a global, you must use the global
statement.
• This declares the local or the inner variable of the function to have module scope.

5
PPS Unit-III DIT,Pimpri

• For ex.
x=”Good”
def show()
global y
y = “Morning”
print(“In function x is – “, x)

show()
print(“Outside function y is – “, y) # accessible as it is global variable
print(“ x is – “, x)

Output:
In function x is- Good
Outside function y is – Morning
x is - Good

3.3.3 Resolution of Names


Q. When we can have variable with same name as that of global variable in program,
how is name resolved in python.

Ans:
• If we have variable with same name as Global and Local variable. Then local
variable is accessible within the function/block in which it is defined.
• Global variable is defined outside of any function and accessible throughout the
program.
• In the code given below, str is a global string because it has been defined before
calling the function.
• Program that demonstrates using a variable defined in global namespace.

6
PPS Unit-III DIT,Pimpri

def fun():
print(str)
str = “Hello World!!!”
fun()

Output:
Hello World

• You cannot define a local variable with the same name as that of global variable. If
you want to do that you just use the global statement.
• Program describes using a local variable with same name as that of global
def f():
global str
print(str)
str= “hello world”
print(str)

str= “ welcome to python programming”


f()
Output:
welcome to python programming
hello world

3.4 The return statement


Q. Return statement is optional. Justify this statement with the help of example.
Ans:
• In python, every function is expected to have return statement.
• When we do not specify return statement at the end of our function, Implicit return
statement is used as last statement for such function.
• This implicit return statement returns nothing to its caller, so it is said to return none.
7
PPS Unit-III DIT,Pimpri

• In the example below we can see there is no return statement used.


• So here default return none is used as last statement, and program will execute
successfully.
def func1():
x=5
print(“Value of x: ”,x)
func1()
print(“Hello World!)

Output:
Value of x: 5
Hello World

• So from this we can say that return statement is optional in function definition.
Q. Write a note on return statement with suitable example.
Ans:
• In python, every function is expected to have return statement.
• When we do not specify return statement at the end of our function, Implicit return
statement is used as last statement for such function.
• This implicit return statement returns nothing to its caller, so it is said to return none.
• But you can change this default behavior by explicitly using the return statement to
return some value to the caller.

• The syntax of return statement is:


return [expression]
• a return statement with no argument is same as return none
• A function may or may not return a value.
• The return statement is used for two things:
1. Return a value to the caller
2. To end and exit a function and go back to its caller
• Example 1: program to write a function without a return statement and try to print its
return value. Such function should return none.
8
PPS Unit-III DIT,Pimpri

def display(str):
print(str)
x= display(“Hello World”)
print(x)
print(display(“Hello again”))
Output:
Hello World
None
Hello again
None

Note that in output None is return by the function


Example 2: Program for function which returns integer value to the caller.
def cube(x):
return (x*x*x)
num = 10
result= cube(num)
print(“Cube of “, num, ”=”, result)

Output:
Cube of 10 = 100
Note: return statement cannot be used outside the function.

3.5 Types of Parameters


Q. Explain types of function arguments. OR
Q. Write a note on:
1. Required arguments
2. Keyword arguments
3. Default arguments
4. Variable-length arguments

9
PPS Unit-III DIT,Pimpri

Ans: There are four types of function arguments available in Python as follow:
1. Required arguments
2. Keyword arguments
3. Default arguments
4. Variable-length arguments
1. Required Arguments:
• In the required arguments, the arguments are passed to the function in correct
positional order.
• The number of arguments in the function call should exactly match with the
number of arguments specified in the function definition
• For ex.
def person(name, age):
print(name)
print( age)
person(“Amar”, 20)
Output:
Amar
20

2. Keyword Arguments:
• In keyword arguments the order(or position) of the arguments can be changed.
• The values are assigned to the arguments by using their names
• The python interpreter uses keywords provided in the function call to match the
values with parameters.
• Program to demonstrate keyword arguments
def person(name, age, salary):
print(“Name: ”, name)
print(“Age: ”, age)
print(“Salary: ”, salary)

person(salary=50000, name=”Ajay”, age=30)

10
PPS Unit-III DIT,Pimpri

Output:
Name: Ajay
Age: 30
Salary: 50000

• Note:
o All the keyword arguments passed should match one of the arguments
accepted by the function
o The order of keyword argument is not important
o In no case argument should receive a value more than once

3. Default Arguments:
• Python allows user to specify function arguments that can have default
values
• Function call can have less number of arguments than provided in its
definition.
• User can specify default value for one or more arguments which is used if no
value provided in call for that argument.
def display(name, age=18):
print(“Name: ”+ name)
print(“Age: ”, age)

display(age=25, name=”Ajay”)
display(”Amar”)
Output:
Name: Ajay
Course: 25
Name: Amar
Course: 18

• In the above example, default value is not specified for name, so it is mandatory.

11
PPS Unit-III DIT,Pimpri

• But age has provided default value, so if value not provided in calling for age, it will
take 18.
Note: Non default arguments should be provided before default arguments.

4. Variable Length arguments:


• In some situations, it is not known in advance how many arguments will be
passed to a function.
• I such cases variable length arguments can be used, in this function definition
uses an asterisk(*) before the parameter name.
Syntax:
def function_name([arg1, arg2, …] *var_args_tuple )
function statements
return [expression]
Program to demonstrate the use of variable length arguments
def sumFun(a, *tup):
sum1=a
for i in tup:
sum1= sum1 + i
print(sum1)
sumFun(10, 20, 30, 40)
Output:
100

• In the above program, in the function definition we have two parameters- one is a
and other is variable length parameter tup.
• The first value is assigned to a and other values are assigned to parameter tup.
• In tup parameter, 0 to n values are acceptable.
• The variable length argument if present in the function definition should be the last
in the list of formal parameters.
• To see or use all the values in the variable length parameter, we have to use for loop
as given in above example.

12
PPS Unit-III DIT,Pimpri

3.6 Lambda or Anonymous functions


Q. What is lambda or anonymous functions in python? Explain with example.
Ans.
• Lambda or anonymous function have no name.
• They are created using lambda keyword instead of def.
• Lambda function contains only single line.
• Lambda function can take any number of arguments.
• It can returns only one value in the form of an expression.
• Lambda function does not have explicit return statement.
• Lambda function cannot contain multiline expressions.
• It cannot access variable other than those in their parameter list
• We can pass Lambda function as arguments in other functions.
• Syntax:
Lambda arguments: expression

▪ The arguments contains comma separated list of variables


▪ The expression is an arithmetic expressions that uses these arguments
• Example:
sum = lambda x, y: x + y
print(“sum =”, sum(3,5))

Output:
Sum=8

13
PPS Unit-III DIT,Pimpri

3.7 Documentation String


Q. What are docstring?
Ans:
• Docstrings (documentation string) serves the same purpose as that of comments.
• Docstrings are designed to explain code.
• Docstrings are created by putting multiline string to explain the code.
• Docstrings are important as they help tools to automatically generate printed
documentation
• Docstrings are very helpful to readers and users of the code to interactively browse
the code.
• Docstrings specified in function can be accessed through the __doc__ attributes of
the functions.
• Unlike comments, Docstrings are retained throughout the runtime of the program.
(Docstrings ignored by the compilers)
• Syntax:
def function_name(parameters):
""" Function written for factorial,
Calculates factorial of number """
Function statements
return [expression]
• Example:
def func():
""" function just prints message.
It will display Hello World !! """
print(“Hello World!!”)
func( )
print(func.__doc__)
Output:
Hello World!!
function just prints message.
It will display Hello World !!
14
PPS Unit-III DIT,Pimpri

3.8 Good Programming Practices


Q. Write a note on good programming practices in python.
Ans:
To develop readable, effective and efficient code programmer has to take care of following
practices:
• Instead of tabs, use 4 spaces for indentations.
• Wherever required use comments to explain code.
• Use space around operators and after commas.
• Name of the function should be in lower case with underscore to separate words
Eg. get_data()
• Use document string that explains purpose of the functions
• Name of the class should be written as first letter capital in each word
Eg. ClassName()
• Do not use non ASCII character in function names or any other identifier.
• Inserts blank lines to separate functions, Classes, and statement blocks inside
functions

3.9 Introduction to Module


Q. What are modules? How do you use them in your program?
Ans:
Module:
• Definition: Module is a file with .py extension that has definitions of functions and
variables that can be used even in other programs.
• Modules are the pre-written pieces of code.
• They are used to perform common tasks like generate random numbers, performing
mathematical operations etc.
• Using Modules in programs:
o Programs in which you want to use functions or variables defined in the module will
simply import that particular module (or .py file).

15
PPS Unit-III DIT,Pimpri

o To use a module in any program, add import module_name as the first line in your
program.
Syntax:
import module_name

o Then module_name.var is written to access functions and values with the name var
in the module.

o Example: Program to print sys.path variable


import sys
print("PYTHONPATH = \n", sys.path)

o Here, sys standard library module is imported.


o When import sys statement is executed, python looks for sys.py module and then
executes the statement to print sys.path variable.

• Module Loading & Execution (optional)


o A module imported in a program must be located and loaded into memory
before it can be used.
o Python will search a module:
▪ in current working directory
▪ if not found there, it searches directories in the environmental
variable PYTHONPATH.
▪ If not found, then a Python installation specific path (like
C:\Python34\Lib) is searched.
▪ If the module is not located even there, then an error ImportError
exception is generated.
o In order to make a module available to other programs, it should be either
saved in the directory specified in path PYTHONPATH, or stored in Python
installation Lib directory.
o Once a module is located, it is loaded in memory.

16
PPS Unit-III DIT,Pimpri

o A compiled version of module with file extension .pyc is generated.


o Next time when the module is imported, this .pyc file is loaded instead of .py
file.
o A new compiled version of a module is again produced whenever the
compiled module is out of date.
o Even the programmer can force the python shell to reload and recompile
the .py file to generate a new .pyc file by using reload( ) function.

3.9.1 The from…import statement


• A module may contain definition for many variables or functions.
• When a module is imported, any variable or function defined in that module can be
used.
• But if you want to use only selected variables or functions, then use the
from…import statement.
• Syntax
from module_name import member_name
• Example:
from math import pi
print("PI= ",pi)

• To import more than one item from a module, use comma separated list. For
example, to import value of pi and sqrt( ) from math module write:
Example:
from math import pi, sqrt
print("PI= ", pi)
print("Square root of 4=", sqrt(4))
Output:
PI= 3.141592653589793
Square root of 4= 2.0

17
PPS Unit-III DIT,Pimpri

• To import all identifiers defined in a module, except those beginning with


underscore ( _ ), use import * statement.
• Example:
from math import *
print("PI= ", pi)
print("Square root of 4=", sqrt(4))
Output:
PI= 3.141592653589793
Square root of 4= 2.0

3.9.2 Name of Module


• Every module has a name.
• You can find the name of a module by using the __name__ attribute of the module.
• Example:
print("Hello")
print("Name of module is = ", __name__)
Output:
Hello
Name of module is = __main__
• Note that, for every standalone program written by the user the name of module is
__main__.

3.9.3 Making your own module


• You can create your own modules.
• Every python program is a module.
• That is, every file that is saved with .py extension is a module.
• For example, let us create our own module say Mymodule.py
• In this file, some functionality is written.
File Name: Mymodule.py
def display():
print("Hello")
18
PPS Unit-III DIT,Pimpri

str = "Welcome to World of Python"

• Then open another file (main.py) and write code given below.
File Name: main.py
import Mymodule
print("Mymodule string=", Mymodule.str)
Mymodule.display()

• When you run main.py file, you get following output.


Mymodule string= Welcome to World of Python
Hello

• Modules should be placed in the same directory as that of the program in which it is
imported.
• It can also be stored in one of the directories listed in sys.path.
• The dot operator is used to access members (variables or functions) of module.

3.10 Packages
Q. What are packages in python?
Ans:
• A package is a hierarchical file directory structure.
• A package has modules and other packages within it.
• Every package in python is a directory which must have a special file called
__init__.py. This may not even have a single line of code.
• It is simply added to indicate that this is not an ordinary directory and contains a
Python package.
• A package can be accessed in other python program using import statement.
• For example, to create a package MyPackage, create directory called MyPackage
having module MyModule and __init__.py file.
File Name: Mymodule.py
def display():
19
PPS Unit-III DIT,Pimpri

print("Hello")
str = "Welcome to World of Python"
• Now, to use MyModule in a program, import it in any one of the two ways:

import MyPackage.MyModule
or
from MyPackage import MyModule

3.11Introduction to Standard Library Modules


Q. Explain any four standard library modules.
Ans:
• Python supports 3 types of modules – those written by the programmer, those that
are installed from external sources, and those that are pre-installed with python.
• Modules that are pre-installed in python together are known as the standard library.
• Some useful modules in standard library are string, re, datetime,math, random, os,
multiprocessing, socket, email, json, doctest, unittest, pdb, argparse and sys.
• A few standard libraries in python are:
1. Math (import math)
This is a package for providing various functionalities regarding mathematical
operations.
For ex. math.sqrt(9), will give you 3 as square root of 9.
2. Random (import random)
This is a module which supports various functions for generation of random
numbers and setting seed of random number generator.
For ex. random.random(), function will generate random number
3. Sys (import sys)
It supports all system information related operations.
For ex. sys.path , will give you information about Current file Path.
4. Os ( import os )
It gives all the information related to Operating System.
For ex. os.name , will give you the name of Operating System.
20
PPS Unit-VI DIT,Pimpri

Dr. D. Y. PATIL INSTITUTE OF TECHNOLOGY, PIMPRI, PUNE-18


Department of First Year Engineering
Programming and Problem Solving
Unit- 4 Notes
_________________________________________________________________________
Unit IV: Strings
4.1 Strings and Operations

Q 1. What is String? With the help of example explain how we can create string
variable in python.
Ans:
 Strings data type is sequence of characters, where characters could be letter, digit,
whitespace or any other symbol.
a. Creation of Strings:
o Strings in Python can be created using single quotes or double quotes or even
triple quotes.
o Example:
string1 = 'Welcome' # Creating a String with single Quotes
string2 = "Welcome" # Creating a String with double Quotes
string3 = '''Welcome''' # Creating a String with Triple Quotes

b. Accessing strings:
o In Python, individual characters of a String can be accessed by using the method
of Indexing or range slice method [:].
o Indexing allows negative address references to access characters from the back
of the String, e.g. -1 refers to the last character, -2 refers to the second last
character and so on.

String W E L C O M E
Indexing 0 1 2 3 4 5 6
Negative Index -7 -6 -5 -4 -3 -2 -1

1
PPS Unit-VI DIT,Pimpri

o Example:
string = 'Welcome'
print(string[0]) #Accessing string with index
print(string[1])
print(string[2])
print(srting[0:2]) #Accessing string with range slice
method

Output:
w
e
l
wel

c. Deleting/Updating from a String:


o In Python, updating or deletion of characters from a String is not allowed as
Strings are immutable.
o Although deletion of entire String is possible with the use of a built-in del
keyword.
o Example:
string='welcome'
del string

Q 2. Explain Operations on string.


Ans:
Operation Description Example Output
Concatenation(+) -It joins two strings x="Good" Good Morning
and returns new list. y="Morning"
z=x+y
print(z)

2
PPS Unit-VI DIT,Pimpri

Append (+=) -Append operation x="Good" Good Morning


adds one string at y="Morning"
the end of another x+=y
string print(x)
Repetition(*) -It repeats elements x="Hello" HelloHello
from the strings n y=x*2
number of times print(y)
Slice [] - It will give you x="Hello" e
character from a print(x[1])
specified index.

Range slice[:] -It will give you x="Hello" He


characters from print(x[0:2])
specified range slice.

4.2 Strings are immutable


Q 3. Python strings are immutable. Comment on this.
Ans:
 Python Strings are immutable, which means that once it is created it cannot be changed.
 Whenever you try to change/modify an existing string, a new string is created.
 As every object (variable) is stored at some address in computer memory.
 The id() function is available in python which returns the address of object(variable) in
memory. With the help of memory locations/address we can see that for every
modification, string get new address in memory.
 Here is the example to demonstration the address change of string after modification.
# prints string1 and its address
string1="Good"
print("String1 value is: ",string1)
print("Address of string1 is: ",id(string1)

3
PPS Unit-VI DIT,Pimpri

# prints string2 and its address


string2="Morning"
print("String2 value is: ",string2)
print("Address of string2 is: ",id(string2)

#appending string1 to string2


string1+= string2
print("String1 value is: ",string1)
print("Address of string1 is: ",id(string1)

Output:
String1 value is: Good
Address of String1 is: 1000

String2 value is: Morning


Address of String1 is: 2000

String1 value is: GoodMorning


Address of String1 is: 3000

 From the above output you can see string1 has address 1000 before modification. In
later output you can see that string1 has new address 3000 after modification.
 It is very clear that, after some operations on a string new string get created and it has
new memory location. This is because strings are unchangeable/ immutable in nature.
Modifications are not allowed on string but new string can be created at new address
by adding/appending new string.

4.3 Strings formatting operator


Q 4. Explain various ways of string formatting with example.
Ans:
 In python, % sign is a string formatting operator.

4
PPS Unit-VI DIT,Pimpri

 The % operator takes a format string on the left and the corresponding values in a
tuple on the right.
 The format operator, % allows users to replace parts of string with the data stored in
variables.
 The syntax for string formatting operation is:
"<format>" % (<values>)
 The statement begins with a format string consisting of a sequence of characters and
conversion specification.
 Following the format string is a % sign and then a set of values, one per conversion
specification, separated by commas and enclosed in parenthesis.
 If there is single value then parenthesis is optional.
 Following is the list of format characters used for printing different types of data:
Format Purpose
Symbol
%c Character
%d or %i Signed decimal integer
%s String

%u Unsigned decimal integer

%o Octal integer

%x or %X Hexadecimal integer

%e or %E Exponential notation

%f Floating point number

%g or %G Short numbers in floating point or exponential notation

Example: Program to use format sequences while printing a string.


name="Amar"
age=8
print("Name = %s and Age = %d" %(name,age))
print("Name = %s and Age = %d" %("Ajit",6))

5
PPS Unit-VI DIT,Pimpri

Output:
Name = Amar and Age = 8
Name = Ajit and Age = 6

In the output, we can see that %s has been replaced by a string and %d has been replaced by
an integer value.

4.4 Built-in String methods and functions


Q 5. List and explain any 5 string methods.
Or
Q. Explain the use of ______ ( ) with the help of an example.
Ans.
Sr. Function Usage Example
No.
1 capitalize() This function is used to capitalize str="hello"
first letter of string. print(str.capitalize())
output:
Hello
2 isalnum() Returns true if string has at least 1 message="JamesBond007"
character and every character is print(message.isalnum())
either a number or an alphabet and output:
False otherwise. True
3 isalpha() Returns true if string has at least 1 message="JamesBond007"
character and every character is an print(message.isalpha())
alphabet and False otherwise. output:
False
4 isdigit() Returns true if string has at least 1 message="007"
character and every character is a print(message.isdigit())
digit and False otherwise. output:
True
5 islower() Returns true if string has at least 1 message="Hello"

6
PPS Unit-VI DIT,Pimpri

character and every character is a print(message.islower())


lowercase alphabet and False output:
otherwise. False
6 isspace() Returns true if string contains only message=" "
white space character and False print(message.isspace())
otherwise. output:
True
7 isupper() Returns true if string has at least 1 message="HELLO"
character and every character is an print(message.isupper())
uppercase alphabet and False output:
otherwise. True
8 len(string) Returns length of the string. str="Hello"
print(len(str))
output:
5
9 zfill(width) Returns string left padded with str="1234"
zeros to a total of width characters. print(str.zfill(10))
It is used with numbers and also output:
retains its sign (+ or -). 0000001234
10 lower() Converts all characters in the string str="Hello"
into lowercase. print(str.lower())
output:
hello
11 upper() Converts all characters in the string str="Hello"
into uppercase. print(str.upper())
output:
HELLO
12 lstrip() Removes all leading white space in str=" Hello"
string. print(str.lstrip())
output:
Hello

7
PPS Unit-VI DIT,Pimpri

13 rstrip() Removes all trailing white space in str=" Hello "


string. print(str.rstrip())
output:
Hello
14 strip() Removes all leading white space str=" Hello "
and trailing white space in string. print(str.strip())
output:
Hello
15 max(str) Returns the highest alphabetical str="hello friendz"
character (having highest ASCII print(max(str))
value) from the string str. output:
z
16 min(str) Returns the lowest alphabetical str="hellofriendz"
character (having lowest ASCII print(min(str))
value) from the string str. output:
d
17 replace(old,new[, max]) Replaces all or max (if given) str="hello hello hello"
occurrences of old in string with print(str.replace("he","Fo"))
new. output:
Follo Follo Follo
18 title() Returns string in title case. str="The world is beautiful"
print(str.title())
output:
The World Is Beautiful
19 swapcase() Toggles the case of every character str="The World Is
(uppercase character becomes Beautiful"
lowercase and vice versa). print(str.swapcase())
output:
tHE wORLD iS
bEAUTIFUL
20 split(delim) Returns a list of substrings str="abc,def, ghi,jkl"

8
PPS Unit-VI DIT,Pimpri

separated by the specified print(str.split(','))


delimiter. If no delimiter is output:
specified then by default it splits ['abc', 'def', ' ghi', 'jkl']
strings on all whitespace
characters.
21 join(list It is just the opposite of split. The print('-'.join(['abc', 'def', '
function joins a list of strings using ghi', 'jkl']))
delimiter with which the function output:
is invoked. abc-def- ghi-jkl
22 isidentifier() Returns true if the string is a valid str="Hello"
identifier. print(str.isidentifier())
output:
True
23 enumerate(str) Returns an enumerate object that str="Hello World"
lists the index and value of all the print(list(enumerate(str)))
characters in the string as pairs. output:
[(0, 'H'), (1, 'e'), (2, 'l'), (3,
'l'), (4, 'o'), (5, ' '), (6, 'W'),
(7, 'o'), (8, 'r'), (9, 'l'), (10,
'd')]

4.5 Slice operation


Q 6. What is slice operation? Explain with example.
Ans.
Slice: A substring of a string is called a slice.
A slice operation is used to refer to sub-parts of sequences and strings.
Slicing Operator: A subset of a string from the original string by using [] operator
known as Slicing Operator.

9
PPS Unit-VI DIT,Pimpri

Indices in a String

Index from
P Y T H O N
the start
0 1 2 3 4 5
-6 -5 -4 -3 -2 -1

Index from
Syntax:
the end
string_name[start:end]
where start- beginning index of substring
end -1 is the index of last character

Program to demonstrate slice operation on string objects


str=”PYTHON”
print(“str[1:5]= “, str[1:5]) #characters start at index 1 and extending upto index 4
# but not including index 5
print(“str[ :6]= “, str[ :6]) # By defaults indices start at index 0
print(“str[1: ]= “, str[1: ]) # By defaults indices ends upto last index
print(“str[ : ]= “, str[ : ]) # By defaults indices start at index 0 and end upto last
#character in the string
#negative index
print(“str[-1]= “, str[ -1]) # -1 indicates last character
print(“str[ :-2 ]= “, str[ : -2]) #all characters upto -3
print(“str[ -2: ]= “, str[ -2: ]) #characters from index -2
print(“str[-5 :-2 ]= “, str[ -5: -2]) # characters from index -5 upto character index -3

OUTPUT
str[1:5]= YTHO
str[ :6]= PYTHON
str[1: ]= YTHON
str[ : ]= PYTHON

10
PPS Unit-VI DIT,Pimpri

str[-1]= N
str[ :-2 ]= PYTH
str[ -2: ]= ON
str[-5 :-2 ]= YTH

Specifying Stride while Slicing Strings


 In the slice operation, you can specify a third argument as the stride, which refers
to the number of characters to move forward after the first character is retrieved
from the string.
 The default value of stride is 1, i.e. where value of stride is not specified, its
default value of 1 is used which means that every character between two index
number is retrieved.
Program to use slice operation with stride
str=” Welcome to the world of Python“
print(“str[ 2: 10]= “, str[2:10]) #default stride is 1
print(“str[ 2:10:1 ]= “, str[2:10:1]) #same as stride=1
print(“str[ 2:10:2 ]= “, str[2:10:2]) #skips every alternate character
print(“str[ 2:10:4 ]= “, str[2:10:4]) #skips every fourth character

OUTPUT
str[ 2: 10]=lcome to
str[ 2: 10]= lcome to
str[ 2:10:2 ]=loet
str[ 2:10:4 ]=l
 Whitespace characters are skipped as they are also part of the string.

4.6 ord() and chr() functions
Q 7.Write a short note on ord() and chr() functions
Ans.
 The ord() function return the ASCII code of the character

11
PPS Unit-VI DIT,Pimpri

 The chr() function returns character represented by a ASCII number.

ch=’R’ print(chr(82)) print(chr(112)) print(ord(‘p’))


print(ord(ch))

OUTPUT OUTPUT OUTPUT OUTPUT


82 R p 112

4.7 in and not in operators


Q 8.Write a short note on in and not in operators
OR
Q.With the help of example, explain significance of membership operators.
Ans.
 in and not in operators can be used with strings to determine whether a string is
present in another string. Therefore the in and not in operator is known as
membership operators.

 For example:
str1=” Welcome to the world of Python!!!“ str1=” This is very good book“
str2=”the” str2=”best”
if str2 in str1: if str2 in str1:
print(“found”) print(“found”)
else: else:
print(“Not found”) print(“Not found”)

OUTPUT OUTPUT
Found Not found

 You can also use in and not in operators to check whether a character is present in a
word.
 For example:
‘u‘ in “starts” ‘v‘ not in “success”

12
PPS Unit-VI DIT,Pimpri

OUTPUT OUTPUT
False True

4.8 Comparing strings


Q 9. Explain string comparison operator with example?
Ans.
 Python allows us to combine strings using relational (or comparison) operators such
as >, <, <=,>=, etc.
 Some of these operators along with their description and usage are given as follows:
Operator Description Example
== If two strings are equal, it returns True. >>>”AbC”==”AbC”
True
!= or <> If two strings are not equal, it returns True. >>>”AbC”!=”Abc”
True
> If the first string is greater than the second, it >>>”abc”>”Abc”
returns True. True
< If the second string is greater than the first, it >>>”abC”<”abc”
returns True. True
>= If the first string is greater than or equal to >>>”aBC”>=””ABC”
the second, it returns True. True
<= If the second string is greater than or equal to >>>”ABc”<=”ABc”
the first, it returns True. True

 These operators compare the strings by using ASCII value of the characters.
 The ASCII values of A-Z are 65-90 and ASCII code for a-z is 97-122.
 For example, book is greater than Book because the ASCII value of ‘b’ is 98 and ‘B’
is 66.

String Comparison Programming Examples: (Any one)


 There are different ways of comparing two strings in Python programs:

13
PPS Unit-VI DIT,Pimpri

 Using the ==(equal to) operator for comparing two strings:


 If we simply require comparing the values of two variables then you may use
the ‘==’ operator.
 If strings are same, it evaluates to True, otherwise False.

 Example1:
first_str='Kunal works at Phoenix'
second_str='Kunal works at Phoenix'
print("First String:", first_str)
print("Second String:", second_str)
#comparing by ==
if first_str==second_str:
print("Both Strings are Same")
else:
print("Both Strings are Different")

Output:
First String: Kunal works at Phoenix
Second String: Kunal works at Phoenix
Both Strings are Same

 Example2(Checking Case Sensitivity):


first_str='Kunal works at PHOENIX'
second_str='Kunal works at Phoenix'
print("First String:", first_str)
print("Second String:", second_str)
#comparing by ==
if first_str==second_str:
print("Both Strings are Same")
else:
print("Both Strings are Different")

14
PPS Unit-VI DIT,Pimpri

Output:
First String: Kunal works at PHOENIX
Second String: Kunal works at Phoenix
Both Strings are Different

 Using the !=(not equal to) operator for comparing two strings:
 The != operator works exactly opposite to ==, that is it returns true is both
the strings are not equal.
 Example:
first_str='Kunal works at Phoenix'
second_str='Kunal works at Phoenix'
print("First String:", first_str)
print("Second String:", second_str)
#comparing by !=
if first_str!=second_str:
print("Both Strings are Different")
else:
print("Both Strings are Same")
output:
First String: Kunal works at Phoenix
Second String: Kunal works at Phoenix
Both Strings are Same

 Using the is operator for comparing two strings:


 The is operator compares two variables based on the object id and returns
True if the two variables refer to the same object.
 Example:
name1=”Kunal”
name2=”Shreya”
print(“name1:”,name1)

15
PPS Unit-VI DIT,Pimpri

print(“name2:”,name2)
print(“Both are same”,name1 is name2)
name2=”Kunal”
print(“name1:”,name1)
print(“name2:”,name2)
print(“Both are same”,name1 is name2)
 Output:
name1=Kunal
name2=Shreya
Both are same False
name1=Kunal
name2=Kunal
Both are same True
 In the above example, name2 gets the value of Kunal and subsequently
name1 and name2 refer to the same object.

4.9 Iterating strings
Q. No.10 How to iterate a string using:
Ans.
i) for loop with example
ii) while loop with example
Ans.

 String is a sequence type (sequence of characters).


 We can iterate through the string using:

i) for loop:
 for loop executes for every character in str.
 The loop starts with the first character and automatically ends when
the last character is accessed.
 Example-

16
PPS Unit-VI DIT,Pimpri

str=”Welcome to python”
for i in str:
print(i,end=’ ’)
Output-
Welcome to Python

ii) while loop:


 We can also iterate through the string using while loop by writing the
following code.
 Example-
message=” Welcome to python”
index=0
while index < len(message):
letter=message[index]
print(letter,end=’ ‘)
index=index+1
Output-
Welcome to Python

 In the above program the loop traverses the string and displays each
letter.
 The loop condition is index < len(message), so the moment index
becomes equal to the length of the string, the condition evaluates to
False, and the body of the loop is not executed.
 Index of the last character is len(message)-1.

4.10 The string module


Q. No. 11 Write a note on string module?
 The string module consists of a number of useful constants, classes and functions.
 These functions are used to manipulate strings.

17
PPS Unit-VI DIT,Pimpri

 String Constants: Some constants defined in the string module are:


 string.ascii_letters: Combination of ascii_lowecase and ascii_uppercase
constants.
 string.ascii_lowercase: Refers to all lowercase letters from a-z.
 string.ascii_uppercase: Refers to all uppercase letters from A-Z.
 string.lowercase: A string that has all the characters that are considered
lowercase letters.
 string.uppercase: A string that has all the characters that are considered
uppercase letters.
 string.digits:Refers to digits from 0-9.
 string.hexdigits: Refers to hexadecimal digits,0-9,a-f, and A-F.
 string.octdigits: Refers to octal digits from 0-7.
 string.punctuation: String of ASCII characters that are considered to be
punctuation characters.
 string.printable: String of printable characters which includes digits, letters,
punctuation, and whitespaces.
 string.whitespace: A string that has all characters that are considered
whitespaces like space, tab, return, and vertical tab.
 Example: (Program that uses different methods such as upper, lower, split, join,
count, replace, and find on string object)
str=”Welcome to the world of Python”
print(“Uppercase-“, str.upper())
print(“Lowercase-“, str.lower())
print(“Split-“, str.split())
print(“Join-“, ‘-‘.join(str.split()))
print(“Replace-“,str.replace(“Python”,”Java”))
print(“Count of o-“, str.count(‘o’))
print(“Find of-“,str.find(“of”))

18

You might also like