0% found this document useful (0 votes)
9 views156 pages

PSP Full

The document outlines the syllabus for the GE3151 - Problem Solving and Python Programming course for the I Year B.E/B.Tech students (Batch 2024-2028) at Mailam Engineering College. It covers topics such as computational thinking, data types, control flow, functions, lists, tuples, dictionaries, and file handling in Python, along with illustrative problems and important questions for exams. The document also includes a list of textbooks and reference materials for the course.

Uploaded by

janciraniaids
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)
9 views156 pages

PSP Full

The document outlines the syllabus for the GE3151 - Problem Solving and Python Programming course for the I Year B.E/B.Tech students (Batch 2024-2028) at Mailam Engineering College. It covers topics such as computational thinking, data types, control flow, functions, lists, tuples, dictionaries, and file handling in Python, along with illustrative problems and important questions for exams. The document also includes a list of textbooks and reference materials for the course.

Uploaded by

janciraniaids
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/ 156

MAILAM (PO), Villupuram (DT).

Pin: 604 304

(Approved by AICTE, New Delhi, Affiliated to Anna University, Chennai,


Accredited by NBA, NAAC with ‘A’ Grade and TATA Consultancy Services)

I Year B.E / B.Tech

Semester I

Batch: 2024 – 2028

GE3151 – Problem Solving & Python Programming

Name : ………………………………………………………….

Enroll Number : ………………………………………………………….

Department : ………………………………………………………….

i
MAILAM (PO), Villupuram (DT). Pin: 604 304
(Approved by AICTE, New Delhi, Affiliated to Anna University, Chennai,
Accredited by NBA, NAAC with ‘A’ Grade and TATA Consultancy Services)

I Year B.E / B.Tech


Semester I
Batch: 2024 – 2028

GE3151 – Problem Solving & Python Programming

UNIT I COMPUTATIONAL THINKING AND PROBLEM SOLVING


Fundamentals of Computing – Identification of Computational Problems -Algorithms, building blocks of
algorithms (statements, state, control flow, functions), notation (pseudo code, flow chart,
programming language), algorithmic problem solving, simple strategies for developing
algorithms (iteration, recursion). Illustrative problems: find minimum in a list, insert a card in a list of
sorted cards, guess an integer number in a range, Towers of Hanoi.

UNIT II DATA TYPES, EXPRESSIONS, STATEMENTS


Python interpreter and interactive mode, debugging; values and types: int, float, boolean, string, and
list; variables, expressions, statements, tuple assignment, precedence of operators, comments;
Illustrative programs: exchange the values of two variables, circulate the values of n variables,
distance between two points.

UNIT III CONTROL FLOW, FUNCTIONS, STRINGS


Conditionals: Boolean values and operators, conditional (if), alternative (if-else), chained
conditional (if-elif-else); Iteration: state, while, for, break, continue, pass; Fruitful functions: return
values, parameters, local and global scope, function composition, recursion; Strings: string
slices, immutability, string, functions and methods, string module; Lists as arrays. Illustrative
programs: square root, GCD, exponentiation, sum an array of numbers, linear search, binary search.

UNIT IV LISTS, TUPLES, DICTIONARIES


Lists: list operations, list slices, list methods, list loop, mutability, aliasing, cloning lists,
list parameters; Tuples: tuple assignment, tuple as return value; Dictionaries: operations and
methods; advanced list processing – list comprehension; Illustrative programs: simple sorting,
histogram, Students marks statement, Retail bill preparation.

UNIT V FILES, MODULES, PACKAGES


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, Voter’s age validation, Marks range validation (0-100).

TEXT BOOKS:
1. Allen B. Downey, “Think Python: How to Think like a Computer Scientist”, 2nd Edition,
O’Reilly Publishers, 2016.
2. Karl Beecher, “Computational Thinking: A Beginners Guide to Problem Solving
and programming”, 1st Edition, BCS Learning & Development Limited, 2017.

REFERENCE BOOKS:
1. Paul Deitel and Harvey Deitel, “Python for Programmers”, Pearson Education, 1st Edition, 2021.
2. G Venkatesh and Madhavan Mukund, “Computational Thinking: A Primer for Programmers and
Data Scientists”, 1st Edition, Notion Press, 2021.
3. John V Guttag, "Introduction to Computation and Programming Using Python:
With Applications to Computational Modeling and Understanding Data‘‘, Third Edition, MIT Press
2021 GE3151 Syllabus PROBLEM SOLVING AND PYTHON PROGRAMMING
4. Eric Matthes, “Python Crash Course, A Hands – on Project Based Introduction to Programming”,
2nd Edition, No Starch Press, 2019.
5. https://www.python.org/
6. Martin C. Brown, “Python: The Complete Reference”, 4th Edition, Mc-Graw Hill, 2018.

i
Part-A Part-B
University
Unit Page Page Page Page
Q.No Q.No Q.No Q.No QP
No. No. No. No.
- - - - 28 28 - - Dec 2023
1
- - - - 10 17 - - Apr 2024

29 34 - - - - - - Dec 2023
2
4 29 8 30 21,22 52 23 52 Apr 2024

12 54 - - - - - - Dec 2023
3
30 58 31 50 5 68 30 89 Apr 2024

16 92 - - 12 108 - - Dec 2023


4
15 92 21 93 - - - - Apr 2024

28 120 - - - - - - Dec 2023


5
- - - - 19 139 - - Apr 2024

Prepared by
1. Mr. M. RajeshKumar, ASP / MCA
2. Mrs. S. Aswini, A.P / CSE
3. Mrs. S. M. Sassirekha, A.P / CSE
4. Ms. E. Praveena, A.P / CSE
5. Mrs. M. Vijayalakshmi, A.P / IT
6. Ms. S. Jayabharathi, A.P / AI & DS
7. Ms. N. Jancirani, A.P / AI & DS
8. Ms. A. Thilagavathi, A.P / CSE
9. Mr. A. Mohamed Ali Jinna, A.P / CS & BS
10. Ms. K. T. Hemalatha, A.P / CSE

ii
Content Page No.

Anna University Important Questions – Unit wise

Unit 1

Part A 1

Part B 8

Unit 2

Part A 29

Part B 34

Unit 3

Part A 53

Part B 60

Unit 4

Part A 90

Part B 95

Unit 5

Part A 116

Part B 121

Anna University Questions 140

iii
MAILAM (PO), Villupuram (DT). Pin: 604 304
(Approved by AICTE, New Delhi, Affiliated to Anna University, Chennai,
Accredited by NBA, NAAC with ‘A’ Grade and TATA Consultancy Services)

I YEAR B.E / B.Tech


SEMESTER – I (2024 – 2028)

GE 3151 – PROBLEM SOLVING AND PYTHON PROGRAMMING


IMPORTANT QUESTIONS (Updated)
UNIT – 1
1) Draw basic symbols of flow charts. And explain the rules to draw flowchart.
2) Briefly explain the rules to write Pseudocode.
3) Discuss about building blocks of algorithm or flowchart. [AU – Jan 19, Dec 24]
4) Identify the simple strategies for developing an algorithm. [AU – Jan 2019]
5) May ask to write algorithm, Pseudocode and draw flowchart for any logic in University
Exam.
 Find minimum in a list [AU – Apr 2023]
 Guess an integer number in a range [AU – Apr 2024]
 Insert a card in a list of sorted cards
 Tower of Hanoi [AU – Jan 2018] & [AU – Jan 2019] & AU – Jan 2022,
2023, Dec 2023, Apr 2024]

UNIT – 2
1) Briefly explain about the data types available in python with examples.
2) Define variable. And explain how to declare variable and explain about the scope of the
variable. (Visibility mode of variables) – (In Unit 3 also)
3) Illustrate the concept of modules in details. (In Unit 5 also)
4) Briefly explain about the function with clear example. [AU – Jan 2019]
5) Illustrative arguments in function and explain the types of arguments with return
statement with neat examples. [AU – Jan 2019]
6) Operator precedence in Python. [AU – Jan 2018], [AU – Jan 2019] & [AU – May
2019]

UNIT – 3
1) What are operators? Illustrate each one with example. (In Unit 2 also) [AU – Jan
2018] & [AU – Jan 2022, Dec 2024]
2) Explain the branching statements in python with relevant syntax and example. (or) Conditional
Statements. [AU – Jan 2018], [AU – Jan 2019], [AU – Jan 2022]
3) Explain the iteration in python with relevant syntax and example. (or) Looping [AU – Jan 2022]
o Conditional looping
 While [AU – Jan 2018]
 For
 Nested for
o Unconditional looping
 Break [AU – Jan 2018] & [AU – Apr 2022]
 Continue [AU – Jan 2018] & [AU – Apr 2022]
 Pass
4) Briefly explain about fruitful functions with examples and also give explanation about
parameters in fruitful functions.
5) Outline about function definition and call with example. [AU – May 2019]
6) Briefly explain about recursion with example program of factorial. [AU – Jan 2018]
7) Explain the below concept in detail.
 Strings are immutable. Justify with an example. [AU – Jan 2019]
 String slices with examples [AU – May 2019]
 String functions and methods with examples.
UNIT – 4
1) Discuss the different options to traverse a list. [AU – Jan 2019], [AU – Jan 2022] &
[AU – Apr 2022, AU – Apr 2023, Apr 2024]
2) Illustrate with an example about list slices, methods available in list ,aliasing and
cloning of lists.
3) Explain about tuples and also the concept of tuple assignment and tuples as return
value with example. [AU – May 2019]
4) Compare and contrast tuples and lists in Python. [AU – Jan 2019]
5) What is dictionary in python? List out the operations and methods with example.
[AU – Jan 2018] & [AU – Jan 2022, Apr 2024]

UNIT – 5
1) Give brief introduction about files in python and list out the file opening modes.
[AU – Jan 2018] & [AU – Jan 2022]
2) Explain about the concept of file operations with relevant and explain how to
manipulate a file? [AU – Jan 2019] & [AU – May 2019, Apr 2024] (Explain the commands used
to read and write into a file with examples.)
3) Illustrate the concept of command-line arguments with syntax and examples. [AU –
Dec 2023]
4) What is error? Explain the types of error.
5) List out and describe about pre-defined methods of exception handling and How to
handle exception (try and except block)? Explain in details about used-defined
exception with example. [AU – Jan 2018], [AU – Jan 2019] & [AU – May 2019] &
[AU – Jan 2022] & [AU – Apr 2022]

IMPORTANT PROGRAM – EXPECTED IN ANNA UNIVERSITY


EXAMINATIONS

1) Write a Python program to Exchange the values of two variables.


[AU – Jan 2018], [AU – Jan 2019, AU- Apr 2023]
2) Write a Python program to circulate the values of n variables.
3) Write a Python program to find distance between two points. [AU – Dec 2023]
4) Write a python program to calculate square root.
5) Write a python program to find exponentiation.
6) Write a python program to calculate GCD of a number.
7) Write a python program to Fibonacci series. [AU – Jan 2018, Apr 2024]
8) Write a python program to search a required number in set of numbers using the concept
of linear search. [AU – Jan 2018, AU- Apr 2023]
9) Write a python program to search a required number in set of numbers using the concept
of binary search. [AU – Jan 2019] & [AU – May 2019]
10) Write a python program for selection sort. [AU – Jan 2018], [AU – Jan 2019]
11) Write a python program for insertion sort.
12) Write a python program for merge sort. [AU – May 2019]
13) Write a python program to count no. of words appears in a file. [AU – May 2019]
14) Write a python program to copy a source file to destination file. [AU – Apr 2023]
15) Write a Python program to multiply of two matrices.
16) Write a Python program to find first ‘n’ prime number.

Prepared by: Subject handling Staff


Approved by
Verified by (Principal)
(M.RAJESHKUMAR, ASP / MCA)

ALL THE VERY BEST


Mailam Engineering College GE3151 - Problem Solving and Python Programming

UNIT I COMPUTATIONAL THINKING AND PROBLEM SOLVING


Fundamentals of Computing – Identification of Computational Problems -Algorithms,
building blocks of algorithms (statements, state, control flow, functions), notation
(pseudo code, flow chart, programming language), algorithmic problem solving, simple
strategies for developing algorithms (iteration, recursion). Illustrative problems: find
minimum in a list, insert a card in a list of sorted cards, guess an integer number in a
range, Towers of Hanoi

FUNDAMENTALS OF COMPUTING

1) Define Computer.
Computer is a fast operating electronic device, which automatically accepts and
store input data, processes them and produces results under the direction of step by
step program.

2) What are the basic operations of a computer?


The basic operations of the computers are
 Input
 Process
 Storing
 Controlling
 Output

3) What are the applications of a computer?


The computer is used to assert man in business, research, etc.
The main areas in which, the computers are used.
 Business application
 Payroll and Personal records
 Office Automation
 Banking
 Insurance and Stock broking
 Scientific Research
 Industrial application
 Medicine
 Communication
 Education
 Engineering Design

4) What are the characteristics of Computers? [AU- Jan 2009, 11, Jan 11]
The characteristics of the computers are,
 Speed
 Accuracy
 Automation
 Endurance
 Versatility
 Storage
 Cost reduction
No Intelligent Quotient

5) How will you classify computer systems? [AU- Jan 2009, 11,May/June 2016]
Based on utility
 General Purpose Computers
 Special Purpose Computers
Based on Size and Capacity
 Micro Computers
 Mini Computers

Unit – 1 1
Mailam Engineering College GE3151 - Problem Solving and Python Programming

 Mainframe Computers
 Super Computers
Based on Mode of Use
 Palmtop
 Laptop PCs
 Workstations
 Client and Servers

6) What is super computer? Give an example. [AU, Apr/May 2015]


 The amount of data to be processed by super computer is very large and the
results are to be presented in very short time.
 It is very powerful and can solve very complex calculations.
 It handle FLOPS concept,
 FLOPS stands for Floating Point Operations per Seconds.
 Today’s super computer is equal to thatof 40,000 Micro computers.
 Super computers have very high memory capacity.
 Super computers can perform billions of instructions per second.
Example
It is used in scientific applications such as
o Space research
o Atomic research
o Processing of geological data
o Meteorological data and Aerodynamic design simulation

7) What are the Components of the computer system?


 Input Unit
 Central Processing Unit
 Secondary Storage Unit
 Output Unit

8) What are the languages used in Computer Generations?

S.No Generation of Computer Languages used

1. First Generation Machine ( binary) language

2. Second Generation Assembly Language

3. Third Generation High level language

4. Fourth Generation 4GL

5. Fifth Generation Artificial Intelligence

9) Specify the various Input and Output devices.


Input devices:
 Keyboard
 Mouse
 Light Pen
 Digitizer
 Trackball
 Joystick
 OCR (Optical Character Recognizer)
 MICR (Magnetic Ink Character Recognizer)
 OMR (Optical Mark Recognizer)
Output devices:
 VDU (Visual Display Unit) or Monitor
 Printer
 Plotter

Unit – 1 2
Mailam Engineering College GE3151 - Problem Solving and Python Programming

IDENTIFICATION OF COMPUTATIONAL PROBLEMS

10) What is computation?


It is any type of calculation that includes both arithmetic and non-arithmetical
steps and follows a well-defined model.
Example: Algorithm

11) List out the types of computational problems.


 Decision problems
 Search problems
 Counting problems
 Optimization problems

12) What are the factors of computational thinking?


 To take a complex problem
 Understand the nature of the problem
 Develop possible solution
 Present these solutions in a readability mode.

13) List out the basic design structure?(Or) basic logic structures.
 Sequence structure
 Selection structure
 Loop structure

14) What are all the steps to be followed to frame a function block?
 Understand the purpose of the function.
 Define the data that comes into the function from the caller (in the form of
parameters)
 Define what data variables are needed inside the function to accomplish its goal.
 Decide on the set of steps that the program will use to accomplish this goal.

ALGORITHM, FLOWCHART & PSEUDOCODE

15) What is an algorithm? [AU – Jan 2018, Apr 2019, Dec 2023]
 Algorithm is an ordered sequence of finite, well defined, unambiguous
instructions for completing a task.
 It is a step-by-step procedure for solving any problem.
 Algorithm is an English-like representation of the logic which is used to solve
the problem.

16) How can you measure the quality of algorithm? (Or)


How will you analyze the efficiency of an algorithm? [AU – Dec 2019]
 Time
 Memory
 Accuracy
 Sequence
 Generability

17) What are the characteristics of an algorithm?


Or Summaries the characteristics of a algorithm [AU – Apr2019]
 In algorithms each and every instruction should be precise.
 In algorithms each and every instruction should be unambiguous.
 The instructions in an algorithm should not be repeated infinitely.
 Ensure that the algorithm will ultimately terminate.
 The algorithm should be written in sequence.
 It looks like normal English.
 The desired result should be obtained only after the algorithm terminates.

Unit – 1 3
Mailam Engineering College GE3151 - Problem Solving and Python Programming

18) How many types the Algorithm can be represented?


 Normal English
 Program
 Flowchart
 Pseudo code
 Decision table

19) What is Flowchart? Why is flowchart required?


 A flowchart is a diagrammatic representation of the logic for solving a task.
 A flowchart is drawn using different shapes with lines connecting them to show
the flow of control.
 The purpose of drawing a flowchart is to make the logic of the program
clearer in a visual form.

20) What are the rules for drawing a flowchart?


 The standard symbols should only be used.
 The arrowheads in the flowchart represent the direction of flow of control in the
Problem.
 The usual direction of the flow of procedure is from top to bottom or left to right.
 The flow lines should not cross each other.
 Be consistent in using names and variables in the flowchart.
 Keep the flowchart as simple as possible.
 Words in the flowchart symbols should be common statements and easy to
understand.
 Chart main line of logic, and then incorporate all the details of logic.
 If a new page is needed for flowcharting, then use connectors for better
representation.

21) List out the advantages of flowchart. [AU, Apr – 24]


 Communication
 Effective analysis
 Proper documentation
 Efficient Coding
 Proper Debugging
 Proper testing
 Efficient Program Maintenance

22) What are all the disadvantages of flowchart or limitations?


 Complex logic
 Alteration or Modification
 Reproduction
 Unknown
 Cost

23) What is pseudo code? [AU, Jan -2013, Apr/May 2015]


“Pseudo” means imitation or false and “code” refers to the instruction written in
the Programming language. Pseudo code is programming analysis tool that is used for
planning program logic.

24) What are the rules for writing pseudo code?


 Write on statement per line.
 Capitalize initial keywords.
 Indent to show hierarchy.
 End multi line structure.
 Keep statements language independent.

Unit – 1 4
Mailam Engineering College GE3151 - Problem Solving and Python Programming

25) List out the advantages of Pseudo code.


 It can be done easily in any word processor.
 It can be easily modified as compared to flowchart.
 Its implementation is very useful in structured design element.
 It can be written easily.
 It can be read and understood easily.

26) List out the disadvantages of Pseudo code.


 It is not visual.
 We do not get a picture of the design.
 There is no standard style or format.
 One pseudocode may be different from another.
 For a beginner, it is more difficult to follow the logic or write pseudocode as
compared to flowchart.

27) What is the use of Algorithm, Flowchart and Pseudocode in the perspective
of problem solving? [AU-Jan 2019]
These three are problem solving tools and also used to makes the clear idea
about logical implementation of the given task. At the same time, it’s give reference idea
to new user or programmer.

RECURSION & ITERATION

28) Define recursion.


It is the functional block, function call itself.
29) Define an iterative statement. [AU, Jan -2022]
It is the block of statements or instructions executed again and again until the
condition occurs false.
In python programming language, there are two types of iteration, they are listed
below.
 While
 For

30)List out the Advantages of Recursive functions


 Recursion can produce simpler, more natural solutions to a problem
 It is written with less number of statements
 Recursive functions are effective where the terms are generated successively to
compute a value
 It requires few variables which makes program clean
 It is useful for branching processes.

31) Differentiate: Recursion and Iteration.


S.No Recursion Iteration
1 Functions call itself until the base iteration means repetition of process until the
condition is reached. condition fails
2 Only base condition (terminate Iterative approach involves four steps,
condition) is specified. initialization, condition, execution and
updation.
3 Recursion keeps your code short and Iterative approach makes your code longer.
simple.
4 Recursion is slower than iteration Iteration is faster.
due to overhead of
maintaining stack.
5 Recursion takes more memory than Iteration takes less memory.
iteration due to overhead
of maintaining stack.

Unit – 1 5
Mailam Engineering College GE3151 - Problem Solving and Python Programming

32) Which is better iteration or recursion? Justify your answer.[AU, Jan -2022]
For the simple logical block iteration is better than recursion.

For the complex logic, recursion is better than iteration because it reduces the
length of the coding. One and only drawback of the recursion is it consume more stack
memory when compare to iteration.

EXAMPLES FOR ALGORITHM, FLOWCHART & PSEUDOCODE

33) Write an algorithm to find largest of two numbers.


Step 1: Start
Step 2: Read input for A and B
Step 3: Check if A is greater than B then go to step 4 otherwise go to step 5
Step 4: Print A is greater
Step 5: Print B is greater
Step 6: Stop

34) Write an algorithm to accept two numbers, compute the sum and print the
result. AU-Jan 2018, Jan 2022]
Step 1: Start
Step 2: Read input for a and b
Step 3: Calculate sum=a+b
Step 4: Print the sum
Step 5: Stop

35) Write an algorithm to find minimum number in a given list of numbers.


[AU-Jan2019]
Step 1: Start
Step 2: Get input for n
Step 3: Assign i=0
Step 4: Set loop, is i<n, then
Step 4.1: Get input for a[i]
Step 4.2: Calculate i = i +1
Step 5: Assign min = a[0], i=1
Step 6: Set loop, is i<n, then
Step 6.1: Check is min > a[i], then
Step 6.1.1: Assign min=a[i]
Step 6.2: Calculate i = i + 1
Step 7: Print min
Step 8: Stop

36) Write an algorithm to find smallest among three numbers.[AU-Apr 2022]


Step 1: Start
Step 2: Get input for A, B and C
Step 3: Check if A< B and A<C then
Step 3.1: Print A is smaller
Step 4: Else
Step 4.1: Check if B<C then
Step 4.1.1: Print B is smaller
Step 4.2: Else
Step 4.2.1: Print C is smaller
Step 5: Stop

37) Write an algorithm to find largest among three numbers.


Step 1: Start
Step 2: Get input for A, B and C
Step 3: Check if A> B and A>C then

Unit – 1 6
Mailam Engineering College GE3151 - Problem Solving and Python Programming

Step 3.1: Print A is larger


Step 4: Else
Step 4.1: Check if B>C then
Step 4.1.1: Print B is larger
Step 4.2: Else
Step 4.2.1: Print C is larger
Step 5: Stop

38) Write an algorithm to find the sum of first ‘N’ natural numbers.[AU-Dec 2022]
Step 1: Start
Step 2: Get input for N.
Step 3: Assign i=1, sum=0
Step 4: Set loop, check if i<=10 then
Step 4.1: Calculate sum=sum+i
Step 4.2: Calculate i=i+1
Step 5: Print the value of sum
Step 5: Stop

39) Distinguish between algorithm and program. [AU – Jan 19, Apr 24]
S.No Algorithm Program
1 It is written in natural A program is written in any specific
language.(human understandable) Programming language.

2 It cannot be executed. It can be executed.


3 It cannot be compiled. It can be compiled.
4 It cannot generate any output. It can generate any output.
5 Step 1: Assign a=10 and b=20 a=10
Step 2:calculate c=a+b b=20
c=a+b

40) Distinguish between top down and bottom up approaches to design an


algorithm. [AU – Dec 2022]
S.No Top down Bottom up
1 It is decomposition approach. It is composition approach.
2 Easy to understand Difficult to understand.
3 Easy for implementation Difficult to implement for complex logic.
4 Beginners easy get an idea Beginners may not get an idea

Unit – 1 7
Mailam Engineering College GE3151 - Problem Solving and Python Programming

PART – B

FUNDAMENTALS OF COMPUTING
1) Briefly explain about basic operations of computer.

BASIC OPERATIONS OF A COMPUTER


In general, the computer has the five basic operations, they are listed below.
(i) Input
(ii) Process
(iii) Output
(iv)Storing
(v) Controlling

(i) Input
It is the process of accepting data from the computer system.
(ii) Process
Performing arithmetic operations or logical on data to convert them intouseful
information (data into information).

(iii) Output
It is the process of producing the processed data (or) information. i.e., Results.
(iv) Storing
It is the process of saving the data or information for further use.
(v) Controlling
Directing the manner or sequence in which all of the above operations
are performed.

2) Explain about the characteristics and applications ofcomputers.


[AU Jan 2005, 09, 10, 13]
CHARACTERISTICS OF COMPUTERS
 Speed: A powerful computer is capable of executing about 3 million calculations
per second. It is the most important characteristics of computer. Computer
having more speed to perform jobs instantaneously.
Speed Measurement
1 milli second = 1 x 10-3 seconds
1 micro second = 1 x 10-6 seconds
1 nano second = 1 x 10-9 seconds
1 pico second = 1 x 10-12 seconds
 Accuracy: The computers are perfect, accurate and precise. Accuracy signifies
the reliability of the hardware components of computers.
Example:
The computer accurately gives the result of division of any number
up to 10 decimal points.
 Automation: Once the instructions are fed into computer it works automatically
without any human intervention.
 Storage: Computer can store mass storage of data with appropriate format . This
is used to save information or programs for our future use.

Unit – 1 8
Mailam Engineering College GE3151 - Problem Solving and Python Programming

Storage Measurement
1024 Bytes = 1 KB
1024 KB = 1 MB
1024 MB = 1 GB
1024 GB = 1 TB
 Endurance: A computer works continuously and will not get tired and will not
suffer from lack of concentration.

 Versatility: It can perform different types of task with same time. A computer
can be put to work in various fields.
 Resource Sharing: Data and information can be shared among groups of
computers. Apart from the data sharing, devices can also be sharing like printer.
 No intelligent Quotient (No I.Q): Its I.Q is zero. It can only perform what is
programmed to do. Hence, only the user can determine what tasks a computer
will perform. Computers have no sense of meaning, cannot perceive and are only
able to make simple robotic decision about the data they receive.

3) Basic computer organization


[AU- Jan 2005,08,09,10,11,13 and 2014,2015]

The basic architecture of the computer system contains three units.


i. Input Unit
ii. Central Processing Unit
iii. Output Unit

Basic Block Diagram

Let see in details about Computer organization with its relevant block diagram

Block Diagram

Unit – 1 9
Mailam Engineering College GE3151 - Problem Solving and Python Programming

INPUT UNIT
 Input Unit is used to supply data and instructions to the computer through
external devices (input devices).
 Input devices are electronic or electro-mechanical equipment.
 Input devices capture information and translate it into a form that can be
processed by the CPU.
 The computer accepts input in two ways

Accepts in
two ways

By manually By directly

 In case of manual data entry, the user enters data into the computer by hand.
o Example
 By using a keyboard
 And a mouse
 In case of direct entry, information is fed by source document.
o Example
 Source document (Barcode Reader)
Example:
 Keyboard &Mouse
 Joystick
 Light Pen
 Image Scanner & Bar Code Reader

CENTRAL PROCESSING UNIT


 CPU stands for Central Processing Unit.
 It is the Heart of the computer system.
 It performs all calculations and decisions.
 It controls all internal and external devices.
 It performs arithmetic and logic operations, and operated only on binary data (0’s
and 1’s)
 It also controls the usage of memories.
The CPU consists of three main sub-system.
i) Control Unit
ii) Arithmetic and Logical Unit
iii) Memory Unit
a. Primary storage
b. Secondary storage
Control unit
 It is nervous system of the computer
 It controls the input/ output devices and directs the overall functioning of the
other units of the computer.
 This unit checks the correctness of sequence of operations.
 It controls the flow of data and instructions from the storage unit to ALU.
 It also controls the flow of results from ALU to the storage unit.
Arithmetic and logic unit
 This unit performs all the arithmetic and logical operations.
 Arithmetic operations like addition, subtraction, multiplication and logical
operations are performed in ALU.
 All calculations are performed in the ALU of the computer.
Memory Unit
It is the brain of the computer
Memory Unit is used to store the data and in formations. It contains two types.
i) Primary memory
ii) Secondary memory

