0% found this document useful (0 votes)
18 views

PSPP Unit 1 and 2 - short and big question

The document outlines the course structure for 'Problem Solving using Python Programming' at K.L.N. College of Engineering, detailing objectives, units, outcomes, and recommended textbooks. It covers fundamental computer concepts, Python programming constructs, data structures, file handling, and exception management. The course aims to equip students with problem-solving skills using Python through various illustrative programs and algorithms.

Uploaded by

Anand Duraiswamy
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)
18 views

PSPP Unit 1 and 2 - short and big question

The document outlines the course structure for 'Problem Solving using Python Programming' at K.L.N. College of Engineering, detailing objectives, units, outcomes, and recommended textbooks. It covers fundamental computer concepts, Python programming constructs, data structures, file handling, and exception management. The course aims to equip students with problem-solving skills using Python through various illustrative programs and algorithms.

Uploaded by

Anand Duraiswamy
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/ 61

K.L.N.

COLLEGE OF ENGINEERING
(An Autonomous Institution – Approved by AICTE, New Delhi and Affiliated
to Anna University, Chennai)

Department of Computer Science and Engineering


I Year Computer Science and Engineering

20CS101 – Problem Solving using Python


Programming

Python Handlers of KLNCE

December 18, 2020


20CS101 – Problem Solving using Python Programming

20CS101 PROBLEM SOLVING USING PYTHON PROGRAMMING L T P C


3 0 0 3
OBJECTIVES:
• To know the basics of Computers and algorithmic problem solving
• To understand Python programs with conditional and looping constructs.
• To define Python functions and strings.
• To use Python data structures — lists, tuples, set and dictionaries.
• To do input/output with files in Python.

UNIT I COMPUTER FUNDAMENTALS AND PROBLEM SOLVING 9


Introduction to computer system – Block Diagram of Computer, Types of Memory, I/O Devices,
Application Programs, System Programs – Loader, linker, assembler, compiler, interpreter,
Programming process – source code to executable code, Problem Solving Strategies – Problem
analysis, Algorithms, Flow Charts, Pseudo Code. Illustrative problems: odd or even number, Leap
year, Biggest of three numbers, square root of a number, Sum of n numbers, Armstrong number,
Palindrome, Fibonacci Series, Prime number, Bubble Sort and Linear Search.
UNIT II DATA, EXPRESSIONS, CONTROL-FLOW STATEMENTS 9
Python interpreter and interactive mode; values and types: int, float, boolean, string,
and list; variables, expressions, statements, tuple assignment, operators and precedence
of operators, comments. Control Flow Statements – Conditional (if), alternative(if-else),
chained-conditional(if-elif-else); Iteration: state, while, for, break, continue, pass; Illustrative
programs: exchange the values with and without using temporary variables, circulate the values
of n variables, distance between two points.
UNIT III FUNCTIONS, STRINGS 9
Functions – function definition and use, flow of execution, parameters and arguments; function
composition, Fruitful functions: return values, parameters, local and global scope, recursion; Strings:
string slices, immutability, string functions and methods, string module; Illustrative programs: square
root, GCD, exponentiation, Factorial of a number, linear search, binary search.
UNIT IV LISTS, TUPLES, SETS, DICTIONARIES 9
Lists: list operations, list slices, list methods, list loop, mutability, aliasing, cloning lists, list
parameters; Tuples: tuple assignment, tuple as return value;Sets - Creating a set, Modifying a
set, Removing elements from a set, Set operations- Set Union, Set intersection, Set difference, Set
membership test, Iterating through a set, Set methods, Built-in functions with set, Frozenset –
Dictionaries: operations and methods; advanced list processing - list comprehension; Illustrative
programs: selection sort, insertion sort, Matrix addition and subtraction, sum and array of numbers.
UNIT V FILES, MODULES, PACKAGES 9
Files and exception: text files, reading and writing files, format operator; command line arguments,
errors and exceptions, handling exceptions, modules, packages; Illustrative programs: word count,
copy file, merge two files.
TOTAL: 45 PERIODS

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

Unit I Big Questions 19

Unit II Short Questions 28

Unit II Big Questions 39

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

8 Logical Operators and their usage . . . . . . . . . . . . . . . . . . . . . . . . . . 48


9 Membership Operators and their usage . . . . . . . . . . . . . . . . . . . . . . . 48
10 Identity Operators and their usage . . . . . . . . . . . . . . . . . . . . . . . . . 49
11 Operator Precedence . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 50

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

Unit I Short Questions


Introduction to computer system
1. List the four parts of a complete computer system.

(a) Hardware (c) Data


(b) Software (d) Users

2. Differentiate between analog and digital computers.


Analog Digital
The data is represented in the form of Data is stored in terms of 0s and 1s.
electrical pulses.
The electronic circuit employed in This consists of ALU, control unit, a
the analog computer is an operational memory unit and I/O units.
amplifier.
3. Draw the block diagram of a computer
The block diagram of a computer is shown in Figure 1. The Input Unit receives the
input, the CPU processes the input using the memory Unit and outputs the result in the
Output Unit.

Input Unit CPU Output Unit

Memory Unit

Figure 1: Block diagram of a Computer

4. Give a detailed block diagram of a Computer.


See Figure: 2
5. Define the characteristics of computers.
The human race developed computers so that they can perform some intricate tasks such
as calculation and data processing. The following aspects determine the desirable features
for human development:
• Speed: The speed of a computer is calculated as MIPS Millions of Instructions per
second they are possible using with clocks of speed in Gigahertz(GHz)
• Accuracy: The accuracy depends on how precise the answers are produced which
depends on the capabilities of the processing units being used in the CPU.
• Diligence: The computer does not suffer from the human traits of tiredness and
lack of concentration. If 10 billion calculations are performed now and then it will
perform the next 10 billion operations with the same accuracy and speed.

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

