Python Reckoner
Python Reckoner
Python Reckoner
Ready Reckoner
GE 8151 - PROBLEM SOLVING AND PYTHON PROGRAMMING
By
The
he Department of Computer Science & Engineering
2023-2024
2024
GE8151 PROBLEM SOLVING AND PYTHON PROGRAMMING
UNIT I
COMPUTATIONAL THINKING & PROBLEM SOLVING
Fundamentals of Computers
Computer is an advanced electronic device that takes raw data as an input from the user and
processes it under the control of a set of instructions (called program), produces a result
(output), and saves it for future use.
Computer input is called data and the output obtained after processing it, based on user’s
instructions is called information. Raw facts and figures which can be processed using
arithmetic and logical operations to obtain information are called data.
Characteristics of Computer
To understand why computers are such an important part of our lives, let us look at some of
its characteristics −
Speed − Typically, a computer can carry out 3-4 million instructions per second.
Accuracy − Computers exhibit a very high degree of accuracy. Errors that may occur
are usually due to inaccurate data, wrong instructions or bug in chips – all human
errors.
Reliability − Computers can carry out same type of work repeatedly without throwing
up errors due to tiredness or boredom, which are very common among humans.
Versatility − Computers can carry out a wide range of work from data entry and ticket
booking to complex mathematical calculations and continuous astronomical
observations. If you can input the necessary data with correct instructions, computer
will do the processing.
Storage Capacity − Computers can store a very large amount of data at a fraction of
cost of traditional storage of files. Also, data is safe from normal wear and tear
associated with paper.
Now that we know the characteristics of computers, we can see the advantages that
computers offer−
Computers can do the same task repetitively with same accuracy.
Computers do not get tired or bored.
Computers can take up routine tasks while releasing human resource for more
intelligent functions.
There are five generations of the computer, which can be classified as below:
First Generation (1946 - 1959): During the first generation, computers were based on
electronic valves (Vacuum Tubes). Some popular computers of first-generation are ENIAC,
EDVAC, UNIVAC, etc.
Second Generation (1959 - 1965): During the second generation, computers were based on
Transistors. Some popular computers of second-generation are IBM 1400, IBM 1620, IBM
7000 series, etc.
Third Generation (1965 - 1971): During the third generation, computers were based
on Integrated Circuits (ICs). Some popular computers of the third generation are IBM 360,
IBM 370, PDP, etc.
Fourth Generation (1971 - 1980): During the fourth generation, computers were based
on very large scale integrated (VLSI) circuits. Some popular computers of fourth-
generation are STAR 1000, CRAY-1, CRAY-X-MP, DEC 10, etc.
Fifth Generation (1980 - Present): The fifth generation is still ongoing. The computers are
based on multiple technologies, such as ultra large scale integration (ULSI), artificial
intelligence (AI), and parallel processing hardware. The fifth generation of computers
includes Desktop, Laptop, NoteBook, etc.
Software
Computer software is a group of instructions or programs that instructs the computer system to
work accordingly. There are mainly two types of software:
System Software: System software help establish communication between hardware components
so that the user can interact with the computer. These types of software are necessary for the
computer to operate correctly. They provide an interface to run additional third party programs or
utility tools. Operating systems, drivers, utility software, and firmware are typical examples of the
system software.
Application Software: Application software is designed to help users to perform specific tasks,
such as online surfing, setting the alarm, listening to music, playing videos, photo designing,
editing, etc. This type of software mostly runs in the frontend and allows end-users to work on.
Web browsers, Photoshop software, multimedia software and word processors are the example of
the application software.
Hardware
The physical parts attached to a computer that form a whole computer are called hardware or
hardware components. There can be different types of hardware, depending on the structure.
Some most common hardware are mouse, keyboard, monitor, printer, etc. These are the parts that
can be seen and touched by humans.
Binary Computer
Binary describes a numbering scheme in which there are only two possible
values for each digit -- 0 or 1 -- and is the basis for all binary code used in
computing systems. These systems use this code to understand
operational instructions and user input and to present a relevant output to the
user.
1.PROBLEM SOLVING
Problem solving is the systematic approach to define the problem and creating
number of solutions.
The problem solving process starts with the problem specifications and ends with a
Correct program.
1.2.ALGORITHM
Algorithm is an ordered sequence of finite, well defined, unambiguous
instructions for completing a task. It is an English-like representation of the logic which
is used to solve the problem. It is a step- by-step procedure for solving a task or a
problem.
It is also defined as “any problem whose solution can be expressed in a list of
executable instruction”.
Or
rability - Used to solve single problem and more often algorithms are designed to
handle a range of input data.
2.2.State:
Transition from one process to another process under specified condition with in
a time is called state.
2.3.Control flow:
The process of executing the individual statements in a given order is called control
flow
.
The control can be executed in three ways
1. sequence
2. selection
3. iteration
Sequence:
All the instructions are executed one after another is called sequence execution.
Example:
Add two numbers:
Step 1: Start
Step 2: get a,b
Step 3: calculate c=a+b
Step 4: Display c
Step 5: Stop
Selection:
A selection statement causes the program control to be transferred to a specific
part of the program based upon the condition.
If the conditional test is true, one part of the program will be executed, otherwise
it will execute the other part of the program.
\
Example
Write an algorithm to check whether he is eligible to vote?
Step 1: Start
Step 2: Get age
Step 3: if age >= 18 print “Eligible to vote”
Step 4: else print “Not eligible to vote”
Step 6: Stop
Iteration:
In some programs, certain set of statements are executed again and again based
upon conditional test. i.e. executed more than one time. This type of execution is called
looping or repetition or iteration.
Example
Step 1: Start
Step 2: get n value.
Step 3: initialize i=1
Step 4: if (i<=n) go to step 5 else go to step 7
Step 5: Print i value and increment i value by 1
Step 6: go to step 4
Step 7: Stop
2.4.Functions:
Function is a sub program which consists of block of code(set of instructions)
that performs a particular task.
For complex problems, the problem is been divided into smaller and
simpler tasks during algorithm design.
3.NOTATIONS
3.1.FLOW CHART
4. Only one flow line should enter a decision symbol. However, two or three flow
lines may leave the decision symbol.
Advantages/Benefits of flowchart:
1. Communication: - Flowcharts are better way of communicating the logic of a
system to all concerned.
2. Effective analysis: - With the help of flowchart, problem can be analyzed in
more effective way.
3. Proper documentation: - Program flowcharts serve as a good
program documentation, which is needed for various purposes.
4. Efficient Coding: - The flowcharts act as a guide or blueprint during
the systems analysis and program development phase.
5. Proper Debugging: - The flowchart helps in debugging process.
6. Efficient Program Maintenance: - The maintenance of operating
program
becomes easy with the help of flowchart. It helps the programmer
to put efforts more efficiently on that part.
Disadvantages/Limitation of using flowchart
1. Complex logic: - Sometimes, the program logic is quite
complicated. In that case, flowchart becomes complex and clumsy.
2. Alterations and Modifications: - If alterations are required
the flowchart may require re-drawing completely.
3. Reproduction: - As the flowchart symbols cannot be typed,
reproduction of flowchart becomes a problem.
4. Cost: For large application the time and cost of flowchart drawing
becomes costly.
GUIDELINES FOR DRAWING A FLOWCHART
Flowcharts are usually drawn using some standard symbols; however, some special symbols
can also be developed when required. Some standard symbols, which are frequently required for
flowcharting many computer programs.
Terminator:
An oval flow chart shape indicates the start or end of the process, usually containing the word
“Start” or “End”.
Terminator
Process:
A rectangular flow chart shape indicates a normal/generic process flow step.
For example, “Add 1 to X”, “M = M*F” or similar.
Process
Decision:
A diamond flow chart shape indicates a branch in the process flow. This symbol is
used when a decision needs to be made, commonly a Yes/No question or True/False test.
Decision
No
Yes
Connector:
A small, labelled, circular flow chart shape used to indicate a jump in the process flow.
Connectors are generally used in complex or multi-sheet diagrams.
Data:
A parallelogram that indicates data input or output (I/O) for a process. Examples: Get
X from the user, Display X.
Delay:
Used to indicate a delay or wait in the process for input from some other process.
Arrow:
Used to show the flow of control in a process. An arrow coming from one symbol and
ending at another symbol represents that control passes to the symbol the arrow points to.
Example Flowchart
Problem 1: Draw the flowchart to find the largest number between A and B
Problem 4: Flowchart for an algorithm which gets two numbers and prints sum of their value
.
Problem5: Flowchart for the problem of printing even numbers between 0 and 99.
3.2.PSEUDO CODE:
“Pseudo” means initiation or false.
“Code” means the set of statements or instructions written in a programming
language. Pseudocode is also called as “Program Design Language [PDL]”.
Pseudo code consists of short, readable and formally styled English languages
used for explaining an algorithm.
It does not include details like variable declaration, subroutines.
It is easier to understand for the programmer or non programmer to understand
the general working of the program, because it is not based on any programming
language.
It gives us the sketch of the program before actual coding.
It is not a machine readable
Pseudo code can’t be compiled and executed.
There is no standard syntax for pseudo code.
Example:
Addition of two numbers:
BEGIN
GET a,b
ADD c=a+b
PRINT c
END
Syntax for if else: Example: Greates of two numbers
IF (condition)THEN BEGIN
Statement READ a,b
... IF (a>b) THEN
ELSE DISPLAY a is greater
Statement ELSE
... DISPLAY b is greater
ENDIF END IF
END
Syntax for For: Example: Print n natural numbers
FOR( start-value to end-value) DO BEGIN
Statement GET n
... INITIALIZE i=1
ENDFOR FOR (i<=n) DO
PRINT i
i=i+1
ENDFOR
END
Syntax for While: Example: Print n natural numbers
WHILE (condition) DO BEGIN
Statement GET n
... INITIALIZE i=1
ENDWHILE WHILE(i<=n) DO
PRINT i
i=i+1
ENDWHILE
END
Advantages:
Pseudo is independent of any language; it can be used by most programmers.
It is easy to translate pseudo code into a programming language.
It can be easily modified as compared to flowchart.
Converting a pseudo code to programming language is very easy as compared
with converting a flowchart to programming language.
It does not provide visual representation of the program’s logic.
There are no accepted standards for writing pseudo codes.
It cannot be compiled nor executed.
For a beginner, It is more difficult to follow the logic or write pseudo code as
compared to flowchart.
Disadvantage
It is not visual.
We do not get a picture of the design.
There is no standardized style or format.
For a beginner, it is more difficult to follow the logic or write pseudocode as
compared to flowchart.
Algorithm Flowchart Pseudo code
An algorithm is a sequence It is a graphical It is a language
of instructions used to representation of algorithm representation of
solve a problem algorithm.
User needs knowledge to not need knowledge of Not need knowledge of
write algorithm. program to draw or program language to
understand flowchart understand or write a
pseudo code.
2. simplicity.
An algorithm should be precisely defined and investigated with mathematical
expressions.
Simpler algorithms are easier to understand and easier to program.
Simple algorithms usually contain fewer bugs.
Coding an Algorithm
Most algorithms are destined to be ultimately implemented as computer
programs. Programming an algorithm presents both a peril and an opportunity.
A working program provides an additional opportunity in allowing an empirical
analysis of the underlying algorithm. Such an analysis is based on timing the
program on several inputs and then analysing the results obtained.
Main function:
Step1: Start
Step2: Get n
Step3: call factorial(n)
Step4: print fact
Step5: Stop
Main function:
BEGIN
GET n
CALL factorial(n)
PRINT fact
BIN
IF(n==1) THEN
fact=1
\RETURN fact
ELSE
RETURN fact=n*factorial(n-1)
More examples:
Write an algorithm to find area of a rectangle
BEGIN
READ num
IF (num>0) THEN
DISPLAY num is positive
ELSE
DISPLAY num is negative
END IF
END
To check odd or even number
Step 1: Start
Step 2: get num
Step 3: check if(num%2==0) print num is even
Step 4: else num is odd
Step 5: Stop
BEGIN
READ num
IF (num%2==0) THEN
DISPLAY num is even
ELSE
DISPLAY num is odd
END IF
END
Step 1: Start
Step 2: get n value.
Step 3: initialize i=1
Step 4: if (i<=n) go to step 5 else go to step 8
Step 5: Print i value
step 6 : increment i value by 1
Step 7: go to step 4
Step 8: Stop
BEGIN
GET n
INITIALIZE i=1
WHILE(i<=n) DO
PRINT i
i=i+1
ENDWHILE
END
Write an algorithm to print n odd numbers
Step 1: start
step 2: get n value
step 3: set initial value i=1
step 4: check if(i<=n) goto step 5 else goto step 8
step 5: print i value
step 6: increment i value by 2
step 7: goto step 4
step 8: stop
BEGIN
GET n
INITIALIZE i=1
WHILE(i<=n) DO
PRINT i
i=i+2
ENDWHILE
END
Write an algorithm to print n even numbers
Step 1: start
step 2: get n value
step 3: set initial value i=2
step 4: check if(i<=n) goto step 5 else goto step8
step 5: print i value
step 6: increment i value by 2
step 7: goto step 4
step 8: stop
BEGIN
GET n
INITIALIZE i=2
WHILE(i<=n) DO
PRINT i
i=i+2
ENDWHILE
END
Write an algorithm to print squares of a number
Step 1: start
step 2: get n value
step 3: set initial value i=1
step 4: check i value if(i<=n) goto step 5 else goto step8
step 5: print i*i value
step 6: increment i value by 1
step 7: goto step 4
step 8: stop
BEGIN
GET n
INITIALIZE i=1
WHILE(i<=n) DO
PRINT i*i
i=i+2
ENDWHILE
END
Write an algorithm to print to print cubes of a number
Step 1: start
step 2: get n value
step 3: set initial value i=1
step 4: check i value if(i<=n) goto step 5 else goto step8
step 5: print i*i *i value
step 6: increment i value by 1
step 7: goto step 4
step 8: stop
BEGIN
GET n
INITIALIZE i=1
WHILE(i<=n) DO
PRINT i*i*i
i=i+2
ENDWHILE
END
Write an algorithm to find sum of a given number
Step 1: start
step 2: get n value
step 3: set initial value i=1, sum=0
Step 4: check i value if(i<=n) goto step 5 else goto step8
step 5: calculate sum=sum+i
step 6: increment i value by 1
step 7: goto step 4
step 8: print sum value
step 9: stop
BEGIN
GET n
INITIALIZE i=1,sum=0
WHILE(i<=n) DO
sum=sum+i
i=i+1
ENDWHILE
PRINT sum
END
29
Write an algorithm to find factorial of a given number
Step 1: start
step 2: get n value
step 3: set initial value i=1, fact=1
Step 4: check i value if(i<=n) goto step 5 else goto step8
step 5: calculate fact=fact*i
step 6: increment i value by 1
step 7: goto step 4
step 8: print fact value
step 9: stop
BEGIN
GET n
INITIALIZE i=1,fact=1
WHILE(i<=n) DO
fact=fact*i
i=i+1
ENDWHILE
PRINT fact
END
ILLUSTRATIVE PROBLEM
1.Guess an integer in a range
Algorithm:
Step1: Start
Step 2: Declare hidden, guess,range=1 to 100
Step 3: Compute hidden= Choose a random value in a range
Step 4: Read guess
Step 5: If guess=hidden, then Print
Guess is hit
Else
Print Guess not hit
Print hidden
Step 6: Stop
Pseudocode:
BEGIN
COMPUTE hidden=random value in a range
READ guess
IF guess=hidden, then PRINT
Guess is hit
ELSE
PRINT Guess not hit
PRINT hidden
END IF-ELSE
END
Flowchart:
2.Find minimum in a list
Algorithm: Step 1:
Start Step 2: Read n
Step 3:Initialize i=0
Step 4: If i<n, then goto step 4.1, 4.2 else goto step 5
Step4.1: Read a[i]
Step 4.2: i=i+1 goto step 4
Step 5: Compute min=a[0]
Step 6: Initialize i=1
Step 7: If i<n, then go to step 8 else goto step 10
Step 8: If a[i]<min, then goto step 8.1,8.2 else goto 8.2
Step 8.1: min=a[i]
Step 8.2: i=i+1 goto 7
Step 9: Print min
Step 10: Stop
Pseudocode:
BEGIN
READ n
FOR i=0 to n, then READ
a[i] INCREMENT
i
END FOR COMPUTE
min=a[0] FOR i=1 to n,
then
IF a[i]<min, then CALCULATE
min=a[i] INCREMENT i
ELSE
INCREMENT i
END IF-ELSE
END FOR
PRINT min
END
Flowchart:
3.Insert a card in a list of sorted cards
Algorithm: Step 1:
Start Step 2: Read n
Step 3:Initialize i=0
Step 4: If i<n, then goto step 4.1, 4.2 else goto step 5
Step4.1: Read a[i]
Step 4.2: i=i+1 goto step 4
Step 5: Read item
Step 6: Calculate i=n-1
Step 7: If i>=0 and item<a[i], then go to step 7.1, 7.2 else goto step 8
Step 7.1: a[i+1]=a[i]
Step 7.2: i=i-1 goto step 7
Step 8: Compute a[i+1]=item
Step 9: Compute n=n+1
Step 10: If i<n, then goto step 10.1, 10.2 else goto step 11
Step10.1: Print a[i]
Step10.2: i=i+1 goto step 10
Step 11: Stop
Pseudocode:
BEGIN
READ n
FOR i=0 to n, then READ
a[i] INCREMENT
i
END FOR
READ item
FOR i=n-1 to 0 and item<a[i], then
CALCULATE a[i+1]=a[i]
DECREMENT i
END FOR COMPUTE
a[i+1]=a[i] COMPUTE
n=n+1 FOR i=0 to n, then
PRINT a[i]
INCREMENT i
END FOR
END
Flowchart:
4. Tower of Hanoi
Algorithm:
Step 1: Start
Step 2: Read n
Step 3: Calculate move=pow(2,n)-1
Step 4: Function call T(n,Beg,Aux,End) recursively until n=0
Step 4.1: If n=0, then goto step 5 else goto step 4.2
Step 4.2: T(n-1,Beg,End,Aux)
T(1,Beg,Aux,End) , Move disk from source to destination
T(n-1,Aux,Beg,End)
Step 5: Stop
Pseudcode:
BEGIN
READ n
CALCULATE move=pow(2,n)-1
FUNCTION T(n,Beg,Aux,End) Recursively until n=0
PROCEDURE IF
n=0 then,
No disk to move
Else
T(n-1,Beg,End,Aux)
T(1,Beg,Aux,End), move disk from source to destination
T(n-1,Aux,Beg,End)
END PROCEDURE
END
Flowchart:
Procedure to solve Tower of Hanoi
The goal of the puzzle is to move all the disks from leftmost peg to rightmost peg.
1. INTRODUCTION TO PYTHON:
Python is a general-purpose interpreted, interactive, object-oriented, and high-
level programming language.
It was created by Guido van Rossum during 1985- 1990.
Python got its name from “Monty Python’s flying circus”. Python was released in the
year 2000.
❖ Python is interpreted: Python is processed at runtime by the interpreter. You
do not need to compile your program before executing it.
❖ Python is Interactive: You can actually sit at a Python prompt and interact with
the interpreter directly to write your programs.
❖ Python is Object-Oriented: Python supports Object-Oriented style or
technique of programming that encapsulates code within objects.
❖ Python is a Beginner's Language: Python is a great language for the beginner-
level programmers and supports the development of a wide range of applications.
Compiler Interpreter
Interpreter Takes Single instruction as
Compiler Takes Entire program as input
Input
No Intermediate Object Code
Intermediate Object Code is Generated
is Generated
Conditional Control Statements are Conditional Control Statements are
Executes faster Executes slower
Memory Requirement is More(Since Object Memory Requirement is Less
Code is Generated)
Every time higher level program is
Program need not be compiled every time
converted into lower level program
Errors are displayed after entire Errors are displayed for every
program is checked instruction interpreted (if any)
Example : C Compiler Example : PYTHON
Script mode:
❖ In script mode, we type python program in a file and then use interpreter to
execute the content of the file.
❖ Scripts can be saved to disk for future use. Python scripts have the extension
.py, meaning that the filename ends with .py
❖ Save the code with filename.py and run the interpreter in script mode to execute
the script.
Value:
Value can be any letter ,number or string.
Eg, Values are 2, 42.0, and 'Hello, World!'. (These values belong to different
datatypes.)
Data type:
Every value in Python has a data type.
It is a set of values, and the allowable operations on those values.
Python has four standard data types:
2.1Numbers:
❖ Number data type stores Numerical Values.
❖ This data type is immutable [i.e. values/items cannot be changed].
❖ Python supports integers, floating point numbers and complex numbers.
They are defined as,
2.2 Sequence:
❖ A sequence is an ordered collection of items, indexed by positive integers.
❖ It is a combination of mutable (value can be changed) and immutable (values
cannot be changed) data types.
❖ There are three types of sequence data type available in Python, they are
1. Strings
2. Lists
3. Tuples
i. Indexing
ii. Slicing
iii. Concatenation
iv. Repetitions
v. Member ship
Creating a string >>> s="good morning" Creating the list with elements of
different data types.
Indexing >>> print(s[2]) ❖ Accessing the item in the
o position 0
>>> print(s[6]) ❖ Accessing the item in the
O position 2
Slicing( ending >>> print(s[2:]) - Displaying items from 2nd till
position -1) od morning last.
Slice operator is >>> print(s[:4]) - Displaying items from 1st
used to extract Good position till 3rd .
part of a data
type
Concatenation >>>print(s+"friends") -Adding and printing the
good morningfriends characters of two strings.
2.2.2 Lists
❖ List is an ordered sequence of items. Values in the list are called elements / items.
❖ It can be written as a list of comma-separated items (values) between square
brackets[ ].
❖ Items in the lists can be of different data types.
Operations on list:
Indexing
Slicing
Concatenation
Repetitions
Updation, Insertion, Deletion
2.2.4Tuple:
❖ A tuple is same as list, except that the set of elements is enclosed in parentheses
instead of square brackets.
❖ A tuple is an immutable list. i.e. once a tuple has been created, you can't add
elements to a tuple or remove elements from the tuple.
❖ Benefit of Tuple:
❖ Tuples are faster than lists.
❖ If the user wants to protect the data from accidental changes, tuple can be used.
❖ Tuples can be used as keys in dictionaries, while lists can't.
Basic Operations:
Creating a tuple >>>t=("python", 7.79, 101, Creating the tuple with elements
"hello”) of different data types.
Indexing >>>print(t[0]) ❖ Accessing the item in the
python position 0
>>> t[2] ❖ Accessing the item in the
101
position 2
Slicing( ending >>>print(t[1:3]) ❖ Displaying items from 1st
position -1) (7.79, 101) till 2nd.
Altering the tuple data type leads to error. Following error occurs when user tries to
do.
>>> t[0]="a"
Trace back (most recent call last):
File "<stdin>", line 1, in <module>
Type Error: 'tuple' object does not support item
assignment
2.3 Mapping
-This data type is unordered and mutable.
-Dictionaries fall under Mappings.
2.3.1Dictionaries:
❖ Lists are ordered sets of objects, whereas dictionaries are unordered sets.
❖ Dictionary is created by using curly brackets. i,e. {}
❖ Dictionaries are accessed via keys and not via their position.
❖ A dictionary is an associative array (also known as hashes). Any key of the
dictionary is associated (or mapped) to a value.
❖ The values of a dictionary can be any Python data type. So dictionaries are
unordered key-value-pairs(The association of a key and a value is called a key-
value pair )
Dictionaries don't support the sequence operation of the sequence data types like
strings, tuples and lists.
If you try to access a key which doesn't exist, you will get an error message:
>>> words = {"house" : "Haus", "cat":"Katze"}
>>> words["car"]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
KeyError: 'car'
3.1VARIABLES:
❖ A variable allows us to store a value by assigning it to a name, which can be used
later.
❖ Named memory locations to store values.
❖ Programmers generally choose names for their variables that are meaningful.
❖ It can be of any length. No space is allowed.
❖ We don't need to declare a variable before using it. In Python, we simply assign a
value to a variable and it will exist.
>>> a=b=c=100
Assigning multiple values to multiple variables:
>>> a,b,c=2,4,"ram"
3.2KEYWORDS:
❖ Keywords are the reserved words in Python.
We cannot use a keyword as variable name, function name or any
other identifier.
❖ They are used to define the syntax and structure of the Python language.
❖ Keywords are case sensitive.
3.3IDENTIFIERS:
Identifier is the name given to entities like class, functions, variables etc. in
Python
Identifiers can be a combination of letters in lowercase (a to z) or uppercase
(A to Z) or digits (0 to 9) or an underscore (_). .
❖ all are valid example.
❖ An identifier cannot start with a digit.
❖ Keywords cannot be used as identifiers.
❖ Cannot use special symbols like !, @, #, $, % etc. in our identifier.
❖ Identifier can be of any length.
Example:
Names like myClass, var_1, and this_is_a_long_variable
3.6 COMMENTS:
❖ A hash sign (#) is the beginning of a comment.
❖ Anything written after # in a line is ignored by interpreter.
Eg:percentage = (minute * 100) / 60 # calculating percentage of an hour
❖ Python does not have multiple-line commenting feature. You have to
comment each line individually as follows :
Example:
# This is a comment.
# This is a comment, too.
# I said that already.
3.7 DOCSTRING:
❖ Docstring is short for documentation string.
❖ It is a string that occurs as the first statement in a module, function, class, or
method definition. We must write what a function/class does in the docstring.
❖ Triple quotes are used while writing docstrings.
Syntax:
functionname__doc.__
Example:
def double(num):
"""Function to double the value"""
return 2*num
>>> print(double.__doc__)
Function to double the value
Example:
-It is useful to swap the values of two variables. With conventional assignment
statements, we have to use a temporary variable. For example, to swap a and b:
(a, b) = (b, a)
-In tuple unpacking, the values in a tuple on the right are ‘unpacked’ into the
variables/names on the right:
4.OPERATORS:
❖ Operators are the constructs which can manipulate the value of operands.
❖ Consider the expression 4 + 5 = 9. Here, 4 and 5 are called operands and + is
called operator
❖ Types of Operators:
-Python language supports the following types of operators
• Arithmetic Operators
• Comparison (Relational) Operators
• Assignment Operators
• Logical Operators
• Bitwise Operators
• Membership Operators
• Identity Operators
4.1 Arithmetic operators:
They are used to perform mathematical operations like addition, subtraction,
multiplication etc. Assume, a=10 and b=5
Examples Output:
a=10 a+b= 15
b=5 a-b= 5
print("a+b=",a+b) a*b= 50
print("a-b=",a-b) a/b= 2.0
print("a*b=",a*b) a%b= 0
print("a/b=",a/b) a//b= 2
print("a%b=",a%b) a**b= 100000
print("a//b=",a//b)
print("a**b=",a**b)
> If the value of left operand is greater than the value of right (a > b) is
operand, then condition becomes true. not true.
< If the value of left operand is less than the value of right (a < b) is
operand, then condition becomes true. true.
>= If the value of left operand is greater than or equal to the (a >= b) is
value of right operand, then condition becomes true. not true.
<= If the value of left operand is less than or equal to the value (a <= b) is
of right operand, then condition becomes true. true.
Example
a=10 Output:
b=5 a>b=> True
print("a>b=>",a>b) a>b=> False
print("a>b=>",a<b) a==b=> False
print("a==b=>",a==b) a!=b=> True
print("a!=b=>",a!=b) a>=b=> False
print("a>=b=>",a<=b) a>=b=> True
print("a>=b=>",a>=b)
+= Add AND It adds right operand to the left operand and assign c += a is
the result to left operand equivalent
to c = c + a
Example Output
a = 21 Line 1 - Value of c is 31
b = 10 Line 2 - Value of c is 52
c=0 Line 3 - Value of c is 1092
c=a+b Line 4 - Value of c is 52.0
print("Line 1 - Value of c is ", c) Line 5 - Value of c is 2
c += a Line 6 - Value of c is 2097152
print("Line 2 - Value of c is ", c) Line 7 - Value of c is 99864
c *= a
print("Line 3 - Value of c is ", c)
c /= a
print("Line 4 - Value of c is ", c)
c = 2c%= a
print("Line 5 - Value of c is ", c)
c**= a
print("Line 6 - Value of c is ", c)
c //= a
print("Line 7 - Value of c is ", c)
4.4 Logical Operators:
-Logical operators are the and, or, not operators.
Example Output
a = True x and y is False
b = False x or y is True
print('a and b is',a and b) not x is False
print('a or b is',a or b)
print('not a is',not a)
Example Output
a = 60 # 60 = 0011 1100 Line 1 - Value of c is 12
b = 13 # 13 = 0000 1101 Line 2 - Value of c is 61
c=0 Line 3 - Value of c is 49
c = a & b; # 12 = 0000 1100 Line 4 - Value of c is -61
print "Line 1 - Value of c is ", c Line 5 - Value of c is 240
c = a | b; # 61 = 0011 1101 Line 6 - Value of c is 15
print "Line 2 - Value of c is ", c
c = a ^ b; # 49 = 0011 0001
print "Line 3 - Value of c is ", c
c = ~a; # -61 = 1100 0011
print "Line 4 - Value of c is ", c
c = a << 2; # 240 = 1111 0000
print "Line 5 - Value of c is ", c
c = a >> 2; # 15 = 0000 1111
print "Line 6 - Value of c is ", c
Example:
x=[5,3,6,4,1]
>>> 5 in x
True
>>> 5 not in x
False
Example
x=5 Output
y=5 False
x2 = 'Hello' True
y2 = 'Hello'
print(x1 is not y1)
print(x2 is y2)
5.OPERATOR PRECEDENCE:
When an expression contains more than one operator, the order of
evaluation depends on the order of operations.
Operator Description
a=2,b=12,c=1 a=2*3+4%5-3//2+6
d=a<b>c a=2,b=12,c=1 a=6+4-1+6
d=2<12>1 d=a<b>c-1 a=10-1+6
d=1>1 d=2<12>1-1 a=15
d=0 d=2<12>0
d=1>0
d=1
6.1 FUNCTIONS:
➢ Function is a sub program which consists of set of instructions used to
perform a specific task. A large program is divided into basic building
blocks called function.
Need For Function:
❖ When the program is too complex and large they are divided into parts. Each part
is separately coded and combined into single program. Each subprogram is called
as function.
❖ Debugging, Testing and maintenance becomes easy when the program is divided
into subprograms.
❖ Functions are used to avoid rewriting same code again and again in a program.
❖ Function provides code re-usability
❖ The length of the program is reduced.
❖ The order in which statements are executed is called the flow of execution
❖ Execution always begins at the first statement of the program.
❖ Statements are executed one at a time, in order, from top to bottom.
❖ Function definitions do not alter the flow of execution of the program, but
remember that statements inside the function are not executed until the function
is called CONTROL FLOW STATEMENTS.
❖ Function calls are like a bypass in the flow of execution. Instead of going to the
next statement, the flow jumps to the first line of the called function, executes all
the statements there, and then comes back to pick up where it left off.
Note: When you read a program, don’t read from top to bottom. Instead, follow the
flow of execution. This means that you will read the def statements as you are scanning
from top to bottom, but you should skip the statements of the function definition until
you reach a point where that function is called.
OUTPUT: OUTPUT:
enter a 5 enter a 5
enter b 10 enter b 10
15 15
6.6 Parameters And Arguments:
Parameters:
• Parameters are the value(s) provided in the parenthesis when we write function
header.
• These are the values required by function to work.
• If there is more than one value required, all of them will be listed in parameter
list separated by comma.
• Example: def my_add(a,b):
Example:
def my_add(a,b):
c=a+b
return c
x=5
y=4
print(my_add(x,y))
Output:
9
6.8 ARGUMENTS TYPES:
1. Required Arguments
2. Keyword Arguments
3. Default Arguments
4. Variable length Arguments
❖ Required Arguments: The number of arguments in the function call should
match exactly with the function definition.
def my_details( name, age ):
print("Name: ", name)
print("Age ", age)
return
my_details("george",56)
Output:
Name: george
Age 56
❖ Keyword Arguments:
Python interpreter is able to use the keywords provided to match the values
with parameters even though if they are arranged in out of order.
❖ Default Arguments:
Assumes a default value if a value is not provided in the function call for that argument.
def my_details( name, age=40 ):
print("Name: ", name)
print("Age ", age)
return
my_details(name="george")
Output:
Name: george
Age 40
6.9 MODULES:
➢ A module is a file containing Python definitions ,functions, statements and
instructions.
➢ Standard library of Python is extended as modules.
➢ To use these modules in a program, programmer needs to import the
module.
➢ Once we import a module, we can reference or use to any of its functions or
variables in our code.
o There is large number of standard modules also available in python.
o Standard modules can be imported the same way as we import our user-
defined modules.
o Every module contains many function.
o To access one of the function , you have to specify the name of the module and
the name of the function separated by dot . This format is called dot
notation.
Syntax:
import module_name
module_name.function_name(variable)
Importing Builtin Module: Importing User Defined Module:
import math import cal
x=math.sqrt(25) x=cal.add(5,4)
print(x) print(x)
ILLUSTRATIVE PROGRAMS
Program for SWAPPING(Exchanging )of Output
values
a = int(input("Enter a value ")) Enter a value 5
b = int(input("Enter b value ")) Enter b value 8
c=a a=8
a=b b=5
b=c
print("a=",a,"b=",b,)
Part A:
1. What is interpreter?
2. What are the two modes of python?
3. List the features of python.
4. List the applications of python
5. List the difference between interactive and script mode
6. What is value in python?
7. What is identifier? and list the rules to name identifier.
8. What is keyword?
9. How to get data types in compile time and runtime?
10. What is indexing and types of indexing?
11. List out the operations on strings.
12. Explain slicing?
13. Explain below operations with the
example (i)Concatenation (ii)Repetition
14. Give the difference between list and tuple
15. Differentiate Membership and Identity operators.
16. Compose the importance of indentation in python.
17. Evaluate the expression and find the
result (a+b)*c/d
a+b*c/d
18. Write a python program to print ‘n’ numbers.
19. Define function and its uses
20. Give the various data types in Python
21. Assess a program to assign and access variables.
22. Select and assign how an input operation was done in python.
23. Discover the difference between logical and bitwise operator.
24. Give the reserved words in Python.
25. Give the operator precedence in python.
26. Define the scope and lifetime of a variable in python.
27. Point out the uses of default arguments in python
28. Generalize the uses of python module.
29. Demonstrate how a function calls another function. Justify your answer.
30. List the syntax for function call with and without arguments.
31. Define recursive function.
32. What are the two parts of function definition? give the syntax.
33. Point out the difference between recursive and iterative technique.
34. Give the syntax for variable length arguments.
Part B
1. Explain in detail about various data types in Python with an example?
2. Explain the different types of operators in python with an example.
3. Discuss the need and importance of function in python.
4. Explain in details about function prototypes in python.
5. Discuss about the various type of arguments in python.
6. Explain the flow of execution in user defined function with example.
7. Illustrate a program to display different data types using variables and literal constants.
8. Show how an input and output function is performed in python with an example.
9. Explain in detail about the various operators in python with suitable examples.
10. Discuss the difference between tuples and list
11. Discuss the various operation that can be performed on a tuple and Lists
(minimum 5)with an example program
12. What is membership and identity operators.
13. Write a program to perform addition, subtraction, multiplication, integer division,
floor division and modulo division on two integer and float.
14. Write a program to convert degree Fahrenheit to Celsius
15. Discuss the need and importance of function in python.
16. Illustrate a program to exchange the value of two variables with temporary variables
17. Briefly discuss in detail about function prototyping in python. With suitable
example program
18. Analyze the difference between local and global variables.
19. Explain with an example program to circulate the values of n variables
20. Analyze with a program to find out the distance between two points using python.
21. Do the Case study and perform the following operation in tuples i) Maxima minima
iii)sum of two tuples iv) duplicate a tuple v)slicing operator vi) obtaining a list from a
tuple vii) Compare two tuples viii)printing two tuples of different data types
22. Write a program to find out the square root of two numbers.
Basic python programs:
31
Find greatest of three numbers output
a=eval(input(“enter the value of a”)) enter the value of a 9
b=eval(input(“enter the value of b”)) enter the value of a 1
c=eval(input(“enter the value of c”)) enter the value of a 8
if(a>b): the greatest no is 9
if(a>c):
print(“the greatest no is”,a)
else:
print(“the greatest no is”,c)
else:
if(b>c):
print(“the greatest no is”,b)
else:
print(“the greatest no is”,c)
Programs on for loop
Print n natural numbers Output
print(i)
Print n odd numbers Output
for i in range(1,10,2):
13579
print(i)
for i in range(1,5,1): 1 4 9 16
print(i*i)
for i in range(1,5,1): 1 8 27 64
print(i*i*i)
32
Print n natural numbers Output
i=1 1
while(i<=5): 2
print(i) 3
i=i+1 4
5
Print n odd numbers Output
i=2 2
while(i<=10): 4
print(i) 6
i=i+2 8
10
Print n even numbers Output
i=1 1
while(i<=10): 3
print(i) 5
i=i+2 7
9
Print n squares of numbers Output
i=1 1
while(i<=5): 4
print(i*i) 9
i=i+1 16
25
33
factorial of n numbers/product of n numbers Output
i=1 3628800
product=1
while(i<=10):
product=product*i
i=i+1
print(product)
34
check the no divisible by 5 or not Output
def div(): enter n value10
n=eval(input("enter n value")) the number is divisible by
if(n%5==0): 5
print("the number is divisible by 5")
else:
print("the number not divisible by 5")
div()
35
program for basic calculator Output
def add(): enter a value 10
a=eval(input("enter a value")) enter b value 10
b=eval(input("enter b value")) the sum is 20
c=a+b enter a value 10
print("the sum is",c) enter b value 10
def sub(): the diff is 0
a=eval(input("enter a value")) enter a value 10
b=eval(input("enter b value")) enter b value 10
c=a-b the mul is 100
print("the diff is",c) enter a value 10
def mul(): enter b value 10
a=eval(input("enter a value")) the div is 1
b=eval(input("enter b value"))
c=a*b
print("the mul is",c)
def div():
a=eval(input("enter a value"))
b=eval(input("enter b value"))
c=a/b
print("the div is",c)
add()
sub()
mul()
div()
UNIT III
= CONTROL FLOW, FUNCTIONS
Conditionals: Boolean values and operators, conditional (if), alternative (if-else),
chained conditional (if-elif-else); Iteration: state, while, for, break, continue, pass;
Fruitful functions: return values, parameters, scope: local and global, composition,
recursion; Strings: string slices, immutability, string functions and methods,string
module; Lists as arrays. Illustrative programs: square root, gcd, exponentiation,
sum the array of numbers, linear search, binary search.
BOOLEAN VALUES:
Boolean:
Boolean data type have two values. They are 0 and 1.
0 represents False
1 represents True
True and False are keyword.
Example:
>>> 3==5
False
>>> 6==6
True
>>> True+True
2
>>> False+True
1
>>> False*True
0
OPERATORS:
Operators are the constructs which can manipulate the
value of operands.
if… else
Chained
if…elif…else
Nested if….else
Inline if
Conditional (if):
Conditional (if) is used to test a condition, if the condition is true the statements
inside if will be executed.
syntax:
Flowchart:
Example:
1. Program to provide flat rs 500, if the purchase amount is greater than 2000.
2. Program to provide bonus mark if the category is sports.
Program to provide flat rs 500, if the purchase amount output
is greater than 2000.
purchase=eval(input(“enter your purchase amount”)) enter your purchase
if(purchase>=2000): amount
purchase=purchase-500 2500
print(“amount to pay”,purchase) amount to pay
2000
Program to provide bonus mark if the category is output
sports
m=eval(input(“enter ur mark out of 100”)) enter ur mark out of 100
c=input(“enter ur categery G/S”) 85
if(c==”S”): enter ur categery G/S
m=m+5 S
print(“mark is”,m) mark is 90
Flowchart:
Examples:
1. odd or even number
2. positive or negative number
3. leap year or not
4. greatest of two numbers
5. eligibility for voting
Odd or even number Output
n=eval(input("enter a number")) enter a number4
if(n%2==0): even number
print("even number")
else:
print("odd number")
positive or negative number Output
n=eval(input("enter a number")) enter a number8
if(n>=0): positive number
print("positive number")
else:
print("negative number")
leap year or not Output
y=eval(input("enter a yaer")) enter a year2000
if(y%4==0): leap year
print("leap year")
else:
print("not leap year")
The if block can have only one else block. But it can have multiple elif blocks.
The way to express a computation like that is a chained conditional.
syntax:
Flowchart:
Example:
1. student mark system
2. traffic light system
3. compare two numbers
4. roots of quadratic equation
Syntax:
Flowchart:
Example:
1. greatest of three numbers
2. positive negative or zero
greatest of three numbers output
a=eval(input(“enter the value of a”)) enter the value of a 9
b=eval(input(“enter the value of b”)) enter the value of a 1
c=eval(input(“enter the value of c”)) enter the value of a 8
if(a>b): the greatest no is 9
if(a>c):
print(“the greatest no is”,a)
else:
else:
if(b>c):
print(“the greatest no is”,b)
else:
print(“the greatest no is”,c)
Inline if:
An inline if statement is a simpler form of if statement and is more convenient ,if we
need to perform simple task.
Syntax:
Flowchart:
Examples:
1. program to find sum of n numbers:
2. program to find factorial of a number
3. program to find sum of digits of a number:
4. Program to Reverse the given number:
5. Program to find number is Armstrong number or not
6. Program to check the number is palindrome or not
Sum of n numbers: output
n=eval(input("enter n")) enter n
i=1 10
sum=0 55
while(i<=n):
sum=sum+i
i=i+1
print(sum)
For loop:
for in range:
We can generate a sequence of numbers using range() function.
range(10) will generate numbers from 0 to 9 (10 numbers).
In range function have to define the start, stop and step size
as range(start,stop,step size). step size defaults to 1 if not provided.
syntax
Flowchart:
For in sequence
The for loop in Python is used to iterate over a sequence (list, tuple, string) .
Iterating over a sequence is called traversal. Loop continues until we reach
the last element in the sequence.
The body of for loop is separated from the rest of the code using indentation .
2
2. For loop in list for i in [2,3,5,6,9]: 3
print(i) 5
6
9
for i in (2,3,1): 2
3. For loop in tuple print(i) 3
1
Examples:
1. print numbers divisible by 5 not by 10:
2. Program to print fibonacci series.
3. Program to find factors of a given number
4. check the given number is perfect number or not
5. check the no is prime or not
6. Print first n prime numbers
7. Program to print prime numbers in range
Flowchart
example Output
for i in "welcome": w
if(i=="c"): e
break l
print(i)
CONTINUE
It terminates the current iteration and transfer the control to the next iteration in
the loop.
Syntax: Continue
Flowchart
Example: Output
for i in "welcome": w
if(i=="c"): e
continue l
print(i) o
m
e
PASS
Itexecute.isusedwhen a statement is required syntactically but you don’t want
any code to
It is a null statement, nothing happens when it is executed.
Syntax:
pass
break
Example Output
for i in “welcome”: w
if (i == “c”): e
pass l
print(i) c
o
m
e
Fruitful Function
Fruitful function
Void function
Return values
Parameters
Local and global scope
Function composition
Recursion
Fruitful function:
A function that returns a value is called fruitful
function. Example:
Root=sqrt(25)
Example:
def add():
a=10 b=20
c=a+b
return c
c=add()
print(c)
Void Function
A function that perform action but don’t return any value.
Example:
print(“Hello”)
Example:
def add():
a=10
b=20
c=a+b
print(c)
add()
Return values:
return keywords are used to return the values from the function.
example:
return a – return 1 variable
return a,b– return 2 variables
return a,b,c– return 3 variables
return a+b– return expression
return 8– return value
PARAMETERS / ARGUMENTS:
Parameters are inputs to
Parameters are the variables which used in the function definition.
functions. Parameter receives the input from the function call.
It is possible to define more than one parameter in the function definition.
Types of parameters/Arguments:
1. Required/Positional parameters
2. Keyword parameters
3. Default parameters
4. Variable length parameters
Required/ Positional Parameter:
Example Output:
def student( name, roll ): George 98
print(name,roll)
student(“George”,98)
Keyword parameter:
When we call a function with some values, these values get assigned to the
parameter according to their position. When we call functions in keyword parameter, the
order of the arguments can be changed.
Example Output:
def student(name,roll,mark): 90 102 bala
print(name,roll,mark)
student(90,102,"bala")
Default parameter:
Python allows function parameter to have default values; if the function is called
without the argument, the argument gets its default value in function definition.
Example Output:
def student( name, age=17): Kumar 17
print (name, age)
Ajay 17
student( “kumar”):
student( “ajay”):
Example Output:
def student( name,*mark): bala ( 102 ,90)
print(name,mark)
student (“bala”,102,90)
Example: Output:
math.sqrt(math.log(10))
def add(a,b): 900
c=a+b
return c
def mul(c,d):
e=c*d
return e
c=add(10,20)
e=mul(c,30)
print(e)
Examples:
1. sum of n numbers using recursion
2. exponential of a number using recursion
Sum of n numbers Output
def sum(n): enter no. to find sum:10
if(n==1): Fact is 55
return 1
else:
return n*sum(n-1)
Strings:
String is defined as sequence of characters represented in quotation marks
(either single quotes ( ‘ ) or double quotes ( “ ).
An individual character in a string is accessed using a index.
The index should always be an integer (positive or negative).
A index starts from 0 to n-1.
Stringscreated.are immutable i.e. the contents of the string cannot be changed after it is
Python will get the input at run time by default as a string.
Python doesnot support character data type. A string of size 1 can be treated as characters.
1. single quotes (' ')
2. double quotes (" ")
3. triple quotes(“”” “”””)
Operations on string:
1. Indexing
2. Slicing
3. Concatenation
4. Repetitions
5. Member ship
>>>a=”HELLO” Positive indexing helps in accessing
indexing >>>print(a[0]) the string from the beginning
>>>H Negative subscript helps in accessing
>>>print(a[-1]) the string from the end.
>>>O
Print[0:4] – HELL The Slice[start : stop] operator extracts
Slicing: Print[ :3] – HEL sub string from the strings.
Print[0: ]- HELLO A segment of a string is called a slice.
Immutability:
Python strings are “immutable” as they cannot be changed after they are created.
Therefore [ ] operator cannot be used on the left side of an assignment.
Stringname.method()
a=”happy birthday”
here, a is the string name.
syntax example description
1 a.capitalize() >>> a.capitalize() capitalize only the first letter
' Happy birthday’ in a string
2 a.upper() >>> a.upper() change string to upper case
'HAPPY BIRTHDAY’
3 a.lower() >>> a.lower() change string to lower case
' happy birthday’
4 a.title() >>> a.title() change string to title case i.e.
' Happy Birthday ' first characters of all the
words are capitalized.
5 a.swapcase() >>> a.swapcase() change lowercase characters
'HAPPY BIRTHDAY' to uppercase and vice versa
6 a.split() >>> a.split() returns a list of words
['happy', 'birthday'] separated by space
7 a.center(width,”fillchar >>>a.center(19,”*”) pads the string with the
”) '***happy birthday***' specified “fillchar” till the
length is equal to “width”
8 a.count(substring) >>> a.count('happy') returns the number of
1 occurences of substring
9 a.replace(old,new) >>>a.replace('happy', replace all old substrings
'wishyou happy') with new substrings
'wishyou happy
birthday'
10 a.join(b) >>> b="happy" returns a string concatenated
>>> a="-" with the elements of an
>>> a.join(b) iterable. (Here “a” is the
'h-a-p-p-y' iterable)
11 a.isupper() >>> a.isupper() checks whether all the case-
False based characters (letters) of
the string are uppercase.
12 a.islower() >>> a.islower() checks whether all the case-
True based characters (letters) of
the string are lowercase.
13 a.isalpha() >>> a.isalpha() checks whether the string
False consists of alphabetic
characters only.
14 a.isalnum() >>> a.isalnum() checks whether the string
False consists of alphanumeric
characters.
15 a.isdigit() >>> a.isdigit() checks whether the string
False consists of digits only.
16 a.isspace() >>> a.isspace() checks whether the string
False consists of whitespace only.
17 a.istitle() >>> a.istitle() checks whether string is title
False cased.
18 a.startswith(substring) >>> a.startswith("h") checks whether string starts
True with substring
19 a.endswith(substring) >>> a.endswith("y") checks whether the string
True ends with the substring
20 a.find(substring) >>> a.find("happy") returns index of substring, if
0 it is found. Otherwise -1 is
returned.
21 len(a) >>>len(a) Return the length of the
>>>14 string
22 min(a) >>>min(a) Return the minimum
>>>’ ‘ character in the string
23 max(a) max(a) Return the maximum
>>>’y’ character in the string
String modules:
A module is a file containing Python definitions, functions, statements.
Standard library of Python is extended as modules.
To use these modules in a program, programmer needs to import the module.
Once we import a module, we can reference or use to any of its functions or variables in our
code.
There is large number of standard modules also available in python.
List as array:
Array:
Array is a collection of similar elements. Elements in the array can be accessed
by index. Index starts with 0. Array can be handled in python by module named array.
To create array have to import array module in the program.
Syntax :
import array
Syntax to create array:
Array_name = module_name.function_name(‘datatype’,[elements])
example:
a=array.array(‘i’,[1,2,3,4])
a- array name
array- module name
i- integer datatype
Example
Program to find sum of Output
array elements
import array 10
sum=0
a=array.array('i',[1,2,3,4])
for i in a:
sum=sum+i
print(sum)
Convert list into array:
fromlist() function is used to append list to array. Here the list is act like a array.
Syntax:
arrayname.fromlist(list_name)
Example
program to convert list Output
into array
import array 35
sum=0
l=[6,7,8,9,5]
a=array.array('i',[])
a.fromlist(l)
for i in a:
sum=sum+i
print(sum)
Function:
Lambda function (Anonymous Functions)
A function is said to be anonymous function when it is defined without
a name and def keyword.
In python, normal function are defined using def keyword
and Anonymous function are defined using lambda keyword.
Lambda function can have any number of argument but only one
expression.The expression are evaluated and returned.
Example:
>>> a=lambda b: b*2+b
>>> print(a(3))
9
Or
def a(b):
return b*2+b
Part A:
1. What are Boolean values?
2. Define operator and operand?
3. Write the syntax for if with example?
4. Write the syntax and flowchart for if else.
5. Write the syntax and flowchart for chained if.
6. define state
7. Write the syntax for while loop with flowchart.
8. Write the syntax for for loopwith flowchart.
9. Differentiate break and continue.
10. mention the use of pass
11. what is fruitful function
12. what is void function
13. mention the different ways of writing return statement
14. What is parameter and list down its type?
15. What is local and global scope?
16. Differentiate local and global variable?
17. What is function composition, give an example?
18. Define recursion.
19. Differentiate iteration and recursion.
20. Define string. How to get a string at run time.
>>> print(a[2])
4 Updating the list using
Updating >>> a[2]=100 index value.
>>> print(a)
[2, 3, 100, 5, 6, 7, 8, 9, 10]
>>> a=[2,3,4,5,6,7,8,9,10]
>>> 5 in a
Membership True Returns True if element is
>>> 100 in a present in list. Otherwise
False returns false.
>>> 2 not in a
False
>>> a=[2,3,4,5,6,7,8,9,10]
>>>b=[2,3,4] Returns True if all elements
Comparison
>>> a==b in both elements are same.
False Otherwise returns false
>>> a!=b
True
List slices:
❖
List slicing is an operation that extracts a subset of elements from an list and packages them as another
list.
Syntax:
Listname[start:stop]
Listname[start:stop:steps]
❖
❖
default stop value is n-1
❖
[:] this will print the entire list
❖
slices example description
a[0:3] >>> a=[9,8,7,6,5,4] Printing a part of a list from
>>> a[0:3] 0 to 2.
[9, 8, 7]
a[:4] >>> a[:4] Default start value is 0. so
[9, 8, 7, 6] prints from 0 to 3
a[1:] >>> a[1:] default stop value will be
[8, 7, 6, 5, 4] n-1. so prints from 1 to 5
a[:] >>> a[:] Prints the entire list.
[9, 8, 7, 6, 5, 4]
List methods:
Python provides methods that operate on lists.
syntax:
list name.method name( element/index/list)
>>>a=[8, 7, 6, 5, 4, 3, 2, 1, 0]
7 a.pop() >>> a.pop() Removes and
0
>>>print(a)
=[8, 7, 6, 5, 4, 3, 2, 1] returns an element
at the last element
8 a.pop(index) >>> a.pop(0) Remove the
8
>>>print(a)
[7, 6, 5, 4, 3, 2, 1, 0] particular element
and return it.
>>>a=[7, 6, 5, 4, 3, 2, 1]
9 a.remove(element) >>> a.remove(1) Removes an item
>>> print(a) from the list
[7, 6, 5, 4, 3, 2]
>>>a=[7, 6, 5, 4, 3, 2,6]
10 a.count(element) >>> a.count(6) Returns the count of
2 number of items
passed as an
argument
>>>a=[7, 6, 5, 4, 3, 2]
11 a.copy() >>> b=a.copy() Returns a
>>> print(b) copy of the list
[7, 6, 5, 4, 3, 2]
>>>a=[7, 6, 5, 4, 3, 2]
12 len(list) >>> len(a) return the length of
6 the length
>>>a=[7, 6, 5, 4, 3, 2]
17 sum(list) >>> sum(a) return the sum of
27 element in a list
14 max(list) >>> max(a) return the maximum
element in a list.
7
15 a.clear() >>> a.clear() Removes all items
>>> print(a) from the list.
[]
16 del(a) >>> del(a) delete the entire list.
>>> print(a)
Error: name 'a' is not
defined
List loops:
1. For loop
2. While loop
3. Infinite loop
List using For Loop:
❖
The for loop in Python is used to iterate over a sequence (list, tuple, string) or other
iterable objects.
❖
Iterating over a sequence is called traversal.
❖
Loop continues until we reach the last item in the sequence.
❖
The body of for loop is separated from the rest of the code using indentation.
Syntax:
for val in sequence:
❖
When the condition is tested and the result is false, the loop body will be skipped and the first statement
after the while loop will be executed.
Syntax:
while (condition):
body of while
Infinite Loop
A loop becomes infinite loop if the condition given never becomes false. It keeps
on running. Such loops are called infinite loop.
Example Output:
a=1 Enter the number 10
while (a==1): you entered:10
n=int(input("enter the number")) Enter the number 12
print("you entered:" , n) you entered:12
Enter the number 16
you entered:16
Mutability:
❖
Lists are mutable. (can be changed)
❖
Mutability is the ability for certain types of data to be changed without entirely
recreating it.
❖
An item can be changed in a list by accessing it directly as part of the assignment
statement.
❖
Using the indexing operator (square brackets[ ]) on the left side of an assignment, one of the list items can be
updated.
Example description
Aliasing(copying):
❖
Creating a copy of a list is called aliasing.
❖ When you create a copy both the list will be having same memory location.
❖
Example Output:
a= [1, 2, 3 ,4 ,5]
b=a
print (b) [1, 2, 3, 4, 5]
a is b True
a[0]=100
print(a) [100,2,3,4,5]
print(b) [100,2,3,4,5]
❖
In this a single list object is created and modified using the subscript operator.
❖
When the first element of the list named “a” is replaced, the first element of the list named “b” is also
replaced.
❖
This type of change is what is known as a side effect. This happens because after
the assignment b=a , the variables a and b refer to the exact same list object.
❖
They are aliases for the same object. This phenomenon is known as aliasing.
❖
To prevent aliasing, a new object can be created and the contents of the
original can be copied which is called cloning.
Clonning:
❖ To avoid the disadvantages of copying we are using cloning.
❖ Creating a copy of a same list of elements with two different memory locations is called cloning.
❖
Changes in one list will not affect locations of aother list.
❖
Cloning is a process of making a copy of the list without modifying the original list.
1. Slicing
2. list()method
3. copy() method
a=[1,2,3,4,5]
>>>b=a.copy()
>>> print(b)
[1, 2, 3, 4, 5]
>>> a is b
False
List as parameters:
❖
In python, arguments are passed by reference.
❖
If any changes are done in the parameter which refers within the function, then the
changes also reflects back in the calling function.
❖
When a list to a function is passed, the function gets a reference to the list.
❖
Passing a list as an argument actually passes a reference to the list, not a copy of the list.
❖
Since lists are mutable, changes made to the elements referenced by the parameter change the same
list that the argument is referencing.
Example 1`: Output
def remove(a): [2,3,4,5]
a.remove(1)
a=[1,2,3,4,5]
remove(a)
print(a)
Example 2: Output
def inside(a): inside [11, 12, 13, 14, 15]
for i in range(0,len(a),1): outside [11, 12, 13, 14, 15]
a[i]=a[i]+10
print(“inside”,a)
a=[1,2,3,4,5]
inside(a)
print(“outside”,a)
Example 3 output
def insert(a): [30, 1, 2, 3, 4, 5]
a.insert(0,30)
a=[1,2,3,4,5]
insert(a)
print(a)
Tuple:
❖
A tuple is same as list, except that the set of elements is enclosed in parentheses instead
of square brackets.
❖
A tuple is an immutable list. i.e. once a tuple has been created, you can't add elements to a tuple or remove
elements from the tuple.
❖
But tuple can be converted into list and list can be converted in to tuple.
methods example description
list( ) >>> a=(1,2,3,4,5) it convert the given tuple
>>> a=list(a) into list.
>>> print(a)
[1, 2, 3, 4, 5]
tuple( ) >>> a=[1,2,3,4,5] it convert the given list into
>>> a=tuple(a) tuple.
>>> print(a)
(1, 2, 3, 4, 5)
Benefit of Tuple:
❖
Tuples are faster than lists.
❖
If the user wants to protect the data from accidental changes, tuple can be used.
❖
Tuples can be used as keys in dictionaries, while lists can't.
Operations on Tuples:
1. Indexing
2. Slicing
3. Concatenation
4. Repetitions
5. Membership
6. Comparison
Operations examples description
Creating the tuple with
Creating a tuple >>>a=(20,40,60,”apple”,”ball”) elements of different data
types.
>>>print(a[0]) Accessing the item in the
Indexing 20 position 0
>>> a[2] Accessing the item in the
60 position 2
Slicing >>>print(a[1:3]) Displaying items from 1st
(40,60) till 2nd.
Concatenation >>> b=(2,4) Adding tuple elements at
>>>print(a+b) the end of another tuple
>>>(20,40,60,”apple”,”ball”,2,4) elements
Repetition >>>print(b*2) repeating the tuple in n no
>>>(2,4,2,4) of times
>>> a=(2,3,4,5,6,7,8,9,10)
>>> 5 in a
Membership True Returns True if element is
>>> 100 in a present in tuple. Otherwise
False returns false.
>>> 2 not in a
False
>>> a=(2,3,4,5,6,7,8,9,10)
>>>b=(2,3,4) Returns True if all elements
Comparison
>>> a==b in both elements are same.
False Otherwise returns false
>>> a!=b
True
Tuple methods:
❖
Tuple is immutable so changes cannot be done on the elements of a tuple once it is assigned.
methods example description
a.index(tuple) >>> a=(1,2,3,4,5) Returns the index of the
>>> a.index(5) first matched item.
4
a.count(tuple) >>>a=(1,2,3,4,5) Returns the count of the
>>> a.count(3) given element.
1
len(tuple) >>> len(a) return the length of the
5 tuple
min(tuple) >>> min(a) return the minimum
1 element in a tuple
max(tuple) >>> max(a) return the maximum
5 element in a tuple
del(tuple) >>> del(a) Delete the entire tuple.
Tuple Assignment:
❖
Tuple assignment allows, variables on the left of an assignment operator and values
of tuple on the right of the assignment operator.
❖
Multiple assignment works by creating a tuple of expressions from the right hand
side, and a tuple of targets from the left, and then matching each expression to a
target.
❖
Because multiple assignments use tuples to work, it is often termed tuple
assignment.
Uses of Tuple assignment:
❖
It is often useful to swap the values of two variables.
Example:
Swapping using temporary variable: Swapping using tuple assignment:
a=20 a=20
b=50 b=50
temp = a (a,b)=(b,a)
a=b print("value after swapping is",a,b)
b = temp
print("value after swapping is",a,b)
Multiple assignments:
Multiple values can be assigned to multiple variables using tuple assignment.
>>>(a,b,c)=(1,2,3)
>>>print(a)
1
>>>print(b)
2
>>>print(c)
3
❖
A function can return one value. if you want to return more than one value from a function. we can
use tuple as return value.
Example1: Output:
def div(a,b): enter a value:4
r=a%b enter b value:3
q=a//b reminder: 1
return(r,q) quotient: 1
a=eval(input("enter a value:"))
b=eval(input("enter b value:"))
r,q=div(a,b)
print("reminder:",r)
print("quotient:",q)
Example2: Output:
def min_max(a): smallest: 1
small=min(a) biggest: 6
big=max(a)
return(small,big)
a=[1,2,3,4,6]
small,big=min_max(a)
print("smallest:",small)
print("biggest:",big)
Tuple as argument:
❖
The parameter name that begins with * gathers argument into a tuple.
Example: Output:
def printall(*args): (2, 3, 'a')
print(args)
printall(2,3,'a')
Dictionaries:
❖
Dictionary is an unordered collection of elements. An element in dictionary has a key: value pair.
❖
All elements in dictionary are placed inside the curly braces i.e. { }
❖ Elements in Dictionaries are accessed via keys and not by their
❖
position. The values of a dictionary can be any data type.
❖
Keys must be immutable data type (numbers, strings, tuple)
Operations on dictionary:
1. Accessing an element
2. Update
3. Add element
4. Membership
Operations Example Description
Methods in dictionary:
Programs on matrix:
Matrix addition Output
a=[[1,1],[1,1]] [3, 3]
b=[[2,2],[2,2]] [3, 3]
c=[[0,0],[0,0]]
for i in range(len(a)):
for j in range(len(b)):
c[i][j]=a[i][j]+b[i][j]
for i in c:
print(i)
def divide(x):
if len(x) == 0 or len(x) == 1:
return x
else:
middle = len(x)//2
a = divide(x[:middle])
b = divide(x[middle:])
return merge(a,b)
x=[38,27,43,3,9,82,10]
c=divide(x)
print(c)
Histogram Output
def histogram(a): ****
for i in a: *****
sum = '' *******
while(i>0): ********
sum=sum+'#' ************
i=i-1
print(sum)
a=[4,5,7,8,12]
histogram(a)
Calendar program Output
import calendar enter year:2017
y=int(input("enter year:")) enter month:11
m=int(input("enter month:")) November 2017
print(calendar.month(y,m)) Mo Tu We Th Fr Sa Su
12345
6 7 8 9 10 11 12
13 14 15 16 17 18 19
20 21 22 23 24 25 26
27 28 29 30
PART - A
1. What is slicing?
2. How can we distinguish between tuples and lists?
3. What will be the output of the given code?
a. List=[‘p’,’r’,’i’,’n’,’t’,]
b. Print list[8:]
4. Give the syntax required to convert an integer number into string?
5. List is mutable. Justify?
6. Difference between del and remove methods in List?
7. Difference between pop and remove in list?
8. How are the values in a tuple accessed?
9. What is a Dictionary in Python
10. Define list comprehension
11. Write a python program using list looping
12. What do you meant by mutability and immutability?
13. Define Histogram
14. Define Tuple and show it is immutable with an example.
15. state the difference between aliasing and cloning in list
16. what is list cloning
17. what is deep cloning
18. state the difference between pop and remove method in list
19. create tuple with single element
20. swap two numbers without using third variable
21. define properties of key in dictionary
22. how can you access elements from the dictionary
23. difference between delete and clear method in dictionary
24. What is squeezing in list? give an example
25. How to convert a tuple in to list
26. How to convert a list in to tuple
27. Create a list using list comprehension
28. Advantage of list comprehension
29. What is the use of map () function.
30. How can you return multiple values from function?
31. what is sorting and types of sorting
32. Find length of sequence without using library function.
33. how to pass tuple as argument
34. how to pass a list as argument
35. what is parameter and types of parameter
36. how can you insert values in to dictionary
37. what is key value pair
38. mention different data types can be used in key and value
39. what are the immutable data types available in python
40. What is the use of fromkeys() in dictioanary.
PART-B
1. Explain in details about list methods
2. Discuss about operations in list
3. What is cloning? Explain it with example
4. What is aliasing? Explain with example
5. How can you pass list into function? Explain with example.
6. Explain tuples as return values with examples
7. write a program for matrix multiplication
8. write a program for matrix addition
9. write a program for matrix subtraction
10. write a program for matrix transpose
11. write procedure for selection sort
12. explain merge sort with an example
13. explain insertion with example
14. Explain in detail about dictionaries and its methods.
15. Explain in detail about advanced list processing.
UNIT V FILES, MODULES, PACKAGES
Files and exception: text files, reading and writing files, format operator; command line
arguments, errors and exceptions, handling exceptions, modules, packages; Illustrative
programs: word count, copy file.
Files :
• Binary files
• Text files
File operation and file functions
A file is one, which will enable the user to read, write and store a group of related data, without losing
them even if the program is over. To perform these functions there are several basic file operations as,
• Naming a file - It is conventional, and convenient to name files in relation to the data stored.
• Opening a file
• Reading data from the file
• Writing data to the file and
• Closing a file
open()
Before going to do any file operation, the concerned file should be opened.
Syntax:
file_object=open(“file_name”,”file_mode”)
The open() function creates a file object. Finally it should be given, as to what purpose the file is
being used. It is also called the file mode.
file_mode Description
R Opens a file for reading purpose and this is the default file opening mode/
W Opens a file for writing purpose
A Opens a file for appending data to it.
r+ Existing file is opened to the beginning for both reading and writing
w+ Opens a file for reading and writing purpose. The file pointer is positioned at the beginning
of the file.
a+ Opens a file for reading and writing purpose. The file pointer is positioned at the end of the
file
Rb Opens a file for reading in binary format and this is the default file opening mode.
Ab Opens a file for appending data in binary format
1
Wb Opens a file for writing in binary format
rb+ Opens a file for reading and writing purpose in a binary format and the file pointer is
positioned at the beginning of the file
wb+ Opens a file for reading and writing purpose in a binary format. If the file already exists it
overwrites the file. If the file does not exist it will create a new one for both reading and
writing.
ab+ Opens a file for appending and reading data in binary format. Here the file pointer is
positioned at end if the file already exists. It will create a new one if the file does not exists.
close()
These two functions are considered as most basic of all input/output functions in file handling. The
write() function writes characters to a disk file that was previously opened for writing,through the use of
the function open().Similarly read() function is used to read characters from a file opened in read mode
by open().The general format for read() method is:
file_object.read(no_of_bytes_to_be_read)
The write() method is used to write data to a file. This method requires only one parameter,
that must be a string and writes that string into a file. The general for write() method is:
file_object.write(string)
2
Text file –example:
F1=open(“abc.txt”,”x”)
out=open("abc.dat","w")
str= input("Enter string : ")
out.write(str)
out.close()
out=open("abc.dat","r")
str=out.read()
print("File contains")
print(str)
out.close()
Output
Enter string : Welcome to Python file handling
File contains
Welcome to Python file handling
Example program:
import sys
noargs=len(sys.argv)
print ("Number of arguments :%d" %noargs)
arguments= str(sys.argv)
print ("Arguments are : %s" %arguments)
Output
3
Errors and Exceptions:
•Syntax errors
– python interpreter find the syntax error when it
executes the coding. Once find the error, it displays the error
by stopping the execution.
Examples:
➢
Trying to access a file that doesn’t exists
➢
Performing the operations like division by zero
➢
Using an identifier which is not defined
•Definition
– An exception is an event, which occurs during
the execution of the program that disrupts the normal flow of
the program.
4
• The handling mechanism is done by
•try, except and else blocks
placed here
try:
except exception1:
except exception2:
.
..
else:
Example program:
try:
n=int(input(“enter a value”))
expert:
print(“you didn’t enter the integer input”)
else:
print(“value entered correctly and stored”)
5
output:
enter a value:5
value entered correctly and stored
Packages:
Packages are namespaces which contain multiple packages and modules themselves. They
are simply directories, but with a twist.
Each package in Python is a directory which must contain a special file called _ _init_ _.py
To be a package the folder must contain a file called __init__.py
Packages can be nested to any depth i.e. it contains many sub packages and modules in it.
11/20/2017
8
Accessing Packages:
Step 1: Create a folder name “MyPackage” in the folder where the python files are storing.
Step 2: Create a subfolder name “Add” in the folder “MyPackage”.
Step 3: Type a python program containing the function to add two numbers with function name
“add” and save the file inside the folder
“Add” by the name “addition”
Example Program:
6
Format Operator – ‘%’
Symbol is ‘%’.
Python uses C-style string formatting to create new strings. The "%" operator is used
to format a set of variables enclosed in a "tuple" along with a format string. The format string
contains text with argument specifier symbols like "%f" and "%d".
Modules
In Python module is a file that contains definitions of functions, variables and classes. The module name
is the same as the file name. We have used some scientific functions that present in math module and it
is a built in Python module. The main advantage of using module is it allows us to make our programs
more robust and powerful. We can have our own module and in our example program we created a
module by name “myfunctions.py”. The module contains two functions definition namely fact() and
maximum(). The coding is as follows.
7
def fact(no):
f=1
for i in range(1,no+1):
f=f*i
return (f)
def maximum(arr):
max=arr[0]
for i in range(1,len(arr)):
if (max <arr[i]):
max=arr[i]
return max
import myfunctions
a=[8,10,30,15,20]
Output
8
Illustrative programs:
Word Count of a file:
import sys
fname=sys.argv[1]
n=0
with open(fname,'r') as f:
for line in f:
words=line.split()
n+=len(words)
print("Number of words:",n)
Copy file:
f1=open(“sourcefile.txt”,”r”)
f2=open(“destinationfile.txt”,”w”)
for line in f1:
f2.write(“\n”+line)
f1.close( )
f2.close( )
print(“Content of Source file:”)
f1=open(“sourcefile.txt”,”r”)
print(f1.read( ))
print(“Content of Copied file:”)
f2=open(“destinationfile.txt”,”r”)
print(f2.read( ))