Unit – 1 10
Mailam Engineering College GE3151 - Problem Solving and Python Programming

(i) Primary memory


 The primary storage is also called as main memory stores and access information
very fast.
 This is generally used to hold the program being currently executed in the
computer, the data being received from the input unit, the intermediate and final
results of the program.
 The primary memory contents generally lose its contents when we switch off
the computer. Primary memory contains two types;
1. RAM (Random Access Memory)
2. ROM (Read Only Memory)
Types of ROM
PROM : Programmable ROM
EPROM : Erasable Programmable ROM
EEPROM : Electrically Erasable Programmable ROM.
(ii) Secondary Memory
 The secondary storage is also known as Auxiliary storage.
 It may store several programs, documents, databases etc.
 The secondary memory is slower and cheaper than the primary memory.
 It is a permanent storage.
Example:
 Floppy disk,
 Hard Disk,
 CD.
OUTPUT UNIT
 The computer can communicate with human beings using output devices.
 The output unit processes data into useful information.
 The physical form of an output is known as hard copy.
 The electronic form of an output is known as soft copy.
 Devices used to get the response or result of a process from the computer is
called output.
 The output unit of a computer provides the information and results of a
computation to the outside world.
Example:
 Monitor
 Printer
 Speaker

ALGORITHM
4) Discuss about the building blocks of algorithms.[AU – Jan 19]
Or
Explain the different building blocks of algorithms with their
notations. [AU – Dec 22, Dec 23]
In general, there are three types of building blocks of algorithm, they are
 Sequence
 Selection
 Loop
• Top tested loop
• Bottom tested loop
(i) Sequence Structure
It is a sequence or linear structure because the flow always continues in same direction
every time the structure is executed.
Example:
Step 1: Start the program
Step 2: Get input for a and b
Step 3: Calculate c=a + b
Step 4: Print the value of c
Step 5: Stop the program.

Unit – 1 11
Mailam Engineering College GE3151 - Problem Solving and Python Programming

(ii) Selection Structure


 This structure includes the decision and the operations to be performed in
response to the decision.This are also known as “two way branching structure”.
Example:
Step 1: Start.
Step 2: Read the three numbers A, B, C.
Step 3: Check if A greater than B and C then go to step 4 otherwise go to step 5.
Step 4: Print A is greater
Step 5: Check if B greater than C then go to step 6 otherwise go to step 7.
Step 6: Print B is greater
Step 7: Print C is greater
Step 6: Stop.

(jjj) Loop Structure


 The loop structure is used to execute a sequence of steps in a no. of
times or until a specific condition going to occur false.
 There are two concepts available, they are

o Top tested loop.


o Bottom tested loop.

Example:
Step 1: Start the program.
Step 2: Read n
Step 3: Assign i=1
Step 4: Set loop, check if i<=n then
Step 4.1: Print i
Step 4.2: Calculate i=i+1
Step 5: Stop the program.

5) Identify the simple strategies for developing an algorithm.


[AU-Jan 2019]
Algorithm:
 A logical sequence of steps for solving a problem.
 An unambiguous set of steps for solving a problem in a finite amount of time
using a finite amount of data.
 An algorithm is a specification of a behavioral process. It consists of a finite set of
instructions that govern behavior step-by-step.

Strategies are 2 Mark - [AU-Jan 2019]


 Obtain a description of the problem.
 Analyze the problem.
 Develop an efficient algorithm.
 Refine the algorithm by adding more detail.
 Review the algorithm.

Let see the example for developing an algorithm with the above mentioned
strategies.
Example:
Step 1: Start the program
Step 2: Procedure Hanoi(dis, source, dest, aux)
Step 3: if disk == 0 then go to step 4 otherwise execute step 5 to 7.
Step 4: Move disk from source to dest
Step 5: Hanoi(dis-1, source, aux,dest)
Step 6: Move disk from source to dest
Step 7: Hanoi(dis-1, aux, dest ,source)
Step 8: Stop

Unit – 1 12
Mailam Engineering College GE3151 - Problem Solving and Python Programming

FLOWCHART
6) Draw and explain the various symbols of flowchart.
List the symbols used in drawing the flowchart [AU-Apr 2019]
Flowchart Symbols
Symbol Name Description

A process or action such as calculation and


Rectangular or action
assignment

Oval For Begin/End or Start/Stop

Diamond or decision For Decision making (YES/NO)

Arrows Flow lines of the program (Directions)

For the Connector or when describing a


Circle portion of a complete algorithm continued
from or will continue on.

Parallelogram The data or input/Output

7) What are the various guidelines to be followed while drawing a


flowchart?
Rules for Drawing a Flowchart
 The standard symbols should only be used.
 The flow lines should be from top to bottom or left to right.
 Only one flow line should enter into process and only one should exit from it.

 Only one flow line should enter into I/O symbols and only one should exit from it.

 Only one flow line is used in conjunction with terminal symbol.

 Only one flow line should enter into decision symbol and one or two may exit
from it. (in

 some case three lines are also exit from it)


 The flow lines should not intersect each other.
 Make the flowchart as simple.
 Use simple & common word in the flowchart symbols

Unit – 1 13
Mailam Engineering College GE3151 - Problem Solving and Python Programming

8) Discuss about basic design structures in Flowchart.


Basic design structures in flowchart
In general, there are three types of designs available, they are
 Sequence
 Selection
 Loop
Top tested loop
Bottom tested loop

Sequence Structure
It is a sequence or linear structure because the flow always continues in same
direction every time the structure is executed.

(ii) Selection Structure


• This structure includes the decision and the operations to be performed in
response to the decision. This is also known as “two way branching structure”.

START

Input A,
B

If A >
B

Print A is Print A is
greater greater

STOP
(iii) Loop Structure
• The loop structure is used to execute a sequence of steps in a no. of times or
until a specific condition going to occur false. There are two concepts
available, they are
(a) Top tested loop.
(b) Bottom tested loop.
(a) Top tested loop
The condition is appearing always at the first statements of the loop. If it is true,
the control will transfer into body of the loop otherwise it will terminate.

Unit – 1 14
Mailam Engineering College GE3151 - Problem Solving and Python Programming

(b) Bottom tested loop


The condition is appearing always at the last statements of the loop. If it is true,
the control will transfer into body of the loop otherwise it will terminate.

PSEUDOCODE

9) What is Pseudocode? Explain how to write pseudocode with


example.

Definition
 It is one of the “design tool”.
 Pseudocode is combination of ‘Pseudo’ and ‘Code’
 Pseudo Imitation (False)
 Code Instruction (Program)
 It is half – way communication between design and development phase.

Rules for Writing Pseudocode (Part B Question)


There are some rules available that should be following while writing pseudocode.
They are given below.
(i) Write one statement per line.
(ii) Capitalize initial keyword.
(iii) Indent to show hierarchy.
(iv) End multiline structure.
(v) Keep statements language independent.

(i) Write one statement per line.


Write Pseudocode for each and every task and sub-task. But only condition is use
one action or statement per line then writes another statement in next new line.

Unit – 1 15
Mailam Engineering College GE3151 - Problem Solving and Python Programming

Example:
Tasks are:

Read name and marks.


Calculate total and average.
Print the outputs.
Pseudocode:
READ name, m1, m2, m3, m4, m5
Tot = m1+m2+m3+m4+m5
Avg = Tot / 5

PRINT Tot, Avg

(ii) Capitalize initial keywords.


The keywords in the pseudocode should be written in all capital letters that give
specific meaning to the operation.
Example:
The keywords are
READ or INPUT or GET

WRITE or OUTPUT
or PUT or PRINT IF,
THEN, END IF

WHILE, UNTIL, LOOP

(iii) Indent to show hierarchy.


Indentation is the process of showing the “boundaries” of the structure. It is used
for readability.
Example:
READ name, m1, m2, m3, m4, m5
Tot = m1+m2+m3+m4+m5
Avg = Tot / 5
IF Avg> 75 THEN
Rank = Distinction
END IF
WRITE Tot, Avg, Rank.
(iv) End Multiline Structure.
The multiline structure must be ended for readability and clarity. It is also helps
to make sure that you know where the loop or selection is completed or ended.
Example:
IF a>b THEN
WRITE A is greater
ELSE
WRITE B is greater
END IF;

(or)

WHILE(n > 0)

-------------
-------------
END WHILE

(v) Keep statements language independent.


Here languages refer programming languages. Our pesudocode is not dependent
to the program coding.

Unit – 1 16
Mailam Engineering College GE3151 - Problem Solving and Python Programming

10) Explain the design structures in pseudocode. [AU – Apr 24]


In general, there are three types of design structure in pseudocode, they are
 Sequence
 Selection
 Loop
• Top tested loop
• Bottom tested loop
(i) Sequence Structure
It is a sequence or linear structure because the flow always continues in same direction
every time the structure is executed.
Example:
READ a and b
CALCULATE c=a + b
PRINT c
END
(ii) Selection Structure
 This structure includes the decision and the operations to be performed in
response to the decision. This are also known as “two way branching structure”.
Example:
READ a, b
IF a>b, then
PRINT A is greater
ELSE
PRINT B is greater
END

(jjj) Loop Structure


 The loop structure is used to execute a sequence of steps in a no. of
times or until a specific condition going to occur false.
 There are two concepts available, they are

o Top tested loop.


o Bottom tested loop.

Example:
READ n
ASSIGN i=1
WHILE i<=n then
PRINT i
CALCULATE i=i+1
END

EXAMPLES
11) Write an algorithm to sort the given numbers in ascending
order using bubble sort.
Step 1: Start the program.
Step 2: Read input for n.
Step 3: Set loop i=0, check if i<n then executes step 4 to 5 until the condition
occur false.
Step 4: Read a[i].
Step 5: Increment i by 1.
Step 6: Set loop i=0, check if i<n then executes step 7 to 13 until the condition
occur false.
Step 7: Set loop j=i+1, check if i<n then executes step 8 to 12 until condition occur
false.
Step 8: Check if a[i] > a[j] then executes step 9 to 11.

Unit – 1 17
Mailam Engineering College GE3151 - Problem Solving and Python Programming

Step 9: Assign temp=a[i].


Step 10: Assign a[i]=a[j].
Step 11: Assign a[j]=temp.
Step 12: Increment j by 1.
Step 13: Increment i by 1.
Step 14: Set loop i=0, check if i<n then executes step 15 to 16 until the condition occur
false.
Step 15: print a[i].
Step 16: Increment i by 1.
Step 17: Stop the program.

12) Develop an algorithm to find the greatest of three numbers.


Step 1: Start the program.
Step 2: Read A, B, C
Step 3: Check If A>B and A>C then go to step 4 otherwise go to step 5
Step 4: Print A is greater
Step 5: Check If B>C then go to step 6 otherwise go to step 7
Step 6: Print B is greater
Step 7: Print C is greater
Step 8: Stop the program.

(or)

Step 1: Start the program.


Step 2: Read A, B, C
Step 3: Check If A>B and A>C then
Step 3.1: Print A is greater
Step 4: Else
Step 4.1: Check If B>C then
Step 4.1.1: Print B is greater
Step 4.2: Else
Step 4.2.1: Print C is greater
Step 5: Stop the program.

13) Draw a flow chart to accept three distinct numbers, find the
greatest and print the result. [AU – Jan 2018, Jan 2022]

Unit – 1 18
Mailam Engineering College GE3151 - Problem Solving and Python Programming

14) Draw the flowchart for finding the roots of a quadratic


equation.

15) Draw a flowchart to find factorial of a number

Unit – 1 19
Mailam Engineering College GE3151 - Problem Solving and Python Programming

16) Draw a flowchart to find sum first 100 natural numbers. (or)
Draw a flowchart to find the sum of the series
1+2+3+4+5+…+100 [AU – Jan 2018, Jan 2022]
Find the sum of first 100 integers [AU – Apr 2024]

17) Draw a flowchart to check if the given word is palindrome.


[AU – Dec 2022]

Unit – 1 20
Mailam Engineering College GE3151 - Problem Solving and Python Programming

18) Write the pseudocode to multiply two matrixes.


READ n
//Read the elements of matrix a
FOR i = 1 to n do
FOR j = 1 to n do
INPUT
a[i][j]
END FOR
END FOR
//Read the elements of matrix a
FOR i = 1 to n do
FOR j = 1 to n
do
INPUT
b[i][j]
END FOR
END FOR
FOR i = 1 to n do
FOR j = 1 to n do
c[i][j]=0
FOR k = 1 to n do
c[i][j]=c[i][j]+a[i][k]*b[k][j]
PRINT c[i][j]
END FOR
END FOR
END FOR

19) Write an algorithm to find an element in he given set of


numbers. [AU-Dec 2022]
Step 1: Start the program.
Step 2: Read ‘n’
Step 3: Assign i=0, flag=0
Step 4: Set loop, i<n then
Step 4.1: Get input of a[i]
Step 4.2: Calculate i=i+1
Step 5: Get input for searching element as ‘key’
Step 5: Set loop, i<n then
Step 5.1: Check if a[i]==key then
Step 5.1.1: Assign flag=1
Step 5.1.2: break the loop
Step 5.2: Calculate i= i+1
Step 6: Check if flag==1, then
Step 6.1: Print the searching element is PRESENT
Step 7: Else
Step 7.1: Print the searching element is NOT PRESENT
Step 5: Stop the program.

Unit – 1 21
Mailam Engineering College GE3151 - Problem Solving and Python Programming

ILLUSTRATION PROBLEMS

20) Outline the Towers of Hanoi problem. Suggest a solution to


the Towers of Hanoi problem with relevant diagrams.
[AU-Jan 18, Jan 19, Jan 22, Dec 2022, Dec 2023 & Apr 2024]
It is one the best application of the concept of Recursion.
“Tower of Hanoi game is a puzzle invented by French mathematician Édouard
Lucas in 1883.”

The Tower of Hanoi (also called the Tower of Brahma or Lucas' Tower

Total of 2n − 1 moves are made


Simple rules:
 Only one disk can be moved at a time.
 Each move consists of taking the upper disk from one of the stacks and placing it
on top of another stack i.e. a disk can only be moved if it is the uppermost disk
on a stack.
 No disk may be placed on top of a smaller disk.
 The below diagram shows the steps of disk movement.

Unit – 1 22
Mailam Engineering College GE3151 - Problem Solving and Python Programming

Algorithm for Tower of Hanoi


Step 1: Start the program
Step 2: Procedure Hanoi(dis, source, dest, aux)
Step 3: if disk == 0 then go to step 4 otherwise execute step 5 to 7.
Step 4: Move disk from source to dest
Step 5: Hanoi(dis-1, source, aux,dest)
Step 6: Move disk from source to dest
Step 7: Hanoi(dis-1, aux, dest ,source)
Step 8: Stop

Pseudocode for Tower of Hanoi


Procedure Hanoi(dis, source, dest, aux)
IF disk == 0 then
Move disk from source to dest
ELSE
Hanoi(dis-1, source, aux,dest)
Move disk from source to dest
Hanoi(dis-1, aux, dest ,source)
END IF
END

Unit – 1 23
Mailam Engineering College GE3151 - Problem Solving and Python Programming

21) Write the pseudocode to find minimum in a list.

READ n
SET i=0
WHILE i < n THEN
READ a[i]
CALCULATE i = i + 1
END WHILE

SET min=a[0], i=1

WHILE i < n THEN


IF min > a[i] THEN
SET min=a[i]
END IF
CALCULATE i=i+1
END WHILE

PRINT min
END

22) Draw a flowchart to find minimum in a list.

START
Z

INPUT n

IS i<n
i=0

IS i<n IS min>a[i]

min=a[i]
INPUT a[i]
min=a[0]
I=i+1

I=i+1 i=1

PRINT min

Z
STOP

Unit – 1 24
Mailam Engineering College GE3151 - Problem Solving and Python Programming

23) Write an algorithm to find minimum in a list.


Step 1: Start
Step 2: Get input for n
Step 3: Assign i=0
Step 4: Set loop, is i<n, then
Step 4.1: Get input for a[i]
Step 4.2: Calculate i = i +1
Step 5: Assign min = a[0], i=1
Step 6: Set loop, is i<n, then
Step 6.1: Check is min > a[i], then
Step 6.1.1: Assign min=a[i]
Step 6.2: Calculate i = i + 1
Step 7: Print min
Step 8: Stop

24) Write an algorithm to guess an integer number in a range.


Step 1: Start [AU – Apr 2024]
Step 2: Assign max_num=10
Step 3: Get random number through random function and assign to secret_num
Step 4: Print the range of number
Step 5: Assign max_guesses=3
Step 6: guesses_left=max_guesses
Step 7: set loop, is guesses_left until 0, then
Step 7.1: Print Guesses remaining.
Step 7.2: Get input for guess.
Step 7.3: Check is guess is equal to secret_num, then
Step 7.3.1: Print correct
Step 7.3.2: Break the loop
Step 7.4: Else, check is guess <secret_num, then
Step 7.4.1: Print it’s too low
Step 7.5: Else
Step 7.5.1: Print it’s too high
Step 7.6: Calculate guesses_left=guesses_left-1
Step 8: Stop.

25) Write pseudocode to guess an integer number in a range.


SET max_num=10 [AU – Apr 2024]
INPUT random number through random function and assign to secret_num
PRINT range of number
SET max_guesses=3
SET guesses_left=max_guesses
WHILE guesses_left until 0, THEN
PRINT Guesses remaining.
INPUT for guess.
IF guess is equal to secret_num, then
PRINT correct
BREAK the loop
ELSE IF guess <secret_num, then
PRINT it’s too low
ELSE
PRINT it’s too high
END IF
END IF
Calculate guesses_left=guesses_left-1
END LOOP
END

Unit – 1 25
Mailam Engineering College GE3151 - Problem Solving and Python Programming

26) Draw flowchart to guess an integer number in a range.


[AU – Apr 2024]

Unit – 1 26
Mailam Engineering College GE3151 - Problem Solving and Python Programming

27) Write an algorithm, Pseudocode and draw flowchart to insert


a card in a list of sorted cards. [AU Jan 2019]

Algorithm:
Step 1: Start
Step 2: Get input for ‘n’
Step 3: Initialize i=0
Step 4: Check If i<n, then execute step 4.1, 4.2 otherwise go to step 5
Step 4.1: Get input for a[i]
Step 4.2: Calculate i=i+1 goto step 4
Step 5: Get input for ‘item’
Step 6: Calculate i=n-1
Step 7:Check If i>=0 and item<a[i], then go to step 7.1, 7.2 otherwise go to
step 8
Step 7.1: Assign a[i+1]=a[i]
Step 7.2: Calculate i=i-1 go to step 7
Step 8: Calculate a[i+1]=item
Step 9: Calculate n=n+1
Step 10: Check If i<n, then go to step 10.1, 10.2 otherwise go to step 11
Step10.1: Print a[i]
Step10.2: Calculate i=i+1 go to step 10
Step 11: Stop

Pseudocode:
READ n
FOR i=0 to n, then
READ a[i]
CALCULATE i=i+1
END FOR

READ item

FOR i=n-1 to 0 and item<a[i], then


CALCULATE a[i+1]=a[i]
CALCULATE i=i-1
END FOR

CALCULATEa[i+1]=a[i]
CALCULATEn=n+1

FOR i=0 to n,then


PRINT a[i]
CALCULATE i=i+1
END FOR

END

Unit – 1 27
Mailam Engineering College GE3151 - Problem Solving and Python Programming

Flowchart

28) Define the computational problem and how these problems


are classified. [AU Dec 2023]
A computational problem is a problem that can be solved step-by-step with a
computer. These problems usually have well-defined input, constraints, and conditions
that the output must satisfy.

Here are some types of computational problems:


 A decision problem
 A search problem
 A counting problem
 An optimization problem.

Unit – 1 28
Mailam Engineering College GE3151 - Problem Solving and Python Programming

UNIT II DATA, EXPRESSIONS, STATEMENTS


Python interpreter and interactive mode; values and types: int, float, boolean, string,
and list; variables, expressions, statements, tuple assignment, precedence of operators,
comments; Illustrative programs: exchange the values of two variables,
circulate the values of n variables, distance between two points.

PART A - 2 MARKS

PYTHON INTERPRETER AND INTERACTIVE MODE

1) What is Python? What are the benefits of using Python?


Python is a programming language with objects, modules, threads, exceptions
and automatic memory management. The benefits of pythons are that it is simple and
easy, portable, extensible, build-in data structure and it is an open source.

2) Mention some benefits of using Python.


 Python comprises of a huge standard library for most Internet platforms like
Email, HTML, etc.
 Python does not require explicit memory management as the interpreter itself
allocates the memory to new variables and free them automatically.
 Provide easy readability & Easy to learn for beginners.
 Having the built-in data types saves programming time and effort from declaring
variables.

3) Compare interpreter and compiler. What type of translator is used for


Python? [AU – Dec 2019]

S.No Interpreter Compiler


1 Performs statement by statement Performs the translation of a program as
translation. a whole.
2 Execution is slower. Execution is faster.
It stops translation when the first Debugging is hard as the error messages
error is met. Hence, debugging is are generated after scanning the entire
easy. program only.
3 Programming languages like Python, Programming languages like C, C++ uses
BASIC, and Ruby uses interpreters. compilers.

Types of Python Interpreter


Python 2.7
Python 3.5
Python 3.6
Python 3.7 and so on…

4) What is the difference between interactive mode and script mode?


[AU – Apr 2024]
S.No Interactive Mode Script Mode
1 We can type commands one at a Python code is written in a file (with a .py
time and get immediate feedback. extension) and then executed all at once
by running the script through the Python
interpreter
2 Quick and efficient for testing and Better for managing large codebases and
experimenting. writing reusable programs.
3 Good for testing and experimenting Ideal for writing and executing complete
with code in real time. programs stored in files.

Unit II 29
Mailam Engineering College GE3151 - Problem Solving and Python Programming

VALUES & TYPES

5) What are keywords? Give example. [AU – Jan 2019]


The keywords are also known as reserved words. The python interpreter uses
keywords to recognize the structure of the program, and they cannot be used as variable
names. Python 2 has 31 keywords and python 3 has 33 keywords.

Example:
o print
o input
o from
o import
o int

6) Name the four types of scalar objects Python has. [AU –Jan 2018]
List the various single valued data types in Python. [AU –Dec 2023]
 int
 float
 bool
 None

7) List any four built in data types in Python. [AU – Apr/May 2022]
Python has five standard data types.
 Numbers
 String
 List
 Tuple
 Dictionary

8) Mention the features of lists in python? [AU – Apr 2024]


Few features of list are
 Mutable
 Ordered Collection
 Heterogeneous Elements
 Dynamic Size
 Indexing and Slicing

VARIABLES
9) What is variable? Give example.
A variable is nothing but a reserved memory location to store values. In other
words a variable in a program gives data to the computer to work on.
Example:
Let see an example with declare variable “b” and print it.
b=200
print(b)

10) How will you concatenate the variables in python?


Example:
It will concatenate “World” with number “88”. Unlike Java, which concatenates
number with string without declaring number as string, Python requires declaring the
number as string otherwise it will show a TypeError.
Once the integer is declared as string, it can concatenate both “World” +
str(“88”)= “World88” in the output.

a=”Guru”
b = 99
print(a+str(b))

Unit II 30
Mailam Engineering College GE3151 - Problem Solving and Python Programming

11) How to Create and Assign Numbers (Number Objects)?


Creating numbers is as simple as assigning a value to a variable,

anInt = 1
aLong = -9999999999999999L
aFloat = 3.1415926535897932384626433832795
aComplex = 1.23 + 4.56J

12) Write the content of swapping of two numbers in a single line.


x = 10 x, y = y, x
y = 20 print(x)
print(x) (or) print(y)
print(y)

13) Write a python program to print sum of cubes of the values of n variables.
[AU, Dec 2019]
n=int(input(“Enter N:”)) n=int(input(“Enter N:”))
sum=0 sum=0
i=1
while (i<=n): (or) for i in range(1, n+1):
sum=sum + (i**3) sum=sum + (i**3) #sum=sum+i*i*i
i=i+1
Print(“Answer=”, sum) Print(“Answer=”, sum)

EXPRESSIONS & STATEMENTS


14) What is a tuple? How literals of type are written? Give example.
[AU-Jan 2018]
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.
Example:
t1=()
t2=(1,’two’,3)

15) What is the difference between tuples and lists in Python?


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.

16) What is an expression? Give example.


An expression is a combination of operands and operators.
Here:
 Operands refers Variables and Values
 Operators refers Symbol

17) What is a statement in python?


A statement is an instruction that the Python interpreter can execute. We have
seen two kinds of statements: print and assignment.
Example:

print(1)
x=2
print(x)
Output:
1
2
The assignment statement produces no output.

Unit II 31
Mailam Engineering College GE3151 - Problem Solving and Python Programming

TUPLE ASSIGNMENT
18) How do you assign a value to a tuple in Python? [AU, Apr/May 2022]
Program:
ans=divmod(13,2)
print(ans)
q,r=ans
print(q)
print(r)
Output:
(6,1)
6
1
19) Give example for tuple assignment.
Python provides a form of tuple assignment that solves this problem neatly:

a, b = b, a

The left side is a tuple of variables; the right side is a tuple of values. Each value
is assigned to its respective variable. All the expressions on the right side are evaluated
before any of the assignments. This feature makes tuple assignment quite versatile.

PRECEDENCE OF OPERATORS

20) Define operator. Give example of operator.


Operator is a symbol that is used to manipulate mathematical and other expression.
Expression is the combination of operator and operands.

Example:
a+b
a, b are operands
+ is a operator

21) List out the types of operator.


Python language supports the following types of operators.
o Arithmetic Operators
o Comparison (Relational) Operators
o Assignment Operators
o Logical Operators
o Bitwise Operators
o Membership Operators
o Identity Operators

22) What is the purpose of ** operator and // operator?


** Exponent − Performs exponential (power) calculation on operators.

Example:
a**b = 10 to the power 20 if a = 10 and b = 20.

// Floor Division − The division of operands where the result is the quotient in which the
digits after the decimal point are removed.

Example:
3//10=3

23) What is the purpose of is operator and not in operator?


is − Evaluates to true if the variables on either side of the operator point to the
same object and false otherwise. x is y, here is results in 1 if id(x) equals id(y).

Unit II 32
Mailam Engineering College GE3151 - Problem Solving and Python Programming

not in − Evaluates to true if it does not finds a variable in the specified sequence
and false otherwise. x not in y, here not in results in a 1 if x is not a member of
sequence y.

24) List out the points of precedence of operators.


a) ** – Exponent
b) *, /, %, // – Multiplication, true division, modulo, floor division. In this case if
these operators where in the same equation then the equation would run left to
right.
c) +, – Addition and Subtraction are the last operators to run.

25) Identify the operand (s) and operator (s) in the following expression:
sum = a + b [AU, Jan 2022]

Solution:
sum, a, b are OPERANDS
=, + are OPERATORS

26) Are comments executable statements in a python program? How comments


are included in a Python program? [AU, Jan 2022]
The comments are non-executable statements in the program.

Example:
In Python there are basically two ways to comment: single line and multiple line.
Single line comment
A single line comment starts with the number sign (#) character:
# This is a comment
print(‘Hello’)
Multiline comment
Multiple lines can be created by repeating the number sign several times:
# This is a comment
# second line
x=4
(or)
‘’’ This is a multiline
Python comment example.’’’
x=5

27) Write the Python program to exchange the values of two variables.

a=int(input(“Enter first value”))


b=int(input(“Enter second value”))
print(“Before Swapping”)
print(“A=”,a)
print(“B=”,b)
t=a
a=b
b=t
print(“After Swapping”)
print(“A=”,a)
print(“B=”,b)

28) Python variables do not have specific types. Justify this statement using an
example. [AU, Dec 2022]
No. Because, Python language is an interpreted language and there isn’t really
any need of having types.

Unit II 33
Mailam Engineering College GE3151 - Problem Solving and Python Programming

29) What is an indentation in Python? Give an example. [AU, Dec 2023]


In Python, indentation is used to define the structure and hierarchy of blocks of
code, rather than using braces ({}) like in some other programming languages. Proper
indentation is crucial because Python relies on it to identify where a block of code starts
and ends.

Example:
n=int(input(“Enter N:”))
sum=0
i=1
while (i<=n):
sum=sum + (i**3)
i=i+1
print(“Answer=”, sum)