Figure 2: Detailed Block Diagram of a Computer

• Reliability: This is the measurement of the performance of the computer, which


is found at a predetermined interval of operations without any failures. This factor
is mostly at the hardware level. Also recent computers have built-in self diagnostic
capabilities, which help in continuous monitoring.
• Storage: Computers can store large amount of data and can recall the required
information almost instantly
• Versatility: Computers are versatile in nature. They can perform multiple tasks
simultaneously with great ease. For example, they can edit a document, play music,
and print a letter on the printer.
• Resource Sharing: Initially, computers were isolated machines but, now a days
computers can share several resources like weather, maps, printing videos and music
among several users.
Also computer parts require regular check-ups and maintenance to give correct results
also they have to be kept in clean – dust free places and at proper ambient temperature.
6. Explain Stored Program concept.
Old computers were known as program-controlled machines in which writing new program
or changing existing program require restructuring or redesigning the machines. Thus
programming these computers was a tedious task. To ease the programming process,
stored program concept was proposed by mathematicians and an early computer
scientist John Von Neumann. According to this concept, both data and instructions are
kept in the main memory. Thus, a computer could get its instructions from the memory
and the programs could be setup or changed from within the memory as well, without
having to redesign the computer.

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.

(a) Desktop computers (d) Tablet computers


(b) Workstations (e) Handheld computers
(c) Notebook computers (f) Smart phones

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.”

Types of Memory and I/O Devices


11. Mention the key factors that characterize the memory.
The memory is characterized on the basis of two key factors—capacity and access time.
Capacity is the amount of information (in bits) that a memory can store. Access time is
the time interval between the read/ write request and the availability of data. The lesser
the access time, the faster is the speed of memory. Ideally, we want the memory with
fastest speed and largest capacity. However, the cost of fast memory is very high. The
computer uses a hierarchy of memory that is organized in a manner to enable the fastest
speed and largest capacity of memory.
12. Mention the different range of binary values and their names. What is a
terabyte?
The terabyte (TB) is 1,099,511,627,776 (240 ) bytes, although communications and secondary
storage systems developers started using the term to mean 1,000,000,000,000 (1012 ) bytes.
To reduce confusion, we now use the term tebibyte (TiB) for 240 bytes, defining terabyte
(TB) to mean 1012 bytes. Figure 3 shows the full range of decimal and binary values and
names.

7
Unit I Short Questions 20CS101 – Problem Solving using Python Programming

Decimal Abbreviation Value in Binary Abbreviation Value in


term power of term power of
10 2
kilobyte KB 103 kibibyte KiB 210
megabyte MB 106 mebibyte MiB 220
gigabyte GB 109 gigibyte GiB 230
terabyte TB 1012 tebibyte TiB 240
petabyte PB 1015 pebibyte PiB 250
exabyte EB 1018 exbibyte EiB 260
zettabyte ZB 1021 zebibyte ZiB 270
yottabyte YB 1024 yobibyte YiB 280

Figure 3: Range of binary values and their names

13. Mention the storage capacities of the following devices:


(a) Floppy disc
(b) CDROM disc
Ans:
(a) 1MB
(b) 640MB(normal disk), 4-8GB(DVD disc)
14. List out the different types of memory used in a desktop computer.

Figure 4: Memory types over the period of time

(a) Primary memory


i. RAM(Random Access Memory)
• SRAM(Static RAM)
• DRAM(Dynamic RAM)
ii. ROM(Read Only Memory)
• PROM(Programmed ROM)
• EEPROM(Electrically Erasable Programmable ROM)

8
Unit I Short Questions 20CS101 – Problem Solving using Python Programming

(b) Secondary Memory


• HDD(Hard Disk Drive)
• SSD(Solid State Drive)
• CD(Compact Disk)
• FD(Floppy Disk)
• MT(Magnetic Tape)

Application Programs, System Programs


Loader, linker, assembler, compiler, interpreter
15. Define a program.
A program is a set of instructions written for performing a specific task. However, writing
a good program is not a straightforward task.
16. What is system software?
System software provides basic functionality to the computer. System software is required
for the working of computer itself. The user of computer does not need to be aware about
the functioning of system software, while using the computer. For example, when you
buy a computer, the system software would also include different device drivers.
17. Describe the two categories of system software.
System software for the management and functionality of computer relates to the functioning
of different components of the computer, like, processor, input and output devices etc.
System software for the development of application software provides services required
for the development and execution of application software. System software provides the
software tools required for the development of application software.
18. What is the need of an operating system?
Operating System (OS) is an important part of a computer. OS intermediates between
the user of a computer and the computer hardware. Different kinds of application software
use specific hardware resources of a computer like CPU, I/ O devices and memory, as
needed by the application software. OS controls and coordinates the use of hardware
among the different application software and the users. It provides an interface that is
convenient for the user to use, and facilitates efficient operations of the computer system
resources.
19. Describe the functions of an operating system.
It provides an environment in which users and application software can do work. It
manages different resources of the computer like the CPU time, memory space, file storage,
I/ O devices etc. During the use of computer by other programs or users, operating system
manages various resources and allocates them whenever required, efficiently. It controls
the execution of different programs to prevent occurrence of error. It provides a convenient
interface to the user in the form of commands and graphical interface, which facilitates
the use of computer.
20. Define a device driver.

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

Compiler and interpreter convert a program written in high-level language to machine


