[go: up one dir, main page]

0% found this document useful (0 votes)
14 views66 pages

P2S12019Batch Content

This document introduces the basics of algorithms and flowcharts, emphasizing the importance of problem-solving in daily life and the structured approach of algorithms to achieve solutions. It outlines the definition, structure, qualities, advantages, and disadvantages of algorithms, as well as control structures and flowcharting as methods to represent algorithms visually. The document also discusses algorithm efficiency and tracing, providing examples to illustrate these concepts.

Uploaded by

n191044
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
14 views66 pages

P2S12019Batch Content

This document introduces the basics of algorithms and flowcharts, emphasizing the importance of problem-solving in daily life and the structured approach of algorithms to achieve solutions. It outlines the definition, structure, qualities, advantages, and disadvantages of algorithms, as well as control structures and flowcharting as methods to represent algorithms visually. The document also discusses algorithm efficiency and tracing, providing examples to illustrate these concepts.

Uploaded by

n191044
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 66

Unit 1 - Basics of Algorithms and Flow charts

Module 1 – Introduction to problem solving and algorithms


1.1 Introduction:
Intelligence is one of the key characteristics which differentiate a human being from other living creatures on the
earth. Basic intelligence covers day to day problem solving and making strategies to handle different situations which
keep arising in day to day life. One person goes Bank to withdraw money. After knowing the balance in his account,
he/she decides to with draw the entire amount from his account but he/she has to leave minimum balance in his
account. Here deciding about how much amount he/she may with draw from the account is one of the examples of the
basic intelligence. During the process of solving any problem, one tries to find the necessary steps to be taken in a
sequence. In this Unit you will develop your understanding about problem solving and approaches.
Problem Solving:
Can you think of a day in your life which goes without problem solving? Answer to this question is of course, No. In
our life we are bound to solve problems. In our day to day activity such as purchasing something from a general store
and making payments, depositing fee in school, or withdrawing money from bank account. All these activities involve
some kind of problem solving. It can be said that whatever activity a human being or machine do for achieving a
specified objective comes under problem solving. To make it clearer, let us see some other examples.
Example1: If you are watching a news channel on your TV and you want to change it to a sports channel, you need to
do something i.e. move to that channel by pressing that channel number on your remote. This is a kind of problem
solving.
Example 2: One Monday morning, a student is ready to go to school but yet he/she has not picked up those books and
copies which are required as per timetable. So here picking up books and copies as per timetable is a kind of problem
solving.
Example 3: If someone asks to you, what is time now? Seeing time in your watch and telling is also a kind of problem
solving.
Example 4: Some students in a class plan to go on picnic and decide to share the expenses among them. So
calculating total expenses and the amount an individual have to give for picnic is also a kind of problem solving.
 Now, we can say that problem is a kind of barrier to achieve something and problem solving is a process to
get that barrier removed by performing some sequence of activities.
 Here it is necessary to mention that all the problems in the world cannot be solved. There are some problems
which have no solution and these problems are called Open Problems.
 If you can solve a given problem then you can also write an algorithm for it. In next section we will learn what
is an algorithm?
1.2 Algorithm Introduction
Algorithm is a step-by-step process of solving a well-defined computational problem. In practice, in order to solve any
complex real-life problems, first we have to define the problem and then, design algorithm to solve it. Writing and
executing a simple program may be easy; however, for executing a bigger one, each part of the program must be well
organized. In short, algorithms are used to simplify the program implementation. The study of algorithms is one of the
key foundations of computer science. Algorithms are essential to the way computers process information, because a
computer program is essentially an algorithm that tells the computer what specific steps to perform (in what specific
order) in order to carry out a specified task, such as calculating employees‘ paychecks or printing students‘ report
cards. Thus, an algorithm can be considered to be any sequence of operations that can be performed by a computing
device such as a computer.
1.2.1 What is an Algorithm?
• Algorithm is a step by step procedure to solve a particular problem or ―A sequence of activities to be
processed for getting desired output from a given input.
• It‘s a easy way of analyzing a problem.

1.2.2 Structure of an algorithm:


START
– STEP 1
– SETP 2
– SETP 3
– SETP 4
– ……………………so on
STOP
Example 1: A simple algorithm to print „Good Morning‟.
Step 1: Start
Step 2: Print „Good Morning‟
Step 3: Stop
Example 2: Let us take one simple day-to-day example by writing algorithm for making ―Maggi Noodles‖ as a food.
Inputs to the algorithm: Maggie Noodles packet, Pan, Water, Gas
Expected output: Maggie Noodles
Algorithm:
Step 1: Start
Step 2: Take pan with water
Step 3: Put pan on the burner
Step 4: Switch on the gas/burner
Step 5: Put Maggie and masala
Step 6: Give two minutes to boil
Step 7: Take off the pan
Step 8: Take out the magi with the help of fork/spoon
Step 9: Put the Maggie on the plate and serve it
Step 10: Stop
Example3: Find the area of a Circle of radius r.
Inputs to the algorithm: Radius r of the Circle.
Expected output: Area of the Circle
Algorithm:
Step1: Start
Step2: Read\input Radios
Step3: Set 3.14 to PI
Step4: Set Area PI* Radios * Radios // calculation of area
Step5: Print Area
Step6: stop
1.3 Expressing Algorithms:
An algorithm is a set of steps designed to solve a problem or accomplish a task. Algorithms are usually written in
pseudo code, or a combination of your speaking language and one or more programming languages, in advance of
writing a program. An algorithm may be expressed in a number of ways, including:
 Natural language: usually verbose and ambiguous.
 Flow charts: avoid most (if not all) issues of ambiguity; difficult to modify w/o specialized tools; largely
standardized.
 Programming language: Tend to require expressing low – level details that are not necessary for a high –
level understanding.
1.4 Qualities of a good algorithm
1. Inputs and outputs should be defined precisely.
2. A good algorithm should produce correct and accurate results for any set of legal or correct inputs.
3. Each step in algorithm should be clear and unambiguous.
4. Algorithm should be most effective among many different ways to solve a problem.
5. An algorithm shouldn‘t have computer code. Instead, the algorithm should be written in such a way that it can
be used in similar programming languages Whenever we write an algorithm, we should make sure that all of
these parameters given for a good algorithm are incorporated.
1.5 Advantage and disadvantages of algorithm
1.5.1 Advantages
1. It is a step-wise representation of a solution to a given problem, which makes it easy to understand.
2. An algorithm uses a definite procedure.
3. It is not dependent on any programming language, so it is easy to understand for anyone even without
programming knowledge.
4. Every step in an algorithm has its own logical sequence so it is easy to debug.
5. By using algorithm, the problem is broken down into smaller pieces or steps hence, it is easier for programmer
to convert it into an actual program
1.5.2 Disadvantages
1. Writing algorithm takes a long time.
2. An Algorithm is not a computer program, it is rather a concept of how a program should be
3. Big tasks are difficult to put in Algorithms.
4. Difficult to show Branching and Looping in Algorithms.
1.6 Properties of algorithm:
1. Finiteness: An algorithm must always terminate after a finite number of steps. It means after every step one
reach closer to solution of the problem and after a finite number of steps algorithm reaches to an end point.
2. Definiteness: Each step of an algorithm must be precisely defined. It is done by well thought actions to be
performed at each step of the algorithm. Also the actions are defined unambiguously for each activity in the
algorithm.
3. Input: An algorithm has zero or more inputs, taken from a specified set of objects.
4. Output: An algorithm has one or more outputs, which have a specified relation to the inputs.
5. Effectiveness: All operations to be performed must be sufficiently basic that they can be done exactly and in
finite length
1.7 Algorithm Efficiency
Algorithmic efficiency is a property of an algorithm which relates to the number of computational resources used by
the algorithm. An algorithm must be analyzed to determine its resource usage, and the efficiency of an algorithm can
be measured based on usage of different resources.
 Speed - Method that takes the least time
 Space - Method that uses the least memory
 Code — Method that is shortest to describe
Speed is now the most important factor Example
A real world example: Travelling from Vempalli to Hyderabad in Vehicle
Case 1:
1. Take vehicle
2. Check vehicle condition if not get it repair
3. Drive from vempalli to Proddutur
4. Then Proddutur to Hyderabad
5. Travel is successfully completed.
Case 2:
1. Take vehicle
2. Check vehicle condition if not get it repair
3. Drive from Vempalli to kadapa
4. Then Kadapa tokurnool
5. Then Kurnool to Hyderabad
6. Travel is successfully completed
While comparing both cases Algorithm executed successfully with same output but in case 1 travelling time is lesser
than the case 2 travelling time.
1.8 Tracing an Algorithm
Tracing of an Algorithm means showing how the value of a variable changes during the execution of an algorithm.
Steps in tracing:
1. Identify the variables in the algorithm that need to be traced.
2. Examine the value of the variables at each step in the execution of the algorithm.
3. Determine if the algorithm is giving the correct outputs for a set of legitimate/legal input. Values.
4. Analyze and determine what the purpose of the algorithm
In this module we will see examples of computational algorithms and the techniques used for tracing algorithms. A
computational algorithm is a set of precise instructions expected to be expressed as a computer program that can
execute on a computer.
Let us now get started with an example of adding two numbers.
Algorithm: Add two numbers
Step1: Start
Step2: Input x
Step3: Input y
Step4: Set z x+ y
Step5: Output z
Step6: Stop
If you notice the algorithm it takes two inputs, performs an addition operation and gives the output. Let us see how the
algorithm executes step by step.
Input x/* Takes input from the user by using input devices like keyboard. After entering input from the key board, for
ex: 5 the value is stored in a memory location. The name of this memory location is x in this particular case. Any time
this variable x can store only one value. For ex: if you set x value 6 you will find the new value is referred by x is 6
but not 5 that means the old value which was stored in x values is lost. This is a very good example that shows a
variable can store only one value at a time. Input value :5*/ Input y /* Similar to previous statement where new
memory location is created for variable y and the user inputs to y is stored.Input value :2*/
Set z to x+ y /* in this statement actual operation that is performed on the input values which is to add the numbers
referred to by the variables x and y. In this example you will notice after the addition operation is executed and the
values 5 and 2 are added and set to new variable z. */
Output z //the result value i.e. z is displayed to an output device like monitor?
You will notice that algorithm also can be visualized as functions. A function performs a specific operation like
addition and multiplication or it could be more complex operations like finding square roots or sorting list of numbers.
Variable:
 Variables are used to handle the data by the algorithm.
 Variables refer to a memory location where the actual value is stored.
 Variable can store one value at a time.
 Old values of the variable are lost when a new value is assigned.
1.9 Control structure:
Control Structures are just a way to specify flow of control in programs. Any algorithm or program can be clearer
and more understood if they use self-contained modules called as logic or control structures. It basically analyzes and
chooses in which direction a program flows based on certain parameters or conditions.
19.1 Types of control structures:
There are three types of control structures
1. Sequence
2. Selection or Branching
3. Loop or Repetition
1.9.1Sequence Control Structure: This refers to the line – by – line execution, in which statements are executed
sequentially, in the same order in which they appear in the script.They might, for example, carry out a series of read or
write operations, arithmetic operations, or assignments to variables.
Example problem:
Write algorithm to find the greater number between two numbers
Step1: Start
Step2: Read\input the Number1
Step3: Read\input the Number2.
Step4: Set Average  (Number1+ Number2)/2
Step5: Print Average
Step6: End
1.9.2Selection or Decision Control Structure: The branch refers to a binary decision based on some condition.
Depending on whether a condition is true or false. If the condition is true, one of the two branches is explored; if the
condition is false, the other alternative is taken. This is usually represented by the ‗if-then‘ construct in pseudo-codes
and programs. This structure is also known as the selection structure
Example problem:
A person whose age is more than or equals to 18 years is eligible to vote. Now write an algorithm to check whether he
is eligible to vote?
Step 1: Start
Step2: Input/Read age //Taking age value from the user
Step 3: Check if age >= 18
a) Print ―Eligible to vote‖ //If Condition is true
Step 4: Otherwise/else
a) Print ―Not eligible to vote‖ //if Condition is false
Step 5: Stop
1.9.3 Repetition or Loop Control Structure: This is a control structure that allows the execution of a block of
statements multiple times until a specified condition is met. The loop allows a statement or a sequence of statements to
be repeatedly executed based on some loop condition. It is represented by the ‗while‘ and ‗for‘ constructs in most
programming languages, for unbounded loops and bounded loops respectively. (Unbounded loops refer to those
whose number of iterations depends on the eventuality that the termination condition is satisfied; bounded loops refer
to those whose number of iterations is known before-hand.) In the flowcharts, a back arrow hints the presence of a
loop. A trip around the loop is known as iteration. You must ensure that the condition for the termination of the
looping must be satisfied after some finite number of iterations, otherwise it ends up as an infinite loop, a common
mistake made by inexperienced programmers. The loop is also known as the repetition structure.
Example problem:
Algorithm to print all-natural numbers upto ―n‖ (Here you need to accept a number from the user, and to print all the
natural numbers till ‗n‘ i.e. 1 to n)
Step 1: Start
Step2: Read/Input n
Step 3: Store 1 to ―i‖ //initialization
Step 4: Do the following statements until i<=n//condition
a) print i
b) add 1 to i//increment
Step 5: Stop
Nested control structures: Combining the use of these control structures, for example, a loop within a loop (nested
loops), a branch within another branch (nested if), a branch within a loop, a loop within a branch, and so forth, is not
uncommon. Complex algorithms may have more complicated logic structure and deep level of nesting, in which case
it is best to demarcate parts of the algorithm as separate smaller modules. Beginners must train themselves to be
proficient in using and combining control structures appropriately, and go through the trouble of tracing through the
algorithm before they convert it into code.
Module 2 - Introduction to Flow chart
1.10 Flowchart
The diagrammatic representation of an algorithm is called ―Flowchart‖.Before you start coding a program it is
necessary to plan the step by step solution to the task your program will carry out. Such a plan can be symbolically
developed using a diagram. This diagram is then called a flowchart. Hence a flowchart is a symbolic representation of
a solution to a given task. A flowchart can be developed for practically any job. Flowcharting is a tool that can help us
to develop and represent graphically program logic sequence.
For example suppose you are going for a picnic with your friends then you plan for the activities you will do there. If
you have a plan of activities then you know clearly when you will do what activity. Similarly when you have a
problem to solve using computer or in other word you need to write a computer program for a problem then it will be
good to draw a flowchart prior to writing a computer program. Flowchart is drawn according to defined rules.
Features of flowchart:
The features of a flowchart are:
1. It is an easy method of communication.
2. It is independent of a programming language.
3. It is the key to correct programming.
4. It clearly indicates the task to be performed at each level.
1.11 Flowchart Symbols
There are 6 basic symbols commonly used in flowcharting of assembly language Programs: Terminal, Process, and
input/output, Decision, Connector and Predefined Process. This is not a complete list of all the possible flowcharting
symbols; it is the ones used most often in the structure of Assembly language programming.
1. Process Symbol:
o A process symbol is used to represent arithmetic and data movement instructions in the flowchart. All
arithmetic processes of addition, subtraction, multiplication and division are indicated in the process symbol.
o The logical process of data movement from one memory location to another is also represented in the
process box. If there are more than one process
2. Input/ Output Symbol:
o This symbol is used to denote any input/output function in the program. Thus, if there is any input to the
program via an input device, like a keyboard, tape, card reader etc. it will be indicated in the flowchart with
the help of the Input/output symbol.
o Similarly, all output instructions, for output to devices like printers, plotters, magnetic tapes, disk, monitors
etc. are indicated in the Input/ Output symbol.
3. Decision Symbol:
o The decision symbol is used in a flowchart to indicate the point where a decision is to be made and
branching done upon the result of the decision to one or more alternative paths. The criteria for decision
making are written in the decision box.
o All the possible paths should be accounted for. During execution, the appropriate path will be followed
depending upon the result of the decision.
4. Loops: Looping is a problem-solving technique through which a group of statements is executed repeatedly,
until certain specified condition is satisfied. Looping is also called a repetitive or an iterative control statement
5. Connectors:
This symbol shows continuation of the flow chart from one page to another. When you reach the bottom of
the page or need to jump to another page, draw flow chart connector symbol and connect it to the last item on
the chart. Label the inside of the symbol with a letter, typically beginning with an ―A‖.
6. Predefined process (Function):
This symbol indicates a sequence of actions that perform a specific task embedded within a larger process.
7. Terminal Symbol:
o Every flowchart has a unique starting point and an ending point.
o The flowchart begins at the start terminator and ends at the stop terminator.
o The Starting Point is indicated with the word START inside the terminator symbol. The Ending Point is
indicated with the word STOP inside the terminator symbol. There can be only one START and one STOP
terminator in your entire flowchart.
1.12 General Rules for flowcharting
1. All boxes of the flowchart are connected with Arrows. (Not lines)
2. Flowchart symbols have an entry point on the top of the symbol with no other entry points. The exit point for
all flowchart symbols is on the bottom except for the Decision symbol.
3. The Decision symbol has two exit points; these can be on the sides or the bottom and one side.
4. Generally, a flowchart will flow from top to bottom. However, an upward flow can be shown as long as it
does not exceed 3 symbols.
5. Connectors are used to connect breaks in the flowchart. Examples are:
i. From one page to another page.
ii. From the bottom of the page to the top of the same page.
6. Subroutines (Functions) and Interrupt programs have their own and independent flowcharts.
7. All flow charts start with a Terminal or Predefined Process (for interrupt programs or subroutines) symbol.
8. All flowcharts end with a terminal or a contentious loop.
Flowcharting uses symbols that have been in use for a number of years to represent the type of operations and/or
processes being performed. The standardized format provides a common method for people to visualize problems
together in the same manner. The use of standardized symbols makes the flow charts easier to interpret, however,
standardizing symbols is not as important as the sequence of activities that make up the process.
1.13 Advantages and Disadvantages of using flowchart
1.13.1 Advantages: As we discussed flow chart is used for representing algorithm in pictorial form. This pictorial
representation of a solution/system is having many advantages. These advantages are as follows:
 Communication: A Flowchart can be used as a better way of communication of the logic of a system and