PART B
PYTHON INTERPRETER AND INTERACTIVE MODE

1) SKETCH THE STRUCTURE OF INTERPRETER AND COMPILER. DETAIL THE


DIFFERENCES BETWEEN THEM. EXPLAIN HOW PYTHON WORKS IN
INTERACTIVE MODE AND SCRIPT MODE WITH EXAMPLES. (or) [AU – Jan 19]

EXPLAIN THE PYTHON INTERPRETER AND INTERACTIVE MODE IN DETAIL.


[AU – Dec 23]

Interpreter:
It is a program that reads the high level program (source code) and executes the
program line by line. Then, finally performs computations and prints the output. Thus,
the structure of interpreter is shown below.

Compiler:
A compiler is a computer program that transforms code written in a high-level
programming language into the machine code. It is a program which translates the
human-readable code to a language a computer processor understands (binary 1 and 0
bits). The computer processes the machine code to perform the corresponding tasks.

Difference between Interpreter and compiler


S.No Interpreter Compiler
1 Performs statement by statement Performs the translation of a program as
translation. a whole.
2 Execution is slower. Execution is faster.
It stops translation when the first Debugging is hard as the error messages
error is met. Hence, debugging is are generated after scanning the entire
easy. program only.
3 Programming languages like Python, Programming languages like C, C++ uses
BASIC, and Ruby uses interpreters. compilers.

Unit II 34
Mailam Engineering College GE3151 - Problem Solving and Python Programming

Script mode (or) Interpreter mode:


It is used when the user is working with more than one single code or a block of
code. The interpreter mode is the mode where the scripted and finished .py files are
run in the Python interpreter.
Example:
a=int(input(“Enter A:”))
b=int(input(“Enter B:”))
sum=a+b
print(“Answer=”, sum)
Interactive mode:
Interactive mode is used when a user wants to run one single line or one block of
code. It runs very quickly and gives the output instantly.
Example:
>>>squ=26
>>>print(squ*2)
676

2) WHY DO WE CALL PYTHON AS INTERPRETED AND OBJECT-ORIENTED


PROGRAMMING LANGUAGE? ALSO EXPLAIN ABOUT INTERACTIVE PYTHON.
[AU – Apr/May 2022]
Interpreter:
It is a program that reads the high level program (source code) and executes the
program line by line. Then, finally performs computations and prints the output. Thus,
the structure of interpreter is shown below.

 Python is an Interpreted language, which means the source code of a Python


program is converted into byte code then executed by the Python virtual
machine.
 Python is different from major compiled languages like as C, C++ and etc.,
 Python code is not required to be built and linked like code for these languages.

Python code is fast to develop:


As the code is not needed to be compiled and built, Python code can be readily
changed and executed. This makes for a fast development cycle.

Python is Object-oriented language:


 Everything in Python is an OBJECT.
 Using Python, we can create classes and objects.
 Classes: It is like a blueprint that helps to create an object. In other words, a
class comprises variables, methods and functions.
 Objects: Objects are an instance of a class. With the help of objects, we can
access the method and function of a class.

OOP’s concepts like Classes, Encapsulation, Polymorphism, Inheritance etc.. in


Python makes it as a object – oriented programming language.

Interactive Python:
In general, Python has two basic modes, they are given below.
 Script and

Unit II 35
Mailam Engineering College GE3151 - Problem Solving and Python Programming

 Interactive
Let see about Interactive mode of Python.
The normal mode is the mode where the scripted and finished .py files are run in the
python interpreter.
Interactive mode is a command line shell which gives immediate feedback for each
statement, while running previously fed statements in active memory.
Interactive mode is a good way to play around and try variations on syntax.
The symbol >>> is Python’s way of telling you that you are in interactive mode. In
this mode what you type is immediately run.

Example:
>>> 12 + 5
17

>>> print(‘Answer=’,12*3)
Answer=36

BASIC PYTHON
3) BRIEFLY EXPLAIN ABOUT TOKENS IN PYTHON WITH CLEAR EXAMPLE.
Python breaks each logical line into a sequence of elementary lexical components
known as tokens. A token is the smallest individual unit of the program. Each token
corresponds to a substring of the logical line.

(i) Keywords
 Keywords are reserved words they have predefined meanings in Python.
 They cannot be used as ordinary identifiers and must be spelled exactly as they
are written.
 Python3 has 33 keywords.
 The Table presents all 33 of Python’s keywords. The first three are grouped
together because they all start with uppercase letters.
False class finally is return
None continue for lambda try
True def from nonlocal while
and del global not with
as elif if or yield
assort else import pass
break except in raise
(ii) Identifiers
 Python identifier is the name given to a variable, function, class, module or other
object.
 An identifier can begin with an alphabet (AZ or az), or an underscore (_) and
can include any number of letters, digits, or underscores.
 Spaces are not allowed.
 Python will not accept special characters as identifiers.
 Python is a case-sensitive language. Thus, Hello and hello are different identifiers.

Unit II 36
Mailam Engineering College GE3151 - Problem Solving and Python Programming

(iii) Literals
A literal is a sequence of one of more characters that stands for itself. There are
two important types of literals. They are,
 Numeric Literals
 String LiteralsLiterals
 A numeric literal is a literal containing only the digits 0 – 9, an optional sign
character ( + or  ), and a possible decimal point.
 Commas are never used in numeric literals. If a numeric literal contains a decimal
point, then it denotes a floating-point (float) value. Example: 12.35.
 If a numeric literal does not contain a decimal point, then it denotes an integer
(int) value. Example: 10.
 String literals or strings represent a sequence of characters.
Example:
'Hello'
'Jovita, Jesvita'
"231, Carmel Nagar, 629004“
In Python, string literals may be delimited (surrounded) by a matching pair of
either single (') or double (") quotes.

Example:
>>>print('Welcome to Python!')
Welcome to Python!

(iv) Delimiters
Delimiters are symbols that perform three special roles in Python like grouping,
punctuation, and assignment/ binding of objects to names. Table presents all 24 of
Python’s delimiters.

Delimiters Classification
( ) [ ] { } Grouping
. , : ; @ Punctuation
= += = *= /= //= %= **= Arithmetic assignment/ binding
&= != ^= <= >>= Bit wise assignment/ binding

(v) Operators
Operator i are the constructs (operator) which can manipulate the value of operands.
Consider the expression 4 + 5 = 9. Here, 4 and 5 are called operands and + is called
operator.

VALUES & TYPES


4) WHAT IS A NUMERIC LITERAL? GIVE EXAMPLE. [AU – Jan 2018]
o A numeric literal is a literal containing only the numeric or digits (0 – 9)
o An optional sign is + or -.
o If a numeric literal contains a decimal point, then it denotes a real value or float.
Example:
 12.21
 10.00
 00.02
o Or, it denotes an integer value.
Example:
 12
 21
o Commas are never used in numeric literals.
Example:
12,500 (Invalid)
12500 (Valid)

Unit II 37
Mailam Engineering College GE3151 - Problem Solving and Python Programming

General Example:
Operator Meaning Example (a=10, b=20)

+ Addition a + b = 30

- Subtraction a – b = -10

* Multiplication a * b = 200

/ Division b/a=2

% Modulus b%a=0

** Exponent a**b =10 to the power 20

// 9//2 = 4 and 9.0//2.0 = 4.0, -11//3 = -4, -11.0//3 = -


4.0

5) OUTLINE THE DATA TYPES SUPPORTED BY PYTHON WITH AN EXAMPLES.


[AU – Jan 2022]
Data type of an object determines what values it can have and what operations can be
performed on it. Data type is a category of values.
Types
(i) Integer
(ii) Float
(iii) Boolean
(iv)String
(v) List

(i) Integers and float:


A data type is a category for values, and every value belongs to exactly one data
type. All data values in Python are encapsulated in relevant object classes. The most
common data types in Python are listed in below.
Data Type Examples
Integers -2, -1, 0, 1, 2, 3, 4, 5
Floating-point numbers -1.25, -1.0, --0.5, 0.0, 0.5, 1.0, 1.25
The values -2 and 30, for example, are said to be integer values. The integer (or
int) data type indicates values that are whole numbers. Numbers with a decimal point,
such as 2.14, are called floating-point numbers (or floats).
Example for Integers
>>> 1 + 1
2
>>> a = 4
>>> type(a)
<type ‘int’>
Example for Floats
>>> c = 2.1
>>> type(c)
<type ‘float’>

(iii) Boolean
Boolean is a data type named after George Boole (1815-1864). A Boolean
variable can take only two values, True or False. The main use of this type is in logical
expressions.

Unit II 38
Mailam Engineering College GE3151 - Problem Solving and Python Programming

Example
a = True
b = 30 > 45 # b gets the value False
Boolean expressions are often used in conjunction with the if statement:
Boolean operators
Boolean operations are performed using the and, or, and not keywords in Python:
Example Result
True and False False
False or True True
(30 > 45) or (27 < 30) True
not True False
not (3 > 4) True
The operators follow some precedence rules which would make the parentheses in
the third line and in the last obsolete. Note that the and operator is implicitly chained in
the following Boolean expressions:
a<b<c # same as: a < b and b < c
a == b == c # same as: a == b and b == c
Example for Booleans
>>> 3 > 4
False
>>> test = (3 > 4)
>>> test
False
>>> type(test)
<type ‘bool’>

(iv) Strings:
Strings are amongst the most popular types in Python and it is an ordered
sequence of characters. We can create them simply by enclosing characters in quotes.
Python treats single quotes the same as double quotes. Creating strings is as simple as
assigning a value to a variable.
>>> str = “Think Positive”
Characters
Python does not have a distinct character type. In Python, a character is a string of
length. You can use the ord() built_in functions to convert from character to integer and
chr() built_in functions to convert from character to integer to Character.
Example:
1. The character “a” is a plain string of length 1:
>>> x = ‘a’
2. The integer equivalent of the letter “A”:
>>> x = “A”
>>> ord(x)
65
Operators on strings
The concatenate strings with the “+” operator and create multiple concatenated
copies of a string with the “*” operator. And, augmented assignment (+= and *=) also
work.
Examples
>>> ‘god ’ + ‘is ’ + ‘great’
‘god is great’
>>> ‘#’ * 40
‘########################################’
>>>
>>> s1 = ‘flower’
>>> s1 += ‘s’
>>> s1
‘flowers’

Unit II 39
Mailam Engineering College GE3151 - Problem Solving and Python Programming

(v) Lists:
Python offers a range of compound data types often referred to as sequences.
List is one of the most frequently used and very versatile data type used in Python. In
Python programming, a list is created by placing all the items (elements) inside a square
bracket [ ], separated by commas.
It can have any number of items and they may be of different types (integer, float,
string etc.).

my_list = [] # empty list


my_list = [1, 2, 3] # list of integers
my_list = [1, “World”, 3.4] # list with mixed datatypes
my_list = [“Horse”, [8, 4, 6], [‘a’]] # nested list
There are various ways in which we can access the elements of a list.
Example 1:
x = [10, 20, 30]
print(x[0],x[1],x[2])
for i in x:
print(i)
print (x)

VARIABLES & EXPRESSIONS

6) DEFINE VARIABLE. AND EXPLAIN HOW TO DECLARE VARIABLE AND EXPLAIN


ABOUT THE SCOPE OF THE VARIABLE.
A variable is an identifier, which holds a value. In programming, a value is assigned
to a variable.
A variable is nothing but a ‘reserved memory location to store values’. In other
words a variable in a program ‘gives data to the computer to work on’.
Variables hold different kind of data and the same variable might hold different
values during the execution of a program. Every value in Python has a data type.
Different data types in Python are Numbers, List, Tuple, Strings, Dictionary, etc.
Variables can be declared by any name or even alphabets like a, aa, abc etc.

Declaring variable
Let see an example with declare variable “b” and print it.
b=200
print ( b )

Re-declare a Variable
In this re-declare the variable even after you have declared it once.
Here variable initialized to c=0.
Later, re-assign the variable f to value “welcome”

Program
c = 0; #Declare a variable and initialize it
print (c)
c = “welcome” #re-declaring the variable works
print (c)
Output
0
Welcome

Delete a variable
In delete variable using the command del ”variable name”. In the example below,
deleted variable f and when proceed to print it, get error “variable name is not defined”
which means it has deleted the variable.

Unit II 40
Mailam Engineering College GE3151 - Problem Solving and Python Programming

Example
b = 102; #Declare a variable and initialize it
print (b)
del b
print (b)
NameError: name ‘b’ is not defined

Swap variables
Python swap values in a single line and this applies to all objects in python.
Syntax :
var1, var2 = var2, var1
Example
x = 10
y = 20
print(x) # 10
print(y) # 20

x, y = y, x

print(x) # 20
print(y) # 10
Scope of the variable
There are two types are available, they are given below.
(i) Local variable
(ii) Global variable

Local & Global Variables


In Python use the same variable for rest of the program or module and declare it
global variable, while if want to use the variable in a specific function or method you use
local variable. Let’s understand this difference between local and global variable with the
below program.
Variable “f” is global in scope and is assigned value 101 which is printed in
output
Variable f is again declared in function and assumes local scope. It is assigned
value “God is great.” which is printed out as an output. This variable is different from the
global variable “f” define earlier
Once the function call is over, the local variable f is destroyed. When it again,
print the value of “f” is it displays the value of global variable f=101.

Example 1: #Global vs. local variables in functions


f = 101
Print (f)
def someFunction():
#global f
f = “God is great”
print (f)
somefunction ()
print (f)

Output
101
God is great
101

Using the keyword global, you can reference the a global variable inside a function
Variable “f” is global in scope and is assigned value 101 which is printed in
output.Variable f is declared using the keyword global. This is NOT a local variable but

Unit II 41
Mailam Engineering College GE3151 - Problem Solving and Python Programming

the same global variable declared earlier. Hence when we print its value the output is
101.
We changed the value of “f” inside the function. Once the function call is over, the
changed value of the variable “f” persists. When we again, print the value of “f” is it
displays the value “changing global variable”.

Example 2:
f = 101
print (f) #Global vs. local variables in function
def someFunction():
global f
print (f)
f = “changing global variable”
someFunction ()
print (f)
Output
101
101
changing global variable

7) WHAT IS AN EXPRESSIONS? EXPLAIN WITH EXAMPLES


 In Python, most of the lines or statements are written in the form of expressions.
 Expressions are made up of operators and operands. Expressions are evaluated
according to operators.
 An expression is a combination of values, variables, and operators. Expressions
combine variables and constants to produce new values. A value by itself is
considered an expression.

Example:
A*B+C Where *, + are operators; A, B and C are operands.

Types of expressions
Based on the position of operators in an expression, Python supports three types of
expressions, they are,
 Infix expression
 Prefix expression
 Postfix expression

(i) Infix expression: The operator is placed in between the operands.


Example: b+c
(ii) Prefix expression: The operator is placed before the operands.
Example: +bc
(iii) Postfix expression: The operator is placed after the operands.
Example: bc+
In general, the expressions are named as based on the type of operators placed in
between operands.
Example
a+b Arithmetic expression
a>b Relational expression
(a > b) and (a> c) Logical expression

Unit II 42
Mailam Engineering College GE3151 - Problem Solving and Python Programming

8) EVALUATE THE FOLLOWING EXPRESSIONS IN PYTHON. [AU, Dec 2019]

i) 24//6%3
=4%3
=1

ii) float(4+int(2.39)%2)
=float(4+2%2)
=float(4+0)
=4.0

iii) 2**2**3
=4**3
=256

TUPLE ASSIGNMENTS

9) IN PYTHON, HOW TUPLE ASSIGNMENTS WILL ACHIEVE? EXPLAIN WITH


EXAMPLES

 A tuple is another sequence data type similar to list.


 A tuple consists of a sequence of elements separated by commas.
 The main differences between lists and tuples are:
 Lists are enclosed in brackets ( [ ] ) and their elements and size can be changed.
 Tuples are enclosed in parentheses ( ( ) ) and cannot be updated.

Example:
Tuple with string values
>>>T=('sun','mon','tue')
>>>print(T)
('sun', 'mon', 'tue')

Tuple with single character


>>>T=('P','Y','T','H','O','N')
>>>print(T)
('P', 'Y', 'T', 'H', 'O', 'N')

Tuple Assignments
Tuple assignment is an assignment with a sequence on the right side and a tuple
of variables on the left. The right side is evaluated and then its elements are assigned to
the variables on the left.

Example 1:
>>>T1=(10,20,30)
>>>T2=(100,200,300,400)
>>>print(T1)
(10, 20, 30)
>>>print(T2)
(100, 200, 300, 400)

Example 2 :
>>>T1=(10,20,30)
>>>T2=(100,200,300,400)
>>>print(T1)
(10, 20, 30)
>>>print(T2)
(100, 200, 300, 400)
>>>T1,T2=T2,T1 # swap T1 and T2

Unit II 43
Mailam Engineering College GE3151 - Problem Solving and Python Programming

>>>print(T1)
(100, 200, 300, 400)
>>>print(T2)
(10, 20, 30)

Explanation
The left side is a tuple of variables; the right side is a tuple of expressions. Each
value is assigned to its respective variable. All the expressions on the right side are
evaluated before any of the assignments.

Example 3 :
>>>T1=(10,20,30)
>>>T2=(100,200,300)
>>>t3=(1000,2000,3000)
>>>T1,T2=T2,T1,t3
Error:
Traceback (most recent call last):
File "<pyshell#3>", line 1, in <module>
T1,T2=T2,T1,t3
ValueError: too many values to unpack

Explanation:
Here, two tuples are in the left side and three tuples are in right side. So it gives
errors.
Example 4 :
>>>T1=(10,20,30)
>>>T2=(100,200,300)
>>>t3=(1000,2000,3000)
>>> T1,T2,t3=t3,T1,T2
>>>print(T1)
(1000, 2000, 3000)
>>>print(T2)
(10, 20, 30)
>>>print(t3)
(100, 200, 300)

OPERATORS

10) WHAT ARE OPERATORS? ILLUSTRATE EACH ONE WITH EXAMPLE.


(or)
NAME THE TYPES OF OPERATORS SUPPORTED BY PYTHON AND OUTLINE ANY
TWO WITH AN EXAMPLE. [AU – Jan 2022, Dec 2022] (or)
EXPLAIN THE DIFFERENT BOOLEAN AND BITWISE OPERATOR TYPES IN
PYTHON. [AU – Dec 2023]
Operators are the constructs (operator) which can manipulate the value of
operands.
Consider the expression 4 + 5 = 9. Here, 4 and 5 are called operands and + is
called operator.
Types of Operators
Python language supports the following types of operators.
i. Arithmetic Operators
ii. Comparison (Relational) Operators
iii. Assignment Operators
iv. Logical Operators
v. Bitwise Operators
vi. Membership Operators
vii. Identity Operators
Let us have a look on all operators one by one.

Unit II 44
Mailam Engineering College GE3151 - Problem Solving and Python Programming

i) Arithmetic Operators
Operator Meaning Example (a=10, b=20)

+ Addition a + b = 30

- Subtraction a – b = -10

* Multiplication a * b = 200

/ Division b/a=2

% Modulus b%a=0

** Exponent a**b =10 to the power 20

// Floor Division 9//2 = 4 and 9.0//2.0 = 4.0, -11//3 = -4, -


11.0//3 = -4.0

Example1
Integer arithmetic
days = int(input("Enter days: "))
months = days / 30
days = days % 30
print("Months = %d Days = %d" % (months, days))

Output
Enter days: 265
Months = 8 Days = 25

Example 2
// operator gives the floor division result

4.0 // 3
1.0
4.0 / 3
1.3333333333333333

ii) Comparison Operators


These operators compare the values on either sides of them and decide the relation
among them. They are also known as relational operators.

Operator Meaning Example (a=10, b=20)

== Equal to (a == b)

!= Not equal (a!=b)

> Greater than (a > b)

< Lesser than (a < b)

>= Greater than or equal to (a >= b)

<= Lesser than or equal to (a <= b)

Unit II 45
Mailam Engineering College GE3151 - Problem Solving and Python Programming

Example
a=int(input(“Enter A:”))
b=int(input(“Enter B:”))
if a> b:
print(“A is greater”)
else:
print(“B is greater”)

iii) Assignment Operators


It is used to hold a value of evaluated expression.
Operator Example Example

= c=a+b Assigns value of a + b into c

+= Add AND c += a Equivalent to c = c + a

-= Subtract AND c -= a Equivalent to c = c - a

*= Multiply AND c *= a Equivalent to c = c * a

/= Divide AND c /= a Equivalent to c = c / a

%= Modulus AND c %= a Equivalent to c = c % a

**= Exponent AND c **= a Equivalent to c = c ** a

//= Floor Division c //= a Equivalent to c = c // a

iv) Logical Operators [AU- Dec 2022]


There are following logical operators supported by Python language.
Assume variable a holds 10 and variable b holds 20 then
Operator Meaning Example

and Logical AND (a and b) is true.

or Logical OR (a or b) is true.

not Logical NOT Not (a and b) is false.

v) Bitwise Operators [AU- Dec 2022]


It works on bits and performs bit by bit operation. Assume if a = 60; and b = 13; Now
in binary format they will be as follows:
Operator Meaning Example

& Binary AND (a & b) (means 0000 1100)

| Binary OR (a | b) = 61 (means 0011 1101)

^ Binary XOR (a ^ b) = 49 (means 0011 0001)

~ Binary Ones Complement (~a ) = -61 (means 1100 0011 in 2's


complement form due to a signed binary
number.

Unit II 46
Mailam Engineering College GE3151 - Problem Solving and Python Programming

<< Binary Left Shift a << = 240 (means 1111 0000)

> Binary Right Shift a >> = 15 (means 0000 1111)


>
Example:
a = 0011 1100
b = 0000 1101
-----------------
a&b = 0000 1100
a|b = 0011 1101
a^b = 0011 0001
~a = 1100 0011

vi) Membership Operators [AU- Dec 2022]


Python’s membership operators test for membership in a sequence, such as strings,
lists, or tuples. There are two membership operators as explained below
Operator Example

in x in y, here in results in a 1 if x is a member of sequence y.

not in x not in y, here not in results in a 1 if x is not a member of sequence y.

vii) Identity Operators [AU- Dec 2022]


Identity operators compare the memory locations of two objects. There are two Identity
operators explained below:
Operator Example

is x is y, here is results in 1 if id(x) equals id(y).

is not x is not y, here is not results in 1 if id(x) is not equal to id(y).

11) BRIEFLY EXPLAIN ABOUT THE CONCEPT OF PRECEDENCE OF OPERATORS.


(OR) OUTLINE THE OPERATOR PRECEDENCE OF ARITHMETIC OPERATORS IN
PYTHON. [AU-Jan 18, 19] (or)
WHAT OPERATOR HAS THE HIGHEST PRECEDENCE IN PYTHON? [AU-Dec 23]
In this Python, we are going to look at operator precedence in Python. We will be
focusing on the operators we have already learned like **, *, /, //, %, + and -. It is
important to understand what operator will run first.
Operator Precedence
The list below will show which operator has more precedence over the operators.
So the first operator in the list will run before the second operator below.
1. ** – Exponent
2. *, /, %, // – Multiplication, true division, modulo, floor division. In this case if these
operators where in the same equation then the equation would run left to right.
3. +, – Addition and Subtraction are the last operators to run.

EXAMPLES
(i) Exponent and Multiplication
Exponent will always run before the multiplication equation. Take a look at the
example.
>>> 2 ** 4 + 2 #Exponent Runs First
18
>>> 2 * 4 ** 2 #If multiplication ran first this answer would be 16
32.

Unit II 47
Mailam Engineering College GE3151 - Problem Solving and Python Programming

(ii) Exponent and Division


Exponent will always run before a division equation. Take a look at this example.
>>> 4 / 2 ** 6 #Exponent runs first
0.0625
>>> 4 / 64 #2 ** 6 is 64
0.0625

(iii) Multiplication and Division


In this scenario Python will run the equation from left to right since multiplication
and division have the precedence. Take a look at the example below.
>>> 5 / 4 * 3 #In this case division is ran first then multiplied by 3
3.75

(iv) Multiplication and Addition


Multiplication will run before an addition equation since multiplication has more
precedence over addition. Here is an example.
>>> 2 + 4 * 4
18

(v) Addition and Subtraction


In this scenario the equation will run left to right since addition and subtraction are
on the same level.
>>> 2 + 3 - 5 + 8 - 4 + 2 - 9
-3
Example
x = (15 + 6) - 10 * 4
print (x)
In the expression to evaluate the value of x, the brackets have highest of all
precedence, so is evaluated before anything else, then * is done, and lastly the -
subtraction, resulting in an output of -19 (minus 19), as explained here...
15 + 6 is 21
10 * 4 is 40
21 - 40 is -19
Operator precedence rule in Python
Operators Meaning
() Parentheses
** Exponent
+x, -x, ~x Unary plus, Unary minus, Bitwise NOT
Multiplication, Division, Floor division,
*, /, //, %
Modulus
+, - Addition, Subtraction
<<, >> Bitwise shift operators & Bitwise AND
^ Bitwise XOR
| Bitwise OR
in ==,!=, >, >=, <, <=, Comparisons, Identity, Membership
is, is not, in, not in operators
not Logical NOT
and Logical AND
or Logical OR
# Left-right associativity
# Output: 3
print(5 * 2 // 3)
# Shows left-right associativity
# Output: 0
print(5 * (2 // 3))

Unit II 48
Mailam Engineering College GE3151 - Problem Solving and Python Programming

COMMENTS
12) ILLUSTRATIVE COMMENTS IN PYTHON IN BRIEFLY.
Comments in Python are also quite different than other languages, but it is pretty
easy to get used to.
In Python there are basically two ways to comment:
 Single line and
 Multiple line.
Single line comments is good for a short, quick comment (or for debugging), while
the block comments is often used to describe something much more in detail or to block
out an entire chunk of code.
A hash sign (#) that is not inside a string literal is the beginning of a comment. All
characters after the #, up to the end of the physical line, are part of the comment and
the Python interpreter ignores them.
(i) Single line comment
A single line comment starts with the number sign (#) character:
# This is a comment
print(‘Hello’)
For each line you want to comment, put the number sign (#) in front.
# print(‘This is not run’)
print(‘Hello’)

(ii) Multiline comment


Multiple lines can be created by repeating the number sign several times:
# This is a comment
# second line
x=4
but this quickly becomes impractical. A common way to use comments for multiple
lines is to use the (”’) symbol:
‘’’ This is a multiline
Python comment example.’’’
x=5

13) WRITE THE PYTHON PROGRAM FOR THE CONCEPT OF EXCHANGE THE
VALUES OF TWO VARIABLES. [AU – Jan 2018, Jan 2019, Dec 2022]
(or) WRITE AND EXPLAIN THE PYTHON PROGRAM TO SWAP TWO NUMBERS
WITH AND WITHOUT TEMPORARY VARIABLES. [AU – Apr/May 2022]

Program 1
a = input(“Enter value of a: “)
b = input(“Enter value of b: “)
temp = a # create a temporary variable and swap the values
a=b
b = temp
print(“The value of a after swapping: {}”.format(a))
print(“The value of b after swapping: {}”.format(b))
Output:
The value of a after swapping: 200
The value of b after swapping: 25

Program 2
a = input(“Enter value of a: “)
b = input(“Enter value of b: “)
a,b=b,a
print(“The value of a after swapping:”,a)
print(“The value of b after swapping:”,b)
Output:
The value of a after swapping: 200
The value of b after swapping: 25

Unit II 49
Mailam Engineering College GE3151 - Problem Solving and Python Programming

14) WRITE A PYTHON PROGRAM TO CIRCULATE THE VALUES OF N VARIABLES


(or)
WRITE A PYTHON PROGRAM TO ROTATE A LIST BY RIGHT n TIMES WITH AND
WITHOUT SLICING TECHNIQUE. [AU, DEC 2019]

def rotate(x,n):
list1=x[n:] + x[:n]
return list1
sample=[1,2,3,4,5]
print("Original list=",sample)
mylist=rotate(sample,1)
print("List rotated clockwise by 1=",mylist)
mylist=rotate(sample,2)
print("List rotated clockwise by 2=",mylist)
mylist=rotate(sample,-2)
print("List rotated anti-clockwise by 2=",mylist)

Output:
Original list= [1, 2, 3, 4, 5]
List rotated clockwise by 1= [2, 3, 4, 5, 1]
List rotated clockwise by 2= [3, 4, 5, 1, 2]
List rotated anti-clockwise by 2= [4, 5, 1, 2, 3]

15) WRITE A PYTHON PROGRAM TO FIND DISTANCE BETWEEN TWO POINTS:


import math [AU – Dec 23]
p1=[4,6]
p2=[5,7]
distance=math.sqrt(((p2[0] - p1[0])**2) + ((p2[1] - p1[1])**2))
print("Distance between two points =",distance)

Output:
Distance between two points = 1.4142135623730951

16) WRITE A PYTHON PROGRAM TO CHECK WHETHER THE YEAR IS LEAP YEAR
OR NOT: [AU – Apr 24]
print(“Enter ‘x’ for exit.”)
num = input(“Enter year: “)
if num == ‘x’:
break
try:
year = int(num)
except ValueError:
print(“Please, enter year...”)
else:
if((year%4 == 0) and (year%100 != 0)):
print(year, “is a Leap Year.\n”)
elif(year%100 == 0):
print(year, “is not a Leap Year.\n”)
elif(year%400 == 0):
print(year, “is a Leap Year.\n”)
else:
print(year, “is not a Leap Year.\n”)

Output:
Enter ‘x’ for exit.
Enter year: 2004
2004 is a Leap Year.

Unit II 50
Mailam Engineering College GE3151 - Problem Solving and Python Programming

Enter ‘x’ for exit.


Enter year: 2003
2003 is not a Leap Year.

17) WRITE A PYTHON PROGRAM USING FUNCTION TO FIND THE SUM OF FIRST
‘N’ EVEN NUMBERS AND PRINT THE RESULT. [AU – Jan 2018]
def sumeven(n):
i=2
sum=0
while(i<=n):
sum=sum+i
i=i+2
return sum
n=int(input(“Enter n”))
m=sumeven(n)
print(“The sum of first N even number is ”,m)