language. Compiler is the software that translates the program written in a high-level
language to machine language. The program written in high-level language is referred
to as the source code and compiled program is referred as the object code. The object
code is the executable code, which can run as a stand-alone code. It does not require
the compiler to be present during execution. Each programming language has its own
compiler. Some languages that use a compiler are C++, COBOL, Pascal, and Python.
35. How does an interpreter work?
Interpreter performs line-by-line execution of the source code during program execution.
Interpreter reads the source code line-by-line, converts it into machine understandable
form, executes the line, and then proceeds to the next line. Some languages that use an
interpreter are BASIC and Python.
36. Name two high-level languages that use compiler for translation.
C++ and Pascal
37. Name two high-level languages that use interpreter for translation.
BASIC and Python
38. What is the purpose of linker?
Linker is a program that links several object modules and libraries to a single executable
program. A source code of a program is often very large consisting of several hundred or
more lines. The source code may also include reference to libraries. All these independent
modules may not be stored in a single object file. The code is broken down into many
independent modules for easy debugging and maintenance. Before execution of the
program, these modules and the required libraries are linked together using the linker
software. The compiled and the linked program are called the executable code.
39. What is the purpose of loader?
loader software is used to load and re-locate the executable program in the main memory.
Software has to be loaded into the main memory during execution. Loader assigns storage
space to the program in the main memory for execution.
40. Difference between compiler and interpreter
• The key differences between a compiler and an interpreter are as follows: Interpreter
looks at a source code line-by-line. Compiler looks at the entire source code.
• Interpreter converts a line into machine executable form, executes the line, and
proceeds with the next line. Compiler converts the entire source code into object-code
and creates the object code. The object code is then executed by the user.
• For a given source code, once it is compiled, the object code is created. This object
code can be executed multiple number of times by the user. However, interpreter
executes line-by-line, so executing the program using an interpreter means that
during each execution, the source code is first interpreted and then executed.
• During execution of an object code, the compiler is not required. However, for
interpretation, both interpreter and the source code is required during execution
(because source code is interpreted during execution).

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).

Problem Solving Strategies


Problem analysis, Algorithms, Flow-Charts, Pseudocode
43. Give an informal definition about an algorithm.
An algorithm is any well-defined computational function that takes some value, or set of
values, as input and produces some value, or set of values, as output. An algorithm is
thus a sequence of computational steps that transform the input into the output.
44. Point out an example problem solved by computer algorithm.
The Human Genome Project has made great progress toward the goals of identifying all
the 100,000 genes in human DNA, determining the sequences of the 3 billion chemical base
pairs that make up human DNA, storing this information in databases, and developing
tools for data analysis. Each of these steps requires sophisticated algorithms. The
Internet enables people all around the world to quickly access and retrieve large amounts
of information. With the aid of clever algorithms, sites on the Internet are able to manage
and manipulate this large volume of data.

13
Unit I Short Questions 20CS101 – Problem Solving using Python Programming

45. Give an example of a sorting problem.


Input: A sequence of n numbers a1 , . . . , an Output: A permutation or reordering < a01 , . . . , a0n >
such that for every i < j, a0i ≤ a0j .
46. Define the concept of an array.
An array is much analogous to a street with row of houses. The attribute that all the
houses share is the name of the street. Each house in the street has a unique address which
distinguish it from other houses in the street. Thus the adress is made up of two parts,
the street and the number of the lot. The street name corresponds to the array name and
the street number corresponds to the suffix. The house at each address corresponds to the
memory storage unit or computer word(or byte) at each address in the array. People and
furniture are "stored" in the houses and we store numbers or characters in fixed length
binary representation in the array locations. It is a copy of the number or characters
stored in an array location that we retrieve when we reference a particular array location
by specifying its array name and suffix. The processing of arrays is simplified by using
variables to specify suffixes.
47. Name the three steps in solving a problem.
(i) Understand the problem (ii) Find the connection between the data and the unknown
– devise a plan(iii) carry out the plan and examine the solution obtained.(iv) look back
– check if there are more approaches.
48. State the purpose of problem solving through computers.
Computers are very fast in solving problems. The Computer calculates with great
accuracy. A Computer produces results without any error. A repetitive calculation is
performed with the same accuracy for any number of times in a Computer. That is why
Computers are used in solving problems.
49. List the characteristics of a good algorithm.
The properties of Algorithm are: 1) There must be no ambiguity in any instruction.2)
There should not be any uncertainty about which instruction is to be executed next. 3)
The algorithm should conclude after a finite number of steps. An algorithm cannot be
open-ended. The algorithm must be general enough to deal with any contingency.

Instructions/statements, state, control flow, functions, notation,


pseudocode, flowchart, programming language.
50. Define the term ‘pseudo-code’
Pseudocode is not the actual name but it models and may even look like programming
code. It is the generic way of describing an algorithm without using any programming
language related notations. Or, more simply it is the outline of the program, written in
a form that can be easily converted into real programming statements.
51. Mention the need for pseudocodes.
For developing an effective algorithm, flowcharts and pseudocodes are used by programmers.
They are further expressed in programming languages to develop computer programs.
52. What is meant by computational complexity of an algorithm?
It is the execution time of the algorithm in terms of its input parameters.

14
Unit I Short Questions 20CS101 – Problem Solving using Python Programming

53. Give the advantages and limitations of flowchart.


Advantages: it makes the logic clear and visual. It communicates the interconnection of
the logical system. The problem can be well analysed. Useful for coding the problem.
Testing and debugging is easily done. Flowcharts are good programming documentation
for future reference. Disadvantages: it is complicated. It is costly and difficult to modify
in future and no updates are easy to do.
54. Give the advantages and limitations of pseudocode.
Advantages: it is language independent. It is easier to develop program from pseudocode
than from flowchart. It is very compact than a flowchart. Limitations: Pseudocode may
vary for different programming languages thus it is implementation specific so not every
developer can understand.
55. Name the three basic program control structures.
Sequence, selection and repetition. See Figure 9, 10, 11
56. Write the algorithm for finding the sum of any two numbers
Let the two numbers be A and B and let their sum be equal to C. Then, the desired
algorithm is given as follows:
1. START
2. PRINT “ENTER ANY TWO NUMBERS”
3. INPUT A,B
4. C ← A + B
5. print C
6. STOP

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

