265 - GE8151 Problem Solving and Python Programming - Notes 1
265 - GE8151 Problem Solving and Python Programming - Notes 1
UNIT IV
COMPOUND DATA: LISTS, TUPLES, DICTIONARIES
Lists, list operations, list slices, list methods, list loop, mutability, aliasing, cloning lists,
list parameters; Tuples, tuple assignment, tuple as return value; Dictionaries:
operations and methods; advanced list processing - list comprehension, Illustrative
programs: selection sort, insertion sort, merge sort, quick sort.
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:
1. Indexing
2. Slicing
3. Concatenation
4. Repetitions
5. Updating
6. Membership
7. Comparison
>>> 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 start value is 0
default stop value is n-1
[:] this will print the entire list
[2:2] this will create a empty slice
slices example description
>>> a=[9,8,7,6,5,4]
a[0:3] >>> a[0:3] Printing a part of a list from
[9, 8, 7] 0 to 2.
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]
www.BrainKart.com
Click Here for Problem Solving and Python Programming full study material.
List methods:
Methods used in lists are used to manipulate the data quickly.
These methods work only on lists.
They do not work on the other sequence types that are not mutable, that is, the
values they contain cannot be changed, added, or deleted.
syntax:
www.BrainKart.com
Click Here for Problem Solving and Python Programming full study material.
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.
4 Unit 3:control flow, functions
www.BrainKart.com
Click Here for Problem Solving and Python Programming full study material.
Syntax:
for val in sequence:
www.BrainKart.com
Click Here for Problem Solving and Python Programming full study material.
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
>>> a=[1,2,3,4,5] changing single element
>>> a[0]=100
>>> print(a)
[100, 2, 3, 4, 5]
>>> a=[1,2,3,4,5] changing multiple element
>>> a[0:3]=[100,100,100]
>>> print(a)
[100, 100, 100, 4, 5]
>>> a=[1,2,3,4,5] The elements from a list can also be
>>> a[0:3]=[ ] removed by assigning the empty list to
>>> print(a) them.
[4, 5]
>>> a=[1,2,3,4,5] The elements can be inserted into a list by
>>> a[0:0]=[20,30,45] squeezing them into an empty slice at the
>>> print(a) desired location.
[20,30,45,1, 2, 3, 4, 5]
www.BrainKart.com
Click Here for Problem Solving and Python Programming full study material.
Aliasing(copying):
Creating a copy of a list is called aliasing. When you create a copy both list will be
having same memory location. changes in one list will affect another list.
Alaising refers to having different names for same list values.
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
www.BrainKart.com
Click Here for Problem Solving and Python Programming full study material.
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)
8 Unit 3:control flow, functions
www.BrainKart.com
Click Here for Problem Solving and Python Programming full study material.
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
9 Unit 3:control flow, functions
www.BrainKart.com
Click Here for Problem Solving and Python Programming full study material.
www.BrainKart.com
Click Here for Problem Solving and Python Programming full study material.
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
www.BrainKart.com
Click Here for Problem Solving and Python Programming full study material.
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
www.BrainKart.com
Click Here for Problem Solving and Python Programming full study material.
Methods in dictionary:
www.BrainKart.com
Click Here for Problem Solving and Python Programming full study material.
www.BrainKart.com
Click Here for Problem Solving and Python Programming full study material.
Can contain duplicate Can contain duplicate elements. Cant contain duplicate
elements Faster compared to lists keys, but can contain
duplicate values
Slicing can be done Slicing can be done Slicing can't be done
Usage: Usage: Usage:
List is used if a Tuple can be used when data Dictionary is used
collection of data that cannot be changed. when a logical
doesnt need random A tuple is used in combination association between
access. with a dictionary i.e.a tuple might key:value pair.
List is used when represent a key. When in need of fast
data can be modified lookup for data, based
frequently on a custom key.
Dictionary is used
when data is being
constantly modified.
www.BrainKart.com
Click Here for Problem Solving and Python Programming full study material.
Nested list:
List inside another list is called nested list.
Example:
>>> a=[56,34,5,[34,57]]
>>> a[0]
56
>>> a[3]
[34, 57]
>>> a[3][0]
34
>>> a[3][1]
57
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)
www.BrainKart.com
Click Here for Problem Solving and Python Programming full study material.
Illustrative programs:
Selection sort Output
a=input("Enter list:").split() Enter list:23 78 45 8 32 56
a=list(map(eval,a)) [8,2 3, 32, 45,56, 78]
for i in range(0,len(a)):
smallest = min(a[i:])
sindex= a.index(smallest)
a[i],a[sindex] = a[sindex],a[i]
print (a)
www.BrainKart.com
Click Here for Problem Solving and Python Programming full study material.
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)
www.BrainKart.com
Click Here for Problem Solving and Python Programming full study material.
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
1234 5
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
www.BrainKart.com
Click Here for Problem Solving and Python Programming full study material.
www.BrainKart.com
Click Here for Problem Solving and Python Programming full study material.
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.
www.BrainKart.com
Click Here for Problem Solving and Python Programming full study material.
www.BrainKart.com
Click Here for Problem Solving and Python Programming full study material.
Example:
Example
Write an algorithm to print „Good Morning”
Step 1: Start
Step 2: Print “Good Morning”
Step 3: Stop
2.2. State:
Transition from one process to another process under specified condition with in a
time is called state.
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 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
Flow chart is defined as graphical representation of the logic for problem solving.
The purpose of flowchart is making the logic of the program clear in a visual
representation.
4. Only one flow line should enter a decision symbol. However, two or three flow
lines may leave the decision symbol.
Advantages 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.3.PROGRAMMING LANGUAGE
A programming language is a set of symbols and rules for instructing a computer
to perform specific tasks. The programmers have to follow all the specified rules before
writing program using programming language. The user has to communicate with the
computer using language which it can understand.
Types of programming language
1. Machine language
2. Assembly language
3. High level language
Machine language:
The computer can understand only machine language which uses 0’s and 1’s. In
machine language the different instructions are formed by taking different
combinations of 0’s and 1’s.
Advantages:
Translation free:
Machine language is the only language which the computer understands. For
executing any program written in any programming language, the conversion to
machine language is necessary. The program written in machine language can be
executed directly on computer. In this case any conversion process is not required.
High speed
The machine language program is translation free. Since the conversion time is
saved, the execution of machine language program is extremely fast.
Disadvantage:
It is hard to find errors in a program written in the machine language.
Writhing program in machine language is a time consuming process.
Machine dependent: According to architecture used, the computer differs from each
other. So machine language differs from computer to computer. So a program
developed for a particular type of computer may not run on other type of computer.
Assembly language:
To overcome the issues in programming language and make the programming
process easier, an assembly language is developed which is logically equivalent to
machine language but it is easier for people to read, write and understand.
Unit 1: Algorithmic problem solving 8
www.BrainKart.com
Click Here for Problem Solving and Python Programming full study material.
Compiler:
A compiler is a program which translates the source code written in a high level
language in to object code which is in machine language program. Compiler reads the
whole program written in high level language and translates it to machine language. If
any error is found it display error message on the screen.
Interpreter
Interpreter translates the high level language program in line by line manner. The
interpreter translates a high level language statement in a source program to a machine
code and executes it immediately before translating the next statement. When an error
is found the execution of the program is halted and error message is displayed on the
screen.
Advantages
Readability
High level language is closer to natural language so they are easier to learn and
understand
Machine independent
High level language program have the advantage of being portable between
machines.
Easy debugging
Easy to find and correct error in high level language
Disadvantages
Less efficient
The translation process increases the execution time of the program. Programs in
high level language require more memory and take more execution time to execute.
Scripting language:
Scripting language are programming languages that control an application.
Scripts can execute independent of any other application. They are mostly embedded in
the application that they control and are used to automate frequently executed tasks
like communicating with external program.
Examples:
Apple script
VB script
Markup languages:
A markup language is an artificial language that uses annotations to text that
define hoe the text is to be displayed.
Examples:
HTML
XML
Concurrent programming language:
Concurrent programming is a computer programming technique that provides
for the execution of operation concurrently, either with in a single computer or across a
number of systems.
Examples:
Joule
Limbo
Object oriented programming language:
Object oriented programming is a programming paradigm based on the concept
of objects which may contain data in the form of procedures often known as methods.
Examples:
Lava
Moto
In the earlier days of computing, the dominant vehicle for specifying algorithms
was a flowchart, a method of expressing an algorithm by a collection of
connected geometric shapes containing descriptions of the algorithm’s steps.
Analysing an Algorithm
1. Efficiency.
Time efficiency, indicating how fast the algorithm runs,
Space efficiency, indicating how much extra memory it uses.
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.
www.BrainKart.com
Click Here for Problem Solving and Python Programming full study material.
5.2. Recursions:
A function that calls itself is known as recursion.
Recursion is a process by which a function calls itself repeatedly until some
specified condition has been satisfied.
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
www.BrainKart.com
Click Here for Problem Solving and Python Programming full study material.
BEGIN
READ a,b
IF (a>b) THEN
DISPLAY a is greater
ELSE
DISPLAY b is greater
END IF
END
BEGIN
READ num
IF (num>0) THEN
DISPLAY num is positive
ELSE
DISPLAY num is negative
END IF
END
www.BrainKart.com
Click Here for Problem Solving and Python Programming full study material.
BEGIN
READ a, b, c
IF (a>b) THEN
IF(a>c) THEN
DISPLAY a is greater
ELSE
DISPLAY c is greater
END IF
ELSE
IF(b>c) THEN
DISPLAY b is greater
ELSE
DISPLAY c is greater
END IF
END IF
END
BEGIN
GET n
IF(n==0) THEN
DISPLAY “ n is zero”
ELSE
IF(n>0) THEN
DISPLAY “n is positive”
ELSE
DISPLAY “n is positive”
END IF
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
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
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
BEGIN
GET n
INITIALIZE i=1
WHILE(i<=n) DO
PRINT i*i
i=i+2
ENDWHILE
END
www.BrainKart.com
Click Here for Problem Solving and Python Programming full study material.
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
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
www.BrainKart.com
Click Here for Problem Solving and Python Programming full study material.
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)
Part A:
1. What is mean by problem solving?
2. List down the problem solving techniques?
3. Define algorithm?
4. What are the properties of algorithm?
5. List down the equalities of good algorithm?
6. Define statements?
7. Define state?
8. What is called control flow?
9. What is called sequence execution?
10. Define iteration?
11. What is mean by flow chart?
12. List down the basic symbols for drawing flowchart?
13. List down the rules for drawing the flowchart?
14. What are the advantages of flowchart?
15. What are the disadvantages of flowchart?
16. Define pseudo code?
17. List down the keywords used in writing pseudo code?
18. Mention the advantages of using pseudo code?
19. Mention the disadvantages of using pseudo code?
20. What are the ways available to represent algorithm?
21. Differentiate flowchart and pseudo code?
22. Differentiate algorithm and pseudo code?
23. What is programming language?
24. Mention the types of programming language?
25. What is mean by machine level language?
26. What are the advantages and disadvantages of machine level language?
27. What is high level programming language and mention its advantages?
28. What are the steps in algorithmic problem solving?
29. Write the algorithm for any example?
30. Draw the flow chart for any example?
31. Write pseudo code for any example?
Part B:
1. Explain in detail about problem solving techniques?
2. Explain in detail about building blocks of algorithm?
3. Discuss the symbols and rules for drawing flowchart with the example?
4. Explain in detail about programming language?
5. Discuss briefly about algorithmic problem solving?
6. Write algorithm, pseudo code and flow chart for any example?
7. Explain in detail about simple strategies for developing algorithms?
Unit 1: Algorithmic problem solving 37
www.BrainKart.com
Click Here for Problem Solving and Python Programming full study material.
UNIT II
DATA, EXPRESSIONS, STATEMENTS
Python interpreter and interactive mode; values and types: int, float, boolean, string,
and list; variables, expressions, statements, tuple assignment, precedence of operators,
comments; Modules and functions, function definition and use, flow of execution,
parameters and arguments; Illustrative programs: exchange the values of two
variables, circulate the values of n variables, distance between two points.
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.
1.1. Python Features:
Easy-to-learn: Python is clearly defined and easily readable. The structure
of the program is very simple. It uses few keywords.
Easy-to-maintain: Python's source code is fairly easy-to-maintain.
Portable: Python can run on a wide variety of hardware platforms and has the
same interface on all platforms.
Interpreted: Python is processed at runtime by the interpreter. So, there is no
need to compile a program before executing it. You can simply run the program.
Extensible: Programmers can embed python within their C,C++,Java script
,ActiveX, etc.
Free and Open Source: Anyone can freely distribute it, read the source code, and
edit it.
High Level Language: When writing programs, programmers concentrate on
solutions of the current problem, no need to worry about the low level details.
Scalable: Python provides a better structure and support for large programs
than shell scripting.
1.2. Applications:
Bit Torrent file sharing
Google search engine, Youtube
Intel, Cisco, HP, IBM
i–Robot
NASA
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
This is an example of a print statement. It displays a result on the screen. In this case,
the result is the words.
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.1 Numbers:
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
2.2.1 Strings:
A String in Python consists of a series or sequence of characters - letters,
numbers, and special characters.
Strings are marked by quotes:
single quotes (' ') Eg, 'This a string in single quotes'
double quotes (" ") Eg, "'This a string in double quotes'"
triple quotes(""" """) Eg, This is a paragraph. It is made up of
multiple lines and sentences."""
Individual character in a string is accessed using a subscript (index).
Characters can be accessed using indexing and slicing operations
Strings are immutable i.e. the contents of the string cannot be changed after it is
created.
Indexing:
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
6.78, 9]
Repetition >>> list2*3 Creates new strings,
['god', 6.78, 9, 'god', 6.78, 9, 'god', concatenating multiple
6.78, 9] copies of the same string
Updating the list >>> list1[2]=45 Updating the list using index
>>>print( list1) value
[‘python’, 7.79, 45, ‘hello’]
Inserting an >>> list1.insert(2,"program") Inserting an element in 2nd
element >>> print(list1) position
['python', 7.79, 'program', 45,
'hello']
Removing an >>> list1.remove(45) Removing an element by
element >>> print(list1) giving the element directly
['python', 7.79, 'program', 'hello']
2.2.4 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.
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.1 Dictionaries:
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 (_).
Example:
>>> x=input("enter the name:")
enter the name: george
>>>y=int(input("enter the number"))
enter the number 3
#python accepts string as default data type. conversion is required for type.
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:
a=3
b=1
if a>b:
print("a is greater")
else:
print("b is greater")
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:
www.BrainKart.com
Click Here for Problem Solving and Python Programming full study material.
(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
13 Unit 2: Data ,expressions, Statements
www.BrainKart.com
Click Here for Problem Solving and Python Programming full study material.
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)
www.BrainKart.com
Click Here for Problem Solving and Python Programming full study material.
> 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
www.BrainKart.com
Click Here for Problem Solving and Python Programming full study material.
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=2
c %= 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)
www.BrainKart.com
Click Here for Problem Solving and Python Programming full study material.
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
17 Unit 2: Data ,expressions, Statements
www.BrainKart.com
Click Here for Problem Solving and Python Programming full study material.
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)
18 Unit 2: Data ,expressions, Statements
www.BrainKart.com
Click Here for Problem Solving and Python Programming full study material.
5.OPERATOR PRECEDENCE:
When an expression contains more than one operator, the order of evaluation
depends on the order of operations.
Operator Description
www.BrainKart.com
Click Here for Problem Solving and Python Programming full study material.
Example:
a=9-12/3+3*2-1 A=2*3+4%5-3/2+6
a=? A=6+4%5-3/2+6 find m=?
a=9-4+3*2-1 A=6+4-3/2+6 m=-43||8&&0||-2
a=9-4+6-1 A=6+4-1+6 m=-43||0||-2
a=5+6-1 A=10-1+6 m=1||-2
a=11-1 A=9+6 m=1
a=10 A=15
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.
Types of function:
Functions can be classified into two categories:
i) user defined function
ii) Built in function
i) Built in functions
Built in functions are the functions that are already created and stored in python.
These built in functions are always available for usage and accessed by a
programmer. It cannot be modified.
Built in function Description
20 Unit 2: Data ,expressions, Statements
www.BrainKart.com
Click Here for Problem Solving and Python Programming full study material.
www.BrainKart.com
Click Here for Problem Solving and Python Programming full study material.
Syntax:
def fun_name(Parameter1,Parameter2…Parameter n):
statement1
statement2…
statement n
return[expression]
Example:
def my_add(a,b):
c=a+b
return c
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.
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.
www.BrainKart.com
Click Here for Problem Solving and Python Programming full study material.
OUTPUT: OUTPUT:
enter a 5 enter a 5
enter b 10 enter b 10
15 15
www.BrainKart.com
Click Here for Problem Solving and Python Programming full study material.
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)
www.BrainKart.com
Click Here for Problem Solving and Python Programming full study material.
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.
www.BrainKart.com
Click Here for Problem Solving and Python Programming full study material.
www.BrainKart.com
Click Here for Problem Solving and Python Programming full study material.
than or equal to x
math.floor(x) - Return the floor of x, the largest integer less than or
equal to x.
math.factorial(x) -Return x factorial. math.gcd(x,y)- Return the
greatest common divisor of the integers a and b
math.sqrt(x)- Return the square root of x
math.log(x)- return the natural logarithm of x
math.log10(x) – returns the base-10 logarithms
math.log2(x) - Return the base-2 logarithm of x.
math.sin(x) – returns sin of x radians
math.cos(x)- returns cosine of x radians
math.tan(x)-returns tangent of x radians
math.pi - The mathematical constant π = 3.141592
math.e – returns The mathematical constant e = 2.718281
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,)
www.BrainKart.com
Click Here for Problem Solving and Python Programming full study material.
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.
www.BrainKart.com
Click Here for Problem Solving and Python Programming full study material.
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.
www.BrainKart.com
Click Here for Problem Solving and Python Programming full study material.
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.
Consider the expression 4 + 5 = 9. Here, 4 and 5 are called operands and + is
called operator.
Types of Operators:
1. Arithmetic Operators
2. Comparison (Relational) Operators
3. Assignment Operators
4. Logical Operators
5. Bitwise Operators
6. Membership Operators
7. Identity Operators
www.BrainKart.com
Click Here for Problem Solving and Python Programming full study material.
Arithmetic operators:
They are used to perform mathematical operations like addition, subtraction,
multiplication etc.
Operator Description Example
a=10,b=20
+ Addition Adds values on either side of the operator. a + b = 30
- Subtraction Subtracts right hand operand from left hand operand. a – b = -10
* Multiplication Multiplies values on either side of the operator a * b = 200
/ Division Divides left hand operand by right hand operand b/a=2
% Modulus Divides left hand operand by right hand operand and b % a = 0
returns remainder
** Exponent Performs exponential (power) calculation on a**b =10 to the
operators power 20
// Floor Division - The division of operands where the 5//2=2
result is the quotient in which the digits after the
decimal point are removed
www.BrainKart.com
Click Here for Problem Solving and Python Programming full study material.
*= Multiply AND It multiplies right operand with the left operand c *= a is equivalent
and assign the result to left operand to c = c * a
/= Divide AND It divides left operand with the right operand and c /= a is equivalent
assign the result to left operand to c = c / ac /= a is
equivalent to c = c
/a
%= Modulus AND It takes modulus using two operands and assign c %= a is
the result to left operand equivalent to c = c
%a
**= Exponent AND Performs exponential (power) calculation on c **= a is
operators and assign value to the left operand equivalent to c = c
** a
//= Floor Division It performs floor division on operators and c //= a is
assign value to the left operand equivalent to c = c
// a
Logical Operators:
Logical operators are and, or, not operators.
Bitwise Operators:
Let x = 10 (0000 1010 in binary) and y = 4 (0000 0100 in binary)
Membership Operators:
Evaluates to find a value or a variable is in the specified sequence of string,
list, tuple, dictionary or not.
To check particular element is available in the list or not.
Operators are in and not in.
www.BrainKart.com
Click Here for Problem Solving and Python Programming full study material.
Example:
x=[5,3,6,4,1]
>>> 5 in x
True
>>> 5 not in x
False
Identity Operators:
They are used to check if two values (or variables) are located on the same part of
the memory.
Example
x=5
y=5
a = 'Hello'
b = 'Hello'
print(x is not y) // False
print(a is b)//True
CONDITIONALS
Conditional if
Alternative if… else
Chained if…elif…else
Nested if….else
Conditional (if):
conditional (if) is used to test a condition, if the condition is true the statements
inside if will be executed.
syntax:
Flowchart:
www.BrainKart.com
Click Here for Problem Solving and Python Programming full study material.
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
alternative (if-else)
In the alternative the condition must be true or false. In this else statement can
be combined with if statement. The else statement contains the block of code that
executes when the condition is false. If the condition is true statements inside the if get
executed otherwise else part gets executed. The alternatives are called branches,
because they are branches in the flow of execution.
syntax:
Flowchart:
Examples:
1. odd or even number
2. positive or negative number
3. leap year or not
www.BrainKart.com
Click Here for Problem Solving and Python Programming full study material.
Chained conditionals(if-elif-else)
The elif is short for else if.
This is used to check more than one condition.
If the condition1 is False, it checks the condition2 of the elif block. If all the
conditions are False, then the else part is executed.
Among the several if...elif...else part, only one part is executed according to
the condition.
www.BrainKart.com
Click Here for Problem Solving and Python Programming full study material.
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
www.BrainKart.com
Click Here for Problem Solving and Python Programming full study material.
www.BrainKart.com
Click Here for Problem Solving and Python Programming full study material.
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:
print(“the greatest no is”,c)
9 Unit 3:control flow, functions
www.BrainKart.com
Click Here for Problem Solving and Python Programming full study material.
else:
if(b>c):
print(“the greatest no is”,b)
else:
print(“the greatest no is”,c)
positive negative or zero output
n=eval(input("enter the value of n:")) enter the value of n:-9
if(n==0): the number is negative
print("the number is zero")
else:
if(n>0):
print("the number is positive")
else:
print("the number is negative")
ITERATION/CONTROL STATEMENTS:
state
while
for
break
continue
pass
State:
Transition from one process to another process under specified condition with in
a time is called state.
While loop:
While loop statement in Python is used to repeatedly executes set of
statement as long as a given condition is true.
In while loop, test expression is checked first. The body of the loop is
entered only if the test_expression is True. After one iteration, the test
expression is checked again. This process continues until
the test_expression evaluates to False.
In Python, the body of the while loop is determined through indentation.
The statements inside the while starts with indentation and the first
unindented line marks the end.
Syntax:
www.BrainKart.com
Click Here for Problem Solving and Python Programming full study material.
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)
www.BrainKart.com
Click Here for Problem Solving and Python Programming full study material.
sum=sum+a
n=n//10
print(sum)
www.BrainKart.com
Click Here for Problem Solving and Python Programming full study material.
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.
www.BrainKart.com
Click Here for Problem Solving and Python Programming full study material.
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 nos 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
www.BrainKart.com
Click Here for Problem Solving and Python Programming full study material.
www.BrainKart.com
Click Here for Problem Solving and Python Programming full study material.
Flowchart
example Output
for i in "welcome": w
if(i=="c"): e
break l
print(i)
www.BrainKart.com
Click Here for Problem Solving and Python Programming full study material.
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
It is used when a statement is required syntactically but you don’t want any code
to execute.
It is a null statement, nothing happens when it is executed.
www.BrainKart.com
Click Here for Problem Solving and Python Programming full study material.
Syntax:
pass
break
Example Output
for i in “welcome”: w
if (i == “c”): e
pass l
print(i) c
o
m
e
www.BrainKart.com
Click Here for Problem Solving and Python Programming full study material.
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
19 Unit 3:control flow, functions
www.BrainKart.com
Click Here for Problem Solving and Python Programming full study material.
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 the variables which used in the function definition. Parameters
are inputs to 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:
The number of parameter in the function definition should match exactly with
number of arguments in the function call.
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")
www.BrainKart.com
Click Here for Problem Solving and Python Programming full study material.
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”):
In the function definition we use an asterisk (*) before the parameter name
to denote this is variable length of parameter.
Example Output:
def student( name,*mark): bala ( 102 ,90)
print(name,mark)
student (“bala”,102,90)
www.BrainKart.com
Click Here for Problem Solving and Python Programming full study material.
Local Scope A variable with local scope can be used only within the function .
Example output
def add():
b=20
c=a+b 70
Local Variable
print©
def sub():
b=30 20
c=a-b Local Variable
print©
print(a) error
print(b) error
Function Composition:
Function Composition is the ability to call one function from within another
function
It is a way of combining functions such that the result of each function is passed
as the argument of the next function.
In other words the output of one function is given as the input of another function
is known as function composition.
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)
www.BrainKart.com
Click Here for Problem Solving and Python Programming full study material.
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)
www.BrainKart.com
Click Here for Problem Solving and Python Programming full study material.
Strings:
Strings
String slices
Immutability
String functions and methods
String module
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.
Strings are immutable i.e. the contents of the string cannot be changed after it is
created.
Python will get the input at run time by default as a string.
Python does not 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
www.BrainKart.com
Click Here for Problem Solving and Python Programming full study material.
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.
operations Example output
element assignment a="PYTHON" TypeError: 'str' object does
a[0]='x' not support element
assignment
www.BrainKart.com
Click Here for Problem Solving and Python Programming full study material.
print(a)
string built in functions and methods:
A method is a function that “belongs to” an object.
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.
26 Unit 3:control flow, functions
www.BrainKart.com
Click Here for Problem Solving and Python Programming full study material.
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.
Standard modules can be imported the same way as we import our user-defined
modules.
Syntax:
import module_name
Example output
import string
print(string.punctuation) !"#$%&'()*+,-./:;<=>?@[\]^_`{|}~
print(string.digits) 0123456789
print(string.printable) 0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJ
print(string.capwords("happ KLMNOPQRSTUVWXYZ!"#$%&'()*+,-
y birthday")) ./:;<=>?@[\]^_`{|}~
print(string.hexdigits) Happy Birthday
print(string.octdigits) 0123456789abcdefABCDEF
01234567
27 Unit 3:control flow, functions
www.BrainKart.com
Click Here for Problem Solving and Python Programming full study material.
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)
www.BrainKart.com
Click Here for Problem Solving and Python Programming full study material.
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)
Methods in array
a=[2,3,4,5]
www.BrainKart.com
Click Here for Problem Solving and Python Programming full study material.
4 elements in an array
ILLUSTRATIVE PROGRAMS:
Square root using newtons method: Output:
def newtonsqrt(n): enter number to find Sqrt: 9
root=n/2 3.0
for i in range(10):
root=(root+n/root)/2
print(root)
n=eval(input("enter number to find Sqrt: "))
newtonsqrt(n)
GCD of two numbers output
n1=int(input("Enter a number1:")) Enter a number1:8
n2=int(input("Enter a number2:")) Enter a number2:24
for i in range(1,n1+1): 8
if(n1%i==0 and n2%i==0):
gcd=i
print(gcd)
Exponent of number Output:
def power(base,exp): Enter base: 2
if(exp==1): Enter exponential value:3
return(base) Result: 8
else:
return(base*power(base,exp-1))
base=int(input("Enter base: "))
exp=int(input("Enter exponential value:"))
result=power(base,exp)
print("Result:",result)
sum of array elements: output:
a=[2,3,4,5,6,7,8] the sum is 35
sum=0
for i in a:
sum=sum+i
print("the sum is",sum)
Linear search output
a=[20,30,40,50,60,70,89] [20, 30, 40, 50, 60, 70, 89]
print(a) enter a element to search:30
search=eval(input("enter a element to search:")) element found at 2
for i in range(0,len(a),1):
if(search==a[i]):
print("element found at",i+1)
break
else:
print("not found")
www.BrainKart.com
Click Here for Problem Solving and Python Programming full study material.
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.
www.BrainKart.com
Click Here for Problem Solving and Python Programming full study material.
www.BrainKart.com