steps involve in the solution, to all concerned particularly to the client of system.
 Effective analysis: A flowchart of a problem can be used for effective analysis of the problem.
 Documentation of Program: Program flowcharts are a vital part of good program documentation. Program
document is used for various purposes like knowing the components in the program, complexity of the
program etc.
 Efficient Program Maintenance: Once a program is developed and becomes operational it needs time to
time maintenance. With help of flowchart maintenance become easier.
 Coding of the Program: Any design of solution of a problem is finally converted into computer program.
Writing code referring the flowchart of the solution become easy.
1.13.2Disadvantages:
 Drawing flowchart is a time-consuming task.
 Manual tracing is needed to check correctness of flowchart drawn on paper.
 Simple modification in problem logic may lead to complete redraw of flowchart.
 Showing many branches and looping in flowchart is difficult.
 In case of complex program/algorithm, flowchart becomes very complex and clumpsy.
1.14 Some examples of Flowcharts
Now, we will discuss some examples on flowcharting. These examples will help in proper understanding of
flowcharting technique. This will help you in program development process in next unit of this block.
Problem1: Find the area of a circle of radius r

Problem 2: Convert temperature Fahrenheit to Celsius.

Problem3: Flowchart for an algorithm which gets two numbers and prints sum of their value.
1.15 Types of control structures:
Definition
 The logic of a program may not always be a linear sequence of statements to be executed in that order.
 The logic of the program may require execution of a statement based on a decision.
 Control structures specify the statements to be executed and the order of execution of statements.
Where is the usage of control structure?
Flowchart and Pseudo Code use Control structures for representation

There are three kind of Control Structure:


1. Sequential
2. Selection(Branch or conditional )
3. Iterative(loop)
1.15.1 Sequential:
 Instruction is executed in linear order.
 Statements are executed in a specified order. No statement is skipped and no statement is executed more than
once.
Example problem:
1. Take two numbers from the user print their sum?

2. Take input of two numbers from the user and do the division of two numbers?
1.15.2 Selection (Branch or conditional):
 It‘s asked a true/false question THEN selects the next instruction based on the answer.
 It selects a statement to execute on the basis of condition. Statement is executed when the condition is
true and ignored when it is false
Example: if, if else, switch structures.

Example problem:
3. Draw a flowchart to determine greatest among two numbers?

1.15.3 Iterative (loop):


 Its repeat the execution of a block of instruction.
 In this structure the statements are executed more than one time. It is also known as iteration or loop
 A loop structure is used to execute a certain set of actions for a predefined number of times or until a
particular condition is satisfied
Example: while loop, for loop do-while loops etc.

Iterative Structure
Example problem:
Write an algorithm and flowchart to find Total Sum from 1 to 100 natural numbers
Step 1: Start
Step 2: Read value of n
Step 3: Set i←1
Step 4: Set Total_Sum 0
Step 5: Repeat the steps until i greater than n
a) Set Total_SumTotal_Sum+i
b) increment i // (i.e. i=i+1)
Step 6: Display ―1 to 100 Natural Numbers Sum:‖ Total_Sum
Step 7: End

Nested Control Structures:


A nested control statement is a control statement that is contained within another control statement. You can do this to
many levels. You can place control statements inside other control statements, for example an If...Then...Else block
within a for. Next loop. A control statement placed inside another control statement is said to be nested.

Example problem:
1. Draw a flowchart to determine largest among three numbers?

1.16 Pseudo code


A pseudo code is an informal way of writing a program. However, it is not a computer program. It only represents the
algorithm of the program in natural language and mathematical notations. Besides, there is no particular programming
language to write a pseudo code. Unlike in regular programming languages, there is no syntax to follow when writing
a pseudo code. Furthermore, it is possible to use pseudo codes using simple English language statements.
 Pseudo code is a kind of structured English for describing algorithm.
 It has no syntax like any of the programming language and thus can‘t be compiled or interpreted by the
computer.
 No syntax for Pseudo code
 Not executable program
1.17 Advantages of Pseudo code
 Improves the readability of any approach. It‘s one of the best approaches to start implementation of an
algorithm.
 Acts as a bridge between the program and the algorithm or flowchart. Also works as a rough documentation,
so the program of one developer can be understood easily when a pseudo code is written out. In industries, the
approach of documentation is essential. And that‘s where a pseudo-code proves vital.
 The main goal of a pseudo code is to explain what exactly each line of a program should do, hence making the
code construction phase easier for the programmer
1.18 How to write a Pseudo-code?
 To begin the comment double forward slash are used ―//―.
 Matching braces ―{and}‖ are used to present blocks where a compound statement (set of simple statements)
can be illustrated as a block and terminated by a semicolon‖;―. The body of a procedure constructs a block as
well.
 All the identifiers start with a letter and the data type of the variables are not declared explicitly.
 An assignment statement is used for the assigning values to the variables.
 To produce the Boolean values (i.e., true and false) the logical operators and, or and not and the relational
operators <, ≤, =, =, ≥ and > are provided.
Input and output are presented by read and write instructions.
Example:
1. A pseudo code to find the total of two numbers is as follows.
Sum Of Two Numbers ()
begin
Set sum =0;
Read: number 1, number 2;
Set sum = number1 + number 2;
Print sum;
End
2. A pseudo code to find the area of a triangle is as follows.
AreaofTrinagle()
Begin
Read: base,height;
Set area =0.5*base*height;
Print area;
End
1.19 Differences between algorithm and Flowchart:
Algorithm Flow chart
Step by step instruction representing the process of any Block by block information diagram representing the
solution. data flow.
It is step wise analysis of the work to be done It is a pictorial representation of a process
Solution is shown in non computer language like English. Solution is shown in graphical format.
It is something difficult to understand. Easy to understand as compared to algorithm.
Difficult to show branching and looping. Easy to show branching and looping.
Algorithm can be written for any problem. Flow chart for big problem is impractical.
Easy to debug errors. Difficult to debug errors.
It is difficult to write algorithm as compared to flowchart. It is easy to make flowchart.
1.20 Differences between algorithm and Pseudocode:
Basis for comparison Algorithm Pseudo code
Comprehensibility Quite hard to understand Easy to interpret
Uses Complicated programming language Combination of programming language and
natural language.
Debugging Moderate simpler
Ease of construction Complex Easier
1.21 Difference between flow chart and pseudo code:
Flow chart Pseudo code
A diagrammatic representation that illustrates a solution An informal high – level description of the operating
model to a given problem. principle of an algorithm.
Written using various symbols. Written in natural language and mathematical notations
help to write pseudo code.
Solved problems:
1. Write an algorithm to go for class picnic.
Algorithm:
Step 1: Start
Step 2: Decide the picnic venue, date and time
Step 3: Decide the picnic activities
Step 4: Hire a vehicle to reach to the venue and comeback
Step 5: Goto to the picnic venue on the decided date
Step 6: Do the activities planned for the picnic
Step 7: Come back to school in the hired vehicle
Step 8: Stop
2. To celebrate Teachers' Day
Algorithm:
Step 1: Start
Step 2: Decide the activities for teachers' day like dance performances, plays, etc.
Step 3: Form groups of students and assign the decided activities from step 2 to each group.
Step 4: Decide the practice timings for each group.
Step 5: Each group to practice as per the timings decided in step 4.
Step 6: Invite the teachers to Teachers' Day celebrations.
Step 7: Perform the activities planned in step 2 on Teachers' Day
Step 8: Stop
3. To celebrate New Year
Algorithm:
Step 1: Start
Step 2: Prepare a guest list for New Year party
Step 3: Decide the venue, food menu, games and fun activities for the party
Step 4: Invite the guests for the party
Step 5: On New Year eve, get ready and enjoy the party
Step 6: Stop
4. Convert temperature Fahrenheit to Celsius with flowchart
Inputs to the algorithm: Temperature in Fahrenheit
Expected output: Temperature in Celsius
Algorithm:
Step1: Start
Step2: Read Temperature in Fahrenheit F
Step3: Set C 5/9*(F-32)
Step4: Print ―Temperature in Celsius: ―+C
Step5: End
5. Write an algorithm to read two numbers and find their product?
Inputs to the algorithm: First num1. Second num2.
Expected output: Sum of the two numbers.
Algorithm:
Step1: Start
Step2: Read\input num1.
Step3: Read\input num2.
Step4: set product  num1 * num2 // calculation of product
Step5: Print product.
Step6: End
6. An algorithm to display even numbers between 0 and 99 with
flowchart
Step 1: Start
Step2: input/read value of n
Step3: Set even0
Step4: Do the following until even < 100
a) Display even
b) Set even even+2
Step5: End
7. Design an algorithm which generates even numbers between 1000 and 2000 and then prints them in the
standard output. It should also print total sum:
Step 1: Start
Step2: input/read value of n
Step3: Set even1000
Step4: Do the following until even < 2000
a) Display even
b) Set even even+2
Step5: End
8. Define the following symbol and use?

Answer: Process Box: A process box is used to represent all types of mathematical tasks like addition,
subtraction, multiplication, division, etc.
9. Algorithm to find area of a rectangle?
Algorithm:
Step 1: Start
Step 2: Take length and breadth and store them as L and B? // Input
Step 4: Multiply L and B and store it in area //Area of Rectangle = L*B
Step 5: Print area //Output
Step 6: Stop.
10. Write an algorithm to find the largest among three different numbers entered by user with flowchart
Step 1: Start
Step 2: Read variables a, b and c.
Step 3: If a greater than b
a) If a greater than c
i) Display a is the largest number.
b) else
i) Display c is the largest number.
Step 4: else
a) If b greater than c
i) Display b is the largest number.
b) else
i) Display c is the greatest number.
Step 5: Stop
Multiple Choice Questions:
1) An Algorithm is expressed by
a) Flowchart b) common language c) pseudo code d) all
2) A good algorithm having finite steps?
a) True b) False
3) Algorithm efficiency is measured by?
a) Speed b) space c) code d) all of the above
4) How many control structures are there in algorithm?
a) 3 b) 2 c) 1
5) Which control structure used weather a condition is true or false?
a) Selection b) iteration c) sequence d) none
6) Which control structure used to check a condition more than one time?
a) Iteration b) loop c) a & b d) None of the above
7) In computer science, algorithm refers to a pictorial representation of a flowchart.
a) True b) False
8) The process of drawing a flowchart for an algorithm is called __________
a) Performance b) Evaluation c) Algorithmic Representation d) Flowcharting
9) Actual instructions in flowcharting are represented in _________
a) Circles b) Boxes c) Arrows d) Lines
10) A box that can represent two different conditions.
a) Rectangle b) Diamond c) Circle d) Parallelogram
11) The following box denotes?
a) Decision b) Initiation c) Initialization d) I/O
12) There should be certain set standards on the amount of details that should be provided in a flowchart
a) True b) False
13) Which of the following is not an advantage of a flowchart?
a) Better communication b) Efficient coding c) Systematic testing d) Improper documentation
14) The symbol denotes _______

a) I/O n b) Flow c) Terminal d) Decision


15) Pseudo code is an informal high-level description of an algorithm.
a) True b) false
16) In a flowchart a calculation(process) is represented by
a) A rectangle b) A rhombus c) A parallelogram d) A circle
17) The symbol denotes__________
a) I/O b) Flow c) Loop d) Decision
18) To repeat a task a number times
a) Loop statement b) Input statement c) Conditional statement d) Output statement
19) In a flow chart how are the symbols connected?
a) Symbols do not get connected together in a flowchart
b) With lines and arrow to show the direction of flow
c) With dashed lines and numbers
d) With solid lines to link events
20) A flow chart does need to have a start?
a) True b) False
Unsolved Problems:
1) Write an algorithm and flow chart to add four numbers?
2) Write an algorithm to make tea/coffee
3) Write 6 No‘s Algorithms for performing day to day activities.
4) Write an algorithm and flow chart to find large number among given two numbers.
5) Draw the flow chart to convert distance entered in Km to Meters.
6) Accept the age of a person and check whether he/she is eligible to vote or not. A person is eligible to vote
only when he/she is 18 years or more.
7) Draw the flow chart to find the area of a rectangle whose length and breadth are given
8) Draw the flow chart to find the average of three numbers a, b and c.
9) Write an algorithm and flow chart Print 1 to 100?
10) Write an algorithm to find average of three numbers?
Unit 2 - Introduction to Python Programming
Module 1 - What is Python Programming Language and its Classifications
2.1 What is a Language?
 Language is the method of human communication, either spoken or written, It consisting of the use of words
in a structured and conventional way.
 The Language is nothing but set of instructions we are used to communicate.
 To communicate a particular person, we are passing instruction using a particular language
like English, Telugu, and Hindi…. etc.
 But while using a language we need to follow some of instructions, some rules are already they
have given.
 What are the rules? If I want to speak in English, to form a sentence, first we should be good at