58. Write an algorithm to print the largest of 3 numbers.


Let the three numbers be represented by A, B, and C. There can be three ways of solving
the problem. The three algorithms, with some differences, are given Algorithm 1 is
represented in a flow-chart as in Figure 8. Algorithm 2 uses ’AND’ operator to simplify
the logic of execution: The Algorithm 3 uses a variable MAX to store the largest number
to reduce the steps.

15
Unit I Short Questions 20CS101 – Problem Solving using Python Programming

Algorithm 1: Largest of the three numbers


1. print “Enter Three Numbers”
2. INPUT A, B, C
3. if A > B then
4. if A > C then
5. print A
6. else
7. if C > B then
8. print C
9. else
10. print B
11. else
12. if B > C then
13. print B
14. else
15. print C

Algorithm 2: Largest of three using and operator


1. START
2. print "ENTER THE THREE NUMBERS A, B, C"
3. READ A, B, C
4. if A > B and A > C then
5. print A
6. if B > C and C > A then
7. print B
8. else
9. print C
10. STOP

59. List few of the flow-chart symbols:


See Figure 5
60. Mention the guidelines for drawing flow-charts.
• In drawing a proper flowchart, all necessary requirements should be listed out in a
logical order.
• There should be a logical start and stop to the flowchart.
• The flowchart should be clear, neat, and easy to follow. There should be no ambiguity
in understanding the flowchart.
• The usual direction of the flow of a procedure or system is from left to right or top
to bottom.
• Only one flow line should emerge from a process symbol see Figure 6.
61. Mention the advantages and limitations of using flow-charts
Advantages of using flowcharts
• Communication Flowcharts are a better way of communicating the logic of a system
to all concerned.

16
Unit I Short Questions 20CS101 – Problem Solving using Python Programming

Algorithm 3: Largest of Three using variable MAX


1. START
2. print “ENTER THREE NUMBERS”
3. INPUT A, B, C
4. M AX ← A
5. if B > M AX then
6. M AX ← B
7. if C > M AX then
8. M AX ← C
9. print M AX
10. STOP

Start

Input Process

Decision Output

Stop

Figure 5: Flow-Chart Symbols

• 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

Figure 6: Flow-Chart Rules

• 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

Figure 7: Flow-Chart for Sum of 50 natural numbers

63. Draw a flowchart to find the largest of three numbers A, B, and C.


See Figure: 8
64. Give comment on pseudocode and actual/real code

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

PRINT B PRINT C PRINT A

STOP

Figure 8: Flow-Chart for Largest of 3 numbers

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.

Unit I Big Questions


Algorithms, building blocks of algorithms
1. List and explain the steps that a programmer follows in writing a program.
Problem Analysis — The programmer first understands the problem to be solved. The
programmer determines the various ways in which the problem can be solved, and decides
upon a single solution which will be followed to solve the problem.
Program Design — The selected solution is represented in a form, so that it can be
coded. This requires three steps —
• An algorithm is written, which is an English-like explanation of the solution.
• A flowchart is drawn, which is a diagrammatic representation of the solution. The
solution is represented diagrammatically, for easy understanding and clarity.

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

then after execution of the assignment a ← b we have


a : 456 b : 456
The assignment (1) has changed the value of a but has left the value of b untouched.
Checking with our target configuration we see that a has assumed the value 456 as
required. So far so good! We must also check on b. When the assignment step (2)
i.e. b ← a is made after executing step (1) we end up with:
a : 456 b : 456
In executing step (2) a is not changed while b takes on the value that currently belongs
to a. The configuration that we have ended up with does not represent the solution we
are seeking. The problem arises because in making the assignment:
a←b
we have lost the value that originally belonged to a (i.e. 123 has been lost). It is this value
that we want b to finally assume. Our problem must therefore be stated more carefully
as:
new value of a ← old value of b;
new value of b ← old value of a
What we have done with our present proposal is to make the assignment
new value of b ← new value of a.
In other words when we execute step (2) we are not using the value a, that will make
things work correctly—because a has already changed. To solve this exchange problem,
we need to find a way of not destroying "the old value of a" when we make the assignment
a←b
A way to do this is to introduce a temporary variable t and copy the original value of a
into this variable before executing step (1). The steps to do this are:

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

Figure 9: Flow-Chart for Sequence Construct

Test True Test False


Expression False Expression

True Statement1 Statement2

Statement

(a) if expression branching (b) if expression . . . else. . . branching

Figure 10: Branching Process

Repetition: Repetition or loop pattern causes an interruption in the normal sequence


of processing (Figure 11) It directs the system to loop back to a previous statement in the
program, repeating the same sequence over and over again, usually with new data. When
a sequence of statements is repeated against a condition, it is said to be in a loop. Using
looping, the programmer avoids writing the same set of instructions again and again.
The looping process can either be one time or multiple times until the desired output is
obtained(or, the given condition is satisfied) within a single program.
In the Figure 11 we have two types of repetition or looping – the first one Figure 11a is
a post test loop(also known as repeat . . . until loop) and the second one Figure 11b is
a pre test loop(also known as a while loop).
The following example,(Figure 12), prints the first 10 natural numbers. Notice that at
the beginning, the value of COU N T variable is initialized to zero. After that, COU N T
is incremented by one and the value is printed. If the value of COU N T is less than 10
(which represents the count of numbers to be displayed) then the same process is repeated.
At the conclusion of each iteration, the condition is evaluated, and the loop repeats until
the condition becomes true. The loop terminates when the condition becomes false.

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

Figure 11: Repetition Process

5. Develop an algorithm and flowchart to find the minimum and maximum in a