Output:
Enter n 20
The sum of first N even number is 110

18) WRITE A PYTHON PROGRAM PRINT THE MAXIMUM AMONG ‘n’ RANDOMLY
GENERATE ‘d’ NUMBERS BY STORING THEM IN A LIST. [AU, Dec 2019]
Program:
import random
n=int(input(“Enter N:”))
start=int(input(“Enter starting value:”))
end=int(input(“Enter ending value:”))
res=[]
for i in range(num):
res.append(random.randint(start,end))
print(“The list is:”, res)
print(“The maximum value in list is “,max(res))

Output:
Enter N: 5
Enter starting value:1
Enter ending value: 7
The list is: [2,2,7,1,1]
The maximum value in list is 7

19) WRITE A PYTHON PROGRAM TO FIND THE ROOTS OF A QUADRATIC


EQUATION GIVEN THE COEFFICIENTS a, b, c. [AU, Dec 2022]
Program:
import math
a=int(input(‘Enter A:’))
b=int(input(‘Enter B:’))
c=int(input(‘Enter C:’))
d=(b**2) – (4 * a * c)
if d>0:
r1=(-b + math.sqrt(d))/(2*a)
r2=(-b - math.sqrt(d))/(2*a)
print(‘ROOT 1 =’, r1)
print(‘ROOT 2 =’, r2)
else:
print(‘The Roots are Imaginary’)

Unit II 51
Mailam Engineering College GE3151 - Problem Solving and Python Programming

20) WRITE A PYTHON PROGRAM TO PRINT THE DIGITS AT ONE’S PLACE OF A


NUMBER. [AU - Dec 2022]
Program:
n=int(input(‘Enter an integer number:’))
d=n%10
print(“The one’s place of number = “, d)

21) TO FIND WHEATHER A GIVEN NUMBER IS ARMSTRONG NUMBER OR NOT.


[AU - Apr 2024]
n=int(input(‘Enter an integer number:’))
m=n
sum=0
while n>0:
d=n%10
sum=sum+(d*d*d)
n=n//10
if sum==m:
print(‘The given number is an Armstrong Number’)
else:
print(‘The given number is Not Armstrong Number’)

22) TO PRINT FIBONACCI SERIES [AU - Apr 2024]


n=int(input(‘Enter an integer number:’))
a=0
b=1
print(a)
print(b)
i=1
while i<=n-2:
c=a+b
print(c)
a=b
b=c
i=i+1

23) TO CONVERT CELSIUS TO FAHRENHEIT [AU - Apr 2024]

celsius = float(input("Enter temperature in Celsius: "))


fahrenheit = (celsius * 9/5) + 32 return fahrenheit
print(‘The Fahrenheit value is’,fahrenheit)

“The difference between ordinary and


Extraordinary is just that little “Extra”

Unit II 52
Mailam Engineering College GE3151 - Problem Solving and Python Programming

UNIT III CONTROL FLOW, FUNCTIONS


Conditionals: Boolean values and operators, conditional (if), alternative (if-
else), chained conditional (if-elif-else); Iteration: state, while, for, break,
continue, pass; Fruitful functions: return values, parameters, scope: local and
global, function composition, recursion; Strings: string slices, immutability,
string functions and methods, string module; Lists as arrays. Illustrative
programs: square root, gcd, exponentiation, sum the array of numbers, linear
search, binary search.

PART – A
BOOLEAN VALUES & OPERATORS
1) Define Boolean values.
 Boolean values are the two constant objects False and True.
 They are used to represent truth values (false or true).
 In numeric contexts (for example, when used as the argument to an arithmetic
operator), they behave like the integers 0 and 1, respectively.
 The built-in function bool() can be used to cast any value to a Boolean,
 if the value can be interpreted as a truth value
 They are written as False and True, respectively.

2) List out the Boolean operators.


 or operator Example: x or y
 and operator Example: x and y
 not operator Example: not x

3) Define operator. Give example of operator.


 Operator is a symbol that is used to manipulate mathematical and other
expression.
 Expression is the combination of operator and operands.
Example: a + b
 a, b are operands
 + is a operator

4) List out the types of operator.


Python language supports the following types of operators.
o Arithmetic Operators
o Comparison (Relational)Operators
o Assignment Operators
o Logical Operators
o Bitwise Operators
o Membership Operators
o Identity Operators

CONDITIONAL STATEMENTS& ITERATIVE STATEMENTS


5) Define conditional statements.
Decision structures evaluate multiple expressions which produce TRUE or
FALSE as outcome. Let need to determine which action to take and which statements
to execute if outcome is TRUE or FALSE otherwise.
Types of Conditional statements
 if statements(conditional)
 if-else statements(alternative)
 if-elif-else (chained conditional)
 Nested Conditional

6) What is the purpose of iteration? Give example.


Iteration is simply known as looping. A loop statement allows us to execute a
statement or group of statements multiple times. Repeated execution of a set of
statements is called iteration.

Unit III 53
Mailam Engineering College GE3151 - Problem Solving and Python Programming

Types
i) While loop
ii) For loop
iii) Nested loop
Example
count = 0
while (count < 9):
print(“The count is:”, count )
count = count + 1

7) What are unconditional looping statements?


Any loop that needs to be executed compulsorily without any condition is
called an unconditional loop. This means that the loop will be executed in the program
without any conditional checks and the output of the loop is an essential one for the
completion of the program.
Example:
i) Break statement
ii) Continue statement
iii) Pass statement

8) What is the purpose break, continue and pass statement in python?


(OR)
What is the purpose of pass statement in python? [AU – Apr/May 2022]
break: It terminates the loop statement and transfers execution to the statement
immediately following the loop.
Continue: It causes the loop to skip the remainder of its body and
immediately retest its condition prior to reiterating.
Pass: The pass statement in Python is used when a statement is required
syntactically but you do not want any command or code to execute.

9) Write a Python program to accept two numbers, multiply them and print the
result. [AU – Jan 2018]
a=int(input(“Enter A:”))
b=int(input(“Enter B:”))
c=a*b
print(“The product of the given two numbers:”,c)

10) Write a Python program to accept two numbers, find the greatest and print the
result. [AU – Jan 2018]
a=int(input(“Enter A:”))
b=int(input(“Enter B:”))
if a > b:
print(“First number is largest “,a)
else:
print(“Second number is largest “,b)

11) What is iterative statements in Python? (or)


Name the two types of iterative statements supported by Python.[AU – Jan 2022]
Group of statements or instructions are executed again and again until the condition
occur false.
In Python, there are two types of iterative statements are available, they are listed
below.
 While and for loop

12) Write a for loop that prints numbers from 0 to 57 using the range functions in
python. [AU – Jan 2022]
for i in range(58):
print(i)

Unit III 54
Mailam Engineering College GE3151 - Problem Solving and Python Programming

13) Do Loop statements have else clause? When will it be executed?


[AU – Dec 2019]
Yes, In Python, else clause is associated with looping statements. But, it is optional one.
The else clause executes after the loop completes normally. This means that the loop did not
encounter a break statement.
Example:
i=1
while i<5:
print(i)
i=i+1
else:
print("After Loop")
print("The End")

Output:
1
2
3
4
5
After Loop
The End

14) Present the flow of execution for a while statement. [AU – Jan 2019]
Step 1: Evaluate the condition, yielding true or false.
Step 2: If the condition is true, execute the body and then go back to step 1.
Step 3: If the condition is false, exit from the block of looping.

FUNCTION, FRUITFUL FUNCTION, PARAMETERS,


LOCAL AND GLOBAL SCOPE

15) What are function and fruitful function? [AU – Dec 2023]
Function is a block of statement that will execute for a specific task.
Fruitful function
Functions that return values are sometimes called fruitful functions. In many
other languages, a function that doesn’t return a value is called a procedure, but we will stick
here with the Python way of also calling it a function, or if we want to stress it, a non-
fruitful function.

16) Define parameter. List out its types.


Data sent to one function from another is called parameter. There are two
types of parameters are available in general, they are given below.
i) Formal parameter
ii) Actual Parameter

17) How will you call a function by arguments?


You can call a function by using the following types of formal arguments:
 Required arguments
 Keyword arguments
 Default arguments
 Variable-length arguments

18) Define scope of the variable and its types.


All variables in a program may not be accessible at all locations in that program.
This depends on where you have declared a variable. The scope of a variable determines
the portion of the program where you can access a particular identifier.
There are two basic scopes of variables in Python:
 Global variables & Local variables

Unit III 55
Mailam Engineering College GE3151 - Problem Solving and Python Programming

COMPOSITION & RECURSION


19) What is composition?
In situation to call one function from within another function. This
ability is called composition.
Example:
radius = distance(xc, yc, xp, yp)
result = area(radius)
return result

20) Define recursion with example. [AU – Jan 2019, Jan 2022]
The function call by itself, this is known as recursion.
Example:
def factorial(n):
if n == 0:
return 1
else:
fact = n*factorial(n-1)
return result

21) List out the advantages of recursion.


 Recursion adds clarity and (sometimes) reduces the time needed to write and debug
code (but doesn't necessarily reduce space requirements or speed of execution).
 Reduces time complexity.
 Performs better in solving problems based on tree structures.

22) List out the disadvantages of recursion.


 It is usually slower due to the overhead of maintaining the stack.
 It usually uses more memory for the stack.

STRING, STRIBNG SLICES & MODULES

23) What is a module? Give example.


A Module is a file containing Python definitions and statements. The file name is the
module name with the suffix .py appended.
Example:
import math
import string
import DateTime

24) What is string? Give example.


A sequence of character enclosing within quotes. Python treats single quotes the same
as double quotes.

Creating strings is as simple as assigning a value to a variable.


Example:
var1 = 'Hello World!'
(or)
var1 = "Hello World!"

25) List out some escape sequence in python.


notation Description

\a Bell or alert

\b Backspace

\cx Control-x

Unit III 56
Mailam Engineering College GE3151 - Problem Solving and Python Programming

notation Description

\C-x Control-x

\e Escape

\f Form feed

\M-\C-x Meta-Control-x

\n Newline

\nnn Octal notation, where n is in the range 0.7

\r Carriage return

\s Space

\t Tab

\v Vertical tab

26) What is slicing operator in python? Give an example. [AU – Dec 2022]
The slice s[start:end] is the elements beginning at start and extending up to but not
including end. (Or) piece of string
Example:
s = "Hello".
 s[1:4] is 'ell' -- chars starting at index 1 and extending up to but not including index 4
 s[1:] is 'ello' -- omitting either index defaults to the start or end of the string

27) Is strings are immutable in python?


Yes, strings are immutable, which means cannot change an existing string. The best
you can do is creating a new string that is a variation on the original.
Example:
sample = "Hello, world!"
sample1 = 'J' + greeting[1:]
print(sample1)
print(sample) # same as it was

Output
Jello, world!
Hello, world!

28) List out some important string methods.


SN Methods with Description

1 capitalize()- Capitalizes first letter of string

2 isalnum()- Returns true if string has at least 1 character and all characters are
alphanumeric and false otherwise.

3 isalpha()- Returns true if string has at least 1 character and all characters are
alphabetic and false otherwise.

4 isdigit()- Returns true if string contains only digits and false otherwise.

Unit III 57
Mailam Engineering College GE3151 - Problem Solving and Python Programming

29) Write a program to display a set of strings using range() function.


[AU – Dec 2019]
for i in range(2):
print(“Success”)
print(“**********”)
for i in range(2**3):
print(“Success”)
print(“**********”)

Output:
Success
Success
**********
Success
Success
Success
Success
Success
Success
Success
Success
**********

30) What is ‘len’ function? Give example for how it is used on strings.
[AU – Apr 2024]

The len() function in Python is used to return the length of an object. For strings, it
returns the number of characters (including spaces, punctuation, etc.) present in the string.
Example:
my_string = "Hello, world!"
length = len(my_string)
print("The length of the string is’,length)
Output:
The length of the string is 13

31) How to split strings and what function is used to perform that operation?
We can split a string into a list of substrings using the split() function. This function
breaks the string at the specified delimiter (by default, whitespace) and returns a list of the
resulting substrings.

Syntax:
string.split(separator, maxsplit)
separator: The delimiter at which the string is split. If not specified, the default is any
whitespace (space, newline, tab, etc.).
maxsplit: (Optional) The maximum number of splits to do. If not specified, all occurrences of
the separator are considered.

Example:
text = "Python is fun"
words = text.split() print(words)
Output:
['Python', 'is', 'fun']

32) What is Linear Search? [AU – Dec 2019]


In searching techniques, linear searching is also known as ‘Sequential Searching’. It is
a method for finding an element within a list. It sequentially checks each element of the list
until a match is found or the whole list has been searched. This mechanism also achieved in
unsorted data.

Unit III 58
Mailam Engineering College GE3151 - Problem Solving and Python Programming

33) Write a python program to add two matrices. [AU – Dec 2022]
a=[[1,2],
[2,3]]
b=[[2,3],
[1,2]]
c=[[0,0],
[0,0]]
for i in range(len(a)):
for j in range(len(a[0])):
c[i][j]=a[i][j] + b[i][j]
for r in c:
print(r)

34) Write a simple function to multiply two numbers in python. [AU – Dec 2022]
def product(a,b):
c=a*b
return c
print(“The Product of two numbers = “,product(5,3))

Unit III 59
Mailam Engineering College GE3151 - Problem Solving and Python Programming

PART – B
CONDITIONAL STATEMENTS

1) EXPLAIN THE BRANCHING STATEMENTS IN PYTHON WITH RELEVANT SYNTAX AND


EXAMPLE.
(or)
LIST THE THREE TYPES OF CONDITIONAL STEMENTS AND EXPLAIN THEM.[AU – Jan 2019]
(or)
OUTLINE THE CONDITIONAL BRANCHING STATEMENTS IN PYTHON WITH AN EXAMPLE.
[AU – Jan 22, Dec 22 & Dec 23]
The execution of the program taking action according to the conditions.
This concept is also known as
 Conditional statements or
 Branching statements
This technique is somewhat differ from normal program. The sequence of the control
flow may differ from normal logical code. Decision structures evaluate multiple expressions
which produce TRUE or FALSE as outcome. You need to determine which action to take and
which statements to execute if outcome is TRUE or FALSE otherwise.

Types of Conditional statements


 if statements (conditional)
 if-else statements (alternative)
 if-elif-else (chained conditional)
[AU – Jan 2018] – PART B
 Nested Conditional
[AU – Jan 2018] – PART B
Let us see each decision making in briefly manner:

i) If Statement
It is similar to that of other languages. The if statement contains a logical expression
using which data is compared and a decision is made based on the result of the comparison.
Syntax
if expression:
statement(s)

If the Boolean expression evaluates to TRUE, then the block of statement(s) inside the
if statement is executed. If Boolean expression evaluates to FALSE, then the first set of code
after the end of the if statement(s) is executed.

Flowchart

Example
sal=int(input(“Enter salary:”))
if sal>=10000:
sal=sal+2000
print(“salary=”,sal)
Output
Enter salary: 11000
Salary=13000

Unit III 60
Mailam Engineering College GE3151 - Problem Solving and Python Programming

ii) If…else Statement


An else statement can be combined with an if statement. An else statement contains
the block of code (false block) that executes if the conditional expression in the if statement
resolves to 0 or a FALSE value.
The else statement is an optional statement and there could be at most only one else
statement following if.
Syntax
if expression:
statement(s)
else:
statement(s)

Flowchart
Example
sal=int(input(“Enter salary:”))

if sal>=10000:
sal=sal+2000
else:
sal=sal+1000
print(“salary=”,sal)

Output
Enter salary:8000
Salary=9000

iii) The elif Statement (chained conditional) [AU – Jan 2018] – PART B
The elif statement allows you to check multiple expressions for TRUE and execute a
block of code as soon as one of the conditions evaluates to TRUE. Similar to the else, the elif
statement is optional. However, unlike else, for which there can be at most one statement,
there can be an arbitrary number of elif statements following an if.
Syntax
if expression1:
statement(s) if..elif...statements to simulate switch case as follows:
elif expression2:
statement(s)
elif expression3:
statement(s)
else:
statement(s)

Flowchart
Example
a=int(input(“Enter A:”))
b=int(input(“Enter B:”))
c=int(input(“Enter C:”))
if a>b and a>c:
print(“A is Greater”)
elif b>c:
print(“B is Greater”)
else:
print(“C is Greater”)
Output
Enter A: 12
Enter B: 22
Enter C: 2
B is Greater

Unit III 61
Mailam Engineering College GE3151 - Problem Solving and Python Programming

iv) Nested Conditionals [AU – Jan 2018] – PART B


One conditional can also be nested within another. (It is the same theme of composibility,
again!) We could have written the previous example as follows:
Syntax
if expression1:
statement(s)
else:
if expression2:
statement(s)
else:
statement(s)

Flowchart
Example
num=float(input("Enter a number: "))
if num>=0:
if num==0:
print("Zero")
else:
print("Positive number")
else:
print("Negative number")

Output 1
Enter a number: 5
Positive number
Output 2
Enter a number: -54
Negative number

ITERATION STATEMENT

2) EXPLAIN THE ITERATION IN PYTHON WITH RELEVANT SYNTAX AND EXAMPLE.


A loop statement allows us to execute a statement or group of statements multiple
times. Repeated execution of a set of statements is called iteration. Programming languages
provide various control structures that allow for more complicated execution paths. Python has
two statements for iteration they are given below
Types
i) while loop [AU – Jan 2018, Dec 2022] – PART B
ii) for loop
iii) nested loop
Let us see one by one as follows

i) While Loop [AU – Jan 2018] – PART B


A while loop statement executes a block of statement again and again until the
condition will occur false (or) Repeats a statement or group of statements while a given
condition is TRUE.
It tests the condition before executing the loop body so this technique is known as
Entry controlled loop.

Syntax

while expression:
statement(s)

Unit III 62
Mailam Engineering College GE3151 - Problem Solving and Python Programming

Flowchart
Example
count = 0
while (count < 9):
print(“The count is:”, count)
count = count + 1
print("The End")

Output 1
The count is: 0
The count is: 1…..

The count is: 8


The End

ii) For Loop


Executes a sequence of statements multiple times and abbreviates the code that
manages the loop variable.

Syntax

for iterating_var in sequence:


statements(s)

Flowchart
Example
for letter in 'Python':
print(“Current Letter :”, letter)

fruits = ['banana', 'apple', 'mango']


for fruit in fruits: # Second Example
print(”Current fruit :”, fruit)

print("The End")

iii) Nested Loops


Python programming language allows using one loop inside another loop. Following section
shows few examples to illustrate the concept. You can use one or more loop inside any
another while, for or do...while loop.
Syntax - nested for loop
for iterating_var in sequence:
for iterating_var in sequence:
statements(s)
statements(s)

Unit III 63
Mailam Engineering College GE3151 - Problem Solving and Python Programming

Syntax - nested while loop


while expression:
while expression:
statement(s)
statement(s)

Note:
Loop nesting is that you can put any type of loop inside of any other type of loop. For
example a for loop can be inside a while loop or vice versa.

Example
# Find the prime numbers from 2 to 100:
i=2
while(i < 100):
j=2
while(j <= (i/j)):
if not(i%j): break
j=j+1
if (j > i/j) :
print( i, " is prime")
i=i+1
print("The End")

Output
2 is prime
3 is prime
…..
89 is prime
97 is prime
The End

BREAK, PASS & CONTINUE

3) EXPLAIN ABOUT UNCONDITIONAL LOOPING STATEMENTS WITH RELEVANT


EXAMPLE.
(OR)
OUTLINE WHILE LOOP, BREAK STATEMENT AND CONTINUE STATEMENT IN PYTHON
WITH AN EXAMPLE. [AU – Jan 2022]
(OR)
WHAT IS THE DIFFERENCE BETWEEN BREAK AND CONTINUE IN PYTHON? EXPLAIN
WITH SUITABLE EXAMPLES.

Types:
 break statement [AU –JAN 2018] – PART B
 continue statement [AU –JAN 2018] – PART B
 pass statement
Let us see one by one as follows

i) Break Statement
Terminates the loop statement and transfers execution to the statement immediately
following the loop. The most common use for break is when some external condition is
triggered requiring a hasty exit from a loop.
The break statement can be used in both while and for loops.
If you are using nested loops, the break statement stops the execution of the
innermost loop and start executing the next line of code after the block.
Syntax
break

Unit III 64
Mailam Engineering College GE3151 - Problem Solving and Python Programming

Flowchart Example
for letter in 'Python': # First Example
if letter == 'h':
break
print(“Current Letter :”, letter)

var = 10 # Second Example


while var> 0:
print(“Current variable value :”, var)
var = var -1
if var == 5:
break
print( "The End")

Output
Current Letter : P
Current Letter : y
Current Letter : t
Current variable value : 10
Current variable value : 9
Current variable value : 8
Current variable value : 7
Current variable value : 6
The End

ii) Continue Statement


It returns the control to the beginning of the while 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 can be used in both while and for loops.
Syntax
Continue
Flowchart

Example
for letter in 'Python': # First Example
if letter == 'h':
continue
print(”Current Letter :”, letter)
var = 10 # Second Example
while var> 0:
var = var -1
if var == 5:
continue
print(“Current variable value :”, var)
print("The End”)

Unit III 65
Mailam Engineering College GE3151 - Problem Solving and Python Programming

Output
Current Letter : P
Current Letter : y
Current Letter : t
Current Letter : o
Current Letter : n
Current variable value : 9
Current variable value : 8
Current variable value : 7
Current variable value : 6
Current variable value : 4
Current variable value : 3
Current variable value : 2
Current variable value : 1
Current variable value : 0
The End

ii) Pass Statement


The pass statement in Python is used when a statement is required syntactically but
you do not want any command or code to execute.
The pass statement is a null operation; nothing happens when it executes. The pass is
also useful in places where your code will eventually go, but has not been written yet.

Syntax
pass

Example
for letter in 'Python':
if letter == 'h':
pass
print(“This is pass block”)
print(“Current Letter :”, letter)
print("The End")
Output
Current Letter : P
Current Letter : y
Current Letter : t
This is pass block
Current Letter : h
Current Letter : o
Current Letter : n
The End

FUNCTIONS
4) BRIEFLY EXPLAIN ABOUT THE FUNCTION WITH CLEAREXAMPLE.
(OR)
EXPLAIN THE SYNTAX AND STRUCTURE OF USER DEFINED FUNCTIONS IN PYTHON
WITH EXAMPLES. ALSO DISCUSS ABOUT PARAMETER PASSING IN FUNCTIONS.
[AU-JAN 19]
A function is a named container for a block of code that will execute for a specific task.
Functions help programmers to break the program into small manageable units or modules.
Functions may or may not take arguments and may or may not produce a result.
Advantages of using functions in Python
 Reusability
 Better readability
 Easy to debug and testing
There are two types of functions:

Unit III 66
Mailam Engineering College GE3151 - Problem Solving and Python Programming

(i) User-defined functions and


(ii) Library functions/PREDEFINED function,

(i) USER-DEFINED FUNCTION


ELEMENTS OF USER DEFINED FUNCTIONS
In python the user defined functions contain two elements. They are,
 Function definition
 Function call
Function definition
A function definition specifies the name of a new function and the sequence of
statements that run when the function is called.
Syntax

The elements of a function definition are,


1. Function header
2. Function body
Function Header
 The first line of a function definition is the function header.
 A function header starts with the keyword def, followed by the function name.
 The function name is followed by a comma-separated list of identifiers called formal
parameters, or simply parameters.
 The parameter list is ended with a colon ( : ).

Function Body
 The function body follows the function header.
 The function body contains one or more valid Python statements or the function's
instructions.
 Statements must have same indentation level, relative to the function header.
Example:
def greet(name):
print(“Hello,” + name + “. Good morning!”)
greet(‘saravanan’)

Output:
Hello, saravanan. Good morning

Function Call
 A function call is a statement that runs a function.
 It consists of the function name followed by an argument list in parentheses.
 Once function is defined, it can be called from another function, program or even the
Python prompt.
 To call a function, simply type the function name with appropriate parameters.
def functionName():
... .... ...
... ...
...
... .... ...
...
functionName()
...
... .... ...
...

Unit III 67
Mailam Engineering College GE3151 - Problem Solving and Python Programming

Program:
def swap(a,b):
a,b=b,a
print("After swap :")
print("First number = ",a)
print("second number = ",b)
a=int(input(“Enter the first number :"))
b=int(input("Enter the second number :"))
print("Before swap :")
print("First number = ",a)
print("second number = ",b)
swap(a,b)

Output:
Enter the first number:56
Enter the second number: 97
Before swap:
First number = 56
second number = 97
After swap:
First number = 97
second number = 56

(ii) BUILT-IN FUNCTIONS


 Built-in-functions are predefined functions. The Python interpreter has a number of
built-in functions and types, they are always available.
 The user can use the functions but cannot modify them. abs(), float(), format(),
help(), input() etc., are some of the built in functions in Python.
Example:
>>>divmod (14,5)
(2,4) // 2 is quotient and 4 is remainder
>>>import math
>>>math.sqrt(4)
2.0

5) BRIEFLY EXPLAIN ABOUT FUNCTION PROTOTYPES. [AU – Apr 23]


In Python, there is no concept of explicitly declaring a function prototype as in
languages like C or C++.
Instead, functions in Python are defined directly using the def keyword and Python's
dynamic typing system means we don't need to declare variable types in the function header.
However, function definitions can include type hints (optional) for clarity.

Refer Question number: 4, Page number: 67

PARAMETER PASSING IN FUNCTION


6) EXPLAIN IN DETAIL ABOUT THE CONCEPT OF PARAMETERS&ARGUMENTS.(or)
DESCRIBE PARAMETER PASSING IN FUNCTIONS USING EXAMPLES. [AU-Dec 22]
 Parameter: A name used inside a function to refer to the value passed as an
argument.
 Argument: A value provided to a function when the function is called. This value is
assigned to the corresponding parameter in the function.
 Some of the functions require arguments. For example, math.sin requires number as
an argument.
 Some functions take more than one argument. For example, math.pow takes two
arguments, the base and the exponent.
 Inside the function, the arguments are assigned to variables called parameters. Here is
a definition for a function that takes an argument:

Unit III 68
Mailam Engineering College GE3151 - Problem Solving and Python Programming

Example
a =15
b =20
c=5
d = 10
defcalcu(no1, no2):
total = no1 + no2
print(total )
calc(a,b)
Output:35

7) ILLUSTRATIVE ARGUMENTS IN FUNCTION AND EXPLAIN THE TYPES OF


ARGUMENTS WITH NEAT EXAMPLES. [AU, Dec 2019]
ARGUMENTS
 The ‘arguments’ means parameter in a function.
 An argument is a way of passing data into a function when we don’t
Know which variable or variables that data is going to be in.
 Arguments are defined inside the parentheses.
 And each argument is given a name, with a comma separating each.
 An argument acts as a temporary reference to the data that you
passed in while the function is running.

Example 1:
a =15
b =20
c=5
d = 10
defcalcu(no1, no2):
total = no1 + no2
print(total )
calc(a,b)
Output:
35
Explanation:
When we call the calc function, the two variables that we’ve passed in (a and b) are
put into the arguments no1 and no2.
This always happens in the same order you define the argument in other words, the first
variable you pass in is assigned to the first argument, the second to the second argument,
and so on for as many arguments as your function takes.
TYPES:

(i) Required arguments


(ii) Default Arguments [AU, Dec 2019]
(iii) Keyword arguments [AU, Dec 2019]
(iv) Variable-length arguments

(i) Required arguments


Required arguments are the arguments passed to a function in correct positional order.
Here, the number of arguments in the function call should match exactly with the function
definition.
Example:
def add(a,b):
c=a+b
print(c)
add(10,20) # Output is30
add(20) # Error: add() missing 1 required positional argument:'b'

Unit III 69
Mailam Engineering College GE3151 - Problem Solving and Python Programming

(ii) Default arguments


Let, provide a default value to an argument by using the assignment operator (=).
Example:
def add(a,b=25):
c=a+b
print(c)
add(10,20) # Output is30
add(10) # Error: add() missing 1 required positional argument:'b'

Output:
30
35
(iii) Keyword arguments
 Python allows functions to be called using keyword arguments.
 We can mix positional arguments with keyword arguments during a function call.
 But we must keep in mind that keyword arguments must follow positional
arguments.
Example:
def details(rno, name="arun",dept="CSE"):
print("Reg No=",rno,"Name=",name,"Department=",dept)

details(121)
details(122,name="Basha")
details(123,name="David",dept="Mech")

Output:
Reg No= 121 Name= arun Department= CSE
Reg No= 122 Name= Basha Department= CSE
Reg No= 123 Name= David Department= Mech

iv) Variable-length arguments


 The number of arguments that will be passed into a function is not known in advance.
 Python allows us to handle this kind of situation through function calls with arbitrary
number of arguments.
 Use an asterisk (*) before the parameter name to denote this kind of arguments.
Example:
def welcome(*names):
for i in names:
print(i)
welcome(“Arun”,”Basha”,”David”,”Zahir”)

Output:
Arun
Basha
David
Zahir

Unit III 70
Mailam Engineering College GE3151 - Problem Solving and Python Programming

RETURN VALUES

8) WITH CLEAR EXAMPLE, EXPLAIN RETURN STATEMENT IN FUNCTION.


RETURNING VALUES
The return statement is used to exit a function and go back to the place from where it
was called. Let see in example program.
Example 1: (without return statement)
a =15
b =20
c=5
d = 10
defcalcu(no1, no2):
total = no1 + no2
print(total)
calcu(a, b)
calcu(c, d)

Output:
35
15

Example 2: (with return statement)


a =15
b =20
c=5
d = 10
defcalcu(no1, no2):
total = no1 + no2
return total

ans1 = calcu(a, b)
ans2 = calcu(c, d)
print( ans1)
print( ans2)

Output:
35
15

Example 3:
def area(radius):
b = 3.14159 * radius**2
return b

Explanation:
In the above program, which return area of circle with the statement of return b.
Before this statement, the variable b evaluated already.

Example 4:
def area(radius):
return 3.14159 * radius**2

Explanation:
In the above program, which is also return area of circle, but it have slightly differ
from example 1. Yes, the expression includes in the single statement of return statement.

Unit III 71
Mailam Engineering College GE3151 - Problem Solving and Python Programming

FRUITFUL FUNCTIONS

9) BRIEFLY EXPLAIN ABOUT FRUITFUL FUNCTIONS WITH EXAMPLES.


The user can not only pass a parameter value into a function, a function can also
produce a value.
Functions that return values are sometimes called fruitful functions. In many other
languages, a function that doesn’t return a value is called a procedure, but we will stick here
with the Python way of also calling it a function, or if we want to stress it, a non-
fruitful function.

The square function will take one number as a parameter and return the result of
squaring that number. Here is the black-box diagram with the Python code following.

The return statement is followed by an expression which is evaluated. Its result is


returned to the caller as the “fruit” of calling this function.
Example:
def add(a,b):
c=a+b
return c
x=int(input(“EnterNumber1:”))
y=int(input(“EnterNumber2:”))
z=add(x,y)
print(“Addition of two number is “,z)

Output:
Enter number1:12
Enter number2:25
Addition of two number is 37
In Python, any functions that return values, which we will call fruitful functions.

PARAMETERS IN FRUITFULFUNCTIONS
Once a function is defined, it can be called from the main program or from
another function.
Parameter is the “input data that is sent from function call to function definition”.
Types:
i) Actual parameters
ii) Formal parameters
Let see one by one as follows.
(i) Actual parameters: This parameter defined in the function call.
(ii) Formal parameters: This parameter defined as the part of function definition.
Example:
def add(a,b): a, b are formal arguments
c = a +b
return c

x = int(input(“Enter Number1:”))
y = int(input(“Enter Number2:”))

z=add(x,y) x, y are actual arguments

print(“Addition of two number is “,z)

Unit III 72
Mailam Engineering College GE3151 - Problem Solving and Python Programming

COMPOSITION

10) WHAT IS FUNCTION COMPOSITION? EXPLAIN IN DETAILS WITH EXAMPLE.


Composition is the ability to take small building blocks (variables, expressions and
statements) and compose them (or) Call one function from within another function, this
technique is known as composition.

Syntax:

def function1():
def function2():
-----------
return x

a=function1()
a

Example 1:
x = math.sin(degrees / 360.0 * 2 * math.pi)
Here the argument of a function can be any kind of expression, including arithmetic
operators and function calls.
Example 2:
def sam(x):
def add(y):
print(x+y)
return add

s=sam(5)
print("Answer",s(12))
Output:
17
None
RECURSION

11)WHAT IS RECURSION? WRITE AND EXPLAIN A PYTHON PROGRAM TO FIND


FACTORIAL OF NUMBER USING RECURSION. [AU – Apr/May 2022]
A recursive definition is similar to a circular definition, i.e., “function call itself”
this is known as recursion.
Syntax:
def function_name(a):
------------
------------

function_name(b)
------------

Example:
def factorial(n):
if n == 0:
return 1
else:
return n * factorial(n-1)

n=int(input(“Enter N:”))
f=factorial(n)
print(“The factorial of “,n,” is “,f)

Unit III 73
Mailam Engineering College GE3151 - Problem Solving and Python Programming

Output:
Enter N:5
The factorial of 5 is 120

Explanation
Here is what the stack diagram looks like for this sequence of function calls:

Advantages of recursion
 Recursion adds clarity and (sometimes) reduces the time needed to write and debug
code (but doesn't necessarily reduce space requirements or speed of execution).
 Reduces time complexity.
 Performs better in solving problems based on tree structures.

Disadvantages of recursion
 It is usually slower due to the overhead of maintaining the stack.
 It usually uses more memory for the stack.

STRINGS
12) EXPLAIN IN DETAILS ABOUT STRINGS WITH EXAMPLE.
Strings are amongst the most popular types in Python. We can create them simply by
enclosing characters in quotes. Python treats single quotes the same as double quotes.
Creating strings is as simple as assigning a value to a variable.
Example:
var1 = 'Hello World!' #Single quotes
var2 = "Python” #Double quotes
var2 = ’’’ Programming’’’ #Triple Single quotes
var3=”””Python Programming””” #Triple double quotes

ACCESSING VALUES IN STRINGS


 An individual character in a string is accessed using a subscript (index). The subscript
should always be an integer (positive or negative). A subscript starts from 0.
 Positive subscript helps in accessing the string from the beginning
 Negative subscript helps in accessing the string from the end.
 From left to right, the first character of a string has the index 0
 From right end to left, the first character of a string is –1.
Example
String ‘Computer’ with a Positive or Negative Index Position Number

Unit III 74
Mailam Engineering College GE3151 - Problem Solving and Python Programming

Program
>>>fruit='banana'
>>>fruit[0]
'b'
>>>fruit[1]
'a'
>>>fruit[4]
'n'
>>>fruit[6]

Traceback (most recent call last):


File "<pyshell#15>", line 1, in <module>
fruit[6]
IndexError: string index out of range

>>>fruit[5]
'a‘
>>>fruit[5]
'a'
>>>fruit[4]
'n'
>>>fruit[2]
'n'
>>>fruit[1]
'a'
>>>fruit[0]
'b'

UPDATING STRINGS
You can "update" an existing string by (re)assigning a variable to another string. The
new value can be related to its previous value or to a completely different string altogether.
Example:
var1 = 'Hello World!'
print("Updated String :- ", var1[:6] + 'Python')
When the above code is executed, it produces the following result:

Output:
Updated String :- Hello Python

ESCAPE CHARACTERS
Following table is a list of escape or non-printable characters that can be represented
with backslash notation.
An escape character gets interpreted; in a single quoted as well as double quoted strings.
Backslash Hexadecimal Description
notation character

\a 0x07 Bell or alert

\b 0x08 Backspace

\cx Control-x

\C-x Control-x

\e 0x1b Escape

\f 0x0c Formfeed

Unit III 75
Mailam Engineering College GE3151 - Problem Solving and Python Programming

Backslash Hexadecimal Description


notation character

\M-\C-x Meta-Control-x

\n 0x0a Newline

\nnn Octal notation, where n is in the range 0.7

\r 0x0d Carriage return

\s 0x20 Space

\t 0x09 Tab

\v 0x0b Vertical tab

\x Character x

\xnn Hexadecimal notation, where n is in the range 0.9, a.f, or A.F

13) LIST OUT THE STRING SPECIAL OPERATORS WITH EXAMPLES.


Assume string variable a holds 'Hello' and variable b holds 'Python',
Operator Description Example

+ Concatenation - Adds values on either side of the a + b will give HelloPython


operator

* Repetition - Creates new strings, concatenating a*2 will give -HelloHello


multiple copies of the same string

[] Slice - Gives the character from the given index a[1] will give e

[:] Range Slice - Gives the characters from the given a[1:4] will give ell
range

in Membership - Returns true if a character exists in the H in a will give 1


given string

not in Membership - Returns true if a character does not M not in a will give 1
exist in the given string

r/R Raw String - Suppresses actual meaning of Escape print r'\n' prints \n and
characters. The syntax for raw strings is exactly the print R'\n'prints \n
same as for normal strings with the exception of the
raw string operator, the letter "r," which precedes the
quotation marks. The "r" can be lowercase (r) or
uppercase (R) and must be placed immediately
preceding the first quote mark.

Unit III 76
Mailam Engineering College GE3151 - Problem Solving and Python Programming

14) LIST OUT THE STRING FORMATTING OPERATOR WITH EXAMPLE. (or)
EXPLAIN ANY TWO STRING FORMATS AVAILABLE IN PYTHON. [AU – Dec 2023]
One of Python's coolest features is the string format operator %. This operator is
unique to strings and makes up for the pack of having functions from C's printf() family.
Example
print("My name is %s and weight is %d kg!" % ('Zara', 21) )
Output
My name is Zara and weight is 21 kg!
Here is the list of complete set of symbols which can be used along with % −
Format Symbol Conversion

%c character

%s string conversion via str() prior to 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 UPPERcase 'E')

%f floating point real number

Other supported symbols and functionality are listed in the following table
Symbol Functionality

* argument specifies width or precision

- left justification

+ display the sign

<sp> leave a blank space before a positive number

# add the octal leading zero ( '0' ) or hexadecimal leading '0x' or


'0X', depending on whether 'x' or 'X' were used.

0 pad from left with zeros (instead of spaces)

% '%%' leaves you with a single literal '%'

Unit III 77
Mailam Engineering College GE3151 - Problem Solving and Python Programming

STRING SLICES
15) DISCUSS BRIEFLY ABOUT STRING SLICES WITH EXAMPLES.
 A segment of a string is called a slice. Selecting a slice is similar to selecting a
character.
 Subsets of strings can be taken using the slice operator with two indices in square
brackets separated by a colon ([ ] and [m:n]).
 The operator [m:n] returns the part of the string from the mth character to the
nth character, including the first but excluding the last.

Syntax:
s[start:stop] #[] Index
Example 1: (Positive Index: Left to Right)
s='Engineering' #E n g i n e er i n g
#0 12 3 4 5 6 7 8 9 10
print(s[0]) #E
print(s[3]) #i

Example 2: (Negative Index: Right to Left)


s='Engineering' #E n g i n eer i n g
#-11 -10 -9 -8 -7 -6 -5 -4 -3 -2 -1
print(s[-1]) #g

Example 3:
s='Engineering'
print(s[5]) #e
print(s[-5]) #e
print(s[0:5]) #Engin
print(s[:5)) #Engin
print(s[2:7]) #ginee
print(s[0:]) #Engineering
print(s[0:100]) #Engineering
print(s[:]) #Engineering
print(s[-7:-1]) #neerin

Syntax 2:
s[start:stop:step] #[] Index

Example:
s='Mailam Engineering College'
print(s[0:100]) # Mailam Engineering College
print(s[0:100:2]) # Mianiernolg
print(s[0:100:3]) # Mlgeilg
print(s[0:100:-2]) # No Output

It is a neat truism of slices that for any index n, a[:n] + a[n:] == a. This works even for n
negative or out of bounds. Or put another way a[:n] and a[n:] always partition the string into
two string parts, conserving all the characters. As we'll see in the list section later, slices work
with lists too.

Unit III 78
Mailam Engineering College GE3151 - Problem Solving and Python Programming

STRING FUNCTIONS AND METHODS

16) LIST OUT THE STRING FUNCTIONS AND METHODS WITH EXAMPLES.
Python includes the following built-in methods to manipulate strings.

SN Methods with Description

1 capitalize()Capitalizes first letter of string

2 center(width, fillchar)Returns a space-padded string with the original string


centered to a total of width columns.

3 count(str, beg= 0,end=len(string))Counts how many times str occurs in string or


in a substring of string if starting index beg and ending index end are given.

4 decode(encoding='UTF-8',errors='strict')Decodes the string using the codec


registered for encoding. Encoding defaults to the default string encoding.

5 encode(encoding='UTF-8',errors='strict')Returns encoded string version of


string; on error, default is to raise a ValueError unless errors is given with 'ignore' or
'replace'.

6 endswith(suffix, beg=0, end=len(string))Determines if string or a substring of


string (if starting index beg and ending index end are given) ends with suffix; returns
true if so and false otherwise.

7 find(str, beg=0 end=len(string))Determine if str occurs in string or in a substring


of string if starting index beg and ending index end are given returns index if found
and -1 otherwise.

8 index(str, beg=0, end=len(string))Same as find(), but raises an exception if str


not found.

9 isalnum()Returns true if string has at least 1 character and all characters are
alphanumeric and false otherwise.

10 isalpha()Returns true if string has at least 1 character and all characters are
alphabetic and false otherwise.

11 isdigit()Returns true if string contains only digits and false otherwise.

12 islower()Returns true if string has at least 1 cased character and all cased
characters are in lowercase and false otherwise.

13 isnumeric()Returns true if a unicode string contains only numeric characters and


false otherwise.

14 isspace()Returns true if string contains only whitespace characters and false


otherwise.

15 istitle()Returns true if string is properly "titlecased" and false otherwise.

16 isupper()Returns true if string has at least one cased character and all cased
characters are in uppercase and false otherwise.

17 join(seq)Merges (concatenates) the string representations of elements in sequence

Unit III 79
Mailam Engineering College GE3151 - Problem Solving and Python Programming

seq into a string, with separator string.

18 len(string)Returns the length of the string

19 lower()Converts all uppercase letters in string to lowercase.

20 max(str) Returns the max alphabetical character from the string str.

21 min(str) Returns the min alphabetical character from the string str.

22 replace(old, new [, max])Replaces all occurrences of old in string with new or at


most max occurrences if max given.

23 rstrip()Removes all trailing whitespace of string.

24 split(str="", num=string.count(str))Splits string according to delimiter str (space


if not provided) and returns list of substrings; split into at most num substrings if
given.

25 splitlines(num=string.count('\n'))Splits string at all (or num) NEWLINEs and


returns a list of each line with NEWLINEs removed.

26 swapcase() - Inverts case for all letters in string.

27 title()Returns "titlecased" version of string, that is, all words begin with uppercase
and the rest are lowercase.

28 upper()Converts lowercase letters in string to uppercase.

17) WHAT IS STRING FUNCTION IN PYTHON? EXPLAIN ANY THREE PYTHON STRING
METHODS WITH AN EXAMPLE. [AU – Jan 2022]
Python string is a built-in type sequence. Strings can be used to handle textual data in
Python. Python Strings are immutable sequences of Unicode points. Creating Strings is the
simplest and easy to use in Python. To create a string in Python, we simply enclose a text in
single as well as double-quotes. Python treats both single and double quotes statements the
same.

Important String Functions


The Python String Functions which we are going to discuss in this article are as follows:
 capitalize( ) function
 lower( ) function
 title( ) function
 casefold( ) function
 upper( ) function
 count( ) function
 find( ) function
 replace( ) function
 swapcase( ) function
 join( ) function
Let see example for three string functions.

(i) string.upper()
It converts all the character of lower case in to upper case format.

Unit III 80
Mailam Engineering College GE3151 - Problem Solving and Python Programming

Example:
text ='all is well'

print("In Upper Case:")


print(text.upper())

Output:
ALL IS WELL

(ii) string.isalpha()

Python String isalpha() method is used to check whether all characters in the String
is an alphabet.

Syntax:
String.isalpha()

Parameter:
Does not take any parameter

Returns:
True: If all characters in the string are alphabet.
False: If the string contains 1 or more non-alphabets.

Example 1:
string = "all is well"
print(string.isalpha())

Output:
True

Example 2:
string = "1 all is well"
print(string.isalpha())
Output:
False

(ii) string.isdigit()

Python String isdigit() method is used to check whether all characters in the String is
digit.

Syntax:
string.isdigit()

Parameter:
Does not take any parameter

Returns:
True: If all characters in the string are digits.
False: If the string contains 1 or more non-digits.

Example 1:
string = "369"
print(string.isdigit())

Unit III 81
Mailam Engineering College GE3151 - Problem Solving and Python Programming

Output:
True

Example 2:
string = "all is well"
print(string.isdigit())
Output:
False

STRING MODULE
18) BRIEFLY DISCUSS ABOUT STRING MODULE WITH RELEVANT EXAMPLE.
This module contains a number of functions to process standard Python strings. In
recent versions, most functions are available as string methods as well.
Example: Using the string module
import string
text = "python programming"
print("upper=", string.upper(text))
print("lower=", string.lower(text))
print("split=", string.split(text))
print("join=", string.join(string.split(text), "+"))
print("replace=", string.replace(text, "Python", "Java"))
print("find=", string.find(text, "Python"), string.find(text, "Java"))
print("count=", string.count(text, "n"))

Output
upper = MONTY PYTHON'S FLYING CIRCUS
lower = monty python's flying circus
split = ['Monty', "Python's", 'Flying', 'Circus']
join = Monty+Python's+Flying+Circus
replace = Monty Java's Flying Circus
find = 6 -1
count = 3
Example: Using string methods instead of string module functions (Python 1.6 and
later)
text = "Monty Python's Flying Circus"
print("upper", "=>", text.upper())
print("lower", "=>", text.lower())
print("split", "=>", text.split())
print("join", "=>", "+".join(text.split()))
print("replace", "=>", text.replace("Python", "Perl"))
print("find", "=>", text.find("Python"), text.find("Perl"))
print("count", "=>", text.count("n"))

Output
upper => MONTY PYTHON'S FLYING CIRCUS
lower =>monty python's flying circus
split => ['Monty', "Python's", 'Flying', 'Circus']
join =>Monty+Python's+Flying+Circus
replace => Monty Perl's Flying Circus
find => 6 -1
count => 3

Unit III 82
Mailam Engineering College GE3151 - Problem Solving and Python Programming

STRING – IMMUTABLE

19) PYTHON STRINGS ARE IMMUTABLE. JUSTIFY WITH AN EXAMPLE. [AU–Dec 2023]
Yes, In python also, strings are immutable. That is, once defined a string, we cannot
modify a specific character in specific index.
It may be assumed to use [] operator on the left side of an augment, with the intention
of changing a character in a string.
Example:
sample=’Hello, world!’
sample[0]=’J’

The above code will make an error.


Reason:
The object in this case is the string and the item is the character tried to assign. For
now, an object is the same thing as a value, but we will refine that definition later. An item is
one of the values in a sequence. The reason for the error is that strings are immutable, which
means that existing string cannot be changed. The best option is to create a new string that is a
variation on the original.

Alternate idea to update string without affecting original:


sample=’Hello, world!’
sample1=’J’+sample[1:]
print(sample1)
Output:
Jello, world!

20) WHY WE NEED LIST INSTEAD OF ARRAY IN PYTHON? EXPLAIN IN DETAILS


ABOUT LISTS WITH EXAMPLE.
One of the most fundamental data structures in any language is the array. Python
doesn't have a native array data structure, but it has the list which is much more general and
can be used as a multidimensional array quite easily.
List basics
A list in Python is just an ordered collection of items which can be of any type. By
comparison an array is an ordered collection of items of a single type - so in principle a list is
more flexible than an array but it is this flexibility that makes things slightly harder when you
want to work with a regular structure.

A list is also a dynamic mutable type and this means you can add and delete elements
from the list at any time.
To define a list you simply write a comma separated list of items in square brackets:

myList=[1,2,3,4,5,6]
This looks like an array because you can use "slicing" notation to pick out an individual
element - indexes start from 0.
Example
print(myList[2])
will display the third element, i.e. the value 3 in this case. Similarly to change the third
element you can assign directly to it:
myList[2]=100
The slicing notation looks like array indexing but it is a lot more flexible.
Example
myList[2:5]
is a sublist from the third element to the fifth i.e. from myList[2] to myList[4].
Notice that the final element specified i.e. [5] is not included in the slice.
Also notice that you can leave out either of the start and end indexes and they will be
assumed to have their maximum possible value.
Example
myList[5:]is the list from List[5] to the end of the list and

Unit III 83
Mailam Engineering College GE3151 - Problem Solving and Python Programming

myList[:5]is the list up to and not including myList[5] and


myList[:]is the entire list.
List slicing is more or less the same as string slicing except that you can modify a slice.
Example:
myList[0:2]=[0,1]
has the same effect as
myList[0]=0
myList[1]=1
Finally is it worth knowing that the list you assign to a slice doesn't have to be the
same size as the slice - it simply replaces it even if it is a different size.
Basic array operations
So far so good, and it looks as if using a list is as easy as using an array. The first
thing that we tend to need to do is to scan through an array and examine values.
Example
To find the maximum value (forgetting for a moment that there is a built-in max
function)
m=0
for e in myList:
if m<e:
m=e
This uses the for...in construct to scan through each item in the list. This is a very useful way
to access the elements of an array but it isn't the one that most programmers will be familiar
with. In most cases arrays are accessed by index and you can do this in Python:
m=0
for i in range(len(myList)):
if m<myList[i]:
m=myList[i]
Notice that we are now using range to generate the sequence 0,1, and so on up to the length
of myList.
Let to admit that there is a lot to be said for the simplicity of the non-index version of
the for loop but in many cases the index of the entry is needed. There is the option of using
the index method to discover the index of an element but this has its problems.
Example
If you wanted to return not the maximum element but its index position in the list you
could use:
m=0
mi=0
for i in range(len(myList)):
if m<myList[i]:
m=myList[i]
mi=i
Also use the non-indexed loop and the index method:
m=0
for e in myList:
if m<e:
m=e
mi=myList.index(m)
print(mi)
The only problem is that index(m) returns the index of m in the list or an error if m isn't in the
list. There is also the slight problem that behind the scenes it is clear that index is performing
another scan of the entire list.
Two dimensions
It has to be said that one-dimensional arrays are fairly easy - it is when we reach two
or more dimensions that mistakes are easy to make. For a programmer moving to Python the
problem is that there are no explicit provisions for multidimensional arrays. As a list can
contain any type of data there is no need to create a special two-dimensional data structure.
All you have to do is store lists within lists - after all what is a two-dimensional array but a
one-dimensional array of rows.

Unit III 84
Mailam Engineering College GE3151 - Problem Solving and Python Programming

In Python a 2x2 array is [[1,2],[3,4]] with the list [1,2] representing the first row and
the list [3,4] representing the second row. You can use slicing to index the array in the usual
way.
Example
myArray=[[1,2],[3,4]]
then
myArray[0]is the list [1,2] and
myArray[0][1]

is [1,2][1], i.e. 2.

As long as you build your arrays as nested lists in the way described then you can use
slicing in the same way as you would array indexing. That is:
myArray[i][j]
is the i,jth element of the array.
Example
To do something with each element in myArray you might write:

for i in range(len(myArray)):
for j in range(len(myArray[i])):
print(myArray[i][j])

Where len(myArray) us used to get the number of rows and len(myArray[i])) to get
the number of elements in a row.

21) WRITE A PYTHON PROGRAM TO FIND THE FACTORIAL OF A GIVEN NUMBERS


WITHOUT RECURSION AND WITH RECURSION. [AU – Jan 2018]

Program 1
#Without recursion
n=int(input(“Enter N:”))
fact=1
i=1
while i<=n:
fact=fact * i
i=i+1
print(“The factorial is “,fact)

Output:
Enter N:5
The factorial is 120

Program 2
#With recursion
def fact(n):
if n ==1:
return 1
else:
return n*fact(n-1)

n=int(input(“Enter N:”))
f=fact(n)

print(“The factorial is “,f)

Output:
Enter N:5
The factorial is 120

Unit III 85
Mailam Engineering College GE3151 - Problem Solving and Python Programming

22) WRITE A PYTHON PROGRAM TO CALCULATE SQUARE ROOT


# Python Program - Find Square Root of a Number without looping
print("Square Root Program")
num = input("Enter a number: ")
number = float(num)
number_sqrt = number ** 0.5
print("Square Root of %0.2f is %0.2f" %(number, number_sqrt))

23) WRITE A PYTHON PROGRAM TO FIND EXPONENTIATION


n= int(input ("enter number :") )
e= int(input ("enter exponent :") )
r=1 i=1
while(i<=e):
r=n*r
i=i+1
print(r)

Output
Enter number : 3
Enter exponent : 3
27

24) WRITE A PYTHON PROGRAM TO CALCULATE GCD


n1=int(input("Enter the first number: "))
n2=int(input("Enter the second number: "))
i=1
while (i <= n1 and i <= n2):
if(n1%i==0 and n2%i==0):
gcd = i;
i=i+1
print("GCD of given numbers is :", gcd)

Output
Case 1:
Enter first number:5
Enter second number:15
GCD is: 5

Case 2:
Enter first number:30
Enter second number:12
GCD is: 6

25) WRITE A PYTHON PROGRAM TO CALCULATE SUM THE ARRAYS OF NUMBERS


def listsum(numList):
if len(numList) == 1:
return numList[0]
else:
return numList[0] + listsum(numList[1:])

print(listsum([1,3,5,7,9]))

OUTPUT
25

Unit III 86
Mailam Engineering College GE3151 - Problem Solving and Python Programming

26) WRITE A PYTHON PROGRAM TO SEARCH A REQUIRED NUMBER IN SET OF


NUMBERS USING THE CONCEPT OF LINEAR SEARCH. [AU – JAN 2018]
n = int(input("Enter N:")) x = []
i=1
while i <= n:
y = int(input("Enter value:")) x.append(y)
i=i+1
key = int(input("Enter searching element:"))
i=0
found = 0

