Basics
Basics
1
Programming and Computational Thinking - 1
Introduction
Computers are all around us. Computers are used in almost all walks of day to day life. Have you ever
wondered about what is so special in computers that they can be used in such versatile applications as from
adding two numbers to controlling satellites?
Actually, a computer is a machine which can do data processing at a super-fast speed and with great accuracy.
So, wherever we need to do data processing, we can use computers. When a computer is being used for
playing video games, for creating report cards, for doing medical testing, for issuing train tickets, for controlling
aircraft, for controlling satellites, or for any other purpose, it is being used for data processing. In general we
can say that Computers are used for data processing. Data processing comprises of two things – data and
processing.
For a computer to perform data processing, the computer must know what the data is and how to process it.
The data is generated from the related day to day activities. For example, data (marks) is generated when
exam papers are checked, data (temperature, humidity etc.) is generated by sensors for weather forecast, data
(item code, price, quantity, discount, tax) is generated when some items are sold in a shop. There can be a lot
of other examples. Once the data is generated, it can be stored in a computer. After storing the data in a
computer, we have to tell the computer how to process it. For this, we give instructions to the computer. A set of
instructions given to the computer to perform a specific job is called a program. We have to use some
language to write these instructions. This language cannot be a natural language like Hindi, Punjabi,
Malayalam, English, or Arabic (Why?). There are some specific languages which have been developed to write
programs. These languages are called programming languages. Examples of some programming languages
are Python, C, C++, LISP, Pascal, Java, PHP, etc. In this course we are going to learn Python. The task of
writing programs is called programming.
When we write a program, we are writing a set of instructions to solve a problem involving data processing.
These instruction have to be executed by the computer to solve the problem. If the instructions are correct and
given in correct sequence, then the problem will be solved properly by the computer, and if the instructions are
incorrect or in wrong sequence then the problem will not be solved correctly or will not be solved at all.
Therefore, writing correct instructions in correct sequence is extremely important. It means that before we start
writing a program, we should be thoroughly clear in our mind about the steps of solving the problem. If we start
writing the program without knowing how to solve the problem, then we can never write the correct program.
This leads us to the concept of Computational Thinking. Wikipedia defines Computational thinking as the
thought processes involved in formulating a problem and expressing its solution(s) in such a way that a
computer—human or machine—can effectively carry out.
So, to write any program, first we have to think computationally – about the problem and its solution – and then
we have to write the program in a programming language (Python in our case).
Python
Python is an easy to learn, open-source, object-oriented, general-purpose programming language. Python has
certain features which distinguish it from other programming languages and make it a very popular
programming language. Some of these features are:
• Python is free to use, even for commercial products, because of its OSI-approved open source license.
• Python runs on Windows, Linux/Unix, Mac OS X, and has been ported to the Java and .NET virtual
machines.
• Python’s syntax is easier to learn than most of the other programming languages.
• Python can be used to create web applications and desktop applications.
• Python has a rich standard library ( https://docs.python.org/3/library/ ) which contains a lot of predefined
functions for most of the common operations, and a large number of pre-defined modules (
https://docs.python.org/3/py-modindex.html ) for specific varieties of functions. This makes
programming in Python an easy task.
Application Domains
Python is used in many diverse fields of application. Following is a list of a few application areas where Python
is used:
1. Web and Internet Development
2. Database Access
3. Desktop GUIs
4. Data Sciences
5. Network Programming
6. Game and 3D Graphics
Python was conceived in late 1980s and its implementation was started in
December 1989 by Guido van Rossum at CWI (Centrum Wiskunde & Informatica) in
Netherlands. Van Rossum is the principal author of Python and he continues to play
central role in deciding the direction of Python. The Python Software Foundation
holds the intellectual property rights behind Python.
Python's name is derived from the television series Monty Python's Flying Circus.
When Guido van Rossum began implementing Python, he was also reading the
published scripts from “Monty Python’s Flying Circus”, a BBC comedy series from
the 1970s. Van Rossum thought he needed a name that was short, unique, and
slightly mysterious, so he decided to call the language Python.
Python IDE
A computer understands only the machine language. It does not understand programs written in any other
programming language like Python. Therefore, for program execution, each Python statement is first interpreted
into machine language by a software called the Python Interpreter, and then it is executed by the computer.
So, if we wish to run a Python program on a computer, we should first install Python Interpreter on it.
The process of programming starts with the problem to be solved. When there is a problem to be solved, we
have to think computationally to formulate the problem well, find its well-defined solution, write the program to
represent the solution, and execute the program. We need a text editor (Like Notepad, Notepad2, Notepad++,
etc) to type the program. After the program is typed, we need an Interpreter to interpret and execute/run the
program. Sometimes the program has some bugs (errors in a program are called bugs), and we need to debug
the program. If these bugs are not easily caught and removed, we need some debugging tools on the
computer to help us. Sometimes we also need some help with the language code and features to write our
program correctly. A professional programmer may need many more tools to develop, test, and organize his/her
work. A software that provides all these tools as a bundle is called an IDE (Integrated Development
Environment). When we install Python on our computer, we actually install the Python IDE. Python IDE is called
IDLE (Integrated Development and Learning Environment).
Installing IDLE
To install IDLE on your computer, first you have to download it from https://www.python.org/downloads/ . When
you open this link, you are shown the following page (The page appearance may change over the time):
From here you can download the version specific to your Operating System. For example, I am working on
Windows 10, and I have installed Python 3.6.4 on my computer. Different versions are available for Windows,
Linux/Unix, Mac OS X, and other operating systems.
Once you download this software, you have to install it on your computer. Installation is very easy. You simply
have to double click the icon representing this software and follow the instructions that appear on the screen.
Actually there are no instructions, you simply have to click at the Next button and finally at the Finish button
when asked for. This will install IDLE on your computer.
Programming in Python
When you start IDLE, computer opens the IDLE window (Called the Python Shell) as shown below:
It shows you a welcome message stating IDLE’s version number and a copyright notice. After this information it
shows you the primary prompt (>>>) followed by a blinking cursor. It indicates that IDLE is now ready to take
Python commands from the user.
IDLE can be used in two modes: Interactive mode and Script mode.
Interactive mode:
When commands are entered directly in IDLE from the keyboard, the Interpreter/IDLE is said to be in interactive
mode. In this mode it prompts for a command with the primary prompt, for continuation lines it prompts with
the secondary prompt (. . .).
Let us try our first command in Python in the interactive mode. Type print ("Hello World") at the
prompt, and press Enter. This command is to display the message Hello World on the screen. When you
press Enter, the interpreter interprets this command and gets it executed. This is shown in the following figure:
After executing the command, IDLE again shows the primary icon, indicating that it is ready to take the next
command.
Let us give another command print ("I am learning Python"), and press Enter. The result is
shown in the following figure:
So, now we understand that we can give commands at the primary prompt and see the result immediately.
print() is a function which is used to display the specified content on the screen. The content (called
argument(s)) is/are specified within the parentheses.
Python is a case-sensitive language. It means that Python differentiates between capital and small alphabets.
For example, Print (P capital) and print (p small) are two different words for Python. Where print is a
valid command in Python, Print is just a word and not a command. This can be observed by typing the
command Print ("Hello World"). Python will not be able to interpret it and will show an error. This is
shown in the following figure:
In the print command, if the argument is put within quotation marks (single '' or double ""), then the
argument is displayed as it is. We have already seen this in the above examples. If the argument is not placed
within quotation marks, then the interpreter tries to evaluate the argument and displays the result. This feature
is used to perform calculations. This is shown in the following figure:
We can also pass more than one arguments to the print() function. In such a case the arguments are
separated by commas. This is shown in the following figure:
Consecutive arguments are separated by commas in print() function. When print() is executed, the
values of consecutive arguments are separated by space between them. We say that space is the default
separator of values in the output. If we wish, we can also specify some other string as the separator using the
sep argument of print() function. An example is shown below:
If we use sep argument to specify the separator, then it must be specified after all the values to be printed.
Otherwise, the interpreter shows a syntax error. An example is given below:
sep is a keyword argument of print() function. print() also has three more keyword arguments besides
sep, these are: end, file, and flush. We shall discuss end, file and flush later.
Using IDLE as a calculator: To evaluate an arithmetic expression, it is not mandatory to use print()
function. If we type an arithmetic expression at the primary prompt and press Enter, the interpreter
automatically evaluates it and shows the result. This is shown in the following figure:
In IDLE you can press Alt+P to view the previous command, and Alt+N to view the next command.
Data types
In Python, each value is an object and has a data type associated with it. Data type of a value refers to the kind
of value it is. Following are the built-in data types in Python:
int (Integer): Represents integral numbers (numbers without any fractional part). Examples of integral numbers
are -3, 8, 4, 0, 13434, -547554677854545. An integer in Python can be of any length.
float: Represents floating point values (numbers with fractional part). The fractional part of a floating point
number may be 0 also. Examples of floating point numbers are 3.14, -23.9, 8.0, 56667.78
str (String): Represents strings of characters enclosed within quotation marks (‘ ‘ Or " "). Examples of strings
are ‘Hello’, "Programming", ‘108’, ’29 States of India’, "xyz@gmail.net". A string enclosed in single or double
quotation marks cannot span more than one lines. For example, the following string is invalid:
"abc
d"
Multi line strings can be created by enclosing them between a pair of three single quotation marks ('''). For
example, the following string is valid:
'''abc
d'''
bool (Boolean): Represents a True or False value. An expression which can be True or False has the data
type bool. Examples of Boolean expressions are 3>4, 5<=18.
complex: Represents complex numbers of the type a+bi, where a is the real part and b is the imaginary part. In
Python, j is used instead of i to represent the imaginary part. It means that in Python notation a+bj is a
complex number.
We can check the data type of a value by using the type() function, as shown in the following example:
>>> type(5)
<class 'int'>
>>> type(5.0)
<class 'float'>
>>> type(22/7)
<class 'float'>
>>> type('5')
<class 'str'>
>>> type(True)
<class 'bool'>
>>> type(False)
<class 'bool'>
>>> type(4>5)
<class 'bool'>
>>> type(4+5j)
<class 'complex'>
Operators in Python
An operator is a symbol or a word that performs some kind of operation on given values and returns the result.
Examples of operators are: +, -, *, / etc. In Python we have many other operators besides arithmetic operators
that you already know. Different types of operators will be covered at suitable points during this course.
Arithmetic Operators: A number of operators are available in Python to form arithmetic or algebraic
expressions. Following is the list of these operators
Operator Description Example(s)
+ (unary) To explicitly express a positive number Value of +3 is +3
- (unary) To represent a negative number Value of -3 is -3
+ (binary) To add two numbers Value of 23+3.5 is 26.6
- (binary) To subtract one number from the other Value of 45 - 32 is 13
* To find the product of two numbers Value of 3.2*6 is 19.2
/ To find the quotient when one number is divided by • Value of 3/2 is 1.5
the other. • Value of -3/2 is -1.5
• Value of 10.0/3 is
3.3333333333333335
// (Floor division) To find the integer part of the quotient • Value of 3//2 is 1
when one number is divided by the other. The result is • Value of -3//2 is -2
always the largest integer less than or equal to the • Value of 10.0//3 is 3.0
actual quotient.
% (Remainder) To find the remainder when one number • Value of 3%2 is 1
is divided by the other. • Value of 10%6 is 4
• Value of 6%10 is 6
• Value of 10.3%3.2 is 0.7
** (Exponent) To raise a number to the power of another • Value of 3**2 is 9
number. The expression a**b is used to find the value • Value of 3**-2 is
of ab. 0.1111111111111111
• Value of 10.2**3.1 is
1338.6299344200029
Unary and Binary operators: An operator can be termed as unary or binary depending upon the number of
operands it takes. A unary operator takes only one operand, and a binary operator takes two operands. For
example, in the expression -2*3+4-5, the first minus sign is a unary minus and the second minus sign is a
binary minus. The multiplication and addition operators in the above expression are binary operators.
Operator precedence
If an expression contains only one operator, then it can be evaluated very easily. But, if an expression contains
more than one operators, then to evaluate it we have to be careful about the sequence in which the operations
have to be done. Operator precedence determines which operators are applied before others when an
expression contains more than one operators. Following is the order of precedence of operators:
(**) > (unary +, unary -) > (*, /, //, %) > (binary +, binary -)
Higher precedence operators are applied before the lower precedence operators. When an expression contains
operators which have the same precedence (like * and /), then whichever operator comes first is evaluated first.
Parentheses can be used to override the order of precedence and force some part of the expression to be
evaluated before others.
Examples:
Evaluate the following expressions:
(1) 12 + 3 * 4 - 6 / 2 (2) (12 + 3) * 4 – 6 / 2 (3) 12 + 3 * (4 – 6) / 2
(4) 12 + (3 ** 4 – 6)/ 2 (5) 12 * (3 % 4)// 2 + 6 (6) 12 % 3 ** 4//5 + 6
Solution:
(1) 12 + 3 * 4 – 6 / 2 (2) (12 + 3) * 4 – 6 / 2 (3) 12 + 3 * (4 – 6) / 2
= 12 + 12 – 6 / 2 = 15 * 4 – 6 / 2 = 12 + 3 * (-2) / 2
= 12 + 12 – 3.0 = 60 – 6 / 2 = 12 + (-6)/ 2
= 24 – 3.0 = 60 – 3.0 = 12 – 3.0
= 21.0 = 57.0 = 9.0
Assignment:
1. Define the term Computational Thinking.
2. Write any four features of Python.
3. Write any four application areas of Python.
4. What is a text editor. Name any two text editors.
5. What is an interpreter?
6. What is IDLE? What are the two modes of working with IDLE?
7. What is print() in Python?
8. Name the keyword arguments of print() function.
9. What is a data type? What are the fundamental data types in Python?
10. Identify the data types of the following:
(i) 7 (ii) '7' (iii) "7" (iv) 7.0 (v) '''7''' (vi) 7.0 (vii) -29 (viii) -15.38
(ix) "29 acres" (x) ". & #"
11. Find outputs of the following commands in Python:
(i) print("Hello") (ii) print(2+3,34-67) (iii) print("2+3",2+3)
(iv) print ('2+3',2+3,sep="=") (v) print(2**3,3**2,sep='*')
(vi) print(2**3, 2**-3, -2**4, (-2)**4, sep=" and ")
12. Find syntax error(s), if any, in the following statements:
(i) print("three') (ii) Print(3) (iii) print(44'+'56) (iv) print(3,2 sep=': ')
(v) print "wisdom" (vi) print['33+44'] (vii) PRINT("15 August 1947")
13. Evaluate the following expressions manually:
(i) (2 + 3) ** 3 - 6 / 2 (ii) (2 + 3) * 5//4+(4 + 6)/ 2 (iii) 12 + (3 * 4 – 6) / 3
(iv) 12 + (3 * *4 – 6)// 2 (v) 12 * 3 % 5 + 2 * 6//4 (vi) 12 % 5 *3 +(2*6)//4
14. What are unary operators and binary operators? Give two examples of each.
15. What is the operator precedence of arithmetic operators in Python?
16. Evaluate the above expressions by using IDLE as a calculator and verify the results that you got
manually.
17. Write Python command/instruction/statement to display your name.
18. Write Python command to display your school name, class, and section, separated by “-“.
Script mode
In the interactive mode each instruction is executed as soon as it is entered. But when we talk about
programming in general, a program consists of more than one instructions (from a few instructions to hundreds
of instructions). In such a case, we don’t want each instruction to be executed as it is entered. We want to enter
all the instructions one after the other and then give this set of instructions to the interpreter. Interpreter should
then interpret and execute these instructions one by one. This can be done by using IDLE in script mode.
To use IDLE in script mode first we have to create the script (program) using some text editor. This text editor
can be Notepad, Notepad++, Text Mate, Vi, or any other text editor. IDLE also provides a text editor and we
shall use that only. After typing the script in the editor, we have to save it with a valid file name and extension
.py. We can use the script without .py extension also, but it is always recommended to use the extension .py.
After saving the file we can run/execute it in IDLE to see the result.
Start Python and click at File → New File (Or press Ctrl+N). This will open IDLE editor as shown in the
following figure:
Now you can start typing the code in the editor. Type the following two commands, and observe that the
commands are not automatically executed as you enter them:
After typing the code, you have to save it before executing it. Save the code with a suitable file name with
extension .py and then Run it (Run→Run Module OR press F5), as shown in the following figure:
The code is run/executed in the Python shell, as shown in the following figure:
Similarly, you can create any other program in the script mode and run it.
By default, print() function puts an ‘end of line’ character after the output. Therefore, each successive print
statement displays the output in a new line. By using end argument, we can specify some other string, of 0 or
more characters, to be used at the end of the output. This way we can have multiple print statements to display
the output in same line. The following example will clear the concept:
Code Output
print("Hello") Hello
print("How are you?") How are you?
print("Hello", end=" ") Hello How are you?
print("How are you?")
print("Hello",end="-*-") Hello-*-How are you?
print("How are you?")
print("2+3",2+3,sep="=", end=" ") 2+3=5 5+8= 13 2x3=6...
print("5+8=",5+8,end=" ") This is the second line
print("2x3=",2*3,sep="",end="...\n")
print("This is the second line")
Variables
A variable is a named memory location which is used to store data. The contents of a variable may change
during the programs execution. A variable can store one and only one data value at a time. When a new value
is stored in a variable, its previous value gets overwritten. (This is the easiest way to understand the concept of
variables, tough it is not technically same in Python.)
Variables are needed in a program when we have to handle multiple data values and/or when a data value has
to be used multiple times in the program. This happens in almost all the programs.
There should be one and only one variable on the left hand side of assignment operator. This variable
is called the Left value or the L-value. There can be any valid expression on the right hand side of
assignment operator. This expression is called the Right value or R-value. The statement:
L-value = R-value
is called the assignment statement. When the interpreter encounters an assignment statement, it
evaluates the right hand side expression (R-value) and assigns its value to the left hand side variable
(L-value).
For example, suppose there is a statement result = 5+6*2 in a program. When the interpreter
encounters this statement, it will evaluate 5+6*2 (= 17), and assign this value to the variable result. After this
when we refer to the variable result in the program, its value will be 17, until it is changed by another
assignment statement.
As another example, observe the following code:
Know more…
In Python a variable is a pointer/indicator/locator which stores the address of a memory location. For example,
the statement x=10 will store a value 10 in some memory location and variable x will point to that memory
location. After this we can say that variable x has a value 10. Now we can refer to x multiple times to access its
value.
Suppose at some point in the code we give another statement x=20. Then 20 will be stored in some other
memory location and x will now point to that location. Now we say that x has a value 20. Whenever we assign a
new value to a variable, it no more refers to any of the previous values. So, if value of x is 20 now, it will remain
20 only until we change it.
We can use id() function to know the address of memory location to which a variable is referring. Following is
an example to show this:
In Python, a variable has no data type. When we say data type of a variable, we are actually referring to the
data type of the value that it represents. For example, if a variable stores an integer value, its data type is
integer. Next time if it stores a floating point value or a string value, its data type changes accordingly. This is
shown in the following example:
As a variable does not have any fixed data type and its data type keeps changing depending upon the value it
represents, we say that Python is a dynamic type language.
In Python, we can declare multiple variables in a single statement. There are two ways of doing this:
Variable names: There are certain rules in Python which have to be followed to form valid variable names.
Any variable which violates any of these rules will be an invalid variable name. The rules are:
(i) A variable name must start with an alphabet (capital or small) or an underscore (_).
(ii) A variable name can consist of UNICODE alphabets, digits, and underscore(_). No other character
is allowed.
(iii) A Python keyword cannot be used as a variable name.
To get a list of Keywords in the Python version installed on your computer, you can type the following
commands at the prompt:
import keyword
keyword.kwlist
It will display an alphabetically sorted list of keywords. On my computer (Python 3.6.4), it shows the
following list:
So, I cannot use these words as variable names in the scripts on my computer.
All these keywords are in small alphabets, except 'False', 'None', and
'True', which are starting with capital alphabets.
Python 3.x is based on UNICODE. Therefore, variable names can contain UNICODE alphabets, besides
English alphabets, digits, and underscore, as well. For examples, दरू ी, and വില are valid variable names in
Python.
Examples:
Find output generated by the following code:
(1) x=2 (2) x=8 (3) a=5
y=3 y=2 b=10
x+=y x+=y a+=a+b
print(x,y) y-=x b*=a+b
print(x,y) print(a,b)
(Ans: 5 3) (Ans: 10 -8) (Ans: 20 300)
(4) p=10 (5) p=5/2 (6) p=2/5
q=20 q=p*4 q=p*4
p*=q//3 r=p+q r=p*q
q+=p+q**2 p+=p+q+r p+=p+q-r
print(p,q) r+=p+q+r r*=p-q+r
q-=p+q*r q+=p+q
print(p,q,r) print(p,q,r)
Operator cascading:
Operator cascading means using an operator multiple times in the same statement. We have seen one
example of operator cascading while declaring multiple variable with same value. To recall it, the statement is
again given below:
X=y=z=-98
With this statement all the three variables x, y, and z are assigned the same value, i.e., -98. When cascaded,
operator execution starts from the right hand side. Therefore, in the above statement, z is assigned the value -
98. This value of z is then assigned to y, which is further assigned to x. Python also allows cascading of
compound assignment operators. Following are a few examples to explain this:
X,y,z=10
X+=y+=z=15
Print(x,y,z)
Assignment:
1. What is the extension of a Python file?
2. What is the shortcut key to execute current Python code?
3. What is a variable? What are the rules for forming valid variable names in Python?
4. How does a simple assignment statement work?
5. Which function is used to know the address of the memory location to which a variable is referring?
6. Why is python called a dynamic type language?
7. Write Python statements to get a list of Python keywords.
8. What is an augmented assignment operator? Give an example to explain.
9. Identify invalid variable names from the following, give reason for each:
Group, if, int, total marks, S.I., volume, tot_strength, #tag, tag$, 9a
10. Find syntax error(s), if any, in each of the following code segments:
(1) x=3 (2) x=-2 (3) a=5
x+2=y y=2 b=2*a
x+=y x+=y a+=a+b
print(x and y) y-x b*=a+b
print(x,y) print(a,b)
Example 1:
Sonia has to travel a distance of 450km by car. She knows that the speed limit is 100km/hr, but due to traffic
conditions, the average speed is 60km/hr. Write Python script to find out how much time will she take to cover
the distance.
Solution:
Required information/result: Time to cover the distance
Given data: Total distance, Time
Processing: We know that time taken to cover a distance is calculated as:
𝑇𝑜𝑡𝑎𝑙 𝐷𝑖𝑠𝑡𝑎𝑛𝑐𝑒
𝑇𝑖𝑚𝑒 =
𝐴𝑣𝑒𝑟𝑎𝑔𝑒 𝑆𝑝𝑒𝑒𝑑
Here we know the values of Total Distance (450km), and Average Speed (60km/hr). So, we can calculate Time.
Following is the required Python script:
Distance=450
Speed=60
Time=Distance/Speed
print("Time taken: ",Time,"hr")
Example 2:
Mahmood has taken a loan of Rs 40000 from Ashraf at a rate of 8% per annum simple interest. After 6 years
Mahmood wants to repay the loan in full and final including interest. Write Python code to calculate and display
the interest and total amount to be paid by Mahmood to settle the account.
Solution:
Required information/result: Interest, Total amount payable
Given data: Principal, Rate, Time
Processing: We know that simple interest is calculated using the formula
𝑃𝑟𝑖𝑐𝑖𝑝𝑎𝑙 𝑥 𝑅𝑎𝑡𝑒 𝑥 𝑇𝑖𝑚𝑒
𝑆𝑖𝑚𝑝𝑙𝑒 𝐼𝑛𝑡𝑒𝑟𝑒𝑠𝑡 =
100
We know the values of Principal (40000), Rate (8% per annum), and Time (6 years). So, we can calculate
Simple Interest. Total amount is the sum of Principal and Simple Interest. So, we can calculate Total amount
also.
Therefore, in the Python script, first we shall store the values of Principal, Rate, and Time in suitable variables.
Then calculate the Simple Interest, and then Amount. Then we shall display the result. Following is the required
Python script:
Principal=40000
Rate=8
Time=6
Simple_Int = Principal*Rate*Time/100
Amount = Principal+Simple_Int
print("Simple Interest = Rs",Simple_Int)
print("Amount payable = Rs",Amount)
Example 3:
A book publisher conducted a survey and found that 70% of the teenagers love to read fiction novels. The
population of the area that the publisher can cover is 500000, out of which 40% are teenagers. The publisher
earns a profit of Rs10 on the sale of each copy of a fiction novel. Write Python script to find maximum profit that
the publisher can earn by selling copies of one fiction novel to teenagers.
Solution:
Required information/result: Maximum profit
Given data: Profit earned on each copy, Population, Some percentages of population
Processing: If Rs.10 is the profit on each copy, then
Maximum profit = 10 x maximum number of copies sold
= 10 x number of teenagers who love fiction novels
= 10 x 70% of teenagers
= 10 x 70% of (40% of population)
= 10 x 70% of (40% of 500000)
70 40
=10 x x x500000
100 100
Example 4:
A school conducts two weekly tests of 30 marks each and a term exam of 100 marks. To calculate the
aggregate percentage of marks obtained by a student, calculations are done as follow:
Aggregate Percentage = (weekly test total)/3+80% of term exam.
Write Python script to calculate and display aggregate percentage of a student if she scored 20, 25, and 60
marks respectively in 1st weekly test, 2nd weekly test, and term exam.
Solution:
Required information/result: Aggregate percentage
Given data: Marks in various weekly test and term exam, formula to calculate aggregate percentage
Processing: According to the given formula
Aggregate Percentage = (weekly test total)/3 + 80% of term exam
𝐹𝑖𝑟𝑠𝑡 𝑤𝑒𝑒𝑘𝑙𝑦 𝑡𝑒𝑠𝑡 𝑚𝑎𝑟𝑘𝑠+𝑆𝑒𝑐𝑜𝑛𝑑 𝑤𝑒𝑒𝑘𝑙𝑦 𝑡𝑒𝑠𝑡 𝑚𝑎𝑟𝑘𝑠 80
= + x 𝑇𝑒𝑟𝑚 𝑒𝑥𝑎𝑚 𝑚𝑎𝑟𝑘𝑠
3 100
User input
We have just seen that it is quite easy to process the given data to get the required information. In the above
examples, the data was given in the form of values and we just created suitable variables to store given values
and used appropriate formulae to get the result. The code that we have written would give the same result
every time it is run. But, it is not always that we are given the data as in the above examples. In almost all the
real world problems we are given only the formulae to get the information from the data. The actual data values
are not given and these have to be obtained from the user when the script runs. Let us now see how to get the
data from the user.
input(): input() function is used to get data from the user during script execution. Let us see a simple
example:
(It is always convenient to work in the interactive mode to check and understand the functioning of a single
function/statement)
The input() function takes one string argument (called prompt). During execution, input() shows the
prompt to the user and waits for the user to input a value from the keyboard. When the user enters value from
the keyboard, input() returns this value to the script. In almost all the cases, we store this value in a
variable.
When the first statement of the above example is executed, the user is prompted to enter his/her name. The
name entered by the user is stored in the variable user_name. After this, the variable user_name can be used
as many times as needed.
Let us now input two numbers from the user and display their sum and product. Following is the script:
n1 = input("Enter first number: ")
n2 = input("Enter second number: ")
sum = n1+n2
print("Sum of the numbers=",sum)
pro = n1*n2
print("Product of the numbers=",pro)
(i) The sum is not correct. Instead of being added, the numbers are being joined.
(ii) An error occurred in line 5 of the code ( pro = n1*n2). The Python interpreter is showing it as
TypeError and flashes the message can’t multiply sequence by non-int of type ‘str’.
The reason for the above behavior of the code is that input() function returns the user input as a string to
the script. For example, in the above code, when the user enters 12, it is stored as a string ‘12’ and not as a
number 12 in the variable n1. Similar is the case with second number. When the interpreter executes the
statement sum=n1+n2, it takes + for concatenation (joining) of two strings and not for addition of two numbers.
So, we get the result 1276 as sum. When the interpreter tries to execute the statement pro = n1*n2, it faces
a hurdle. There is no operator * which is defined for strings. * can be used for arithmetic multiplication only. So,
the interpreter cannot execute the statement and shows an error message.
What to do if we want to input numbers from the user? The solution is the functions int(), float(),
and eval().
(i) int() takes a number, expression, or a string as an argument and returns the corresponding
integer value. Different types of arguments are treated as follows:
a. if the argument is an integer value, int() returns the same integer. For example int(12)
returns 12.
b. if the argument is an integer expression, the expression is evaluated, and int() returns this
value. For example int(12+34) returns 46.
c. if the argument is a float number, int() returns the integer part (before the decimal point) of
the number. For example int(12.56) returns 12.
d. if the argument is a float expression, the expression is evaluated, and int() returns the
integer part of this value. For example int(12+13/5) returns 14.
e. If the argument is a string containing leading +/- sign and digits only, int() returns the integer
represented by this string. For example, int('12') returns 12.
f. If the string argument contains any character other than leading +/- sign or digits, then int()
results in an error. For example, the following statements will result in error:
int('12/3'), int('12+3'), int ('23a')
g. If no argument is passed, int() returns 0.
(ii) float() takes a number, expression, or a string as a parameter and returns the corresponding
float value. Different types of parameters are treated as follows:
a. if the argument is a number, float() returns the same number as a float. For example
float(12) returns 12.0, and float(12.46) returns 12.46.
b. if the argument is an expression, the expression is evaluated, and float() returns its value.
For example float(12+34) returns 46.0, and float(12+3/4) returns 12.75.
c. If the argument is a string containing leading +/- sign and a floating point number in correct
format, float() returns the float value represented by this string. For example,
float('12.45') returns 12.45.
d. If the string argument contains any character other than leading +/- sign and floating point
number in the correct format, then float() results in an error. For example, the following
statements will result in errors:
float('12.2.3'), float('67.6-'), float('23+3/5')
e. If no argument is passed, float() returns 0.0
(iii) eval() takes a string as an argument, evaluates this string as a number, and returns the numeric
result (int or float as the case may be). If the given argument is not a string, or if it cannot be
evaluated as a number, then eval() results is an error. This is shown in the following example:
Let us now modify the above code to input two numbers and find their sum and product. The modified script is
given below:
n1 = input("Enter first number: ")
n1 = eval(n1)
n2 = input("Enter second number: ")
n2 = eval(n2)
sum = n1+n2
print("Sum of the numbers=",sum)
pro = n1*n2
print("Product of the numbers=",pro)
Combining eval() / int() / float() and input() to take the numeric input: We can use a valid
combination of multiple functions in a single statement. For example, we can combine eval(), int(), or
float() funtions with input() function to take the numeric input in a single statement as follows:
n = eval(input("Enter a number: "))
Here we are using input() function as an argument of eval() function. Whenever such a combination is
used, first the inner function (input() in this example) is executed and then its result is passed as an
argument to the outer function (eval() in this example).
The above statement will input a number from the user as a string, evaluate that string as a number, and store
the result in the variable n.
Using this combination, the above code to input two numbers and find their sum and product can be rewritten
as follows:
n1 = eval(input("Enter first number: "))
n2 = eval(input("Enter second number: "))
sum = n1+n2
print("Sum of the numbers=",sum)
pro = n1*n2
print("Product of the numbers=",pro)
eval() can handle both integer and float strings. If we want to specifically work with integer or float values, we
can use int() or float() as per the requirement.
Comments
Comments are statements in a script that are ignored by the Python interpreter, and therefore, have no effect
on the actual output of the code. Comments make the code more readable and understandable for the human
beings. This makes the revision/modification of the code easier by the original author of the code and also by
some new author who has been assigned the responsibility to modify it. Comments are not necessary in a
script, but these are highly recommended if the script is too complex or if it is to be reviewed by multiple people
over an interval of time.
A comment in Python starts with a # anywhere in a line and extends till the end of the line. The following code
contains two single line comments:
Errors in a script
When we write a script, there may be errors in it. There can be three types of errors in a script. These are (i)
Syntax error, (ii) Run time error, and (iii) Logical error.
(i) Syntax error: A syntax error is a grammatical error in a script. All the statements written in a
programming language must exactly follow the grammatical rules of that language. If a statement
does not follow the rules, the interpreter cannot interpret it and shows a Syntax error. Examples of
syntax errors are: mismatching parentheses or quotation marks, unnecessary indentation etc.
Syntax errors are caught by the interpreter and a script with syntax errors does not execute at all.
(ii) Run time error: An error which occurs during program execution due to incorrect or illegal values
used in some operations. Examples of run-time errors are: division by zero, finding log of a
negative number etc. Run-time errors are also called exceptions and there are ways to handle
exceptions properly. Without proper exception handling, a run-time error causes the script to
terminate.
(iii) Logical errors: These are the errors in the logic of the script. Examples of logical errors are
incorrect sequence of statements in the script, errors in the formulae used, incorrect initialization of
variables etc.
Tokens
A token is the smallest element of a Python script that is meaningful to the interpreter. The following
categories of tokens exist: identifiers, keywords, literals, operators, and delimiters.
Identifiers: The name of any variable, constant, function, or module is called an identifier. Examples of
identifiers are: print, int, type etc.
Keywords: The reserved words of Python which have a special fixed meaning for the interpreter are called
keywords. No keyword can be used as an identifier. The Python keywords have already been
listed above.
Literal: A fixed numeric or non-numeric value is called a literal. Examples of literals are: 2, -23.6, “abc”,
‘Independence’ etc.
Operators: A symbol or a word that performs some kind of operation on given values and returns the result.
Examples of operators are: +, -, **, / etc.
Delimiters: Delimiters are the symbols which can be used as separators of values, or to enclose some values.
Examples of delimiters are: ( ) { } [ ] , ; :
Note: # symbol used to insert comments is not a token. Any comment itself is not a token.
Example:
Observe the following script and enlist all the tokens used in it. For each token, write its category too.
print("x, y, z are:",x,y,z)
Solution:
Required information/result: Time to cover the distance
Given data: Total distance
Processing: We know that time taken to cover a distance is calculated as:
𝑇𝑜𝑡𝑎𝑙 𝐷𝑖𝑠𝑡𝑎𝑛𝑐𝑒
𝑇𝑖𝑚𝑒 =
𝐴𝑣𝑒𝑟𝑎𝑔𝑒 𝑆𝑝𝑒𝑒𝑑
Here we know the value of Total Distance (450km), but the value of average speed is not known. We also know
that there is no formula to calculate average speed.
In this problem we need a data value (average speed) which is not given and neither can it be calculated. So,
this value has to be input from the user. Following is the required Python script to solve this problem:
Distance=450
Speed=eval(input("Enter average speed: ")) # to input distance from the user
Time=Distance/Speed #Calculate time taken
print("Time taken: ",Time,"hr")
Example 6:
Mahmood has taken some loan from Ashraf at a certain rate of simple interest. After 6 years Mahmood wants to
repay the loan in full and final including interest. Write Python code to calculate and display the interest and
total amount to be paid by Mahmood to settle the account.
Solution:
Required information/result: Interest, Total amount payable
Given data: Time
Processing: We know that simple interest is calculated using the formula
𝑃𝑟𝑖𝑐𝑖𝑝𝑎𝑙 𝑥 𝑅𝑎𝑡𝑒 𝑥 𝑇𝑖𝑚𝑒
𝑆𝑖𝑚𝑝𝑙𝑒 𝐼𝑛𝑡𝑒𝑟𝑒𝑠𝑡 =
100
Here we know the value of Time (6 years), but the values of Principal and Rate are not known. Values of
Principal and Time are needed to solve the problem, but these are not given and neither can these be
calculated. So, these have to be input from the user. Following is the required Python script:
Principal=eval(input("Enter the value of Principal: "))
Rate=eval(input("Enter the annual rate of interest: "))
Time=6
Simple_Int = Principal*Rate*Time/100
Amount = Principal+Simple_Int
print("Simple Interest = Rs",Simple_Int)
print("Amount payable = Rs",Amount)
Example 7:
A book publisher conducted a survey and found that 70% of the teenagers love to read fiction novels. In
general, maximum 40% of the population of a city are teenagers. The publisher earns a profit of Rupees n on
the sale of each copy of a fiction novel. Write Python script to find maximum profit that the publisher can earn
by selling copies of one fiction novel to teenagers in a city.
Solution:
Required information/result: Maximum profit
Given data: Some Percentages of population
Processing: If Rs.n is the profit on each copy, then
Maximum profit = n x maximum number of copies sold
= n x number of teenagers who love fiction novels
= n x 70% of teenagers
= n x 70% of (40% of population)
70 40
=𝑛 x x x𝑃𝑜𝑝𝑢𝑙𝑎𝑡𝑖𝑜𝑛
100 100
Values of n and Population are needed to solve the problem, but these are not given and neither can these be
calculated. So, these have to be input from the user. Following is the required Python script:
profit=eval(input("Enter the profit earned on each copy: "))
population=eval(input("Enter population of the city: "))
max_profit = profit*70/100*40/100*population
print("Maximum profit that can be earned = Rs",max_profit)
Assignment:
1. Write Python script to input the values of Principal, Rate, and Time and calculate Simple Interest and
Compound Interest.
2. BMI (Body Mass Index) of a person is used as a screening tool to indicate whether the person is
underweight, overweight, obese or a healthy weight for his/her height. BMI is calculated as follows:
𝑚𝑎𝑠𝑠(𝑖𝑛 𝑘𝑔)
𝐵𝑀𝐼 = 2
ℎ𝑒𝑖𝑔ℎ𝑡(𝑖𝑛 𝑚)
Write Python script to calculate the BMI of a person.
3. Write Python script to input two numbers from the user and store these values in two different variables.
Then interchange (swap) the values of these two variables using a third variable.
4. Rewrite the above script, but this time to swap the values of variables without using the third variable.
5. Write Python script to enter temperature in degree Celsius and display it into Fahrenheit. The formula to
convert from degree Celsius to degree Fahrenheit is:
9
𝐹 = x 𝐶 + 32
5
6. Write Python script to input a time duration in seconds and display it in the following :
For example, if the user input is 4526, the output should be:
4526 seconds = 1 hr 15 min 26 seconds
7. A school conducts two weekly tests of and a term exam. To calculate the aggregate percentage of
marks obtained by a student, calculations are done as follow:
(weekly test total)/3+80% of term exam.
Write Python script to calculate and display aggregate percentage of a student.
8. Observe the following script and enlist all the tokens used in it. For each token, write its category too:
#Identify tokens in the script
name="Arjun"
age=eval(input("Enter age: "))
print(name,"is",age,"years old")
Conditional Statements
In each script that we have written till now, the statements of the script get executed sequentially as given in the
script – from first statement till the last statement. This is a very simple case of scripts. Sometimes it is required
that computer executes one of the given set of statements depending upon a condition. Suppose we want to
write the scripts for: the following examples:
(i) To input the marks of a student, and if the marks are in the rage 28 to 32, then the script should
increase the marks to 33, and otherwise the marks should not be changed.
Here we want to do some task (increase the marks to 33) depending upon a condition (the marks are
in the specified range).
(ii) To input the marks of a student and display the result. If the marks are 33 or more then calculate result
as “Pass”, otherwise calculate result as “Fail”.
Here, the script has to display one of the two messages (“Pass” or “Fail”) depending upon a condition.
(iii) To input marks of a student and display the grade. Grade should be calculated as per the following
criteria:
Marks range Grade
90 – 100 A
75 – 89 B
60 – 74 C
50 – 59 D
49 or less E
In all these examples, the script has to check condition(s) and proceed accordingly. For this purpose, Python
provides if statement which can be used in the following three formats as per the requirement of the script:
(i)
"if" expression ":"
suite
Here
(i) the expression is a Boolean expression which evaluates to True or False. Such an
expression represents a condition.
(ii) suite is a group of one or more statements.
Execution: If the expression is true, then the given suite is executed, otherwise suite is not
executed.
Example: To input and check the marks of a student. If the marks are in the range 28 to 32, then
upgrade the marks to 33. Then the marks (upgraded or otherwise) should be displayed.
(ii)
"if" expression ":"
suite-1
"else" ":"
suite-2
Execution: If the expression is true, then the given suite-1 is executed, otherwise suite-2 is
executed.
Example: To input the marks of a student and calculate the result. If the marks are 33 or more then
calculate result as “Pass”, otherwise calculate result as “Fail”. Then display the result on the
screen.
(iii)
"if" expression-1 ":"
suite-1
"elif" expression-2 ":"
suite-2
"elif" expression-3 ":"
suite-3
.
.
"else" ":"
Last-suite
Example: To input marks of a student and display the grade. Grade should be calculated as per the
following criteria:
Marks range Grade
90 – 100 A
75 – 89 B
60 – 74 C
50 – 59 D
49 or less E
Script:
marks = eval(input("Enter marks: "))
if marks>=90:
grade = "A"
elif marks>=75 and marks<=89:
grade = "B"
elif marks>=60 and marks<=74:
grade = "C"
elif marks>=50 and marks<=59:
grade = "D"
elif marks<=49:
grade = "E"
print("Grade:",grade)
OR
print("Grade:",grade)
Comparison or Relational Operators: To form a condition we have to compare two values. Python
provides Relational operators (also called Comparison operators) to compare two values. These relational
operators are:
Operator Description Example
(assuming x=6, y=2)
== Compares two values for equality. Returns true if (x == y) returns
(Equality) they are equal, otherwise returns false. false
!= (Inequality) Compares two values for inequality. Returns true (x != y) returns
if they are unequal, otherwise returns false. true
< Compares two values. Returns true if first value is (x < y) returns
(Less than) less than the second, otherwise returns false. false
<= Compares two values. Returns true if first value is (x <= y) returns
(Less than or equal to) less than or equal to the second, otherwise false
returns false.
> Compares two values. Returns true if first value is (x > y) returns
(Greater than) greater than the second, otherwise returns false. true
>= Compares two values. Returns true if first value is (x >= y) returns
(Greater than or equal greater than or equal to the second, otherwise true
to) returns false.
Logical Operators: A simple condition can be formed using a relational operator. Sometimes a condition
contains more than one comparisons. For example, to check if the marks are in the range 28 to 32. In this case
we have to check that marks are greater than or equal to (>=) 28 as well as marks are less than or equal to (<=)
32. Each relational operator forms a simple condition. If a condition contains more than one relational operators
then we can say that the condition is complex and the complex condition is formed by joining simple conditions
using Logical operators. A complex condition can also be formed by negating a simple condition. For example,
to check that a condition is not true. For forming complex conditions, we have to use logical operators with
simple conditions. Different logical operators available in Python are:
Indentation: Indentation is shifting of a statement to the right of another statement. In Python, indentation is
used to form suites (blocks of statements). A suite is a group of statements which is treated as a unit. If a suite
(let us call it B) is indented with respect to its above statement (let us call it A), then execution of suite B
depends upon the execution of statement A. This concept is used extensively in conditional statements and
loops (covered later). The concept of indentation can be understood better with the help of following figure:
In the above code the suite comprising of second and third statements will be executed only if the condition
(a>b) is true, and if the condition is false, then this suite will not be executed. To understand the concept better,
consider the following three scripts and their respective outputs:
So, we should be careful about where to indent the statements. Unnecessary indentation results in syntax error
and incorrect indentation results in logical error.
Pseudocode: When we are solving small and simple problems, we can directly write the script. But, as the
solutions become complex or large, writing the script directly becomes a difficult task (at least for the
beginners). In such cases, it is always better to write the pseudocode before writing the actual script. A
pseudocode is nothing but the solution to a problem written in sequence of steps to be performed in order. A
pseudocode can be written in any natural language (we shall follow English). There is no hard and fast rule to
be followed for writing pseudocode. The only condition is that pseudocode should be the correct sequence of
steps and should be readable by human beings. After writing pseudocode, writing script becomes an easy task.
if (n%2==0):
print ("Even")
else:
print ("Odd")
Example 9:
To input two numbers and find the greater
Solution:
Required information/result: The greater of two numbers entered by the user.
Given data: No data is given
Processing: First we have to input the numbers from the user. Then we have to compare these numbers with
each other and display the greater number. It may also happen that the numbers are equal and we have to
display an appropriate message in this case.
Pseudocode:
(i) Input first number, say n1
(ii) Input second number, say n2
(iii) If n1 > n2 then
Display(n1 is greater)
Otherwise if (n2>n1) then
Display (n2 is greater)
Otherwise Display(“Numbers are equal”)
Script:
# To input two numbers and find the greater of the two
n1 = eval(input('Enter a number: '))
n2 = eval(input('Enter a number: '))
if n1>n2:
print (n1,"is greater")
elif n2>n1:
print (n2,"is greater")
else:
print("numbers are equal")
Example 10:
To input principal, time and calculate simple interest. If time is more than 10 years, calculate the simple interest
at rate of 8% p.a. Otherwise calculate it at rate of 12% p.a.
Solution:
Required information/result: Simple Interest
Given data: Slabs of interest rate according to time.
Processing: First we have to input the principal and time from the user. Then we have to check the value of
time to decide the rate of interest. Then we have to calculate simple interest and display the result.
Pseudocode:
(i) Input the value of principal
Script:
#To input principal, time and calculate simple interest.
#If time is more than 10 years, calculate the simple interest at rate of 8%
#p.a. Otherwise calculate it at rate of 12% p.a.
Example 11:
To input three numbers and find whether they form the three sides of a triangle.
Solution:
Required information/result: A message stating whether three given numbers form the sides of a triangle or
not.
Given data: No data is given
Processing: We know that three numbers form the sides of a triangle if sum of any two sides is greater than
the third side. This should be true for all possible combinations of sides. Otherwise, if the condition is not
satisfied for any two sides, then the numbers don’t form the sides of a triangle.
Pseudocode:
(i) Input three numbers (a, b, c)
(ii) If (a+b>c and b+c>a and a+c>b) then
Display(“The numbers form the sides of a triangle”)
Otherwise Display(“The numbers don’t form the sides of a triangle”)
Script:
#To input three numbers and find whether they form the three sides of a
#triangle. Sum of any two sides should be greater than the third
Example 12:
An application (program) is to be developed which offers choices to the user to calculate total surface area and
volume of a cylinder, sphere, or cone. The application should input the user’s choice and perform the
corresponding operation.
Solution:
Required information/result: Total surface area and volume of as per the user’s choice.
Given data: No data is given
Processing: First we have to input the user’s choice. Then we have to perform the following depending upon
the user’s choice:
(i) If user’s choice is 1, calculate Total Surface Area and Volume of a cylinder. The formulae are given
below:
Total Surface Area (TSA) = 2rh + r2, Volume (Vol) = r2h
For these calculations, the values of r (radius) and h (height) are unknown and therefore these
have to be input from the user.
So, we have to input the values of r and h from the user, calculate TSA and Vol, and display the
result.
(ii) If user’s choice is 2, calculate Total Surface Area and Volume of a sphere. The formulae are given
below:
Total Surface Area (TSA) = 4r2, Volume (Vol) = 4r3 /3
For these calculations, the value of r (radius) is unknown and therefore it has to be input from the
user.
So, we have to input the value of r from the user, calculate TSA and Vol, and display the result.
(iii) If user’s choice is 3, calculate Total Surface Area and Volume of a cone. The formulae are given
below:
Total Surface Area (TSA) = r l + r2, Volume (Vol) = r2h/3
For these calculations, the values of l (slant height), r (radius) and h (height) are unknown and
therefore these have to be input from the user.
But, value of l can be calculated as √𝑟 2 + ℎ2 , therefore we shall input the values of r and h only.
We should input only those values from the user which are required but are neither
known nor can be calculated.
We should input minimum required values from the user.
Pseudocode:
(i) Display the options to the user to choose from
(ii) Input option from the user
(iii) If (option==1) then
a. Input radius (r) and height (h) from the user
b. Calculate Total Surface Area (TSA) = 2rh + r2, Volume (Vol) = r2h
c. Display the values of TSA and Vol
(iv) Otherwise, if (option==2) then
a. Input radius (r) from the user
b. Calculate Total Surface Area (TSA) = 4r2, Volume (Vol) = 4r3 /3
c. Display the values of TSA and Vol
(v) Otherwise, if (option==3) then
a. Input radius (r) and height (h) from the user
b. Calculate slant height (l) = √𝑟 2 + ℎ2
c. Calculate Total Surface Area (TSA) = r l + r2, Volume (Vol) = r2h/3
d. Display the values of TSA and Vol
(vi) Otherwise Display(“Invalid option”)
Script:
#To calculate total surface are and volume of a
#cylinder, sphere, or cone depending upon the user's choice.
print("1. Cylinder")
print("2. Sphere")
print("3. Cone")
Pi=3.14
choice=eval(input("Enter your choice (1, 2, or 3): "))
if (choice==1):
r=eval(input("Enter radius of cylinder: "))
h=eval(input("Enter height of cylinder: "))
TSA=2*Pi*r*h+Pi*r*r
Vol=Pi*r*r*h
print("Total Surface Area =",round(TSA,2),"sq. units")
print("Volume =",round(Vol,2),"cu. units")
elif (choice==2):
r=eval(input("Enter radius of sphere: "))
TSA=4*Pi*r*r
Vol=4*Pi*r*r*r/3
print("Total Surface Area =",round(TSA,2),"sq. units")
print("Volume =",round(Vol,2),"cu. units")
elif (choice==3):
r=eval(input("Enter radius of cone: "))
h=eval(input("Enter height of cone: "))
l = (r*r+h*h)**0.5
TSA=Pi*r*l+Pi*r*r
Vol=Pi*r*r*h/3
print("Total Surface Area =",round(TSA,2),"sq. units")
print("Volume =",round(Vol,2),"cu. units")
else: print("Invalid choice")
round(): Observe the use of round() function in the above script. Sometimes the value of an expression
involving floating point numbers cannot be calculated precisely and Python gives such a result upto 15 digits
after decimal. In most of the cases we don’t want these many digits after decimal. Therefore, in such cases we
use round() function to get the result upto specified number of digits (2 digits in the above example).
round() function rounds a given floating point number to the specified number of digits and returns the result.
The number itself remains unchanged. In general, round() is used in the format: round(n,p)
Here n is the number/expression to be rounded, and p is the number of digits upto which n is to be rounded. n
is a mandatory argument and can be an integer or a floating point value, p is an optional argument and must be
an integer. Different combinations of n and p are explained below with examples:
(i) p is not specified: n is rounded upto 0 digits of decimal and the result is an integer.
Example:
round(12.452) returns 12, round(12.534) returns 13.
(ii) p is 0: n is rounded upto 0 digits of decimal and the result is a float value.
Example:
round(12.452,0) returns 12.0, round(12.534,0) returns 13.0.
(iii) p is a positive integer: n is rounded upto p digits after decimal and the result is a float.
Example:
round(12.452,1) returns 12.5, round(12.534,2) returns 12.53.
(iv) p is a negative integer: n is rounded upto p digits before decimal and the result is a float. The
trailing p digits of the result o.
Example:
round(1234.56,-1) returns 1230, round(1258.4,-2)returns 1300.
Assignment:
1. Chhaya wants to write a script to input the number of students of a class and perform some processing.
She knows that sometimes the user may enter a negative number for the number of students. In such a
case, she wants to take the positive value of the number (e.g., if user enters -35, she wants to take 35).
Help Chhaya by writing the part of the script which inputs the number of students in a class and
converts it into a positive number if it is a negative number.
2. Write a script which inputs three numbers from the user and displays these numbers in ascending
order.
3. Write a script which inputs two numbers from the user and checks if first number is divisible by the
second or not. The script should then display an appropriate message.
4. Write a script to input a number. If the number is even, print its square, otherwise print its cube.
5. Write a script to find the roots of a quadratic equation.
6. Write a menu driven script to calculate the total surface area and volume of a cube, cuboid, or sphere
depending upon user’s choice..
(i) while: while loop is used for repeated execution as long as an expression (condition) is true. The
syntax of while loop is:
"while" expression ":"
Suite-1
["else" ":"
Suite-2
]
Here
(iii) the expression is a Boolean expression which evaluates to True or False. Such an
expression represents a condition.
(iv) else is an optional clause of while loop
Execution: When the control reaches while statement, the expression is evaluated. If the
expression is true, then the first suite (suite-1) is executed, and the
expression is evaluated again. If it is again true, suite-1 is again executed. This
process continues while the expression is true. When the expression is found to be false,
the second suite (suite-2), if present, is executed. This can be shown by the following
figures:
Example: Following is a script to display first n natural numbers, where n is input from the user. If the
user enters 0 or a negative number, the script generates no output.
Execution of the above script: When the above code is executed, the user will be prompted to enter a
value for n. Let us assume that user enters 5. In the next statement, a variable, i, will be initialized to
1. Then the control will reach while statement. Here the condition will be checked, and will be found to
be true (why?). As the looping condition is true, the suite will be executed. In the suite, first statement
will display 1 (the value of i) and the next statement (i=i+1) will set the value of i to 2. As the suite
has been executed, the control will go to check the condition again. The condition is still true, and
therefore suite will be executed again. This time it will display 2 and i will be incremented to 3. The
condition will be checked again and 3 will be displayed, and i will be incremented to 4. The condition
will be checked again and 4 will be displayed, and i will be incremented to 5. The condition will be
checked again and 5 will be displayed, and i will be incremented to 6. The condition will be checked
again, and this time the condition will be found to be False. As the condition is false, suite will be
skipped and the control will transfer to the next statement: print("Done")). This statement will
display Done and the script execution will end.
Control variable: If the looping condition (expression specified in the while statement) checks the
value of a single variable, then this variable is generally called the control variable. For example, in the
above code, the looping condition checks the value of variable i. So, i is the control variable in the
above loop.
Initialization statement: The value of control variable should be initialized to a particular value before
the the loop starts. The statement to do so is called initialization statement. For example, i=1 is the
initialization statement in the above code.
Update statement: The value of control variable is updated in the loop so that the looping condition
becomes false after some time. The statement to do this is called the update statement. Without an
update statement, the loop becomes an infinite loop. In the above code i+=1 is the update statement.
Example 13:
To find the sum of first n natural numbers, where n is to be input from the user.
Solution:
Required information/result: Sum of first n natural numbers.
Given data: No data is given
Processing: To find the sum of first n natural numbers we have to take a variable (say, sum) and
initialize it to 0. Then we have to keep on adding the successive natural numbers to it. It means that it is
a case of iteration. The following suite of statements is to be repeated:
Add number to sum
Take the next number
We shall take another variable (say, i) to store the values of successive natural numbers.
Pseudocode:
(i) Input the value of n
(ii) sum = 0
(iii) i=1
(iv) while i <=n
a. add value of i to sum (sum = sum+i)
b. take the next value of i (i=i+1)
(v) Display sum
Script:
# To find the sum of first n natural numbers
n = eval(input("Enter the value of n: "))
sum=0
i = 1
while i<=n:
sum += i
i += 1
print("sum of first",n,"natural numbers =",sum)
Here we have taken a variable sum, in which we are adding the values whose sum is to
be found. Such a variable which is used to keep the sum of values which are to be
added, is called an accumulator.
Example 14:
To input a number and display its first 10 multiples.
Solution:
Required information/result: first 10 multiples of a number.
Given data: No data is given
Pseudocode:
(vi) Input a number (n)
(vii) i=1
(viii) while i <=10
a. display n*i
b. take the next value of i (i=i+1)
Script:
# To Input a number and display its first 10 multiples
n = eval(input("Enter a number: "))
i=1
while i<=10:
print(n,"x",i,"=",n*i)
i+=1
Example 15:
To input an integer and find the sum of its digits
Solution:
Required information/result: To find and display the sum of the digits of an integer.
Given data: No data is given
Processing: To find the sum of the digits of a number, we have to separate the digits of the number
and add them to a variable (say, sum). We cannot separate the digits of an integer all at once. We have
to do it one by one, by using the following concept:
(i) If we divide an integer by 10, the remainder is its unit’s digits. For example, 5236%10 is 6.
(ii) If we divide an integer of n (n>=2) digits by 10, the quotient is an integer of n-1 leftmost
digits of the original number. For example, quotient of 5236/10 is 523.
(iii) If we divide a single digit integer by 10, the quotient is 0.
By repeating these steps with successive quotients, we can separately access the digits of an integer.
An example is shown below:
Pseudocode:
(i) Input an integer (n)
(ii) sum=0
(iii) while n ≠ 0
a. digit = n%10
b. sum += digit (Add digit to sum)
c. n = n//10 (Take the quotient as the next integer)
(iv) Display the value of sum
CS(083)-XI 1.33 © Yogesh Kumar – (965) 65891262
XI/CS(083)/Programming in Python/2019/YK
Script:
#To find the sum of the digits of an integer
n = int(input("Enter an integer: "))
sum=0
while n != 0:
digit = n%10
sum += digit
n//=10
print (sum)
This script will give the correct result as long as user enters a positive integer. If the user enters a
negative integer, the script will enter an infinite loop (a never ending loop). If the user enters a floating
point number, the sum will also be displayed as a flowing point value (it will be an incorrect sum).
Therefore, after inputting the number using eval(input()), we should use int() function to
convert the entered number into an integer. Then we should use abs() function to find the absolute
value of the number (To ensure that the number is positive even if the user has entered a negative
number). Following is the modified code to do so:
Example 16:
To input an integer and find the product of its odd digits.
Solution:
Required information/result: The product of the odd digits of an integer.
Given data: No data is given
Processing: This script also needs to separate the digits of an integer, as in the previous example. In
this example, we have to find the product of odd digits of the number. Therefore, we shall take a
variable (say, prod) and initialize it to 1. We shall separate the digits of the integer and check each digit.
If we find an odd digit we multiply prod by that digit. At the end, we shall display the value of prod.
Script:
# To input an integer and find the product of its odd digits.
n = eval(input("Enter a number: "))
n = abs(int(n))
prod=1
oddDigitFound=0
while n != 0:
digit = n%10
if digit%2 == 1:
prod *= digit
oddDigitFound=1
n //= 10
if oddDigitFound==1:
print("Product of odd digits =",prod)
else:
print("No odd digit is present in the number")
Example 17:
To input an integer and check whether it is prime or not.
Solution:
Required information/result: A message indicating whether a given integer is prime or not.
Given data: No data is given
Processing: The simplest (but very inefficient) method to check whether a given number is prime or not
is to find its smallest factor after 1. If this smallest factor is same as the number itself (i.e., the number is
not divisible by any number less than the the number itself), then the the number is prime, otherwise it
is not prime.
Pseudocode:
(i) Input an integer (n)
(ii) count=0
(iii) f=2
(iv) while n%f != 0
f+=1
(v) if (f == n) then
Display the message “Number is prime”
Otherwise Display the message “Number is not prime”
Script:
# To input a number and check whether it is prime or not
n = eval(input("Enter a number: "))
n = abs(int(n))
prime=1
factor=2
while factor<n and prime==1:
if n%factor==0:
prime=0
else: factor+=1;
if n>1 and prime==1:
print(n,"is a prime number")
else:
print(n,"is not a prime number")
(ii) for: for loop is used for repeated execution over the elements of a sequence. In its simplest form,
the syntax of for loop is:
"for" variable "in" "range(" start "," stop "," step ")" ":"
Suite-1
["else" ":"
Suite-2
]
Here:
(i) variable is any variable name.
(ii) range() is a built-in function that produces a sequence of integers from start (inclusive) to
stop (exclusive), by step. Range() can be used in three forms:
a. with one parameter: range(stop) produces a sequence of integers from 0 to stop-1 in steps
of 1. For example range(10) produces a list of integers 0, 1, 2, 3, 4, 5, 6, 7, 8, 9.
b. With two parameters: range(start, stop) produces a sequence of integers from start to
stop-1 in steps of 1. For example range(2,10) produces a list of integers 2, 3, 4, 5, 6, 7, 8,
9.
c. With three parameters: range(start, stop, step) produces a sequence of integers from
start to stop-1 in steps of step. For example range(2,10,3) produces a list of integers 2,
5, 8.
(iii) else is an optional clause of for loop
Execution: When the control reaches for statement, the variable is assigned the first value of first
element of the specified sequence, and first suite (suite-1) is executed. The variable is assigned the
value of next element of the sequence and suite-1 is executed again. This is repeated for all elements
of the sequence. After that the second suite (suite-2), if present, is executed. This can be shown by
the following figures:
Example: Following is the script to display first n natural numbers, where n is input from the user. If the
user enters 0 or a negative number, the code generates no output.
n = eval(input("Enter a number: "))
for i in range(1,n+1):
print(i)
print("Done")
Execution of the above script: When the above code is executed, the user will be prompted to enter a
value for n. Let us assume that user enters 5. The the control reaches the for statement. Here, the
function range(1,n+1) will produce a sequence of integers from 1 to 5, and i will be initialized to first
element (i.e., 1) of this sequence. Now, the suite (containing only one statement, i.e., print(i)) will
be executed and 1 will be displayed on the screen. Then i will be assigned next value in the sequence,
i.e. 2. Again print(i) will executed and it will display 2 on the screen. Like this I will be assigned values 3,
4, and 5 and all these values will be displayed on the screen.
After that, the loop will terminate the control will transfer to the next statement (print("Done")).
This statement will display Done and the script execution will end.
Example 18:
To find the sum of first n even natural numbers, where n is to be input from the user.
Solution:
Required information/result: Sum of first n even natural numbers.
Given data: No data is given
Processing: To find the sum of first n even natural numbers we have to take a variable (say, sum) and
initialize it to 0. Then we have to keep on adding the successive even natural numbers to it. It means
that it is a case of iteration over the sequence 2 to 2n.
Pseudocode:
(i) Input the value of n
(ii) sum = 0
(iii) for num in the range 2 to 2n, in steps of 2
a. sum += num
(iv) Display sum
CS(083)-XI 1.37 © Yogesh Kumar – (965) 65891262
XI/CS(083)/Programming in Python/2019/YK
Script:
# To find the sum of first n natural numbers
n = eval(input("Enter the value of n: "))
n=abs(int(n))
sum=0
for num in range(2, 2*n+1, 2):
sum += num
print("sum of first",n,"even natural numbers =",sum)
Example 19:
To input an integer and find its factorial. Factorial of an integer n (n>=1), is defined as the product of all
natural numbers from 1 to n, and is represented by n!. For example, factorial of 5 is represented by 5!
and is equal to 1x2x3x4x5 (=120). Factorial of 0 is taken as 1 and factorial of negative integers is not
defined.
Solution:
Pseudocode:
(i) Input a positive integer
(ii) factorial=1
(iii) for num in the range 2 to n
factorial = factorial * num
(iv) Display the value of factorial
Script:
# To find the factorial of an integer
n = eval(input("Enter the value of n: "))
n=abs(int(n))
factorial=1
for num in range(2, n+1):
factorial *= num
print(factorial)
Example 20:
To display even natural numbers from 2 to n, where n is to be input from the user. For example, if the
value of n is 13, the output should be 2 4 6 8 10 12.
Solution:
Pseudocode:
(i) Input the value of n
(ii) for num in the range 2 to n, in steps of 2
print(num)
Script:
# To display even natural numbers from 2 to n
n = eval(input("Enter the value of n: "))
n=abs(int(n))
for num in range(2, n+1, 2):
print(num)
The output of this code will be the required even numbers in separate lines. But the requirement is to
have all the numbers in the same line. Here the problem is that print() function puts a newline character
after displaying the last value, so that the next vale is displayed in the next line. If we wish, we can
specify some other string also as the end of line string using the end argument of print() function. An
example is shown below:
print(12,23,end=' ')
print("are integers")
print(12.23,end=', ')
print(21.5, "are floating point numbers")
It means that if we change the print statement in the script of above example, from print(num) to
print(num, end=' '), we shall get all the numbers in one line.
Now you should be at a stage to understand the stated question and the corresponding Python script.
So, Let us now see examples of some more scripts using loops. In the these examples, we state the
problem, write pseudocode (for a few examples only), and then the script. Some scripts will need while
loop and some will need for loop. Remember while loop is used to iterate over a condition, and for loop
is used to iterate over a list of values.
Example 21:
Write script to input a number. If the number is negative, then again input the number. Keep on doing
so until the user enters a zero or a positive number. When the user enters a non-negative number,
display the message “Thank you”.
Pseudocode:
1. input(n)
2. while (n is negative)
a. input(n)
3. print(“Thank you”)
Script:
#To input a non-negative number
n = eval(input("Enter a non-negative number: "))
while (n<0):
n = eval(input("Enter a non-negative number: "))
else:
print("Thank you")
Example 22:
Write script to input 10 numbers and then display then display the largest of the numbers entered.
Pseudocode:
1. Input first number n
2. max=n
3. repeat the following 9 times
a. input a number n
b. if n>max
i. max=n
4. print(max)
Script:
# To the largest of 10 numbers entered
n = eval(input("Enter a number: "))
max=n
for i in range(1,10):
n=eval(input("Enter a number: "))
if n>max:
max=n
print(max,"is the largest number entred")
Example 23:
Write script to input 10 numbers and then display the smallest number entered. If the smallest number
is an integer, then find the sum of its digits, otherwise display the message “smallest number is not an
integer”.
Pseudocode:
1. Input first number n
2. min=n
3. repeat the following 9 times
a. input a number n
b. if n<min
i. min=n
4. print(min)
5. if int(min)==min (if min is an integer)
a. sum=0
b. while min ≠ 0
i. digit = min%10
ii. sum += digit (Add digit to sum)
iii. min = min//10 (Take the quotient as the next integer)
c. Display the value of sum
6. Otherwise Display(“smallest number is not an integer)
Script:
#To find
# (i) the smallest of 10 numbers entered
# (ii) Sum of the digits of the smallest number, if i is an integer
Can you write the above code using while loop instead of for loop? If yes, then write it and execute it. If
not, specify the reason.
Example 24:
Script:
# To input two numbers and find their LCM.
n1 = eval(input("Enter first number:"))
n2 = eval(input("Enter second number:"))
n1=abs(int(n1))
n2=abs(int(n2))
i=1
while ((n1*i)%n2 != 0):
i+=1
LCM = n1*i;
print("LCM of",n1,"and",n2,"=",LCM)
Example 25:
Write a menu driven program to calculate the total surface area and volume of a cube, cuboid, or
sphere depending upon user’s choice. The program should continue until the user selects the option to
exit the program.
Script:
#To calculate total surface are and volume of a
#cylinder, sphere, or cone depending upon the user's choice.
Pi=3.14
choice=1
while choice != 0:
print("1. Cylinder")
print("2. Sphere")
print("3. Cone")
print("0. Exit")
choice=eval(input("Enter your choice (1, 2, 3, or 0): "))
if (choice==1):
r=eval(input("Enter radius of cylinder: "))
h=eval(input("Enter height of cylinder: "))
TSA=2*Pi*r*h+Pi*r*r
Vol=Pi*r*r*h
print("Total Surface Area =",round(TSA,2),"sq. units")
print("Volume =",round(Vol,2),"cu. units")
elif (choice==2):
r=eval(input("Enter radius of sphere: "))
TSA=4*Pi*r*r
Vol=4*Pi*r*r*r/3
print("Total Surface Area =",round(TSA,2),"sq. units")
print("Volume =",round(Vol,2),"cu. units")
elif (choice==3):
r=eval(input("Enter radius of cone: "))
h=eval(input("Enter height of cone: "))
l = (r*r+h*h)**0.5
TSA=Pi*r*l+Pi*r*r
Vol=Pi*r*r*h/3
print("Total Surface Area =",round(TSA,2),"sq. units")
print("Volume =",round(Vol,2),"cu. units")
elif (choice==0):
break;
else: print("Invalid choice")
print('---------------------------------')
Example 26:
Write script to input a list of n number and count how many of the entered numbers were prime.
Script:
# To input a list of n number and
#count how many of the entered numbers were prime
n = eval(input("Enter the value of n: "))
n = abs(int(n))
count=0
for i in range(1,n+1):
num = eval(input("Enter a number: "))
num = int(abs(num))
prime=1
factor=2
while factor<num and prime==1:
if num%factor==0:
prime=0
else: factor+=1;
if num>1 and prime==1:
count+=1
Example:
Write script to find the sum of first n terms of the following series:
x + x2 + x3 + . .
where n and x have to be input from the user.
Script:
#To find the sum of first n terms of the following series:
#x + x**2 + x**3 + . .
#where n and x have to be input from the user.
Example 27:
Write script to find the sum of first n terms of the following series:
x - x2 + x 3 - . . .
where n and x have to be input from the user.
Script:
#Script to find the sum of first n terms of the following series:
#x - x**2 + x**3 - . .
#where n and x have to be input from the user.
Try writing the above code without using if..else. Yes, it can be written.
Example 28:
Write script to find the sum of first n terms of the following series:
x2 x3
1+ x + + +...
2 3
where n and x have to be input from the user.
Script:
#Script to find the sum of first n terms of the following series:
#1 + x + x**2/2 + x**3/3 + . .
#where n and x have to be input from the user.
Example 29:
Write script to find the sum of first n terms of the following series:
x2 x3
1+ x + + +...
2! 3!
where n and x have to be input from the user.
Script:
#Script to find the sum of first n terms of the following series:
#1 + x + x**2/2! + x**3/3! + . .
#where n and x have to be input from the user.
Example 30:
Write script to find the sum of first n terms of the following series:
x2 x3
1- x + - +...
2! 3!
where n and x have to be input from the user.
Script:
#Script to find the sum of first n terms of the following series:
#1 - x + x**2/2! - x**3/3! + . .
Example 31:
#break and continue
for i in range(1,11):
if (i%3 == 0):
continue;
if (i*3 > 25):
break;
print(i,end=' ')
else: print("Else part of loop")
print()
print(i);
Assignment:
1. Write a menu driven program to calculate the total surface area and volume of a cube, cuboid, or
sphere depending upon user’s choice. The program should continue until the user selects the option to
exit the program.
2. WAP to input a number. If the number is negative, then again input the number. Keep on doing so until
the user enters a positive number.
3. WAP to input two numbers m and n. Then display first m multiples of n.
4. WAP to input 10 numbers and then display their sum and average. Also display the largest and the
smallest of the numbers entered.
5. WAP to input two numbers and find their LCM and HCF.
6. Write a program to input a number and check whether it is a prime or not.
7. WAP to display all the prime numbers between m and n, where m and n have to be input from the user.
8. WAP to input a list of n number and count how many of the entered numbers were prime.
9. WAP to input a number and check whether it is palindrome or not.
10. WAP to find the sum of first n terms of the following series:
x + x2 + x3 + . . .
11. WAP to find the sum of first n terms of the following series:
x - x2 + x3 + . . .
12. WAP to find the sum of first n terms of the following series:
x2 x3
1+ x + + +...
2 3
13. WAP to find the sum of first n terms of the following series:
x2 x3
1+ x + + +...
2! 3!
14. WAP to find the sum of first n terms of the following series:
x2 x3
1- x + - +...
2! 3!
15. WAP to find the sum of first n terms of the following series:
x3 x5 x7
1+ + + ...
3! 5! 7!
16. WAP to find the sum of first n terms of the following series:
x3 x5 x7
1- + - ...
3! 5! 7!
17. WAP to generate n lines of the following pattern on the computer screen:
1
12
123
.
.
18. WAP to generate n lines of the following pattern on the computer screen:
1
12
123
.
.
19. WAP to generate n lines of the following pattern on the computer screen:
1
121
12321
1234321
.
.
20. WAP to generate 2n+1 lines of the following pattern on the computer screen:
*
***
*****
*******
*****
***
*
21. WAP to generate 2n+1 lines of the following pattern on the computer screen:
*
@@@
*****
@@@@@@@
*****
@@@
*
22. WAP to generate 2n+1 lines of the following pattern on the computer screen:
*
* *
* *
* *
*********
*******
*****
***
*
23. WAP to generate 2n+1 lines of the following pattern on the computer screen:
*
* *
* *
* *
* *
* *
*
Exceptions
An exception is a run-time error in a script. When an exception occurs in a script, the execution of the script is
abruptly terminated. Let us see an example of an exception. Consider the following code:
This code accepts a number from the user and then displays its reciprocal. This code runs well if the user
enters a valid number, and raises an exception (run-time error) in the following cases:
(i) User enters 0. Exception raised is: ZeroDivisionError
(ii) User enters a string which forms a valid variable name but has not been defined earlier in the
script. Exception raised is: NameError
(iii) User enters a string which does not form a valid number or a valid variable name (e.g. 3a).
Exception raised is: SyntaxError
Exception Handling
Python provides us a way to handle exceptions so that the script does not terminate but executes some
specified code when an exception occurs. This concept is called Exception Handling. An exception can be
addressed by its name. Python has some built-in exception names for common exceptions. If required, a
programmer can also define his/her own exceptions. In this course we shall learn to handle some built-in
exceptions only. These are:
Python provides try statement for exception handling. try statement can be used in the following formats:
(i)
"try" ":" suite
"except" ":" suite
["else" ":" suite]
["finally" ":" suite]
(ii)
"try" ":" suite
"except" ExceptionName ":" suite
["except" ExceptionName ":" suite]
.
.
["except" ":" suite]
["else" ":" suite]
["finally" ":" suite]
The first form means that a try statement must have a try clause and at least one except clause. else and
finally clauses are optional.
The second form means that a try statement may have multiple except clauses with Exception Names to
handle specific exceptions, and one optional except clause. else and finally clauses are optional.
We shall now understand the execution of try statement with the help of examples. Following is a very simple
example of exception handling:
Example 32:
#ExceptionHandling - 1
#Exception Handling with try and except
n=-1
while n != -5:
try:
n=input("Enter a number: ")
n=eval(n)
m=1/n
print("number=",n,", reciprocal=",m,sep='')
except:
print("Some error occured")
print("Done")
If an exception is raised during the execution of this script, the control will be transferred to except clause
which displays the message “Some error occurred”. A sample output is shown below:
Output
Enter a number: 1
number=1, reciprocal=1.0
Enter a number: 2
number=2, reciprocal=0.5
Enter a number: 3a
Some error occured
Enter a number: wxyz
Some error occured
Enter a number: a3$
Some error occured
Enter a number: 0
Some error occured
Enter a number: 5
number=5, reciprocal=0.2
Enter a number: -5
number=-5, reciprocal=-0.2
Done
In the above example of exception handling we saw that the code does not stop when an exception occurs but
gives a message to the user and continues further.
The message “Some error occurred” tells the user that something went wrong, but does not tell what
actually went wrong. Python provides the following solution to this problem.
A try statement can have multiple except clauses and we can specify the name(s) of one or more
exception(s) with an except clause. In such a case, at the occurrence of an exception, the script works as
follows:
(i) control is transferred to the corresponding except clause handling the exception which has
occurred.
(ii) If that particular exception (which has occurred) is not specified in any except clause, then the
control is transferred to the except clause without any exception name.
(iii) If neither of the above two cases are met (there is no except clause handling that particular
exception and there is no except clause without any exception name), then the script terminates
abruptly as it happens when no try statement is used.
Two examples of exception handling in this way are shown below to clear the concept:
Example 33:
#ExceptionHandling - 2
#Exception Handling – with exception names
#Exception Handling-With exception names
n=-1
while n != -5:
try:
n=input("Enter a number: ")
n=eval(n)
m=1/n
print("number=",n,", reciprocal=",m,sep='')
except NameError: print("Variable not found")
except ZeroDivisionError: print("Division by zero not defined")
except: print("Some error occurred")
Output
Enter a number: 1
number=1, reciprocal=1.0
Enter a number: 2
number=2, reciprocal=0.5
Enter a number: 3a
Some error occurred
Enter a number: wxyz
Variable not found
Enter a number: a3$
Some error occurred
Enter a number: 0
Division by zero not defined
Enter a number: 5
number=5, reciprocal=0.2
Enter a number: -5
number=-5, reciprocal=-0.2
Let us see another example. Here we shall try to do the floor division of a number with another number.
Example 34:
#ExceptionHandling - 3
#Exception Handling – with exception names
x=1
while x>-5:
try:
x = eval(input("Enter a number: "))
y = eval(input("Enter another number: "))
z=x//y
Output
Enter a number: 1
Enter another number: 2
x = 1 , y = 2 x//y = 0
Enter a number: 3
Enter another number: 4+5j
Incompatible data types
Enter a number: 4+5j
Enter another number: 3
Incompatible data types
Traceback (most recent call last):
File "C:/Users/ykuma_000/Desktop/2018-19/CS-XI/Python Code/except5.py",
line 3, in <module>
while x>-5:
TypeError: '>' not supported between instances of 'complex' and 'int'
The script works smoothly except for the case when the user enters a complex number as the first number.
When the user enters a negative numberas the first number, thn after showing the message “Incompatible
data types”, when the control goes back to check the condition x>-5 in the while clause, there it finds data
types of x and -5 to be incompatible for comparison. As the while clause is not put under try, so no exception
handling is done here and the script terminates abruptly.
You can try the first solution at your own. Here I am giving you the second solution.
It is not necessary that we give only the print statement in an except clause. We can give any suite of valid
statements in an except clause. So, the updated version of the above script goes as follows:
Example 35:
#ExceptionHandling - 3
#Exception Handling – making corrections in except clause
x=1
while x>-5:
try:
x = eval(input("Enter a number: "))
y = eval(input("Enter another number: "))
z=x//y
print("x =",x,", y =",y,"x//y =",z)
except ValueError: print("Invalid value entered")
except ZeroDivisionError: print("Division by zero not defined")
except TypeError:
print("Incompatible data types")
x=y=1
except SyntaxError: print("Syntax Error")
except NameError: print("Variable not defined")
finally clause in exception handling: In the finally clause of try statement, we can specify the code which
has to be executed in any case - irrespective of whether an exception occurred or not. See the following
example:
Example 36:
#ExceptionHandling - 4
#Exception Handling – with "finally" clause
#ExcepFinally1
x=1
while x>-5:
try:
x = eval(input("Enter a number: "))
y = eval(input("Enter another number: "))
z=x//y
except ValueError:
print("Invalid value entered. Setting both numbers as 1")
x=y=1
except ZeroDivisionError:
print("Division by zero not defined. Setting second value as 1")
y=1
except TypeError:
print("Incompatible data types. Setting both numbers as 1")
x=y=1
except SyntaxError:
print("Syntax Error. Setting both numbers as 1")
x=y=1
except NameError:
print("Variable not defined. Setting both numbers as 1")
x=y=1
finally:
z=x//y
print("x =",x,", y =",y,", x//y =",z)
if (x<=-5):
print("--- Done ---")
Output
Enter a number: 1
Enter another number: 2
x = 1 , y = 2 , x//y = 0
Enter a number: 2+3j
Enter another number: 4+5j
Incompatible data types. Setting both numbers as 1
x = 1 , y = 1 , x//y = 1
Enter a number: 4
Enter another number: 1.2
x = 4 , y = 1.2 , x//y = 3.0
Enter a number: 3a
Syntax Error. Setting both numbers as 1
x = 1 , y = 1 , x//y = 1
Enter a number: 5
Enter another number: a4
Variable not defined. Setting both numbers as 1
x = 1 , y = 1 , x//y = 1
Enter a number: -5
Enter another number: 2
x = -5 , y = 2 , x//y = -3
--- Done ---
else clause in exception handling: In the else clause of try statement, we can specify the code which has
to be executed in case no exception occurs. See the following example:
Example 37:
#ExceptionHandling - 5
#Exception Handling – with "else" clause
x=1
while x>-5:
try:
x = eval(input("Enter a number: "))
y = eval(input("Enter another number: "))
z=x//y
except ValueError:
print("Invalid value entered. Setting both numbers as 1")
x=y=1
except ZeroDivisionError:
print("Division by zero not defined. Setting second value as 1")
y=1
except TypeError:
print("Incompatible data types. Setting both numbers as 1")
x=y=1
except SyntaxError:
print("Syntax Error. Setting both numbers as 1")
x=y=1
except NameError:
print("Variable not defined. Setting both numbers as 1")
x=y=1
else:
print("Normal execution, both values OK")
finally:
z=x//y
print("x =",x,", y =",y,", x//y =",z)
if (x<=-5):
print("--- Done ---")
Output
Enter a number: 1
Enter another number: 2
Normal execution, both values OK
x = 1 , y = 2 , x//y = 0
Enter a number: 2
Enter another number: 0
Division by zero not defined. Setting second value as 1
x = 2 , y = 1 , x//y = 2
Enter a number: 5+3j
Enter another number: 2+4j
Incompatible data types. Setting both numbers as 1
x = 1 , y = 1 , x//y = 1
Enter a number: 55.4
Enter another number: 2.45
Normal execution, both values OK
x = 55.4 , y = 2.45 , x//y = 22.0
Enter a number: -5
Enter another number: 2+3j
Incompatible data types. Setting both numbers as 1
x = 1 , y = 1 , x//y = 1
Enter a number: -5
Enter another number: 2
Normal execution, both values OK
x = -5 , y = 2 , x//y = -3
--- Done ---
If a script has a syntax error, the parser reports it and the program execution does not even start. A script
execution will start only if the script is free from all the syntax errors.
The run-time errors are called exceptions and we have just seen how to handle these in Python.
The logical errors are the most difficult to detect. If a script has logical error(s), the script will execute without
any problem and will produce the output, but the output will not be correct. If the programmer does not verify the
output for its correctness, the error will go unnoticed and may create some kind of trouble for the
administration/organization for which the script is used. If the script is used in some automation process, then
logical errors may prove to be fatal too! Therefore, a programmer must verify the output for its correctness and
remove all the logical errors from the script.
Detecting and correcting the logical errors from a script may, sometimes, be a really tricking process and may
take a long time (may be hours or days). In such situations debugging tools really prove to be of immense use.
Python provides a debugging tool with the name pdb (Python DeBugger). Pdb is a module which provides
many facilities like tracing the script, inserting/removing breakpoints, inspecting the values of variables etc.
Tracing the script means executing the script one line at a time on the user’s command. While tracing, the
interpreter does not execute the whole script automatically. The script is executed one line at a time only when
user gives a command to do so. After execution of a line the user can view the values of variables, test a new
statement (which is not already present in the script), and can do many other tasks which help him/her to
understand the flow of the code, and hence, debug it.
Let us now cover pdb in some details. Let us start with a very simple example to familiarize ourselves with the
pdb commands. Consider the following script:
a=2
b=3
c=a+b
print(a,b,c)
a += a+b+c
b += a+b+c
c=a*b
print(a,b,c)
a += a+b+c
b += a+b+c
c=a*b
print(a,b,c)
To trace this script using pdb, you have to give the command import pdb as the first command of the script.
To start tracing the script, you have to give the command pdb.set_trace() just before the statement from
where you want to start tracing the script. Suppose you want to trace the script from the first print statement,
then your modified code will look as follows:
import pdb
a=2
b=3
c=a+b
pdb.set_trace()
print(a,b,c)
a += a+b+c
b += a+b+c
c=a*b
print(a,b,c)
a += a+b+c
b += a+b+c
c=a*b
print(a,b,c)
Suppose you save this script with the name test.py, and execute this script.
The output will be as follows:
c(cont(inue)) To exit the pdb mode and continue script execution in a normal way.
l(ist) To list eleven lines (current line to be executed, 5 preceding lines, and 5 following lines) of
the script.
b(break) To insert a breakpoint at a specified line number, or to list the breakpoints if no line number
is specified.
q(uit) To terminate the script execution and quit the pdb mode.
ENTER To repeat the last entered pdb command.
Each command can be given in full form or in abbreviated form. For example, to execute the next line we can
give the command n or next. Following figure shows is a sample output of the above script after giving some
pdb commands. Try to understand these commands and the corresponding outputs properly.
How does debugger help? When a script is traced in the debugger mode, we can view the values of variables
whenever required. Usually we display the values of variables whenever some significant calculation takes
place at some point in the code. We then observe the values of variables to check that everything is being done
as expected. If at some point we find that values of variables are not as we expected these to be, or some
statement is being executed where it should not be, or some statement is not being execute where it should be,
then we check the previous lines of the script to find where did the logic go wrong.
Let us see it through a simple example. Suppose you write the following code in Python to find the LCM and
HCF of two numbers:
Example 38:
n1 = eval(input("Enter first number:"))
CS(083)-XI 1.54 © Yogesh Kumar – (965) 65891262
XI/CS(083)/Programming in Python/2019/YK
LCM = n1*n2;
HCF = n1*n2/LCM
print("LCM=",LCM)
print("HCF=",HCF)
You execute this code and get the following output (for example):
Enter first number:6
Enter second number:8
LCM= 48
HCF= 1.0
You execute the code for some other set of numbers and again get incorrect values of LCM and HCF. It always
calculates LCM as the product of two numbers and HCF as 1. Although it is simple to find and correct the error,
yet let us see how can we use the debugger (pdb) to debug this code.
Let us assume that first two lines of our script are OK and we want to trace the program execution from the third
line. So, we modify the script as follows:
Example 39:
import pdb
n1 = eval(input("Enter first number:"))
n2 = eval(input("Enter second number:"))
pdb.set_trace()
n1=n1//1
n2=n2//1
i=1
while ((n1*i)%n2 != 0):
i+=1
LCM = n1*n2;
HCF = n1*n2/LCM
print("LCM=",LCM)
print("HCF=",HCF)
Here we observe that value of LCM should have been calculated as 24 and not as 96. Now we should check
the values of other variables also. We find that other variables are just as expected. Then we check the
previously executed statement(s) in the reverse order. Here we observe that the statement LCM=n1*n2 is the
cause of the problem. Actually it should have been LCM = n1*i. We can give this statement at pdb prompt to
see if it would give the correct result. This command will be executed to calculate the new value of LCM. Then
we can print the value of LCM and verify it. This is shown below:
Now we observe that correct value of LCM is calculated. After this we can keep tracing the script using n
command or execute the script in one go using c command. At the end we find that value of HCF is also being
calculated correctly.
As we have found the source of error and the corresponding correction to be made, we can correct our script
and execute it again to verify the outputs with different inputs. Once we are satisfied with the script, we can
remove import pdb and pdb.set_trace() statements from the script.
Setting breakpoints: A breakpoint is a line in the script where we want to pause the execution. We can set a
breakpoint by b(reak) command followed by the line number where we want to set breakpoint on. Setting
breakpoints is a very useful utility to debug large programs.
While in debugger mode when we give the command c (to continue), the script is executed till the next
breakpoint in the script or till the end of the script if no breakpoint is found. In a large program, it is time-
consuming and annoying to debug the code using n command to execute one line of script in one step. In large
programs, the programmer usually knows the probable points of error in the script. In such cases, the code
between two probable points of error (which may be a few or a large number of statements apart) should not
be traced, but should be executed continuously. The debugger should stop only at specified breakpoints, which
can be put at probable points of error.
Python is an Object Oriented programming language. It has a number of inbuilt classes. You have already seen
some classes like ‘int’, ‘float’, ‘str’, ‘bool’, and ‘complex’ to represent fundamental data types. Whenever we
refer to an integer, it is an object of ‘int’ class, float value is an object of ‘float’ class, and so on.
Lists
A list is an ordered heterogeneous collection of elements. In Python a list is created by putting the elements of
the list in bracktes [ ]. For example, following is a list of five colors:
['Red', 'Green', 'Pink', 'Black', 'Orange']
Usually a list is assigned to a variable name. For example, the following statement:
color = ['Red', 'Green', 'Pink', 'Black', 'Orange']
assigns the list of five colors to the variable color.
The elements in a list are numbered, starting from 0. It means that first element of the list is numbered 0,
second is numbered 1, third is numbered 2, and so on. These numbers are called indices of list elements.
Python supports negative indices also. In case of negative indices, -1 is the index for the last element, -2 for the
second last element, and so on.
So, the above list (color) can be logically viewed as:
0 1 2 3 4
-5 -4 -3 -2 -1
Slicing: A slice of a list means a subset of list elements. For example, [‘Green’,’Pink’] is a slice of list color
defined above. The syntax to obtain a slice of a list is:
listName[start:stop:step]
CS(083)-XI 1.57 © Yogesh Kumar – (965) 65891262
XI/CS(083)/Programming in Python/2019/YK
A statement using this syntax returns a subset of list listName from listName[start] to
listName[stop-1] in steps of specified step (an integer). The values of start, stop, and step are
optional. If skipped, the default value of start is taken as 0, default value of stop is taken as N-1 (where N is
the size of the list), and default value of step is taken as 1. Following are some examples of slicing to clear the
concept:
>>> marks = [12,21,23,19,15,24,21,15,23]
>>> marks[2:] #Slice of marks from marks[2] to end of the list
[23, 19, 15, 24, 21, 15, 23]
>>> marks[:2] #Slice of marks from marks[0] to marks[1]
[12, 21]
>>> marks[2:6] #Slice of marks from marks[2] to marks[5]
[23, 19, 15, 24]
>>> marks[2:6:3] #Slice of marks from marks[2] to marks[6] in steps of 3
[23, 24]
>>> marks[2:9:3] #Slice of marks from marks[2] to marks[8] in steps of 3
[23, 24, 23]
>>> marks[::3] #Slice of marks from beginning to end in steps of 3
[12, 19, 21]
>>> marks[::] #Slice of marks from beginning to end (Complete list)
[12, 21, 23, 19, 15, 24, 21, 15, 23]
>>> marks[] #Not allowed
SyntaxError: invalid syntax
Marks[2:5]=[1,6,3]
List methods:
Method Syntax Description Example
append() list.append(x) Inserts element x as color.append('Red')
the last element of
the list.
extend() list.extend(list1) Concatenates list1 color.extend(['Cyan', 'Red'])
to list.
insert() list.insert(i,x) Inserts element x at color.insert(3, 'Grey')
the index i in the list.
remove() list.remove(x) Removes first color.remove('Pink')
occurrence of
element x from the
list.
pop() list.pop(i) Removes element at color.pop(2)
index i from the
list, and returns this
list.pop() element. color.pop()
but search is
performed in the
range list[start] to
list[end-1]
count() list.count(x) Returns the number color.count('Red')
of times element x
appears in the list.
sort() list.sort() Sorts the elements of color.sort()
the list.
reverse() list.reverse() Reverses the order color.reverse()
of elements in the
list.
copy() list.copy() Returns a copy of color.copy()
the list.
Two small scripts using lists and corresponding methods are given below. The outputs of print statements in the
first script are given on the right hand side of the script. The output of second script is given after the script due
to space constraint.
Output:
Unpacking a list:
Values of a list’s elements can be assigned to individual variables in sequence. This concept is called
unpacking. For example:
While unpacking, the number of variables on the left hand side must be equal to the number of list/slice
elements on the right hand side, otherwise the interpreter will show ValueError. Examples:
Solution:
Pseudocode:
(i) Take an empty list (say, roll)
(ii) When a student enters:
Input a roll number (say, r)
If (r is a roll number in the given range)
If (r is not in roll)
Add r to roll
Else display “Duplicate Roll Number” message
Else display “Invalid roll number message”
(iii) When a student leaves:
Input roll number (say, r)
If (r is in roll)
Delete r from roll
Else display “Roll number not present message”
(iv) To count the number of students present:
Display len(roll)
(v) To display the smallest and the largest roll number present:
Display min(roll) and max(roll)
(vi) To display absentees’ roll numbers
For r in range 91041 to 91090
If (r is not in roll)
Display r
(vii) To display the sorted list of present roll numbers
Roll.sort()
For r in roll
Display r
Script:
roll=[]
first=91041; last=91090
stop = 0
while not stop:
print()
print("1. Student Enters")
print("2. Student Exits")
print("3. Student Count")
print("4. Smallest and Largest Roll number present")
print("5. Absentees' list")
print("6. Sorted list of roll numbers")
print("0. Exit")
option = int(input("Enter your option"))
if (option==0):
stop=1
if option==1:
r = int(input("Enter roll number"))
if (r<first or r>last):
print("Roll number out of range")
elif r in roll:
print("Roll number already present")
else: roll.append(r)
elif option==2:
r = int(input("Enter roll number"))
if r in roll:
roll.remove(r)
else:
Tuples
A tuple is an ordered set of immutable heterogeneous elements. In Python a tuple can be created by putting
the comma-separated elements of the tuple in parentheses (). For example, following is a tuple representing a
book with code 1021, title ‘Programming in Python’, binding type ‘Hard Bound’, and edition 2018:
(1021,'Programming in Python', 'Hard Bound', 2018)
Usually a tuple is assigned to a variable name and then that variable name represents the tuple. For example,
the following statement:
Book = (1021,'Programming in Python', 'Hard Bound', 2018)
assigns the specified tuple to the variable Book.
To create a tuple of one element, the element must be followed by a comma. Example:
Like a list, a tuple is also a sequence of elements. The only difference is that a list is mutable whereas a tuple is
not. This means that a list elements can be changed and deleted, but a tuple elements cannot be. Therefore,
all the methods, functions, operators, and concepts which are defined for lists are applicable to tuples also,
excluding the methods/functions/operators/concepts which try to change the elements of a tuple.
Elements of a tuple are indexed exactly in the same manner as in lists. So, the above tuple (Book) can be
logically viewed as:
0 1 2 3
-4 -3 -2 -1
The tuple elements can be accessed exactly in the same manner as those of lists.
Slicing: A slice of a tuple means a subset of tuple elements. The concept is common to lists and tuples.
Tuple methods:
tuple.index(x,start,end)
Returns the index of
Book.index('2018',2,5)
element x in the
tuple, but search is
performed in the
range tuple[start] to
tuple[end-1]
count() tuple.count(x) Returns the number Book.count('Hard Bound')
of times element x
appears in the tuple.
Values of tuple elements can be assigned to individual variables in sequence. This concept is called unpacking.
For example:
Like in case of lists, while unpacking, the number of variables on the left hand side must be equal to the number
of tuple/slice elements on the right hand side, the interpreter will show ValueError. Example:
tuple1[0] [1,2,3]
tuple1[1] ['a','b']
tuple1[2] 10
tuple1[3] 20
tuple1[4] ('p','q','r')
Example 41:
list1=[1,2,3]
list2=['a','b']
tuple1=(list1, list2, 10, 20, ('p','q','r'))
print("list1:\n",list1)
print("list2:\n",list2)
print("tuple1:\n",tuple1)
print("tuple1[1] ->",tuple1[1]) #prints list2
print("tuple1[1][0] ->",tuple1[1][0]) #prints 'a' - 0th element of tuple[1]
print("tuple1[4][1] ->",tuple1[4][1]) #prints 'q' - 1th element of 4th element of tuple1
list2.append(20) #tuple1 also changes
list1.pop() #tuple1 also changes
tuple1[1][1]='c' #list2 also changes
print("list1:\n",list1)
print("list2:\n",list2)
print("tuple1:\n",tuple1)
Output:
list1:
[1, 2, 3]
list2:
['a', 'b']
tuple1:
([1, 2, 3], ['a', 'b'], 10, 20, ('p', 'q', 'r'))
tuple1[1] -> ['a', 'b']
tuple1[1][0] -> a
tuple1[4][1] -> q
list1:
[1, 2]
list2:
['a', 'c', 20]
tuple1:
([1, 2], ['a', 'c', 20], 10, 20, ('p', 'q', 'r'))
Nesting can be done upto any level. It means that we can have a list/tuple which is an element of a list/tuple
which is an element of another list/tuple which is again an element of a list/tuple, and so on. But to keep the
things easy we shall not go beyond two levels as we have shown in above examples.
Tuples Vs Lists:
Similarities in lists and tuples:
(i) Lists and Tuples are sequences.
(ii) Lists and Tuples may contain heterogeneous elements.
(iii) The concept of slicing is applicable to both Lists and Tuples.
(iv) Both, Lists and Tuples, support the concept of unpacking.
Differences between lists and tuples:
(i) A list is mutable, whereas a tuple is immutable. This means that a list elements can be
changed and deleted, but a tuple elements cannot be.
(ii) The concept of packing is applicable to tuples and not to lists
(iii) A list of one element can be created by putting the element in [ ] without any delimiter. To
create a tuple of one element, the element must be followed by a comma.
When to use what?
In general, lists are used to store homogeneous mutable values. For example, to store the marks of students,
To store the names of books, to stores the names of probable members of a team.
Tuples, in general, are used to store immutable values. For example, to store the names of months of an year,
to store the names of days of a week, to store the names of members of a team after final selection.
For this the invigilator has to be given a menu driven program which allows the invigilator to:
(i) Enter roll numbers of students as they enter the hall (one student at a time). While entry:
a. Only valid roll numbers should be allowed
b. No duplicate roll numbers should be allowed
c. The students’ room number (based on his roll number) should be calculated and displayed on
the screen.
(ii) Delete the roll number of any student who leaves the hall before the exam is over
(iii) Display the number of students present in the hall at any moment
(iv) Display a list of absentees’ roll numbers
(v) Display a sorted list of roll numbers present
Solution:
Here each room can be treated as a list as the elements (roll numbers) will have to be added and deleted as
and when students come and leave. The center itself can be treated as a tuple as it has three rooms and the
number of rooms remains fixed (immutable) during the script execution.
Pseudocode:
(i) Define three empty lists (say, room0, room1, room2)
(ii) Define a tuple (say, center) with room0, room1, and room2 as its elements.
(iii) When a student enters:
Input a roll number (say, r)
If (r is a roll number in the given range)
Calculate roomNo as (r-91041)//50
If (r is not in center[roomNo])
Add r to center[roomNo]
Else display “Duplicate Roll Number” message
Else display “Invalid roll number message”
(iv) When a student leaves:
Input roll number (say, r)
Calculate roomNo as (r-91041)//50
If (r is in center[roomNo])
Delete r from center[roomNo]
Script:
room0=[]
room1=[]
room2=[]
center=room0, room1,room2
first=91041; last=91190
option=1
while option!=0:
print()
print("1. Student Enters")
print("2. Student Exits")
print("3. Student Count")
print("4. Absentees' list")
print("5. Sorted list of roll numbers")
print("0. Exit")
option = int(input("Enter your option"))
if option==1:
r = int(input("Enter roll number"))
if (r<first or r>last):
print("Roll number out of range")
else:
room = (r-91041)//50
if (r in center[room]):
print("Roll number already present")
else:
print("--Room Number:",room," --")
center[room].append(r)
elif option==2:
r = int(input("Enter roll number"))
room = (r-91041)//50
if r in center[room]:
center[room].remove(r)
else:
print("Roll number not present")
elif option==3:
total = len(room0)+len(room1)+len(room2)
print(total,"students are present")
elif option==4:
total=len(room0)+len(room1)+len(room2)
if total == last-first+1:
print("All students are present")
else:
print("The following roll numbers are absent: ")
for r in range(first,last+1):
room = (r-91041)//50
if not(r in center[room]):
print(r, end=" ")
else: print(" ",end=" ")
if (r-91040)%15==0:
print()
elif option == 5:
total=len(room0)+len(room1)+len(room2)
if total==0:
print("No student is present")
else:
print("The following roll numbers are present: ")
for room in range(0,3):
print("Room Number:",room)
center[room].sort()
for r in center[room]:
print(r, end=" ")
print()
print()
Dictionary
A dictionary is an ordered set of key:value pairs, where a key can be a number or a string and value can also
be a number or a string. In Python a dictionary is be created by putting the comma-separated key:value pairs
of the dictionary in braces { }. For example, following is a small dictionary of three elements:
{'Arun':29, 'Khalid':32, 'Xaviour':30}
Usually a dictionary is assigned to a variable name. For example, the following statement:
marks = {'Arun':29, 'Khalid':32, 'Xaviour':30}
assigns the dictionary of three elements to the variable marks.
The keys in a dictionary are used as indices. Therefore, in the above dictionary, 'Arun', 'Khalid', and
'Xaviour' are indices for the values 29, 32, and 30 respectively. This can be logically viewed as:
This is unlike lists and tuples where indices are automatically assigned integers in sequence. As the keys are
indices for a dictionary, a dictionary cannot have multiple occurrences of the same key.
Dictionary methods: To understand the methods defined in the following table, we shall refer to the following
dictionary:
arabic={'where':'shuno','here':’minni’,'there':’hinni’,'come':'taal','go':'roa'}
Returns D[k] f k in
print(Arabic.get('who', 'Not
D.get(k,nf) dictionary D, otherwise
Found')) prints 'Not Found'
returns nf.
Solution:
Pseudocode:
(i) Take two dictionaries:
a. E2A for English to Arabic, initialized with given data
b. A2E for Arabic to English, initialized with given data
(ii) Take two empty lists
a. notFoundEnglish for the words not found in E2A dictionary
b. notFoundArabic for the words not found in A2E dictionary
(iii) To find English -> Arabic word:
Input the word (say, key)
If (E2A[key] exists)
Display the value E2A[key]
Else:
Display the message ‘Word not found’
Append key to the list notFoundEnglish
(iv) To find Arabic -> English word:
Input the word (say, key)
If (A2E[key] exists)
Display the value A2E[key]
Else:
Display the message ‘Word not found’
Append key to the list notFoundArabic
(v) To display English words not found in dictionary
for key in range notFoundEnglish
Display key
(vi) To display Arabic words not found in dictionary
for key in range notFoundArabic
Display key
(vii) To update E2A dictionary
Input password for authentication
If password is correct
If notFoundEnglish is not empty
for key in range notFoundEnglish
Input the Arabic word (say, value) for key
Add (key:value) pair to E2A dictionary
(viii) To update A2E dictionary
Input password for authentication
If password is correct
If notFoundArabic is not empty
for key in range notFoundArabic
Input the English word (say, value) for key
Add (key:value) pair to A2E dictionary
Script:
E2A={'what':'shuno','where':'vain','here':'minni','there':'hinni','why':'lesh'}
A2E={'shuno':'what','vain':'where','minni':'here','hinni':'there','lesh':'why'}
notFoundE=[]
notFoundA=[]
option=1
while option!=0:
print()
print("1. English -> Arabic")
print("2. Arabic -> English")
print("3. Un-found English words")
print("4. Un-found Arabic words")
print("5. Update English -> Arabic dictionary")
print("6. Update Arabic -> English dictionary")
print("0. Exit")
option = int(input("Enter your option: "))
if option==1:
key = input("Enter English word: ")
try:
value = E2A[key]
except KeyError:
notFoundE.append(key)
value = 'Word Not Found'
finally:
print(value)
elif option==2:
key = input("Enter Arabic word: ")
try:
value = A2E[key]
except KeyError:
notFoundA.append(key)
value = 'Word Not Found'
finally:
print(value)
elif option==3:
if len(notFoundE)>0:
print("Students searched for the following words, but did not find:")
print(notFoundE)
else: print("No such word")
elif option==4:
if len(notFoundA)>0:
print("Students searched for the following words, but did not find:")
print(notFoundA)
else: print("No such word")
elif option==5:
pwd=input("Enter password: ")
if pwd=='123':
for key in notFoundE:
value=input('Enter Arabic word for '+key+": ")
E2A.setdefault(key,value)
else: print("Invalid password")
elif option==6:
pwd=input("Enter password: ")
if pwd=='123':
for key in notFoundA:
value=input('Enter English word for '+key+": ")
A2E.setdefault(key,value)
else: print("Invalid password")
Sorting
Sorting means to arrange the elements of a list in ascending or in descending order. There are many methods
of sorting, but for our syllabus (Computer Science (083) – C.B.S.E.) we have to study only two sorting methods.
These are:
(i) Bubble sort (ii) Insertion sort.
Bubble Sort
In bubble sort algorithm we compare each element with its next element in the list. If these two elements are not
in the required order, then we interchange them. First time we compare list[0] with list[1], list[1] with list[2], and
so on till list[N-2] with list[N-1], where N is the length of the list. In this way at the end the largest (if we are
sorting in ascending order) or the smallest (if we are sorting in descending order) element reaches the last
location in the list. Now again we start from the beginning comparing each element to its next element. This
time the comparison is done from list[0] with list[1] to list[N-3] with list[N-2]. After this round of comparisons, the
second largest (or second smallest) element reaches the second last location of the list. We keep on performing
these rounds of comparisons, each round takes one element to its proper position in the sorted list, and hence
next round has one comparison less. This way, After N-1 such passes the complete list of N elements gets
sorted.
An Example:
Suppose we want to sort the following list of 7 elements in ascending order using bubble sort:
0 1 2 3 4 5 6
A
5 4 9 8 0 7 8
(ii)
(iii)
(iv)
(v)
(vi)
This completes one pass (round) of comparisons. This pass had 6 individual comparisons, and has put the
largest element (9) of the list at the last position.
Now, second pass of the comparisons starts. We shall not include the last element (9) in this pass, as it is the
largest element of the list and has been put at its required position by the previous pass. The second pass goes
as follows:
(i)
(ii)
(iii)
(iv)
(v)
This completes second pass of comparisons. This pass had 5 individual comparisons, and has put the largest
element (8), of the list of first six elements, at the last position. It gives the following list:
It means that in each pass we are taking one element to its required position in the sorted list. This is repeated
until all the elements have been sorted. Let us see the list after each pass:
We observe that each pass takes one element to its desired position, and hence, six elements are at their
desired positions in six passes, and seventh element is automatically left at its desired position. So, a list of
seven elements is sorted in six passes.
In general, a list of N elements can be sorted in N-1 passes.
Script
#create list
A=[]
more = 'y'
while more=='y' or more=='Y':
num=eval(input("Enter a number: "))
A.append(num)
more=input("Enter more data(y/n)? ")
#Now sort
N=len(A)
for i in range(1,N):
for j in range (0,N-i):
if A[j]>A[j+1]:
temp=A[j]
A[j]=A[j+1]
A[j+1]=temp
#Now display
print("Sorted list is: ",A)
Output
Enter a number: 3
Enter more data(y/n)? y
Enter a number: 65
Enter more data(y/n)? y
Enter a number: 12
Enter more data(y/n)? y
Enter a number: 32
Enter more data(y/n)? y
Enter a number: 7
Enter more data(y/n)? n
Sorted list is: [3, 7, 12, 32, 65]
Insertion Sort
It is one of the more obvious and natural ways to sort information. In this method we start with the second
element of the list and check where should it be in an list of first two elements only. If it is greater than the first
element then its OK. Otherwise, we interchange it with the first elements. In this way first two elements of the
list get sorted. Now we check the third element. If it is greater than the second element then it’s OK. Otherwise
we place it at the location where it should be to get first three elements sorted. Similarly, we check all the
remaining elements and finally we get the completely sorted list.
Script:
#create list
A=[]
more = 'y'
while more=='y' or more=='Y':
num=eval(input("Enter a number: "))
A.append(num)
more=input("Enter more data(y/n)? ")
#Now sort
N=len(A)
for i in range(1,N):
temp=A[i]
j=i-1
while A[j]>temp and j>=0:
A[j+1]=A[j];
j = j-1
A[j+1]=temp
#Now display
print("Sorted list is: ",A)
Sample Output:
Enter a number: 3
Enter more data(y/n)? y
Enter a number: 8
Enter more data(y/n)? y
Enter a number: 2
Enter more data(y/n)? y
Enter a number: 5
Enter more data(y/n)? y
Enter a number: 0
Enter more data(y/n)? y
Enter a number: 4
Enter more data(y/n)? n
Sorted list is: [0, 2, 3, 4, 5, 8]
Strings
A string is an immutable sequence of zero or more characters (letters, numbers, symbols) enclosed within
quotation marks (' ' or ""). In Python, strings are immutable sequences, meaning they are unchanging.
Following are examples of a few strings:
"Keyboard", "12.3", 'SCHOOL', '# * #', '' (Empty string)
Usually a string is assigned to a variable name. For example, the following statement:
name = 'Sunil'
assigns the string 'Sunil' to the variable name.
A string is an immutable sequence of characters, therefore, it behaves like a tuple of characters. Its characters
are indexed starting from 0 for the first character. Negative indices start from -1 for the last character.
So, the above string (name) can be logically viewed as:
0 1 2 3 4
name S u n i l
-5 -4 -3 -2 -1
Slicing: The concept of slicing of strings is exactly same as that for lists and tuples. Following are some
examples of slicing of strings:
Example 44:
address = '13/12, Raj Gadh, Delhi'
print(address[::])
print(address[1::])
print(address[:4:])
print(address[::2])
print(address[1::2])
print(address[2:7:])
print(address[-5:-2:1])
print(address[-5:-2:-1])
Output:
13/12, Raj Gadh, Delhi
3/12, Raj Gadh, Delhi
13/1
1/2 a ah eh
31,RjGd,Dli
/12,
Del
String methods: None of these methods changes the original string, because strings are immutable. In the
table given below, we are assuming address as the following string:
address = '13/12, Raj Gadh, Delhi'
str.index(x, start) Returns the index of element x in str, but starts the search
from index start.
Example: address.index('a',9) returns 12
hard work’
capitalize() str.capitalize() Capitalizes the first character of the str and converts the
remaining alphabets into small letters, and returns the
resultant string.
“book Shop”.capitalize() returns ‘Book Shop’
“12 books”.capitalize() returns ’12 books’
swapcase() str.swapcase() Converts the uppercase alphabets of str into lowercase
and lowercase alphabets into uppercase, and returns the
resultant string.
“book Shop”.swapcase() returns ‘BOOK sHOP’
“5th CM”.swapcase() returns '5TH cm'
endswith() s1.endswith(s2) Retruns True if s1 ends with s2.
"Mix and Fix".endswith('ix') returns True
"Mix and Fix".endswith('Fi') returns false
s1.endswith(s2,beg,end)
Retruns True if the slice s1[beg:end] ends with s2.
"Mix and Fix".endswith('Fi',3,10) returns True
"Mix and Fix".endswith('Fi',3,8) returns False
startswith() s1.startswith(s2) Retruns True if s1 starts with s2.
"Mix and Fix".startswith('Mi') returns True
"Mix and Fix".startswith('Fi') returns false
Following are some more examples of string methods. In these examples we assume that:
s1 = "Helllo", s2 = "Independence Day"
String comparison:
Relational operators (==, !=, <, <=, >, >=) can be used to compare two strings. Python compares strings
lexicographically, i.e., using ASCII values of characters. Strings are compared character by character using
their ASCII values. String comparison results in True or False as follows:
(i) If both the strings being compared have equal number of characters and all the corresponding
characters of the strings are same, then the strings are considered equal.
(ii) If the corresponding characters of the strings are not same and first mismatching character is found
at index i. Then
a. If s1[i]<s2[i], then the characters s1[i] and s2[i] are compared and the comparison is done
between first mismatching characters
Unpacking a string:
A string can be unpacked into its individual characters. These characters can be assigned to individual
variables, to a list, or a tuple. This is shown in the following example:
>>> str1="a bag"
>>> c1,c2,c3,c4,c5=str1
>>> lst = list(str1)
>>> tpl = tuple(str1)
>>> str1
'a bag'
>>> c1,c2,c3,c4,c5
('a', ' ', 'b', 'a', 'g')
>>> lst
['a', ' ', 'b', 'a', 'g']
>>> tpl
('a', ' ', 'b', 'a', 'g')
Import copy
P3=copy.copy(p1) //hard copy