Académique Documents
Professionnel Documents
Culture Documents
Introduction
In order to tell the computer ‘what is to be done’, a computer program is written in HLL (High Level
Language) such as BASIC, Pascal, C, C++, Java, Haskell, Ruby, Python etcetera. Python will be studied in this
course enforced by the CBSE.
History
Python was created by Guido Van Rossum when he was working at CWI (Centrum Wiskunde &
Informatica) which is a National Research Institute for Mathematics and Computer Science in Netherlands.
The language was released in I991. Python got its name from a BBC comedy series from seventies- “Monty
Python's Flying Circus”. Python can be used to follow both Procedural approach and Object Oriented
approach of programming. It is open source and free to use.
Interactive Mode
On starting Python IDLE on a computer, the following window appears:
What one see is a welcome message of Python interpreter with revision details and the Python prompt,
pg. 1
i.e., ">>>". This is a primary prompt indicating that the interpreter is expecting a python command. There is
secondary prompt also which is "…" indicating that interpreter is waiting for additional input to complete
the current statement. Interpreter uses prompt to indicate that it is ready for instruction. Therefore, we
can say, if there is prompt on screen, it means IDLE is working in interactive mode. We type Python
expression|statement|command after the prompt and Python immediately responds with the output of it.
Let’s start with typing print("How are you?") after the prompt.
>>>print("How are you?")
How are you?
The last line is Python’s response.
pg. 2
parenthesis will allow us to enter an interactive help mode. And with a name (predefined) in bracket
will give us details of the referred word.
To leave the help mode and return back to interactive mode, quit command can be used.
Script Mode
In script mode, the Python program is written in a file and then interpreter is used to execute the content
from the file. Working in interactive mode is convenient for beginners and for testing small pieces of code,
as one can test them immediately. But for coding more than few lines, one should always save code so that
one may modify and reuse the code. Result produced by Interpreter in both the modes- interactive and
script mode is exactly same.
Process of Writing (i.e. Creating) a Python Program (i.e. Python Script) and Running it
To create and run a Python script, we will use following steps in IDLE, if the script mode is not made
available by default with IDLE environment.
1. File>Open OR File>New Window (for creating a new script file)
2. Write the Python code as script
3. Save as (ctrl+shift+S) first time and ^S second time onward
4. Execute it by using RUN option (F5).
[Note: For every updation of script file, we need to repeat step 3 & step 4]
If we write Example1 (given above) in script mode, it will be written in the following way:
Step 1: File> New Window
Step 2:
x=2
y=6
z = x+y
print z
Step 3:
Use File > Save or File > Save As - option for saving the file. Suppose, it saved as “myfirstprog.py”
(By convention all Python program files have names which end with .py)
Step 4:
For execution, press ^F5, and we will go to Python prompt in other window.
>>> myfirstprog.py # this is not required to be typed. It will appear automatically
8
Alternatively we can execute the script directly by choosing the RUN option.
Note: While working in script mode, we add ‘print’ statement in our program to see the results which
otherwise were displayed on screen in interactive mode without typing such statements.
pg. 3
i) Identity of the variable: It is the variable's address in memory and does not change once it has been
created.
ii) (Data) Type of Variable: It is a set of values, and the allowable operations on those values. It can be
one of the following as per CBSE syllabus:
a. integer b. float c. string d. list e. tuple f. dictionary
Currently, we will pay attention to integer, float and string data types only. List, tuple and dictionary will be
introduced and will be discussed later in this chapter.
Integer
Integers are the whole numbers consisting of + or – sign with decimal digits like 100000, -99, 0, 17. While
writing a large integer value, don’t use commas to separate digits. Also integers should not have leading
zeros.
When we are working with integers, we need not to worry about the size of integer as a very big integer
value is automatically handled by Python. When we want a value to be treated as very long integer value,
append L to the value. Such values are treated as long integers by python.
>>> a = 10
>>> b = 5192L #example of supplying a very long value to a variable
>>> c= 4298114
>>> type(c) # type ( ) is used to check data type of value
<type 'int'>
>>> c = c * 5669
>>> type(c)
<type 'long'>
Note: We can know the largest integer in our version of Python by following the given set of commands:
>>> import sys
>>> print sys.maxint
Floating Point
Numbers with fractions or decimal point are called floating point numbers. A floating point number will
consist of sign (+,-) sequence of decimals digits and a dot such as 0.0, -21.9, 0.98333328, 15.2963. These
numbers can also be used to represent a number in engineering|scientific notation. -2.0X 105 will be
represented as -2.0e5. 2.0X10-5 will be 2.0E-5.
Example
y= 12.36
Note: A value when stored as floating point in Python will have 53 bits of precision.
String
The string is an ordered sequence of letters/characters. They are enclosed in single quotes (' ') or double
(" " ). The quotes are not part of string. They only tell the computer where the string constant begins and
ends. They can have any character or sign, including space in them. These are immutable data types. We
will learn about immutable data types while dealing with third aspect of object i.e. value of object.
Example
>>> a = 'Ram'
A string with length 1 represents a character in Python.
Lists (mutable):
List is also a sequence (i.e. an ordered collection of items, indexed by positive integers) of values of any
type. Values in the list are called elements|items. These are mutable and indexed|ordered. List is enclosed
in square brackets.
Example- l = [‘spam’, 20.5, 5]
Tuples (immutable)
Tuples are a sequence of values of any type, and are indexed by integers. They are immutable. Tuples are
enclosed in (). We have already seen a tuple. Example- (4, 2).
Dictionaries:
Dictionary can store any number of python objects. What they store is a key–value pairs, which are
accessed using key. Dictionary is enclosed in curly brackets.
Example- d = {1:'a', 2:'b', 3:'c'}
iii) Value of Object: In order to bind value to a variable, we use assignment operator (=). This is also
known as building of a variable. Example-
>>> pi = 3.1429
Here, value on RHS of '=' is assigned to newly created 'pi' variable.
Keywords
They are the words used by Python interpreter to recognize the structure of program. As these words have
specific meaning for interpreter, they cannot be used for any other purpose.
Remember:
Variables are created when they are first assigned a value.
Variables must be assigned a value before using them in expression,
Variables refer to an object and are never declared ahead of time.
Relational Operators
Symbol Description Example 1 Example 2
< Less than >>>7<10 >>> 'Hello' < 'Goodbye'
True False
>>> 7<5 >>>'Goodbye'< 'Hello'
False True
>>> 7<10<15
True
>>>7<10 and 10<15
True
> Greater than >>>7>5 >>> 'Hello' > 'Goodbye'
True True
>>>10<10 >>>'Goodbye'> 'Hello'
False False
<= less than equal to >>> 2<=5 >>> 'Hello '<= 'Goodbye'
True False
>>> 7<=4 >>>'Goodbye' <= 'Hello'
False True
pg. 7
>= greater than equal to >>>10>=10 >>>'Hello'>= 'Goodbye'
True True
>>>10>=12 >>>'Goodbye' >= 'Hello'
False False
! =, <> not equal to >>>10!=11 >>>'Hello'!= 'HELLO'
True True
>>>10!=10 >>> 'Hello' != 'Hello'
False False
== equal to >>>10==10 >>>'Hello' == 'Hello'
True True
>>>10==11 >>>'Hello' == 'Good Bye'
False False
Note: Two values that are of different data type will never be equal to each other.
Logical Operators
Symbol Description
not Reverses the state of operand/condition.
or If any one of the operand is true, then the condition becomes true.
and If both the operands are true, then the condition becomes true.
Assignment Operators
Assignment Operator combines the effect of arithmetic and assignment operator
Symbol Description Example Explanation
= Assigned values from right >>>x=12
side operands to left variable >>>y='greetings'
(we will 12 as initial value of x for each of the following examples)
+= added and assign back the >>>x+=2 The operand|expression|constant wr-
result to left operand itten on RHS of operator will change
the value of x to 14
-= subtracted and assign back >>>x-=2 x will become 10
the result to left operand
*= multiplied and assign back >>>x*=2 x will become 24
the result to left operand
/= divided and assign back the >>>x/=2 x will become 6
result to left operand
%= taken modulus using two >>>x%=2 x will become 0
operands and assign the
result to left operand
**= performed exponential >>>x**=2 x will become 144
(power) calculation on
operators and assign value to
the left operand
pg. 8
//= performed floor division on >>>x//=2 x will become 6
operators and assign value to
the left operand
Note:
1. Same operator may perform a different function depending on the data type of the value to which it is
applied.
2. Division operator '/' behaves the same way on integer and float values.
Expression in Python
An expression is a combination of value(s) (i.e. constant), variable and
operators. It generates a single value, which by itself is an expression. To
illustrate this, an example is given at RHS. The expression is solved by
computer and gets its value. In this example, it will be 4, and we say the
expression is evaluated.
Note: Expression values in turn can act as, Operands for Operators
We have seen many such expressions (with list of operator as example). 10+5 and 9+4+2 are two
expressions which will result into value 15. Taking another example, 5.0/4+ (6- 3.0) is an expression in
which values of different data types are used, and therefore known as mixed type expressions. When
mixed type expressions are evaluated, Python promotes the result of lower data type to higher data type,
i.e. to float in the above example. This is known as implicit type casting. So the result of above expression
will be 4.25. Expression can also contain another expression. As we have already seen in 9+4+2. When we
have an expression consisting of sub expression(s), Python evaluates it based on precedence of operator.
Higher precedence operator is worked on before lower precedence operator. Operator associativity
determines the order of evaluation when they are of same precedence, and are not grouped by
parenthesis. An operator may be Left-associative or Right-associative. In left associative, the operator
falling on left side will be evaluated first; while in Right-associative, operator falling on right will be
evaluated first. In Python '= ' and '**' are Right-associative.
Table: Precedence of Operators– [useful to find which (sub) expression should be evaluated first]
Operator Description Precedence
** Exponentiation (raise to the power) highest
+, - unary plus and minus
* , /, %, // Arithmetic operators
+, -
<, <=, >, >= Relational operators
==, !=
=, %=, /=, //= , -=, +=, *= Assignment operators
not Logical operators
and
or lowest
Using the above table, we know that 9+4 itself is an expression which evaluates to 13 and then 13+2 is
evaluated to 15 by computer. Similarly, 5.0/4 + (6-3.0) will be evaluated as 5.0/4+3.0 and then to 1.25 +
3.0, and then 4.25.
If we just type 10+, we will get an error message. This happens because 10+ is not a complete expression. A
complete expression will always have appropriate number of value (Operands) with each operator. '+'
needs two operands and we have given just one.
pg. 9
A Python statement is a unit of code that the Python interpreter can execute. Python statement terminates
at the end of line (i.e. when new line character encounters).
Examples of simple statement Examples of Compound Statement
>>> x=5 #Example01
>>> area=x**2 #assignment statement if i<0:
>>>print x #print statement print "i is negative"
5 else:
>>>print area print "i is non-negative"
25 #Example02
>>> print x, area #to print multiple items if i>0:
5 25 print "i is positive"
else:
print "i is equal to 0"
Above at LHS, we see examples of simple statements, i.e. they do not contain a nested block. In Python,
there are compound|group statements also. They are sometimes called nested block. Statements
belonging to a block are indented (usually by 4 spaces). Leading whitespace at the beginning of line is used
to determine the indentation level of line. That means statement(s) which go together must have same
indentation level. Compound statements are given above at RHS.
While writing Python statements, keep the following points in mind:
1. Write one python statement per line (Physical Line). However, it is possible to write two statements
in a line separated by semicolon.
2. Comment starts with '#' outside a quoted string and ends at the end of a line. Comments are not part
of statement. They may occur on the line by themselves or at the end of the statement. They are not
executed by interpreter.
3. For a long statement, spanning multiple physical lines, we can use '/' at the end of physical line to
logically join it with next physical line. Use of the '/' for joining lines is not required with expression
consists of ( ), [ ], { }
4. When entering statement(s) in interactive mode, an extra blank line is treated as the end of the
indented block.
5. Indentation is used to represent the embedded statement(s) in a compound|grouped statement. All
statement(s) of a compound statement must be indented by a consistent no. of spaces (usually 4)
6. White space in the beginning of line is part of indentation, elsewhere it is not significant.
For output in Python we use print. We have already seen its usage in previous examples. Let's learn more
about it.
Print Statement
Syntax:
print expression|constant|variable
Print evaluates the expression before printing it on the monitor. Print statement outputs an entire
(complete) line and then goes to next line for subsequent output(s). To print more than one item on a
single line, comma (,) may be used.
Example
>>> print "Hello"
Hello
>>> print 5.5
5.5
>>> print 4+6
10
Try this on the computer and evaluate the output generated
>>>print 3.14159* 7**2
>>>print "I", "am" + "class XI", "student"
>>>print "I' m",
>>>print "class XI student"
>>>print "I' m", 16, "years old"
Comments
As the program gets bigger, it becomes difficult to read it, and to make out what it is doing by just looking
at it. So it is good to add notes to the code, while writing it. These notes are known as comments. In
Python, single-line comment starts with '#' symbol. Anything written after # in a line is ignored by
pg. 11
interpreter, i.e. it will not have any effect on the program. A comment can appear on a line by itself or they
can also be at the end of line.
Example
# Calculating area of a square
>>> area = side **2
or
>>>area= side**2 #calculating area of a square
For adding multi-line comment in a program, we can:
i) Place '#' in front of each line, or
ii) Use triple quoted string. They will only work as comment, when they are not being used as docstring.
(A docstring is the first thing in a class|function|module, and will be taken up in details when we
study functions in XII standard, only if CBSE syllabus permits).
The comment line "#calculating area of a rectangle" can also be written as following using triple quote:
i) """Calculating area of a rectangle"""
ii) """ Calculating area
of a rectangle"""
We should use as many useful comments as we can, to explain
Any assumptions made
Important details or decisions made in the program. This will make program more readable.
EXERCISE
1. Create following Variables
i) 'mystring' to contain 'hello' ii) 'myfloat' to contain '2.5'
iii) 'myint' to contain '10'
2. Write the value justification
i) 2*(3+4) ii) 2*3+4
iii) 2+3*4
3. What is the type of the following result?
i) 1+2.0+3
4. Which of the following is the valid variable name?
i) global ii) 99flag
iii) sum iv) an$wer
5. True or False
i) Character Data type values should be delimited by using the single quote.
ii) Python does not have any keywords.
iii) The += operator is used to add the right hand side value to the left hand side variable.
iv) The equal to condition is written by using the == operator
6. Which input statements are syntactically correct?
i) a = raw_input ( ) ii) a = raw_input (“enter a number”)
iii) a = raw_imput (enter your name)
7. Which print statements are syntactically correct?
i) _print "9" + "9" ii) _print int("nine")
iii) _print 9+9 iv) print 9
8. Which are correct arithmetical operations?
i) a = 1*2 ii) 2 = 1+1
pg. 12
iii) 5 + 6 = y iv) Seven = 3 * 4
9. Which are correct type conversions?
i) int (7.0+0.1) ii) str (1.2 * 3.4)
iii) float (“77”+“.0”) iv) str ( 9 / 0 )
10. Which operations result in 8?
i) 65 // 8 ii) 17 % 9
iii) 2 * * 4 iv) 64 * * 0.5
11. Which lines are commented?
i) “””This is a comment””” ii) # This is a comment
iii) // this is a comment iv) ‘’’ This is a comment’’’
12. Find the matching pairs of expressions and values.
i) 1023 str
ii) 17.54 int
iii) “my fat cat” float
13. If the value of a = 20 and b = 20, then a+=b will assign ________ to a
i) 40 ii) 30
iii) 20 iv) 10
14. The ____________ operator is used to find out if division of two number yields any remainder
i) / iii) +
iii) % iv) //
15. When will following statement in interpreter result into error:
>>> B+4
17. Is python case sensitive?
18. What does ‘immutable’ mean; which data type in python are immutable.
19. Name three of Python’s Basic data types? Why are they called so?
20. What are relational operators? Explain with the help of examples.
21. What is an integer?
22. What is a variable? What names may variable have?
23. How are keywords different from variable names?
24. Why are data types important?
25. How can you convert a string to integer and when can it be used?
26. How can text be read from the keyboard?
27. How are comments written in a program?
LAB EXERCISE
1. Record what happens when following statements are executed:
a) print n=7
b) print 5+7
c) print 5.2, “this”, 4-2, “that”, 5/2.0
2. Use IDLE to calculate:
a) 6+4*10
b) (6+4)*10
3. Type following mathematical expression and record your observations:
a) 2**500
b) 1/0
pg. 13
4. What will be the output of the following code:
a = 3 - 4 + 10
b=5*6
126
c = 7.0/8.0
print "These are the values:", a, b, c
5. Write a code to show the use of all 6 math function.
6. Write a code that prints your full name and your Birthday as separate strings.
7. Write a program that asks two people for their names; stores the names in variables called name1
and name2; says hello to both of them.
8. Calculate root of the following equation:
a) 34x2 + 68x – 510 = 0
b) 2x2 - x -3 = 0
pg. 14
CONDITIONAL CONSTRUCT
Depending upon time of the day, you wish Good Morning or Good Night to people. Similarly while writing
program(s), we almost always need the ability to check the condition and then change the course of
program. The simplest way to do so is using if statement
if statement if-else statement Nested if statement If-elif-else statement
if statement
Syntax Flow Chart
if Condition1:
sti1
…
stim
Where;
if : Python keyword
Condition1 : Boolean expression
Stij : jth statement in the body of if,
where j = 1 to m
From the flowchart it is clear that if the Condition1 is true, statement is executed; otherwise it is skipped.
The statement may either be a single or compound statement.
if-else statement
Syntax Flow Chart
if Condition1:
sti1
…
stim
else:
ste1
…
sten
Where;
if, else : Python keyword
Condition1 : Boolean expression
stij : jth statement in the body of if, where j = 1 to m
stek : kth statement in the body of else, where k = 1 to n
From the above flowchart, it is clear that the given Condition1 is evaluated first. If the Condition1 is true,
statements sti1 to stim are executed. If the Condition1 is false, statements ste1 to sten are executed.
pg. 15
Nested if (with or without else clause) statement
The if block (with or without else clause) may be nested in another if or else block. This is called nesting of
if (with or without else clause).
Syntax Flow Chart
if Condition1:
if Condition2:
sti21
…
sti2m
[else:
ste21
…
ste2n ]
else:
ste11
…
ste1k
If Condition1:
sti11
…
sti1k
else:
if Condition2:
sti21
…
sti2m
[else:
ste21
…
ste2n]
if-elif-else statement
Syntax Flow Chart
pg. 16
if Condition1:
sti1
…
stik
elif Condition2:
ste21
…
ste2m
else:
ste21
…
ste2n
A few important things to note about conditional construct
The colon(:) is significant and required. It separates the header of the compound statement from
the body.
The line after the colon must be indented. It is standard in Python to use four spaces for indenting.
All lines indented the same amount after the colon will be executed whenever the CONDITION is
true.
Solved Examples on Conditional Construct
1. WAP in Python to determine whether the seller has made profit or incurred loss. Also determine how
much profit he made or loss he incurred. Cost price and selling price of an item is input by the user
#! profitLooss.py
pg. 18
c=int(input('Enter, Third Number: '))
if a>b and a>c:
big=a
if b>c and b>a:
big=b
if c>a and c>b:
big=c
print('Biggest Number is: ', big)
5. WAP in Python to accept total marks secured by Percentage of Marks Grade
students out of 500 and display the grade he/she >=80.0 A
achieved using the criteria given at RHS: >=60.0 to 79.9 B
>=50.0 to 59.9 C
>=40.0 to 49.9 D
<40.0 E
pg. 19
print('Grade achieved : ', grade)
6. #WAP in Python to accept a week day number from the keyboard and display its day name in words
#! dayName.py
if leapYear==True:
print('Given Year', y, ' is Leap Year')
else:
print('Given Year', y, ' is not Leap Year')
9. WAP in Python to accept a character from the keyboard and display whether it is a digit or lower case
alphabet or uppercase alphabet.
#Check if entered character is digit or lowercase alphabet or uppercase alphabet
#!checkDigitLAlpaUAlpha
ch=input('Enter a Character (Digit or Alphabet (Lower/Upper: ')
if ch>='0' and ch<='9':
print('Entered character is a DIGIT')
elif ch>='A' and ch<='Z':
print('Entered character is a UPPERCASE ALPHABET')
elif ch>='a' and ch<='z':
print('Entered character is a LOWERCASE ALPHABET')
else:
print('Entered character is other than DIGIT and ALPHABET')
10. WAP in Python to input any choice(1-3) and compute the area of corresponding geometrical figure:
Choice Compute
1. Area of square
2. Area of rectangle
3. Area of triangle
#! Area_GeoFigure.py
print("Choice\tCompute")
print("1.\tArea of square")
print("2.\tArea of rectangle")
print("3.\tArea of triangle")
c = int(input ("Enter any Choice: "))
if(c==1):
s = float(input("Enter any side of the square:"))
a = s*s
print("Area = ",a)
elif(c==2):
l = float(input("Enter length: "))
b = float(input("Enter breadth: "))
a = l*b
pg. 21
print("Area = ",a)
elif(c==3):
x = float(input("Enter first side of triangle: "))
y = float(input("Enter second side of triangle: "))
z = float(input("Enter third side of triangle: "))
s = (x+y+z)/2
a = (s*(s-x)*(s-y)*(s-z))**0.5
print("Area=",a)
else:
print("Wrong Input")
11. # WAP in Python to accept an alphabet and display whether it is vowel or Consonant.
#!checkVowelConsonant.py
if vowel==True:
print("You entered a vowel")
elif consonant==True:
print("You entered a consonant")
else:
print("You entered other than alphabet")
12. WAP in Python to accept a choice of temperature conversion as per given criteria given below. Also
display the converted
temperature value on screen upto 2 decimal places
Choice Input Value (in) Converted Value (in)
1. Celsius Fahrenheit
2. Fahrenheit Celsius
Note: C=(F-32)/1.8; Where C is Celsius and F is Fahrenheit
#! tempConversion.py
print("Choice\tInput Value (in)")
print("1.\tCelsius")
print("2.\tFahrenheit")
ch=int(input("Enter Your Choice: "))
if ch==1:
C=float(input("Enter Temperature in Celsius: "))
F=int((C*1.8 +32)*100)/100.0
pg. 22
print("Converted Temperature in Fahrenheit=", F, "deg F" )
elif ch==2:
F=float(input("Enter Temperature in Fahrenheit: "))
C=int((F-32)/1.8*100)/100.0
print("Converted temperature in Celsius=", C, "deg C" )
else:
print("Wrong Choice!!!")
13. WAP in Python to accept monthly salary and compute the expected income tax as per criteria given
below:
Annual Income (Rs) Tax (in %)
250000 0.0
250001-500000 10.0
500001-1000000 20.0
>1000000 30.0
Display Annual Salary and Income Tax
#!computeTax.py
mSal=float(input("Enter, Your Monthly Salary: "))
tax=0.0
if 12*mSal<=250000:
tax +=0.0
elif 12*mSal<=500000:
tax=0.0 + (12*mSal-250000)*0.10
elif 12*mSal<=1000000:
tax=0.0 + 25000 + (12*mSal-500000)*0.20
elif 12*mSal>1000000:
tax=0.0 + 25000 + 100000 + (12*mSal-1000000)*0.30
print("Annual Income (Rs): ", 12*mSal)
print("Total Tax= ", tax)
14. WAP in Python to calculate the monthly telephone bills as per the following rule:
Minimum Rs. 200 for first 100 calls. Plus Rs. 0.60 per call for next 50 calls. Plus Rs. 0.50 per call for
next 50 calls. Plus Rs. 0.40 per call for any call beyond 200 calls. 5% is the education cess applied on
the bill. 6% is the cleanliness cess applicable on the bill. 7% per annum is your interest gain on the
security money (Rs. 3000/-) that is to be adjusted with the bill.
#! telephoneBill.py
pg. 23
eduCess= 5.0*charges/100.0
cleanlinessCess=6.0*charges/100.0
intrestOnSecurity=7.5*3000.0/(12*100.0)
totalBill = charges + eduCess + cleanlinessCess - intrestOnSecurity
flatCharges=150.0
units=int(input("Enter the number of units consumed : "))
if units<=100:
charges = (units*4.0) + flatCharges
else:
if units<=300:
charges = 100*4.0 + (units-100)*6.0 + flatCharges
else:
if units > 300:
charges = 100*4.0 + 200*6.0 + (units-300)*8.0 + flatCharges
if a>b:
t=a
a=b
b=t
if b>c:
t=b
b=c
c=t
if c<low:
low=c
if a>b:
high=a
else:
high=b
if c>high:
high=c
pg. 26
0-10000 0%
#!computeCommission.py
salesMade=float(input("Enter, the sales made (Rs.): "))
if salesMade>50000:
comm=0.25*salesMade
elif salesMade>40000:
comm=0.20*salesMade
elif salesMade>30000:
comm=0.15*salesMade
elif salesMade>20000:
comm=0.10*salesMade
elif salesMade>10000:
comm=0.05*salesMade
else:
comm=0.00*salesMade
print("Commission on Sales Made(Rs.): ", comm)
21. WAP in Python to check a triangle is equilateral, isosceles or scalene. Three sides of triangle are
provided as inputs.
Note: An equilateral triangle is a triangle in which all three sides are equal. A scalene triangle is a
triangle that has three unequal sides. An isosceles triangle is a triangle with (at least) two equal sides.
#! checkTriangleType.py
print("Input lengths of the triangle sides: ")
x = int(input("x: "))
y = int(input("y: "))
z = int(input("z: "))
if x == y == z:
print("Equilateral triangle")
elif x != y != z:
print("Scalene triangle")
else:
print("isosceles triangle")
22. WAP in Python to accept three sides (a, b, c) of a triangle and find out whether (a, b, c) forms a
Pythagorean triple.
Note: A triangle whose sides form a Pythagorean triple is called a Pythagorean triangle, and is
necessarily a right triangle.
#! pythagoreanTriple.py
a=float(input("Enter, First side: "))
b=float(input("Enter, Second side: "))
c=float(input("Enter, Third side: "))
pythagoreanTriple=False
if a**2 + b**2 == c**2:
pythagoreanTriple=True
if b**2 + c**2 == a**2:
pythagoreanTriple=True
pg. 27
if c**2 + a**2 == b**2:
pythagoreanTriple=True
if pythagoreanTriple==True:
print("a= ", a, ", b= ", b," c= ",c, " forms a Pythagorean triple")
else:
print("a= ", a, ", b= ", b," c= ",c, " does not form a Pythagorean triple")
23. WAP in Python to accept length (a, b, c) of three lines and find out whether (a, b, c) forms a triangle.
Note: If a, b, and c are the lengths of the three sides of a triangle, then all three inequalities must hold
good. i.e. a+b>c, b+c>a and c+a>b
#!checkTriangleFormation.py
a = float(input("Enter length of first line: "))
b = float(input("Enter length of second line: "))
c = float(input("Enter length of third line: "))
inequalities=0
if a+b>c:
inequalities += 1
if b+c>a:
inequalities += 1
if c+a>b:
inequalities += 1
if inequalities==3:
print("Given three lines form the triangle")
else:
print("Given three lines do not form the triangle")
24. Develop a Compound Interest Calculator application in Python as per given two tables hereunder, to
calculate total amount for given Amount, Rate of Interest and Time using (A=P(1+R/100) T ) and
Interest I=A-P.
COMPOUND INTEREST COMPUTATION CRITERIA SPECIAL INCENTIVE CRITERIA
Principal Fix Deposit Rate of Specialty being Remark
Amount (Rs) Years Interest (%)
<=100000 1 to 3 7.5 Female 0.75% Extra ROI
>3 to 5 8.5 Senior Citizen 0.75% Extra ROI
>5 to 10 9.0
100001 to 500000 1 to 3 7.25 Note: Extra ROI (Rate of interest)
>3 to 5 8.25 cannot exceed 1.25%
>5 to 10 8.75
>500000 >0 7.50
#!compoundInterestCalculator.py
p=float(input("Enter, Principal Amount (Rs.): "))
t=float(input("Enter, Number of Terms For Fix Deposit(Years): "))
specility=int(input("Enter, Your Specilty such as Female|Sr Citizen|Both(1|2|3: "))
if p<=100000:
if t<=3:
r=7.5
pg. 28
elif t<=5:
r=8.5
elif t<=10:
r=9.0
else:
print("Scheme is not available for more than 10 years!!!")
elif p<=500000:
if t<=3:
r=7.5
elif t<=5:
r=8.5
elif t<=10:
r=9.0
else:
print("Scheme is not available for more than 10 years!!!")
elif p>500000:
r=7.50
else:
print("Wrong Choice of Principlal Amount!!!")
if specility==1:
extraROI=0.75
elif specility==2:
extraROI=0.75
elif specility==3:
extraROI=1.25
else:
extraROI=0.0
effectveRI=r+extraROI
A=p*((1+extraROI/100.0)**t)
A=int((A*100))/100.0
I=A-p
I=int((I*100))/100.0
print("Accummulative Amount (Rs.): ", A)
print("Interst (Rs.): ", I)
25. A Quick Fox Transport Company wants to develop an application in Python for calculating amount
based on distance and weight of goods. The charges (Amount) to be calculated as per rates given
below:
Distance (in Km.) Weight (in Kg.) Charges/Km (in Rs.) Total Amount (in Rs)
(Only an Example)
>=800 >=500 12 9600 (if distance=800 Km)
>=100 and <500 10 8000 (if distance=800 Km)
<100 8 6400 (if distance=800 Km)
<800 >=500 11 8789 (if distance=799 Km)
<500 9 7191 (if distance=799 Km)
pg. 29
#!amountBasedOnDist_n_Weight.py
distance=float(input("Enter, distance to be covered by transporter (in Km): "))
weight=float(input("Enter, weight to be carried by transporter (in Kg): "))
if distance>=500:
if weight>=100:
charges=5
elif weight>100 and weight<=10:
charges=6
else:
charges=7
elif distance<500:
if weight>=100:
charges=8
else:
charges=5
amount=charges*distance
print("Total amount payable: ", amount)
26. Develop a Billing application in Python for Happy shopping-- A retail chain involved in sales of Ready-
made garments (e.g. Shirts, Trousers, T-shirts, Blazers, Sport Shoes etc.). The happy shopping offers
discount to its members holding Platinum, Gold and Silver card. The 10% discount is given to
Platinum card, 8% to Gold Card and 5% to Silver Card holders on sales amount. The application gets
input for ‘Item Name’, ‘Rate of Item /Unit’, ‘Number of items purchased’ and computes ‘Net Amount
Payable’.
#!happyShoppingBill
itemName=input("Enter, Item Name: ")
rateOfItem=float(input("Enter, Rate of Item/Unit: "))
noOfItems=int(input("Enter, No. of Items Purchased: "))
cardType=int(input("Enter, Card Type(Platinum|Gold|Siver as 1|2|3): "))
salesAmount=rateOfItem*noOfItems
if cardType==1:
discount=10.0
if cardType==2:
discount=8.0
if cardType==3:
discount=5.0
discountedAmount=salesAmount*discount/100.0
netPayableAmount=salesAmount-discountedAmount
print("=====H A P P Y S H O P I N G B I L L=====")
print("Item Name : ", itemName)
print("Quantity : ", noOfItems)
print("Sales Amount(Rs.) : ", salesAmount)
print("Discounted Amount(Rs.) : ", discountedAmount, " @",discount,"%")
print("Net Payable Amount(Rs.) : ", netPayableAmount)
27. The Entertainment Paradise- A theatre in Delhi wants to develop a computerized Booking System in
pg. 30
Python. The theatre offers different types of seats. The Ticket rates and payment rates are:
Seat Type Rate/Seat (Rs.) Payment Mode Discount (in %)
Stalls 625 Cash 6
Circle 750 Credit Card 8
Upper Class 850 Internet 10
Box 1000
The application gets input as Seat Type, Mode Type and Number of seats to be booked. Kindly,
produce the bill for Entertainment Paradise Theatre as net payable amount after applying
appropriate discount.
#!theatreBookingBill.py
name=input("Enter, your name: ")
seatType=int(input("Enter, seat type such as stalls|circle|upper class|box (1|2|3|4): "))
paymentMode=int(input("Enter, paymant mode such as cash|credit card|internet (10|20|30): "))
numOfSeatsBooked=int(input("Enter, number of seats to be booked: "))
if seatType==1:
seatTypeDescption='Stalls, Rs. 625/seat'
ratePerSeat=625.0
elif seatType==2:
seatTypeDescption='Circle, Rs. 750/seat'
ratePerSeat=750.0
elif seatType==3:
seatTypeDescption='Upper Class, Rs. 850/seat'
ratePerSeat=850.0
elif seatType==4:
seatTypeDescption='Box, Rs. 1000/seat'
ratePerSeat=1000.0
else:
print("Wrong Seat Type Selected!!!", ratePerSeat)
if paymentMode==10:
discountPercentage=6.0
elif paymentMode==20:
discountPercentage=8.0
elif paymentMode==30:
discountPercentage=10.0
else:
print("Wrong Payment Mode Selected!!!")
bookingAmount=numOfSeatsBooked*ratePerSeat
discountedAmount=bookingAmount*discountPercentage/100.0
netPayableAmount=bookingAmount-discountedAmount
print("")
print("=====T H E A T R E B O K I N G B I L L=====")
print("Name Who Booked Seats : ", name)
print("Seat Type Description : ", seatTypeDescption)
print("No of Seats Booked : ", numOfSeatsBooked)
print("Booking Amount(Rs.) : ", bookingAmount)
print("Discounted Amount(Rs.) : ", discountedAmount, " @",discountPercentage,"%")
pg. 31
print("=================================================")
print("Net Payable Amount(Rs.) : ", netPayableAmount)
28. The Milton Casting Company has developed an application in Python to calculate the wage of its
workers. Calculated total wage is displayed on the screen. The following functionalities are expected:
a) The Wage rate are Rs.150/- (per day) for male and Rs.130/- for females.
b) An additional amount Rs.50/- per day is paid if worker is skilled.
#! wageCalculator.py
name=input("Enter, worker name: ")
gender=int(input("Enter, gender of worker(male|female) as (1|2): "))
workerSkill=int(input("Enter, 0 if worker is unskilled or 1 if skilled: "))
noOfWorkingkDays=int(input("Enter number of working days: "))
if gender==1:
wageRate=150
genderStr='Male'
elif gender==2:
wageRate=130
genderStr='Female'
else:
print("Wrong Gender value Entered!!!")
if workerSkill==0:
additionalAmt=0
skillStr='Un-Skilled'
elif workerSkill==1:
additionalAmt=50
skillStr='Skilled'
else:
print("Wrong skill entered!!!")
effectiveRate=wageRate+additionalAmt
totalWage=noOfWorkingkDays*effectiveRate
print("")
print("*****P A Y S L I P F O R W R K E R S*****")
print("Name of Worker : ", name)
print("Gender of Worker : ", genderStr)
print("No of Working Days : ", noOfWorkingkDays)
print("Skill of Worker : ", skillStr)
print("Effective Wage Rate(Rs./day) : ", effectiveRate)
print("=============================================")
print("Total Wage (Rs.) : ", totalWage)
29. The Fashion Gallery- a leading garments shop wants to develop an application in Python to calculate
the discount amount and net amount when bill amount is provided as input. The produced bill must
be displayed on the screen. The discount is given
on the basis on payment mode:
Cash – 10.0%, Cheque – 8.0% and Credit – 5.0% of bill amount.
If Bill amount is more than 10000 then additional 5% discount is also given.
#!fashionGalleryBill.py
custName=input("Enter Customer Name: ")
pg. 32
billAmt=float(input("Enter Bill Amount (Rs.): "))
paymentMode=int(input("Enter Payment Mode(Cash|Cheque|Ctredit) as 1|2|3: "))
if paymentMode==1:
discRate=10.0
paymentModeStr='Cash (10.0% Discount)'
if paymentMode==2:
discRate=8.0
paymentModeStr='Cheque (8.0% Discount)'
if paymentMode==3:
discRate=5.0
paymentModeStr='Cheque (5.0% Discount)'
if billAmt>10000:
additionalDiscRate = 5.0
else:
additionalDiscRate = 0.0
effectiveDiscRate = discRate + additionalDiscRate
totalDisc = billAmt*effectiveDiscRate/100.0
netAmt=billAmt - totalDisc
print("")
print("*****F A S H I O N G A L L E R Y B I L L*****")
print("Name of Customer : ", custName)
print("Payment Mode : ", paymentModeStr)
print("Bill Amount (Rs.) : ", billAmt)
print("Normal Discount (Rs.) :\t ", billAmt*discRate/100.0)
print("Additional Discount (Rs.) :\t ", billAmt*additionalDiscRate/100.0)
print("Toatl Discount (Rs.) : ", totalDisc)
print("=====================================================")
print("Net Amount Payable(Rs.) : ", netAmt)
30. Seema is a junior programmer at 'Avon Shoe Factory'. She developed an application in Python using
following data:
• 3 items namely Shoes(code 101), Sandals(code 102) and Slippers(code 103) are manufactured
by the factory.
• A buyer can buy more than one item at a time.
• Each pair of shoes costs Rs. 3000.00, each pair of sandals costs Rs. 2000.00 and each pair of
slippers costs Rs. 1000.00.
• The item code and the quantity (number of pairs) will be entered by the user.
• Amount to be paid for that item will be computed.
Help Seema to write code for calculating:
i) The amount for each pair of items (i.e. Shoes, Sandals and Slippers)
ii) The total amount (sum total of all the amounts).
itemShoesQty=0
shoesCost=0
shoesAmt=0
pg. 33
itemSandalsQty=0
SandalsCost=0
SandalsAmt=0
itemSlippersQty=0
SlippersCost=0
SlippersAmt=0
print("")
print("*****A V O N S H O E S F A C T O R Y B I L L*****")
print("Item Name Quantity Amount(Rs.) ")
print("Shoes ", itemShoesQty, " ", shoesAmt)
print("Sandals ", itemSandalsQty, " ", sandalsAmt)
print("Slippers ", itemSlippersQty, " ", slippersAmt)
print("===========================================================")
print(" Total Amount(Rs.): ",totalAmt)
31. WAP in Python to find a) the absolute value of a given number, and b) the divisibility of integer value
m by n.
#!absValueAndDivisibility.py
print("<><><><><>MAIN MENU<><><><><>")
print("a. Check Absolute Value: ")
print("b. Check Divisibility of an Integer: ")
choice =input("Enter, Your Choice: ")
if choice=='a':
x=float(input("Enter, a Value whose Absolute Value is required: "))
if x<0:
print("Absolute Value of ", x, " is: ", -x)
pg. 34
else:
print("Absolute Value of ", x, " is: ", x)
elif choice=='b':
m=int(input("Enter, an Integer as Dividend : "))
n=int(input("Enter, an Integer as Divisor: "))
if m%n==0:
print("Given ", m, " is Divisible by ", n)
else:
print("Given ", m, " is Not Divisible by ", n)
else:
print("Enter your Choice Next Time Correctly!!!")
Python while-loop
The while-loop is used to repeatedly execute a block of program statements. The syntax and flow chart for
while-loop are shown below:
Syntax Flow Chart
IE
while (Condition):
st1
st2
...
stm
[else: # optional part of while-loop
ste1
…
sten]
where;
pg. 35
evaluates to False first time, the loop stops without executing any remaining statement(s). The following
example prints the numbers 0 to 4 as we set the condition x < 3.
x=0 Output:
while (x < 3): 0
print(x) 1
x += 1 2
One thing we should remember that a while loop tests its condition before the body of the loop (block of
program statements) is executed. If the initial test returns false, the body is not executed at all. For
example the following code never prints out anything since before executing the body of while, the
condition evaluates to false.
x = 10 Output:
while (x < 3): (No Output)
print(x)
x += 1
The following while loop is an infinite while loop, using True as the condition:
x = 10
while (True):
print(x)
x += 1
countLeapYear=1
while(countLeapYear<=5):
y=int(input('Enter the year (4 digits long): '))
leapYear=False
if y%100==0:
if y%400==0:
leapYear=True
elif y%4==0:
leapYear=True
if leapYear==True:
print('Given Year', y, ' is a Leap Year')
else:
print('Given Year', y, ' is not a Leap Year')
countLeapYear += 1
else:
print("-------------while loop ended here!!!----------------")
11. #From a given list of m distinct positive integers, find out the largest & smallest integer.
#!big_n_small_fromList.py
m=int(input("Enter, an positive integer: "))
big=short=m
count=2
while(count<=5):
m=int(input("Enter, an positive integer: "))
if m>big:
big=m
elif m<short:
short=m
pg. 38
count += 1
else:
print("while loop is ended here!!!")
print("Largest=", big, ", and Smallest=", short)
12. #From a given list of m integers, find out the sum and count of non-negative integers
#!sum_n_count_negInt.py
sum=count_negInt=0
i=1
m=int(input("Enter, number of integers in a list : "))
while(i<=m):
n=int(input("Enter, an integer(- or +): "))
if n>=0:
sum +=n
count_negInt += 1
i +=1
else:
print("while loop is ended here!!!")
print("Sum of Positive Integers=", sum, ", and Number of Positive Integers=", count_negInt)
Python for-loop
Python for-loop is used to iterate over the items of any sequence including the Python list, string, tuple etc.
The for-loop is also used to access elements from a container (for example list, string, tuple) using built-in
function range().The syntax and flow chart for for-loop are shown below:
Syntax Flow Chart
pg. 39
for loop-variable in item-list:
statement block1
[else: # optional block
statement block2]
Example
# Write a for-loop to print value 1 to 10
for i in range (1, 11, 1):
print (i, end= " ")
Execution of the loop will result into
1 2 3 4 5 6 7 8 9 10
Let's move back to the for-loop: i is the variable, which keeps on getting a value generated by range()
function, and the block of statement(s) are worked on for each value of i. As the last value is assigned to i,
the loop block is executed last time and control is returned to next statement. If, else is specified in for
statement, then next statement executed will be else. Now we can easily understand the result of for
statement. range( ) generates a list from 1, 2, 3, 4, 5, …., 10 as the step mentioned is 1, i keeps on getting a
value at a time, which is then printed on screen.
Example
for letter in ‘Python’:
print (‘Current Letter’, letter)
else:
print (‘Coming out of loop’)
On execution, will produce the following:
Current Letter: P
Current Letter: y
Current Letter: t
Current Letter: h
Current Letter: o
Current Letter: n
Coming out of loop
pg. 40
SOLVED EXAMPLES ON FOR-LOOP CONSTRUCT
1. #Print the table of a number m.
#!DispTableUsingFor.py
m=int(input("Enter the number to print the table: "))
print("TABLE OF", m,"is as following:")
for i in range(1, 11, 1):
print (m,"X",i,"=",m*i )
2. """Print the following pattern: """Print the following pattern:
1*2*3*4*5 5*4*3*2*1
1*2*3*4 5*4*3*2
1*2*3 5*4*3
1*2 5*4
1 5
""" """
#!printPattern01.py #!printPattern02.py
m=5 m=5
for i in range(m,0,-1): for i in range(m,0,-1):
for j in range(1,i+1,1): for j in range(m,m-i,-1):
if j!=i: if j!=m+1-i:
print(j,end="*") print(j,end="*")
else: else:
print(j) print(j)
#!revStr.py
givenStr=input("Enter the string to reverse: ")
revStr=''
for ch in givenStr:
revStr=ch+revStr
print("The Reversed String: ", revStr)
str=''
for ch in revStr:
str=str+ch
print(str)
8. #WAP to count the number of digits, sum of digits of an integer. Also, reverse this integer.
#! revInt.py
import math
m=int(input("Enter, the positive integer: "))
sign=1
if m<0:
m=-m
sign=-1
if m > 0:
numDigitts = int(math.log10(m))+1
elif m == 0:
numDigitts = 1
sumDigits=revInt=0
for i in range(1,numDigitts+1, 1):
revInt = revInt*10 + m%10
sumDigits += m%10
pg. 42
m //=10
import math
m=int(input("Enter, the positive integer: "))
n=m; sign=1; numDigitts=1
if m<0:
m=-m
sign=-1
if m > 0:
numDigitts = int(math.log10(m))+1
revInt=0
for i in range(1,numDigitts+1, 1):
revInt = revInt*10 + m%10
m //=10
if n==sign*revInt:
print("Given Integer is a Palindrome")
else:
print("Given Integer is not a Palindrome")
10. #WAP to check if the given string is palindrome or not
#!palindromeStr.py
if givenStr==revStr:
print("Given String is a Palindrome")
else:
print("Given String is not a Palindrome")
11. #WAP in Python to compute the factorial of a positive integer.
#! factorialUsingForLoop.py
fact=1
n=int(input("Enter any number : "))
m=n
for element in range(n,0,-1):
fact*=element
print("Factorial of ", m, ": ", fact)
pg. 43
12 Test if a number is equal to the sum of the cubes of its digits. Find the smallest and largest such numbers.
13. WAP in Python to compute the sum of cosine series.
14. WAP in Python to compute the sum of sine series.
pg. 44
Complex logic: Sometimes, the program logic is quite complicated. In that case, flowchart becomes
complex and clumsy. This will become a pain for the user, resulting in a waste of time and money trying
to correct the problem.
Alterations and Modifications: If alterations are required the flowchart may require re-drawing
completely. This will usually waste valuable time.
Reproduction: As the flowchart symbols cannot be typed, reproduction of flowchart becomes a
problem.
3. Draw the flowchart to calculate area of a 4. Draw the flowchart to calculate the average of
square. three numbers.
5. Draw the flowchart to find the larger of two 6. Draw the flowchart to find the factorial of a
numbers. number.
pg. 45
7. A student who appeared in final examination in 8. Draw the flowchart to find the sum of first N
four subjects, is marked PASS if average marks natural numbers.
are more than or equal to 50 otherwise marked
FAIL. Calculate average marks and print result as
PASS or FAIL.
DECISION TREE
Decision Tree is one of the most powerful and popular algorithm. Decision-tree algorithm falls under the
category of supervised learning algorithms. It works for both continuous as well as categorical output
variables.
INCOMPLETE
PSEUDOCODE
Pseudocode is a method of planning which enables the programmer to plan for coding without worrying about
syntax.
Task2: Write a pseudocode and program that converts from Fahrenheit to Celsius or from Celsius to
Fahrenheit, depending on the user's choice.
Pseudocode: # Python Program:
choice = input "Enter 1 to convert from F to C or choice=input("Enter 1 to convert from F to C or
Enter 2 to convert from C to F: " Enter 2 to convert from C to F: ")
temp = input "ask what number?" temp=input("Enter, Temp Value For Conversion: ")
if 1 is pressed if int(choice)==1:
do f to c conversion temp=(float(temp)-32)*5/9
print output print("Temperature in Celcius is: ", temp)
pg. 46
else if 2 is pressed elif int(choice)==2:
do c to f conversion temp=float(temp)*9/5 +32
print output print("Temperature in Fahrenheit is: ", temp)
else else:
print "Please re-enter either 1 or 2" print("Please re-enter 1 or 2")
Task3: Write a pseudocode and program that lets the user type characters and as soon as 'x' is pressed, it
prints how many characters the user inputted then quits program.
Pseudocode: # Python Program:
Assume count is 0 count = 0
while true while True:
ch=input "ask user to enter a char or 'x' to quit” ch = input("Enter a char (x to quit): ")
print ch print (ch)
if 'x' is entered if ch=='x':
print number of characters entered print ("No. of characters entered: ", count)
break break
otherwise add 1 to count else:
count = count + 1
Task4: Write a pseudocode and program in which a password is set and the program will keep prompting
the user to guess it, until they get the word right.
Pseudocode: # Python Program:
set password as OPWD opwd = "Suzanne" #original pwd
GPWD= input "ask user to try to guess password" gpwd = input("Enter the password: ") #guessed pwd
while GPWD is wrong while gpwd != opwd:
output "access denied" print ("Access denied")
GPWD= input "ask user to re-try to guess password" gpwd = input("Enter the password: ")
if GPWD is correct if gpwd == opwd:
output "Login successful!!" print ("Login successful!")
break break
else output " Login Successful in first attempt " else:
print ("Login successful in first attempt")
Task5: Write a pseudocode and program that asks the user to enter 10 numbers one by one, and then
prints all those 10 numbers after the last 10th number is entered.
Pseudocode: # Python Program:
Set numbercount is to 0 numcount = 0
list list = []
while the number count <= 9 while numcount <= 9:
ask for input number=input("Enter a number: ")
add one to number count numcount = numcount + 1
append number to list list.append(number)
print numbers on a separate lines print ("The numbers you entered were: ")
print ("\n".join(list))
IDEA OF DEBUGGING:
Errors and Exceptions
pg. 47
Errors or mistakes in a program are often referred to as bugs. They are almost always the fault of the
programmer. The process of finding and eliminating errors is called debugging. Errors can be classified into
three major groups:
i) Syntax errors ii) Runtime errors iii) Logical errors
i) Syntax errors (or parsed errors)
Python will find these kinds of errors when it tries to parse your program, and exit with an error
message without running anything. Syntax errors are mistakes in the use of the Python language, and
are analogous to spelling or grammar mistakes in a language like English- for example, the
sentence "Would you some tea?" does not make sense – it is missing a verb. Common Python
syntax errors include:
leaving out a keyword
putting a keyword in the wrong place
leaving out a symbol, such as a colon, comma or brackets
misspelling a keyword
incorrect indentation
empty block
Note: It is illegal for any block (like an if body, or the body of a function) to be left completely
empty. If you want a block to do nothing, you can use the pass statement inside the block.
Python will do its best to tell you where the error is located, but sometimes its messages can be
misleading: for example, if you forget to escape a quotation mark inside a string you may get a syntax
error referring to a place later in your code, even though that is not the real source of the problem. If
you can't see anything wrong on the line specified in the error message, try backtracking through the
previous few lines. As you grow in programming experience, you will get better at identifying and
fixing errors. Here are some examples of syntax errors in Python:
myfunction(x, y): # Invalid syntax. Keyword if is missing
return x + y
else:
print("Hello!")
if arriving:
print("Hi!")
esle: # Invalid syntax. Keyword name is else and not esle
print("Bye!")
if flag:
print("Flag is set!") # Invalid syntax. Expected an indented block
Runtime errors often creep in if you don't consider all possible values that a variable could contain,
especially when you are processing user input. You should always try to add checks to your code to
make sure that it can deal with bad input and edge cases gracefully. We will look at this in more detail
in exception handling.
There are some situations in which runtime errors are likely to occur. Whenever we try to read a file or get
input from a user, there is a chance that something unexpected will happen – the file may have been
moved or deleted, and the user may enter data which is not in the right format. Good programmers should
add safeguards to their programs so that common situations for exceptions could be handled gracefully.
Most users expect that programs must be robust enough to recover from these kinds of setbacks.
If we know that a particular section of our program is likely to cause an error, we can tell Python what to
do if it does happen. Instead of letting the error crash our program we can intercept it, do something about
it, and allow the program to continue. To Handle Exceptions, we use a try-except block as following:
try:
age = int(input("Please enter your age: ")) #useful when a value other than numeric type is entered
print("I see that you are ", age, "years old.")
except ValueError:
pg. 49
print("Hey, that wasn't a number!")
Python will try to process all the statements inside the try block. If a ValueError occurs at any point as it is
executing them, the flow of control will immediately pass to the except block, and any remaining
statements in the try block will be skipped.
In this example, we know that the error is likely to occur when we try to convert the user’s input to an
integer. If the input string is not a number, this line will trigger a ValueError – that is why we specified it as
the type of error that we are going to handle.
Debugging programs
Debugging is a process of detecting errors in a program segment and replacing erroneous segment with
corrected segment.
Syntax errors are usually quite straightforward to debug: the error message shows us the line in the file
where the error is, and it should be easy to find it and fix it.
Runtime errors can be a little more difficult to debug: the error message and the traceback can tell us
exactly where the error occurred, but that doesn’t necessarily tell us what the problem is. Sometimes they
are caused by something obvious, like an incorrect identifier name, but sometimes they are triggered by a
particular state of the program – it’s not always clear which of many variables has an unexpected value.
Logical errors are the most difficult to fix because they don’t cause any errors that can be traced to a
particular line in the code. All that we know is that the code is not behaving as it should be – sometimes
tracking down the area of the code which is causing the incorrect behaviour can take a long time.
It is important to test your program to make sure that it behaves the way that you expect. A quick and
simple way of testing that a program is doing the right thing, for example, is to insert a print statement
after every line which outputs the intermediate results which were calculated on that line. Most
programmers intuitively do this as they are writing a program, or perhaps if they need to figure out why it
isn’t doing the right thing. It is quite cumbersome and time consuming.
The module pdb (Python DeBugger) defines an interactive source code debugger for Python programs. It
supports setting (conditional) breakpoints and single stepping at the source line level, inspection of stack
frames, source code listing, and evaluation of arbitrary Python code in the context of any stack frame. It
also supports post-mortem debugging and can be called under program control. To use the debugger in its
simplest form:
pg. 50
The debugger's prompt is '(Pdb) '. This will stop in the first function call in <a statement>.
Alternatively, if a statement terminated with an unhandled exception, you can use pdb's post-mortem
facility to inspect the contents of the traceback:
breakpoint()
The breakpoint() describes a new built-in called breakpoint() which makes it easy and consistent to enter
the Python debugger. Built-in breakpoint() calls breakpointhook(). By default, this latter imports pdb
and then calls pdb.set_trace(), but by binding sys.breakpointhook() to the function of your choosing,
breakpoint() can enter any debugger. Or, the environment variable PYTHONBREAKPOINT can be set to
the callable of your debugger of choice.
INCOMPLETE
LISTS
It is an ordered set of values enclosed in square brackets []. Values in the list can be modified, i.e. it is
mutable. As it is set of values, we can use index in square brackets [] to identify a value belonging to it. The
values that make up a list are called its elements, and they can be of any type.
We can also say that list data type is a container that holds a number of elements in a given order. For
accessing an element of the list, indexing is used. Its syntax is:
listName [index]
It will provide the value at 'index+1' in the list. Index here, has to be an integer value which can be
positive or negative. Positive value of index means counting forward from beginning of the list and
negative value means counting backward from end of the list. Remember the result of indexing a list is the
value of type accessed from the list. If m is the size of the list then following will be its elements
representation in the memory for the purpose of accessing?
To change the value of element of list, we access the element & assign the new value. Example-
>>>print(L1) # let's get the values of list before change
[1, 2, 3, 4]
pg. 51
>>> L1 [2] = 5
>>> print(L1) # modified list
[1, 2, 5, 4]
Here, 3rd element of the list (accessed using index value 2) is given a new value, so instead of 3 it will be 5.
Note: List index works the same way as String index, which is:
An integer value/expression can be used as index.
An Index Error appears, if you try and access element that does not exist in the list.
An index can have a negative value, in that case counting happens from the end of the list.
Let's create a list of even numbers belonging to 'S' list (in example02):
>>> S = [x**2 for x in range (10)] #given as example02
pg. 52
>>>C = [i for i in S if i % 2 == 0]
>>>print(C)
[0, 4, 16, 36, 64]
A single new list is created every time, you execute [ ]. We have created many different lists each time
using [ ]. But if a list is assigned to another variable, a new list is not created.
i) A=B=[ ] #Creates one list mapped to both A & B
Example01-
>>>A = B = [10, 20, 30]
>>> print(A, B)
[10, 20, 30] [10, 20, 30]
ii) A = [ ]
B = A #Will also create one list mapped to both
Example02-
>>> A = [1, 2, 3]
>>> B = A
>>> print(A, B)
[1, 2, 3] [1, 2, 3]
Accessing an Element of List- For accessing an element, we use index and we have already seen
example doing so. To access an element of list containing another list (i.e the nested list), we use pair of
index. Let’s access elements of L5 list. Also a sub-list of list can be accessed using list slice.
List Slices-Slice operator works very well on list. We know that a slice of a list is its sub-list. Let, L5 be a list
as created below:
>>> L5 = [1, 2, [6, 7, 8], 3]
>>>print(L5 [0]) # first element is 1
1
>>>print( L5 [2]) #third element of L5 is a nested list
[6, 7, 8]
>>>print(L5 [2] [0]) #to access first element from the nested-list, second index is being used
6
>>>print(L5 [2] [2]) #to access third element from the nested-list, second index is being used
8
For creating a list slice, we use [n:m] operator. This will return the part of the list from n th element to mth
element, including the first element but excluding the last element. So the resultant sub-list (i.e. list slice)
will have m-n elements in it. Consider the list L1 as created below:
>>>L1 = [1, 2, 3, 4]
>>>L1 [1:2] #will result into [2]
[2]
pg. 53
Slices are treated as boundaries, and the result will contain all the elements between boundaries. Its
syntax is:
seq = L[start: stop: step]
Where start, stop & step- all three are optional. If you omit first index, slice starts from '0' index and
omitting of stop will take it to last index +1. Default value of step is 1.
Example01- Let L2 be the following list: Example02-
>>> L2 = ['Delhi', 'Chennai', 'Mumbai'] >>>L [:3]
>>> L2[0:2] #The list slice from index 0 to 1 [10, 20, 30]
['Delhi', 'Chennai'] >>>L [:]
[10, 20, 30, 40, 50, 60]
Example03- Example04-
>>>L = [10, 20, 30, 40, 50, 60] >>> L[-1] # '-1' refers to last elements of list
>>> L [::2] #List slice with every alternate element 60
[10, 30, 50] Example05-
>>>L [4:] #List slice from index 4 to end+1 >>> L [-1::-1] #List slice from last index to first index
[50, 60] with a step of -1
[60, 50, 40, 30, 20, 10]
Note: Since lists are mutable, it is often recommended to make a copy of it before performing operation
that change a list.
Traversing a List- Let us visit each element (traverse the list) of the list to display them on screen. This can
be done in many ways. Let L1 = [1, 2, 5, 4]
i) L1=[1,2,5,4] ii) L1=[1,2,5,4]
i=0 for i in L1:
while i < 4: print(i, end=' ')
print(L1[i], end=' ')
i += 1
iii) L1=[1,2,5,4] iv) L1=[1,2,5,4]
i=0 for i in range (len(L1)):
while i < len(L1): print(L1[i], end=' ')
print(L1[i], end=' ')
i += 1
Note:
Each of the four ways will produce the same output as: 1 2 5 4
The len( ) function is used to get the length of list L1. As length of L1 is 4, i will take value from 0 to 3.
Using 2nd way for transversal will only allow us to print the list, but other ways can also be used to
write or update the element of the list.
In 4th way, range( ) function is used to generate, indices from 0 to len -1; with each iteration i gets the
index of next element and values of list are printed.
The for-loop in empty list is never executed. For example-
for i in [ ]:
print(i) # No execution
Appending in the list- Appending to a list means adding one element at a time, at the end of the list. To
do so, Python provides a method append( ). Its Syntax is:
List. append (item)
pg. 54
i) L1 = [1, 2, 3, 4] ii) >>>L4 = ['abc', 10, 20, 30]
>>>L1. append (70) ) # will append 70 to L1 >>>L4.append (30) # will append 30 to L4
>>> print(L1) # will print updated L1 >>>print(L4) # will print updated L4
[1, 2, 5, 4, 70] ['abc', 10, 20, 30, 30]
For adding more than one element, extend( ) method can be used, this can also be used to add elements of
another list to the existing one. (I am stopping writing Python prompt i.e. >>> in rest of the examples)
i) L1 = [1, 2, 3, 4] ii) B=[2009, 2011, 'abc']
A = [100, 90, 80, 50] C=['xyz', 'pqr', 'mn']
L1. extend (A) #will add A to the end of L1 B.extend(C)
print(L1) #will print updated L1 print(B) #will print updated B
#[1, 2, 3, 4, 100, 90, 80, 50] OUTPUT #[2009, 2011, 'abc', 'xyz', 'pqr', 'mn'] OUTPUT
Updating array (i.e. List) elements- Updating an element of a list is, accomplished by accessing the
element & modifying its value in place. It is possible to modify a single element or a part of list. For first
type, we use index to access single element (see following example01) and for second type, list slice is used
(see following example02).
Example01- WAP in Python to modify the list L1=[3, 4, 8, 9] such that all its even elements are multiplied
by 10 and odd elements by 20. Also print the modified list.
i) L1=[3, 4, 8, 9] ii) L1=[3, 4, 8, 9]
i=0 for i in range(len(L1)):
while i < len(L1): if L1[i]%2==0:
if L1[i]%2==0: L1[i]=10*L1[i]
L1[i]=10*L1[i] else:
else: L1[i]=20*L1[i]
L1[i]=20*L1[i] print(L1)
i += 1 #[60, 40, 80, 180] OUTPUT
print(L1)
#[60, 40, 80, 180] OUTPUT
i) L1=[3, 4, 8, 9] ii) L1=[3, 4, 8, 9]
i=0 for i in range(len(L1)):
while i < len(L1): if L1[i]%2==0:
if L1[i]%2==0: L1[i]=10*L1[i]
L1[i]=10*L1[i] else:
else: L1[i]=20*L1[i]
L1[i]=20*L1[i] print(L1)
i += 1 #[60, 40, 80, 180] OUTPUT
print(L1)
#[60, 40, 80, 180] OUTPUT
Example02- (i) WAP in Python to replace (or modify) from mth to (n-1)th elements of a list with list slice ['a',
'b', 'c']. Take L1=[0, 1, 2, 3, 4, 5]
(ii) WAP in Python to replace (or modify) from mth to (last +1)th elements with list slice ['a']. Take L1=[0, 1,
2, 3, 4, 5]
i) L1=[0, 1, 2, 3, 4, 5] ii) L1=[0, 1, 2, 3, 4, 5]
L1[1:3] = ['a', 'b', 'c'] L1[1:6] = ['a']
"""Form index 1 to 3-1, list slice ['a', 'b', 'c'] will """Form index 1 to 6-1, list slice ['a'] will be
be substituted""" substituted"""
pg. 55
print(L1) print(L1)
#[0, 'a', 'b', 'c', 3, 4, 5] OUTPUT #[0, 'a'] OUTPUT
Using + and * operators- Use of these operators generate a new list. It is important to know that ‘+’
operator in lists expects the same type of sequence on both the sides otherwise you get a type error.
If you want to concatenate a list and a string, either you have to convert the list to string or string to list.
Example-
i) L1=[0, 1, 2] ii) L1=[1, 2, 3] + [4, 5, 6]
L2 = ['Delhi', 'Chennai', 'Mumbai'] print(L1)
L3 = L1 + L2 #[1, 2, 3, 4, 5, 6] OUTPUT
print(L3)
#[0, 1, 2, 'Delhi', 'Chennai', 'Mumbai'] OUTPUT
iii) L1=[2, 3, 4] iv) L1 = ['ROSARY']*3
L2 = L1*4 print(L1)
print(L2) #['ROSARY', 'ROSARY', 'ROSARY']OUTPUT
#[2, 3, 4, 2, 3, 4, 2, 3, 4, 2, 3, 4] OUTPUT
v) print(str([11, 12]) + "34") vi) print([11, 12] + list("34"))
#or print("[11, 12]" + "34") # or print([11, 12] + ["3", "4"])
#[11, 12]34 OUTPUT #[11, 12, '3', '4'] OUTPUT
Deleting Elements From List- It is possible to delete/remove element(s) from the list. There are many
ways of doing so:
i) If index is known, we can use pop() or del()
The pop() removes the element from the specified index, and also returns the element which was
removed. Its syntax is:
List.pop ([index])
If no index value is provided in pop ( ), then last element is deleted.
Example-
L1 = [1, 2, 4, 5, 6]
A = L1.pop(1) # here the element deleted will be returned to list A.
print(L1)
print(A)
B = L1.pop() # here the last element is deleted and returned to list B.
print(L1)
print(B)
""" OUTPUT
[1, 4, 5, 6]
2
[1, 4, 5]
6
"""
The del() removes the element from the list with specified index, but does not return the deleted
value.
L1 = [1, 2, 3, 4, 5]
print(L1)
del L1[3] #3 is index number
print(L1)
""" OUTPUT
[1, 2, 3, 4, 5]
pg. 56
[1, 2, 3, 5]
"""
ii) If the element is known, and not the index, remove() can be used.
L1 = [10, 20, 30, 40, 50]
print("List before deletion: ", L1)
L1.remove(30) # 30 is the element value
print("List after deletion: ", L1)
""" OUTPUT
List before deletion: [10, 20, 30, 40, 50]
List after deletion: [10, 20, 40, 50]
"""
iii) To remove more than one element, del() with list slice is used. Consider the following example:
L1 = [10, 20, 30, 40, 50, 60]
print("List before deletion: ", L1)
del L1[2:4]
print("List after deletion: ", L1)
""" OUTPUT
List before deletion: [10, 20, 30, 40, 50, 60]
List after deletion: [10, 20, 50, 60]
"""
iv) Using assignment operator, a list slice can be deleted as shown below:
L5 = [1, 2, [6, 7, 8], 3]
print("Before Deletion: ", L5)
L5[1:2] = []
print("After Deletion: ", L5)
""" OUTPUT
Before: [1, 2, [6, 7, 8], 3]
After: [1, [6, 7, 8], 3]
"""
pg. 57
Note:
(i) All methods modify the list, after deletion(s) applied.
(ii) If an out of range index is provided with del() and pop(), the code will result into run-time error.
(iii) del() can be used with negative index value also.
Inserting Elements in List- The method insert(), inserts an element, at the given position specified by its
index, and the remaining elements are shifted to accommodate the new element. Its syntax is
list. insert (indexValue, itemValue)
Index specifies the position (starting from 0) where the element is to be inserted. Item is the element to be
inserted in the list. Length of list changes after insert operation. Example-
i) Inserting before the 1st element- ii) Inserting after the last element-
L5 = [10,20,30] #indexes are: 0, 1, 2 OR -3, -2, -1 L5 = [10, 20, 30] #index are: 0, 1, 2 OR -3, -2, -1
print("List Before Insertion: ", L5) print("List Before Insertion: ", L5)
L5.insert(0, 5) Length=len(L5)
print("List After Insertion: ", L5) L5.insert(Length, 5)
print("List After Insertion: ", L5)
OUTPUT
List Before Insertion: [10, 20, 30] OUTPUT
List After Insertion: [5, 10, 20, 30] List Before Insertion: [10, 20, 30]
List After Insertion: [10, 20, 30, 5]
iii) Inserting between 1st and last element- iv) Note: If the index specified >=len(list), then item
L5 = [10,20,30] #Indexes are: 0, 1, 2 OR -3, -2, -1 is inserted after the last element(i.e. at the last
print("List Before Insertion: ", L5) element position).
L5.insert(1, 5) L5 = [10, 20, 30] #Indexes are: 0, 1, 2 OR -3, -2, -1
print("List After Insertion: ", L5) print("List Before Insertion: ", L5)
L5.insert(len(L5), 5)
OUTPUT print("List After Insertion: ", L5)
List Before Insertion: [10, 20, 30]
List After Insertion: [10, 5, 20, 30] OUTPUT
List Before Insertion: [10, 20, 30]
List After Insertion: [10, 20, 30, 5]
OUTPUT
List Before Insertion: [10, 20, 30]
List After Insertion: [5, 10, 20, 30]
Reversing Elements of the List- The method reverse() can be used to reverse the elements of the list in
place. Its syntax is:
list.reverse()
Method does not return anything as the reversed list is stored in the same variable. Example-
L1=[10, 20, 30, 40]
pg. 58
print("List Before reversing: ", L1)
L1.reverse() # or L1[::-1] will also result into reversal of list L1
print("List After reversing: ", L1)
OUTPUT
List Before reversing: [10, 20, 30, 40]
List After reversing: [40, 30, 20, 10]
Sorting Elements of the List- For arranging elements in an order Python provides a method sort() and a
function sorted(). Sort() modifies the list in place and sorted() returns a new sorted list. Its Syntax are:
sort ([cmp [, key [, reverse]]])
sorted (list [, cmp [, key [, reverse]]])
Parameters mentioned in [ ] are optional in both the cases. These parameters allow us to customize the
function/method.
'cmp', argument allow us to override the default way of comparing elements of list. By default, sort
determines the order of elements by comparing the elements in the list against each other. To override
this, we can use a user defined function which should take two values and return -1 for 'less than', 0 for
'equal to' and 1 for 'greater than'.
'Key' argument is preferred over 'cmp' as it produces list faster. The parameter 'key' is for specifying a
function that transforms each element of list before comparison. We can use predefined functions or a
user defined function here. If its user defined then, the function should take a single argument and return a
key which can be used for sorting purpose. Reverse parameter can have a boolean value which is used to
specify the order of arranging the elements of list. Value 'True' for reverse will arrange the elements of list
in descending order and value 'False' for reverse will arrange the elements in ascending order. Default
value of this parameter is False.
sorted() function also behaves in similar manner except for it produce a new sorted list, so original is not
changed. This function can also be used to sort any iterable collection. As sort() method does not create a
new list so it can be little faster.
Examples-
i) L2=['Mumbay','Chennai', 'Delhi'] ii) L4 = [20, 40, 30, 10]
print("List Before Sorting: ", L2) print("List Before Sorting: ", L4)
L2.sort() L4.sort()
print("List After Sorting: ", L2) print("List After Sorting: ", L4)
print() L4 = [20, 40, 30, 10]
L2.sort (key=len) L4.sort(reverse = True)
print("List After Sorting for key=len: ", L2) print("List After Sorting in reverse order: ", L4)
OUTPUT OUTPUT
List Before Sorting: ['Mumbay', 'Chennai', 'Delhi'] List Before Sorting: [20, 40, 30, 10]
List After Sorting: ['Chennai', 'Delhi', 'Mumbay'] List After Sorting: [10, 20, 30, 40]
List After Sorting in reverse order: [40, 30, 20,
List After Sorting for key=len: ['Delhi', 'Mumbay', 10]
'Chennai']
Here in i) we have specified len() built in function, as key for sorting. So the list will get sorted by the length
of the strings, i.e., from shortest to longest. sort() will call len() function for each element of list and then
these lengths will be used for arranging elements. See the figure given below :
pg. 59
MATRIX IMPLEMENTATION USING LIST
One can implement matrix using list. Matrix operations require use of nested list. List inside another list is
called nested list. The creation, initialization of matrix and input|output is as following:
For Numeric Elements For String Elements
The Creation and Initialization of matrix The Creation and Initialization of matrix
import random import random
x = random.random() x = str(random.random())
A = [[x for row in range(n)] for col in range(m)] A = [[x for row in range(n)] for col in range(m)]
Where, m represents number of rows, n represents Where, m represents number of rows, n represents
number of columns and A is m-by-n matrix. number of columns and A is m-by-n matrix.
Example- WAP in Python that accepts input for mXn matrix and prints both diagonal values of the matrix.
Matrix With Integer Elements Matrix With String Elements
m=input("Enter total number of rows: "); m=int(m) m=input("Enter number of rows: "); m=int(m)
n=input("Enter total number of columns: "); n=int(n) n=input("Enter number of columns: "); n=int(n)
import random import random
S = random.random() S = str(random.random())
A = [[S for row in range(n)]for col in range(m)] A = [[S for row in range(n)]for col in range(m)]
print("Input all matrix elements one after other") print("Input all matrix elements one after other")
for i in range(m): for i in range(m):
for j in range(n): for j in range(n):
y = input("Enter new element: ") y = input("Enter new element: ")
A[i][j]= int(y) A[i][j]= y
pg. 60
print("\nFirst Diagonal Elements Are:") print("\nFirst Diagonal Elements Are:")
for i in range(m): for i in range(m):
print(A[i][i],end='\t') print(A[i][i],end='\t')
OUTPUT OUTPUT
Enter total number of rows: 3 Enter number of rows: 3
Enter total number of columns: 3 Enter number of columns: 3
Input all matrix elements one after other Input all matrix elements one after other
Enter new element: 1 Enter new element: a
Enter new element: 2 Enter new element: b
Enter new element: 3 Enter new element: c
Enter new element: 4 Enter new element: d
Enter new element: 5 Enter new element: e
Enter new element: 6 Enter new element: f
Enter new element: 7 Enter new element: g
Enter new element: 8 Enter new element: h
Enter new element: 9 Enter new element: i
OUTPUT
Enter 5 Intrger Elements in the List:
3
5
1
4
2
The List Elements are: [3, 5, 1, 4, 2]
Maximum element in the List is: 5
Minimum element in the List is: 1
Mean element in the List is: 3.0
2. WAP in Python to search an item within a list of m integer elements.
Solution:
#!List_linearSearch.py
m=5; L=[]; loc=-1
print("Enter", m, "Intrger Elements in the List(space separated on same line):")
L = [int(x) for x in input().split(' ')]
print("The List is:", L)
item=int(input("Enter, an integer element to search: "))
for i in range(0, m, 1):
if item==L[i]:
loc=i
break
if loc !=-1:
print("The element", item, "is found in the list at location:", loc)
else:
print("The element", item, "is not found in the list")
OUTPUT
Enter 5 Integer Elements in the List:
42513
The List is: [4, 2, 5, 1, 3]
Enter, an integer element to search: 5
The element 5 is found in the list at location: 2
3. WAP in Python to count the frequency of an element in the List.
Solution:
#!List_elementFreq.py
m=10; L=[]; freq=0
print("Enter", m, "Integer Elements in the List(comma separated on the same line):")
L = [int(x) for x in input().split(',')]
print("The List is:", L)
pg. 62
item= int(input("Enter, the element whose frequency is to be conted in the List:"))
for i in range(0, m): #by default step is one when not mentioned
if item==L[i]:
freq +=1
print("The element", item, "appeared in the list", freq,"number of times")
OUTPUT
Enter 10 Integer Elements in the List(comma separated on the same line):
3,1,3,2,6,5,3,8,3,9
The List is: [3, 1, 3, 2, 6, 5, 3, 8, 3, 9]
Enter, the element whose frequency is to be conted in the List:3
The elemnet 3 appeared in the list 4 number of times
OUTPUT
List of coefficients: [-13.39, 17.5, 3, 0.0, 1.0]
Enter value of x: 2.7
p(x) at x= 2.7 is: 108.874
5. WAP in Python that takes a list of numbers and returns the cumulative sum; that is, a new list where
its element is the sum of the first i+1 elements from the original list. For example, the cumulative sum
of [1, 2, 3] is [1, 3, 6].
Solution:
#!List_cumulativeSum.py
m=5; L=[]; newL=[]; sum=0
print("Enter", m, "Integer Elements in the List(space separated on same line):")
L = [int(x) for x in input().split(' ')]
for i in range(0, m, 1):
sum += L[i]
newL.append(sum)
print("Given List:", L)
print("New List:", newL)
OUTPUT
Enter 5 Integer Elements in the List(space separated on same line):
12345
Given List: [1, 2, 3, 4, 5]
pg. 63
New List: [1, 3, 6, 10, 15]
6. WAP in Python that accepts a list through input via keyboard and modifies it by removing the first and
last elements. This modified list is displayed on the screen.
Solution:
#!List_delFirst_n_Last.py
m=7; L=[];
print("Enter", m, "Integer Elements in the List(space separated on same line):")
L = [int(x) for x in input().split(' ')]
print("Original List:", L)
OUTPUT
Enter 7 Integer Elements in the List(space separated on same line):
1234567
Original List: [1, 2, 3, 4, 5, 6, 7]
List after deletion: [2, 3, 4, 5, 6]
7. WAP that accepts a list through input via keyboard and displays either "List is Sorted in ASC order" or
"List is Sorted in DESC order" or "List is not Sorted in any order. In case You can assume (as a
precondition) that the elements of the list can be compared with the relational operators <, >, etc.
For example, the list [1, 2, 2] is in ASC order and *‘b’, ‘a’+) is in DESC order.
Solution:
#!List_sortedUnsorted.py
m=5; L=[]; sortInASC=True; sortInDESC=True; randomOrder=True
print("Enter", m, "in the List(space separated on same line):")
L = [int(x) for x in input().split(' ')]
print("Entered List Elements:", L)
for i in range(0, m-1, 1):
if L[i+1]>=L[i]:
pass
else:
sortInASC=False
if L[i+1]<=L[i]:
pass
else:
sortInDESC=False
if sortInASC==True:
randomOrder=False
print("List is Sorted in ASC order")
if sortInDESC==True:
randomOrder=False
print("List is Sorted in DESC order")
pg. 64
if randomOrder==True:
print("List is not Sorted in any order")
OUTPUT
Enter 5 in the List(space separated on same line):
12234
Entered List Elements: [1, 2, 2, 3, 4]
List is Sorted in ASC order
8. WAP that accepts an integer list in sort order through input via keyboard and inserts an item such
that the sort order remains intact. It displays the resultant list on the screen.
Solution:
#!LIst_insItem.py
#Let the distinct elements in the list are in ASC order.
m=5; L=[]; loc=0
print("Enter", m, "integers in the List(b separated on same line):")
L = [int(x) for x in input().split('b')]
L.insert(loc, item)
print("List After Insertion:", L)
OUTPUT
Enter 5 integers in the List(b separated on same line):
11b22b33b44b55
List Before Insertion: [11, 22, 33, 44, 55]
Enter item for insertion: 1
pg. 65
List After Insertion: [1, 11, 22, 33, 44, 55]
9. WAP that accepts an integer list in any order through input via keyboard and deletes an item. It
displays the resultant list on the screen.
Solution:
#!List_delItem.py
#Let the distinct elements in the list are not in any order.
m=5; L=[]; loc=0
print("Enter", m, "integers in the List(space separated on same line):")
L = [int(x) for x in input().split(' ')]
OUTPUT
Enter 5 integers in the List(space separated on same line):
53142
List Before Deletion: [5, 3, 1, 4, 2]
Enter item for Deletion: 1
List After Deletion: [5, 3, 4, 2]
10. WAP that accepts an integer list in any order through input via keyboard and creates a new list with
distinct elements after removing repeated elements. It displays the resultant list on the screen.
Solution:
#!List_delRepeatedItems.py
m=10; L=[]
print("Enter", m, "integers in the List(space separated on same line):")
L = [int(x) for x in input().split(' ')]
print("List Before New List Creation:", L)
S = []
pg. 66
print("New List with Distinct Elements: ", S)
OUTPUT
Enter 10 integers in the List(space separated on same line):
1232425653
List Before New List Creation: [1, 2, 3, 2, 4, 2, 5, 6, 5, 3]
New List with Distinct Elements: [1, 2, 3, 4, 5, 6]
11. WAP in Python to reverse the order of given list. Also, display the resultant list
Solution:
#!List_reversing.py
m=5; L=[]
print("Enter", m, "integers in the List(space separated on same line):")
L = [int(x) for x in input().split(' ')]
print("List Before Reversing:", L)
i=0; j=m-1
while i<=j:
temp=L[i]
L[i]=L[j]
L[j]=temp
i=i+1; j=j-1
print("List After Reversing : ", L)
OUTPUT
Enter 5 integers in the List(space separated on same line):
53142
List Before Reversing: [5, 3, 1, 4, 2]
List After Reversing : [2, 4, 1, 3, 5]
12. WAP to find the product and sum of all elements in list of integers. Display product and sum on
screen.
Solution:
#!List_product_n_sum.py
m=5; L=[]
print("Enter", m, "integers in the List(space separated on same line):")
L = [int(x) for x in input().split(' ')]
print("List Elements are:", L)
product=1; sum=0
for elements in L:
product=product*elements
sum=sum+elements
print("Product of all Elements: ", product)
print("Sum of all Elements: ", sum)
OUTPUT
pg. 67
Enter 5 integers in the List(space separated on same line):
12345
List Elements are: [1, 2, 3, 4, 5]
Product of all Elements: 120
Sum of all Elements: 15
13 WAP that accepts a list of positive integers in any order through input via keyboard. From this create
three sub-lists named as even, odd and prime. Even list will consist of even integers, odd list will
consist of odd integers and prime list will consist of prime numbers only. Display each of the three
lists with appropriate heading.
Solution:
#!List_evenOddPrime.py
m=10; L=[]; even=[]; odd=[]; prime=[]
print("Enter", m, "integers in the List(space separated on same line):")
L = [int(x) for x in input().split(' ')]
print("List Elements are:", L)
for i in L:
if i%2==0:
even.append(i)
else:
odd.append(i)
flag=1
for j in range(2, i//2, 1):
if i%j==0:
flag=0
break
if flag==1:
prime.append(i)
OUTPUT
Enter 10 integers in the List(space separated on same line):
3 56 59 90 63 82 80 99 107
List Elements are: [3, 56, 59, 90, 63, 82, 80, 99, 107]
List of Even Numbers: [56, 90, 82, 80]
List of Odd Numbers: [3, 59, 63, 99, 107]
List of Prime Numbers: [3, 59, 107]
14. WAP in Python that accepts two lists of positive integers in ASC order through input via keyboard.
Lists may not be of same length and one or both may be empty. Don't use any Python built-in
methods or functions.
Solutions:
#!List_merging.py
m=5; n=7; A=[]; B=[]; C=[]
print("Enter", m, "integers in the List A(space separated on same line):")
A = [int(x) for x in input().split(' ')]
pg. 68
print("Enter", n, "integers in the List B(space separated on same line):")
B = [int(x) for x in input().split(' ')]
ia=0; ib=0;
while ia<m and ib<n:
if A[ia]<B[ib]:
C.append(A[ia])
ia += 1
else:
C.append(B[ib])
ib += 1
if ia>=m:
while ib<n:
C.append(B[ib])
ib += 1
if ib>=n:
while ia<m:
C.append(A[ia])
ia += 1
print("The List A:", A)
print("The List B:", B)
print("The List C:", C)
OUTPUT
Enter 5 integers in the List A(space separated on same line):
11 22 33 44 55
Enter 7 integers in the List B(space separated on same line):
7 17 27 37 47 57 67
The List A: [11, 22, 33, 44, 55]
The List B: [7, 17, 27, 37, 47, 57, 67]
The List C: [7, 11, 17, 22, 27, 33, 37, 44, 47, 55, 57, 67]
15. WAP in Python to input any matrix with mXn, and print the matrix on the output screen in matrix
format.
Solution:
#!List_matrixInput.py
m=3; n=2
#Following is the MATRIX initialization
A=[[[] for i in range(n)] for j in range(m)] # for each row, n columns. For each column, m rows
print(A)
print("Enter", m*n, "Intrger Elements in the Matrix one after other on different lines:")
for i in range(m):
for j in range(n):
print("Enter Element No.", n*i+j+1,":" ,end=' ')
num=int(input())
A[i][j]=num
print("MATRIX")
for i in range(m):
pg. 69
for j in range(n):
print(A[i][j], end='\t')
print()
OUTPUT
Enter 6 Intrger Elements in the Matrix one after other on different lines:
Enter Element No. 1 : 1
Enter Element No. 2 : 2
Enter Element No. 3 : 3
Enter Element No. 4 : 4
Enter Element No. 5 : 5
Enter Element No. 6 : 6
MATRIX
1 2
3 4
5 6
16. WAP to add two matrices with same dimensions i.e. mxn
Solution:
#!List_matrixAddition.py
m=3; n=2
#Following is the MATRICES initialization
A=[[[] for i in range(n)] for j in range(m)] # for each row, n columns. For each column, m rows
B=[[[] for i in range(n)] for j in range(m)]
C=[[[] for i in range(n)] for j in range(m)]
print("Enter", m*n, "Intrger Elements in the Matrix A after other on different lines:")
for i in range(m):
for j in range(n):
print("Enter Element No.", n*i+j+1,":" ,end=' ')
num=int(input())
A[i][j]=num
print("MATRIX A")
for i in range(m):
for j in range(n):
print(A[i][j], end='\t')
print()
print("Enter", m*n, "Intrger Elements in the Matrix B after other on different lines:")
for i in range(m):
for j in range(n):
print("Enter Element No.", n*i+j+1,":" ,end=' ')
num=int(input())
B[i][j]=num
print("MATRIX B")
for i in range(m):
for j in range(n):
print(B[i][j], end='\t')
print()
pg. 70
#MATRIX addition foolws
for i in range(m):
for j in range(n):
C[i][j] = A[i][j] + B[i][j]
print("RESULTANT MATRIX C")
for i in range(m):
for j in range(n):
print(C[i][j], end='\t')
print()
OUTPUT
Enter 6 Intrger Elements in the Matrix A after other on different lines:
Enter Element No. 1 : 11
Enter Element No. 2 : 12
Enter Element No. 3 : 13
Enter Element No. 4 : 14
Enter Element No. 5 : 15
Enter Element No. 6 : 16
MATRIX A
11 12
13 14
15 16
Enter 6 Intrger Elements in the Matrix B after other on different lines:
Enter Element No. 1 : 21
Enter Element No. 2 : 22
Enter Element No. 3 : 23
Enter Element No. 4 : 24
Enter Element No. 5 : 25
Enter Element No. 6 : 26
MATRIX B
21 22
23 24
25 26
RESULTANT MATRIX C
32 34
36 38
40 42
17. WAP to compute the multiplication of two matrices Amxp and Bpxn
Solution:
#!List_matrixMultiplication.py
m=3; p=2; n=3
#Following is the MATRICES initialization
A=[[[] for i in range(p)] for j in range(m)] # for each row, p columns. For each column, m rows
B=[[[] for i in range(n)] for j in range(p)] # for each row, n columns. For each column, p rows
C=[[[] for i in range(n)] for j in range(m)] # for each row, n columns. For each column, m rows
print("Enter", m*p, "Intrger Elements in the Matrix A after other on different lines:")
for i in range(m):
for j in range(p):
pg. 71
print("Enter Element No.", p*i+j+1,":" ,end=' ')
num=int(input())
A[i][j]=num
print("MATRIX A")
for i in range(m):
for j in range(p):
print(A[i][j], end='\t')
print()
print("Enter", p*n, "Intrger Elements in the Matrix B after other on different lines:")
for i in range(p):
for j in range(n):
print("Enter Element No.", n*i+j+1,":" ,end=' ')
num=int(input())
B[i][j]=num
print("MATRIX B")
for i in range(p):
for j in range(n):
print(B[i][j], end='\t')
print()
OUTPUT
Enter 6 Intrger Elements in the Matrix A after other on different lines:
Enter Element No. 1 : 1
Enter Element No. 2 : 2
Enter Element No. 3 : 3
Enter Element No. 4 : 4
Enter Element No. 5 : 5
Enter Element No. 6 : 6
MATRIX A
1 2
3 4
5 6
Enter 6 Intrger Elements in the Matrix B after other on different lines:
Enter Element No. 1 : 11
Enter Element No. 2 : 12
Enter Element No. 3 : 13
pg. 72
Enter Element No. 4 : 14
Enter Element No. 5 : 15
Enter Element No. 6 : 16
MATRIX B
11 12 13
14 15 16
RESULTANT MATRIX C
39 42 45
89 96 103
139 150 161
18. WAP in Python to input MXN matrix and find sum of all even numbers in the matrix.
Solution:
#!List_sumOfEvenInMatrix.py
m=3; n=3
#Following is the MATRICES initialization
A=[[[] for i in range(n)] for j in range(m)] # for each row, n columns. For each column, m rows
print("Enter", m*n, "Intrger Elements in the Matrix A after other on different lines:")
for i in range(m):
for j in range(n):
print("Enter Element No.", n*i+j+1,":" ,end=' ')
num=int(input())
A[i][j]=num
print("MATRIX A")
for i in range(m):
for j in range(n):
print(A[i][j], end='\t')
print()
sum=0
for i in range(m):
for j in range(n):
if A[i][j]%2==0:
sum=sum +A[i][j]
print("Sum of all even numbers in the matrix: ", sum)
OUTPUT
Enter 9 Intrger Elements in the Matrix A after other on different lines:
Enter Element No. 1 : 11
Enter Element No. 2 : 12
Enter Element No. 3 : 13
Enter Element No. 4 : 14
Enter Element No. 5 : 15
Enter Element No. 6 : 16
Enter Element No. 7 : 17
Enter Element No. 8 : 18
Enter Element No. 9 : 19
MATRIX A
11 12 13
pg. 73
14 15 16
17 18 19
Sum of all even numbers in the matrix: 60
19. Write a program to print upper triangle matrix.
Solution:
#!List_upperDiagonal.py
m=3; n=3
#Following is the MATRIX initialization
A=[[[] for i in range(n)] for j in range(m)] # for each row, n columns. For each column, m rows
print("Enter", m*n, "Integer Elements in the Matrix A after other on different lines:")
for i in range(m):
for j in range(n):
print("Enter Element No.", n*i+j+1,":" ,end=' ')
num=int(input())
A[i][j]=num
print("MATRIX A")
for i in range(m):
for j in range(n):
print(A[i][j], end='\t')
print()
print()
print("UPPER TRIANGLE MATRIX FOLLOWS:")
for i in range(m):
for j in range(n):
if i<=j:
x=str(A[i][j])
else:
x=' '
print(x,end='\t')
print()
OUTPUT
Enter 9 Intrger Elements in the Matrix A after other on different lines:
Enter Element No. 1 : 1
Enter Element No. 2 : 2
Enter Element No. 3 : 3
Enter Element No. 4 : 4
Enter Element No. 5 : 5
Enter Element No. 6 : 6
Enter Element No. 7 : 7
Enter Element No. 8 : 8
Enter Element No. 9 : 9
MATRIX A
1 2 3
4 5 6
7 8 9
pg. 74
UPPER TRIANGLE MATRIX FOLLOWS:
1 2 3
5 6
9
20. Write a program to print lower triangle matrix.
Solution:
#!List_lowerDiagonal.py
m=3; n=3
#Following is the MATRIX initialization
A=[[[] for i in range(n)] for j in range(m)] # for each row, n columns. For each column, m rows
print("Enter", m*n, "Integer Elements in the Matrix A after other on different lines:")
for i in range(m):
for j in range(n):
print("Enter Element No.", n*i+j+1,":" ,end=' ')
num=int(input())
A[i][j]=num
print("MATRIX A")
for i in range(m):
for j in range(n):
print(A[i][j], end='\t')
print()
print()
print("LOWER TRIANGLE MATRIX FOLLOWS:")
for i in range(m):
for j in range(n):
if i>=j:
x=str(A[i][j])
else:
x=' '
print(x,end='\t')
print()
OUTPUT
Enter 9 Integer Elements in the Matrix A after other on different lines:
Enter Element No. 1 : 1
Enter Element No. 2 : 2
Enter Element No. 3 : 3
Enter Element No. 4 : 4
Enter Element No. 5 : 5
Enter Element No. 6 : 6
Enter Element No. 7 : 7
Enter Element No. 8 : 8
Enter Element No. 9 : 9
MATRIX A
1 2 3
4 5 6
7 8 9
pg. 75
LOWER TRIANGLE MATRIX FOLLOWS:
1
4 5
7 8 9
21. Write a program to find sum of rows and columns of the matrix.
Solution:
#!List_sumRowsColumns.py
m=3; n=3
#Following is the MATRIX initialization
A=[[[] for i in range(n)] for j in range(m)] # for each row, n columns. For each column, m rows
print("Enter", m*n, "Integer Elements in the Matrix A after other on different lines:")
for i in range(m):
for j in range(n):
print("Enter Element No.", n*i+j+1,":" ,end=' ')
num=int(input())
A[i][j]=num
print("MATRIX A")
for i in range(m):
for j in range(n):
print(A[i][j], end='\t')
print()
OUTPUT
Enter 9 Integer Elements in the Matrix A after other on different lines:
Enter Element No. 1 : 1
Enter Element No. 2 : 2
Enter Element No. 3 : 3
Enter Element No. 4 : 4
Enter Element No. 5 : 5
Enter Element No. 6 : 6
Enter Element No. 7 : 7
Enter Element No. 8 : 8
Enter Element No. 9 : 9
pg. 76
MATRIX A
1 2 3
4 5 6
7 8 9
DICTIONARY
A dictionary is like a list, but more in general. In a list, index value is an integer; while in a dictionary index
value can be any other data type and are called keys. The key will be used as a string as it is easy to recall. A
dictionary is extremely useful data storage construct for storing and retrieving all key value pairs, where
each element is accessed (or indexed) by a unique key. However, dictionary keys are not in sequences and
hence maintain no left-to-right order.
Key-value pair
We can refer to a dictionary as a mapping between a set of indices (which are called keys) and a set of
values. Each key maps a value. The association of a key and a value is called a key-value pair. Its syntax:
my_dict = ,'key1': 'value1','key2': 'value2','key3': 'value3'…'keyn': 'valuen'-
pg. 77
H=dict() OUTPUT
H["one"]="keyboard" {'one': 'keyboard', 'two': 'Mouse', 'three': 'printer',
H["two"]="Mouse" 'Four': 'scanner'}
H["three"]="printer"
H["Four"]="scanner"
print(H)
Traversing a Dictionary- Visiting each element of the dictionary to display on screen can be done by using
'for-loop'. Example-
H={'four': 'scanner', 'three': 'printer', 'two': 'Mouse', 'one': 'keyboard'}
for i in H:
print(i,":", H[i],end='\t\t')
OUTPUT
four : scanner three : printer two : Mouse one : keyboard
OR
H = {'Four': 'scanner', 'three': 'printer', 'two': 'Mouse', 'one': 'keyboard'}
print("i value\tH[i] value")
for i in H:
print(i,"\t", H[i])
OUTPUT
i value H[i] value
Four scanner
three printer
two Mouse
one keyboard
Creating, initializing values during run time (Dynamic allocation)- We can create a dictionary during run
time also by using dict() function. This way of creation is called dynamic allocation. Because during run
time, keys and values are added to the dictionary.
Example- WAP in Python to input sections and class teachers name in 11th class and display all information
on the output screen.
Solution:
classxi=dict()
n=input("Enter total number of section in xi class: "); n=int(n)
i=1
while i<=n:
a=input("Enter section: ")
b=input ("Enter class teacher name: ")
classxi[a]=b
i=i+1
print("Class\tSection\tteacher name")
for i in classxi:
print("XI\t",i,"\t",classxi[i])
OUTPUT
Enter total number of section in xi class: 5
pg. 78
Enter section: A
Enter class teacher name: Amar Malik
Enter section: B
Enter class teacher name: Bikram Sirohi
Enter section: C
Enter class teacher name: Chaman Singh
Enter section: D
Enter class teacher name: Dharm Singh
Enter section: E
Enter class teacher name: Eshwar Deol
Class Sectionteacher name
XI A Amar Malik
XI B Bikram Sirohi
XI C Chaman Singh
XI D Dharm Singh
XI E Eshwar Deol
Appending values to the dictionary- We can add new elements to the existing dictionary, extend it with
single pair of values or join two dictionaries into one. If we want to add only one element to the dictionary,
then we should use the following method. Syntax:
Dictionary name [key] = value
Example-
D={"mon":"monday","tue":"tuesday","wed":"wednesday"}
D["thu"]="thursday"
print(D)
OUTPUT
{'mon': 'monday', 'tue': 'tuesday', 'wed': 'wednesday', 'thu': 'thursday'}
pg. 79
Removing an item from dictionary
One can remove an item from the existing dictionary by using del key word. The syntax is:
del dicname[key]
Example-
D={'d1':'mon','d2':'tue','d3':'wed','d4':'thu','d5':'fri','d6':'sat','d7':'sun'}
del D['d3']
print(D)
OUTPUT
{'d1': 'mon', 'd2': 'tue', 'd4': 'thu', 'd5': 'fri', 'd6': 'sat', 'd7': 'sun'}
SOLVED EXAMPLES
1. WAP in Python to input ‘n’ names and phone numbers of friends to store it in a dictionary. Now input
any name of your friend and print his/her phone number.
Solution:
#!dict_01.py
phonebook=dict()
n=input("Enter total number of friends: "); n=int(n)
i=1
while i<=n:
a=input("Enter name: "); b=input("Enter phone number: ")
phonebook[a]=b
i=i+1
OUTPUT
Enter total number of friends: 4
Enter name:Piyush
Enter phone number: 9192939495
Enter name:Suresh
Enter phone number: 9128384857
Enter name:Prateek
Enter phone number: 7263646528
Enter name:Rahul
Enter phone number: 4256727548
Enter name whose phone number is to be searched: Prateek
7263646528
2. WAP in Python to input 'n' employee numbers and names and to display all information of employees
in ascending order based upon their employee number.
Solution:
#!dict_02.py
empinfo=dict()
n=input("Enter total number of employees: "); n=int(n)
i=1
while i<=n:
a=input("Enter number: ")
b=input("Enter name: ")
empinfo[a]=b
i=i+1
empno=list(empinfo.keys())
empno.sort()
print("Employee Information")
pg. 81
print("Emp No.\tEmp Name")
for i in empno:
print(i,'\t',empinfo[i])
3. Write the output for the following Python code:
A={1:100, 2:200, 3:300, 4:400, 5:500}
Print(A.items())
Print(A.keys())
print (A.values())
OUTPUT
dict_items([(1, 100), (2, 200), (3, 300), (4, 400), (5, 500)])
dict_keys([1, 2, 3, 4, 5])
dict_values([100, 200, 300, 400, 500])
4. # WAP in Python to create a phone book and delete particular phone number using name.
Solution:
#!dict_04.py
phonebook=dict()
n=input("Enter total number of friends: "); n=int(n)
for i in range(1,n+1,1):
a=input("Enter name: "); b=input("Enter phone number: ")
phonebook[a]=b
OUTPUT
Enter total number of friends: 4
Enter name: Arun
Enter phone number: 1928374655
Enter name: Yash Veer
Enter phone number: 5674839211
Enter name: Tejbir
Enter phone number: 9812873476
Enter name: Jaswant
Enter phone number: 3746558291
for i in range(1,n+1,1):
year=input("Enter year: "); cityPopulation=input("Enter city population in this year: ")
populationRegister[year]=cityPopulation
L=list(populationRegister.keys())
print("Year-Wise City Population Information")
print("Year\t\tPhone number")
for i in L:
print(i,'\t\t',populationRegister[i])
OUTPUT
Enter total number of years: 5
Enter year: 1980
Enter city population in this year: 100000
Enter year: 1990
Enter city population in this year: 120000
Enter year: 2000
Enter city population in this year: 141000
Enter year: 2010
Enter city population in this year: 163000
Enter year: 2017
Enter city population in this year: 180000
Year-Wise City Population Information
Year Phone number
1980 100000
1990 120000
2000 141000
2010 163000
2017 180000
6. Write a code in Python to input 'n' number of subjects and head of the departments and also display
all information on the output screen.
#!dict_05.py
HOD=dict()
n=input("Enter total number of subjects: "); n=int(n)
for i in range(1,n+1,1):
subName=input("Enter Subject: "); hodName=input("Enter HOD name in this subject: ")
HOD[subName]=hodName
L=list(HOD.keys())
print("Subject-Wise HOD Names")
print("Subject\t\t\tHOD Name")
for i in L:
pg. 83
print(i,'\t\t\t',HOD[i])
OUTPUT
Enter total number of subjects: 5
Enter Subject: Psysics
Enter HOD name in this subject: Pallavi Joshi
Enter Subject: Chemistry
Enter HOD name in this subject: Raman Singh
Enter Subject: Mathematics
Enter HOD name in this subject: RN Singh
Enter Subject: Biology
Enter HOD name in this subject: Gajendra Chauhan
Enter Subject: Computer Science
Enter HOD name in this subject: Lavinder Sodhi
Subject-Wise HOD Names
Subject HOD Name
Psysics Pallavi Joshi
Chemistry Raman Singh
Mathematics RN Singh
Biology Gajendra Chauhan
Computer Science Lavinder Sodhi
7. Re-write the following code after correction. Underline each correction made.
Given Code: Corrected Code:
c=dict() c=dict()
n=int(input(Enter total number: )) n=int(input("Enter total number: ")) #e01
i=1 i=1
while i<=n while i<=n: #e02
a=input("Enter place: ") a=input("Enter place: ")
b=input("Enter number: ") b=input("Enter number: ")
c(a)=b c[a]=b #e03
i=i+1 i=i+1
print("Place\t\tNumber") print("Place\t\tNumber")
for i in c: for i in c:
print(i,"\t\t",cla[i]) print(i,"\t\t",c[i]) #e04
OUTPUT OUTPUT
(10, 20) <class 'tuple'> ('sun', 'mon', 'tue') <class 'tuple'>
v) T='P','Y','T','H','O','N' #or T=('P','Y','T','H','O','N') L1=[10, 20]; L2=[100,200]
print(T, type(T)) T=L1,L2 # or T=(L1, L2)
print(T, type(T))
OUTPUT
'P', 'Y', 'T', 'H', 'O', 'N') <class 'tuple'> OUTPUT
([10, 20], [100, 200]) <class 'tuple'>
Tuple Creation-
i) If we need to create a tuple with a single ii) Another way of creating tuple is built-in
element, we need to include a final comma. function tuple (). It creates empty tuple.
Example- OUTPUT Example- OUTPUT
T=10, (10,) T = tuple() ()
Print(T) Print(T)
Add New Element to Tuple-
i) We can add new element to tuple using + ii) #WAP to add 'n' numbers & store in the tuple.
operator. See the following code: T=tuple()
T=(10,20,30,40) n=int(input("How many numbers to input: "))
print("Tuple before modification: ",T) for i in range(n):
T+(60,) # this will not create modification of T. print("Enter number ",i+1,": ", end=' ')
print("Result of T+(60,): ",T) a=int(input()); T=T+(a,)
T=T+(60,) # this will do modification of t. print("Output is: ", T) OR
print("Result of T=T+(60,): ",T) print("Output is: ", end=' ')
for i in range(n):
OUTPUT OUTPUT print(T[i], end=' ')
Tuple before modification: (10, 20, 30, 40) How many numbers to input: 3
Result of T+(60,): (10, 20, 30, 40) Enter number 1 : 10
Result of T=T+(60,): (10, 20, 30, 40, 60) Enter number 2 : 30
Enter number 3 : 20
Output is: (10, 30, 20)
iii) We can also add new element to tuple by using list. For that we have to convert the tuple into a list
first and then use append() function to add new elements to the list. After completing the addition,
convert the list into tuple. Following example illustrates how to add new elements to tuple using a list.
See the following code:
T=tuple() #It creates empty tuple
print(T)
L1=list(T) #It convert tuple into list
L1.append(10) #Add new elements to list
L1.append(20)
T=tuple(L1) #It convert list into tuple
print(T)
OUTPUT
pg. 85
()
(10, 20)
Initializing tuple values-
T=(0,)*10 OUTPUT
print(T) (0, 0, 0, 0, 0, 0, 0, 0, 0, 0)
Tuple Assignment-
i) To interchange (swap) any two variable values, ii) Python provides more elegant tuple
temporary variable is used. See the following assignment. See the following code:
code: A=(1,2); B=(11,22,33) # A & B are tuples
A=10; B=20 #A & B are not tuples print("Tuple A & B before swapping:",A,B)
print("Tuple A & B before swapping:",A,B) A,B=B,A
T=A; A=B; B=T print("Tuple A & B after swapping:",A,B)
print("Tuple A & B after swapping:",A,B)
OUTPUT
OUTPUT Tuple A & B before swapping: (1, 2) (11, 22, 33)
Tuple A & B before swapping: 10 20 Tuple A & B after swapping: (11, 22, 33) (1, 2)
Tuple A & B after swapping: 20 10 NOTE: T1,T2,T3=T3,T1,T2 is also valid
Tuple Slices-
Slice operator works on Tuple also. This is used to display more than one selected value on the output
screen. Slices are treated as boundaries and the result will contain all the elements between boundaries.
The syntax is:
Seq = T [start: stop: step]
Where start, stop & step all three are optional. If we omit first index, slice starts from ‘0’. On omitting stop,
slice will take it to end. Default value of step is 1. Some examples-
i) T=(10,20,30,40,50) ii) T=(10,20,30,40,50)
T1=T[2:4] T1=T[:] # or T[::] Produces a copy of Tuple T
print(T1) print(T1)
OUTPUT OUTPUT
(30, 40) (10, 20, 30, 40, 50)
In this example, starting position is 2 and
ending position is 3(4-1), so the selected
elements are 30 & 40.
iii) T=(10,20,30,40,50) iv) T=(10,20,30,40,50, 60, 70)
T1=T[::2] T1=T[::3] #Will produce a Tuple with positions
#Produces a Tuple with positions 0, 2 and 4 0,3,6
print(T1) print(T1)
OUTPUT OUTPUT
(10, 30, 50) (10, 40, 70)
v) T=(10,20,30,40,50) vi) T=(10,20,30,40,50)
T1=T[2:] #Will produce a Tuple from 2 to end. T1=T[:3] #Produces a Tuple 0 to 2(3-1)
print(T1) print(T1)
OUTPUT OUTPUT
(30, 40, 50) (10, 20, 30)
Tuple Functions-
pg. 86
Function Name Description Example
cmp(t1,t2) Returns 0 if both tupless are same T1=(10,20,30)
Returns 1 if t1 has more number of items, T2=(100,200,300)
otherwise -1. T3=(10,20,30)
Note: cmp() is valid for Python version earlier print(cmp(T1,T3))
than 3.0 print(cmp(T2,T1))
print(cmp(T1,T2))
0
1
-1
len(t1) It returns, number of items in a tuple t1. t1=(100,200,300,400,500)
print(len(t1))
5
max(t1) It returns its largest item in the tuple t1. t1=(100,200,300,400,500)
print(max(t1)
500
min(t1) It returns its smallest item in the tuple t1. t1=(100,200,300,400,500)
print(min(t1)
100
tuple() It is used to create empty tuple. t1=tuple()
print(t1)
()
SOLVED EXAMPLES
1. WAP in Python to input 5 subject names and put it in tuple and display that tuple information on the
output screen.
Solution: OUTPUT
Enter all subjects one after other Enter all subjects one after other
Enter subject: Eng Enter subject: Eng
Enter subject: Math Enter subject: Math
Enter subject: Phy Enter subject: Phy
Enter subject: Chem Enter subject: Chem
Enter subject: CS Enter subject: CS
t1= ('Eng', 'Math', 'Phy', 'Chem', 'CS') t1= ('Eng', 'Math', 'Phy', 'Chem', 'CS')
2. WAP In Python to input any two tuples and interchange the tuple values.
Solution: OUTPUT
t1=tuple() Total number of values in first tuple:3
m=int(input("Total number of values in first Enter elements: 10
tuple:")) Enter elements: 20
for i in range(m): Enter elements: 30
a=input("Enter elements: ") Total number of values in second tuple: 4
t1=t1+(a,) Enter elements: 100
t2=tuple() Enter elements: 200
n=int(input("Total number of values in second Enter elements: 300
tuple: ")) Enter elements: 400
for i in range(n): First Tuple: ('10', '20', '30')
a=input("Enter elements: ") Second Tuple: ('100', '200', '300', '400')
t2=t2+(a,) AFTER SWAPPING
First Tuple: ('100', '200', '300', '400')
print("First Tuple: ", t1); Second Tuple: ('10', '20', '30')
pg. 87
print("Second Tuple:", t2);
t1,t2=t2,t1
print("AFTER SWAPPING")
print("First Tuple: ", t1);
print("Second Tuple:", t2);
3. WAP in Python to input 'n' numbers and store it in a tuple and find maximum & minimum values in
the tuple without use of Python function.
Solution: OUTPUT
t1=tuple() Total number of values in a tuple:5
n=int(input("Total number of values in a tuple:")) Enter elements: 30
for i in range(n): Enter elements: 20
a=int(input("Enter elements: ")) Enter elements: 50
t1=t1+(a,) Enter elements: 10
Enter elements: 40
big=small=t1[0] Maximum value= 50
for i in range(1, n): Minimum value= 10
if t1[i]>big:
big=t1[i]
if t1[i]<small:
small=t1[i]
print("Maximum value=",big)
print("Minimum value=",small)
4. Find the output from the following code: OUTPUT
T=(10,30,2,50,5,6,100,65) 100
print(max(T)) 2
print(min(T))
5. Find the output from the following code: OUTPUT
t=tuple() ('PYTHON',)
t = t +('PYTHON',) 1
print(t) 3
print(len(t))
t1=(10,20,30)
print(len(t1))
6. Write the output from the following codes:
i) t=(10,20,30,40,50) OUTPUT
print(len(t)) 5
ii) t=('a','b','c','A','B') OUTPUT
print(max(t)) c
print(min(t)) A
iii) t=tuple() OUTPUT
print(len(t)) 0
iv) T1=(10,20,30,40,50) OUTPUT
T2=(100,200,300) (10, 20, 30, 40, 50, 100, 200, 300)
T3=T1+T2
print(T3)
7. WAP in Python to input two sets of values and store them in tuples and also do the comparison.
Solution: OUTPUT1
pg. 88
t1=tuple() Total number of values in first tuple:3
m=int(input("Total number of values in first Enter elements: 1
tuple:")) Enter elements: 2
for i in range(m): Enter elements: 3
a=int(input("Enter elements: ")) Total number of values in second tuple: 2
t1=t1+(a,) Enter elements: 1
t2=tuple() Enter elements: 2
n=int(input("Total number of values in second t1 is bigger than t2
tuple: ")) OUTPUT2
for i in range(n): Total number of values in first tuple:2
a=int(input("Enter elements: ")) Enter elements: 1
t2=t2+(a,) Enter elements: 2
Total number of values in second tuple: 3
cmpRes=0 Enter elements: 1
len1=len(t1) Enter elements: 2
len2=len(t2) Enter elements: 3
if len1>len2: t1 is smaller than t2
cmpRes=1 OUTPUT3
print("t1 is bigger than t2") Total number of values in first tuple:3
elif len1<len2: Enter elements: 1
cmpRes=-1 Enter elements: 2
print("t1 is smaller than t2") Enter elements: 3
else: Total number of values in second tuple: 3
for i in range(len1): Enter elements: 1
if t1[i] != t2[i]: Enter elements: 2
cmpRes=2 Enter elements: 3
break; t1 is identical to t2
if cmpRes==0: OUTPUT4
print("t1 is identical to t2") Total number of values in first tuple:3
elif cmpRes==2: Enter elements: 1
print("Same size t1 & t2 are different") Enter elements: 2
Enter elements: 3
Total number of values in second tuple: 3
Enter elements: 10
Enter elements: 20
Enter elements: 30
Same size t1 & t2 are different
8. WAP in Python to input 'n' numbers and separate the tuple in the following manner. See the example:
If given tuple T=(10,20,30,40,50,60) then slice it into T1 and T2 such that T1 =(10,30,50) and
T2=(20,40,60)
Solution: OUTPUT
T=tuple() Total number of values in tuple:6
m=int(input("Total number of values in tuple:")) Enter elements: 10
for i in range(m): Enter elements: 20
a=int(input("Enter elements: ")) Enter elements: 30
T=T+(a,) Enter elements: 40
T1=T[0:m:2] Enter elements: 50
T2=T[1:m:2] Enter elements: 60
print("First Slice: ", T1) First Slice: (10, 30, 50)
pg. 89
print("Second Slice: ", T2) Second Slice: (20, 40, 60)
9. Let a, b and c be the three sides of a right triangle such that i) c 2=b2+c2, ii) c=b+1 and iii) The side a>1
and is an odd integer. WAP in Python to input the value of 'a' and compute 'b' and 'c'. Add all three
sides into a tuple and display the tuple on screen. Create three such sets.
Solution: OUTPUT
for i in range(3): Enter side a: 3
T=tuple() Tuple content: (3, 4, 5)
a=int(input("Enter side a: ")) Enter side a: 5
if a>1 and a%2==1: Tuple content: (5, 12, 13)
b=(a**2-1)//2 Enter side a: 7
c=b+1 Tuple content: (7, 24, 25)
T=T+(a,) +(b,) + (c,)
print("Tuple content: ", T)
10. Let a, b and c be the three sides of a right triangle such that i) c2=b2+c2, ii) c=b+2 and iii) The side a>2
and is an even integer. WAP in Python to input the value of 'a' and compute 'b' and 'c'. Add all three
sides into a tuple and display the tuple on screen. Create three such sets.
Solution: OUTPUT
for i in range(3): Enter side a: 4
T=tuple() Tuple content: (4, 3, 5)
a=int(input("Enter side a: ")) Enter side a: 6
if a>2 and a%2==0: Tuple content: (6, 8, 10)
b=(a//2)**2-1 Enter side a: 8
c=b+2 Tuple content: (8, 15, 17)
T=T+(a,) +(b,) + (c,)
print("Tuple content: ", T)
Original
collection
Iteration1: The element a[0] i.e. 8 is compared with a[1] i.e. 5, since 8>5 therefore exchange 8 with 5.
The element a[1] i.e. 8 and a[2] i.e. 9 are already in ascending order so no exchange required.
The element a[2] i.e. 9 and a[3] i.e. 3 are not in ascending order so exchange a[2] with a[3]
pg. 90
The element a[3] i.e. 9 and a[4] i.e. 16 are in ascending order so no exchange required.
The element a[4] i.e. 16 and a[5] i.e. 4 are not in ascending order so exchange a[4] with a[5]
The element a[5] i.e. 16 and a[6] i.e. 7 are not in ascending order so exchange a[5] with a[6]
Since in iteration1 some elements were exchanged with each other which shows that
collection was not sorted yet, next iteration continues. The algorithm will terminate only if
the last iteration do not process any exchange operation which assure that all elements of the
array are in proper order.
In iteration2, some exchange operations were processed. So, at least one more iteration is
required to assure that collection is in sorted order.
Iteration3:
Iteration4:
Iteration5:
In iteration 5 no exchange operation executed because all elements are already in proper
order therefore the algorithm will terminate after 5th iteration.
pg. 91
WAP in Python to accept m distinct integers (in random order) in the list and sort them in ASC order
using Bubble Sort Algorithm.
Solution: OUTPUT
#!List_BubbleSort.py Enter 7 Intrger Elements in the List:
8
m=7; L=list() 5
print("Enter", m, "Intrger Elements in the List:") 9
for i in range(0, m, 1): 3
a=int(input()) 16
L.append(a) 4
7
print("Origional List: ", L) Origional List: [8, 5, 9, 3, 16, 4, 7]
for i in range(0, m, 1): List After Iteration 1 is [5, 8, 3, 9, 4, 7, 16]
swapping=False List After Iteration 2 is [5, 3, 8, 4, 7, 9, 16]
for j in range(0, m-1, 1): List After Iteration 3 is [3, 5, 4, 7, 8, 9, 16]
if L[j]>L[j+1]: List After Iteration 4 is [3, 4, 5, 7, 8, 9, 16]
swapping=True List After Iteration 5 is [3, 4, 5, 7, 8, 9, 16]
temp=L[j]
L[j]=L[j+1]
L[j+1]=temp
if swapping==True:
print("List After Iteration",i+1,"is",L)
else:
print("List After Iteration",i+1,"is",L)
break
WAP in Python to accept m distinct integers (in random order) in the tuple and sort them in ASC order
using Bubble Sort Algorithm.
Solution: OUTPUT
#!Tuple_BubbleSort.py Enter 7 Integer Elements in the Tuple:
m=7; T=tuple() 8
print("Enter", m, "Integer Elements in the Tuple:") 5
for i in range(0, m, 1): 9
a=int(input()) 3
T=T+(a,) 16
4
print("Origional Tuple: ", T) 7
for i in range(0, m, 1): Origional Tuple: (8, 5, 9, 3, 16, 4, 7)
swapping=False Tuple After Iteration 1 is (5, 8, 3, 9, 4, 7, 16)
for j in range(0, m-1, 1): Tuple After Iteration 2 is (5, 3, 8, 4, 7, 9, 16)
if T[j]>T[j+1]: Tuple After Iteration 3 is (3, 5, 4, 7, 8, 9, 16)
swapping=True Tuple After Iteration 4 is (3, 4, 5, 7, 8, 9, 16)
T1=T[0:j] Tuple After Iteration 5 is (3, 4, 5, 7, 8, 9, 16)
T2=T[j+1:j+2]
T3=T[j:j+1]
T4=T[j+2:]
T=T1+T2+T3+T4
if swapping==True:
print("Tuple After Iteration",i+1,"is",T)
pg. 92
else:
print("Tuple After Iteration",i+1,"is",T)
break
Insertion Sort- Insertion sort algorithm divides the collection of n elements into two subparts, the first
subpart contain a[0] to a[k] elements in sorted order and the second subpart contain a[k+1] to a[n] which
are to be sorted. The algorithm starts with only first element in the sorted subpart because collection of
one element is itself in sorted order. In each pass, the first element of the unsorted subpart is removed and
is inserted at the appropriate position in the sorted collection so that the sorted collection remain in sorted
order and hence in each pass the size of the sorted subpart is increased by 1 and size of unsorted subpart is
decreased by 1. This process continues until all n-1 elements of the unsorted collection are inserted at
their appropriate position in the sorted array. For example, consider the following unsorted collection to
be sorted using selection sort:
Original 0 1 2 3 4 5 6
Collection 8 5 9 3 16 4 7
Sorted ----------------------Unsorted-----------------------
Initially the sorted subpart contains only one element i.e. 8 and the unsorted subpart contains
n-1 elements where n is the number of elements in the given collection.
Iteration1: To insert first element of the unsorted subpart i.e. 5 into the sorted subpart, 5 is compared
with all elements of the sorted subpart starting from rightmost element to the leftmost
element, shift all elements of the sorted subpart whose value is greater than 5 one position
towards right to create an empty place at the appropriate position in the sorted array, store 5
at the created empty place, here 8 will move from position a[0] to a[1] and a[0] is filled by 5.
After first pass the status of the collection is:
0 1 2 3 4 5 6
5 8 9 3 16 4 7
--Sorted-- -------------------Unsorted---------------
Iteration2: In 2nd pass, 9 is the first element of the unsorted subpart, 9 is compared with 8, since 8 is less
than 9 so no shifting takes place and the comparing loop terminates. So the element 9 is
added at the rightmost end of the sorted subpart. After second pass the status of the
collection is:
0 1 2 3 4 5 6
5 8 9 3 16 4 7
--------Sorted------- -----------Unsorted-----------
Iteration3: In 3rd pass, 3 is compared with 9, 8 and 5 and therefore, shift will take place one position
towards right and insert 3 at position a[0]. After third pass the status of the collection is:
0 1 2 3 4 5 6
3 5 8 9 16 4 7
---------------Sorted----------- -----Unsorted------
Iteration4: In 4th pass, 16 is greater than the largest number of the sorted subpart so it remains at the
same position in the array. After fourth pass the status of the collection is:
pg. 93
0 1 2 3 4 5 6
3 5 8 9 16 4 7
--------------------Sorted----------------- Unsorted
Iteration5: In 5th pass, 4 is inserted after 3. After fifth pass the status of the collection is:
0 1 2 3 4 5 6
3 4 5 8 9 16 7
-------------------------Sorted----------------------- Unsorted
Iteration6: In 6th pass, 7 is inserted after 5. After fifth pass the status of the array is:
0 1 2 3 4 5 6
3 4 5 7 8 9 16
-------------------------------Sorted----------------------------
Insertion sort takes advantage of sorted(best case) or partially sorted(average case) collection
because if all elements are at their right place then in each pass only one comparison is
required to make sure that the element is at its right position. So for n=7 only 6 (i.e. n-1)
iterations are required and in each iteration only one comparison is required i.e. total number
of comparisons required= (n-1)=6 which is better than other sort methods. Therefore
insertion sort is best suited for sorted or partially sorted arrays.
WAP in Python to accept m distinct integers (in random order) in the list and sort them in ASC order
using Insertion Sort Algorithm.
Solution: OUTPUT
#!List_ InsertionSort.py Enter 7 Integer Elements in the Tuple:
#!List_ InsertionSort.py 8
m=7; L=[] 5
print("Enter", m, "Intrger Elements in the List:") 9
for i in range(0, m, 1): 3
a=int(input()) 16
L.append(a) 4
7
print("Origional List: ", L) Origional List: [8, 5, 9, 3, 16, 4, 7]
List After Iteration 1: [5, 8, 9, 3, 16, 4, 7]
for i in range(1, m): List After Iteration 2: [5, 8, 9, 3, 16, 4, 7]
temp=L[i] List After Iteration 3: [3, 5, 8, 9, 16, 4, 7]
j=i-1 List After Iteration 4: [3, 5, 8, 9, 16, 4, 7]
while(j>=0 and L[j]>temp): List After Iteration 5: [3, 4, 5, 8, 9, 16, 7]
L[j+1]=L[j] List After Iteration 6: [3, 4, 5, 7, 8, 9, 16]
j=j-1
L[j+1]=temp
print("List After Iteration: ",i,L)
WAP in Python to accept m distinct integers (in random order) in the tuple and sort them in ASC order
using Insertion Sort Algorithm.
Solution: OUTPUT
#!Tuple_InsertionSort.py Enter 7 Integer Elements in the Tuple:
#!Tuple_InsertionSort.py 8
pg. 94
m=7; T=tuple() 5
print("Enter", m, "Integer Elements in the Tuple:") 9
for i in range(0, m, 1): 3
a=int(input()) 16
T=T+(a,) 4
7
print("Origional Tuple: ", T) Origional Tuple: (8, 5, 9, 3, 16, 4, 7)
for i in range(1, m): Tuple After Iteration 1 is: (5, 8, 9, 3, 16, 4, 7)
temp=T[i] Tuple After Iteration 2 is: (5, 8, 9, 3, 16, 4, 7)
j=i-1 Tuple After Iteration 3 is: (3, 5, 8, 9, 16, 4, 7)
while(j>=0 and T[j]>temp): Tuple After Iteration 4 is: (3, 5, 8, 9, 16, 4, 7)
T=T[0:j+1] + (T[j],) + T[j+2:] #Shifting element Tuple After Iteration 5 is: (3, 4, 5, 8, 9, 16, 7)
from 'j' to 'j+1' position Tuple After Iteration 6 is: (3, 4, 5, 7, 8, 9, 16)
j=j-1
T=T[0:j+1] +(temp,) + T[j+2:] #Upon exit while-
loop, temp will be stored at 'j+1' position
print("Tuple After Iteration",i,"is:",T)
pg. 95
it should be preceded by a backslash. string it should be preceded by a backslash.
Enclosing the string in triple quotes
str="""An error does not become truth by reason of multiplied propagation, nor does truth become
error because nobody sees it."""
>>> print(str)
An error does not become truth by reason of multiplied propagation, nor does truth become error
because nobody sees it.
Note: Triple quotes are used when the text is multiline.
Escape sequence- An escape sequences is nothing but a special character that has a specific function. As
shown above, backslash (\) is used to escape the single or double quote.
Escape sequence Meaning Example
\n New line >>> print("Hot\nCold")
Hot
Cold
\t Tab space >>> print("Hot\tCold")
Hot Cold
\' (or \" or \""") Single (or Double or Triple) >>>print('This book belongs to Raghav\'s sister')
quote This book belongs to Raghav's sister
String Comparison in Python- To compare two or more string values in Python, one uses comparison (i.e.
relational) operators such as ==, !=, <, <=, >, >=. When comparing values, Python always returns either
"True" or "False" to indicate the result. The format used is "strLitral1 operator strLitral2" or "strVar1
pg. 96
operator strVar2". Python also supports chained comparisons such as a>b>c (i.e. a>b and b>c). There are
some functions used for comparison. See the table below:
pg. 97
Syntax Explanation Example Output
str[n:m] The slice operator [n:m] extracts substring A="Save Earth"
from str, with starting index n to m-1. print(A[2:6]) ve E
If n is omitted, slice operator works from 0 print(A[:6]) Save E
to m-1. print(A[2:]) ve Earth
If m is omitted, slice operator works from n print(A[:]) Save Earth
to the end of the string.
If n & m both are omitted, slice operator
works from 0 to the end of the string.
str.split([sep[, The function splits the string into str="z#sr#sec#sch"
maxsplit]]) substrings using the separator. The second print(str.split('#')) ['z', 'sr', 'sec', 'sch']
argument is optional and its default value is print(str.split('#',2)) ['z', 'sr', 'sec#sch']
m*1. If an integer value N is given for the print(str.split('s')) ['z#', 'r#', 'ec#', 'ch']
second argument, the string is split in N+1*2 print(str.split('s',1)) ['z#', 'r#sec#sch']
strings.
*1: Number of separators + 1
*2: N+1 !> Number of separators + 1
find(sub[, The function is used to search the first str='mammals'
start[, end]]) occurrence of the substring in the given print(str.find('ma')) 0
string. It returns the index at which the print(str.find('ma',2)) 3
substring starts. It returns -1 if the print(str.find('ma',2,4)) -1
substring does occur in the string. print(str.find('ma',2,5)) 3
re.search(str, The search function traverses through the See Qn No. 7 under "SOLVED EXAMOLE ON
gstr) string and determines the position where STRINNGS"
the str matches the gstr.
str.replace(old, The function replaces all the occurrences of str="HELLO"
new) the old string with the new string print(str.replace('L','#')) HE##O
print(str.replace('L','**')) HE****O
sepstr.join(tuple) Returns a string in which the tuple tstr=('jan', 'feb' ,'mar')
elements (each element is a string) have print('*'.join(tstr)) jan*feb*mar
been joined by a separator string.
pg. 98
declaring objects. Objects change its state during different
functions/actions performed on objects. In state transition
diagram it is represented that what actions are there
which leads to change the state of the object. There are
some symbols used in design of STD, given at RHS:
pg. 99
word = 'pineapple'
count = 0
for letter in word:
if letter == 'p':
count = count + 1
print(count)
3. #WAP in Python to input a string "Green Revolution". OUTPUT
Print this string in reverse order. Also print the string Enter a String: Green Revolution
after reversing. Printing in Reversed Order: noituloveR
#!str_reversing.py neerG
str=input("Enter a String: ") Printing After Reversing: noituloveR neerG
length=len(str)
print("Printing in Reversed Order: ",end='')
for i in range(1, length+1, 1):
print(str[-i],end='')
revStr=''
for i in range(length, 0, -1):
revStr = str[-i] + revStr
print("\nPrinting After Reversing: ", revStr)
4. WAP in Python to count number of words in a string. OUTPUT
#!Str_CountWords.py Enter a String: Education is a continuous
str=input("Enter a String: ") and creative process
countWord=0 Number of Words: 7
for ch in str:
if ch==' ':
countWord=countWord+1
print("Number of Words:", countWord+1)
5. WAP in Python to split the string at every occurrence OUTPUT
of a blank. There should not be two successive blanks Enter a String: Mr. Amit How are you?
in the string. No punctuation mark should appear in Mr
split word. Amit
#!Str_SplitAtBlankSpaces.py How
str=input("Enter a String: ") are
S='' you
for ch in str:
if ch!=' ':
if ch.isalnum():
S=S+ch
else:
print(S)
S=''
if S !='':
print(S)
pg. 100
#!Str_SplitAtGivenChar.py ucce
str1=input("Enter a String: ") or
str2=''
for ch in str1:
if ch!='s' and ch!='S':
str2=str2+ch
elif str2!='':
print(str2)
str2=''
if str2 !='':
print(str2)
7. WAP in Python to determine if the given substring is OUTPUT
present in the string. water found at: 6 ,ends at: 11
#!Str_SeachSubString.py
import re
givenstr='Water water everywhere but not a drop to
drink'
substr='water'
search1=re.search(substr,givenstr)
if search1:
startpos=search1.start()
endpos=search1.end()
print(substr,"found at:",startpos,",ends at:", endpos)
else:
print("No match found")
8. WAP in Python to print the following pyramid. OUTPUT
1 1
22 22
333 333
4444 4444
55555 55555
#!Str_PrintPyramid.py
m=6
for i in range(1,m):
for j in range(1,i+1):
print(i, end=' ')
print()
9. Give the output of the following statements OUTPUT
str='Honesty is the best policy' Honesty-is-the-best-policy
str=str.replace(' ', '-')
print(str)
10. WAP in Python to replace each blank with the hyphen OUTPUT
(i.e '-') in the given string. Enter the String: Honesty is the best policy
#!Str_ReplaceBlank New String is: Honesty-is-the-best-policy
str=input("Enter the String: ")
str1=''
pg. 101
for ch in str:
if ch !=' ':
str1=str1 + ch
else:
str1=str1 + '-'
print("New String is:", str1)
11. WAP in Python to print alternate characters in a string. OUTPUT
Input a string of your own choice. Enter the String: Honesty is the best policy
#!Str_PrintAlternateChar Enter index to start: 0
str=input("Enter the String: ") Hnsyi h etplc
start=int(input("Enter Index to start: "))
m=len(str) Enter the String: Honesty is the best policy
for i in range(start,m,2): Enter index Number to start: 1
print(str[i],end=' ') oet stebs oiy
12. WAP in Python to extract m characters either from left OUTPUT
side or right side or from the middle of the given Enter a String: Rosary Sr Sec School
string. Written program must be menu driven. How Many Characters to extract: 4
#!Str_ExtractSubString.py MAIN MENU
gstr=input("Enter a String: ") 1. Extract From Left Side
n=int(input("How Many Characters to extract: ")) 2. Extract From RTight Side
print("\tMAIN MENU\n1. Extract From Left Side\n2. 3. Extract From Middle
Extract From Right Side") Enter Your Choice...1
print("3. Extract From Middle\nEnter Your Choice...", Extracted String is: Rosa
end='')
choice=int(input()) Enter a String: Rosary Sr Sec School
str='' How Many Characters to extract: 4
if choice==1: MAIN MENU
for i in range(0, n): 1. Extract From Left Side
str = str + gstr[i] 2. Extract From Right Side
print("Extracted String is:", str) 3. Extract From Middle
elif choice==2: Enter Your Choice...2
for i in range(-1, -(n+1), -1): Extracted String is: hool
str = gstr[i] + str
print("Extracted String is:", str) Enter a String: Rosary Sr Sec School
elif choice==3: How Many Characters to extract: 6
m=int(input("Enter from which index to start MAIN MENU
extraction: ")) 1. Extract From Left Side
for i in range(m, m+n): 2. Extract From Right Side
str = str + gstr[i] 3. Extract From Middle
print("Extracted String is:", str) Enter Your Choice...3
Enter from which index to start extraction:
7
Extracted String is: Sr Sec
13. #Input a string "Python". WAP to print all the letters OUTPUT
except the letter "y". Enter the String: python
#!Str_DispLetters.py pthon
str=input("Enter the String: ") Newly Created String: pthon
pg. 102
str1=''
for ch in str:
if ch !='y' and ch != 'Y':
print(ch, end='')
str1=str1+ch #New string created that contains all
letters but 'y'
print("\nNewly Created String: ",str1)
To use these modules in the program, a programmer needs to import the module. Once you import a
module, you can reference (use), any of its functions or variables in your code. Following are two ways to
import a module in a program:
The import statement is simplest and most common way to use modules in our code. Its syntax is:
import modulename1 [,modulename2, …, ,…, modulenamem]
Example-
import math
On execution of this statement, Python will
i) Search for the file 'math.py'.
ii) Create space where modules definition & variable will be created,
iii) Then execute the statements in the module.
Now the definitions of the module will become part of the code in which the module was imported.
To use/ access/invoke a function, you will specify the module name and name of the function- separated
by dot (.). This format is also known as dot notation.
Example- value= math.sqrt (25) # dot notation
The example uses sqrt( ) function of module math to calculate square root of the value provided in
parenthesis, and returns the result which is inserted in the value. The expression (variable) written in
parenthesis is known as argument (actual argument). It is common to say that the function takes
arguments and return the result.
The form statement is used to get a specific function in the code instead of the complete module file. If we
know beforehand which function(s), we will be needing, then we may use form. For modules having large
number of functions, it is recommended to use from instead of import. Its syntax is
from modulename import functionname1 [, functionname2, …, ,…, functionnamem ]
Example- from math import sqrt
value = sqrt (25)
Here, we are importing sqrt function only, instead of the complete math module. Now sqrt( ) function will
be directly referenced to. These two statements are equivalent to previous example.
from modulename import *
will import everything from the file.
Note: You normally put all import statement(s) at the beginning of the Python file but technically they can
be anywhere in program but before the use.
pg. 104
floor( x ) It returns the absolute value of x, where x math.fabs(-45.17) 45.17
is a numeric value. math.fabs(100.12) 100.12
math.fabs(100.72) 100.72
fabs( x ) It returns the absolute value of x, where x math.fabs(-45.17) 45.17
is a numeric value. math.fabs(100.12) 100.12
math.fabs(100.72) 100.72
exp( x ) It returns exponential of x: ex, where x is math.exp(-45.17) 2.41500621326e-20
a numeric expression. math.exp(100.12) 3.03084361407e+43
math.exp(100.72) 5.52255713025e+43
log( x ) It returns natural logarithm of x, for x > 0, math.log(100.12) 4.60636946656
where x is a numeric expression. math.log(100.72) 4.61234438974
log10( x ) It returns base-10 logarithm of x for x > 0, math.log10(100.12) 2.00052084094
where x is a numeric Expression. math.log10(100.72) 2.0031157171
pow( x, y) It returns the value of xy, where x and y math.pow(100, 2) 10000.0
are numeric expressions. math.pow(100, -2) 0.0001
math.pow(2, 4) 16.0
math.pow(3, 0) 1.0
sqrt (x ) It returns the square root of x for x > 0, math.sqrt(100) 10.0
where x is a numeric expression. math.sqrt(7) 2.64575131106
cos (x) It returns the cosine of x in radians, math.cos(3) -0.9899924966
where x is a numeric expression math.cos(-3) -0.9899924966
math.cos(0) 1.0
math.cos(math.pi) -1.0
sin (x) It returns the sine of x, in radians, where math.sin(3) 0.14112000806
x must be a numeric value. math.sin(-3) -0.14112000806
math.sin(0) 0.0
tan (x) It returns the tangent of x in radians, math.tan(3) -0.142546543074
where x must be a numeric value. math.tan(-3) 0.142546543074
math.tan(0) 0.0
degrees (x) It converts angle x from radians to math.degrees(3) 171.887338539
degrees, where x must be a numeric math.degrees(-3) -171.887338539
value. math.degrees(0) 0.0
radians(x) It converts angle x from degrees to math.radians(3) 0.0523598775598
radians, where x must be a numeric math.radians(-3) -0.0523598775598
value. math.radians(0) 0.0
pg. 105
a≤x≤b random.randint (-2,20) -1
uniform(a,b) It returns a floating point number x, such random.uniform (5,10) 5.52615217015
that a <= x < b
randrange It returns a random item from the given random.randrange(100 150
([start,] stop range ,1000,3)
[,step])
pg. 106