while i <n:
if key == x[i]:
found = 1
break
i = i +1

if found == 1:
print("Searching element is found")
else:
print("Searching element is NOT found")

OUTPUT
Enter N:5
Enter value:12
Enter value:13
Enter value:14
Enter value:2
Enter value:3
Enter searching element:4
Searching element is NOT found

27) WRITE A PYTHON PROGRAM TO SEARCH A REQUIRED NUMBER IN SET OF


NUMBERS USING THE CONCEPT OF BINARY SEARCH. [AU – Jan 2019, Dec 23]
n = int(input("Enter N:"))
x = []
i=0
while i < n:
y = int(input("Enter value:"))
x.append(y)
i=i+1
key = int(input("Enter Searching element"))
first = 0
last = n - 1
found = 0
while( first<=last and not found):
mid = (first + last)//2
if x[mid] == key :
found = 1
else:
if key < x[mid]:
last = mid - 1
else:
first = mid + 1
if found == 1:
print("Searching element is found")
else:
print("Searching element is NOT found")

Unit III 87
Mailam Engineering College GE3151 - Problem Solving and Python Programming

OUTPUT
Enter N:5
Enter value:12
Enter value:13
Enter value:14
Enter value:2
Enter value:3
Enter searching element:3
Searching element is found

28) WRITE A PYTHON PROGRAM TO GENERATE FIRST ‘N’ FIBONACCI NUMBERS.


[AU-JAN 2018, Apr 2024]
Program:
n=int(input(“Enter N:”))
a=0
b=1
i=2
print(a)
print(b)
while i<n:
c=a+b
print(c)
a=b
b=c
i=i+1
Output:
Enter N: 5
0
1
1
2
3

29) WRITE A PYTHON PROGRAM USING FUNCTION TO FIND THE SUM OF FIRST ‘n’
ODD NUMBERS AND PRINT THE RESULT. [AU – Jan 2022]

Program:
n=int(input(‘Enter N:’))
sum=0
i=1
while i <=n:
if i%2==1:
sum=sum+1
i=i+1
print(‘Sum=’,sum)

Output:
Enter N:10
Sum=25

Unit III 88
Mailam Engineering College GE3151 - Problem Solving and Python Programming

30) WRITE A PYTHON PROGRAM TO CHECK WHETHER ENTERED STRING IS


PALINDROME OR NOT. [AU – Apr 2024]

Program:
def isPalindrome(s):
return s == s[::-1]

s = input(‘Enter any string’)


ans = isPalindrome(s)

if ans:
print("Palindrome")
else:
print("Not Palindrome")
Output:
Enter any string: amma
Palindrome

Enter any string: mother


Not Palindrome

“Successful people do
what failure people are
not willing to do”

Unit III 89
Mailam Engineering College GE3151 - Problem Solving and Python Programming

UNIT IV COMPOUND DATA: LISTS, TUPLES, DICTIONARIES


Lists, list operations, list slices, list methods, list loop, mutability, aliasing, cloning lists, list
parameters; Tuples: tuple assignment, tuple as return value; Dictionaries: operations and
methods; advanced list processing - list comprehension, Illustrative programs: Simple
Sorting, histogram, Students marks statement, Retail bill preparation.

PART A
LISTS
1) Define List with example.
A list is an ordered set of values, where each value is identified by an index. The
values that make up a list are called its elements. Lists are similar to strings, which are
ordered, sets of characters, except that the elements of a list can have any type.
Example
There are several ways to create a new list; the simplest is to enclose the elements in
square brackets [ ]:
a = [10, 20, 30, 40] - List of four integers

2) Give example for list membership.


course = [‘CIVIL’, ‘CSE’, ‘EEE’, ‘ECE’,’MECH’,’IT’]
print(‘CSE’ in course) # True
print(‘AE’ in course) # False
print(‘AE’ not in course) # True

3) What is list slices? (Or) How to slice a list in Python? [AU-Jan 2018]
A subsequence of a sequence is called a slice and the operation that extracts a
subsequence is called slicing. Like with indexing, we use square brackets ([ ]) as the slice
operator, but instead of one integer value inside we have two, separated by a colon (:).
Example:
a= [‘a’, ‘b’, ‘c’, ‘d’, ‘e’, ‘f’]
print(a[:4])
Output:
[‘a’, ‘b’, ‘c’, ‘d’]

4) How will you update list items? Give one example. [AU-Jan 2019]
In python, there are many ways are available to update the existing list by using
built-in list methods.
List updating methods
 list.append()
 list.insert()
 list.extend()
 list.remove()
Example:
course = [‘CIVIL’,CSE’,‘EEE’,‘ECE’]
course.append(‘MECH’)
print(course)
Output:
[‘CIVIL’,CSE’,‘EEE’,‘ECE’,’MECH’]

5) What is the purpose of list methods?


Python has a number of built-in data structures, including lists. Data structures
provide us with a way to organize and store data, and we can use built-in methods to
retrieve or manipulate that data.

6) List out the types of list methods.


 list.append()
 list.insert()
 list.extend()
 list.remove()

Unit – 4 90
Mailam Engineering College GE3151 - Problem Solving and Python Programming

 list.pop()
 list.index()
 list.copy()
 list.reverse()
 list.count()
 list.sort()
 list.clear()

7) Differentiate: append() and extend() methods.


S.No append() extend()
1 It is used to append an element in a It is used to extend another list
list
2 Adds the given element at the end Adds the elements of another list at the
of the list end of the list

8) In python, how the values stored in a list are accessed? Should the elements of
a list be of the same data type? [AU – Jan 2022]
The values are stored in a list with the reference of index value. The index value is
integer data type. By default, its starts with ZERO. The user can access the values from the
list with the use of index value.
Mixed data types of values can be stored.

9) What is the purpose to use list loop in python?


Loop is used to access all the elements in a list. A loop is a block of code that repeats
itself until it runs out of items to work with. Loop will run once for every item in list.

10) What is aliasing? Give example.


Since variables refer to objects, if we assign one variable to another, both variables
refer to the same object:
Example:
a = [1, 2, 3]
b=a
print(a is b) # True
Because the same list has two different names, a and b, we say that it is aliased.
Changes made with one alias affect the other:
b[0] = 5
print(a) # [5, 2, 3]

11) What are the uses of cloning list?


If we want to modify a list and also keep a copy of the original, we need to be able
to make a copy of the list itself, not just the reference. This process is sometimes called
cloning, to avoid the ambiguity of the word copy.
Example: (Write a program to create a clone of the list: list1=[1,2,3,4,5,6]) [AU – DEC 22]
list1 = [1, 2, 3,4,5]
list2 = list1[0:2]
print(list2)
Output:
[1, 2]

12) What is list parameter?


Passing a list as an argument actually passes a reference to the list, not a copy of the
list. Since lists are mutable changes made to the parameter change the argument as well.

13) What is a list? How lists differ from tuples? [AU – JAN 2018]
A list is an ordered sequence of values, where each value is identified by an index.
The syntax for expressing literals of type list is similar to that used for tuples.
The difference is that we use square brackets rather than parentheses.
Lists are mutable, tuples are immutable.

Unit – 4 91
Mailam Engineering College GE3151 - Problem Solving and Python Programming

Example:
a=[1,”two”,3] #list
b=(1,”two”,3) #tuples

14) Relate strings and lists. [AU – JAN 2019]


A string is a sequence of character and a list is a sequence of values, but a list of
character is not the same as a string.
Example: (To convert from a string to a list of characters is given below)
s=’spam’
t=list[s]
print(t)
Output:
[‘s’,’p’,’a’,’m’]

15) What is range() function and how it is used in lists? [AU – APR 2024]
It generates sequence of numbers, which is commonly used in loops or when iterating
over a set of numbers. It returns an immutable sequence of numbers in the form of a range
object.
Syntax:
range(start, stop, step)
Example:
numbers = list(range(5))
print(numbers)
Output:
[0, 1, 2, 3, 4]

16) What are list comprehension? Mention its advantages. [AU – DEC 2023]
In Python provide a concise way to create lists. They allow for the generation of lists
using a single line of code, often making the code more readable and expressive compared
to using traditional loops.
Example:
squares = [x**2 for x in range(10)] print(squares)
Output:
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]

TUPLES
17) Define tuples. (or) How are the values of tuples accessed? Illustrate with an
example. [AU – DEC 2022, DEC 2023]
A tuple is a sequence of immutable Python objects. Tuples are sequences, just like
lists. The differences between tuples and lists are, the tuples cannot be changed unlike
lists and tuples use parentheses, whereas lists use square brackets.
Example:
tup1 = ('physics', 'chemistry', 1997, 2000)
tup2 = (1, 2, 3, 4, 5, 6, 7)
print("tup1[0]: ", tup1[0])
print("tup2[1:5]: ", tup2[1:5])
Output
tup1[0]: physics
tup2[1:5]: [2, 3, 4, 5]

18) Give example for tuple assignment.


Python language is the ability to have a tuple on the left hand side of an assignment
statement. This allows you to assign more than one variable at a time when the left hand
side is a sequence.
Example:

Unit – 4 92
Mailam Engineering College GE3151 - Problem Solving and Python Programming

Here, two element list (which is a sequence) and assign the first and second elements
of the sequence to the variables x and y in a single statement.
m = (“Think”, “Positive”)
x, y = m
print(x) # “Think”
print(y) # “Positive”

19) Give example for tuples as return values.


t = divmod(7, 3)
print(t) # (2, 1)

Or use tuple assignment to store the elements separately:

quot, rem = divmod(7, 3)


print(quot) #2
print(rem) #1

20) Can functions return tuples? If yes give example. [AU – JAN 2018]
Functions can return tuples as return values. In each case, a function (which can only
return a single value), can create a single tuple holding multiple elements.
Example:
def circleInfo(r): # Return (circumference, area) of a circle of radius r
c = 2 * 3.14159 * r
a = 3.14159 * r * r
return (c, a)
print(circleInfo(10))

21) What are the advantages of “Tuple” over “List”? [AU – APR 2024]
Tuples are immutable, meaning once they are created, their elements cannot be
modified, added, or removed. This makes tuples a good choice for representing fixed
collections of items, such as coordinates or records.
Tuples can be slightly more memory efficient and faster to access than lists due to
their immutability. Since their size and content are fixed, Python can optimize their storage
and access.

DICTIONARY
22) What is dictionary in python?
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. Dictionaries are enclosed by curly braces-{
} and values can be assigned and accessed using square braces-[].

23) What is the purpose of dictionary in Python? [AU – Apr/May 2022]


 When quick access to data items is important. Dictionaries are designed to let us find a
value instantly without the need for searching through the whole collection.
 When the data order is not important.
 As dictionaries are mutable, it is not a good idea to use dictionaries to store data that
shouldn’t be modified in the first place.

24) How Python’s dictionaries store data? Give example. [AU – JAN 2022]
The Python list stores a collection of objects in an ordered sequence. In contrast,
the dictionary stores objects in an unordered collection. However, dictionaries allow a
program to access any member of the collection using a key – which can be a human-
readable string.

Example:
sample={‘sno’:123, ‘Name’:’RRR’}

Unit – 4 93
Mailam Engineering College GE3151 - Problem Solving and Python Programming

25) Give a function that can take a value and return the first key mapping to that
value in a dictionary. [AU – JAN 2019]
def testing(d,v):
for k in d:
if d[k]==v:
return k
raiseValueError

26) List out the operations on dictionaries.


Operator Explanation
len(d) returns the number of stored entries, i.e. the number of (key,value) pairs.
del d[k] deletes the key k together with his value
k in d True, if a key k exists in the dictionary d
k not in d True, if a key k doesn't exist in the dictionary d

27) List out the methods on dictionaries.


SN Methods with Description

1 dict.clear() - Removes all elements of dictionary dict

2 dict.copy() - Returns a shallow copy of dictionary dict

3 dict.fromkeys() - Create a new dictionary with keys from seq and


values setto value.
4 dict.get(key, default=None) - For key key, returns value or default if key not in
dictionary
5 dict.has_key(key)-Returns true if key in dictionary dict, false otherwise

6 dict.items() - Returns a list of dict's (key, value) tuple pairs

7 dict.keys() - Returns list of dictionary dict's keys

8 dict.setdefault(key, default=None) - Similar to get(), but will set


dict[key]=default if key is not already in dict
9 dict.update(dict2) - Adds dictionary dict2's key-values pairs to dict

10 dict.values() - Returns list of dictionary dict's values

28) How to merge two dictionaries?


d1={"Dept":"CSE","Gender":"M","Sem":1}
d2={"Age":17,"Sem":2}
d1.update(d2)
print(d1)
Output:
{'Dept': 'CSE', 'Gender': 'M', 'Sem': 2, 'Age': 17}

29) Give example for Mutable and immutable objects. [AU – Apr/May 2022]
Mutable Data type: A data value which can be modified. The types of all mutable values
are compound types.
Example: List and Dictionaries.
Immutable Data type: A data value which cannot be modified.
Example: Strings and Tuples.

Unit – 4 94
Mailam Engineering College GE3151 - Problem Solving and Python Programming

PART – B
LISTS

1) BRIEFLY EXPLAIN ABOUT THE CONCEPT OF LIST AND EXPLAIN HOW TO


ACCESSING ELEMENTS IN A LIST.
A list is an ordered set of values, where each value is identified by an index. The
values that make up a list are called its elements. Lists are similar to strings, which are
ordered sets of characters, except that the elements of a list can have any type.
Syntax:
List_name = [v1,v2,v3,…,vn]
Where
v1,v2,v3,…,vn = ‘n’ no. of values
Example:
[10, 20, 30, 40]
[“spam”, “bungee”, “swallow”]
Nested List:
[“hello”, 2.0, 5, [10, 20]] A list within another list is said to be nested.
Empty List:
Finally, there is a special list that contains no elements. It is called the empty list, and
is denoted [].
a=[]

ACCESSING ELEMENTS
The syntax for accessing the elements of a list is the same as the syntax for accessing
the characters of a string, the bracket operator ( [] – not to be confused with an empty list).
The expression inside the brackets specifies the index. Remember that the indices start at 0:
Program 1:
x = [10, 20, 30]
print(x[0],x[1],x[2])
for i in x:
print(i)
print (x)
Output 1:
10 20 30
10
20
30
[10, 20, 30]

Program 2: (list [] - mutable: can modify)


name = ['Python', 'C', 100]
print(name[0],name[1],name[2])
name[2] = "Java"
for i in name:
print(i)
print(name)
Output 2:
Python C 100
Python
C
Java
['Python', 'C', 'Java']

Unit – 4 95
Mailam Engineering College GE3151 - Problem Solving and Python Programming

2) DEFINE PYTHON LISTS. HOW TO ADD ELEMENTS TO THE LIST? EXPLAIN WITH A
SUITABLE EXAMPLE PROGRAM. [AU – Apr/May 2022]
A list is an ordered set of values, where each value is identified by an index. The
values that make up a list are called its elements. Lists are similar to strings, which are
ordered sets of characters, except that the elements of a list can have any type.
Syntax:
List_name = [v1,v2,v3,…,vn]
Where
v1,v2,v3,…,vn = ‘n’ no. of values
Example:
[10, 20, 30, 40]
[“spam”, “bungee”, “swallow”]

Two Ways available


(i) By using index value
(ii) By using append() method

(i) Adding elements by using index value


Example:
a=[]
a[0]=12
a[1]=’Raju’
a[2]=’CSE’

print(a)

Output:
[12, ‘Raju’, ‘CSE’]

(ii) Adding elements b y using append()


Example:
a=[]
i=0
while i<5:
b=int(input(‘Enter the value:’))
a.append(b)
print(a)

Output:
Enter the value:12
Enter the value:13
Enter the value:14
Enter the value:15
Enter the value:120
[12,13,14,15,120]

Unit – 4 96
Mailam Engineering College GE3151 - Problem Solving and Python Programming

LIST OPERATIONS
3) DEMONSTRATE THE WORKING OF +, * AND SLICE OPERATIONS IN PYTHON.
[AU - Jan 19]
(or) WHAT ARE THE BASIC LIST OPERATIONS THAT CAN BE PERFORMED IN
PYTHON? EXPLAIN EACH OPERATION WITH ITS SYNTAX AND EXAMPLE.
[AU – Apr 24]
There are two types of operations are available, they are listed below:
(i) + (Concatenation)
(ii) * (Repetition)
(i) The + operator concatenates lists:
a = [1, 2, 3]
b = [4, 5, 6]
c=[“a”,”b”,”c”]
d=a+b
e=a + c
print(d)
print(e)
Output:
[1, 2, 3, 4, 5, 6]
[1,2,3,’a’,’b’,’c’]
(ii) The * operator repeats lists:
a = [1, 2, 3]
b=a*2
print(d)
Output:
[1, 2, 3, 1,2,3]

LIST SLICES.
A subsequence of a sequence is called a slice and the operation that extracts a
subsequence is called slicing. Like with indexing, we use square brackets ([ ]) as the slice
operator, but instead of one integer value inside we have two, separated by a colon (:)
Syntax:
List_name=[ i : n-1]
Note: By default ‘i’ value is 0 (Zero)
Example 1:
a= [‘a’, ‘b’, ‘c’, ‘d’, ‘e’, ‘f’]
print(a[1:3])
Print(a[:4])
Print(a[3:])
Print(a[:])
Output:
[‘b’, ‘c’]
[‘a’, ‘b’, ‘c’, ‘d’]
[‘d’, ‘e’, ‘f’]
[‘a’, ‘b’, ‘c’, ‘d’, ‘e’, ‘f’]
Example 2:
demo = [1, 3, 6, 10, 15, 21, “lots”]
part = demo[1:4]
print(part)
nextpart = demo [2:-2]
print(nextpart)
truncated = demo[:-1]
print(truncated)
Output:
[3, 6, 10]
[6, 10, 15]
[1, 3, 6, 10, 15, 21]

Unit – 4 97
Mailam Engineering College GE3151 - Problem Solving and Python Programming

LIST METHODS
4) EXPLAIN IN DETAIL ABOUT THE METHODS AVAILABLE IN LIST.
(OR)
NAME THE OPERATIONS THAT CAN BE PERFORMED ON A LIST AND OUTLINE ANY
FOUR WITH AN EXAMPLE. [AU – Jan 2022, Dec 2023]
Python has a number of built-in data structures, including lists. Data structures
provide us with a way to organize and store data, and we can use built-in methods to
retrieve or manipulate that data.
Types of list methods
a) list.append() [AU – Dec 2022] – Addition operation
b) list.insert() [AU – Dec 2022] – Addition operation
c) list.extend()
d) list.remove() [AU – Dec 2022] – Deletion operation
e) list.pop()
f) list.index()
g) list.copy()
h) ist.reverse()
i) list.count()
j) list.sort()
k) list.clear()
Let see the explanation with example for each.

list.append()
The method list.append(x) will add an item (x) to the end of a list.
course = [‘CIVIL’,CSE’,‘EEE’,‘ECE’]
course.append(‘MECH’)
print(course)

list.insert()
The list.insert(i,x) method takes two arguments, with i being the index position you
would like to add an item to, and x being the item itself.
course.insert(0,’IT’)
print(course)
list.extend()
If we want to combine more than one list, we can use the list.extend(L) method, which
takes in a second list as its argument.

course2 = [‘BIO-TECH’,’IT’]
then
course.extend(course2)
print (course)

list.remove()
When we need to remove an item from a list, we’ll use the list.remove(x) method
which removes the first item in a list whose value is equivalent to x.
course.remove(‘BIO-TECH’)
print(course)
list.pop()
We can use the list.pop([i]) method to return the item at the given index position
from the list and then remove that item. The square brackets around the i for index tell us
that this parameter is optional, so if we don’t specify an index (as in course.pop()), the last
item will be returned and removed.
print(course.pop(3))
print(course)

list.index()
When lists start to get long, it becomes more difficult for us to count out our items to
determine at what index position a certain value is located. We can use list.index(x), where

Unit – 4 98
Mailam Engineering College GE3151 - Problem Solving and Python Programming

x is equivalent to an item value, to return the index in the list where that item is located. If
there is more than one item with value x, this method will return the first index location.
print(course)
print(course.index(‘EEE’))

list.copy()
When we are working with a list and may want to manipulate it in multiple ways while
still having the original list available to us unchanged, we can use list.copy() to make a copy
of the list.
course3 = course.copy()
print(course3)

list.reverse()
We can reverse the order of items in a list by using the list.reverse() method. Perhaps
it is more convenient for us to use reverse alphabetical order rather than traditional
alphabetical order.
course.reverse()
print(course)

list.count()
The list.count(x) method will return the number of times the value x occurs within a
specified list.
We’ll use our current list to count the number of times the item ‘EEE’ appears:
print(course.count(‘EEE’))

list.sort()
We can use the list.sort() method to sort the items in a list.
Just like list.count(), list.sort() can make it more apparent how many of a certain
integer value we have, and it can also put an unsorted list of numbers into numeric order.
course.sort()
print(course)

list.clear()
When we’re done with a list, we can remove all values contained in it by using the
list.clear() method.
course.clear()
print(course)

LIST LOOP

5) EXPLAIN THE CONCEPT OF LOOP USING IN LIST WITH RELEVANT EXAMPLE. (or)
DISCUSS THE DIFFERENT OPTIONS TO TRAVERSE A LIST. [AU – Jan 2019]
This is one of the most important concepts related to lists. We can have a list with a
million items in it, and in three lines of code we can write a sentence for each of those
million items. If we want to understand lists, and become a competent programmer, make
sure we take the time to understand this section.

We use a loop to access all the elements in a list. A loop is a block of code that
repeats itself until it runs out of items to work with, or until a certain condition is
met. In this case, our loop will run once for every item in our list. With a list that is three
items long, our loop will run three times.
Let’s take a look at how we access all the items in a list, and then try to understand
how it works.

Example:
flowers = [‘rose’, ‘lotus’, ‘jasmine’]
for i in flowers:
print(i)

Unit – 4 99
Mailam Engineering College GE3151 - Problem Solving and Python Programming

Output:
rose
lotus
jasmine

Explanation - for i in flowers:


 The keyword “for” tells Python to get ready to use a loop.
 The variable “i”, with no “flowers” on it, is a temporary placeholder variable.
This is the variable that Python will place each item in the list into, one at a
time.
 The first time through the loop, the value of “i” will be ‘rose’.
 The second time through the loop, the value of “i” will be ‘lotus’.
 The third time through, “i” will be ‘jasmine’.
 After this, there are no more items in the list, and the loop will end.

DOING MORE WITH EACH ITEM


We can do whatever we want with the value of “flower” inside the loop.
We can do whatever we want with this value, and this action will be carried out for
every item in the list. Let’s say something about each flower in our list.
Example:
flowers = [‘rose’, ‘lotus’, ‘jasmine’]
for i in flowers:
print(‘I like ‘ + i + ‘very much’)

Output:
I like rose very much
I like lotus very much
I like jasmine very much

INSIDE AND OUTSIDE THE LOOP


Python uses indentation to decide what is inside the loop and what is outside the loop.
Code that is inside the loop will be run for every item in the list. Code that is not indented,
which comes after the loop, will be run once just like regular code.
flowers = [‘rose’, ‘lotus’, ‘jasmine’]
for flowers in dogs:
print(‘I like ‘ + i + ‘very much’)
print(‘Super’)
print(“The End”)
Output:
I like rose very much
Super
I like lotus very much
Super
I like jasmine very much
Super
The End

Unit – 4 100
Mailam Engineering College GE3151 - Problem Solving and Python Programming

LIST MUTABILITY
6) HOW CAN IMPLEMENT MUTABLE IN THE CONCEPT OF LISTS?EXPLAIN WITH
EXAMPLE AND HOW TO DELETE A PARTICULAR ELEMENT IN A LIST.
Unlike strings, lists are mutable, which means we can change their elements. Using
the bracket operator on the left side of an assignment, we can update one of the elements:
>>>fruit = [“banana”, “apple”, “quince”]
>>>fruit[0] = “pear”
>>>fruit[-1] = “orange”
>>>print(fruit)
[‘pear’, ‘apple’, ‘orange’]

The bracket operator applied to a list can appear anywhere in an expression. When it
appears on the left side of an assignment, it changes one of the elements in the list, so the
first element of fruit has been changed from ‘banana’ to ‘pear’, and the last from ‘quince’ to
‘orange’. An assignment to an element of a list is called item assignment. Item assignment
does not work for strings:
>>>my_string = ‘TEST’
>>>my_string[2] = ‘X’
Traceback (most recent call last):
File “<stdin>”, line 1, in <module>
TypeError: ‘str’ object does not support item assignment
but it does for lists:
>>>my_list = [‘T’, ‘E’, ‘S’, ‘T’]
>>>my_list[2] = ‘X’
>>>my_list
[‘T’, ‘E’, ‘X’, ‘T’]
With the slice operator we can update several elements at once:
>>>a_list = [‘a’, ‘b’, ‘c’, ‘d’, ‘e’, ‘f’]
>>>a_list[1:3] = [‘x’, ‘y’]
>>>print(a_list)
[‘a’, ‘x’, ‘y’, ‘d’, ‘e’, ‘f’]
We can also remove elements from a list by assigning the empty list to them:
>>>a_list = [‘a’, ‘b’, ‘c’, ‘d’, ‘e’, ‘f’]
>>>a_list[1:3] = []
>>>print(a_list)
[‘a’, ‘d’, ‘e’, ‘f’]
And we can add elements to a list by squeezing them into an empty slice at the desired
location:
>>>a_list = [‘a’, ‘d’, ‘f’]
>>>a_list[1:1] = [‘b’, ‘c’]
>>>print(a_list)
[‘a’, ‘b’, ‘c’, ‘d’, ‘f’]
>>>a_list[4:4] = [‘e’]
>>>print(a_list)
[‘a’, ‘b’, ‘c’, ‘d’, ‘e’, ‘f’]

List Deletion
Using slices to delete list elements can be awkward, and therefore error-prone. Python
provides an alternative that is more readable.
del removes an element from a list:
>>> a = [‘one’, ‘two’, ‘three’]
>>>del a[1]
>>>a
[‘one’, ‘three’]

Unit – 4 101
Mailam Engineering College GE3151 - Problem Solving and Python Programming

LISTS ALIASING AND LISTS CLONING

7) GIVE EXAMPLE FOR ALIASING AND CLONING LISTS WITH RELEVANT EXAMPLE.
Aliasing
Since variables refer to objects, if we assign one variable to another, both
variables refer to the same object:

>>> a = [1, 2, 3]
>>> b = a
>>>a is b
True
In this case, the state diagram looks like this:
Because the same list has two different names, a and b, we say that it is aliased.
Changes made with one alias affect the other:
>>>b[0] = 5
>>>print(a)
[5, 2, 3]
Note:
In general, it is safer to avoid aliasing when you are working with mutable objects. Of
course, for immutable objects, there’s no problem. That’s why Python is free to alias strings
when it sees an opportunity to economize.

Cloning lists EXPLAIN ANY CLONING LIST TECHNIQUE IN PYTHON [AU – DEC 2024]
If we want to modify a list and also keep a copy of the original, we need to be able
to make a copy of the list itself, not just the reference. This process is sometimes called
cloning, to avoid the ambiguity of the word copy.
The easiest way to clone a list is to use the slice operator:
>>> a = [1, 2, 3]
>>> b = a[:]
>>>print(b)
[1, 2, 3]
Taking any slice of a creates a new list. In this case the slice happens to consist of the
whole list.
Now we are free to make changes to b without worrying about a:
>>>b[0] = 5
>>>print(a)
[1, 2, 3]

TUPLES, TUPLE ASSIGNMENT, TUPLE AS RETURN VALUE

8) EXPLAIN ABOUT TUPLES AND ALSO THE CONCEPT OF TUPLE ASSIGNMENT AND
TUPLES AS RETURN VALUE WITH EXAMPLE. [AU – Jan 2019]
A tuple is a sequence of values much like a list. The values stored in a tuple can be any
type, and they are indexed by integers. The important difference is that tuples are
immutable. Tuples are also comparable and hashable so we can sort lists of them and use
tuples as key values in Python dictionaries.

Syntactically, a tuple is a comma-separated list of values:


>>> t = ‘a’, ‘b’, ‘c’, ‘d’, ‘e’
Although it is not necessary, it is common to enclose tuples in parentheses to help us
quickly identify tuples when we look at Python code:
>>> t = (‘a’, ‘b’, ‘c’, ‘d’, ‘e’)

Example 1:
To create a tuple with a single element, you have to include the final comma:
>>> t1 = (‘a’,)
>>>type(t1)
<type ‘tuple’>

Unit – 4 102
Mailam Engineering College GE3151 - Problem Solving and Python Programming

Example 2:
Without the comma Python treats (‘a’) as an expression with a string in parentheses
that evaluates to a string:
>>> t2 = (‘a’)
>>>type(t2)
<type ‘str’>

Tuple assignment
One of the unique syntactic features of the Python language is the ability to have a
tuple on the left hand side of an assignment statement. This allows you to assign more than
one variable at a time when the left hand side is a sequence.

Example 1:
In this example we have a two element list (which is a sequence) and assign the first
and second elements of the sequence to the variables x and y in a single statement.
>>> m = [ ‘have’, ‘fun’ ]
>>>x, y = m
>>>x
‘have’
>>>y
‘fun’
>>>

Example 2:
It is not magic, Python roughly translates the tuple assignment syntax to be the following: 2
>>> m = [ ‘have’, ‘fun’ ]
>>> x = m[0]
>>> y = m[1]
>>>x
‘have’
>>>y
‘fun’
>>>

Example 3:
A particularly clever application of tuple assignment allows us to swap the values of
two variables in a single statement:
>>>a, b = b, a
Both sides of this statement are tuples, but the left side is a tuple of variables; the
right side is a tuple of expressions. Each value on the right side is assigned to its respective
variable on the left side. All the expressions on the right side are evaluated before any of the
assignments.
The number of variables on the left and the number of values on the right have to be
the same:
>>>a, b = 1, 2, 3
ValueError: too many values to unpack

Example 4:
More generally, the right side can be any kind of sequence (string, list or tuple). For
example, to split an email address into a user name and a domain, you could write:
>>>addr = ‘[email protected]
>>>uname, domain = addr.split(‘@’)
The return value from split is a list with two elements; the first element is assigned to
uname, the second to domain.
>>>print(uname)
monty
>>>print(domain)
python.org

Unit – 4 103
Mailam Engineering College GE3151 - Problem Solving and Python Programming

Tuples as return values


Strictly speaking, a function can only return one value, but if the value is a tuple, the
effect is the same as returning multiple values. For example, if you want to divide two
integers and compute the quotient and remainder, it is inefficient to compute x/y and then
x%y. It is better to compute them both at the same time.

Example:
The built-in function divmod takes two arguments and returns a tuple of two values,
the quotient and remainder. You can store the result as a tuple:
>>> t = divmod(7, 3)
>>>print(t)
(2, 1)
Or use tuple assignment to store the elements separately:
>>>quot, rem = divmod(7, 3)
>>>print(quot)
2
>>>print(rem)
1
Here is an example of a function that returns a tuple:
defmin_max(t):
return min(t), max(t)

max and min are built-in functions that find the largest and smallest elements of a sequence.
min_max computes both and returns a tuple of two values.

9) WRITE SEPARATE PYTHON PROGRAMS TO ILLUSTRATE CREATE, ACCESS,


CONCATENATION AND DELETE OPERATIONS IN A TUPLE. [AU – Jan 2022]
(Or)
DISCUSS THE BASIC TUPLE OPERATIONS WITH EXAMPLES.[AU – Dec 2022]
(i) Tuple Creation: Program
t=()
print()

t=(1, 2, 3)
print(t)

t1=(1,”success’, 9.5)
print(t1)

t2=(‘Raju’, [10,20,30], (1, 2, 3))


print(t2)

Output:
()
(1, 2, 3)
(‘Raju’, [10,20,30], (1, 2, 3))

(ii) Access Elements: Program


student=(‘Raju’, ‘CSE’, 18, 9.5)
print(student[1])
print(student[2])
print(student[-1])

Output:
CSE
18
19.5

Unit – 4 104
Mailam Engineering College GE3151 - Problem Solving and Python Programming

(iii) Concatenation of Tuple: Program


t1 =(1, 3, 5)
t2 =(4, 6)

print("The original tuple1: " +str(t1))


print("The original tuple2: " +str(t2))

res =t1 +t2

print("The tupleafter concatenation is: " +str(res))

Output:
The original tuple 1 : (1, 3, 5)
The original tuple 2 : (4, 6)
The tuple after concatenation is : (1, 3, 5, 4, 6)

(iv) Delete operation: Program


Unable to delete the specific element in a tuple. But delete an entire tuple is possible
by using del keyword.

t1 = (1, 3, 5)
del t1
print(t1) # NameError: name ‘t1’ is not defined.

10) WHAT IS DICTIONARY IN PYTHON? AND LIST OUT THE OPERATIONS AND
METHODS WITH EXAMPLE. (or) APPRAISE THE OPERATIONS FOR DYNAMICALLY
MANIPULATING DICTIONARIES (or) WHATIS DICTIONARY? EXPLAIN PYTHON
DICTIONARIES IN DETAIL DISCUSSING ITS OPERATIONS AND METHODS
[AU – JAN 18,19,APR 24]
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 braces-[].

Syntax:
dict={key1:val1, key2:val2, key3:val3, . . . , key N:val N}

Example:
dict = {}
dict[‘one’] = “This is one”
dict[2] = “This is two”
tinydict = {‘name’: ‘john’,‘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’: ‘john’}
[‘dept’, ‘code’, ‘name’]
[‘sales’, 6734, ‘john’]

Unit – 4 105
Mailam Engineering College GE3151 - Problem Solving and Python Programming

Dictionaries have no concept of order among the elements. It is incorrect to say that
the elements are “out of order”; they are simply unordered.

Types of operations on dictionaries.


Operator Explanation
len(d) Returns the number of stored entries, i.e. the number of (key, value) pairs.
del d[k] deletes the key k together with his value
k in d True, if a key k exists in the dictionary d
k not in d True, if a key k doesn't exist in the dictionary d

Types of methods on dictionaries. [AU – DEC 2023]


SN Methods with Description

1 dict.clear() - Removes all elements of dictionary dict

2 dict.copy() - Returns a shallow copy of dictionary dict

3 dict.fromkeys () - Create a new dictionary with keys from seq and values setto value.

4 dict.get(key, default=None) - For key key, returns value or default if key not in
dictionary

5 dict.has_key(key)-Returns true if key in dictionary dict, false otherwise

6 dict.items() - Returns a list of dict's (key, value) tuple pairs

7 dict.keys() - Returns list of dictionary dict's keys

8 dict.setdefault(key, default=None) - Similar to get(), but will set


dict[key]=default if key is not already in dict

9 dict.update(dict2) - Adds dictionary dict2's key-values pairs to dict

10 dict.values() - Returns list of dictionary dict's values

Example 1:
Print the keys and values in the above “vegetable” dictionary.
We can use the d.items() method to retrieve a list of tuples containing key value
pairs, then use unpacking to capture the key and value:

Vegetables = {
‘Eggplant’: ‘Purple’,
‘Tomato’: ‘Red’,
‘Parsley’: ‘Green’,
‘Lemon’: ‘Yellow’,
‘Pepper’: ‘Green’,
}
def test():

Unit – 4 106
Mailam Engineering College GE3151 - Problem Solving and Python Programming

for key, value in Vegetables.items():


print(‘key:’, key, ‘ value:’, value)
test()

Example 2:
Print the keys and values in the above “vegetable” dictionary with the keys in
alphabetical order.
We retrieve a list of keys with the keys() method, the sort it with the list sort()
method:

Vegetables = {
‘Eggplant’: ‘Purple’,
‘Tomato’: ‘Red’,
‘Parsley’: ‘Green’,
‘Lemon’: ‘Yellow’,
‘Pepper’: ‘Green’,
}
def test():
keys = Vegetables.keys()
keys.sort()
for key in keys:
print(‘key:’, key, ‘ value:’, Vegetables[key])
test()

Example 3:
Test for the occurance of a key in a dictionary.
To test for the existence of a key in a dictionary, we can use either the in operator
(preferred) or the d.has_key() method (old style):

Vegetables = {
‘Eggplant’: ‘Purple’,
‘Tomato’: ‘Red’,
‘Parsley’: ‘Green’,
‘Lemon’: ‘Yellow’,
‘Pepper’: ‘Green’,
}
def test():
if ‘Eggplant’ in Vegetables:
print(‘we have %s egplants’ %)
Vegetables[‘Eggplant’]
if ‘Banana’ not in Vegetables:
print(‘yes we have no bananas’)
ifVegetables.has_key(‘Parsley’):
print(‘we have leafy, %s parsley’ %
Vegetables[‘Parsley’]
test()
Output
we have Purple eggplants
yes we have no bananas
we have leafy, Green parsley

Unit – 4 107
Mailam Engineering College GE3151 - Problem Solving and Python Programming

LIST COMPREHENSION
11) WHAT IS LIST COMPREHENSION IN PYTHON? EXPLAIN WITH EXAMPLE.
[AU – JAN 2019]
A list comprehension is a convenient way to produce a list from an iterable (a sequence
or other object that can be iterated over).
In its simplest form, a list comprehension resembles the header line of a for statement
inside square brackets. However, in a list comprehension, the for statement header is
prefixed with an expression and surrounded by square brackets. Here is a template:
[expr(x) for x in iterable]
where:
expr(x) is an expression, usually, but not always, containing x.
iterable is some iterable. An iterable may be a sequence (for example, a list, a
string, a tuple) or an unordered collection or an iterator (something over which we
can iterate or apply a for statement to).

Example 1:
>>> a = [11, 22, 33, 44]
>>> b = [x * 2 for x in a]
>>>b
[22, 44, 66, 88]
Example 2:
Given the following list of strings:
names = [‘alice’, ‘bertrand’, ‘charlene’]
(i) a list of all upper case names;
(ii) a list of capitalized (first letter upper case);
For our expression in a list comprehension, use the upper and capitalize methods:
>>>names = [‘alice’, ‘bertrand’, ‘charlene’]
>>> [name.upper() for name in names]
[‘ALICE’, ‘BERTRAND’, ‘CHARLENE’]
>>> [name.capitalize() for name in names]
[‘Alice’, ‘Bertrand’, ‘Charlene’]

12) DISCUSS THE DIFFERENCES AND APPLICATIONS OF LISTS, TUPLE, AND


DICTIONARY IN PYTHON. [AU – DEC 2023]

Applications:
 Lists: Useful for dynamic collections where the data needs to be modified frequently,
such as task lists or shopping carts.
 Tuples: Ideal for fixed collections of items where the data should not change, such
as coordinates, dates, or immutable records.
 Dictionaries: Perfect for mapping unique keys to values, such as user profiles,
configurations, or any associative data structure requiring fast lookups and
modifications.

Unit – 4 108
Mailam Engineering College GE3151 - Problem Solving and Python Programming

PROGRAMS
13) WRITE A PYTHON PROGRAM FOR SELECTION SORT. [AU–JAN 18, 19, DEC 23]

# SELECTION SORT
n=int(input("Enter N:"))
a=[]

for i in range(n):
value=int(input("Enter value:"))
a.append(value)

for i in range(n):
min=i
for j in range(i+1,n):
if a[j] < a[min]:
min = j
if min != i:
t=a[i]
a[i]=a[min]
a[min]=t
print("After Sorting", a)
Output:
Enter N:5
Enter value:12
Enter value:21
Enter value:-12
Enter value:0
Enter value:4
After Sorting [-12, 0, 4, 12, 21]

Unit – 4 109
Mailam Engineering College GE3151 - Problem Solving and Python Programming

14) WRITE A PYTHON PROGRAM FOR INSERTION SORT.

n=int(input("Enter N:"))
a=[]

for i in range(n):
value=int(input("Enter value:"))
a.append(value)

for i in range(1,n):
key=a[i]
j=i
while j>0 and key<a[j-1]:
a[j]=a[j-1]
j=j-1
a[j]=key

print("After Sorting", a)
Output:
Enter N:5
Enter value:12
Enter value:34
Enter value:-45
Enter value:6
Enter value:0
After Sorting [-45, 0, 6, 12, 34]

15) WRITE A PYTHON PROGRAM FOR BUBBLE SORT. [AU – Apr/May 2022]

Unit – 4 110
Mailam Engineering College GE3151 - Problem Solving and Python Programming

n=int(input("Enter N:"))
a=[]

for i in range(n):
value=int(input("Enter value:"))
a.append(value)
for i in range(n-1):
for j in range(0, n-i-1):
if a[j] > a[j + 1]
temp = a[j];
a[j] = a[j+1];
a[j+1] = temp;
print ("After Sorting")
for i in range(len(a)):
print ("% d" % arr[i])

Output:
Enter N:5
Enter value:12
Enter value:34
Enter value:-45
Enter value:6
Enter value:0
After Sorting [-45, 0, 6, 12, 34]

16) WRITE A PYTHON PROGRAM FOR MERGE SORT. [AU – Jan 2019]

defmergesort(a):
iflen(a)>1:
mid = len(a)//2
left = a[:mid]
right = a[mid:]

mergesort(left)
mergesort(right)

i=0
j=0
k=0
while i <len(left) and j <len(right):

Unit – 4 111
Mailam Engineering College GE3151 - Problem Solving and Python Programming

if left[i] < right[j]:


a[k]=left[i]
i=i+1
else:
a[k]=right[j]
j=j+1
k=k+1
while i <len(left):
a[k]=left[i]
i=i+1
k=k+1
while j <len(right):
a[k]=right[j]
j=j+1
k=k+1
n=int(input("Enter N:"))
a=[]

for i in range(n):
value=int(input("Enter the value:"))
a.append(value)
print("Before Sorting", a)
mergesort(a)
print("After Sorting", a)

Output:
Enter N:6
Enter the value:12
Enter the value:2
Enter the value:43
Enter the value:56
Enter the value:2
Enter the value:111
Before Sorting [12, 2, 43, 56, 2, 111]
After Sorting [2, 2, 12, 43, 56, 111]

17) WRITE A PYTHON PROGRAM TO DRAW HISTOGRAM.


Histogram Program 1
def histogram( items ):
for n in items:
output = ''
times = n
while( times > 0 ):
output += '*'
times = times - 1
print(output)
histogram([2, 3, 6, 5])
Sample Output:
**
***
******
*****

(or)

Unit – 4 112
Mailam Engineering College GE3151 - Problem Solving and Python Programming

Histogram Program 2
importplotly.plotlyaspy
importplotly.graph_objsasgo

importnumpyasnp

x=np.random.randn(500)
data=[go.Histogram(x=x)]

py.iplot(data,filename='basic histogram')

Sample Output:

18) WRITE A PYTHON PROGRAM TO GENERATE STUDENTS MARKS STATEMENT.


print('STUDENTS MARK STATEMENT')
print('#' * 20)
name=input('Enter Name of the Students:')
dept,year=input('Enter Department:'),int(input('Enter Year:'))
n=int(input('Enter no.of subjects:'))
a=[]
for i in range(n):
print('Enter mark for sub',i+1,':',end=' ')
s=int(input())
a.append(s)
total=sum(a)
avg=total/n
print('#' * 20)
print('TOTAL=',total)
print('AVERAGE=',avg)
print('#' * 20)
Output:
STUDENTS MARK STATEMENT
####################
Enter Name of the Students:Zahir
Enter Department:CSE
Enter Year:1
Enter no.of subjects:5
Enter mark for sub 1 : 95
Enter mark for sub 2 : 96
Enter mark for sub 3 : 85
Enter mark for sub 4 : 89
Enter mark for sub 5 : 92
####################
TOTAL= 457
AVERAGE= 91.4
####################

Unit – 4 113
Mailam Engineering College GE3151 - Problem Solving and Python Programming

19) WRITE A PYTHON PROGRAM FOR RETAIL BILL PREPARATION.


prod_name1, prod_price1 = 'Books', 50.95
prod_name2, prod_price2 = 'Computer', 598.99
prod_name3, prod_price3 = 'Monitor', 156.89
cname = 'The Digital World.'
caddress = '144, Bridge Cross Street.'
ccity = 'NNNNNN'
message = 'Thanks for shopping with us today!'
print('*' * 50)
print('\t\t{}'.format(cname.title()))
print('\t\t{}'.format(caddress.title()))
print('\t\t{}'.format(ccity.title()))
print('=' * 50)
print('\tProduct Name\tProduct Price')
print('\t{}\t\t${}'.format(prod_name1.title(), prod_price1))
print('\t{}\t\t${}'.format(prod_name2.title(), prod_price2))
print('\t{}\t\t${}'.format(prod_name3.title(), prod_price3))
print('=' * 50)
print('\t\t\tTotal')
total = prod_price1 + prod_price2 + prod_price3
print('\t\t\t${}'.format(total))
print('=' * 50)
Output:
**************************************************
The Digital World.
144, Bridge Cross Street.
Nnnnnn
================================================
Product Name Product Price
Books $50.95
Computer $598.99
Monitor $156.89
================================================
Total
$806.83
================================================

20) WRITE A PYTHON PROGRAM TO CREATE A DICTIONARY AND SORT THE CONTEBNT
BASED ON VALUES IN REVERSE ORDER. [AU – Jan 2022]

from collections import OrderedDict

# initializing dictionary
test_dict = {'silver' : 4, 'gold' : 2, 'diamond' : 5}
print("The original dictionary : " + str(test_dict))
res = OrderedDict(reversed(list(test_dict.items())))

# printing dictionary in reversed order


print("The dictionary in reversed order : " + str(res))

Output:
The original dictionary : {'silver': 4, 'gold': 2, 'diamond': 5}
The dictionary in reversed order :OrderedDict([('diamond', 5), ('gold', 2), ('silver', 4)])

Unit – 4 114
Mailam Engineering College GE3151 - Problem Solving and Python Programming

21) WRITE A PYTHON PROGRAM THAT HAS A NESTED LIST TO STORE TOPPER DETAILS
AND DISPLAY THE DETAILS. [AU – Dec 2022]

toppers = [
[‘Anbu’,101, 95],
[‘Basha’,102, 98],
[‘Charles’,103, 92]
]

print(“Topper Details:”)
for t in toppers:
print(f“Name:{[t[0]},Rno:{t[1]},Mark:{t[2]}”)

Success is not in what you have, but who you are

Unit – 4 115
Mailam Engineering College GE3151 - Problem Solving and Python Programming

UNIT V FILES, MODULES, PACKAGES


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, Voter’s age validation, Marks range validation (0 – 100).

PART A – 2 MARKS
FILES
1) What is file? List out its types.
A collection of data or information that has a name, called the filename. Almost all
information stored in a computer must be in a file. File is a named location on disk to store
related information.
There are many different types of files, they are listed below:
 Data files
 Text files
 Program files
 Directory files, and so on.

2) List out the types of file mode.

Mode Description

'r' Open a file for reading. (default)

Open a file for writing. Creates a new file if it does not exist or truncates the file if it
'w'
exists.

'x' Open a file for exclusive creation. If the file already exists, the operation fails.

Open for appending at the end of the file without truncating it. Creates a new file if
'a'
it does not exist.

't' Open in text mode. (default)

'b' Open in binary mode.

'+' Open a file for updating (reading and writing)

3) List out the types of file operations.


 Open the file
 Read or write (Data Updating - perform operation)
 Close the file

4) Give the syntax and example of file open.


Syntax:
file_object = open(“filename”, “mode”)
Where
 File_object is the variable to add the file object
 mode – tells the interpreter and developer which way the file will be used.
Example:
f = open("test.txt")

5) Write the syntax for opening a file to write in binary mode. [AU – Jan 2022]
Syntax:
file_object = open(“filename”, “rb”)

Unit – 5 116
Mailam Engineering College GE3151 - Problem Solving and Python Programming

6) List any four operations. [AU – Jan 2022]


 open()
 read()
 write()
 readline()

7) What is file object attributes? List out its attributes.


Attribute Description

file.closed Returns true if file is closed, false otherwise.

file.mode Returns access mode with which file was opened.

file.name Returns name of the file.

file.softspace Returns false if space explicitly required with print, true


otherwise.

8) What is tell() in python?


The tell() method tells you the current position within the file; in other words, the
next read or write will occur at that many bytes from the beginning of the file.

9) What is seek() in python?


The seek(offset[, from]) method changes the current file position.
The offset argument indicates the number of bytes to be moved. The from argument
specifies the reference position from where the bytes are to be moved.

10) Write methods to rename and delete file. [AU – Dec 2019]
Syntax:
os.remove(file_name)

Example:
os.remove("text2.txt")

Example for rename () function. [AU – Dec 2022]


Syntax:
os.rename(current_file_name, new_file_name)
Example:
os.rename( "test1.txt", "test2.txt" )

11) List out the important directories in python.


a) mkdir()- Create a directory
b) chdir()-Change the current directory
c) getcwd() - Displays the current working directory
d) rmdir() - Deletes the directory

12) How to use command line arguments in python? [AU – Dec 2019, Dec 22]
Python provides a getopt module that helps you parse command-line options and
arguments.
$ python test.py arg1 arg2 arg3
The Python sys module provides access to any command-line arguments via the
sys.argv. This serves two purposes, they are:
sys.argv is the list of command-line arguments.
len(sys.argv) is the number of command-line arguments.

Unit – 5 117
Mailam Engineering College GE3151 - Problem Solving and Python Programming

ERRORS
13) What is error? List out the basic categories of Error.
Errors or mistakes in a program are often referred to as bugs. They are almost
always the fault of the programmer. The process of finding and eliminating errors is called
debugging. Errors can be classified into three major groups:
a) Syntax errors
b) Runtime errors
c) Logical errors

14) List out the common Python syntax errors.


 Leaving out a keyword
 Putting a keyword in the wrong place
 Leaving out a symbol, such as a colon, comma or brackets
 Misspelling a keyword
 Incorrect indentation
 Empty block

15) Give some examples of Runtime errors.


 Division by zero
 Performing an operation on incompatible types
 Using an identifier which has not been defined
 Accessing a list element, dictionary value or object attribute which doesn’t exist
 Trying to access a file which doesn’t exist

16) Give some examples of Logical errors.


 Using the wrong variable name
 Indenting a block to the wrong level
 Using integer division instead of floating-point division
 Getting operator precedence wrong
 Making a mistake in a Boolean expression

17) What is the goal of AssertionError?


 The goal of an AssertionError in Python is to inform developers
about unrecoverable errors in a program.
 Python’s assert statement is a debugging aid, not a mechanism for handling run-time
errors.
 The goal of using assertions is to let developers find the likely root cause of a bug
more quickly.

EXCEPTIONS

18) What are exceptions? [AU – Dec 2022]


An exception is an event, which occurs during the execution of a program that
disrupts the normal flow of the program’s instructions.
In general, when a Python script encounters a situation that it cannot cope with, it
raises an exception. An exception is a Python object that represents an error.
When a Python script raises an exception, it must either handle the exception
immediately otherwise it terminates and quits.

19) How exceptions are handled in Python? [AU – Dec 2023]


Python provides two very important features to handle any unexpected error in the
Python programs and to add debugging capabilities in them.
 Exception Handling
 Assertions

Unit – 5 118
Mailam Engineering College GE3151 - Problem Solving and Python Programming

20) List few common exception types. [AU – Apr 2024]


S.No Exception Description
Name
1 Exception Base class for all exceptions
2 StopIteration Raised when the next() method of an
iterator does not point to any object.
3 ArithmeticError Base class for all errors that occur for
numeric calculation.
4 ZeroDivisionError Raised when division or modulo by zero
takes place for all numeric types.

21) Give the syntax for raise exception.


Syntax:

raise [Exception [, args [, traceback]]]

Here, Exception is the type of exception (For example, NameError) and argument is a
value for the exception argument. The argument is optional; if not supplied, the exception
argument is None. The final argument, traceback, is also optional (and rarely used in
practice), and if present, is the traceback object used for the exception.

22) What are advantages of Exception Handling?


 It separates normal code from code that handles errors.
 Exceptions can easily be passed along functions in the stack until they reach a
function which knows how to handle them. The intermediate functions don’t need to
have any error-handling code.
 Exceptions come with lots of useful error information built in – for example, they can
print a trace back which helps us to see exactly where the error occurred.

MODULES
23) What is module in Python? Give an example. (or)
Write a note on modular design. [AU – Jan 2018, Apr 24]
It is a file consisting of Python code. A module can define functions, classes and
variables. A module can also include runnable code.
Example:
# Fibonacci numbers module
def fib(n): # write Fibonacci series up to n
a, b = 0, 1
while b < n:
print(b)
a, b = b, a+b

Now enter the Python interpreter and import this module with the following command:
import fibo
Using the module name you can access the functions:
fibo.fib(1000)
1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987

24) What are the different modules in Python?


 Numpy
 Tkinter
 Pygame
 DBM
 Ftplib
 Funcools
 Flask
 Matplotlib

Unit – 5 119
Mailam Engineering College GE3151 - Problem Solving and Python Programming

25) Differentiate: locals() and globals()functions.


locals() globals()
If locals() is called from within a function, it If globals() is called from within a function, it
will return all the names that can be will return all the names that can be
accessed locally from that function. accessed globally from that function. The
return type of both these functions is
dictionary. Therefore, names can be
extracted using the keys() function.

26) What is a package in Python? [AU – Apr 2024]


A package is a hierarchical file directory structure that defines a single Python
application environment that consists of modules and subpackages and sub-subpackages,
and so on.

27) Differentiate: module and package in Python.


Module Package
A module is a single file (or files) that are A package is a collection of modules in
imported under one import and used. directories that give a package hierarchy.
Example: Example:
import my_module from Pots import Pots

28) Write the significance of format operator. [AU – Dec 2023]


 %s is a placeholder for a string.
 %d is a placeholder for an integer.
 %f is a placeholder for a floating-point number with two decimal places.

29) Write a Python script to display the current date and time. [AU – Jan 2018]
import datetime
print(“Date and Time=”,datetime.datetime.now())

30) Find the syntax error in the code given: [AU – Jan 2019]
while True print(‘Hello world’)
Error: Syntax Error
Correct Code:
while True:
print(‘Hello world’)

31) Write a python program to count words in a sentence using split() function.
str=’All is well’
print(‘Actual string=’,str)
ans=len(str.split())
print(‘Number of words=’,ans)

Output:
Actual string=All is well
Number of words=3

Unit – 5 120
Mailam Engineering College GE3151 - Problem Solving and Python Programming

PART B
FILES
1) GIVE BRIEF INTRODUCTION ABOUT FILES IN PYTHON AND TABULATE THE
DIFFERENT MODES FOR OPENING A FILE AND BRIEFLY EXPLAIN THE SAME
[AU – Jan 2018]
(or)
WHY DOES PYTHON REQUIRE FILE HANDLING? EXPLAIN OPENING FILES IN
PYTHON WITH ALL MODES. [AU – Apr/May 2022]
(or)
NAME THE DIFFERENT ACCESS MODES FOR OPENING A FILE AND PRESENT AN
OUTLINE OF THE SAME. [AU – Jan 2022, Dec 2023]
 A collection of data or information that has a name, called the filename.
 Almost all information stored in a computer must be in a file.
 File is a named location on disk to store related information.
 It is used to permanently store data in a non-volatile memory (e.g. hard disk).
 Since, random access memory (RAM) is volatile which loses its data when computer
is turned off, we use files for future use of the data.

DIFFERENT TYPES OF FILES


 Data files
 Text files
 Program files
 Directory files, and so on.
Different types of files store different types of information. For example, program files store
programs, whereas text files store text.

REASON FOR USING FILES


 Reusability
 Large storage capacity
 Saves time
 portability

FILE OPENING MODE

Mode Description

r Opens a file for reading only. This is the default mode.

rb Opens a file for reading only in binary format. This is the default mode.

r+ Opens a file for both reading and writing.

rb+ Opens a file for both reading and writing in binary format.

Opens a file for writing only. Overwrites the file if the file exists. If the file does
w
not exist, creates a new file for writing.

wb Opens a file for writing only in binary format. Overwrites the file if the file exists.

Opens a file for both writing and reading. Overwrites the existing file if the file
w+
exists. If the file does not exist, creates a new file for reading and writing.