list of numbers.
Before we begin to work on the algorithm for finding the maximum we need to have a
clear idea of the definition of a maximum. To start on the algorithm development for
this problem, let us examine a particular set of numbers. After studying this example we
can conclude that all numbers need to be examined to establish the maximum. A second
conclusion is that comparison of the relative magnitude of numbers must be made. Here
we are using an array technique to solve our problem. An array is much analogous to a
street with row of houses. The attribute that all the houses share is the name of the street.
Each house in the street has a unique address which distinguish it from other houses in
the street. Thus the adress is made up of two parts, the street and the number of the
lot. The street name corresponds to the array name and the street number corresponds
to the suuffix. The house at each address corresponds to the memory storage unit or
computer word(or byte) at each address in the array. People and furniture are "stored"
in the houses and we store numbers or characters in fixed length binary representation in
the array locations. It is a copy of the number or characters stored in an array location
that we retrieve when we reference a particular array location by specifying its array name
and suffix. The processing of arrays is simplified by using variables to specify suffixes.
In processing a particular array it does not matter what name we give the array suffix –
it is only the suffix value which determines which array location is referenced(i.e. if the
variables i and j both have the value 19, then the references a[i] and a[j] both reference
the same array location which is a[19]). In the problem let us use the term list in the
place of an array
In this algorithm let us use the function length(list) see Algorithm 4 which will return
the length of the argument list. Let us also use two variables called min and max which
will hold the minimum and maximum of the list/array under consideration. The while
loop can be used to traverse over the list in checking the values of the variables in and
update the min and max variables as and when we come across a smaller and larger values.
The index variable i which is initialised as 0 before the entry into the while loop will be
incremented by 1 each step as the loop advances in the list. The flowchart is shown in
Figure 14

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

Is COU N T < 10?


Yes

No
Stop

Figure 12: Flow-Chart to Print first 10 numbers

a[0] a[1] a[8]

8 6 5 15 7 19 18 6 13

Figure 13: Finding the maximum of a list of n numbers

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

Algorithm 4: Find maximum and minimum of a list of numbers


1. Read a list of numbers
2. min ← list[0]
3. max ← list[0]
4. i ← 0
5. length ← lengthof list
6. while i < length do
7. if min > list[i] then
8. min ← list[i]
9. if max < list[i] then
10. max ← list[i]
11. i←i+1
12. print min, max

Algorithm 5: Factorial Algorithm(Iterative)


1. READ n // n ≤ 0
2. i ← 0
3. f act ← 1
4. while i < n do
5. i←i+1
6. f act ← i × f act
7. print f act

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".

Algorithm 6: Leap Year Algorithm


1. START
2. Get year
3. if ((year % 4 == 0) and (year % 100 != 0)) or (year % 400 == 0) then
4. print year is a leap year
5. else
6. print year is not a leap year
7. STOP

8. Find an algorithm to determine the square root of a number.


This is a famous problem during the first century B.C. at Rome. Given a number its
square root is something that when multiplied with other gives the number itself! That
is if x be the square root of a number, then x2 is equals that number. But how to find
the value of x? Refer algorithm 7, 8
9. Describe the characteristics of programming languages.
computer needs to be instructed using computer programs to perform all its tasks; for

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

PRINT min, max

STOP

Figure 14: Flow-Chart for Minimum and Maximum of a list of numbers

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

Figure 15: Flow-Chart to calculate Factorial n

Algorithm 7: Square Root Algorithm


1. Get x
2. Start with a guess, g. If g × g is close enough to x, stop and say that g is the answe
3. Otherwise create a new guess by averaging g and x/g, that is (g+x/g)
2
.
4. Using this new guess, which we again call g, repeat the process until g × g is close enough
to x.

Algorithm 8: Square Root of a number(another version)


1. Start
2. Get x
3. Let epsilon = 0.0001
4. guess = 1.0
5. while absoluteValue(guess*guess - x) > epsilon) do
6. guess = (x/guess + guess)/2
7. print "The squareRoot of x is guess"
8. End

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.

Unit II Short Questions


DATA, EXPRESSIONS AND CONTROL FLOW STATEMENTS
Python Interpreter and interactive mode
1. Give a brief description about Python.
Python is a high-level, interpreted, interactive and object-oriented language. Python
is designed to be highly readable. It uses English keywords frequently whereas other
languages use punctuation, and it has fewer syntactical construction than other languages.
2. Mention the six main reasons why people choose to use Python.
Software quality, developer productivity, program portability, support libraries, component
integration, and simple enjoyment. Of these, the quality and productivity themes seem
to be the main reasons that people choose to use Python.
3. Name some of the features of python.
Following are some of the salient features of python;
• It supports functional and structured programming methods as well as OOP. ıtem
It can be used as a scripting language or can be compiled to byte-code for building
large applications.
• It provides very high-level dynamic data types and supports dynamic type checking.
• It supports automatic garbage collection.
• It can be easily integrated with C, C++, ActiveX, CORBA, and Java.
4. Mention the different ways of running python program in windows and linux/MacOS
systems.
In Windows 10

• In windws 10, PowerShell, Python can be installed


• Using Visual Studio code development environment, we can execute python code
using VS editor.
• If we want to collaborate with others in coding python in projects, we can have a
github console environment in windows.
• Using IDLE, Integrated Development Environment, we can execute python programs
by having two windows like shell window and an editor window for testing Python
programs.
In Linux
• IDLE is available in Linux also.
• ipython is very popular for teaching/learning python. Also for machine learning
researches — ipython is being used in the Google cloud.

28
Unit II Short Questions 20CS101 – Problem Solving using Python Programming

5. Mention the use of IDLE tool.