grammatically, are else we cannot form a sentence, to speak in English language.
 Similarly, computer language is also for communication sake only
2.2 What is Programming Language?
 Programming Language is also like English, Telugu…etc.
 It should contain vocabulary and set of grammatical rules for
instructing a computer to perform specific tasks.
 Each language has a unique set of keywords and a special syntax for
organizing program instructions
 Programming languages are classified as:
 Machine language, Assembly language and High-level
language
 The term programming language usually refers to high-level
languages, such as BASIC, C, C++, COBOL, FORTRAN, Ada, and
Pascal
2.3 Types of Programming Languages
2.3.1 Machine Language: The language of 0s and 1s is called as machine language. This is the only language which
can be understood computers directly.
Merits:
 It is directly understood by the processor so has faster execution time since the programs written in this language
need not to be translated.
 It doesn‘t need larger memory.
Demerits:
 It is very difficult to program using Machine Language since all the instructions are to be represented by 0s and
1s.
 Use of this language makes programming time consuming.
 It is difficult to find error and to debug.
 It can be used by experts only.
2.3.2 Assembly Languages: It is low level programming language in which the sequence of 0‘s and 1‘s are replaced
by mnemonic (ni-monic) codes. Typical instructions for addition and subtraction.
Example: ADD for addition, SUB for subtraction etc.
Since our system only understands the language of 0s and 1s .therefore, a system program is known as assembler.
Which is designed to translate an assembly language program into the machine language program?
Merits:
 It is makes programming easier than Machine Language since it uses mnemonics code for programming. Eg:
ADD for addition, SUB for subtraction, DIV for division, etc.
 It makes programming process faster.
 Error can be identified much easily compared to Machine Language
 It is easier to debug than machine language.
Demerits:
 Programs written in this language is not directly understandable by computer so translators should be used.
 It is hardware dependent language so programmers are forced to think in terms of computer‘s architecture rather
than to the problem being solved.
 Being machine dependent language, programs written in this language are very less or not portable.
 Programmers must know its mnemonics codes to perform any task.
2.3.3 High Level Language: High level languages are English like statements and programs Written in these
languages are needed to be translated into machine language before execution using a system software such as
compiler. Program written in high level languages are much easier to maintain and modified.
 High level language program is also called source code.
 Machine language program is also called object code
Merits:
 Since it is most flexible, variety of problems could be solved easily
 Programmer does not need to think in term of computer architecture which makes them focused on the problem.
 Programs written in this language are portable.
Demerits:
 It is easier but needs higher processor and larger memory.
 It needs to be translated therefore its execution time is more.
2.4 Interpreter and Compiler
 We generally write a computer program using a high-level language. A
high-level language is one which is understandable by humans.
 But a computer does not understand high-level language. It only
understands program written in 0's and 1's in binary, called the
machine code or object code.
A program written in high-level language is called a source code. We need to
convert the source code into machine code and this is accomplished (actioned)
by compilers and interpreters.
Interpreter Compiler
Translates program one statement at a time. Scans the entire program and translates it into machine
code.
It takes less amount of time to analyze the It takes large amount of time to analyze the source code
source code but the overall execution time is but the overall execution time is comparatively faster.
slower.
No intermediate object code is generated, Generates intermediate object code which further
hence are memory efficient. requires linking, hence requires more memory.
Continues translating the program until the It generates the error message only after scanning the
first error is met, in which case it stops. whole program. Hence debugging is comparatively
Hence debugging is easy. hard.
Programming language like Python, Ruby Programming language like C, C++ use
use interpreters. compilers.
Module 2 – Introduction to Python Programming
2.5 Introduction
 Python is an interpreter, object-oriented, high-level programming language with dynamic semantics (substance).
 Python's simple, easy to learn syntax emphasizes readability and therefore reduces the cost of program maintenance.
 Python supports modules and packages, which encourages program modularity and code reuse
 It consists of high-level built in data structures, combined with dynamic typing and dynamic binding; make it very
attractive for Rapid Application Development, as well as for use as a scripting or glue language to connect existing
components together.
 Python is an open-source programming language made to both look good and be easy to read.
2.6 History of Python
 Python is an old language created by Guido Van Rossum. The design began in the late 1980s and was first
released in February 1991.
 Python is influenced by following programming languages:
o ABC language.
o Modula-3
2.7 Why Python was created?
 In late 1980s, Guido Van Rossum was working on the Amoeba distributed operating system group.
 He wanted to use an interpreted language like ABC (ABC has simple easy-to-understand syntax) that could
access the Amoeba system calls.
 So, he decided to create a language that was extensible. This led to a design of new language which was later
named Python.
 Python drew inspiration from other programming languages like C, C++, Java, Perl, and Lisp.
2.8 Why the name was Python?
 No. It wasn't named after a dangerous snake. Rossum was fan of a comedy series Monty Python's Flying
Circus in late seventies.
 The name "Python" was adopted from the same series "Monty Python's Flying Circus".
Release Dates of Different Versions
Version Release Data
Python1.0(firststandardrelease) January1994

Python1.6 (Lastminorversion) September5,2000


Python2.0(Introducedlistcomprehensions) October 16,2000

Python2.7 (Last minorversion) July3, 2010


Python3.0(Emphasis December 3, 2008
onremovingduplicativeconstructs and module)
September13,2015
Python3.5
Python 3.7 June 27, 2018
Python 3.8.0 (Last updated version) Oct. 14, 2019
2.9 Features of Python Programming
A simple language which is easier to learn Python has a very simple and elegant
(graceful) syntax. It's much easier to read and write Python programs compared to other
languages like: C++,Java, C#.

Free and open-source


 You can even make changes to the Python's source code and update.
Portability
 You can move Python programs from one platform to another, and run it without any changes. It runs smoothly
on almost all platforms including Windows, Mac OS X and Linux
Extensible and Embeddable
 Suppose an application requires high performance. You can easily combine pieces of C/C++ or other languages
with Python code and other languages may not provide out of the box
A high-level, interpreted language
 Unlike C/C++, you don't have to worry about daunting (Cause to lose courage) tasks like memory management,
garbage collection and so on, likewise, when you run Python code, it automatically converts your code to the
language your computer understands. You don't need to worry about any lower-level operations
Large standard libraries to solve common tasks
 Python has a number of standard libraries which makes life of a programmer much easier since you don't have to
write all the code yourself
 For example: Need to connect MySQL database on a Web server? You can use MySQLdb library using import
MySQLdb
Object-oriented
 Everything in Python is an object. Object oriented programming (OOP) helps you solve a complex problem
intuitively.
 With OOP, you are able to divide these complex problems into smaller sets by creating objects.
Images For Applications of Python
Web Applications
 You can create scalable Web Apps using frameworks and CMS (Content Management System) that are built on
Python.
 Some of the popular platforms for creating Web Apps are: Django, Flask, Pyramid, Plone, Django CMS.
 Sites like Mozilla, Reddit, Instagram and PBS are written in Python.
Scientific and Numeric Computing
 There are numerous libraries available in Python for scientific and numeric computing. There are libraries like:
SciPy and NumPy that are used in general purpose computing. And,
 There are specific libraries like: EarthPy for earth science, AstroPy for Astronomy and so on.
 Also, the language is heavily used in machine learning, data mining and deep learning.
2.10 Why Python is ver y easy to learn?
 One big change with Python is the use of white space to define code: spaces or tabs are used to organize
code by the amount of spaces or tabs.
 This means at the end of each line; a semicolon is not needed and curly braces ({}) are not used to group
the code.
 Which are both common in C. The combined effect makes Python a very easy to read language.
4 Reasons to Choose Python as First Language
2.10.1 Simple Elegant (Graceful) Syntax
 It's easier to understand and write Python code.
 Why? Syntax feels Naturals with Example Code
A=12
B=23
sum=A+B
print(sum)
 Even if you have never programmed before, you can easily guess that this program adds two numbers and prints
it.
2.10.2 Not overly strict
 You don't need to define the type of a variable in Python. Also, it's not necessary to add
semicolon at the end of the statement.
 Python enforces you to follow good practices (like proper indentation). These small things can make
learning much easier for beginners.
2.10.3 Expressiveness of the language
 Python allows you to write programs having greater functionality with fewer (less) lines of code.
 We can build game (Tic-tac-toe)with Graphical interface in less than 500 lines of code
 This is just an example. You will be amazed how much you can do with Python once you learn the
basics.
2.10.4 Great Community and Support
 Python has a large supporting community.
 There are numerous active forums online which can be handy if you are stuck
2.11 Install and Run Python
Ubuntu
1. Install the following dependencies:
$sudo apt-get install build-essential check install
$sudo apt-get installlibsqlite3-dev
$sudo apt-get installlibbz2-dev
(libreadline-gplv2-devlibncursesw5-devlibssl-devtk-devlibgdbm-devlibc6-dev)
Video Link: -https://www.youtube.com/watch?v=sKiDjO_0dCQ
2. Go to Download Python page on the official site and click DownloadPython3.4.3
3. In the terminal, go to the directory where the file is downloaded and run the command:
i. $tar-xvfPython-3.4.3.tgz
ii. This will extract your zipped file.
Note: The filename will be different if you've downloaded a different version. Use the appropriate filename
4. Go to the extracted directory.
$ cd Python-3.4.3
5. Issue the following commands to compile Python source code on your Operating system
$./configure
$ make
$ make install
6. Go to Terminal and type the following to run sample ‗helloworld‗ Program
ubuntu@~$python3.4.3
>>>print(‗HellowWorld‘)
Hello World
Windows
1. Go to Download Python page on the official site and click Download Python 3.4.3
2. When the download is completed, double-click the file and follow the instructions to install it
3. When Python is installed, a program called IDLE is also installed along with it. It provides graphical user
interface to work with Python
4. Open IDLE, copy the following code below and press enter
print ("Hello, World ")
5. To create a file in IDLE, go to File > New Window (Shortcut: Ctrl+N).
6. Write Python code (you can copy the code below for now) and save (Shortcut: Ctrl+S) with .py file extension
like: hello.py or your-first-program.py
print ("Hello, World ")
7. Go to Run > Run module (Shortcut: F5) and you can see the output. Congratulations, you've successfully run
your first Python program
2.12 Modes of running
There are various ways to start Python
Immediate Mode or Interactive Mode
 Typing python in the command line will invoke the interpreter in immediate mode. We can directly type in
Python expressions and press enter to get the output (>>>)
 Is the python prompt and it tells us interpreter is ready for input

Quitting Python

Script Mode
 This mode is used to execute Python program written in a file. Such a file is called a script. Scripts can be
saved to disk for future use. Python scripts should have the extension .py, it means that the filename ends
with .py.
 For example: helloWorld.py
 To execute this file in script mode we simply write python3 helloWorld.py at the command prompt.

Integrated Development Environment (IDE)


 We can use any text editing software to write a Python script file. Like Notepad, Editplus, sublime…etc
2.13 Python Program to Print Helloworld!
 Type the following code in any text editor or an IDE and Save it as helloworld.py
 Now at the command window, go to the location of this file, use cd command to change directory
 To run the script, type python3helloworld.py in the command window then we get output like this: HelloWorld
 In this program we have used the built-in function print(), to print out a string to the screen
 String is the value inside the quotation marks i.e. HelloWorld
Let us execute programs in different modes of programming.
Interactive Mode Programming:
Invoking the interpreter without passing a script file as a parameter brings up the following prompt:
$ python3
Python 3.7 (r27:82525, Jul 4 2010, 09:01:59) [MSC v.1500 32 bit (Intel)] on win32
Type "copyright", "credits" or "license()" for more information.
Type the following text at the Python prompt and press the Enter:

If you are running new version of Python, then you need to use print statement with parenthesis as in print ("Hello,
IIIT RK Valley");.However in Python version 2.7, this produces the following result:

Script Mode Programming:


Python programs must be written with a structure. The syntax must be correct, or the interpreter will generate error
messages and not execute the program. This section introduces Python by providing a simple example program.
To write Python programming in script mode we have to use editors. Let us write a simple Python program in a script
mode using editors. Python files have extension .py. Type the following source code in a simple.py file.
Program 2.1 (simple.py) is one of the simplest Python programs that does something

We assume that you have Python interpreter set in PATH variable. Now, try to run this program as follows:
$ python3 simple.py
This produces the following result:

Module 3 - Reserved key words, Identifiers, Variables and Constant


2.14 Keywords
 Keywords are the reserved words in Python and we cannot use a keyword as variable name, function name or any
other identifier.
 They are used to define the syntax and structure of the Python language.
 In Python, keywords are case sensitive.
 There are 35 keywords in Python 3.7.3 This number keep on growing with the new features coming in python
 All the keywords except True, False and None are in lowercase and they must be written as it is.
 The list of all the keywords is given below
We can get the complete list of keywords using python interpreter help utility.
$ python3
>>>help()
help> keywords
2.15 Identifiers
Identifier is the name given to entities like class, functions, variables etc. in Python.
Rules for writing identifiers
 Identifiers can be a combination of letters in lowercase (a to z) or uppercase (A to Z) or digits (0 to9) or an
underscore (_).
 Names like myClass, var_1and print_this_to_screen, all are valid example.
 An identifier cannot start with a digit.1variable is invalid, but variable1is perfectly fine.
 Keywords cannot be used as identifiers.
>>> global=1File"<interactiveinput>",line1
global=1
^SyntaxError: invalid syntax
 We cannot use special symbols like!, @, #, $,% etc. in our identifier. >>>a@ =0
File"<interactive input>", line1a@= 0^
Syntax Error: invalid syntax
 Identifier can be of any length.
2.16 Things to care about
 Python is a case-sensitive language. This means, Variable and variable are not the same. Always give a valid
name to identifiers so that it makes sense.
 While, c = 10is valid. Writing count =10would make more sense and it would be easier to figure out what it does
even when you look at your code after a long gap.
 Multiple words can be separated using an underscore, this_is_a_long_variable.
 We can also use camel-case style of writing,
 i.e., capitalize every first letter of the word except the initial word without any spaces.
 For example: camelCase Example.
2.17 Variable
 A variable is a location in memory used to store some data.
 Variables are nothing but reserved memory locations to store values, this means that when we create a variable,
we reserved some space in memory.
 They are given unique names to differentiate between different memory locations.
 The rules for writing a variable name are same as the rules for writing identifiers in Python.
 We don't need to declare a variable before using it.
 In Python, we simply assign a value to a variable and it will exist.
 We don't even have to declare the type of the variable. This is handled internally according to the type of value
we assign to the variable.
Variable assignment: We use the assignment operator (=) to assign values to a variable. Any type of value can be
assigned to any valid variable.
a= 5
b = 3.2
c = "Hello"
Here, we have three assignment statements. 5 is an integer assigned to the variable a. Similarly, 3.2 is a floating-point
number and "Hello" is a string (sequence of characters) assigned to the variables b and c respectively.
Multiple assignments:
 In Python, multiple assignments can be made in a single statement as follows: a, b, c = 5,3.2, "Hello"
 If we want to assign the same value to multiple variables at once, we can do this as x = y= z ="same"
 This assigns the "same" string to all the three variables.
Constants: A constant is a type of variable whose value cannot be changed. It is helpful to think of constants as
containers that hold information which cannot be changed later. You can think of constants as a bag to store some
books which cannot be replaced once placed inside the bag.
Assigning value to constant in Python: In Python, constants are usually declared and assigned in a module. Here, the
module is a new file containing variables, functions, etc which is imported to the main file. Inside the module,
constants are written in all capital letters and underscores separating the words.
Example 1: Declaring and assigning value to a constant
Create a constant.py:
PI = 3.14
GRAVITY = 9.8
Create a main.py:
import constant
print(constant.PI)
print(constant.GRAVITY)
Output
3.14
9.8
In the above program, we create a constant.py module file. Then, we assign the constant value to PI and GRAVITY.
After that, we create a main.py file and import the constant module. Finally, we print the constant value.
Note: In reality, we don't use constants in Python. Naming them in all capital letters is a convention to separate them
from variables; however, it does not actually prevent reassignment.
2.18 Statements & Comments
Instructions that a Python interpreter can execute are called statements.
For example,
a = 1 is an assignment statement. If statement, for statement, while statement etc.
2.18.1 Multi-line statement
 In Python, end of a statement is marked by a new line character. But we can make a statement extend over
multiple lines with the line continuation character (\).
For example:
a=1+2+3+\
4+5+6+\
7+8+9
This is explicit line continuation.
 This is explicit line continuation. In Python, line continuation is implied inside parentheses( ), brackets[ ] and
braces{}.
 For instance, we can implement the above multi-line statement as
a = (1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9)
 Here, the surrounding parentheses ( ) do the line continuation implicitly. Same is the case with []and{ }.
For example: colors = ['red',
'blue',
'green']
 We could also put multiple statements in a single line using semicolons, as follows a= 1; b=2;c =3
2.18.2 Comments
 Comments are very important while writing a program. It describes what's going on inside a program so that a
person looking at the source code does not have a hard time figuring it out.
 You might forget the key details of the program you just wrote in a month's time. So taking time to explain these
concepts in form of comments is always fruitful.
 In Python, we use the hash (#) symbol to start writing a comment. It extends up to the new line character.
 Comments are for programmers for better understanding of a program. Python Interpreter ignores comment.
#this is a comment
#print out Hello
print('Hello')
Multi-linecomments
 If we have comments that extend multiple lines, one way of doing it is to use hash(#) in the beginning of each
line. For example:
#this is a long comment
#and it extends
#to multiple lines
 Another way of doing this is to use triple quotes, either '''or""".
 These triple quotes are generally used for multi-line strings. But they can be used as multi-line comment as well.
Unless they are not docstrings, they do not generate any extracode.
"""This is also a
perfect example of
multi-line comments"""
Module 4 - Python Operators
2.19 Get Started with Python Operators
 Operators are special symbols in Python that carry out arithmetic or logical computation. The value that the
operator operates on is called the operand.
For example: >>> 2+3
 Here, + is the operator that performs addition. 2 and 3 are the operands and 5 is the output of the operation.
 Python has a number of operators which are classified below.
o Arithmetic operators
o Assignment operators
o Comparison (Relational) operators
o Logical (Boolean) operators
o Bitwise operators
o Assignment operators
o Special operators
2.19.1 Arithmetic Operators
Arithmetic operators are used to perform mathematical operations like addition, subtraction, multiplication etc.
Operator Meaning Example
+ Add two operands or unary plus x + y +2
- Subtract right operand from the left or unary minus x – y -2
* Multiply two operands x*y
/ Divide left operand by the right one (always results into float) x/y
% Modulus - remainder of the division of left operand by the right x % y (remainder of x/y)
// Floor division - division that results into whole number adjusted to the x // y
left in the number line
** Exponent - left operand raised to the power of right x**y (x to the power y)
Example Program for Arithmetic operators
x = 25
y = 15
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)
2.19.2 Comparison (Relational) Operators
Comparison operators are used to compare values. It either returns True or False according to the condition
Operator Meaning Example
> Greater than - True if left operand is greater than the right x>y
< Less than - True if left operand is less than the right x<y
== Equal to - True if both operands are equal x == y
!= Not equal to - True if operands are not equal x != y
>= Greater than or equal to - True if left operand is greater than or equal to the right x >= y
<= Less than or equal to - True if left operand is less than or equal to the right x <= y
Example: x = 10;y = 12
print('x > y is',x>y)
2.19.3 Logical (Boolean) Operators
Operator Meaning Example
and True if both the operands are true x and y
or True if either of the operands is true x or y
not True if operand is false (complements the operand) not x
Here is an 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)
2.19.4 Bitwise Operators
Bitwise operators act on operands as if they were string of binary digits. It operates bit by bit, hence the name.
For example, 2 is 10 in binary and 7 is 111.
In the table below: Let x = 10 (0000 1010 in binary) and y = 4 (0000 0100 in binary)
Operator Meaning Example
& Bitwise AND x& y = 0 (0000 0000)
| Bitwise OR x | y = 14 (0000 1110)
~ Bitwise NOT ~x = -11 (1111 0101)
^ Bitwise XOR x ^ y = 14 (0000 1110)
>> Bitwise right shift x>> 2 = 2 (0000 0010)
<< Bitwise left shift x<< 2 = 40 (0010 1000)
2.19.5 Assignment Operators
Assignment operators are used in Python to assign values to variables. a = 5 is a simple assignment operator that
assigns the value 5 on the right to the variable a on the left. There are various compound operators in Python
Example: a += 5 that adds to the variable and later assigns the same. It is equivalent to a = a + 5.
Operator Example Equivalent to
= x=5 x=5
+= x += 5 x=x+5
-= x -= 5 x=x-5
*= x *= 5 x=x*5
/= x /= 5 x=x/5
%= x %= 5 x=x%5
//= x //= 5 x = x // 5
**= x **= 5 x = x ** 5
&= x &= 5 x=x&5
|= x |= 5 x=x|5
^= x ^= 5 x=x^5
>>= x >>= 5 x = x >> 5
<<= x <<= 5 x = x << 5
2.19.6 Membership Operators
in and notin are the membership operators in Python. They are used to test whether a value or variable is found in a
sequence (string, list, tuple, set and dictionary).
Operator Meaning Example
in True if value/variable is found in the sequence 5 in x
not in True if value/variable is not found in the sequence 5 not in x
Here is an 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)
Here, 'H' is in x but 'hello' is not present in x (remember, Python is case sensitive). Similarly, 1 is key and 'a' is the
value in dictionary y. Hence, 'a' in y returns False.
2.20 Rules for solving equations in Python
Order of Operations Worksheets - BEDMAS or PEMDAS
Step 1: First, perform the operations within the brackets or parenthesis.
Step 2: Second, evaluate the exponents.
Step 3: Third, perform multiplication and division from left to right.
Step 4: Fourth, perform addition and subtraction from left to right.
Example: >>>(40+20)*30/10
Output: 180
2.21 Reading Input value from the User
The print() function enables a Python program to display textual information to the user. Python provides built-in
functions to get input from the user. The function is input(). Generally input() function is used to retrieve string values
from the user.
Program 3.6 (sampleinput.py) shows the type of user enter values

Program 3.6 (sampleinput.py) produce result as

We can use the above mentioned functions in python 2.x, but not on python 3.x. input() in python 3.x always return a
string. Moreover, raw_input() has been deleted from python 3
python2.x python3.x
raw_input() -------------- input()
input() ------------------- eval(input())
We can simply say in python 3.x only use of the input () function to read value from the user and it assigns a string to a
variable.
x = input()
The parentheses are empty because, the input function does not require any information to do its job.
Program 3.7 (usinginput.py) demonstrates that the input function produces a string value.

The following shows a sample run of Listing 2.11 (usinginput.py):

The second line shown in the output is entered by the user, and the program prints the first, third, and fourth lines.
After the program prints the message Please enter some text:, the program‘s execution stops and waits for the user to
type some text using the keyboard. The user can type, backspace to make changes, and type some more. The text the
user types is not committed until the user presses the Enter (or return) key. In Python 3.X, input() function produces
only strings, by using conversion functions we can change the type of the input value. Example as int(), str() and
float().
Exercise
1) What is a programming language?
2) Explain different types of programming languages?
3) What is a compiler?
4) What is an interpreter?
5) How is compiled or interpreted code different from source code?
6) Difference between Interpreter and Compiler?
7) What is Python Programming Language?
8) How many ways can run the Python Programming?
9) What is print statement
10) What is prompt
11) Print ―Welcome to Python Programming Language‖ from interactive Python.
12) Write above statement in exercise1.py to print the same text.
13) Run the modified exercise1.py script.
14) Write the below statements in exercise2.py to print the same below
15) What is a variable?
16) What is value? How can you define the type of value?
17) What is assignment statement?
18) What is comment?
19) What is expression?
20) Write a program that uses raw_input to prompt a user for their Name and then welcomes them.
21) Write a program to prompt the user for hours and rate per hour to compute gross pay.
22) Assume that we execute the following assignment statements: width = 17, height = 12.0
For each of the following expressions, write the value of the expression and the type (of the value of the
expression).
(a) width/2
(b) width/2.0
(c) height/3
(d) 4. 1 + 2 * 5
23) Write program and also Use the Python interpreter to check your answers.
24) Write a program which prompts the user for a Celsius temperature, convert the temperature to Fahrenheit, and
print out the converted temperature.
25) Will the following lines of code print the same thing? Explain why or why not.
x=6
print(6)
print("6")
26) What happens if you attempt to use a variable within a program, and that variable has not been assigned a value?
27) What is wrong with the following statement that attempts to assign the value ten to variable x? 10 = x
28) In Python can you assign more than one variable in a single statement?
29) Classify each of the following as either a legal or illegal Python identifier:
a. Flag h. sumtotal
b. if i. While
c. 2x j. x2
d. -4 k. $16
e. sum_total l. _static
f. sum-total m. wilma‘s
g. sum total
30) What can you do if a variable name you would like to use is the same as a reserved word?
31) What is the difference between the following two strings? ‘n‘ and ‘\n‘?
32) Write a Python program containing exactly one print statement that produces the following output

33) Explain type of operators


34) Write a python program to find type of the value of below expressions
 4 > 23
 5+=21
 2**=3
35) Find whether these expressions will evaluate to True or False. Then try them in interactive mode and script
mode
 4>5
 12 != 20
 4 <= 6
 4 => 1
 'sparrow' > 'eagle'
 'dog' > 'Cat' or 45 % 3 == 0
 42+12 < 34//2
 60 - 45 / 5 + 10 == 1 and 32*2 < 12
36) What is compound assignment operator? Explain with examples?
37) Difference between ‗=‘ and ‗==‘
38) Difference between ‗/‘ and ‗//‘
39) Write a python program to prompts the user for x and y operands and find result for all arithmetic operators.
Multiple Choice Questions
1) Python is -------
a) Objected Oriented Programming Language
b) Powerful Programming Language
c) Powerful scripting Language
d) All the above
2) Python is developed by ------------
a) Guido van Rossum. b) Balaguruswami c) James Gosling d) None of the above
3) Which of the following is not a keyword?
a) eval b) assert c) nonlocal d) pass
4) All keywords in Python are in _________
a) lower case b) UPPER CASE c) Capitalized d) None of the mentioned
5) Which of the following is true for variable names in Python?
a) unlimited length
b) all private members must have leading and trailing underscores
c) underscore and ampersand are the only two special characters allowed
d) none of the mentioned
6) Which of the following translates and executes program code line by line rather than the whole program in
one step?
a) Interpreter b) Translator c) Assembler d) Compiler
7) Which of the following languages uses codes such as MOVE, ADD and SUB?
a) assembly language b) Java c) Fortarn d) Machine language
8) What is the output of the following assignment operator?
y = 10
x = y += 2
print(x)
a) 12 b) 10 c) Syntax error
9) What is assignment operator?
a) = = b)= c) += d) - =
10) What is a correct Python expression for checking to see if a number stored in a variable x is between 0 and 5?
a) x>0 and <5 b) x>0 or x<5 c) x>0 and x<5
Descriptive Questions
1) Explain about Applications and Features of Python Programming Language?
2) Write short notes on types of operators in python with appropriate examples?
3) Explain about interpreter and compiler?
4) Explain about identifiers
5) Explain about types of modes
6) Explain briefly about:
 Constant and variables
 keywords and statement
Solved Problems
1) Evaluate the value of z=x+y*z/4%2-1
x=input(―Enter the value of x= ‖)
y=input(―Enter the value of y= ―)
z=input(―Enter the value of z= ―)
a=y*z
b=a/4
c=b%2
t=x+c-1
print(―the value of z=x+y*z/4%2-1 is‖,t)
Input: Enter the value of x=2
Enter the value of y=3
Enter the value of z=4
Output: the value of z=x+y*z/4%2-1 is 2
Note: while solving equations follow the BEDMAS or PADMAS Rule
2) Python program to show bitwise operators
a = 10
b=4
# Print bitwise AND operation
print("a & b =", a & b)
# Print bitwise OR operation
print("a | b =", a | b)
# Print bitwise NOT operation
print("~a =", ~a)
# print bitwise XOR operation
print("a ^ b =", a ^ b)
Output: a&b=0
a | b = 14
~a = -11
a ^ b = 14
Unsolved Problems
1) Write a program to find out the value of 9+3*9/3?
2) Write a program to find out the value of (50-5*6)/4?
3) Write a program to find out the value of 3*3.75/1.5?
4) 45-20+(10?5)%5*3=25 what is the operator in the place of ―?‖ mark?
5) 3*6/22%2+7/2*(3.2-0.7)*2 in this problem which one is evaluated first? finally what is the answer?
6) Write a program to display Arithmetic operations for any two numbers?
7) Python Program to find the average of 3 numbers?
8) Write a python program to find simple and compound interest?
Unit 3 - Data types, I/O, Types of Errors and Conditional Constructs
Module 1 - Data types, I/O, Types of Errors
A data type is a data storage format that can contain a specific type or range of values. Variables can store data of
different types, and different types can do different things. Python has the following data types built-in by default, in
these categories.

Numeric Types: int, float, complex

Sequence Types: str,list, tuple, range

Mapping Type: Dict

Set Types: set, frozenset


3.1.1 Numeric Types
There are three numeric types in Python:
 int
 float
 complex
Variables of numeric types are created when you assign a value to them
Example: x = 1 # int, y = 2.8 # float , z = 1j # complex
Int: Int, or integer, is a whole number, positive or negative, without decimals, of unlimited length.
Example: x = 1, y = 35656222554887711, z = -3255522
Float: Float or "floating point number" is a number, positive or negative, containing one or more decimals.
Example: x = 1.10, y = 1.0, z = -35.59
Float can also be scientific numbers with an "e" to indicate the power of 10.
Example: x = 35e3, y = 12E4, z = -87.7e100
Complex: Complex numbers are written with a "j" as the imaginary part.
Example: x = 3+5j, y = 5j, z = -5j
3.1.2 Sequence Types
In Python, sequence is the generic term for an ordered set. There are several types of sequences in Python; the
following are the most important.
String: Strings in python are surrounded by either single quotation marks, or double quotation marks. 'hello' is the
same as "hello". You can display a string literal with the print() function:
Example: print ("Hello"); print('Hello')
Assign String to a Variable, Assigning a string to a variable is done with the variable name followed by an equal sign
and the string. Example: a = "Hello"; print(a)
Multiline Strings: You can assign a multiline string to a variable by using three quotes, You can use three double
quotes. Example: a = """Lorem ipsum dolor sit amet, consecteturadipiscingelit, sed do
eiusmodemporincididuntutlabore et dolore magna aliqua."""
print(a)
Or three single quotes:
a = '''Lorem ipsum dolor sit amet, consecteturadipiscingelit, sed do eiusmodtemporincididuntutlabore et dolore magna
aliqua.'''
print(a)
However, Python does not have a character data type, a single character is simply a string with a length of 1.
Lists: List is an ordered sequence of items. All the items in a list do not need to be of the same type and lists
are mutable - they can be changed. Elements can be reassigned or removed, and new elements can be inserted.
Declaring a list is pretty straight forward. Items separated by commas are enclosed within brackets [ ].
a = [1, 2.2, 'python']
Tuples: Tuples is an ordered sequences of items same as a list. The only difference is that Tuples are immutable.
Tuples once created cannot be modified. Tuples are used to write-protect data and are usually faster than lists as they
cannot change dynamically. It is defined within parentheses () where items are separated by commas.
t = (5,'program', 1+3j)
range(): The range() type returns an immutable sequence of numbers between the given start integer to the stop
integer. print(list(range(10))
3.1.3 Mapping type
Dictionary is an unordered collection of key-value pairs. In python there is mapping type called dictionary. It is
mutable. In Python, dictionaries are defined within braces {} with each item being a pair in the form key-value. Key
and value can be of any type. The values of the dictionary can be any type, but the key must be of any immutable data
type such as strings, numbers, and Tuples.
>>>d = {1:'value','key':2} >>>type(d)
3.1.4 Set types
Set is an unordered collection of unique items. Set is defined by values separated by comma inside braces { }. Items in
a set are not ordered.
a = {5,2,3,1,4}
print("a = ", a) # printing set variable
print(type(a)) # data type of variable a
We can use the set for some mathematical operations like set union, intersection, difference etc. We can also use set to
remove duplicates from a collection.
3.2. Getting the Data type
We can use the type() function to know which class a variable or a value belongs to. Similarly,
the isinstance() function is used to check if an object belongs to a particular type.
a=5
print(a, "is of type", type(a))
a = 2.0
print(a, "is of type", type(a))
a = 1+2j
print(a, "is complex number?", isinstance(a,complex))
Output
5 is of type <class 'int'>
2.0 is oftype <class 'float'>
(1+2j) is complexnumber? True
3.3. Type Conversion
The process of converting the value of one data type (integer, string, float, etc.) to another data type is called type
conversion. Python has two types of type conversion.
1. Implicit Type Conversion
2. Explicit Type Conversion
3.3.1 Implicit Type Conversion
In Implicit type conversion, Python automatically converts one data type to another data type. This process doesn't
need any user involvement. Let's see an example where Python promotes the conversion of the lower data type
(integer) to the higher data type (float) to avoid data loss.
Example 1: Converting integer to float.

Output

In the above program,


 We add two variables num_int and num_flo, storing the value in num_new.
 We will look at the data type of all three objects respectively.
 In the output, we can see the data type of num_int is an integer while the data type of num_flo is a float.
 Also, we can see the num_new has a float data type because Python always converts smaller data types to larger
data types to avoid the loss of data.
Now, let's try adding a string and an integer, and see how Python deals with it.
Example 2: Addition of string(higher) data type and integer(lower) datatype
num_int = 123
num_str = "456"
print("Data type of num_int:",type(num_int))
print("Data type of num_str:",type(num_str))
print(num_int+num_str)
When we run the above program, the output will be:
Data type of num_int: <class 'int'>
Data type of num_str: <class 'str'>
Traceback (most recent call last):
File "python", line 7, in <module>
TypeError: unsupported operand type(s) for +: 'int' and 'str'
In the above program,
 We add two variables num_int and num_str.
 As we can see from the output, we got TypeError. Python is not able to use Implicit Conversion in such
conditions.
 However, Python has a solution for these types of situations which is known as Explicit Conversion.
3.3.2 Explicit Type Conversion
In Explicit Type Conversion, users convert the data type of an object to required data type. We use the predefined
functions like int(), float(), str(), etc to perform explicit type conversion. This type of conversion is also called
typecasting because the user casts (changes) the data type of the objects.
Syntax: <required_datatype>(expression)
Typecasting can be done by assigning the required data type function to the expression.
Example 3: Addition of string and integer using explicit conversion
num_int = 123
num_str = "456"
print("Data type of num_int:",type(num_int))
print("Data type of num_str before Type Casting:",type(num_str))
num_str = int(num_str)
print("Data type of num_str after Type Casting:",type(num_str))
num_sum = num_int + num_str
print("Sum of num_int and num_str:",num_sum)
print("Data type of the sum:",type(num_sum))
When we run the above program, the output will be:
Data type of num_int: <class 'int'>
Data type of num_str before Type Casting: <class 'str'>
Data type of num_str after Type Casting: <class 'int'>
Sum of num_int and num_str: 579
Data type of the sum: <class 'int'>
In the above program,
 We add num_str and num_int variable.
 We converted num_str from string(higher) to integer(lower) type using int() function to perform the addition.
 After converting num_str to an integer value, Python is able to add these two variables.
 We got the num_sum value and data type to be an integer.
Module 2 - Mutable and Immutable types
A first fundamental distinction that Python makes on data is about whether the value changes are not. If the value can
change, then is called mutable, while if the value cannot change, that is called immutable.
Mutable:
 list,
 dict
 set
Immutable:
 int,
 float,
 complex,
 string,
 tuple
3.5 Input and Output Operations and Formats
Python provides numerous built-in functions that are readily available at the Python prompt.
Some of the functions like input() and print() are widely used for standard input and output operations respectively.
3.5.1 Python Output Using print() function
We use the print() function to output data to the standard output device (screen).
Example 1:
print('This sentence is output to the screen')
Output
This sentence is output to the screen
Example 2:
a=5
print('The value of a is', a)
Output
The value of a is 5
In the second print() statement, we can notice that space was added between the string and the value of variable a. This
is by default, but we can change it.
The actual syntax of the print() function is:
print(*objects, sep=' ', end='\n', file=sys.stdout, flush=False)
 Here, objects are the value(s) to be printed.
 The sep(separator) is used between the values. It defaults into a space character.
 After all values are printed, end is printed. It defaults into a new line.
 The file is the object where the values are printed and its default value is sys.stdout (screen). Here is an example
to illustrate this.
print(1, 2, 3, 4)
print(1, 2, 3, 4, sep='*')
print(1, 2, 3, 4, sep='#', end='&')
Output
1234
1*2*3*4
1#2#3#4&
3.5.2 Output formatting
Sometimes we would like to format our output to make it look attractive. This can be done by using
the str.format() method. This method is visible to any string object.
>>>x = 5; y = 10
>>>print('The value of x is {} and y is {}'.format(x,y))
The value of x is5and y is10
Here, the curly braces {} are used as placeholders. We can specify the order in which they are printed by using
numbers.
print('I love {0} and {1}'.format('bread','butter'))
print('I love {1} and {0}'.format('bread','butter'))
Output
I love bread and butter
I love butter and bread
We can even use keyword arguments to format the string.
>>>print('Hello {name}, {greeting}'.format(greeting = 'Goodmorning', name = 'John'))
Hello John, Goodmorning
We can also format strings like the old sprintf() style used in C programming language. We use the % operator to
accomplish this.
>>>x = 12.3456789
>>>print('The value of x is %3.2f' %x)
The value of x is12.35
>>>print('The value of x is %3.4f' %x)
The value of x is12.3457
3.5.3 Python Input
Until now, our programs were static. The value of variables was defined or hard coded into the source code.
To allow flexibility, we might want to take the input from the user. In Python, we have the input() function to allow
this. The syntax for input() is:
input([prompt])
where prompt is the string we wish to display on the screen. It is optional.
>>>num = input('Enter a number: ')
Enter a number: 10
>>>num
'10'
Here, we can see that the entered value 10 is a string, not a number. To convert this into a number we can
use int() or float() functions.
>>>int('10')
10
>>>float('10')
10.0
3.6 Types of Errors in python
No matter how smart or how careful you are, errors are your constant companion. With practice, you will get slightly
better at not making errors, better at finding and correcting them.There are three kinds of errors: syntax errors, runtime
errors, and logic errors.
3.6.1 Syntax errors: Syntax errors are produced by Python when it is translating the source code into byte code. They
usually indicate that there is something wrong with the syntax of the program.
Example: Omitting the colon at the end of if statement yields the somewhat redundant message.
Syntax Error: invalid syntax.
Here are some ways to avoid the most common syntax errors:
 Make sure you are not using a Python keyword for a variable name.
 Check that you have a colon at the end of the header of every compound statement, including for, while, if,
and def statements.
 Check that indentation is consistent. You may indent with either spaces or tabs but it‘s better not to mix them.
Each level should be nested the same amount.
 Make sure that strings in the code have matching quotation marks.
 If you have multiline strings with triple quotes (single or double), make sure you have terminated the string
properly. An un-terminated string may cause an invalid token error at the end of your program, or it may treat the
following part of the program as a string until it comes to the next string. In the second case, it might not produce
an error message at all!
 An unclosed bracket – (, {, or [ – makes Python continue with the next line as part of the current statement.
Generally, an error occurs almost immediately in the next line.
 Check for the classic = instead of == inside a conditional.
3.6.2 Run Time Error: Errors that occur after the code has been executed and the program is running. The error of
this type will cause your program to behave unexpectedly or even crash. An example of a runtime error is the division
by zero. Consider the following example:
x = float(input('Enter a number: '))
y = float(input('Enter a number: '))
z = x/y
print (x,'dividedby',y,'equals: ',z)
The program above runs fine until the user enters 0 as the second number:
>>>
Enter a number: 9
Enter a number: 2
9.0 divided by 2.0 equals: 4.5
>>>
Enter a number: 11
Enter a number: 3
11.0 divided by 3.0 equals: 3.6666666666666665
>>> Enter a number: 5
Enter a number: 0
Traceback (most recent call last):
File "C:/Python34/Scripts/error1.py", line 3, in <module>
z = x/y
ZeroDivisionError: float division by zero
It is also called semantic errors, logical errors cause the program to behave incorrectly, but they do not usually crash
the program. Unlike a program with syntax errors, a program with logic errors can be run, but it does not operate as
intended. Consider the following example of logical error:
x = float(input('Enter a number: '))
y = float(input('Enter a number: '))
z = x+y/2
print ('The average of the two numbers you have entered is:',z)
The example above should calculate the average of the two numbers the user enters. But, because of the order of
operations in arithmetic (the division is evaluated before addition) the program will not give the right answer:
>>> Enter a number: 3
Enter a number: 4
The average of the two numbers you have entered is: 5.0
>>>
To rectify this problem, we will simply add the parentheses: z = (x+y)/2
Now we will get the right result:
>>>
Enter a number: 3
Enter a number: 4
The average of the two numbers you have entered is: 3.5
>>>
Module 3 - Conditional Constructs
There come situations in real life when we need to make some decisions and based on these decisions, we decide what
we should do next. Similar situations arise in programming also where we need to make some decisions and based on
these decisions we will execute the next block of code.
Decision making statements in programming languages decides the direction of flow of program execution. Decision
making statements available in python are:
 if statement
 if..else statements
 nested if statements
 if-elif ladder
 Short Hand if statement
 Short Hand if-else statement
3.7.1 If statement: if statement is the simplest decision-making statement. It is used to decide whether a certain
statement or block of statements will be executed or not i.e. if a certain condition is true then a block of statement is
executed otherwise not.
Syntax:
if condition:
# Statements to execute if
# condition is true
Here, condition after evaluation will be either true or false. if statement accepts boolean values – if the value is true
then it will execute the block of statements below it otherwise not. We can use condition with bracket ‗(‗ ‗)‘ also.
As we know, python uses indentation to identify a block. So the block under an if statement will be identified as
shown in the below example:
if condition:
statement1
statement2
# Here if the condition is true, if block
# will consider only statement1 to be inside
# its block.
Flowchart:- # python program to illustrate If statement
i = 10
if (i> 15):
print ("10 is less than 15")
print ("I am Not in if")
Output:
I am Not in if
3.7.2 if- else: if statement alone tells us that if a condition is true it will execute a block of statements and if the
condition is false it won‘t. Here comes the else statement. We can use the else statement with if statement to execute a
block of code when the condition is false.
Syntax:
if (condition):
# Executes this block if
# condition is true
else:
# Executes this block if
# condition is false
# Python program to illustrate If else statement
#!/usr/bin/python
i = 20;
if (i< 15):
print ("i is smaller than 15")
print ("i'm in if Block")
else:
print ("i is greater than 15")
print ("i'm in else Block")
print ("i'm not in if and not in else Block")
Output:
i is greater than 15
i'm in else Block
i'm not in if and not in else Block
The block of code following the else statement is executed as the condition present in the if statement is false after call
the statement which is not in block (without spaces).
3.7.3 nested-if: A nested if is if statement that is the target of another if statement. Nested if statements means an if
statement inside another if statement. Yes, Python allows us to nest if statements within if statements. i.e, we can place
an if statement inside another if statement.
Syntax:
if (condition1):
# Executes when condition1 is true
if (condition2):
# Executes when condition2 is true
# if Block is end here
# if Block is end here
# python program to illustrate nested If statement
#!/usr/bin/python
i = 10
if (i<20):
# First if statement
if (i< 15):
print ("i is smaller than 15")
# Nested - if statement
# Will only be executed if statement above
# it is true
else:
print ("i is greater than 15")
if (i< 12):
print ("i is smaller than 12 too")
Output:
I. i is smaller than 15
II. i is smaller than 12 too
3.7.4 if-elif-else ladder: Here, a user can decide among multiple options. The if statements are executed from the top
down. As soon as one of the conditions controlling the if is true, the statement associated with that if is executed, and
the rest of the ladder is bypassed. If none of the conditions is true, then the final else statement will be executed.
Syntax:-
if (condition):
statement
elif (condition):
statement
.
.
else:
statement
Example:-
# Python program to illustrate if-elif-else ladder
#!/usr/bin/python
i = 20
if (i == 10):
print ("i is 10")
elif (i == 15):
print ("i is 15")
elif (i == 20):
print ("i is 20")
else:
print ("i is not present")
Output:
i is 20
3.8 Short Hand if statement
Whenever there is only a single statement to be executed inside if block then shorthand if can be used. The statement
can be put on the same line as if statement.
Syntax:
if condition: statement
Example:
# Python program to illustrate short hand if
i = 10
if i< 15: print("i is less than 15")
Output:
i is less than 15
Short Hand if-else statement: This can be used to write the if-else statements in a single line where there is only one
statement to be executed in both if and else block.
Syntax:
statement_when_True if condition else statement_when_False
Example: # Python program to illustrate short hand if-else
i = 10
print(True) if i< 15 else print(False)
Output:
True
Multiple Choice Questions
1) Which statement is correct?
a) List is immutable && Tuple is mutable
b) List is mutable && Tuple is immutable
c) Both are Mutable.
d) Both are Immutable.
2) Which one of the following is mutable data type?
a) Set b) Int c) Str d) tupl
3) Which one of the following is immutable data type?
a) List b) Set c) Int d) dict
4) Which of these is not a core data type?
a) List b) Tuple c) Dictionary d) Class
5) Which one of the following is False regarding data types in Python?
a) In python, explicit data type conversion is possible
b) Mutable data types are those that can be changed.
c) Immutable data types are those that cannot be changed.
d) None of the above
6) Which of the following function is used to know the data type of a variable in Python?
a) datatype() b) typeof() c) type() d) vartype()
7) Which one of the following is a valid Python if statement :
a) if (a>=2): b) if (a >= 2) c) if (a => 22) d) if a >= 22
8) What keyword would you use to add an alternative condition to an if statement?
a) else if b) elseif c) elif d) None of the above
9) Can we write if/else into one line in python?
a) Yes b) No c) if/else not used in python d) None of the above
10) Which statement will check if a equal to b?
a) if a = b: b) if a == b: c) if a === c: d)if a == b
Solved Problem Set
1) Write a Python program to find whether the given number is divisible by 7 and multiple of 5?
num=int(input("Enter a number: "))
if num%7==0 and num%5==0:
print(num, "is divisible by 7 and multiple of 5")
else:
print("the given number is either divisible by 7 or multiple of 5")
2) Write a program to input any number and check whether it is even or odd
num=int(input("Enter a number: "))
if num%2==0:
print("Even number")
else:
print("Odd number")
3) Write a program to input any number and check whether it is negative, positive or zero
num=int(input("Enter a number: "))
if num>0:
print("Positive number")
else if num<=0:
print("Negative number")
else:
print("Zero")
4) A student will not be allowed to sit in exam if his/her attendance is less than 75%.
Take following input from user:
Number of classes held
Number of classes attended.
And print
percentage of class attended
Is student is allowed to sit in exam or not.
print "Number of classes held"
noh = input()
print "Number of classes attended"
noa = input()
atten = (noa/float(noh))*100
print "Attendence is",atten
ifatten>= 75:
print "You are allowed to sit in exam"
else:
print "Sorry, you are not allowed. Attend more classes from next time."
Un-Solved Problem Set
1) Take values of length and breadth of a rectangle from user and check if it is square or not.
2) Take two int values from user and print greatest among them
3) A shop will give discount of 10%, if the cost of purchased quantity is more than 1000.
Ask user for quantity, suppose, one unit will cost 100.
Ex: quantity=11, cost=11*100=1100>1000, so, he will get 10% discount, that is 110,
Final cost is 1100-110=990
4) A company decided to give bonus of 5% to employee if his/her year of service is more than 5 years.
Ask user for their salary and year of service and print the net bonus amount.
5) A school has following rules for grading system:
a. Below 25 – F d. 50 to 60 - C
b. 25 to 45 – E e. 60 to 80 - B
c. 45 to 50 – D f. Above 80 - A
Ask user to enter marks and print the corresponding grade.
6) Take input of age of 3 people by user and determine oldest and youngest among them.
7) Write a program to print absolute value of a number entered by user.
E.g.- INPUT: 1 OUTPUT: 1, INPUT: -1 OUTPUT: 1
8) Modify the 4th question (in solved problem set) to allow student to sit if he/she has medical cause. Ask user if
he/she has medical cause or not ('Y' or 'N') and print accordingly.
9) Ask user to enter age, sex (M or F ), marital status ( Y or N ) and then using following rules print their place
of service. if employee is female, then she will work only in urban areas.
if employee is a male and age is in between 20 to 40 then he may work in anywhere
if employee is male and age is in between 40 t0 60 then he will work in urban areas only.
And any other input of age should print "ERROR".
Descriptive Questions
1) What is data type? What are the different types of data?
2) What are the numeric data types? Explain with examples.
3) What are the sequence types of data?
4) Explain about type conversions.
5) What is mutable and immutable? What are mutable and immutable data types?
6) Explain about python output formatting.
7) Describe types of errors.
8) Explain about types of conditional constructs.
9) Give examples for all conditional constructs.
10) Write shorthand if and shorthand if-else statement.
Unit 4 - Loops/iterative statements
Module 1 – While Loop
Introduction
Looping is a powerful programming technique through which a group of statements is executed repeatedly, until
certain specified condition is satisfied. Looping is also called repetitive or iterative control statements.
A loop in a program essentially consists of two parts, one is called the body of the loop and other is known as a control
statement. The control statement performs a logical test whose result is either True or False. If the result of this
logical test is true, then the statements contained in the body of the loop are executed. Otherwise, the loop is
terminated.
There must be a proper logical test condition in the control statement, so that the statements are executed repeatedly
and the loop terminates gracefully. If the logical test condition is carelessly designed, then there may be possibility of
formation of an infinite loop which keeps executing the statements over and over again.
4.1 while loop
This is used to execute a set of statements repeatedly as long as the specified condition is true. It is an indefinite loop.
In the while loop, the condition is tested before executing body of the statements. If the condition is True, only body
of the block of statements will be executed otherwise if the condition is False, the control will jump to other
statements which are outside of the while loop block.
Syntax:
while(logexp):
block of Statements
Where,
while  is a keyword
logexp is a logical expression that results in either True or Fasle
Statement may be simple or a compound statement
Here, first of all the logical expressions is evaluated and if the result is true (non-zero) then the statement is repeatedly
executed. If the result is false (zero), then control comes out of the loop and continues with the next executable
statements.
Flowchart:

In while loop there are mainly it contains three parts, which are as follows
 Initialization: to set the initial value for the loop counter. The loop counter may be an increment counter or a
decrement counter
 Decision: an appropriate test condition to determine whether the loop be executed or not
 Updation: incrementing or decrementing the counter value.
Example Programs:
Q1. Write a program to display your name up to „n‟ times

When you run the following program, then output will be display like

Q2. Write a program to display natural numbers up to n


Output:

Q3.Write a program to display even numbers up to n

Output:

4.1.1 The infinite while loop: A loop becomes infinite loop if a condition never becomes FALSE. You must use
caution when using while loops because of the possibility that this condition never resolves to a FALSE value. This
results in a loop that never ends. Such a loop is called an infinite loop.
An infinite loop might be useful in client/server programming where the server needs to run continuously so that client
programs can communicate with it as and when required.
Program to demonstrate infinite loop:

Above two programs that never stop, that executes until your Keyboard Interrupts (ctrl+c). Otherwise, it would have
gone on unendingly. Many ‗Hi‘ output lines will display when you executes above two programs and that never
display ‗Good bye‘
4.1.2 While loop with else clause/statement: Python allows an optional else clause at the end of a while loop. This is
a unique feature of Python. If the else statement is used with a while loop, the else statement is executed when the
condition becomes false. But, the while loop can be terminated with a break statement. In such cases, the else part is
ignored. Hence, a while loop's else part runs if no break occurs and the condition is False
Syntax:

Example Program:
Q1. Write a program to demonstrate while loop with else block.

Output:

Q2. Write a program to demonstrate else block with break statement

Output:
Module 2 – For Loop
4.2 for loop
Like the while loop, for loop works, to repeat statements until certain condition is True. The for loop in python is used
to iterate over a sequence (list, tuple, string and range() function) or other iterable types. Iterating over a s sequence is
called traversal. Here, by sequence we mean just an ordered collection of items. for loop is usually known as definite
loop because the programmer knows exactly how many times the loop will repeat.
Syntax:
for counter_variable in sequence:
block of statements
Here counter_variable is the variable name that takes the value of the item inside the sequence on each iteration. Loop
continues until we reach the last item in the sequence. The body of for the loop is separated from the rest of the code
using indentation.
Example programs:
Q7. Write a program to make sum of all numbers stored in a list.

When you run the program, Output will be:

4.2.1 The range() function:


The range() function is a built-in function in python that is used to iterate over a sequence of numbers. The range()
function contains three arguments/parameters like
range(start, end, step)
The range() generates a sequence of numbers starting with start(inclusive) and ending with one less than the number
‗end‘. The step argument is optional
By default, every number in the range is incremented by 1. Step can be either a positive or negative value but it cannot
be equal to zero
Example Program:
Q8. Write a program to print first n natural numbers using a for loop

For both programs, output will be the same

Q9. If you want to display including the given input number you can write a program like

Output:

4.2.2 for loop with else:


A for loop can have an optional else block. The else part is executed when the loop has exhausted iterating the list.
But, when the break statement use in for loop, the else part is ignored.
Hence, a for loop's else part runs if no break occurs.
Example:
Q. Program to demonstrate else block in for loop

Output:

Here, the for loop prints numbers from the starting number to less than ending number. When the for loop exhausts, it
executes the block of code in the else and prints No items left.
Q. Program to demonstrate else block in for loop with break statement:

Output:

4.3 Nested loops


Python programming language allows using one loop inside another loop which is called a nested loop. Although this
feature will work for both while loop as well as for loop. The syntax for a nested while loop statement in Python
programming language is as follows
Syntax:

Note:
You can put any type of loop inside of any other type of loop. For example, a for loop can be inside a while loop or
vice versa.
Example Program: Program to demonstrate nested for loop Nested while loop:

Output:
If you run above two programs output will be the same

Module 3 - Control Statements


4.4 Control statements
Loops iterate over a block of code until the test expression is false, but sometimes we wish to terminate the current
iteration or even the whole loop without checking test expression. These can be done by loop control statements. Loop
control statements change execution from its normal sequence.
There are three different kinds of control statements which are as follows
1. break
2. continue
3. pass
4.4.1Break Statement: The break statement in Python terminates the current loop and resumes execution at the next
statement (out of the loop).
This break statement is used in both for and while loops.
Syntax:
break
Flowchart
Example Programs:
Write a program to demonstrate break statement by using for loop and while loop
for loop

while loop

Output:

4.4.2Continue Statement: The continue statement is used to skip the rest of the code inside a loop for the current
iteration only. Loop does not terminate but continues on with the next iteration. Continue statement is opposite to
break statement, instead of terminating the loop; it forces to execute the next iteration of the loop.
Syntax:
continue
Flowchart:

Example Programs:
Write a program to demonstrate continue statement by using for loop

Output:
In output, 5 integer value is skipped based on if condition and continues flow of the loop until the condition satisfied.
4.4.3 Pass Statement: The pass statement in Python is used when a statement is required syntactically but you do not
want any command or code to execute. It is a null statement. However, nothing happens when the pass statement is
executed. It results in no operation (NOP). Pass statement can also be used for writing empty loops, functions and
classes.
Syntax:
pass
Example Program:
Program to demonstrate pass statement using for loop

Output:
Solved Questions
1. Write a program to display your name up to n times.
Using while loop

Using for loop

Output:

2. Write a program to display sum of odd numbers up to n


#Using while loop
n=int(input("Enter n Value:"))
i=1
s=0
while(i<=n):
if(i%2!=0):
s=s+1
i=i+1
print("Sum of Odd Values", s)
#Using for loop
n=int(input("Enter n Value:"))
s=0
for i in range(1,n+1):
if(i%2!=0):
s=s+1
print("Sum of Odd Values", s)
3. Write a program to display numbers of factors to the given number
# Using while loop
n=int(input("Enter n Value:"))
i=1
c=0
while(i<=n):
if(n%i==0):
c=c+1
i=i+1
print("count of factors is ", c)
# Using for loop
n=int(input("Enter n Value:"))
c=0
for i in range(1,n+1):
if(n%i==0):
c=c+1
print("count of factors is ", c)
4. Write a program to find given number is prime number or not
n=int(input("Enter n Value:"))
c=0
for i in range(1,n+1):
if(n%i==0):
c=c+1
if(c==2):
print("given number is prime number")
else:
print("given number is not prime number")
Descriptive Questions:
1) Explain about while loop and for loop?
2) Explain about loop control statements?
3) Explain about range function with different arguments?
Unsolved Questions:
1) Write a program to print all-natural numbers in reverse (from n to 1).
2) Write a program to print all even numbers up to n
3) Write a program to print sum of all odd numbers between two intravel given.
4) Write a program to print table of any number.
5) Write a program to enter any number and calculate sum of its digits.
6) Write a program to print all Prime numbers between 1 to n
7) Write a program to enter any number and display perfect numbers between 1 to n
8) Write a program to enter any number and find its first and last digit.
9) Write a program to display given number is a number palindrome or not
10) Write a program to print all alphabets from a to z.
11) Write a program to enter any number and check whether it is Armstrong number or not.
12) Write a program to print all Strong numbers between 1 to n.
13) Write a program to print Fibonacci series up to n terms.
14) Star pattern programs - Write a program to print the given star patterns.

15) Write a Python program to construct the following patterns, using a nested loop number
1 P
23 PY
456 PYT
7 8 9 10 PYTH
11 12 13 14 15 PYTHO
PYTHON
Multiple Choice Questions:
1) A while loop in Python is used for what type of iteration?
a) Indefinite b) Discriminate c) Definite d) Indeterminate
2) When does the else statement written after loop executes?
a) When break statement is executed in the loop
b) When loop condition becomes false
c) Else statement is always executed
d) None of the above
3) What do we put at the last of for/while loop?
a) Semicolon b) Colon c) Comma d) None of the above
4) Which of the following loop is work on the particular range in python?
a) For loop b) While loop c) Do-while loop d) Recursion
5) How many times it will print the statement?, for i in range(100): print(i)
a) 101 b) 99 c) 100 d) 0
6) What is the result of executing the following code?

a) The program will loop indefinitely


b) The value of number will be printed exactly 1 time
c) The while loop will never get executed
d) The value of number will be printed exactly 5 times
7) Which of the following sequences would be generated by given line of the code?
a) 5 4 3 2 1 0 -1 b) 5 4 3 2 1 0 c)5 3 1 d) Error
8) Which of the following is a valid for loop in Python?
a) for (i=0;i<=n; i++) b) for i in range(5) c) for i in range (1, 5): d) for i in range(0,5,1)
9) Which statement is used to terminate the execution of the nearest enclosing loop in which it appears?
a) pass b) break c) continue d) jump
10) Which statement indicates a NOP?
a) Pass b) break c) continue d) jump
Unit 5 – Strings
Module 1
5.1 Definition
In python, consecutive sequence of characters is known as a string. Strings are immutable and amongst the most
popular types in Python. In python, String literals are surrounded by single or double or triple quotation marks.
‗RGUKT‘ is same as ―RGUKT‖
5.1.1 Declaring & Initializing StringVariables
Assigning a string to a variable is done with the variable name followed by an equal sign and the string
>>> s1 = ―This is a stringone‖
>>> s2 = ―This is a string two‖
>>>s3=‖ ― #emptystring
>>>type(s1)<class'str'>
 Multi-line strings can be denoted using triple single or double quotes, ''' or""".
 Even triple quotes can be used in Python but generally used to represent multiline strings ordocstrings.
>>> s4 = ‗‘‘amultiline String‘‘‘

5.1.2 How to access characters in String


 We can access individual characters using indexing and a range of characters using slicingoperator [ ]or
TheSubscriptOperator
 Index starts from 0. Trying to access a character out of index range will raise an Index Error.
 The index must be an integer. We can't use float or other types;this will result into Type Error.
 Python allows negative indexing for itssequences.
 The index of -1 refers to the last item, -2 to the second last item and soon.
 We can access a range of items in a string by using the slicing operator withcolon[ :].
S=‖hello‖

Important points about accessing elements in the strings using index


 Positive index helps in accessing the string from the beginning
 Negative index helps in accessing the string from the end.
 Index 0 or –ve n(where n is length of the string) displays the first element.
Example:A[0] or A[-5] will display ―H‖
 Index -1 or (n-1) displays the last element.
Example: A[-1] or A[4] will display ―O‖
Note: Python does not support character data type. A string of size 1 can be treated as characters.
If we try to access index out of the range or use decimal number, we will get errors.
Accessing sub strings/Slicing Operator:
To access substrings, use the square brackets for slicing, using slice operator, along with the index or indices to obtain
your substring.
Syntax:
stringname[start:end:step]
start – starting point of the index value (default value: 0)
end or stop – ending point of the index value (default value: len(stringname))
step- increment of the index values (default value: 1)
Examples:
5.1.3 How to change or delete a string?
Strings are immutable
Strings are immutable means that the contents of the string cannot be changed after it is created.
Let us understand the concept of immutability with help of an example.We can simply reassign different strings to the
samename.

We cannot delete or remove characters from string,deleting the string is possible use the keyword del.

5.2. Python String Operations


There are many operations that can be performed with string which makes it one of the most used data types in python

Comparing Strings: Python allows you to compare strings using relational (or comparison) operator such as
 = =,! =, >, <, < =, >=,etc.
 == if two strings are equal, it returns True
 != or <> if two strings are not equal, it returns True
 if first string is greater than the second, it returns True
 < if second string is greater than the first ,it returns True
 >= if first string is greater than or equal to the second, it returns True
 <= if second string is greater than or equal to the first, it returns True
Note:
 These operators compare the strings by using the lexicographical order i.e using ASCII values of the
characters.
 The ASCII values of A-Z is 65 -90 and ASCII code for a-z is 97-122 .
Logical Operators on String in Python: Python considers empty strings as having boolean value of ‗false‘ and non-
empty string as having boolean value of ‗true‘.
Let us consider the two strings namely str1 and str2 and try boolean operators on them:
Output:

5.3 Escape sequence characters


 To insert characters that are illegal in a string, use an escape character.
 Escape sequence characters or non-printable characters that can be represented with backslash notation.
 An escape character gets interpreted; in a single quoted as well as double quoted strings
An example of an illegal character is a double quote inside a string that is surrounded by double quotes
Example
You will get an error if you use double quotes inside a string that is surrounded by double quotes:
txt = "We are the so-called "Vikings" from the north."
#You will get an error if you use double quotes inside a string that are surrounded by double quotes:

To fix this problem, use the escape character \":


Example
The escape character allows you to use double quotes when you normally would not be allowed:
txt = "We are the so-called \"Vikings\" from the north."
print(txt)

Other escape characters used in Python


Escape Description Example Result
Character
\' Single Quote txt = 'It\'s alright.' It's alright.
print(txt)
\\ Backslash txt = "This will insert one \\ (backslash)." This will insert one \
print(txt) (backslash).
\n New Line txt = "Hello\nWorld!" Hello
print(txt) World!
\r Carriage txt = "Hello\rWorld!" Hello
Return print(txt) World!
\t Tab txt = "Hello\tWorld!" Hello World!
print(txt)
\b Backspace #This example erases one character HelloWorld!
(backspace):
txt = "Hello \bWorld!"
print(txt)
\ooo Octal value #A backslash followed by three integers will Hello
result in a octal value:
txt = "\110\145\154\154\157"
print(txt)
\xhh Hex value #A backslash followed by an 'x' and a hex Hello
number represents a hex value:
txt = "\x48\x65\x6c\x6c\x6f"
print(txt)
Module – 2
5.4 Iterating through String/Traversing a string
Traversing a string means accessing all the elements of the string one after the other by using the subscript. A string
can be traversed using: for loop or while loop.
Example:

Example:

Example:

Example:
Python program to print reverse string using for loop

5.5 The format() Method for Formatting Strings


 The format() method that is available with the string object is very versatile and powerful in formatting
strings.
 Format strings contains curly braces {} as placeholders or replacement fields which gets replaced.
 We can use positional arguments or keyword arguments to specify the order.

5.6 Built-in functions to Work with Python Strings


 Various built-in functions that work with sequence, works with string as well.
 The enumerate() function returns an enumerate object. It contains the index and value of all the items in the
string as pairs. This can be useful for iteration.
 The len() function returns the length (number of characters) of the string.
 The method center() makes str centered by taking width parameter into account. Padding is specified by
parameter fillchar. Default filler is a space.
Syntax: str.center(width[, fillchar])

 The functionmax() returns the max character from string str according to ASCII value.in first print statement
y is max character, because ASCII code of "y" is 121. In second print statement "s" is max character, ASCII
code of "s" is 115.
Syntax:- max(str)
 The functionmin() returns the min character from string str according to ASCII value.
Syntax :- min(str)

 The ord() function returns ASCII code of the character.

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

Module – 3
5.7 String Methods
 count():The method count() returns the number of occurrence of Python string substr in string str. By using
parameter start and end you can give slice of str.This function takes 3 arguments, substring, beginning
position (by default 0) and end position (by default string length).Return Int Value
Syntax: str.count(substr [, start [, end]])

 endswith(“string”, beg, end): This function returns true if the string ends with mentioned string(suffix) else
return false.Return Bool Value
The use of start and end to generate slice of Python string str.
Syntax: str.endswith(suffix[, start[, end]])

 startswith(“string”, beg, end):This function returns true if the string begins with mentioned string(prefix)
else return false.

 find(“string”, beg, end):This function is used to find the position of the substring within a string. It takes 3
arguments, substring , starting index(by default 0) and ending index(by default string length).
o It returns ―-1‖ if string is not found in given range.
o It returns first occurrence of string if found.
Return the lowest index in S where substring sub is found
If given Python string is found, then the find() method returns its index. If Python string is not found then -1 would be
returned.
Syntax : str.find(str, beg=0 end=len(string))

 rfind(“string”, beg, end): This function is similar to find(), but it returns the position of the last occurrence of
sub string.

 replace(): This function is used to replace the substring with a new substring in the string. This function has 3
arguments. The string to replace, new string which would replace and max value denoting the limit to replace
action (by default unlimited).

 The method isalnum() is used to determine whether the Python string consists of alphanumeric characters,
false otherwise
Syntax :-str.isalnum()
 The method isalpha() return true if the Python string contains only alphabetic character(s), false otherwise.
Syntax :- str.isalpha()
 The method isdigit() return true if the Python string contains only digit(s),false otherwise.
Syntax :-str.isdigit()
 The method islower() return true if the Python string contains only lower cased character(s), false otherwise
Syntax :- str.isdigit()

 The method isspace() return true if the Python string contains only white space(s).
Syntax :- str.isspace()
 The method istitle() return true if the string is a titlecased
Syntax :- str.istitle()
 The method isupper() return true if the string ontains only upper cased character(s), false otherwise.
Sytax:-str.isupper()
 The method ljust(), it returns the string left justified. Total length of string is defined in first parameter of
method width. Padding is done as defined in second parameter fillchar .( default is space)
Syntax : -str.ljust(width[, fillchar])

 In above example you can see that if you don't define the fillchar then the method ljust() automatically take
space as fillchar.
 The method rjust(), it returns the string right justified. Total length of string is defined in first parameter of
methodwidth. Padding is done as defined in second parameter fillchar .( default is space)
Syntax:-str.rjust(width[, fillchar])
 This function capitalize() first letter of string.
Syntax:-str.capitalize()
 The method lower() returns a copy of the string in which all case-based characters have been converted to
lower case.
Syntax:-str.lower()
 The method upper() returns a copy of the string in which all case-based characters have been converted to
upper case.
Syntax:-str.upper()
 The method title() returns a copy of the string in which first character of all words of string are capitalised.
Syntax:-str.title()
 The method swapcase() returns a copy of the string in which all cased based character swap their case
Syntax:-str.swapcase()

 This method join() returns a string which is the concatenation of given sequence and stringas shown in
example.
seq = it contains the sequence of separated strings.
str = it is the string which is used to replace the separator of sequence
Syntax:-str.join(seq)
 The method lstrip() returns a copy of the string in which specified char(s) have been stripped from left side
of string. If char is not specified then space is taken as default.
Syntax : - str.lstrip([chars])
 The method rstrip() returns a copy of the string in which specified char(s) have been stripped from right side
of string. If char is not specified then space is taken as default.
Syntax : - str.rstrip([chars])
 The method strip() returns a copy of the string in which specified char(s) have been stripped from both side
of string. If char is not specified then space is taken as default.
Syntax : - str.strip([chars])
 The method split() returns a list of all words in the string, delimiter separates the words. If delimiter is not
specified then whitespace is taken as delimiter, parameter num
Syntax :- str.split("delimiter", num)
Multiple Choice Questions
1) What will be the output of above Python code?
a) 1 b) 6/4 c) 1.5 d) str1
2) Which of the following is False?
a) String is immutable.
b) capitalize() function in string is used to return a string by converting the whole given string into
uppercase.
c) lower() function in string is used to return a string by converting the whole given string into
lowercase.
d) None of these
3) What will be the output of below Python code?
a) format B. formation C. orma D. ormat
4) What will be the output of below Python code?
a) Application b) Application c) ApplicAtion d) Application

5) What will be the output of below Python code?


a) POWER b) Power c) power d) power
6) What will the below Python code will return?

a) 70251 b) 7 c) 15 d) Error
7) Which of the following will give "Simon" as output?

a) print(str1[-7:-12]) b) print(str1[-11:-7]) c) print(str1[-11:-6]) d) print(str1[-7:-11])


8) What will return following Python code?
a) 13 B. 14 C.15 D. 16
Solved Problems
1. Write a program to print Alphabet using ASCII Numbers ?
Solutions:-

2. Write a Python program to calculate the length of a string.


Solutions:-

3. Write a Python program to get a string made of the first 2 and the last 2 chars from a given a string. If
the string length is less than 2, return instead of the empty string.
Solutions:-

Unsolved Problems
1. Write a program to find number of digits ,alphabets and symbols ?
2. Write a program to convert lower case to upper case from given string?
3. Write a program to print the following output? image like
4. Write a program to check whether given string is palindrome or not?
5. Write a program to find no_ words, no_letters, no_digits and no_blanks in a line?
6. Write a program to sort list names in alphabetical order?
7. To find the first character from given string,count the number of times repeated
and replaced with * except first character then print final string?
8. To find the strings in a list which are matched with first character equals to last character in a string?
9. Write a program that accepts a string from user and redisplays the same string after removing vowels from it?
10. This is a Python Program to take in two strings and display the larger string without using built-in functions?
11. Python Program to Read a List of Words and Return the Length of the Longest One?
12. Python Program to Calculate the Number of Upper-Case Letters and Lower-Case Letters in a String?
Unit 6 - List, Tuples and Dictionary
Module 1 - List
6.1 Definition
Python offers a range of compound data types often referred to as sequences. List is one of the most frequently used
and very versatile data types used in Python. Like a string, a list is a sequence of values. In a string, the values are
characters; in a list, they can be any type. The values in list are called elements or sometimes items.
There are several ways to create a new list; the simplest is to enclose the elements in square brackets and are separated
by commas. It can have any number of items and they may be of different types (integer, float, string etc.).
[10, 20, 30, 40]
['crunchy frog', 'ram bladder', 'lark vomit']
The first example is a list of four integers. The second is a list of three strings. The elements of a list don‘t have to be
the same type. The following list contains a string, a float, an integer, and another list:
['spam', 2.0, 5, [10, 20]]
A list can also have another list as an item. This is called a nested list. It can have any number of items and they may
be of different types (integer, float, string etc.).
6.2 How to create a list?
In Python programming, a list is created by placing all the items (elements) inside square brackets [], separated by
commas.
# empty list
my_list = []
# list of integers
my_list = [1, 2, 3]
# list with mixed data types
my_list = [1, "Hello", 3.4]
6.3 How to access elements from a list?
There are various ways in which we can access the elements of a list.
6.3.1 List Index: We can use the index operator [] to access an item in a list. In Python, indices start at 0. So, a list
having 5 elements will have an index from 0 to 4. Trying to access indexes other than these will raise an IndexError.
The index must be an integer. We can't use float or other types, this will result in TypeError.
 Nested lists are accessed using nested indexing.
6.3.2 Negative indexing
Python allows negative indexing for its sequences. The index of -1 refers to the last item, -2 to the second last item
and so on.

When we run the above program, we will get the following output:
e
p
6.4 Change or add elements to a list
p
The syntax for accessing the elements of a list is the same as for accessing the characters of a string the bracket
operator. The expression inside the brackets specifies the index. Remember that the indices start at 0:
Unlike strings, lists are mutable because you can change the order of items in a list or reassign an item in a list. When
the bracket operator appears on the left side of an assignment, it identifies the element of the list that will be assigned.
>>> numbers = [17, 123]
>>>numbers[1] = 5
>>> print numbers
[17, 5]
The one-eth element of numbers, which used to be 123, is now 5.
You can think of a list as a relationship between indices and elements. This relationship is called a mapping; each
index ―maps to‖ one of the elements.
List indices work the same way as string indices:
6.5 Traversing a list
The most common way to traverse the elements of a list is with a for loop. The syntax is the same as for strings:
cheeses = ['Cheddar', 'Edam', 'Gouda']
for cheese in cheeses:
print (cheese)
This works well if you only need to read the elements of the list. But if you want to write or update the elements, you
need the indices. A common way to do that is to combine the functions range and len:
numbers = [17, 123]
for i in range(len(numbers)):
numbers[i] = numbers[i] * 2
This loop traverses the list and updates each element.len returns the number of elements in the list. range returns a list
of indices from 0 to n−1, where n is the length of the list. Each time through the loop, i gets the index of the next
element. The assignment statement in the body uses i to read the old value of the element and to assign the new value.
A for loop over an empty list never executes the body:
for x in empty:
print ('This never happens.')
Although a list can contain another list, the nested list still counts as a single element. The length of this list is four:
['spam', 1, ['Brie', 'Roquefort', 'Pol le Veq'], [1, 2, 3]]
6.6 List operations
The + operator concatenates lists:
>>> a = [1, 2, 3]
>>> b = [4, 5, 6]
>>> c = a + b
>>> print (c)
[1, 2, 3, 4, 5, 6]
Similarly, the * operator repeats a list a given number of times:
>>> [0] * 4
[0, 0, 0, 0]
>>> [1, 2, 3] * 3
[1, 2, 3, 1, 2, 3, 1, 2, 3]
The first example repeats [0] four times. The second example repeats the list [1, 2, 3] three times.
List slices: The slice operator also works on lists
>>> t = ['a', 'b', 'c', 'd', 'e', 'f']
>>>t[1:3]
['b', 'c']
>>>t[:4]
['a', 'b', 'c', 'd']
>>>t[3:]
['d', 'e', 'f']
If you omit the first index, the slice starts at the beginning. If you omit the second, the slice goes to the end. So if you
omit both, the slice is a copy of the whole list.
>>>t[:]
['a', 'b', 'c', 'd', 'e', 'f']
Since lists are mutable, it is often useful to make a copy before performing operations that fold, spindle, or mutilate
lists.
A slice operator on the left side of an assignment can update multiple elements:
>>> t = ['a', 'b', 'c', 'd', 'e', 'f']
>>>t[1:3] = ['x', 'y']
>>> print (t)
['a', 'x', 'y', 'd', 'e', 'f']
Syntax: List[start:end:step]
start –starting point of the index value end
stop –ending point of the index value
step- increment of the index values
>>> t = ['a', 'b', 'c', 'd', 'e', 'f']
>>>t[1:3:1]
['b', 'c']
6.7 List methods
Adding Elements into a list
6.7.1 list.append()
Python provides methods that operate on lists. For example, append adds a new element to the end of a list
>>> t = ['a', 'b', 'c']
>>>t.append('d')
>>> print (t)
['a', 'b', 'c', 'd']
6.7.2 list.extend()
extend takes a list as an argument and appends all of the elements
>>> t1 = ['a', 'b', 'c']
>>> t2 = ['d', 'e']
>>> t1.extend(t2)
>>> print (t1)
['a', 'b', 'c', 'd', 'e']
This example leaves t2 unmodified.
sort arranges the elements of the list from low to high:
>>> t = ['d', 'c', 'e', 'b', 'a']
>>>t.sort()
>>> print(t)
['a', 'b', 'c', 'd', 'e']
6.7.3 list.insert(i, x)
Insert an item at a given position. The first argument is the index of the element before which to insert,
so a.insert(0, x) inserts at the front of the list, and a.insert(len(a), x) is equivalent to a.append(x).
Example 1: Inserting an Element to the List
# vowel list
vowel = ['a', 'e', 'i', 'u']
# 'o' is inserted at index 3
# the position of 'o' will be 4th
vowel.insert(3, 'o')
print('Updated List:', vowel)
Deleting elements
6.7.4 list.remove(x)
Remove the first item from the list whose value is equal to x. It raises a ValueError if there is no such item.
6.7.5 list.clear()
Remove all items from the list. Equivalent to del a[:].
Example 1: Working of clear() method
# Defining a list
list = [{1, 2}, ('a'), ['1.1', '2.2']]
# clearing the list
list.clear()
print('List:', list)
6.7.6 list.pop([i])
Remove the item at the given position in the list, and return it. If no index is specified, a.pop() removes and returns the
last item in the list. (The square brackets around the I in the method signature denote that the parameter is optional, not
that you should type square brackets at that position. You will see this notation frequently in the Python Library
Reference.)
>>> t = [„a‟, „b‟, „c‟]
>>> x = t.pop(1)
>>> print (t)
[„a‟, „c‟]
>>> print (x)
b
If you don‘t need the removed value, you can use the del operator:
>>> t = [„a‟, „b‟, „c‟]
>>> del t[1]
>>> print (t)
[„a‟, „c‟]
If you know the element you want to remove (but not the index), you can use remove:
>>> t = [„a‟, „b‟, „c‟]
>>>t.remove(„b‟)
>>> print (t)
[„a‟, „c‟]
The return value from remove is None.
To remove more than one element, you can use del with a slice index:
>>> t = [„a‟, „b‟, „c‟, „d‟, „e‟, „f‟]
>>> del t[1:5]
>>> print (t)
[„a‟, „f‟]
As usual, the slice selects all the elements up to, but not including, the second index.
6.7.6 list.index(x[, start[, end]])
Return zero-based index in the list of the first item whose value is equal to x. Raises a ValueError if there is no such
item.
The optional arguments start and end are interpreted as in the slice notation and are used to limit the search to a
particular subsequence of the list. The returned index is computed relative to the beginning of the full sequence rather
than the start argument.
Example:
# vowels list
vowels = ['a', 'e', 'i', 'o', 'i', 'u']
# index of 'e' in vowels
index = vowels.index('e')
print('The index of e:', index)
# element 'i' is searched
# index of the first 'i' is returned
index = vowels.index('i')
print('The index of i:', index)
Example: Working of index() With Start and End Parameters
# alphabets list
alphabets = ['a', 'e', 'i', 'o', 'g', 'l', 'i', 'u']
# index of 'i' in alphabets
index = alphabets.index('e') # 2
print('The index of e:', index)
# 'i' after the 4th index is searched
index = alphabets.index('i', 4) # 6
print('The index of i:', index)
# 'i' between 3rd and 5th index is searched
index = alphabets.index('i', 3, 5) # Error!
print('The index of i:', index)
6.7.7 list.count(x)
Return the number of times x appears in the list.
Example:
# vowels list
vowels = ['a', 'e', 'i', 'o', 'i', 'u']
# count element 'i'
count = vowels.count('i')
# print count
print('The count of i is:', count)
# count element 'p'
count = vowels.count('p')
# print count
print('The count of p is:', count)
6.7.8 list.sort(key=None, reverse=False)
Sort the items of the list in place (the arguments can be used for sort customization, see sorted() for their explanation).
Most list methods are void; they modify the list and return None. If you accidentally write list= list.sort(), you will be
disappointed with the result.
Example : Sort a given list
# vowels list
vowels = ['e', 'a', 'u', 'o', 'i']
# sort the vowels
vowels.sort()
# print vowels
print('Sorted list:', vowels)
Example : Sort the list in Descending order
# vowels list
vowels = ['e', 'a', 'u', 'o', 'i']
# sort the vowels
vowels.sort(reverse=True)
# print vowels
print('Sorted list (in Descending):', vowels)
6.7.9 list.reverse()
Reverse the elements of the list in place.
# Operating System List
systems = ['Windows', 'macOS', 'Linux']
print('Original List:', systems)
# List Reverse
systems.reverse()
# updated list
print('Updated List:', systems)
6.7.10 list.copy()
Return a shallow copy of the list. Equivalent to a[:]
# mixed list
my_list = ['cat', 0, 6.7]
# copying a list
new_list = my_list.copy()
print('Copied List:', new_list)
6.8 List Comprehension
List comprehension is an elegant and concise way to create a new list from an existing list in Python. A list
comprehension consists of an expression followed by for statement inside square brackets. Here is an example to
make a list with each item being increasing power of 2.
List Membership Test:
We can test if an item exists in a list or not, using the keyword in.

6.9 Built-in functions


There are a number of built-in functions that can be used on lists that allow you toquickly look through a list without
writing your own loops:
>>>nums = [3, 41, 12, 9, 74, 15]
>>> print len(nums)
6
>>> print max(nums)
74
>>> print min(nums)
3
>>> print sum(nums)
154
>>> print sum(nums)/len(nums)
25
The sum() function only works when the list elements are numbers. The other functions (max(), len(), etc.) work with
lists of strings and other types that can be comparable.
Example:
`

Output:
Example:2

Output: 1

Output: 2

Example:3

Output:

Module 2 – Tuples
We saw that lists and strings have many common properties, such as indexing and slicing operations. They are two
examples of sequence data types (Sequence Types — list, tuple, range). Since Python is an evolving language, other
sequence data types may be added. There is also another standard sequence data type: the tuple.
A tuple consists of a number of values separated by commas, for instance:

As you see, on output tuples are always enclosed in parentheses, so that nested tuples are interpreted correctly; they
may be input with or without surrounding parentheses, although often parentheses are necessary anyway (if the tuple
is part of a larger expression). It is not possible to assign to the individual items of a tuple, however it is possible to
create tuples which contain mutable objects, such as lists.
Though tuples may seem similar to lists, they are often used in different situations and for different purposes. Tuples
are immutable, and usually contain a heterogeneous sequence of elements that are accessed via unpacking or indexing
(or even by attribute in the case of namedtuples). Lists are mutable, and their elements are usually homogeneous and
are accessed by iterating over the list.
A special problem is the construction of tuples containing 0 or 1 items: the syntax has some extra quirks to
accommodate these. Empty tuples are constructed by an empty pair of parentheses; a tuple with one item is
constructed by following a value with a comma. For example:

A tuple can also be created without using parentheses. This is known as tuple packing.

6.10 Access Tuple Elements


There are various ways in which we can access the elements of a tuple.
Indexing:
We can use the index operator [] to access an item in a tuple, where the index starts from 0. So, a tuple having 6
elements will have indices from 0 to 5. Trying to access an index outside of the tuple index range (6,7,... in this
example) will raise an IndexError.
The index must be an integer, so we cannot use float or other types. This will result in TypeError.
Likewise, nested tuples are accessed using nested indexing, as shown in the example below.

Negative Indexing:
Python allows negative indexing for its sequences.
The index of -1 refers to the last item, -2 to the second last item and so on.
Slicing:
We can access a range of items in a tuple by using the slicing operator colon:.

Slicing can be best visualized by considering the index to be between the elements as shown below. So if we want to
access a range, we need the index that will slice the portion from the tuple.

6.11 Changing a Tuple


Unlike lists, tuples are immutable. This means that elements of a tuple cannot be changed once they have been
assigned. But, if the element is itself a mutable data type like list, its nested items can be changed.
We can also assign a tuple to different values (reassignment).

Deleting a Tuple
As discussed above, we cannot change the elements in a tuple. It means that we cannot delete or remove items from a
tuple. Deleting a tuple entirely, however, is possible using the keyword del.

When you run the above code output will be:


6.12 Tuple operations
We can use + operator to combine two tuples. This is called concatenation.
We can also repeat the elements in a tuple for a given number of times using the * operator.
Both + and * operations result in a new tuple.

Tuple Membership Test


We can test if an item exists in a tuple or not, using the keyword in.

6.13 Iterating Through a Tuple


We can use a for loop to iterate through each item in a tuple.

6.14 Built-in functions


len()- to determine how many elements in the tuple
tuple()-a function to make a tuple
count()-Returns the number of times a specified value occurs in a tuple
index()-Searches the tuple for a specified value and returns the position where it was found
min()-Returns the minimum value in a tuple
max()-Returns the maximum value in a tuple
6.15 Advantages of Tuple over List
 Since tuples are quite similar to lists, both of them are used in similar situations. However, there are certain
advantages of implementing a tuple over a list. Below listed are some of the main advantages:
 We generally use tuples for heterogeneous (different) data types and lists for homogeneous (similar) data
types.
 Since tuples are immutable, iterating through a tuple is faster than with list. So there is a slight performance
boost.
 Tuples that contain immutable elements can be used as a key for a dictionary. With lists, this is not possible.
 If you have data that doesn't change, implementing it as tuple will guarantee that it remains write-protected.
Example: 1

Output:
Example: 2

Output:

Module3 - Dictionaries
A dictionary is like a list, but more general. In a list, the index positions have to be integers; in a dictionary, the
indices can be (almost) any type.
You can think of a dictionary as a mapping between a set of indices (which are called keys) and a set of values. Each
key map to a value. The association of a key and a value is called a key-value pair or sometimes an item.
As an example, we‘ll build a dictionary that map from English to Spanish words, so the keys and the values are all
strings.
The function dict creates a new dictionary with no items. Because dict is the name of a built-in function, you should
avoid using it as a variable name.
>>> eng2sp = dict()
>>> print (eng2sp)
{}
The curly brackets, {}, represent an empty dictionary. To add items to the dictionary,you can use square brackets:
>>> eng2sp['one'] = 'uno'
This line creates an item that maps from the key ‘one‘ to the value 'uno'. If weprint the dictionary again, we see a key-
value pair with a colon between the keyand value:
>>> print (eng2sp)
{'one': 'uno'}
This output format is also an input format. For example, you can create a newdictionary with three items:
>>> eng2sp = {'one': 'uno', 'two': 'dos', 'three': 'tres'}
But if you print eng2sp, you might be surprised:
>>> print (eng2sp)
{'one': 'uno', 'three': 'tres', 'two': 'dos'}
The order of the key-value pairs is not the same. In fact, if you type the same example on your computer, you might
get a different result. In general, the order of items in a dictionary is unpredictable.
But that‘s not a problem because the elements of a dictionary are never indexed with integer indices. Instead, you use
the keys to look up the corresponding values:
>>> print (eng2sp['two'])
'dos'
The key ‟two‟ always maps to the value 'dos' so the order of the items doesn‘t matter.
If the key isn‘t in the dictionary, you get an exception:
>>> print (eng2sp['four'])
KeyError: 'four'
6.16 Accessing Elements from Dictionary
While indexing is used with other data types to access values, a dictionary uses keys. Keys can be used either inside
square brackets [] or with the get() method.
If we use the square brackets [], KeyError is raised in case a key is not found in the dictionary. On the other hand,
the get() method returns None if the key is not found.
Output:
6.17 Changing and Adding Dictionary elements
Dictionaries are mutable. We can add new items or change the value of existing items using an assignment operator.
If the key is already present, then the existing value gets updated. In case the key is not present, a new (key: value)
pair is added to the dictionary.
Output:

6.18 Looping Techniques


When looping through dictionaries, the key and corresponding value can be retrieved at the same time using
the items() method.

When looping through a sequence, the position index and corresponding value can be retrieved at the same time using
the enumerate() function.

To loop over two or more sequences at the same time, the entries can be paired with the zip() function.

6.19 Removing elements from Dictionary


We can remove a particular item in a dictionary by using the pop() method. This method removes an item with the
provided key and returns the value.
The popitem() method can be used to remove and return an arbitrary (key, value) item pair from the dictionary. All
the items can be removed at once, using the clear() method.
We can also use the del keyword to remove individual items or the entire dictionary itself.
6.20 Dictionary Comprehension
Dictionary comprehension is an elegant and concise way to create a new dictionary from an iterable in Python.
Dictionary comprehension consists of an expression pair (key: value) followed by a for statement inside curly
braces {}.
Here is an example to make a dictionary with each item being a pair of a number and its square.

6.21 Dictionary Membership Test


We can test if a key is in a dictionary or not using the keyword in. Notice that the membership test is only for
the keys and not for the values.

6.22 Dictionary Methods


Methods that are available with a dictionary are tabulated below. Some of them have already been used in the above
examples.
6.23 Dictionary Built-in Functions
Built-in functions like all(), any(), len(), cmp(), sorted(), etc. are commonly used with dictionaries to perform
different tasks.

Example:1

Example:2
Example:3

Multiple Choice Questions


1) What will be the output of the following Python code?
>>>names = ['Amir', 'Bear', 'Charlton', 'Daman']
>>>print(names[-1][-1])
a) A b) Daman c) Error d) n
2) Suppose list1 is [1, 3, 2], What is list1 * 2?
a) [2, 6, 4] b) [1, 3, 2, 1, 3] c) [1, 3, 2, 1, 3, 2] d) [1, 3, 2, 3, 2, 1]
3) Suppose list1 = [0.5 * x for x in range(0, 4)], list1 is:
a) [0, 1, 2, 3] b) [0, 1, 2, 3, 4] c) [0.0, 0.5, 1.0, 1.5] d) [0.0, 0.5, 1.0, 1.5, 2.0]
4) To insert 5 to the third position in list1, we use which command?
a) list1.insert(3, 5) b) list1.insert(2, 5) c) list1.add(3, 5) d) list1.append(3, 5)
5) Suppose t = (1, 2, 4, 3), which of the following is incorrect?
a) print(t[3]) b) t[3] = 45 c) print(max(t)) d) print(len(t))
6) What will be the output of the following Python code?
>>>t = (1, 2)
>>>2 * t
a) (1, 2, 1, 2) b) [1, 2, 1, 2] c) (1, 1, 2, 2) d) [1, 1, 2, 2]
7) What will be the output of the following Python code?
>>>my_tuple = (1, 2, 3, 4)
>>>my_tuple.append( (5, 6, 7) )
>>>print len(my_tuple)
a) 1 b) 2 c) 5 d) Error
8) Which of these about a dictionary is false?
a) The values of a dictionary can be accessed using keys
b) The keys of a dictionary can be accessed using values
c) Dictionaries aren‘t ordered
d) Dictionaries are mutable
9) Which of the following is not a declaration of the dictionary?
a) {1: ‗A‘, 2: ‗B‘} b) dict([[1,‖A‖],[2,‖B‖]]) c) {1,”A”,2”B”} d) { }
10) What will be the output of the following Python code snippet?
a={1:"A",2:"B",3:"C"}
print (a.get(1,4))
a)1 b)A c)4 d) Invalid syntax forget method
Descriptive Questions
1) What is list in python; explain its merits and demerits.
2) Can you explain tuple methods with suitable examples?
3) How can we create a dictionary and remove the item from it?
4) Write a python program to find second largest number in the given list.
5) Python Program to Generate Random Numbers from 1 to 20 and Append Them to the List
6) Python program to Sort a List of Tuples in Increasing Order by the Last Element in Each Tuple
7) Write a python program to multiply all the items in a dictionary.
8) Python Program to Create a Dictionary with Key as First Character and Value as Words Starting with that
Character

You might also like