PSPP Unit 1 and 2 - short and big question
PSPP Unit 1 and 2 - short and big question
COLLEGE OF ENGINEERING
(An Autonomous Institution – Approved by AICTE, New Delhi and Affiliated
to Anna University, Chennai)
1
20CS101 – Problem Solving using Python Programming
OUTCOMES:
At the end of the course, learners will be able to:
• Explain Components of a Computer System, types of programming languages, types of
software with examples and purpose.
• Perform problem analysis, use algorithms and prepare flow charts, pseudo code for solving
simple problems.
• Use Conditional, iteration constructs of python programming and apply to solve simple
problems.
• Use Functions, recursive function, String functions in python programming and apply to
perform linear and binary search.
• Explain the various operations for manipulating Tuples, Sets, Dictionaries and Use List
to perform simple and sorting operations.
• Explain file handling operations, exception handling, modules and packages and illustrate
programs for word count, file copy, merge operations and exception handling.
TEXT BOOKS:
1. E. Balagurusamy, “Problem Solving and Python Programming”, First edition, McGraw
Hill Education (India) Private Limited, 2017.
2. Allen B. Downey, “Think Python: How to Think Like a Computer Scientist“, 2nd edition,
Updated for Python 3, Shroff/O‘Reilly Publishers, 2016
(http://greenteapress.com/wp/think-python/)
REFERENCES:
1. Yashavant Kanetkar, Aditya Kanetkar, "Let Us Python", 2nd Edition, BPB Publications,
2020.
2. John V Guttag, —Introduction to Computation and Programming Using Python“, Revised
and expanded Edition, MIT Press , 2013
3. Robert Sedgewick, Kevin Wayne, Robert Dondero, —Introduction to Programming in
Python: An Inter-disciplinary Approach, Pearson India Education Services Pvt. Ltd.,
2016.
4. Timothy A. Budd, —Exploring Python‖, Mc-Graw Hill Education (India) Private Ltd.„
2015.
5. Kenneth A. Lambert, —Fundamentals of Python: First Programs‖, CENGAGE Learning,
2012.
6. Charles Dierbach, —Introduction to Computer Science using Python: A Computational
Problem-Solving Focus, Wiley India Edition, 2013.
7. Paul Gries, Jennifer Campbell and Jason Montojo, —Practical Programming: An Introduction
to Computer Science using Python 3‖, Second edition, Pragmatic Programmers, LLC,
2013.
8. Dr.A.Kannan,Dr.L.SaiRamesh,Problem SolvingandPythonProgramming, UpdatedEdition,
April2018, United Global Publishers Pvt. Ltd.
2
CONTENTS 20CS101 – Problem Solving using Python Programming
Contents
Unit I Short Questions 5
List of Figures
1 Block diagram of a Computer . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5
2 Detailed Block Diagram of a Computer . . . . . . . . . . . . . . . . . . . . . . . 6
3 Range of binary values and their names . . . . . . . . . . . . . . . . . . . . . . . 8
4 Memory types over the period of time . . . . . . . . . . . . . . . . . . . . . . . . 8
5 Flow-Chart Symbols . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17
6 Flow-Chart Rules . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18
7 Flow-Chart for Sum of 50 natural numbers . . . . . . . . . . . . . . . . . . . . . 18
8 Flow-Chart for Largest of 3 numbers . . . . . . . . . . . . . . . . . . . . . . . . 19
9 Flow-Chart for Sequence Construct . . . . . . . . . . . . . . . . . . . . . . . . . 22
10 Branching Process . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22
11 Repetition Process . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23
12 Flow-Chart to Print first 10 numbers . . . . . . . . . . . . . . . . . . . . . . . . 24
13 Finding the maximum of a list of n numbers . . . . . . . . . . . . . . . . . . . . 24
14 Flow-Chart for Minimum and Maximum of a list of numbers . . . . . . . . . . . 26
15 Flow-Chart to calculate Factorial n . . . . . . . . . . . . . . . . . . . . . . . . . 27
16 Software used in the coding process . . . . . . . . . . . . . . . . . . . . . . . . . 34
17 Steps in interpreting a Python Program . . . . . . . . . . . . . . . . . . . . . . . 35
18 Branching Process . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 36
19 List of Data Types in Python . . . . . . . . . . . . . . . . . . . . . . . . . . . . 40
20 List of Operators in Python . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 45
21 Identity Operator Functionality . . . . . . . . . . . . . . . . . . . . . . . . . . . 50
22 Python if ... elif ... else statement . . . . . . . . . . . . . . . . . . . . . . . . . . 53
23 While and For Loops . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 54
24 Python break statement . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 58
25 Python continue statement . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 59
List of Tables
1 Bitwise Operators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 32
2 Type Number . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 40
3 Print Format Specifiers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 41
4 Numeric Literals . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 44
5 Arithmetic Operators and their usage . . . . . . . . . . . . . . . . . . . . . . . . 45
6 Relational Operators and their usage . . . . . . . . . . . . . . . . . . . . . . . . 46
7 Assignment Operators and their usage . . . . . . . . . . . . . . . . . . . . . . . 47
3
LIST OF ALGORITHMS 20CS101 – Problem Solving using Python Programming
List of Algorithms
1 Largest of the three numbers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16
2 Largest of three using and operator . . . . . . . . . . . . . . . . . . . . . . . . . 16
3 Largest of Three using variable MAX . . . . . . . . . . . . . . . . . . . . . . . . . 17
4 Find maximum and minimum of a list of numbers . . . . . . . . . . . . . . . . . 25
5 Factorial Algorithm(Iterative) . . . . . . . . . . . . . . . . . . . . . . 25
6 Leap Year Algorithm . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25
7 Square Root Algorithm . . . . . . . . . . . . . . . . . . . . . . . . . . . . 27
8 Square Root of a number(another version) . . . . . . . . . . . . . 27
4
Unit I Short Questions 20CS101 – Problem Solving using Python Programming
Memory Unit
5
Unit I Short Questions 20CS101 – Problem Solving using Python Programming
Output
Input Unit Memory Unit
Unit
Cache Memory
Register
Arithmetic
Logic Unit
Control
Unit
CPU
6
Unit I Short Questions 20CS101 – Problem Solving using Python Programming
7. Mention the various types of computers according to their size and capability.
• Microcomputers(single user)
• Minicomputers(more than 10 users)
• Mainframe computers(weather forecasting etc)
• Super computers or Cloud computers(Cellphone servers)
8. Mention the different categories of computers made for individual users.
9. Define a server.
A computer used for running larger programs for multiple users, often simultaneously,
and typically accessed only via a network. Servers span the widest range in cost and
capability. At the low end, a server may be little more than a desktop computer without
a screen or keyboard and cost about fifty thousand rupees. These low-end servers are
typically used for file storage, small business applications, or simple web serving
10. List out the difference between mainframe computers and Cloud Computer.
Mainframe Computer: Used by large business organisation employing very huge
applications such as financial transaction processing, consumer statistics, enterprise resource
planning. The term refers to huge cabinet with a central processor and a huge main
memory.
Cloud Computers: Cloud computing, the computing infrastructure is located in diverse
geographical locations, all working in harmony via the Internet. It is similar to distributed
computing which is useful particularly for projects that “are not as sensitive to latency.”
7
Unit I Short Questions 20CS101 – Problem Solving using Python Programming
8
Unit I Short Questions 20CS101 – Problem Solving using Python Programming
9
Unit I Short Questions 20CS101 – Problem Solving using Python Programming
A device driver acts as a translator between the hardware and the software that uses the
devices. In other words, it intermediates between the device and the software, in order
to use the device.
21. What is the purpose of a device driver?
Some devices that are commonly connected to the computer are— keyboard, mouse,
hard disk, printer, speakers, microphone, joystick, webcam, scanner, digital camera, and
monitor. For proper working of a device, its corresponding device driver must be installed
on the computer. For example, when we give a command to read data from the hard disk,
the command is sent to the hard disk driver and is translated to a form that the hard
disk can understand. The device driver software is typically supplied by the respective
device manufacturers.
22. What is the need for programming languages?
Programming Language consists of a set of vocabulary and grammatical rules, to express
the computations and tasks that the computer has to perform. Programming languages
are used to write a program, which controls the behavior of computer, codify the algorithms
precisely, or enables the human-computer interface. Each language has a unique set
of keywords (words that it understands) and a special syntax for organizing program
instructions. The programming language should be understood, both by the programmer
(who is writing the program) and the computer. A computer understands the language
of 0s and 1s, while the programmer is more comfortable with English-like language.
23. Name the three categories of programming languages.
Machine Language is what the computer can understand but it is difficult for the
programmer to understand. Machine languages consist of numbers only. Each kind
of CPU has its own unique machine language. Assembly Language falls in between
machine language and high-level language. They are similar to machine language, but
easier to program in, because they allow the programmer to substitute names for numbers.
High-level Language is easier to understand and use for the programmer but difficult
for the computer.
24. What are low-level languages?
Machine languages and assembly languages are also called low-level languages, and are
generally used to write the system software.
25. Define source code
The program written in a programming language is also called the source code.
26. Define object code.
A program written in machine language is a collection of binary digits or bits that the
computer reads and interprets. It is a system of instructions and data executed directly
by a computer’s CPU. It is also referred to as machine code or object code. It is written
as strings of 0s and 1s
27. Machine language is hardware dependent— True or False.
True
28. List the key features of machine language.
10
Unit I Short Questions 20CS101 – Problem Solving using Python Programming
Program written in machine language can be executed very fast (Since no translation is
required).
29. List the key features of assembly language.
program written in assembly language uses symbolic representation of machine codes
needed to program a particular processor (CPU) or processor family. This representation
is usually defined by the CPU manufacturer, and is based on abbreviations (called
mnemonics) that help the programmer remember individual instructions, registers, etc.
Small, English-like representation is used to write the program in assembly language, as
shown below:
MVI B,A
MVI C, 06H
LXI H, XX50H
ADD M
JNC NXTITM
INR B
INR H
DCR C
JNZ NXTBIT
Assembly language programs are easier to write than the machine language programs,
since assembly language programs use short, English-like representation of machine code.
30. List the key features of high-level languages.
Programs are easier to write, read or understand in high-level languages than in machine
language or assembly language. For example, a program written in Python is easier to
understand than a machine language program. Programs written in high-level languages
is the source code which is converted into the object code (machine code) using translator
software like interpreter or compiler. A line of code in high-level program may correspond
to more than one line of machine code. Programs written in high-level languages are easily
portable from one computer to another.
31. Why is it difficult to write a program in machine language?
It is a tedious process because some of the repeated tasks can not be avoided.
32. Classify the programming languages based on their generations?
Generation Language
First Generation Machine language
Second Generation Assembly language
Third Generation C, COBOL, Fortran, Pascal, C + +, Java,
ActiveX (Microsoft), Python etc.
Fourth Generation .NET (VB.NET, C#.NET etc.) Scripting
language (Javascript, Microsoft Frontpage
etc.)
Fifth Generation LISP, Prolog
33. What is the purpose of an assembler?
Assembler converts a program written in assembly language to machine language.
34. What is the purpose of a compiler?
11
Unit I Short Questions 20CS101 – Problem Solving using Python Programming
12
Unit I Short Questions 20CS101 – Problem Solving using Python Programming
• Since interpreter interprets line-by-line, the interpreted code runs slower than the
compiled code
41. Define a software package.
The software that a user uses for accomplishing a specific task is the application software.
Application software may be a single program or a set of programs. A set of programs that
are written for a specific purpose and provide the required functionality is called software
package. Application software is written for different kinds of applications— graphics,
word processors, media players, database applications, telecommunication, accounting
purposes etc.
42. Mention the list of application packages.
• Word Processing Software: For writing letter, reports, documents etc. (e.g. MS-WORD).
• Image Processing Software: For assisting in drawing and manipulating graphics (e.g.
Adobe Photoshop).
• Accounting Software: For assisting in accounting information, salary, tax returns
(Tally software).
• Spreadsheet Software: Used for creating budget, tables etc. (e.g. MS-Excel).
• Presentation Software: To make presentations, slide shows (e.g. MS-PowerPoint)
Suite of Software having Word Processor,
• Spreadsheet and Presentation Software: Some examples are MS-Office, Google Docs,
Sun Openoffice, Apple iWork.
• CAD/ CAM Software: To assist in architectural design. (e.g. AutoCAD, Autodesk)
• Geographic Information Systems: It captures, stores, analyzes, manages, and presents
data, images and maps that are linked to different locations. (e.g. ArcGIS)
• Web Browser Software: To access the World Wide Web to search documents, sounds,
images etc. (e.g. Internet Explorer, Netscape Communicator, Chrome).
13
Unit I Short Questions 20CS101 – Problem Solving using Python Programming
14
Unit I Short Questions 20CS101 – Problem Solving using Python Programming
57. Write an algorithm to check whether the given number is odd or even.
Let the number to be checked be represented by N. The number N is divided by 2
to give an integer quotient, denoted by Q. If the remainder, designated as R, is zero,
N is even; otherwise N is odd. This logic has been applied in the following algorithm:
1. START
2. print “ENTER THE NUMBER”
3. INPUT N
4. Q ← N/2 (INTEGER DIVISION)
5. R←N −Q×2
6. if R = 0 then
7. print “N IS EVEN”
8. if R = 1 then
9. print “N IS ODD”
10. STOP
15
Unit I Short Questions 20CS101 – Problem Solving using Python Programming
16
Unit I Short Questions 20CS101 – Problem Solving using Python Programming
Start
Input Process
Decision Output
Stop
• Effective analysis With the help of flowcharts, problems can be analysed more
effectively.
• Proper documentation Program flowcharts serve as a good program documentation
needed for various purposes.
• Efficient coding Flowcharts act as a guide or blueprint during the systems analysis
and program development phase.
• Proper debugging Flowcharts help in the debugging process.
• Efficient program maintenance The maintenance of an operating program become
easy with the help of a flowchart.
Limitations of using flowcharts
• Complex logic Sometimes, the program logic is quite complicated. In such a case, a
flowchart becomes complex and clumsy.
• Alterations and modifications If alterations are required, the flowchart may need to
be redrawn completely.
• Reproduction Since the flowchart symbols cannot be typed in, the reproduction of a
flowchart becomes a problem.
17
Unit I Short Questions 20CS101 – Problem Solving using Python Programming
Process1 Process2
No Decision1 Yes
• The essentials of what has to be done can easily be lost in the technical details of
how it is to be done.
62. Draw a flowchart to find the sum of the first 50 natural numbers
See Figure: 7
Start N ←N +1
SUM=0 SU M ← SU M + N
N=0
IS N > 50?
No
Yes
PRINT SU M
STOP
18
Unit I Big Questions 20CS101 – Problem Solving using Python Programming
Start
READ A, B, C
Yes
Is B > C? Is A > B? Is A > C?
Yes No YES
No No
STOP
What separates pseudocode from “real” code is that in pseudocode, we employ whatever
expressive method is most clear and concise to specify a given algorithm. Sometimes,
the clearest method is English, so we may not be surprised if we come across an English
phrase or sentence embedded within a section of “real” code. Another difference between
pseudocode and real code is that pseudocode is not typically concerned with issues of
software engineering. Issues of data abstraction, modularity, and error handling are often
ignored in order to convey the essence of the algorithm more concisely.
19
Unit I Big Questions 20CS101 – Problem Solving using Python Programming
• A pseudo code is written for the selected solution. Pseudo code uses the structured
programming constructs. The pseudo code becomes an input to the next phase.
Program Development
• The computer programming languages are of different kinds – low-level languages,
and high- level languages like C, C++, Python and Java. The pseudo code is coded
using a suitable programming language.
• The coded pseudo code or program is compiled for any syntax errors. Syntax errors
arise due to the incorrect use of programming language or due to the grammatical
errors with respect to the programming language used. During compilation, the
syntax errors, if any, are removed.
• The successfully compiled program is now ready for execution.
• The executed program generates the output result, which may be correct or incorrect.
The program is tested with various inputs, to see that it generates the desired results.
If incorrect results are displayed, then the program has semantic error (logical error).
The semantic errors are removed from the program to get the correct results.
• The successfully tested program is ready for use and is installed on the user’s
machine.
Program Documentation and Maintenance — The program is properly documented
so that, later on, anyone can use it and understand its working. Any changes made to
the program, after installation, forms part of the maintenance of programs. The program
may require updating, fixing errors etc. during the maintenance phase.
2. What are the three tools the programmer uses to develop a program solution?
i) flow-chart ii) pseudo-code iii) algorithm(explain each as above)
3. Given two variables a and b exchange the values assigned to them
Consider the variables are assigned values as outlined below:
Starting Configuration:
a : 123 b : 456
This means that memory cell or variable a contains the value 123 and memory cell or
variable b contains the value 456. Our task is to replace the contents of a with 456, and
the contents of b with 123. In other words we want to end up with the configuration
below:
Target Configuration:
a : 456 b : 123
To exchange the value of a variable, we can use the assignment operator. Because we
want a to assume the value currently belonging to b, and b the value belonging to a we
could perhaps make the exchange with the following assignments:
a←b (1)
b←a (2)
where "←" is the assignment operator. In (1) "←" causes the value stored in memory
cell b to be copied into memory cell a.
Let us work through these two steps to make sure they have the desired effect. We started
out with the configuration:
a : 123 b : 456
20
Unit I Big Questions 20CS101 – Problem Solving using Python Programming
t ← a; (3)
a ← b; (4)
After these two steps we have
a : 456 t : 123 b : 456
Now we have to copy down the value of t to b so that we will be able to achieve exchanging
the values between a and b.
b ← t; (5)
4. Discuss the three basic program control structures with suitable examples.
Sequence Control Structure: As the name implies, in a sequence structure, the
instructions to be computed simply follow one another in a logical progression. This
structure is denoted by writing one action after another, each action on a line by itself,
and all actions aligned with the logical indent. The actions are performed in the same
sequence (top to bottom) in which they are written. Typical sequence operations consist
of the process and I/ O steps. Figure 9 illustrates a simple sequence:
Selection Structure: A selection structure allows the program to make a choice
between two alternate paths, whether it is true or false. The first statement of a selection
structure is a conditional statement. Once the sequence of steps in the selected path has
been carried out, the paths are rejoined and then the next instruction is carried out. Thus,
the selection structure has only a single entry and a single exit. In the example given
in Figure 10a, we have a Test expression which is evaluated. In the selection process,
if the expression is true then the statement is executed if the expression is false, the
statement is bypassed Figure 10a. In Figure 10b, if the Test expression evaluates to True,
then, statement1 is executed otherwise statement2 will be executed
21
Unit I Big Questions 20CS101 – Problem Solving using Python Programming
ACTION 1
ACTION 2
ACTION n
Statement
22
Unit I Big Questions 20CS101 – Problem Solving using Python Programming
False
Condition
Repeated Task
True
False
Condition Repeated Task
True
(a) repeat. . . until – post-test loop (b) while – pre-test loop
23
Unit I Big Questions 20CS101 – Problem Solving using Python Programming
Start
COU N T ← 0
COU N T ← COU N T + 1
Print COU N T
No
Stop
8 6 5 15 7 19 18 6 13
6. Draw the flow-chart and write an algorithm for printing the factorial of the
given number n that is
n! = n × (n − 1) × (n − 2) × . . . × 2 × 1.
First of all we read the value of n. While calculating the factorial of a number, there are
two variables involved. 1) The i value and 2) the f act value. The i value is initially set
to 0 and f act is set to 1. Since
n! = n × (n − 1) × (n − 2) × . . . × 3 × 2 × 1.
Since, 0! = 1, when initially, n = 0, the condition i = n becomes immediately True and
our program doesn’t enter the loop at all. If n > 0, the looping will take place at least
once. In every iteration, i is incremented by 1 and it gets multiplied with f act and the
result is assigned to f act itself. Thus the loop will terminate when i = n and at that time,
the f act value will be the factorial of n. The algorithm 5 and flow-chart for computing
factorial is shown in Figure: 15
7. Write an algorith that determines whether the given year is a leap year or
not.
24
Unit I Big Questions 20CS101 – Problem Solving using Python Programming
Refer to algorithm 6 which determines whether the given year is a leap year or not. Here
we are using a test expression that detrmines if the year is divisible by 4 and if so, it
checks whether it is not divisible by 100 and concludes that it is a leap year. On the
other hand if the given year happens to be be divisible by 400, it is concluded to be a
leap year. Thus it follows a logic of "if the year is just divisible by 100 which implies that
it is divisible by 4 also is not a sufficient condition that it is a leap year".
25
Unit I Big Questions 20CS101 – Problem Solving using Python Programming
Start
READ the Is
No
list of numbers i < length?
Yes
min ← list[0]
max ← list[0]
Is
Yes min > list[i]
length ← length
of list min ← list[i]
No
i←0
Yes Is
max < list[i]
max ← list[i]
No
i←i+1
STOP
this, programs are written in special computer languages. A natural language is not
used to instruct the computer even though a programming language consists of a set of
characters, symbols, and usage rules that allow the user to communicate with computers,
just as in natural languages. Programming languages can be divided into three major
categories:
26
Unit I Big Questions 20CS101 – Problem Solving using Python Programming
Start
READn
i←0
f act ← 1
Is i = n? Yes
No
i←i+1
Print f act
f act ← f act × i
Stop
Machine Language: It is the native language of computers. It uses only ‘0’ s and ‘1’ s
to represent data and the instructions.
Assembly Language: It corresponds to symbolic instructions and executable machine
codes and was created to use letters instead of ‘0’ s and ‘1’ s to run a machine.
High-level Language: These languages are written using a set of words and symbols
following some rules similar to a natural language, such as English. The programs written
27
Unit II Short Questions 20CS101 – Problem Solving using Python Programming
in high-level languages are known as source programs and these programs are converted
into machine-readable form by using compilers or interpreters.
28
Unit II Short Questions 20CS101 – Problem Solving using Python Programming
29
Unit II Short Questions 20CS101 – Problem Solving using Python Programming
Numbers, strings, lists, dictionaries, tuples, files, andsets are generally considered to be
the core object (data) types. Types, None , and Booleans are sometimes classified this
way as well. There are multiple number types (integer, floating point, complex, fraction,
and decimal) and multiple string types (simple strings and Unicode strings in Python
2.X, and text strings and byte strings in Python 3.X).
30
Unit II Short Questions 20CS101 – Problem Solving using Python Programming
print("<expression>,<expression>")
print("<expression>",<variable name>)
31
Unit II Short Questions 20CS101 – Problem Solving using Python Programming
The value will be 10 , the result of 6 + 4. Python’s operator precedence rules are applied
in the absence of parentheses, and
multiplication has higher precedence than (i.e., happens before) addition.
29. Discuss the use of //, ** operator with suitable example.
The floor division operator, //, divides two numbers and rounds down to an integer. For
example, suppose the run time of a movie is 111 minutes. We might want to know how
long that is in hours. Conventional division returns a floating-point number.
>>> hours = 111 / 60
>>> hours
1.85
>>>
Floor division returns the integer number of hours, dropping the fraction part
>>> hours = 111 // 60
>>> hours
1
The operator ** performs exponentiation; that is, it raises a number to a power:
>>> answer = 5**2 + 3
>>> answer
28
>>>
30. Define Membership operator.
Membership operators are used to test whether a value (variable) is found in a sequence
like string, list, tuple, set and dictionary. There are two membership operators that are
used in Python. They are:
• in: Evaluates to true, if it finds a variable in the specified sequence and false
otherwise
• not in: Evaluates to true if it does not finds a variable in the specified sequence
and false otherwise
31. Mention the use of identity operators.
Identity operators are used to compare the memory location of two objects. It is used to
check whether the two values (variables) are located on the same part of the memory. The
variables that are equal doesn’t mean that, they are identical. The two identify operators
used in Python. They are:
32
Unit II Short Questions 20CS101 – Problem Solving using Python Programming
• is: Evaluates to true, if the variables on either side of the operator point to the same
object and false otherwise.
• is not: Evaluates to false, if the variables on either side of the operator point to the
same object and true otherwise.
32. Explain briefly about operator precedence
The operator precedence determines which operators need to be evaluated first. To avoid
ambiguity in values, precedence of operators are necessary.
33. Define Associativity.
Associativity is the order in which an expression is evaluated, that has multiple operator
of same precedence. Almost all the operators have left-to-right associativity. When
two operators have the same precedence, associativity helps to determine the order of
operations.
34. List out the various advantages of Python.
• Compared to other languages it is 5 to 10 times faster – Object-Oriented
• Dynamic Type Checking makes it inherently generic – C++ templates for free
• Free, as in Open Source — free Portability
• Powerful language features and library, used in internet security
• Easy to use and learn
35. List out the various disadvantages of Python.
• Python is slow compared to C or C++ or java.
• Python is not a great choice for a high-graphic 3d game and memory intensive tasks.
• It has some limitations with database access
Tuple Assignment
36. Define tuple assignment
consider the following statements:
>>> x=2
>>> y=3
>>> x,y = y,x
When we code a tuple on the left side of the =, Python pairs objects on the right side
with targets on the left by position and assigns them from left to right. In the above
example the variable x is assigned the value 2, and y is bound to 3. In the third line,
Python internally may make a tuple of the items on the right, which is why this is called
tuple-unpacking assignment or tuple assignment.
37. Define a tuple. How literals of type tuple are written? Give example.
A tuple is a sequence data type that is similar to the list. A tuple consists of a number of
values separated by commas. Unlike lists, however, tuples are enclosed within parentheses.
They are immutable. Syntactically, they are normally coded in parentheses instead
33
Unit II Short Questions 20CS101 – Problem Solving using Python Programming
of square brackets, and they support arbitrary types, arbitrary nesting, and the usual
sequence operations:–
>>> T = (1, 2, 3, 4) # A 4-item tuple
>>> len(T) # Length
4
>>> T + (5, 6) # Concatenation
(1, 2, 3, 4, 5, 6)
>>> T[0] # Indexing
1
>>> T[1:3] # slicing
(2, 3)
38. Identify the meaning of “sequence” in python and which three types are
involved into this category?
A “sequence” is a positionally ordered collection of objects. Strings, lists, and tuples are
all sequences in Python. They share common sequence operations, such as indexing,
concatenation, and slicing, but also have type-specific method calls. A related term,
"iterable", means either a physical sequence, or a virtual one that produces its items on
request.
39. Explain the role played by the translators in the programming process?
Program Outputs
34
Unit II Short Questions 20CS101 – Problem Solving using Python Programming
English teacher who rejects any sentence that does not adhere to the grammar rules,
or syntax, of the language. As soon as the interpreter encounters such an error, it
halts translation with an error message. See figure:17.
ii) If a Python expression is well formed, the interpreter then translates to an equivalent
form in a low-level language called byte code when the interpreter runs a script, it
completely translates it to byte code.
iii) This byte code is next sent to another software component, called the Python virtual
machine (PVM), where it is executed, If another error occurs during this step,
execution also halts with an error message.
Syntax error
Python Code messages
Syntax Checker
and Translator
Byte Code
Other error
User Inputs messages
Python Virtual
Machine (PVM)
Program
Outputs
35
Unit II Short Questions 20CS101 – Problem Solving using Python Programming
Statement Block
if expression : if expression1 :
statements1 statements1
else : elif expression2 :
statements2 statements2
else :
Listing 1: Syntax for if-else See Figure staements3
18b
Listing 2: if-elif-else
In Listing 1, the expression is first evaluated if it is True, statements1 is executed if
expression is False, statements2 is executed. In Listing 2, we have a if-elif-else
structure. Here first of all, statements1 is executed if expression1 is True. In the event of
expression1 False, expression2 is evaluated and if True, staements2 gets executed and
if False, statements3 will get executed.
45. Write a program to check if the number is positive or negative or zero.
numl = float(input ("Enter a number: "))
if numl >= 0:
if numl 0:
print("Zero")
else :
print (" Positive number")
else :
print ("Negative number")
36
Unit II Short Questions 20CS101 – Problem Solving using Python Programming
a simple task.
Syntax
do Task A if condition is true else do Task B
Example
>>>b = True
>>>a = 1 if b else None
>>>a
Iteration: state, while, for, break, continue, pass
47. Define loops in Python.
A loop is a programming control structure that facilitates the repetitive execution of a
statement or group of statements. See Example 1
Example 1.
for i in range(1,3):
print( ' i =', i )
Output.
i= 1
i= 2
>>>
37
Unit II Short Questions 20CS101 – Problem Solving using Python Programming
In the above syntax, Statement1(s) is(are) associated with inner for and Statement2(s)
is(are) associated with outer for. We must note that the indentation that is placed makes
all the difference.
52. Compute the output of the following:
L = ['ab' , 'cd' ]
for i in L:
i .upper()
print(L)
Output. [’ab’,’cd’]
Since the print(L) is done outside the loop the individual elements of the list is unaffected.
53. What is the purpose of break statement in Python?
A break statement is used to end the current loop and instruct Python to execute the
statement after the loop. If it is inside a nested loop (A loop inside another loop), break
will terminate the innermost loop. It can be used with both for and while loops.
54. What is the purpose of continue statement in Python?
The continue statement skips remaining statement(s) in the present iteration and directs
the program to the next iteration. Actually, continue returns the control to the beginning
of the loop. The continue statement rejects all the remaining statements in the current
iteration of the loop and moves the control back to the top of the loop.
55. Define pass statement in Python.
The use of Pass statement is to do nothing. It is just a placeholder for a statement that
is required for syntax purpose. It does not execute any code or command. Some of the
use cases for pass statement are as follows:
Syntax purpose:
>>> while True:
... pass # Wait till user input is received
Minimal Class: It can be used for creating minimal classes:
>>> class MyMinimalClass:
... pass
Place-holder for TODO work: We can also use it as a placeholder for TODO work
on a function or code that needs to be implemented at a later point of time.
>>> def initialization():
... pass #TODO
56. Outline the main functional differences between a while and a for
The while loop is a general looping statement, but the for is designed to iterate across
items in a sequence or other iterable. Although the while can imitate the for with
counter loops, it takes more code and might run slower.
57. Define Infinite loop with an example.
A loop becomes infinite loop if a condition never becomes False. This results in a loop
that never ends. Such a loop is called an infinite loop.
Example:
38
Unit II Big Questions 20CS101 – Problem Solving using Python Programming
while True:
n = int(input("Enter an integer : "))
print("The square of",n," is ", n∗∗2)
Output.
Enter a list(space separated) :a w e r d e w p u r y P w
['a', 'w', 'e', 'r', 'd', 'p', 'u', 'y', 'P']
>>>
61. Write a program that accept a word from the user and reverse it.
word = input("Input a word to reverse :")
for char in range(len(word)− 1, −1, −1):
print(word[char] , end="")
39
Unit II Big Questions 20CS101 – Problem Solving using Python Programming
DATA TYPES
Floating
Integer Complex Strings Tuples List Dictionary
Point
Boolean
Unlike other languages that include several different data types for storing numbers based
on storage needs, Python creates a new object with a new memory allocation for larger
numbers. The different numerical types include:
1) int (signed integers)
2) long (long integers)
3) float (float integers)
4) complex (complex integers)
Most of the time Python will do variable conversion automatically. We can also use
Python conversion functions like (int(), long(), float(), complex()) to convert
data from one type to another. In addition, the type function returns information about
how our data is stored within a variable.
>>>message = "Good morning"
>>>num = 85
>>>pi = 3.14159
>>> x=4+5j
>>> y=-8-2j
>>> xy=x+y
>>> print(xy)
(-4+3j)
>>>print(type(message))#This will return a string
>>>print(type(num)) #This will return an integer
>>>print(type(pi)) #This will return a float
Binary literal (base 2) A binary literal is of the form 0 (zero) followed by either an
uppercase B or lowercase b
Example:
>>> bin_num=0b1010001
40
Unit II Big Questions 20CS101 – Problem Solving using Python Programming
>>> print(bin_num)
81
>>> print(oct(bin_num))
0o121
>>> print(hex(bin_num))
0x51
>>> print(type(bin_num))
<class 'int'>
>>>
In the above example we see that bin_num is a variable of type integer. oct( and hex(
are functions that convert the given input variables to octal and hexadecimal respectively.
The function type( returns the type of the variable.
String We can create string variables by enclosing characters in quotes. Python uses
single quotes ’ double quotes “ and triple quotes ”“ to denote literal strings. Only the
triple quoted strings ”“ also will automatically continue across the end of line statement.
firstName = "baba"
lastName = "sai"
message = """This is a string that will span across
multiple lines. Using newline characters and no spaces
for the next lines. The end of lines within this string
also count as a newline when printed"""
>>>k="q"
>>>print("The value is %c"%k)
The value is q
>>>
Example
>>>name="Kannan"
>>>money=400
>>>print("%s took %d Rupees"%(name,money))
Kannan took 400 Rupees
Boolean Boolean often called bools, are either TRUE or FALSE condition. These
two values are used when evaluating comparisons, conditional expressions and in other
structures that require values to be represented for True or False conditions.
41
Unit II Big Questions 20CS101 – Problem Solving using Python Programming
>>> flag=True
>>> type(flag)
<class 'bool'>
Sequence A sequence is an ordered collection of items, indexed by positive integers. It
is available in mutable and non mutable data types. Three types of sequence data type
available in Python are Strings, Lists and Tuples Strings are already defined; now we will
see about lists and tuples.
Lists: Lists are the most versatile of Python’s compound data types. A list contains
items separated by commas and enclosed within square brackets ([]). To some extent,
lists are similar to arrays in C. One difference between them is that all the items belonging
to a list can be of different data type. The values stored in a list can be accessed using
the slice operator ([ ] and [:]) with indexes starting at 0 in the beginning of the list and
working their way to end -1. The plus (+) sign is the list concatenation operator, and
the asterisk (*) is the repetition operator. Consider the script Example 2
Example 2. list = ['abcd', 345 , 2.23, 'maya', 70.2]
tinylist = [123, 'maya']
print(list) # Prints complete list
print(list[0]) # Prints first element of the list
print(list[1:4]) #Prints elements starting from 2nd till 4th
print(list[2:]) # Prints elements starting from 3rd element
print(tinylist * 2) # Prints list two times
print(list + tinylist) #Prints concatenated lists
Output.
['abcd', 345 , 2.23, 'maya', 70.2]
abcd
[345,2.23,'maya ']
[2.23,'maya',70.2]
[123,'maya', 123,'maya']
['abcd', 345 , 2.23, 'maya', 70.2, 123,'maya']
Tuples
A tuple is another sequence data type that is similar to the list. A tuple consists of a
number of values separated by commas. Unlike lists, however, tuples are enclosed within
parentheses.
The main differences between lists and tuples are: Lists are enclosed in brackets ([ ]) and
their elements and size can be changed, while tuples are enclosed in parentheses (( )) and
cannot be updated. Tuples can be thought of as read-only lists.
Example 3.
tuple = ( 'abcd', 456 , 2.23, 'baba', 70.2)
tinytuple = (123, 'baba')
print(tuple) # Prints complete list of tuples
print(tuple[0]) # Prints first element of the list
print(tuple[1:3]) # Prints elements starting from 2nd till 3rd
print(tuple[2:]) # Prints elements starting from 3rd element
print(tuple[:2]) # Prints elements up to 2nd
print(tinytuple * 2) # Prints list two times
print(tuple + tinytuple) # Prints concatenated lists
Output.
42
Unit II Big Questions 20CS101 – Problem Solving using Python Programming
43
Unit II Big Questions 20CS101 – Problem Solving using Python Programming
Most of the time Python will do variable conversion automatically. We can also use
Python conversion functions (int(), long(), float(), complex()) to convert data from one
type to another. In addition, the type function returns information about how our data
is stored within a variable.
>>>num = 85
>>>pi = 3.14159
>>> x=4+5j
>>> y=-8-2j
>>> xy=x+y
>>> print(xy) # This is a complex number
(-4+3j)
>>>print(type(num)) #This will return an integer
>>>print(type(pi)) #This will return a float
4. Discuss about the operators in Python with example.
Python is a strongly typed programming language. The interpreter checks data types of
all operands before operators are applied to those operands. If the type of an operand is
not appropriate, the interpreter halts execution with an error message.
Consider the expression Z = X + Y.Here X, Y and Z are the operands. The signs + and
= are the operators. Python uses different operators. They are:
1) Arithmetic Operators
2) Relational or Comparison Operators
3) Assignment Operators
4) Bit wise Operators
5) Logical Operators
6) Membership Operators
7) Identity Operators
Arithmetic Operators
Arithmetic operators are used for performing basic arithmetic operations. Python’s
arithmetic expressions consists of operators and operands. Python supports seven types
of arithmetic operations they are listed in Example 5:
Example 5. .
>>> x,y,z=40,5,3
>>> print("x+y=",x+y)
x + y = 45
44
Unit II Big Questions 20CS101 – Problem Solving using Python Programming
OPERATORS
=
+ < &
+=
- > |
or -=
/ <= >> in
and /=
// >= << not in
not %=
* != ∼
//=
** = ˆ
**=
Figure 20: List of Operators in Python
Ope-
rator Explanation Example
+ Addition: It adds two operands or unary plus x+y
- Subtract right operand from the left or unary minus x - y or
-x - y
* Multiplication: It multiplies values on either side of operator x*y
/ Division: It divides left hand operand by the right hand operand x/y
% Modulus: It also divides left hand operand by right hand operand and x%y
returns the remainder
// Floor division: The division of operands where the result is the quotient x // y
in which the digits after the decimal point are removed. But if one of the
operands is negative, the result is floored, i.e., rounded away from zero
(towards negative infinity)
** Exponent: left operand raised to the power of right x ** y
>>> print("x-y=",x-y)
x - y = 35
>>> print("x * y =",x*y)
x * y = 200
>>> print("x / y =",x/y)
x / y = 8.0
>>> print("x % z == ",x%z)
x % z == 1
>>> print("x**z=",x**z)
x**2= 64000
>>> print("x floor division z=",x // z)
x floor division z= 13
>>>
45
Unit II Big Questions 20CS101 – Problem Solving using Python Programming
Ope-
rator Explanation 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 x >= y
or equal to the right
Less than or equal to: True if left operand is less
<= than or equal to the right x <= y
Example 6.
>>> x,y=3,4
>>> print("x > y",x>y)
x > y False
>>> print("x < y",x<y)
x < y True
>>> print("x == y?",x == y)
x == y? False
>>> print("x+1<=y",x+1<=y)
x+1<=y True
>>> print("x+1>=y",x+1>=y)
x+1>=y True
>>> print("x != y",x!=y)
x != y True
>>> print("x==y?",x==y)
x==y? False
>>>
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 like a += 5 that adds to the variable
and later assigns the same. It is equivalent to a = a + 5. Assignment operators and their
usage are summarised in Table 7. Example 7 shows some basic assignment operations.
Example 7.
>>> x,y=5,10
>>> x=y # y is in x as well
>>> print(x)
10
46
Unit II Big Questions 20CS101 – Problem Solving using Python Programming
Ope-
rator Explanation Example
It Assigns values from right side operands to x=y assigns the
= left side operand value of y to x
It adds right operand to the left operand and x+=y is equivalent
+= assign the result to left operand to x = x+y
It subtracts right operand from the left x-=y is equivalent
-= operand and assign the result to left operand to x = x-y
It multiplies right operand with the left x*=y is equivalent
*= operand and assign the result to left operand to x = x*y
It divides left operand with the right operand x/=y is equivalent
/= and assign the result to left operand to x = x/y
It takes modulus using two operands and x %=y is equivalent
%= assign the result to left operand
Performs exponential (power) calculation on x**=y is
**= operators and assign value to the left equivalent to x =
operand x**y
It performs floor division on operators and x//=y is equivalent
//= assign value to the left operand to x = x//y
>>> print("x=",x)
x= 10
>>> x+=y #10+10=20 is the new value of x
>>> print("x=",x)
x= 20
>>> x-=y #20 – 10 = 10 is the new value of x
>>> print("x=",x)
x= 10
>>> x*=y #10 * 10 = 100 is the new value of x
>>> print("x=",x)
x= 100
>>> x,y=3,10 #x is 3 and y is 10
>>> x/=y
>>> print("x=",x)
x= 0.3
>>> x,y=10,3 #x is 10 and y is 3
>>> x%=y #x is 10 % 3 remainder after dividing 10 by 3
>>> print("x=",x)
x= 1
>>> x,y=10,3 #x is 10 and y is 3
>>> x//=y #quotient after dividing 10 by 3
>>> print("x=",x) #or x = x // y
x= 3
>>> x**=y #exponentiation
>>> print("x=",x)
x= 27
>>>
47
Unit II Big Questions 20CS101 – Problem Solving using Python Programming
Ope-
rator Explanation 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 not x
operand)
Logical Operators
Logical operators are shown in Table 8 Their usage is quiet self explanatory in nature.
Some important considerations that have to be adopted which using these logical operators
for efficiency purposes. Their operations are illustrated in Example 8
Example 8.
>>> x,y=10,10
>>> print((x>=y) and (x ==y))
True
>>> x,y=10,5
>>> print((x>y) and (y>x))
False
>>> print((x>y) or (y>x))
True
>>> x=y
>>> print((x>y) or (y>x))
False
>>> print(not(x>y))
True
>>>
Membership Operators
Membership operators are used to test whether a value (variable) is found in a sequence
like string, list, tuple, set and dictionary. There are two membership operators that are
used in Python (in, not in) Table 9. They are illustrated in Example 9
Ope-
rator Explanation Example
in Evaluates to true, if it finds a variable in x in y
the specified sequence and false otherwise
not in Evaluates to true if it does not finds a x not in y
variable in the I specified sequence and
false otherwise
Example 9.
>>> k="K.L.N. COLLEGE OF ENGINEERING"
>>> l1=k.split()
>>> e="ENGINEERING"
>>> print(e in l1)
48
Unit II Big Questions 20CS101 – Problem Solving using Python Programming
True
>>> print('k.l.n.' in l1)
False
>>> print('K.L.N.' in l1)
True
>>> print('Science' not in l1)
True
>>>
Identity Operators
Identity operators are used to compare the memory location of two objects. It is used to
check whether the two values (variables) are located on the same part of the memory. The
variables that are equal doesn’t mean that, they are identical. The two identity operators
used in Python are as shown in Table 10
Ope-
rator Explanation Example
Evaluates to true, if the variables on either
is side of the operator point to the same x is y
object and false otherwise.
Evaluates to false, if the variables on either
is not side of the operator point to the same x is not y
object and true otherwise.
Example 10. .
>>> a='banana'
>>> b='banana'
>>> print(a == b)
True
>>> print(a is b)
True
>>> L=[1,2,3]
>>> M=L
>>> L == M
True
>>> L is M
True
>>> M = [1,2,3]
>>> M == L
True
>>> L is M
False
In the example 10, variables a and b refer to the same object ’banana’ that is why is
operator returns True. The first technique here, the == operator, tests whether the
two referenced objects have the same values; this is the method almost always used for
equality checks in Python. The second method, the is operator, instead tests for object
identity — it returns True only if both names point to the exact same object, so it is a
49
Unit II Big Questions 20CS101 – Problem Solving using Python Programming
much stronger form of equality testing and is rarely applied in most programs.
Actually, is simply compares the pointers that implement references, and it serves as
a way to detect shared references in the code if needed. It returns False if the names
point to equivalent but different objects, as is the case when we run two different literal
expressions. These can be better understood from the Figure 21
b L L [1,2,3]
"banana" [1,2,3]
a M M [1,2,3]
Operators Explanation
** Exponentiation (raise to the power)
-,+,- Complement, unary plus and minus
*,/,%,// Multiply, divide, modulo and floor division
+,- Addition and subtraction
>>,<< Right and left bitwise shift
& bitwise ’AND’
ˆ,| Bitwise exclusive ’OR’ and regular ’OR
<=,>=,<,> Comparison Operators
==,!= Equality operators
=,%=,/=,//=,-=,+=,*=,**= Assignment operators
is,is not Identity operators
in, not in Membership operators
not,or,and Logical Operators
When we want to evaluate 3 + 4*5 the result would be 23 because first the value of 4*5
is evaluated and then 3 is added to it. Suppose if we want to add 3 with 4 and multiply
it together with 5 then we must specify it as (3+4)*5 because anything inside parenthesis
is evaluated first. In short we can remember the rule pedmas(parenthesis, exponential,
division, multiplication, addition and subtraction) in evaluating expressions.
50
Unit II Big Questions 20CS101 – Problem Solving using Python Programming
>>> p,q,r,s,t=3,4,8,5,0
>>> t = (p+q)*r/s
>>> print(t)
11.2
>>> #(3+4)*8/5 = 7*8/5 = 56/5 = 11.2
>>>
6. Write a program in Python to calculate the distance between the two points
(x1 , y1 ) and (x2 , y2 ).
The formula for calculating the distance between the two points is:
p
distance = (y2 − y1 )2 + (x2 − x1 )2
We can write a Python script to determine the distance between the two points (x1 , y1 )
and (x2 , y2 ) either by interactive or a scripting method. In interactive method we can do
as follows:
>>> x1=3
>>> y1=4
>>> x2=7
>>> y2=7
>>> distance=((y2-y1)**2+(x2-x1)**2)**0.5
>>> print(distance)
5.0
>>>
In scripting method, we can type in a function that will determine the distance between
the two points (x1 , y1 ) and (x2 , y2 ) as follows:
Program 1.
x1 = int(input("Enter x1:"))
y1 = int(input("Enter y1:"))
x2 = int(input("Enter x2:"))
y2 = int(input("Enter y2:"))
u = x2−x1
v = y2−y1
dist = (u∗u+v∗v)∗∗0.5
print("distance between(%d,%d) and (%d,%d) = %f" %(x1,y1,x2,y2,dist))
The above function together with its corresponding invocation script is called a python
module which shall be saved as a python file(with a .py extension) and it is possible to
run this module by pressing the <F5> key from the terminal
Output.
============= RESTART: /python/distant.py ==
5.0
>>>
Thus the given python module returned the value of the distance between the two points
(3,4) and (7,7).
7. Explain in detail about conditional statements in python. Develop a Python
program to find the largest among three numbers.
51
Unit II Big Questions 20CS101 – Problem Solving using Python Programming
Decision making constructs begins with a Boolean expression, an expression that returns
either True or False. In Python programming zero and null values are assumed as false.
Decision making structures are necessary to perform an action or a calculation only when
a certain condition is met. In Python we have the following types of decision making
statements. They are: 1. if statement
2. if ... else statements 3. if ...elif statements 4. Inline if
5. Nested if ... elif ... else statements
Conditional if Statement
Conditional if statement starts with a Boolean expression followed by statement or a
group of statements, which evaluates the ’if’ expression and executes the body of the
program only if the evaluation is TRUE. If the Boolean expression evaluates to FALSE,
then the next code after the end of if statement will be executed. In Python, the body of
if statements were indicated by the indentation. It starts with an indentation and ends
with the first un-indented line. Refer Figure 18a. at page 36
Example 11. number = int(input("Enter any number from the Keyboard: "))
if number> 50:
print ("Passed")
52
Unit II Big Questions 20CS101 – Problem Solving using Python Programming
Test
False
Expression
True
if elif False
Block Expression
True
elif Block
else Block
else :
print("num is greater than 150")
53
Unit II Big Questions 20CS101 – Problem Solving using Python Programming
for each
item in Enter while loop
sequence
Last
Yes Test False
item
Expression
reached?
No True
When Python runs a for loop, it assigns the items in the iterable object to the target
one by one and executes the loop body for each. The loop body typically uses the
assignment target to refer to the current item in the sequence as though it were a cursor
stepping through the sequence. See Figure 23a Consider the following example:
>>> for c in 'spam':
print(c.upper())
S
P
A
M
Looping through an iterable
In Python, an iterable refers to anything that can be looped over such as a string, list or
tuple and it has the _iter_method defined.
54
Unit II Big Questions 20CS101 – Problem Solving using Python Programming
Explanation
The first time the program(See Listing 3) runs through for loop, it assigns ’Li’ to the variable
metal. The statement print(metal) then prints the value ’Li’. The second time the program
loops through for statement, it assigns the value ’Na’ to metal and prints the value ’Na’. The
program continues looping through the list until the end of the list is reached.
Looping through a sequence of numbers
To loop through a sequence of numbers in the form of a list, the built-in range() function is
used to iterate over for loops.
Syntax
range(start , end, step)
range() function produces the list iterates of numbers starting with start (inclusive) and
generate numbers with one less than the number end ; step: It is the difference between each
number in the sequence. It can be negative and positive, but not zero.
If start is not given, the numbers will start from zero. If step is not specified, a list of
consecutive numbers will be generated. Refer Example 14
Example 14. .
>>range(5)
>>list(range(5))
# If the Start value is not specified.
# It generates from 0 to end
>>range(3,10)
>>list(range(3,10))
# It starts from 3 ends with one less than the end (10)
>> range(4, 10, 2)
>>list(range(4,10,2))
#It generates the value from 4 (start) to 10 (end)
# with an increment of 2(step)
Output.
[0,1,2,3,4]
[3,4,5,6,7,8,9]
[4,6,8]
for num in range(5):
print(num,end=' ')
Output.
0 1 2 3 4
for loop with else
Python supports to have an else statement associated with a loop statement. If the else
statement is used within for loop, it gets executed when the loop has finished iterating the
list. A break statement terminates for loop iteration. See Program 2
Program 2.
55
Unit II Big Questions 20CS101 – Problem Solving using Python Programming
Example 15.
n = int(input("Enter the upper limit : "))
s =0
i =1
while (i <= n):
s =s+i
i =i +1
print ("Sum of first ", n, "natural numbers is", s)
Output.
56
Unit II Big Questions 20CS101 – Problem Solving using Python Programming
while test_expression :
while test_expression :
Statement(s)
Statement(s)
Program 4.
# Program to generate prime numbers using for loop
num = int(input("Enter a Limit:"))
for a in range(1,num):
k = int(a/2)
for b in range(2, k + 1):
if a % b == 0:
break
else :
print(a,end=" ")
Output. Enter a Limit:30
1 2 3 5 7 11 13 17 19 23 29
Program 4 illustrates generating prime numbers, using nested loop and a break statement.
9. Explain break and continue statement with the help of for loop in an example.
CONTROL STATEMENTS
Control statements change the execution from normal sequence. i.e. It controls the flow
of program execution to get desire behaviour or result. Loops iterate over a block of code
until test expression is false, but sometimes we wish to terminate the current iteration or
even the whole loop without checking test expression. The break and continue statements
are used in these cases. Python supports the following three control statements:
1) break
57
Unit II Big Questions 20CS101 – Problem Solving using Python Programming
2) continue
3) pass
Control statement Meaning
It terminates the loop statement and transfers execution to
break
the statement immediately following the loop.
Causes the loop to skip the remainder of its body and
continue
immediately retest its condition prior to reiterating.
The pass statement in Python is used when a statement is
pass required syntactically but we do not want any command or
code to execute.
Break Statement
A break statement is used to end the current loop and instruct Python to execute the
statement after the loop. If it is inside a nested loop (A loop inside another loop), break
will terminate the innermost loop(Figure 24). It can be used with both for and while
loops. It is commonly used when a quick exit is required.
Enter
while
or for
loop
Range or
other True
Expressions
Rest of
if False
for / while
Condition?
iterations
False
True
break
Continue Statement
The continue statement skips remaining statement(s) in the present iteration and directs
the program to the next iteration. continue returns the control to the beginning of the
loop. The continue statement rejects all the remaining statements in the current iteration
of the loop and moves the control back to the top of the loop. The continue statement
58
Unit II Big Questions 20CS101 – Problem Solving using Python Programming
Example 16.
num = 0
breakn = int(input("Enter when to break(n<10):"))
while (num < 10):
if (num == breakn):
break
print(num,end =" ")
num = num + 1
print("End of Program")
Output.
Enter when to break(n<10):4
0 1 2 3 End of Program
Explanation
In example 16, "if (num == breakn): break" will run the "break" command if num is 4,
the break statement will exit from the while loop, and run "print(End of Program")
The continue statement
Enter
while
or for
loop
Range or
other True
Expressions
Rest of
if False
for / while
Condition?
iterations
False
True
continue
The continue statement causes an immediate jump to the top of a loop(figure 25). It
59
Unit II Big Questions 20CS101 – Problem Solving using Python Programming
also sometimes lets us avoid statement nesting. Example 17, uses continue to skip odd
numbers. This code prints all even numbers less than 10 and greater than or equal to 0.
Also, we must remember that the value 0 means False thus it terminates the while loop
when x decrements to 0
Example 17.
x = 10
while x:
x = x−1 # Or, x −= 1
if x % 2 != 0:
continue # Odd? −− skip print
print(x, end=' ')
Output.
8 6 4 2 0
>>>
10. Differentiate for loop and while loop.
for loop while loop
for is designed to iterate across items in a The while loop is a general looping
sequence or other iterable statement
The for loop will run exactly n times The while loop will not run n times
The for loop in python is very powerful so
while loop is rarely used
it is very frequently used
60