The IDLE tool offers a more efficient platform to write code and work interactively with
Python. We can access IDLE on the same folder or the command line icon or on the start
menu.
6. Explain the steps to exit from Python.
To exit from Python, you can type any of these commands:
• quit()
• exit()
Control-Z then press enter key.
7. Mention about the Python interpreter
The Python interpreter is a program that runs the Python programs we write.
8. Define a source code. What is byte code?
Source code is the statements we write for our program—it consists of text in text files
that normally end with a .py extension. Byte code is the lower-level form of our program
after Python compiles it. Python automatically stores byte code in files with a .pyc
extension.
9. Explain briefly about the Python Virtual Machine(PVM)
The PVM is the Python Virtual Machine – the runtime engine of Python that interprets
our compiled byte code.
10. Mention the two ways of Using Python Interpreter.
Interactive mode - Interactive mode is a command line shell which gives immediate
feedback for each statement, while running previously fed statements in active memory.
Script mode - A script mode can store code in a file and it uses the interpreter to execute
the contents of file.
11. Explain the steps involved to run a script from within IDLE.
Within the text edit window of the file we wish to run, we must select the window’s
Run→Run Module menu option. This runs the window’s source code as a top-level script
file and displays its output back in the interactive Python shell window.

Values and Types


12. Define data types.
Data type is a set of values and allowable operations on those values. Data types allow
programming languages to organize different kinds of data.
13. Name the four types of scalar objects Python has.
int Any integer. float Floating point number (64 bit precision) complex Numbers with
an optional imaginary component. bool True, False str A sequence of characters (can
contain unicode characters).
14. Name four of Python’s core data types.

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).

Variables and Expressions


15. List out the rules used for naming a variable in python.
• Variable names can only contain upper case (A-Z), lower case (a-z) letters digits
(0-9) and underscore characters.
• Variable names are case sensitive
• Numbers are allowed, but they should not be used at the beginning of the variable
name.
• Camel case notation or underscores can be used. Camel case is the practice of writing
compound words with mixed casing.
• No special symbols other than underscore are allowed.
• Reserved keywords cannot be used as a variable name
16. Describe the way to assign a value to a variable in python.
The equal sign (=) is used to assign values to variables. The operand to the left of =
operator is the name of the variable and the operand to the right of = operator is the
value stored in that variable. Syntax: <variable name> = <value>
17. Define Keywords.
Keywords or reserved words are special commands that compiler/interpreter understands
and these reserve words cannot be used as a const variable, or any other identifier names.
There are 33 keywords.
18. Define Identifiers.
An identifier is a name used to identify a variable, function, class, module or any other
object. It helps differentiating one entity from another.
19. Explain about “Immutable”, and mention the three Python’s core types that
are considered immutable.
An “immutable” object is an object that cannot be changed after it is created. Numbers,
strings, and tuples in Python fall into this category. While we cannot change an immutable
object in place, we can always make a new one by running an expression. Byte arrays in
recent Pythons offer mutability for text, but they are not normal strings, and only apply
directly to text if it’s a simple 8-bit kind (e.g., ASCII).
20. Define multiline statement in Python.
A multiple line expression is a single statement by wrapping the lines inside braces
{},square brackets [ ] and parentheses ( ).
21. Write the syntax for the Python output function.
print("<expression>")
#multiple expressions

30
Unit II Short Questions 20CS101 – Problem Solving using Python Programming

print("<expression>,<expression>")
print("<expression>",<variable name>)

22. Define raw_input() with syntax


The raw_input([prompt] ) function reads one line from standard input and returns it as
a string(removing the trailing new line). This is used in Python 2.X
Syntax: variable_name = raw_input("<prompt: Input Statement>")
23. Describe how to import modules in Python?
A module is a built-in file containing python definitions and statements with the .py
extension, which implement a set of functions. Modules are imported from other modules
using the import command.
Syntax: import <modulename>
Example: import math

Precedence of Operators and Comments