Unit – 5 121
Mailam Engineering College GE3151 - Problem Solving and Python Programming

wb+ Opens a file for both writing and reading in binary format.

Opens a file for appending. The file pointer is at the end of the file if the file
a
exists.

ab Opens a file for appending in binary format. The file pointer is at the end of the
file if the file exists.

Opens a file for both appending and reading. The file pointer is at the end of the
a+
file if the file exists. The file opens in the append mode.

Opens a file for both appending and reading in binary format. The file pointer is
ab+
at the end of the file if the file exists. The file opens in the append mode.

FILE OPERATIONS
When the user wants to read from or write to a file we need to open it first, it needs
to be closed, so that resources that are tied with the file are freed.
In Python, a file operation takes place in the following order.
 Open the file
 Read or write (Data Updating - perform operation)
 Close the file

2) BRIEFLY EXPLAIN ABOUT THE CONCEPT OF FILE OPERATIONS WITH RELEVANT


EXAMPLES. [AU – Dec 2023]
When the user wants to read from or write to a file we need to open it first, it needs
to be closed, so that resources that are tied with the file are freed.
In Python, a file operation takes place in the following order.
i) Open the file
ii) Read or write (Data Updating - perform operation)
iii) Close the file

i) OPEN A FILE
Python has a built-in function open() to open a file. This function returns a file object,
so it is most commonly used with two arguments. An argument is nothing more than a
value that has been provided to a function, which is relayed when you call it. So, for
instance, if we declare the name of a file as “Test File,” that name would be considered an
argument.

Syntax:
file_object = open(“filename”, “mode”)
Where
 File_object is the variable to add the file object
 mode – tells the interpreter and developer which way the file will be used.

Example:
f = open("test.txt") # open file in current directory
f = open("C:/Python33/sample.txt") # specifying full path
f = open("test.txt") # equivalent to 'r' or 'rt'
f = open("test.txt",'w') # write in text mode
f = open("homepg.bmp",'r+b') # read and write in binary mode

Unit – 5 122
Mailam Engineering College GE3151 - Problem Solving and Python Programming

(ii) READING AND WRITING FILES [AU – Jan 2019]


The file object provides a set of access methods to make our lives easier. In general,
there are two methods to manipulate the files, they are given below:
a) write()
b) read()

a) write() Method
This method writes any string to an open file. It is important to note that Python
strings can have binary data and not just text.
The write() method does not add a newline character ('\n') to the end of the string.

Syntax:
fileObject.write(string);
Example:
f= open("sam1.txt", "wb") # Open a file
f.write( "I will try my best.\nGod is always with me!!\n");
f.close() # Close opend file

The above method would create sam1.txt file and would write given content in that
file and finally it would close that file. If you would open this file.

Output:
I will try my best
God is always with me!!

b) read() Method
This method reads a string from an open file. It is important to note that Python
strings can have binary data. Apart from text data.

Syntax:
fileObject.read([count]);

Here, passed parameter is the number of bytes to be read from the opened file. This
method starts reading from the beginning of the file and if count is missing, then it tries to
read as much as possible, maybe until the end of file.

Example:
Let's take a file sam1.txt, which we created above.
f = open("sam1.txt", "r+") # Open a file
str = f.read(10);
print("Read String is : ", str)
f.close() # Close opend file

Output
Read String is : I will tr

(iii) CLOSE A FILE


This method of a file object flushes any unwritten information and closes the file
object, after which no more writing can be done.
Python automatically closes a file when the reference object of a file is reassigned to
another file. It is a good practice to use the close() method to close a file.
Syntax
fileObject.close();

Unit – 5 123
Mailam Engineering College GE3151 - Problem Solving and Python Programming

Example
f = open("sam1.txt", "wb") # Open a file
print("Name of the file: ", f.name)
f.close() # Close opend file

Output
Name of the file: sam1.txt

3) HOW TO CREATE A TEXT FILE AND HOW TO SPLIT A LINE IN A SPECIFIC TEXT
FILE?

CREATE A TEXT FILE


 To get more familiar with text files in Python, let’s create our own and do some
additional exercises.
 Using a simple text editor, let’s create a file. The user can name it anything as like,
and it’s better to use something you’ll identify with.
 To manipulate the file, write the following in your Python environment (you can copy
and paste if you’d like):

Example:
file = open(“samtext.txt”,”w”)

file.write(“Hello World”)
file.write(“God is Great”)
file.write(“Think Positive.”)
file.write(“Everything is possible.”)

file.close()

Output:
$ cat samtext.txt
Hello World
God is Great
Think Positive.
Everything is possible.

SPLITTING LINES IN A TEXT FILE


This function that allows you to split the lines taken from a text file. What this is
designed to do, is split the string contained in variable data whenever the interpreter
encounters a space character.
The user can actually split your text using any character you wish - such as a colon,
instead of space character.

Example:
f=open(“hello.text”, “r”)
data = f.readlines()

for line in data:


words = line.split()
print(words)

Unit – 5 124
Mailam Engineering College GE3151 - Problem Solving and Python Programming

If you wanted to use a colon instead of a space to split your text, you would simply
change line.split() to line.split(“:”).

Output

[“hello”, “world”, “how”, “are”, “you”, “today?”]


[“today”, “is”, “Myday”]

The reason the words are presented in this manner is because they are stored – and
returned – as an array. Be sure to remember this when working with the split function

4) BRIEFLY EXPLAIN HOW TO MANIPULATE A FILE? WHAT ARE ALL METHODS ARE
AVAILABLE IN IT? EXPLAIN WITH EXAMPLES.

(i) FILE POSITIONS


There are two major methods are play the vital role, they are:
 tell()
 seek()

 The tell() method tells you the current position within the file; in other words,
the next read or write will occur at that many bytes from the beginning of the
file.

 The seek(offset[, from]) method changes the current file position.


The offset argument indicates the number of bytes to be moved.
The from argument specifies the reference position from where the bytes are
to be moved.
If from is set to 0, it means use the beginning of the file as the reference position
and 1 means use the current position as the reference position and if it is set to 2 then the
end of the file would be taken as the reference position.

Example
Let us take a file sam1.txt, which we created above.

f = open("sample.txt", "r+") #I will try my best


str = f.read(10)
print("Read String is : ", str)

# Check current position


position = f.tell()
print("Current file position : ", position)

# Reposition pointer at the beginning once again


position = f.seek(0, 0)
str = f.read(13)
print("Again read String is : ", str)
f.close()

Output

Read String is : I will try


Current file position : 10
Again read String is : I will try my

Unit – 5 125
Mailam Engineering College GE3151 - Problem Solving and Python Programming

(ii) RENAMING AND DELETING FILES


Two file-processing operations are there, they are:
a) renaming
b) deleting or remove files.
To use this module you need to import it first and then you can call any related functions.

a) The rename() Method


The rename() method takes two arguments, the current filename and the new
filename.

Syntax
os.rename(current_file_name, new_file_name)

Example
import os
os.rename( "test1.txt", "test2.txt" ) # Rename a file from test1.txt to test2.txt

b) The remove() Method


This method is used to delete files by supplying the name of the file to be deleted as
the argument.

Syntax
os.remove(file_name)
Example
Following is the example to delete an existing file test2.txt

import os
os.remove("text2.txt") # Delete file test2.txt

5) LIST OUT AND EXPLAIN THE DIRECTORIES IN PYTHON.


DIRECTORIES IN PYTHON
All files are contained within various directories, and Python has no problem handling
these too. The os module has several methods that help you create, remove, and change
directories, they are:
a) mkdir()
b) chdir()
c) getcwd()
d) rmdir()
a) The mkdir() Method
This mkdir() method of the os module to create directories in the current directory.
You need to supply an argument to this method which contains the name of the directory to
be created.
Syntax
os.mkdir("newdir")

Example
Following is the example to create a directory test in the current directory −
import os
os.mkdir("test")

b) The chdir() Method


This chdir() method to change the current directory. The chdir() method takes an
argument, which is the name of the directory that you want to make the current directory.

Unit – 5 126
Mailam Engineering College GE3151 - Problem Solving and Python Programming

Syntax
os.chdir("newdir")
Example
Following is the example to go into "/home/newdir" directory −
import os
os.chdir("/home/newdir")

c) The getcwd() Method


The getcwd() method displays the current working directory.
Syntax:
os.getcwd()
Example:
import os
os.getcwd()

d) The rmdir() Method


This rmdir() method deletes the directory, which is passed as an argument in the
method.
Before removing a directory, all the contents in it should be removed.
Syntax:
os.rmdir('dirname')
Example:
To remove "/tmp/test" directory. It is required to give fully qualified name of the
directory, otherwise it would search for that directory in the current directory.
import os
os.rmdir( "/tmp/test" )

COMMAND-LINE ARGUMENTS
6) ILLUSTRATE THE CONCEPT OF COMMAND-LINE ARGUMENTS WITH SYNTAX AND
EXAMPLE. [AU – Dec 2023]
Command-line options and arguments:
Python provides a getopt module that helps you parse command-line options and
arguments.
$ python test.py arg1 arg2 arg3
The Python sys module provides access to any command-line arguments via
the sys.argv. This serves two purposes, they are:
 sys.argv is the list of command-line arguments.
 len(sys.argv) is the number of command-line arguments.
Here sys.argv[0] is the program ie. script name.

Example:
Consider the following script test.py
import sys

print(“Number of arguments:”, len(sys.argv), “arguments.”)


print(“Argument List:', str(sys.argv))

Output:
$ python test.py arg1 arg2 arg3
Number of arguments: 4 arguments.
Argument List: ['test.py', 'arg1', 'arg2', 'arg3']

Unit – 5 127
Mailam Engineering College GE3151 - Problem Solving and Python Programming

NOTE: As mentioned above, first argument is always script name and it is also being
counted in number of arguments.

PARSING COMMAND-LINE ARGUMENTS


Python provided a getopt module that helps you parse command-line options and
arguments. This module provides two functions and an exception to enable command line
argument parsing.
 getopt.getopt method
This method parses command line options and parameter list.
Syntax
getopt.getopt(args, options, [long_options])

Here is the detail of the parameters:


 args: This is the argument list to be parsed.
 options: This is the string of option letters that the script wants to recognize, with
options that require an argument should be followed by a colon (:).
 long_options: This is optional parameter and if specified, must be a list of strings
with the names of the long options, which should be supported. Long options, which
require an argument should be followed by an equal sign ('='). To accept only long
options, options should be an empty string.
 This method returns value consisting of two elements: the first is a list of (option,
value) pairs. The second is the list of program arguments left after the option list
was stripped.
 Each option-and-value pair returned has the option as its first element, prefixed with
a hyphen for short options (e.g., '-x') or two hyphens for long options (e.g., '--long-
option').
 Exception getopt.GetoptError
This is raised when an unrecognized option is found in the argument list or when an
option requiring an argument is given none.

The argument to the exception is a string indicating the cause of the error. The
attributes msg and opt give the error message and related option

Example
Consider we want to pass two file names through command line and we also want to
give an option to check the usage of the script. Usage of the script is as follows.
usage: test.py -i <inputfile> -o <outputfile>

Here is the following script to test.py

import sys, getopt

def main(argv):
inputfile = ''
outputfile = ''
try:
opts, args = getopt.getopt(argv,"hi:o:",["ifile=","ofile="])
except getopt.GetoptError:
print('test.py -i <inputfile> -o <outputfile>')
sys.exit(2)
for opt, arg in opts:
if opt == '-h':
print('test.py -i <inputfile> -o <outputfile>')
sys.exit()
elif opt in ("-i", "--ifile"):
inputfile = arg
elif opt in ("-o", "--ofile"):

Unit – 5 128
Mailam Engineering College GE3151 - Problem Solving and Python Programming

outputfile = arg
print('Input file is "', inputfile)
print('Output file is "', outputfile)

if __name__ == "__main__":
main(sys.argv[1:])

Output:
$ test.py -h
usage: test.py -i <inputfile> -o <outputfile>

$ test.py -i BMP -o
usage: test.py -i <inputfile> -o <outputfile>

$ test.py -i inputfile
Input file is " inputfile
Output file is "

Many programs can be run to provide you with some basic information about how
they should be run. Python enables you to do this with -h:

$ python –h

usage: python [option] ... [-c cmd | -m mod | file | -] [arg] ...

Options and arguments (and corresponding environment variables):


-c cmd : program passed in as string (terminates option list)
-d : debug output from parser (also PYTHONDEBUG=x)
-E : ignore environment variables (such as PYTHONPATH)
-h : print this help message and exit
ERRORS

7) WHAT IS ERROR? EXPLAIN THE TYPES OF ERROR.


Errors or mistakes in a program are often referred to as bugs. They are almost
always the fault of the programmer. The process of finding and eliminating errors is called
debugging.

THREE MAJOR GROUPS:


a) Syntax errors
b) Runtime errors
c) Logical errors

a) Syntax errors
Python will find these kinds of errors when it tries to parse your program, and exit
with an error message without running anything. Syntax errors are mistakes in the use of
the Python language, and are analogous to spelling or grammar mistakes in a language like
English:

Common Python syntax errors include:


 leaving out a keyword
 putting a keyword in the wrong place
 leaving out a symbol, such as a colon, comma or brackets
 misspelling a keyword
 incorrect indentation
 empty block
Examples - syntax errors in Python:

Unit – 5 129
Mailam Engineering College GE3151 - Problem Solving and Python Programming

myfunction(x, y):
return x + y

else:
print("Hello!")

if mark >= 50
print("You passed!) #Ending of double quotes missing

if arriving:
print("Hi!")
esle: # Spelling mistakes in else
print("Bye!")

if flag:
print("Flag is set!") #Indentation

b) Runtime errors
If a program is syntactically correct, that is, free of syntax errors, it will be run by the
Python interpreter. However, the program may exit unexpectedly during execution if it
encounters a runtime error – a problem which was not detected when the program was
parsed, but is only revealed when a particular line is executed. When a program comes to a
halt because of a runtime error, we say that it has crashed.
Examples of Python runtime errors:
 division by zero
 performing an operation on incompatible types
 using an identifier which has not been defined
 accessing a list element, dictionary value or object attribute which doesn’t exist
 trying to access a file which doesn’t exist

c) Logical errors
Logical errors are the most difficult to fix. They occur when the program runs without
crashing, but produces an incorrect result. The error is caused by a mistake in the program’s
logic. You won’t get an error message, because no syntax or runtime error has occurred. You
will have to find the problem on your own by reviewing all the relevant parts of your code,
although some tools can flag suspicious code which looks like it could cause unexpected
behavior.
Examples
 using the wrong variable name
 indenting a block to the wrong level
 using integer division instead of floating-point division
 getting operator precedence wrong
 making a mistake in a Boolean expression
 off-by-one, and other numerical errors
If you misspell an identifier name, may get a runtime error or a logical error,
depending on whether the misspelled name is defined.

Unit – 5 130
Mailam Engineering College GE3151 - Problem Solving and Python Programming

EXCEPTION HANDLING
8) HOW TO HANDLE EXCEPTION? EXPLAIN IN DETAILS
(or)
APPRAISE THE USE OF TRY BLOCK AND EXCEPT BLOCK IN PYTHON WITH SYNTAX.
[AU – JAN 2018 & Dec 2019]
(or)
WHAT IS AN EXCEPTION? ELABORATE EXCEPTION HANDLING IN PYTHON.
[AU – Jan 2022]
 Errors can also occur at runtime and these are called exceptions.
 A file trying to open does not exist (FileNotFoundError), dividing a number by Zero
(ZeroDivisionError), trying to import a module and is not found (ImportError) etc, are
exceptions.
 Whenever these types of n time error occur, python creates an exception object. If
they are not handled properly, it prints a traceback to that error along with some
details about why that error occurred.

The try and except statements are used to handle the runtime errors.
 try
 except
Syntax

try:
You do your operations here;
......................
except ExceptionI:
If there is ExceptionI, then execute this block.
except ExceptionII:
If there is ExceptionII, then execute this block.
......................
else:
If there is no exception then execute this block.

Important points about syntax:


 A single try statement can have multiple except statements. This is useful when the
try block contains statements that may throw different types of exceptions.
 You can also provide a generic except clause, which handles any exception.
 After the except clause(s), you can include an else-clause. The code in the else-block
executes if the code in the try: block does not raise an exception.
 The else-block is a good place for code that does not need the try: block's protection.

Example 1

try:
fh = open("testfile", "w")
fh.write("This is my test file for exception handling!!")

except IOError:
print("Error: can\'t find file or read data")

else:
print("Written content in the file successfully")
fh.close()

Output
Written content in the file successfully

Unit – 5 131
Mailam Engineering College GE3151 - Problem Solving and Python Programming

Example 2
This example tries to open a file where you do not have write permission, so it raises
an exception:

try:
fh = open("testfile", "r")
fh.write("This is my test file for exception handling!!")

except IOError:
print("Error: can\'t find file or read data")

else:
print("Written content in the file successfully")

Output
Error: can't find file or read data

9) LIST OUT AND DESCRIBE THE PRE-DEFINED METHODS OF EXCEPTION


HANDLING.
EXCEPTION NAME DESCRIPTION

Exception Base class for all exceptions

StopIteration Raised when the next() method of an iterator does not point
to any object.

SystemExit Raised by the sys.exit() function.

StandardError Base class for all built-in exceptions except StopIteration and
SystemExit.

ArithmeticError Base class for all errors that occur for numeric calculation.

OverflowError Raised when a calculation exceeds maximum limit for a


numeric type.

FloatingPointError Raised when a floating point calculation fails.

ZeroDivisionError Raised when division or modulo by zero takes place for all
numeric types.

AssertionError Raised in case of failure of the Assert statement.

AttributeError Raised in case of failure of attribute reference or assignment.

EOFError Raised when there is no input from either the raw_input() or


input() function and the end of file is reached.

ImportError Raised when an import statement fails.

KeyboardInterrupt Raised when the user interrupts program execution, usually


by pressing Ctrl+c.

LookupError Base class for all lookup errors.

Unit – 5 132
Mailam Engineering College GE3151 - Problem Solving and Python Programming

IndexError Raised when an index is not found in a sequence.


KeyError Raised when the specified key is not found in the dictionary.

NameError Raised when an identifier is not found in the local or global


namespace.

IOError Raised when an input/ output operation fails, such as the


IOError print statement or the open() function when trying to open a
file that does not exist.
Raised for operating system-related errors.

SystemError Raised when the interpreter finds an internal problem, but


when this error is encountered the Python interpreter does
not exit.

SystemExit Raised when Python interpreter is quit by using the sys.exit()


function. If not handled in the code, causes the interpreter to
exit.

TypeError Raised when an operation or function is attempted that is


invalid for the specified data type.

ValueError Raised when the built-in function for a data type has the valid
type of arguments, but the arguments have invalid values
specified.

RuntimeError Raised when a generated error does not fall into any
category.

10) EXPLAIN IN DETAILS ABOUT USED-DEFINED EXCEPTION WITH EXAMPLE. (or)


EXPLAIN WITH AN EXAMPLE EXCEPTIONS WITH ARGUMENTS IN PYTHON.
[AU – JAN 2018]
 Python also allows you to create your own exceptions by deriving classes from the
standard built-in exceptions.
 Here is an example related to RuntimeError. Here, a class is created that is
subclassed from RuntimeError. This is useful when you need to display more specific
information when an exception is caught.
 In the try block, the user-defined exception is raised and caught in the except block.
 The variable e is used to create an instance of the class Networkerror.

class Networkerror(RuntimeError):
def __init__(self, arg):
self.args = arg

So once you defined above class, you can raise the exception as follows:
try:
raise Networkerror("Bad hostname")
except Networkerror,e:
print(e.args)

Unit – 5 133
Mailam Engineering College GE3151 - Problem Solving and Python Programming

MODULES

11) WHAT ARE MODULES IN PYTHON? HOW WILL YOU IMPORT THEM? EXPLAIN
THE CONCEPT BY CREATING AND IMPORTING A MODULE. [AU – Dec 19, Dec 22]
 A module allows to logically organizing the Python code.
 Grouping related code into a module makes the code easier to understand and use.
 A module is a Python object with arbitrarily named attributes that you can bind and
reference.
 Simply, a module is a file consisting of Python code. A module can define functions,
classes and variables. A module can also include runnable code.
Example 1
The Python code for a module named aname normally resides in a file
named aname.py. Here is an example of a simple module, support.py
def print_func( par ):
print("Think : ", par)
return

Example 2
A module is a file containing Python definitions and statements. The file name is the
module name with the suffix .py appended. Within a module, the module’s name (as a
string) is available as the value of the global variable name. For instance, use your favorite
text editor to create a file called fibo.py in the current directory with the following contents:

# Fibonacci numbers module

def fib(n): # write Fibonacci series up to n


a, b = 0, 1
while b < n:
print(b)
a, b = b, a+b

def fib2(n): # return Fibonacci series up to n


result = []
a, b = 0, 1
while b < n:
result.append(b)
a, b = b, a+b
return result
Now enter the Python interpreter and import this module with the following command:
 import fibo
This does not enter the names of the functions defined in fibo directly in the current
symbol table; it only enters the module name fibo there. Using the module name you
can access the functions:

fibo.fib(1000)
1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987

fibo.fib2(100)
[1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]

fibo.__name__
'fibo'

If you intend to use a function often you can assign it to a local name:
fib = fibo.fib
fib(500)
1 1 2 3 5 8 13 21 34 55 89 144 233 377

Unit – 5 134
Mailam Engineering College GE3151 - Problem Solving and Python Programming

THREE WAYS TO ACCESS MODULE:


a) The import Statement
b) The from...import Statement
c) The from...import * Statement
a) The import Statement
You can use any Python source file as a module by executing an import statement in
some other Python source file. The import has the following syntax:
import module1[, module2[,... moduleN]
When the interpreter encounters an import statement, it imports the module if the
module is present in the search path. A search path is a list of directories that the interpreter
searches before importing a module. For example, to import the module hello.py, you need
to put the following command at the top of the script:
# Import module support
import support
# Now you can call defined function that module as follows
support.print_func("Positive")
Output
Think : Positive

b) The from...import Statement


Python's from statement lets you import specific attributes from a module into the
current namespace. The from...import has the following syntax:
from modname import name1[, name2[, ... nameN]]

To import the function fibonacci from the module fib, use the following statement:
Example
from fib import fibonacci
This statement does not import the entire module fib into the current namespace; it
just introduces the item fibonacci from the module fib into the global symbol table of the
importing module.

c) The from...import * Statement


It is also possible to import all names from a module into the current namespace by
using the following import statement:
from modname import *
This provides an easy way to import all the items from a module into the current
namespace; however, this statement should be used sparingly.

LOCATING MODULES
When you import a module, the Python interpreter searches for the module in the
following sequences:
 The current directory.
 If the module isn't found, Python then searches each directory in the shell variable
PYTHONPATH.
 If all else fails, Python checks the default path. On UNIX, this default path is normally
/usr/local/lib/python/.
The module search path is stored in the system module sys as the sys.path variable.
The sys.path variable contains the current directory, PYTHONPATH, and the
installation-dependent default.

Unit – 5 135
Mailam Engineering College GE3151 - Problem Solving and Python Programming

PACKAGES
12) EXPLAIN IN DETAIL ABOUT PACKAGES IN PYTHON. [AU – Dec 22]
 A package is a collection of modules in hierarchical file directory structure.
 Structure that defines a single Python application environment that consists of
modules and subpackages and sub-subpackages, and so on.
Syntax:
import PackageName.SubPackageName.ModuleName

Example:
import bankapp.atmpack.withdrawnpro

THREE WAY OF ACCESSING:


a) import
b) from (option 1)
c) from (option 2)

a) import
Example:
import bankapp.atmpack.withdrawnpro
bankapp.atmpack.withdrawnpro.start()
b) from (option 1)
Example:
from bankapp.atmpack import withdrawnpro
withdrawnpro.start()
c) from (option 1)
Example:
from bankapp.atmpack.withdrawnpro import start
start()
Diagram:
Bankapp (Bank Application)

Atmpack (ATM Package)

withdrawnpro (Withdrawn Program)

13) WRITE A PYTHON PROGRAM TO COUNT NO.OF WORDS APPEARS IN A FILE.


Program: [AU – Dec 2019, Dec 2023]
#COUNT MOST FREQUENT WORD – FILE
f = open("myfile.txt", "r")
data = f.read()

words = data.split(" ")

i=0
wordcount= {}
while i < len(words):
item = words[i]
wordcount[item] = words.count(item)
i=i+1
print(wordcount)
f.close()
Output:
#myfile.txt
hello world hello python
{'hello': 2, 'world': 1, 'python': 1}

Unit – 5 136
Mailam Engineering College GE3151 - Problem Solving and Python Programming

14) WRITE A PROGRAM TO CONCATENATE THE CONTENTS OF TWO FILES INTO A


SINGLE FILE. GET THE INPUT FOR TWO FILES FROM THE USER AND CONCATENATE
IT. (or) OPENING & CLOSING FILE [AU – Apr/May 2022, Dec 2022]

data1=data2=' '

f=open('file1.txt','w')
f.write('All is well\n Think Positive')
f.close()

f=open('file2.txt','w')
f.write('Today My story\nTomorrow History')
f.close()

f1=open('file1.txt','r')
f2=open('file2.txt','r')
f3=open('file3.txt','w')

data1=f1.read()
data2=f2.read()

data1=data1 + ' '


data1=data1 + data2

f3.write(data1)

f1.close()
f2.close()
f3.close()

print('Concatenation process success')

15) WRITE A PYTHON PROGRAM TO COPY A SOURCE FILE TO DESTINATION FILE.

from shutil import copyfile


sourcefile = input("Enter source file name: ")
destinationfile = input("Enter destination file name: ")

copyfile(sourcefile, destinationfile)

print("File copied successfully!")


print("Want to display the content ? (y/n): ")
check = input()

if check == 'n':
print("Thank You")
else:
c = open(destinationfile, "r")
print(c.read())
c.close()
print("Thank You")

Unit – 5 137
Mailam Engineering College GE3151 - Problem Solving and Python Programming

16) WRITE A PYTHON PROGRAM FOR VOLTER’S AGE VALIDATION

def main():
try:
age=int(input('Enter your age:'))
if age>18:
print("Eligible to vote")
else:
print("Not eligible to vote")

except ValueError as err:


print(err)
else:
print("Thank you, you have successfully checked the voting eligibility")

main()

Output

Enter your age: 19


Eligible to vote
Thank you, you have successfully checked the voting eligibility

17) WRITE A PYTHON PROGRAM FOR MARKS RANGE VALIDATION (0 – 100)

def main():
try:
mark=int(input('Enter your Mark:'))
if age<=100 and mark>=0:
print("Valid Mark")
else:
print("Invalid")
#display exception's default error message
except ValueError as err:
print(err)
else:
# code to be excuted when there is no exception
print("Thank you, Validated")

main()

Output

Enter your Mark:99


Valid Mark
Thank you, Validated

18) WRITE A PYTHON PROGRAM TO HANDLE THE DIVISION BY ZERO EXCEPTION.


[AU – Dec 2022]
try:
a=int(input(‘Enter any number:’))
d=int(input(‘Enter the divisor:’))
ans=a/d
except ZeroDivisionError:
print(‘Divisor is zero’)
else:
print(‘Answer:’, ans)

Unit – 5 138
Mailam Engineering College GE3151 - Problem Solving and Python Programming

19) WRITE A PROGRAM TO ENTER A NUMBER IN PYTHON AND PRINT ITS OCTAL
AND HEXADECIMAL EQUIVALENT. [AU – Apr 2024]

number = int(input("Enter a number: "))


octal_equivalent = oct(number)
hexadecimal_equivalent = hex(number)
print(f"Decimal: {number}")
print(f"Octal: {octal_equivalent}")
print(f"Hexadecimal: {hexadecimal_equivalent}")

I have just trIed to do my very best each and every day.”


Abraham Lincoln

All the very best

Unit – 5 139
www.EnggTree.com

Downloaded from EnggTree.com


www.EnggTree.com

Downloaded from EnggTree.com


EnggTree.com

Downloaded from EnggTree.com


EnggTree.com

Downloaded from EnggTree.com


EnggTree.com

Downloaded from EnggTree.com

You might also like