PSP Full
PSP Full
Semester I
Name : ………………………………………………………….
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)
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
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.
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
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)
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]
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.
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
Unit – 1 2
Mailam Engineering College GE3151 - Problem Solving and Python Programming
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.
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.
Unit – 1 3
Mailam Engineering College GE3151 - Problem Solving and Python Programming
Unit – 1 4
Mailam Engineering College GE3151 - Problem Solving and Python Programming
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.
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.
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
Unit – 1 6
Mailam Engineering College GE3151 - Problem Solving and Python Programming
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.
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.
(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.
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.
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
Unit – 1 10
Mailam Engineering College GE3151 - Problem Solving and Python Programming
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
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.
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
Only one flow line should enter into I/O symbols and only one should exit from it.
Only one flow line should enter into decision symbol and one or two may exit
from it. (in
Unit – 1 13
Mailam Engineering College GE3151 - Problem Solving and Python Programming
Sequence Structure
It is a sequence or linear structure because the flow always continues in same
direction every time the structure is executed.
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
PSEUDOCODE
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.
Unit – 1 15
Mailam Engineering College GE3151 - Problem Solving and Python Programming
Example:
Tasks are:
WRITE or OUTPUT
or PUT or PRINT IF,
THEN, END IF
(or)
WHILE(n > 0)
-------------
-------------
END WHILE
Unit – 1 16
Mailam Engineering College GE3151 - Problem Solving and Python Programming
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
(or)
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
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]
Unit – 1 20
Mailam Engineering College GE3151 - Problem Solving and Python Programming
Unit – 1 21
Mailam Engineering College GE3151 - Problem Solving and Python Programming
ILLUSTRATION PROBLEMS
The Tower of Hanoi (also called the Tower of Brahma or Lucas' Tower
Unit – 1 22
Mailam Engineering College GE3151 - Problem Solving and Python Programming
Unit – 1 23
Mailam Engineering College GE3151 - Problem Solving and Python Programming
READ n
SET i=0
WHILE i < n THEN
READ a[i]
CALCULATE i = i + 1
END WHILE
PRINT min
END
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
Unit – 1 25
Mailam Engineering College GE3151 - Problem Solving and Python Programming
Unit – 1 26
Mailam Engineering College GE3151 - Problem Solving and Python Programming
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
CALCULATEa[i+1]=a[i]
CALCULATEn=n+1
END
Unit – 1 27
Mailam Engineering College GE3151 - Problem Solving and Python Programming
Flowchart
Unit – 1 28
Mailam Engineering College GE3151 - Problem Solving and Python Programming
PART A - 2 MARKS
Unit II 29
Mailam Engineering College GE3151 - Problem Solving and Python Programming
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
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)
a=”Guru”
b = 99
print(a+str(b))
Unit II 30
Mailam Engineering College GE3151 - Problem Solving and Python Programming
anInt = 1
aLong = -9999999999999999L
aFloat = 3.1415926535897932384626433832795
aComplex = 1.23 + 4.56J
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)
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
Example:
a+b
a, b are operands
+ is a operator
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
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.
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
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.
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
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
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.
Unit II 34
Mailam Engineering College GE3151 - Problem Solving and Python Programming
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 (AZ or az), 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.
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
(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.).
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
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
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
Unit II 42
Mailam Engineering College GE3151 - Problem Solving and Python Programming
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
Example:
Tuple with string values
>>>T=('sun','mon','tue')
>>>print(T)
('sun', 'mon', 'tue')
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
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
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
== 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”)
or Logical OR (a or b) is true.
Unit II 46
Mailam Engineering College GE3151 - Problem Solving and Python Programming
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
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’)
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
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]
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
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
Unit II 51
Mailam Engineering College GE3151 - Problem Solving and Python Programming
Unit II 52
Mailam Engineering College GE3151 - Problem Solving and Python Programming
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.
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
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)
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
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.
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.
Unit III 55
Mailam Engineering College GE3151 - Problem Solving and Python Programming
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
\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
\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
Output
Jello, world!
Hello, world!
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
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']
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
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
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
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
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…..
Syntax
Flowchart
Example
for letter in 'Python':
print(“Current Letter :”, letter)
print("The End")
Unit III 63
Mailam Engineering College GE3151 - Problem Solving and Python Programming
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
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)
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
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
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
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
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
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:
Unit III 69
Mailam Engineering College GE3151 - Problem Solving and Python Programming
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
Output:
Arun
Basha
David
Zahir
Unit III 70
Mailam Engineering College GE3151 - Problem Solving and Python Programming
RETURN VALUES
Output:
35
15
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
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.
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:”))
Unit III 72
Mailam Engineering College GE3151 - Problem Solving and Python Programming
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
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
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]
>>>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
\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
\M-\C-x Meta-Control-x
\n 0x0a Newline
\s 0x20 Space
\t 0x09 Tab
\x Character x
[] 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
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
%o octal integer
Other supported symbols and functionality are listed in the following table
Symbol Functionality
- left justification
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 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
16) LIST OUT THE STRING FUNCTIONS AND METHODS WITH EXAMPLES.
Python includes the following built-in methods to manipulate strings.
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.
12 islower()Returns true if string has at least 1 cased character and all cased
characters are in lowercase 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.
Unit III 79
Mailam Engineering College GE3151 - Problem Solving and Python Programming
20 max(str) Returns the max alphabetical character from the string str.
21 min(str) Returns the min alphabetical character from the string str.
27 title()Returns "titlecased" version of string, that is, all words begin with uppercase
and the rest are lowercase.
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.
(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'
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’
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
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.
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)
Output:
Enter N:5
The factorial is 120
Unit III 85
Mailam Engineering College GE3151 - Problem Solving and Python Programming
Output
Enter number : 3
Enter exponent : 3
27
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
print(listsum([1,3,5,7,9]))
OUTPUT
25
Unit III 86
Mailam Engineering College GE3151 - Problem Solving and Python Programming
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
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
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
Program:
def isPalindrome(s):
return s == s[::-1]
if ans:
print("Palindrome")
else:
print("Not Palindrome")
Output:
Enter any string: amma
Palindrome
“Successful people do
what failure people are
not willing to do”
Unit III 89
Mailam Engineering College GE3151 - Problem Solving and Python Programming
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
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’]
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()
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.
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
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]
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”
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-[].
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
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
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]
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”]
print(a)
Output:
[12, ‘Raju’, ‘CSE’]
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
Output:
I like rose very much
I like lotus very much
I like jasmine very much
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
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]
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.
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
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.
t=(1, 2, 3)
print(t)
t1=(1,”success’, 9.5)
print(t1)
Output:
()
(1, 2, 3)
(‘Raju’, [10,20,30], (1, 2, 3))
Output:
CSE
18
19.5
Unit – 4 104
Mailam Engineering College GE3151 - Problem Solving and Python Programming
Output:
The original tuple 1 : (1, 3, 5)
The original tuple 2 : (4, 6)
The tuple after concatenation is : (1, 3, 5, 4, 6)
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.
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
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
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’]
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
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
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]
(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:
Unit – 4 113
Mailam Engineering College GE3151 - Problem Solving and Python Programming
20) WRITE A PYTHON PROGRAM TO CREATE A DICTIONARY AND SORT THE CONTEBNT
BASED ON VALUES IN REVERSE ORDER. [AU – Jan 2022]
# initializing dictionary
test_dict = {'silver' : 4, 'gold' : 2, 'diamond' : 5}
print("The original dictionary : " + str(test_dict))
res = OrderedDict(reversed(list(test_dict.items())))
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]}”)
Unit – 4 115
Mailam Engineering College GE3151 - Problem Solving and Python Programming
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.
Mode Description
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.
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
10) Write methods to rename and delete file. [AU – Dec 2019]
Syntax:
os.remove(file_name)
Example:
os.remove("text2.txt")
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
EXCEPTIONS
Unit – 5 118
Mailam Engineering College GE3151 - Problem Solving and Python Programming
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.
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
Unit – 5 119
Mailam Engineering College GE3151 - Problem Solving and Python Programming
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.
Mode Description
rb Opens a file for reading only in binary format. This is the default mode.
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
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
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
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?
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.
Example:
f=open(“hello.text”, “r”)
data = f.readlines()
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
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.
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.
Example
Let us take a file sam1.txt, which we created above.
Output
Unit – 5 125
Mailam Engineering College GE3151 - Problem Solving and Python Programming
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
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
Example
Following is the example to create a directory test in the current directory −
import os
os.mkdir("test")
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")
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
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.
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>
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] ...
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:
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.
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
StopIteration Raised when the next() method of an iterator does not point
to any object.
StandardError Base class for all built-in exceptions except StopIteration and
SystemExit.
ArithmeticError Base class for all errors that occur for numeric calculation.
ZeroDivisionError Raised when division or modulo by zero takes place for all
numeric types.
Unit – 5 132
Mailam Engineering College GE3151 - Problem Solving and Python Programming
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.
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:
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
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.
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
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)
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
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()
f3.write(data1)
f1.close()
f2.close()
f3.close()
copyfile(sourcefile, destinationfile)
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
def main():
try:
age=int(input('Enter your age:'))
if age>18:
print("Eligible to vote")
else:
print("Not eligible to vote")
main()
Output
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
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]
Unit – 5 139
www.EnggTree.com