24. Identify the method to write Comments in python.
Comments are used by programmers for better understanding of a program Comments
are very important while writing a Program. It describes what the source code has done.
In Python, we use the hash (#) symbol to start writing a comment Alternatively, use
triple single (''') or triple double quotes (""") at the start and end of a multiple-line
comment. Python interpreter ignores comment.
25. Define Operators and list its type.
An operator is a symbol that represents an operation performed on one Or more operands.
An operand is a quantity on which an operation is performed Operators that take one
operand are called unary operators. A binary operator operates on two operands. Python
uses different operators. They are:
1. Arithmetic Operators
2. Relational or Comparison Operators
3. Assignment Operators
4. Bit wise Operators Logical Operators
5. Membership Operators
6. Identity Operators
26. Outline in a few words about bitwise operators in Python.
Bitwise operations are operations that directly manipulate bits. It performs bit by bit
operations. It returns binary coded output(Table:1).
27. Compute the value of the expression 2 * (3 + 4) in Python.
The value will be 14 , the result of 2 * 7, because the parentheses force the addition to
happen before the multiplication.
28. Compute the value of the expression 2 * 3 + 4 in Python.

31
Unit II Short Questions 20CS101 – Problem Solving using Python Programming

Table 1: Bitwise Operators

Operator Description Example Result


x=5(510 = 01012 )
& (Binary AND) x&3 1
| (Binary OR) x|3 7
ˆ (Binary XOR) xˆ 3 6
˜ (Binary Ones Complement) ˜x -6
<< (Binary Left Shift) x<<2 20

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?

Create High-level Syntax error Messages


Text Editor Translator
language program

User Inputs Run Time Other error messages


system

Program Outputs

Figure 16: Software used in the coding process

A programmer typically starts by writing high-level language statements in a text editor.


The programmer then runs another program called translator to convert the high-level
program code into executable code. Because it is possible for a programmer to make
grammatical mistakes even when writing high-level code, the translator checks for syntax
errors before it completes the translation process. If it detects any of these errors, the
translator alerts the programmer via error messages. The programmer then has to revise
the program. If the translation process succeeds without a syntax error, the program be
executed by the run-time system. The run-time system might execute the program
directly on the hardware or run yet another program called interpreter or virtual
machine to execute the program. Figure 16 shows the steps and software used in the
coding process.
40. Explain the steps involved in interpreting a Python program
i) The interpreter reads a Python expression or statement, also called the source code,
and verifies that it is well formed. In this step, the interpreter behaves like a strict

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

Figure 17: Steps in interpreting a Python Program

Control Flow Statements – Conditionals


Conditionals: Boolean values and operators, conditional (if), alternative
(if-else), chained conditional (if-elif-else);
41. Define Flow control.
A program’s control flow is the order in which the program’s code executes. The control
flow of a Python program is regulated by conditional statements, loops, control structures.
42. List the type of Python’s Decision making statements.
• if statements
• if . . . else statements
• elif statements
• nested if . . . elif . . . else statements
• inline if
43. Draw the flowchart for if statement and if-else statement in python.
Figure 18
44. Write the syntax for if ..else and if-elif statements in Python.

35
Unit II Short Questions 20CS101 – Problem Solving using Python Programming

Test True Test False


Expression False Expression

True Statement1 Statement2

Statement Block

(a) Python if expression construct (b) Python if expression . . . else branching

Figure 18: Branching Process

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")

46. Define Inline if statements with example.


An inline if statement is a simpler form of if statement and is more if we need to perform

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
>>>

48. Mention the types of looping constructs.


Python provides two types of looping constructs. They are:
1) for loop
2) while loop
49. Explain for loop with else clause.
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.
50. Write a program to find the sum of first N natural numbers using while loop.
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)

51. Write the syntax for nested for loops in Python.


for < iterating variable > in <sequence>:
for < iterating variable > in <sequence>:
statement1(s)
statement2(s)

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)

58. Write a program to find the factorial of a number.


num = int(input("Enter the number:"))
for i in range(1, num + 1):
fact = fact ∗ i
print(" Factorial of", num, "is", fact )

59. Write a program to count the number of vowels in a word


sent = input("Enter a String:") #Reads the String
count = 0
for letter in sent :
if letter in 'aeiouAEIOU':
count += 1
print("The number of vowels in ", sent ," is ", count)

60. Write a program to remove duplicates from a list.


lis = input("Enter a list (space separated) :")
lisl = list ( lis . split ()) #converts string input to string list
uniq_items = []
for x in lisl :
if x not in uniq_items:
uniq_items.append(x)
print (uniq_items)

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="")

Unit II Big Questions


DATA, EXPRESSIONS AND CONTROL FLOW STATEMENTS
1. Explain in detail about data types in python with suitable examples
A value is one of the fundamental things, like a letter or a number that a program
manipulates. They are grouped into different data types or classes. Data type is a set of
values and allowable operations on those values. Data types allow programming languages
to organize different kinds of data.
Numbers: A numeric literal containing only the digits (0-9), an optional sign character
(+ or -) and a possible decimal point. Number data types are used to store numeric values.

39
Unit II Big Questions 20CS101 – Problem Solving using Python Programming

DATA TYPES

Numbers None Sequences Sets Mappings

Floating
Integer Complex Strings Tuples List Dictionary
Point

Boolean

Figure 19: List of Data Types in Python

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)

Table 2: Type Number

int long float complex


10 51924361L 0.0 3.14j
100 -0x19323L 15.20 45.j

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

Table 3: Print Format Specifiers

Format Specifier Conversion


%c character
%s string formatting
%i signed decimal integer
%d signed decimal integer
%u unsigned decimal integer
%o octal integer
%x hexadecimal integer (lowercase letters)
%X hexadecimal integer (UPPERCAsE letters)
%e exponential notation (with lowercase ’e’)
%E exponential notation (with UPPER CASE ’E’)
%f floating point real number

>>> 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

('abcd', 456, 2.23, 'baba', 70.2)


'abcd'
(456, 2.23)
(2.23, 'baba', 70.2)
('abcd',456)
(123, 'baba', 123, 'baba')
('abcd', 456, 2.23, 'baba', 70.2, 123, 'baba')
Dictionary
Python’s dictionaries are kind of hash table type. They work like associative arrays or
hashes found in Perl and consist of key-value pairs. A dictionary key can be almost any
Python type, but are usually numbers or strings. Values, on the other hand, can be any
arbitrary Python object.
Dictionaries are enclosed by curly braces { } and values can be assigned and accessed
using square brackets [].
Example 4.
dict = {}
dict['one'] = "This is one"
dict[2] = "This is two"
tinydict = {'name':'baba','code':6734, 'dept':'sales'}
print(dict['one']) # Prints value for ’one’ key
print(dict[2]) # Prints value for 2 key
print(tinydict) # Prints complete dictionary
print(tinydict.keys()) # Prints all the keys
print(tinydict.values()) # Prints all the values
Output.
This is one
This is two
{'dept':'sales','code':6734, 'name':'baba'} ['dept', 'code', 'name']
['sales', 6734, 'baba'])
2. Prepare a Python program to exchange the value of two variables.
a = int(input("enter a")
b = int(input("enter b")
print("a=",a,"b=",b)
a,b = b,a
print("a=",a,"b=",b)

3. What is a numeric literal? Give examples.


Numbers
A numeric literal containing only the digits (0-9), an optional sign character (+ or -) and
a possible decimal point.
Number data types are used to store numeric values. 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)

43
Unit II Big Questions 20CS101 – Problem Solving using Python Programming

3) float (float integers)


4) complex (complex integers)

Table 4: Numeric Literals

int long float complex


10 51924361L 0.0 3.14j
100 -00x1932L 15.20 45.j

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

Arithmetic Relational Logical Assignment Bitwise Membership


Operators Operators Operators Operators Operators Operators

=
+ < &
+=
- > |
or -=
/ <= >> in
and /=
// >= << not in
not %=
* != ∼
//=
** = ˆ
**=
Figure 20: List of Operators in Python

Table 5: Arithmetic Operators and their usage

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

Relational or Comparison Operators


Comparison operators are used to compare values. It either returns True or False according
to the condition. It describes relation between the left and right operands. They are also
called as relational operator. The relational operators are shown in Table 6 Example 6
illustrates some of them in operation.

Table 6: Relational Operators and their usage

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

Table 7: Assignment Operators and their usage

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

Table 8: Logical Operators and their usage

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

Table 9: Membership Operators and their usage

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

Table 10: Identity Operators and their usage

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]

a==b[True] L==M[True] L==M[True]


a is b[True] L is M[True] L is M[False]

Figure 21: Identity Operator Functionality

5. Outline the operator precedence of arithmetic operators in Python


The operator precedence determines which operators need to be evaluated first. To avoid
ambiguity in values, precedence operators are necessary. The following table summarizes
the operator precedence in Python, from highest precedence (most binding) to lowest
precedence (least binding). Operators in the same row have the same precedence. Operators
are always binary unless the syntax is explicitly given. Operators in the same row groups
from left to right (except for exponentiation, it groups from right to left).
Example

Table 11: Operator Precedence

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")

Output. Enter any number from the Keyboard: 60


Passed
Alternative if ... else Statement
An if ... else statement block first evaluates the ’if expression’. If the test condition
is TRUE, Python executes statements in the body of the ’if statement’. Otherwise, if the
condition is FALSE, Python executes the statements in the else block. Refer Listing 1,
page 36. Also refer Example 12
Example 12.
a, b = 100,200
if a > b: # 100 > 200
print("a is Greater than b")
else :
print("a is Less than b")

Output. a is Less than b


Chained Conditional if...elif ...else statements
An elif(else if) statement can be used when there is a need to check or evaluate multiple
expressions. An if.. .elif... else structure first checks if the ’if Test-Expression’ is True.
If it is true, then Python executes the statements in the if block. If it is False, it tests the
condition in the elif block. If the elif Expression is evaluated as True, Python executes
the statements in the elif block. Otherwise, control passes to the else block. Refer Listing
2 at page 36 and Figure 22 at page 53 Alse refer Example 13
Example 13.
num = 200
if num < 100:
print("num is less than 100")
elif 100 < num < 150:
print("num is between 100 and 150")

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

Figure 22: Python if ... elif ... else statement

else :
print("num is greater than 150")

Output. num is greater than 150


>>>
Inline if statements
An inline if statement is a simpler form of if statement and is more convenient, if we need
to perform a simple task.
Syntax
do Task A if condition is true else do Task B
Example
>>>a = 2
>>>b = True
>>>a = 1 if b else None
"""This statement assigns 1 to a (Task A) if b is True.
Else it assigns None to a (Task B)"""
>>>a
1
8. Explain the syntax and flow chart of the following loop statements

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

Body of for Body of while

Exit loop Exit loop


(a) Operation of for loop (b) while – pre-test loop

Figure 23: While and For Loops

(i) for loops


(ii) while loop
For loops
The for loop is a simple and efficient way to step through all the items in a sequence
and run a block of code for each item in turn. For loop iterates over a sequence that may
have different data types such as the list, tuple and string. It can also iterate any other
objects that may be defined in Python. The for-in loop repeats a given block of codes
by specified number of times.
Syntax
for target in object: # Assign object items to target
statements # Repeated loop body: use target
else : # Optional else part
statements # If we didn' t hit a 'break'

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

metals = [' Li ' , 'Na', 'K']


for metal in metals:
print(metal,end = ' ' )

Listing 3: For loop iteration


Output. Li Na K

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

# Program to find whether an item is present in the list


L = [10,12,13,34,27,98]
num = int(input("Enter the number to be searched in the list : "))
for item in range(len(L)):
if L[item] == num:
print("Item found at : ", (item+1))
break
else :
print("Item not found in the given list ")
Output. Enter the number to be searched in the list: 34
Item found at:4
Output. Enter the number to be searched in the list: 99
Item not found in the given list
While Loop
While loop is used when we need to repeatedly execute a statement or group of statements,
while the test condition is True. When the test condition is no longer true, program control
passes to the line after the loop. See Program 3
Syntax
while Boolean−expression:
Statement 1
Statement 2
...
Statement n
Program 3.
# Program to print the numbers from 0 to 4
counter = 0
while(counter < 4):
print( 'Count is : ' , counter)
counter = counter + 1
print ("Exit of the loop!")
Output.
Count is: 0
Count is: 1
Count is: 2
Count is: 3
Exit of the loop!
The flow-chart is shown in Figure 23b

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

Enter the upper limit: 5


Sum of first 5 natural numbers is 15
Explanation In example 15, when the text Enter the upper limit appears, 5 is given as the
input. i.e., n = 5. Initially, a counter i is set to 1 and sum is set to 0. When the condition is
checked for the first time i <= n, it is True. Hence the execution enters the body of while loop.
Variable sum is added with i and i is incremented. Since the next statement is un-indented,
it assumes the end of while block and again go back to check the condition. This process is
repeated until the condition given in the while loop is False and the control goes to the next
print statement to print the sum.
NESTED LOOPS
Nesting is defined as the placing of one loop inside the body of another loop. When we "nest"
two loops, the outer loop takes control of the number of complete repetitions of the inner loop.
While all types of loops may be nested, we can have nested loops for both while and for loops.
Syntax for nested for loop

for < iterating_variable > in <sequence>:


for < iterating_variable > in <sequence>:
Statement(s)
Statement(s)
Syntax for nested while loop

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

Figure 24: Python break statement

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

can be used in both while and for loops.

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

Figure 25: Python continue statement

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

You might also like