0% found this document useful (0 votes)
183 views81 pages

Basics

Uploaded by

Soham
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
183 views81 pages

Basics

Uploaded by

Soham
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 81

XI/CS(083)/Programming in Python/2019/YK

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.

Suitable definition of data 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.

CS(083)-XI 1.1 © Yogesh Kumar – (965) 65891262


XI/CS(083)/Programming in Python/2019/YK

• 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):

CS(083)-XI 1.2 © Yogesh Kumar – (965) 65891262


XI/CS(083)/Programming in Python/2019/YK

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:

CS(083)-XI 1.3 © Yogesh Kumar – (965) 65891262


XI/CS(083)/Programming in Python/2019/YK

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:

CS(083)-XI 1.4 © Yogesh Kumar – (965) 65891262


XI/CS(083)/Programming in Python/2019/YK

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.

CS(083)-XI 1.5 © Yogesh Kumar – (965) 65891262


XI/CS(083)/Programming in Python/2019/YK

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("Peace and Harmony")


<class 'str'>

>>> type(True)
<class 'bool'>

CS(083)-XI 1.6 © Yogesh Kumar – (965) 65891262


XI/CS(083)/Programming in Python/2019/YK

>>> 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 -)

CS(083)-XI 1.7 © Yogesh Kumar – (965) 65891262


XI/CS(083)/Programming in Python/2019/YK

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

(4) 12 + (3 ** 4 – 6) / 2 (5) 12 *( 3 % 4)// 2 + 6 (6) 12 % 3**4//5 + 6


= 12 + (81 – 6) / 2 = 12*3//2 + 6 = 12%81//5 5 + 6
= 12 + 75 /2 = 36//2 + 6 = 12 // 5 + 6
= 12 + 37.5 = 18 + 6 =2+6
= 49.5 = 24 =8

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 “-“.

CS(083)-XI 1.8 © Yogesh Kumar – (965) 65891262


XI/CS(083)/Programming in Python/2019/YK

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.

Let us see it with the help of an example:

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:

CS(083)-XI 1.9 © Yogesh Kumar – (965) 65891262


XI/CS(083)/Programming in Python/2019/YK

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.

The assignment operator (=)


Values are assigned to variables using assignment operator ( =). For example, the statement a=10 assigns
value 10 to variable a. The general rule of assignment is:

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:

CS(083)-XI 1.10 © Yogesh Kumar – (965) 65891262


XI/CS(083)/Programming in Python/2019/YK

Price = 25 # Value 25 is assigned to the variable Price

Qty = 3 # Value 3 is assigned to the variable Qty

Amt1 = Price*Qty # Price*Qty is evaluated to 75 and the value


# 75 is assigned to the variable Amt1

Price = 25-3 # Value 22 (25-3) is assigned to Price


# So, now onwards value of Price is 22, and not 25

Qty = Qty*2 # Value 6 (Qty*2) is assigned to Qty


# So, now onwards value of Qty is 6, and not 3

Amt2 = Price*Qty # Value 132 (22*6) is assigned to the variable Amt2

Amt = Amt1+Amt2 # Value 207 (75+132) is assigned to the variable Amt

print(Amt) # Value 207 is displayed on the screen.

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:

CS(083)-XI 1.11 © Yogesh Kumar – (965) 65891262


XI/CS(083)/Programming in Python/2019/YK

(i) var1, var2, var3, . . ., varn = value1, value2, value3,. . ., valuen


This statement will declare variables var1, var2, . . ., varn with values value1,
value2,…, valuen respectively.
(ii) var1=var2=var3= . . .=varn = value1
This statement will declare variables var1, var2, . . ., varn , all with value value1

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:

['False', 'None', 'True', 'and', 'as', 'assert', 'break', 'class',


'continue', 'def', 'del', 'elif', 'else', 'except', 'finally',
'for', 'from', 'global', 'if', 'import', 'in', 'is', 'lambda',
'nonlocal', 'not', 'or', 'pass', 'raise', 'return', 'try', 'while',
'with', 'yield']

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.

Examples of some valid variable names are:


st_name, father_name, TotalValue, Age, Bal_Qty, A123, BillNo9

Following are examples of some invalid variable names:


Invalid Variable Name Reason
Roll Number Space is not allowed
9years Variable name cannot start with a digit
D.P.S. . is not allowed
No# Special characters are not allowed
while while is a keyword in Python, so it cannot be used as a variable name.

Some features of variable names in Python are:


(i) A variable name can be of any length.
(ii) Variable names are case-sensitive (e.g., Age and age are different variable names).

CS(083)-XI 1.12 © Yogesh Kumar – (965) 65891262


XI/CS(083)/Programming in Python/2019/YK

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.

Variable naming conventions


Although we are free to use any valid variable name, but if we follow some conventions in naming variables, it
will save us a lot of time and frustration. Some of these conventions are:
i) Use meaningful variable names of reasonable length. Examples of some meaningful variable
names are length, height, age, total, whereas a, b, c may not be meaningful
variable names.
ii) If a variable name contains more than one words, separate the words using underscore (because
space is not allowed in a variable name). For example Total_Amount, First_Name
iii) Don’t use l (as in luxury), O (as in Orange), o (as in orange), and I (as in India) as independent
variable names, because they may confuse you.
iv) Use only English alphabets (A-Z, a-z) in variable names. Don’t use additional UNICODE
characters.

The Style Guide for Python Code (https://www.python.org/dev/peps/pep-0008/#a-foolish-consistency-is-the-


hobgoblin-of-little-minds) recommends many more things about programming conventions besides variable
naming conventions.

Augmented Assignment Operators: An Augmented Assignment operator (or compound assignment


operator or Shorthand operator) is a combination of a binary operation and assignment. Different augmented
assignment operators available in Python are:

Operator Description Example


x=5;
y = 10;
+= Evaluates R-value and adds it to L-value. The x += 2*y;
(Add and Assign) final result is assigned to L-value. print("x=",x, "and y=",y)
gives the result: x= 25 and y= 10
x=5;
-= y = 10;
Evaluates R-value and subtracts it from L- x -= 2*y;
(Subtract and
value. The final result is assigned to L-value. print("x=",x, "and y=",y)
Assign)
gives the result: x= -15 and y= 10
x=5;
*= y = 10;
Evaluates R-value and multiplies it with L- x -= 2*y;
(Multiply and
value. The final result is assigned to L-value. print("x=",x, "and y=",y)
Assign)
gives the result: x= 100 and y= 10
x=5;
/= Evaluates R-value and divides the L-value y = 10;
(Divide and with R-value. The quotient is assigned to L- x /= y;
Assign Quotient) value. print("x=",x, "and y=",y)
gives the result: x= 0.5 and y= 10
%= x=5;
Evaluates R-value and divides the L-value x %= 4;
(Divide and
with R-value. The remainder is assigned to L- print("x="+x)
Assign
value. gives the result: x= 1
Remainder)
x=5;
//= Evaluates R-value and divides (floor division)
x //= 4;
(Floor division the L-value with R-value. The quotient is print("x="+x)
and Assign) assigned to L-value. gives the result: x= 1
x=5;
**=
Evaluates R-value and calculates (L-value)R- x %= 4;
(Exponent and value. The final result is assigned to L-value. print("x="+x)
Assign) gives the result: x= 1

CS(083)-XI 1.13 © Yogesh Kumar – (965) 65891262


XI/CS(083)/Programming in Python/2019/YK

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)

(Ans: 60 (Ans: 27.5 -642.5 (Ans: 1.7599999999999998 4.96


480) 62.5) 0.512)

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)

(4) p=10 (5) p=5%2 (6) p=21//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)

CS(083)-XI 1.14 © Yogesh Kumar – (965) 65891262


XI/CS(083)/Programming in Python/2019/YK

11. Find the output of each of the following code segments:


(1) x=3 (2) x=-2 (3) a=5
y=x+2 y=2 b=2*a
x+=y x+=y a+=a+b
print(x,y) y-=x b*=a+b
print(x,y) print(a,b)

(4) p=10 (5) p=5%2 (6) p=21//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)

12. Write Python expressions equivalent to the following arithmetic/algebraic expressions:


(1) 𝑎 + 𝑏 (2) 32 + 93 (3) 93
32 +
2 2 5

(4) 𝑎+2 (5) 6 ∗ 𝑠𝑢𝑚 (6) 1


√𝑎 + 8−6+ − √𝑣𝑎𝑟 𝑢𝑡 + 𝑎𝑡 2
𝑏 7 2
(u ,a, t are variables)
13. Write Python expressions to represent the following situations:
a. Add remainder of 6/5 to the product of 6 and 5.
b. Find the square root of the sum of 8 and 43.
c. Find the sum of the square roots of 8 and 43.
d. Find the integral part of the quotient when 63 is divided by 29.

Some examples of Python scripts for problem solving:


When we have to solve a problem using computers, we should always think of the required final
information/solution/result. Then we have to see what data is available with us to find the required solution.
After that we have to think of processing in terms of getting the desired information/result from the available
data.
Let us now see how we can practically use Python to solve some day to day problems.

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:

CS(083)-XI 1.15 © Yogesh Kumar – (965) 65891262


XI/CS(083)/Programming in Python/2019/YK

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

Following is the required Python script:


profit=10
population=500000
max_profit = profit*70/100*40/100*population
print("Maximum profit that can be earned = Rs",max_profit)

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

CS(083)-XI 1.16 © Yogesh Kumar – (965) 65891262


XI/CS(083)/Programming in Python/2019/YK

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

Following is the required Python script:


wt1 = 20
wt2 = 25
te = 60
agg_per = (wt1+wt2)/3+80/100*te
print("Aggregate Percentage = ",agg_per)

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)

and following is the sample output:

We observe the following problems with the above code:


CS(083)-XI 1.17 © Yogesh Kumar – (965) 65891262
XI/CS(083)/Programming in Python/2019/YK

(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:

CS(083)-XI 1.18 © Yogesh Kumar – (965) 65891262


XI/CS(083)/Programming in Python/2019/YK

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)

A sample output is:

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.

CS(083)-XI 1.19 © Yogesh Kumar – (965) 65891262


XI/CS(083)/Programming in Python/2019/YK

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:

# This is a single line comment


n=1
m=n+1 # value of n+1 is assigned to m
print(m)

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.

#Identify tokens in the script


x=28
y=20
if x>y:
z=x/y;
else: z=y/x;

CS(083)-XI 1.20 © Yogesh Kumar – (965) 65891262


XI/CS(083)/Programming in Python/2019/YK

print("x, y, z are:",x,y,z)

Token Category Token Category


x Identifier : Delimiter
y Identifier ( Delimiter
z Identifier } Delimiter
print identifier > Operator
if Keyword / Operator
else Keyword 28 Literal
= Delimiter / Operator 20 Literal
, Delimiter "x, y, z are: " literal

Problem solving (contd.):


Example 5:
Sonia has to travel a distance of 450km by car. From her experience she knows that she will be travelling at a
certain average speed. 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
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)

CS(083)-XI 1.21 © Yogesh Kumar – (965) 65891262


XI/CS(083)/Programming in Python/2019/YK

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 :

____________ Seconds = _____ hr ________ min _______ seconds.

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")

CS(083)-XI 1.22 © Yogesh Kumar – (965) 65891262


XI/CS(083)/Programming in Python/2019/YK

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

Here we have to check multiple alternate conditions to calculate the grade.

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.

marks = eval(input("Enter marks (out of 100): "));


if marks >= 28 and marks <= 32:
marks = 33;
print('Marks:',marks)

(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.

CS(083)-XI 1.23 © Yogesh Kumar – (965) 65891262


XI/CS(083)/Programming in Python/2019/YK

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.

marks = eval(input("Enter marks (out of 100): "));


if marks >= 33:
result=”Pass"
else:
result="Fail"
print(result)

(iii)
"if" expression-1 ":"
suite-1
"elif" expression-2 ":"
suite-2
"elif" expression-3 ":"
suite-3
.
.
"else" ":"
Last-suite

Execution: If expression-1 is true, then the suite-1 is executed, otherwise expression-2


is checked, if expression-2 is true then suit-2 is executed, otherwise
expression-3 is checked, if expression-3 is true then suite-3 is executed,
and so on. If none of the specified expressions is true, then last-suite is executed.

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

CS(083)-XI 1.24 © Yogesh Kumar – (965) 65891262


XI/CS(083)/Programming in Python/2019/YK

marks = eval(input("Enter marks: "))


if marks>=90:
grade = "A"
elif marks>=75:
grade = "B"
elif marks>=60:
grade = "C"
elif marks>=50:
grade = "D"
else:
grade = "E"

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:

Operator Description Example


(assuming x=6, y=2)
Negates a condition and returns true if the not(x > y) returns
not
condition is false, otherwise returns false. false
Combines two conditions and returns true if both (x >3 and y<2)
and
the conditions are true, otherwise returns false. returns false
Combines two conditions and returns true if at
(x>3 or y<2) returns
or least one of the conditions is true, otherwise
true
returns false

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

CS(083)-XI 1.25 © Yogesh Kumar – (965) 65891262


XI/CS(083)/Programming in Python/2019/YK

(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:

Let us see the following code part of a Python script:


if a>b:
print("a is greater than b")
print("a is not less than b")

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:

(i) Unnecessary indentation is taken as an error.

(ii) One statement linked with if.

(iii) Two statements linked with if.

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.

CS(083)-XI 1.26 © Yogesh Kumar – (965) 65891262


XI/CS(083)/Programming in Python/2019/YK

Problem solving (contd.):


Example 8:
To input a number and tell whether it is even or odd.
Solution:
Required information/result: A message telling whether the given number is even or odd.
Given data: No data is given
Processing: First we have to input the number from the user. Then we have to check whether the number is
even or odd. We know that a number is even if it is divisible by 2 (On dividing the number by 2 we should get 0
as the remainder). If the number is not even, then it is odd. Following is the Python script:

#To input a number and find whether it is even or odd


n = eval(input('Enter a number: '))

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

CS(083)-XI 1.27 © Yogesh Kumar – (965) 65891262


XI/CS(083)/Programming in Python/2019/YK

(ii) Input the value of time


(iii) If time > 10 then
Set rate=8
Otherwise
Set rate = 12
(iv) Calculate Simple Interest as Principal x Time x Rate /100
(v) Display the value of Simple Interest

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.

P = eval(input('Enter Principal: '))


T = eval(input('Enter time (in years): '))
if T > 10:
R = 8
else:
R = 12
SI = P*R*T/100
print ('Rate =',R,'% p.a.')
print ('Simple Interest = Rs',SI)

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

a = eval(input('Enter first number: '))


b = eval(input('Enter second number: '))
c = eval(input('Enter third number: '))

if a+b>c and b+c>a and a+c>b:


print ("These numbers form the three sides of a triangle")
else:
print ("These numbers do not form the three sides of a triangle")

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.

CS(083)-XI 1.28 © Yogesh Kumar – (965) 65891262


XI/CS(083)/Programming in Python/2019/YK

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) = 2rh + 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) = 4r2, Volume (Vol) = 4r3 /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) = 2rh + 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) = 4r2, Volume (Vol) = 4r3 /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): "))

CS(083)-XI 1.29 © Yogesh Kumar – (965) 65891262


XI/CS(083)/Programming in Python/2019/YK

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.

CS(083)-XI 1.30 © Yogesh Kumar – (965) 65891262


XI/CS(083)/Programming in Python/2019/YK

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..

Iteration (or Loop)


Iteration means to do something repeatedly. Iteration is also called loop. In programming there are many
situations when we have to repeat a set of statements. Every programming language provides some iterative or
looping statements which are used to automatically repeat a set of statements. There are 2 iterative statements
available in Python. These are:
• while
• for

(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

CS(083)-XI 1.31 © Yogesh Kumar – (965) 65891262


XI/CS(083)/Programming in Python/2019/YK

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.

Following are some more examples with while loop:

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)

CS(083)-XI 1.32 © Yogesh Kumar – (965) 65891262


XI/CS(083)/Programming in Python/2019/YK

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.

We have taken a variable I, in which we are storing successive natural numbers. i is


also being used to keep a count of how many times the loop has been executed. A
variable which is used to keep a count of how many times a particular process has been
performed, is called a counter.

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:

n = eval(input("Enter an integer: "))


n = int(n) #To extract the integer value of the number
n=abs(n) # to make the number positive, if it is negative
sum=0
while n != 0:
digit = n%10
sum += digit
n//=10
print (sum)

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.

(i) Input an integer (n)


(ii) prod=1
(iii) while n ≠ 0
a. digit = n%10
b. if (digit%2==0)
prod *= digit
c. n = n//10 (Take the quotient as the next integer)
(iv) 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:

CS(083)-XI 1.34 © Yogesh Kumar – (965) 65891262


XI/CS(083)/Programming in Python/2019/YK

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.

CS(083)-XI 1.35 © Yogesh Kumar – (965) 65891262


XI/CS(083)/Programming in Python/2019/YK

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:

CS(083)-XI 1.36 © Yogesh Kumar – (965) 65891262


XI/CS(083)/Programming in Python/2019/YK

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.

Following are some more examples with for loop:

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)

The script can also be written as follows:


# 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(1, n+1):
sum += 2*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)

CS(083)-XI 1.38 © Yogesh Kumar – (965) 65891262


XI/CS(083)/Programming in Python/2019/YK

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")

The output of this code is:


12 23 are integers
12.23, 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")

Can you write the above code:


(a) using for loop? If yes, then write it and execute it. If not, specify the reason.
(b) Without using else? If yes, then write it and execute it. If not, specify the reason.

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)

CS(083)-XI 1.39 © Yogesh Kumar – (965) 65891262


XI/CS(083)/Programming in Python/2019/YK

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

n = eval(input("Enter a number: "))


min=n
for i in range(1,10):
n=eval(input("Enter a number: "))
if n<min:
min=n
print(min,"is the smallest number entred")
if (int(min)==min):
min=abs(min) # to make the number positive, if it is negative
sum=0
while min != 0:
digit = min%10
sum += digit
min//=10
print ("Sum of the digits of smallest number",sum)
else: print("Smallest number is not 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:

CS(083)-XI 1.40 © Yogesh Kumar – (965) 65891262


XI/CS(083)/Programming in Python/2019/YK

Write script to input two integers and find their LCM.

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('---------------------------------')

CS(083)-XI 1.41 © Yogesh Kumar – (965) 65891262


XI/CS(083)/Programming in Python/2019/YK

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

print(count,"number(s) was/were prime")

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.

n=eval(input("How many terms? "))


n=abs(int(n))
x=eval(input("Enter the value of x: "))
sum=0
for i in range (1,n+1):
sum += pow(x,i)
print("Sum of first",n,"terms of the series =",sum)

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.

n=eval(input("How many terms? "))


n=abs(int(n))
x=eval(input("Enter the value of x: "))
sum=0
for i in range (1,n+1):
if i%2==1: sum += pow(x,i)

CS(083)-XI 1.42 © Yogesh Kumar – (965) 65891262


XI/CS(083)/Programming in Python/2019/YK

else: sum -= pow(x,i)


print("Sum of first",n,"terms of the series =",sum)

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.

n=eval(input("How many terms? "))


n=abs(int(n))
x=eval(input("Enter the value of x: "))
sum=1
for i in range (1,n):
sum += pow(x,i)/i
print("Sum of first",n,"terms of the series =",sum)

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.

n=eval(input("How many terms? "))


n=abs(int(n))
x=eval(input("Enter the value of x: "))
sum=1
factorial=1;
for i in range (1,n):
factorial*=i
sum += pow(x,i)/factorial
print("Sum of first",n,"terms of the series =",sum)

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! + . .

CS(083)-XI 1.43 © Yogesh Kumar – (965) 65891262


XI/CS(083)/Programming in Python/2019/YK

#where n and x have to be input from the user.

n=eval(input("How many terms? "))


n=abs(int(n))
x=eval(input("Enter the value of x: "))
sum=1
factorial=1;
for i in range (1,n):
factorial*=i
sum += pow((-x),i)/factorial
print("Sum of first",n,"terms of the series =",sum)

Unconditional exit from loop – The break statement


The break statement prematurely ends execution of the current while or for loop. It brings the
control to the statement immediately following the current control structure, skipping the optional
"else" clause if the loop has one.

Shift to the next iteration of the loop - The continue statement


The continue statement is used to skip the execution of the current iteration of a loop, and continue
with the next. continue does not terminate the loop, but continues with the next iteration of the
loop.

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:

CS(083)-XI 1.44 © Yogesh Kumar – (965) 65891262


XI/CS(083)/Programming in Python/2019/YK

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:
*

CS(083)-XI 1.45 © Yogesh Kumar – (965) 65891262


XI/CS(083)/Programming in Python/2019/YK

* *
* *
* *
*********
*******
*****
***
*
23. WAP to generate 2n+1 lines of the following pattern on the computer screen:
*
* *
* *
* *
* *
* *
*

CS(083)-XI 1.46 © Yogesh Kumar – (965) 65891262


XI/CS(083)/Programming in Python/2019/YK

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:

#To find the reciprocal of a number


p=4
n=input("Enter a number: ")
n=eval(n)
m=1/n
print("number=",n,", reciprocal=",m,sep='')
print("Done")

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

Sample output of the above code in different cases is shown below:

Case 1: (User enters a valid number)


Enter a number: -5
number=-5, reciprocal=-0.2
Done

Case 2: (User enters a pre defined variable name)


Enter a number: p
number=4, reciprocal=0.25

Case 3: (User enters 0)


Enter a number: 0
Traceback (most recent call last):
File "M:\CS-XI\Python Code\except0.py", line 6, in <module>
m=1/n
ZeroDivisionError: division by zero

Case 4: (User enters an undefined variable name)


Enter a number: a3
Traceback (most recent call last):
File "M:\CS-XI\Python Code\except0.py", line 5, in <module>
n=eval(n)
File "<string>", line 1, in <module>
NameError: name 'a3' is not defined

Case 5: (User enters an invalid string – neither a number, nor a variable)


Enter a number: 3a
Traceback (most recent call last):
File "M:\CS-XI\Python Code\except0.py", line 4, in <module>
n=eval(n)
File "<string>", line 1
3a
^
SyntaxError: unexpected EOF while parsing

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:

Exception When does it occur?


SyntaxError When the parser encounters a syntax error.

CS(083)-XI 1.47 © Yogesh Kumar – (965) 65891262


XI/CS(083)/Programming in Python/2019/YK

TypeError When an operation or function is applied to an object of inappropriate type.


ValueError When a built-in operation or function receives an argument that has the right type but an
inappropriate value.,
ZeroDivisionError When the second argument of a division or modulo operation is zero.
NameError When an undefined identifier is referenced.

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

CS(083)-XI 1.48 © Yogesh Kumar – (965) 65891262


XI/CS(083)/Programming in Python/2019/YK

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

CS(083)-XI 1.49 © Yogesh Kumar – (965) 65891262


XI/CS(083)/Programming in Python/2019/YK

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")
except SyntaxError: print("Syntax Error")
except NameError: print("Variable not defined")

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.

There are two solutions to this problem:


(i) Include while also in try statement.
(ii) In the case of incompatible data types, reset the value of x to any real (int or float) value.

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")

You can run this script and test it.

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

CS(083)-XI 1.50 © Yogesh Kumar – (965) 65891262


XI/CS(083)/Programming in Python/2019/YK

#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")

CS(083)-XI 1.51 © Yogesh Kumar – (965) 65891262


XI/CS(083)/Programming in Python/2019/YK

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 ---

pdb (Python DeBugger)


In software development, a bug is an error in a script, and debugging is the process of removing that error. This
error may be a syntax error, run-time error (exception), or logical error.

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.

CS(083)-XI 1.52 © Yogesh Kumar – (965) 65891262


XI/CS(083)/Programming in Python/2019/YK

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:

Here we observe that:


(i) After that IDLE displays the current module (script) name along with its path. (6) after the filename
indicates that the execution is paused at line number 6 of the code, i.e., 5 lines have been executed
properly, and the next line to be executed is line number 6.
(ii) This is followed by ->print(a, b, c) in the next line. This is the next line (line number 6) to
be executed.
(iii) Then there is the line (Pdb). This is the pdb prompt, which means that IDLE is now ready to
accept a pdb command from the user. At this prompt we can give any valid pdb command.

Some of the frequently used pdb commands are:


Pdb command Descriptions
n(ext) To execute the next statement of the script
p(rint) To print the values of specified variables/expressions

CS(083)-XI 1.53 © Yogesh Kumar – (965) 65891262


XI/CS(083)/Programming in Python/2019/YK

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

n2 = eval(input("Enter second number:"))


n1=n1//1 #to retain the integer part only
n2=n2//1 #to retain the integer part only
i=1
while ((n1*i)%n2 != 0):
i+=1

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)

When we execute the code, the output is as follows:

Now we start trace the script as shown in the following image:

CS(083)-XI 1.55 © Yogesh Kumar – (965) 65891262


XI/CS(083)/Programming in Python/2019/YK

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.

CS(083)-XI 1.56 © Yogesh Kumar – (965) 65891262


XI/CS(083)/Programming in Python/2019/YK

List, Tuple, and Dictionary


Classes, Objects, and Methods
Before we start with Lists, Tuples, and Dictionary, it is important to have an idea of classes, objects, and
methods. We know that computers are used for data processing. Whenever we say data, it means some facts
and figures. For example marks, names, prices, codes etc. Data always belongs to some objects. For example,
in an attendance register the data of students’ or employees’ attendance is stored. Here each student/employee
is an object. In a computerized billing system, data of each item is stored in a file. Here each item is an object.
There are also certain functions which can be performed on the objects. For example, a student can be given
admission, can be promoted to next class, or can be issued TC. So, admission, promotion, and issue_TC are
the functions which can be performed on students.
In general, when we do data processing, we have to handle multiple objects of the same type. For example, in
a school all the students are different objects of the same type. In a computerized billing system, all the items
are different objects of same type. In an object oriented programming language we use the term ‘class’ for a
type. So, we can say that all students are objects of the same class, and all items are the objects of the same
class. The functions of a class are called Methods. Methods of a class can be applied to any object of that
class. So, admission, promotion, and issue_TC are methods of class ‘student’, and hence, are applicable to all
the students.

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.

List, Tuple, and Dictionary are also in-built classes in Python.

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

color ‘Red’ ‘Green’ ‘Pink’ ‘Black’ ‘Orange’

-5 -4 -3 -2 -1

The list elements can be accessed:


(i) by using the list name and index numbers. For example:
Print (color[2]) displays 'Pink'.
Print (color[-2]) displays 'Black'.
(ii) by using for loop where the range is specified by the list name. For example:
for i in color:
print(i)
displays
'Red'
'Green'
'Pink'
'Black'
'Orange'

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()

Removes the last


element from the list,
and returns this
element..
clear() list.clear() Removes all color.clear()
elements from the
list.
index() list.index(x) Returns the index of color.index('Red')
element x in the list.

list.index(x, start) Returns the index of color.index('Red',2)


element x in the list,
but starts the search
from index start.

list.index(x,start,end) Returns the index of color.index('Red',2,5)


element x in the list,

CS(083)-XI 1.58 © Yogesh Kumar – (965) 65891262


XI/CS(083)/Programming in Python/2019/YK

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.

#Example: lists and corresponding methods - 1


color = ['red','black','blue','orange','pink']
print (color)
color.append('cyan')
print (color)
color.insert(4,'blue')
print (color)
print(color.remove('blue'))
print (color)
print(color.pop(2))
print (color)
color.pop()
print (color)
color.clear()
print (color)

#Example: lists and corresponding methods – 2


color = ['red','black','blue','orange','pink','blue','pink']
print (color)
blue = color.index('blue')
print("blue appears at index",blue,"in the list")
blue = color.index('blue',3)
print("blue appears at index",blue,"in the list")
blue = color.index('blue',1,4)
print("blue appears at index",blue,"in the list")
c = color.count("pink")
print("pink appears",c,"times in the list")
color.reverse()
print(color)
clr=['a','b']
color.sort(reverse=True)
print(color)

Output:

CS(083)-XI 1.59 © Yogesh Kumar – (965) 65891262


XI/CS(083)/Programming in Python/2019/YK

Operators defined for lists:


Operator Description Example
+ Concatenates two lists [1,2]+["aman","syed","davis"] returns
[1,2,"aman","syed","davis"]
* Repeats list elements [1,2]*4 returns [1,2,1,2,1,2,1,2]
in Checks membership 1 in [1,2] returns True
del Deletes specified list element, slice, or del color[0]
complete list del color[2:5]
del color

Built-in functions for lists:


For the examples in this table we assume the following list:
color = ['red','black','blue','orange','pink','blue','pink']
Function Description Example
len() Returns the length of the specified list. Length of a len(color) returns 7
list means the total number of elements in the list.
max() Returns the largest element of the list list. max(color) returns ‘red’
max([12,3,14,10]) returns 14
max(['12','3','14','10']) returns ‘3’
max([12,'12']) results in TypeError
min() Returns the smallest element of the list. min(color) returns ‘red’
min([12,3,14,10]) returns 3
min(['3','10','14']) returns ‘10’
min([12,'12']) results in TypeError

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:

Problem solving using lists:


Example 40:
Problem:
50 students have to take an exam in an examination hall. Roll numbers of these students are from 91041 to
91090. The invigilator in the examination hall has to maintain a list of roll numbers of all the students present in
the hall at any moment. 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:

CS(083)-XI 1.60 © Yogesh Kumar – (965) 65891262


XI/CS(083)/Programming in Python/2019/YK

a. Only valid roll numbers should be allowed


b. No duplicate roll numbers should be allowed
(ii) Delete the roll number of any student who leaves the hall
(iii) Display the number of students present in the hall at any moment
(iv) Display the smallest and the largest roll number present in the hall
(v) Display a list of absentees’ roll numbers
(vi) Display a sorted list of roll numbers present

Our task is to develop a Python script to do the desired task.

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:

CS(083)-XI 1.61 © Yogesh Kumar – (965) 65891262


XI/CS(083)/Programming in Python/2019/YK

print("Roll number not present")


elif option==3:
print(len(roll),"students are present")
elif option==4:
if len(roll)==0:
print('No student present')
else:
small = min(roll)
large = max(roll)
print("Smallest roll number present is:",small)
print("Largest roll number present is:",large)
elif option==5:
if len(roll) == last-first+1:
print("All students are present")
else:
print("The following roll numbers are absent: ")
for r in range(first,last+1):
if not(r in roll):
print(r, end=" ")
elif option == 6:
if len(roll)==0:
print("No student is present")
else:
roll.sort()
print("The following roll numbers are present: ")
for r in roll:
print(r, end=" ")

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

Book 1021 ‘Programming in Python’ ‘Hard Bound 2018

-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:

CS(083)-XI 1.62 © Yogesh Kumar – (965) 65891262


XI/CS(083)/Programming in Python/2019/YK

Method Syntax Description Example


index() tuple.index(x) Returns the index of Book.index('Hard Bound')
element x in the
tuple.

tuple.index(x, start) Returns the index of Book.index(2018,2)


element x in the
tuple, but starts the
search from index
start.

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.

Operators defined for tuples:


Operator Description Example
+ Concatenates two tuples and returns the (1,2)+("aman","syed","davis") returns
resultant tuple (1,2,"aman","syed","davis")
* Repeats tuple elements and returns the resultant (1,2)*4 returns (1,2,1,2,1,2,1,2)
tuple
in Checks membership 1 in (1,2) returns True
del Deletes the specified tuple del Book

Built-in functions for tuples:


For the examples in this table we assume the following tuple:
pixel = (56,72,'red',215,65,65)
Function Description Example
len() Returns the length of the specified tuple. Length of len(pixel) returns 6
a tuple means the total number of elements in the
tuple.
max() Returns the largest element of the list list. max(pixel) results in TypeError
max((12,3,14,10)) returns 14
max(('12','3','14','10')) returns ‘3’
min() Returns the smallest element of the list. min(pixel) results in TypeError
min((12,3,14,10)) returns 3
min(('3','10','14')) returns ‘10’

Packing and Unpacking:


A set of comma separated values automatically becomes a tuple. This concept is called packing. For example:

Values of tuple elements can be assigned to individual variables in sequence. This concept is called unpacking.
For example:

Unpacking is applicable on slices also. Example:


CS(083)-XI 1.63 © Yogesh Kumar – (965) 65891262
XI/CS(083)/Programming in Python/2019/YK

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:

Nesting of lists and tuples:


We can include one or more lists in a tuple and vice-versa. We can also include tuples in tuples, and lists in
lists. Examples:
>>> list1=[1,2,3]
>>> list2=['a','b']
>>> tuple1=(list1, list2, 10, 20, ('p','q','r'))
In this example two lists and one tuple are nested in a tuple. The two nested lists are list1 and list2, and the
nested tuple is the unnamed tuple (‘p’,’q’,’r’). These are nested in the tuple tuple1. Tuple1 can logically be
viewed as:

tuple1[0] [1,2,3]

tuple1[1] ['a','b']

tuple1[2] 10

tuple1[3] 20

tuple1[4] ('p','q','r')

Accessing and updating elements of nested lists and tuples:


Assume that a list/tuple (say, A) of m elements contains a list/tuple (say, B) of n elements. Let B is ith element
of A. Therefore, A[i] refers to B, and to access jth element of B, we have to use the expression A[i][j]. A[i][j] can
also be understood as jth element of ith element of A.
If we make any updation in B (the nested list), the corresponding change is reflected in A (the container
list/tuple). Similarly if we make change in a nested list through the container list/tuple.
These concepts are illustrated through the following script and the corresponding output:

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

CS(083)-XI 1.64 © Yogesh Kumar – (965) 65891262


XI/CS(083)/Programming in Python/2019/YK

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'))

Following are a few more examples of nesting:


(i) Lists in in tuple:
>>> list1=[1,2,3]
>>> list2=['a','b']
>>> tuple1=(list1, list2, 10, 20, ['p','q','r'])
>>> tuple1
([1, 2, 3], ['a', 'b'], 10, 20, ['p', 'q', 'r'])
>>> tuple1[0][1]
2
>>> tuple1[3][0]
Traceback (most recent call last):
File "<pyshell#53>", line 1, in <module>
tuple1[3][0]
TypeError: 'int' object is not subscriptable
>>> tuple1[4][0]
'p'

(ii) Tuples in list:


>>> t1=1,2,3
>>> t2=('Book',12,'Reference')
>>> list1=[1,t1,'School','Location',t2,'End']
>>> t1
(1, 2, 3)
>>> t2
('Book', 12, 'Reference')
>>> list1
[1, (1, 2, 3), 'School', 'Location', ('Book', 12, 'Reference'), 'End']
(iii) Lists in List
>>> list1=[1,2,3]
>>> list2=['a','b']
>>> list3=[list1,list2,"two lists"]
>>> list3
[[1, 2, 3], ['a', 'b'], 'two lists']
(iv) Tuples in tuple
>>> t1=1,2,3
>>> t2=('Book',12,'Reference')
>>> t3=t1,"and",t2
>>> t3
((1, 2, 3), 'and', ('Book', 12, 'Reference'))

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.

CS(083)-XI 1.65 © Yogesh Kumar – (965) 65891262


XI/CS(083)/Programming in Python/2019/YK

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.

Problem solving using tuples:


Example 42: 150 students have to take an exam in an examination center. The center has arranged 3 rooms,
each for 50 students. Roll numbers of these students are from 91041 to 91190. The center is planning to have a
computer on the gate. When a student enters the centre, the officer at the gate will check his/her admit card
and tell the room number in which the student has to sit. The officer will also make an entry of the roll number in
the computer. Also, if a student leaves the center before the exam is over, his/her entry is to be deleted from
the computer. The aim is to achieve the following:
(i) Students’ time should not be wasted in finding the room number in which they have to sit. This will
also reduce the chaos and confusions.
(ii) Students with duplicate or invalid roll numbers should not get entry to the center.
(iii) The lists of present and absent students can be made at any moment.

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

Our task is to develop the desired script.

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]

CS(083)-XI 1.66 © Yogesh Kumar – (965) 65891262


XI/CS(083)/Programming in Python/2019/YK

Else display “Roll number not present message”


(v) To count the number of students present:
Display len(room0)+len(room1)+len(room2)
(vi) To display the absentees’ list:
For r in range 91041 to 91190
Calculate roomNo as (r-91041)//50
If (r is not in center[roomNo]
Display r
(vii) To display the list of students present:
room0.sort(), room1.sort(), room2.sort()
For room in range(0,3)
print (“Present in Room Number”,room)
for r in center[room]
Display r

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:

CS(083)-XI 1.67 © Yogesh Kumar – (965) 65891262


XI/CS(083)/Programming in Python/2019/YK

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:

‘Arun’ ‘Khalid’ ‘Xaviour’


marks
29 32 30

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.

The dictionary elements can be accessed:


(iii) by using the list name and key. For example:
Print (marks['Arun']) displays 29.
(iv) by using for loop where the range is specified by the dictionary name. For example:
for k,v in marks.items():
print(k,'-',v)
displays
Arun - 29
Khalid - 32
Xaviour – 30

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'}

Method Syntax Description Example


clear() D.clear() Removes all items from arabic.clear()
dictionary D
copy() D.copy Creates a copy of Arabic1 = arabic.copy()
dictionary D
fromkeys() D.fromkeys(seq) Creates a new dictionary a='slow','fast','close'
with keys from seq and b = dict.fromkeys(a)
values None print(b)
prints
{'slow': None, 'fast': None,
'close': None}

D.fromkey(seq, Creates a new dictionary c=dict.fromkeys(a,'-')


value) with keys from seq and print(c)
values set to value prints

CS(083)-XI 1.68 © Yogesh Kumar – (965) 65891262


XI/CS(083)/Programming in Python/2019/YK

{'slow': '-', 'fast': '-',


'close': '-'}

get() D.get(k) Returns D[k] if k in print(Arabic.get('who')) prints None


dictionary D, otherwise
returns None.

Returns D[k] f k in
print(Arabic.get('who', 'Not
D.get(k,nf) dictionary D, otherwise
Found')) prints 'Not Found'
returns nf.

items() D.items() Returns a collection of print(Arabic.items())


(key, value) pairs of all the
elements of dictionary D.
keys() D.keys() Returns a collection of print(D.keys())
keys of dictionary D.
pop() D.pop(k) Removes D[k] from print(arabic.pop('here')) removes
dictionary D and returns arabic['here'] from arabic and
the corresponding value. If prints ‘minni’.
the key k is not found,
KeyError is raised. print(D.pop(‘who')) raises KeyError

Removes D[k] from


dictionary D and returns print(arabic.pop('egg','-' ))
the corresponding value. prints '-'.
D.pop(k,nf) Returns nf, if the key k is
not found.
popitem() D.popitem() Removes and returns the print(arabic.popitem()) removes last
last key:value pair of item 'go':'roa' and prints ('go',
dictionary D as a tuple 'roa')
(key, value). Raises
KeyError if D is empty.
setdefault() D.setdefault(k) Similar to get(), but will set arabic.setdefault('this':'hada')
D[key]=None if key is not
already in D

D.setdefault(k, Similar to get(), but will set


value) D[key]=value if key is not
already in D
update() D.update(D1) Adds dictionary D1’s key- arabic.update(new_words)
values pairs to
dictionary D

values() D.values() Returns a collection of arabic.values()


dictionary D’s values.

Operators defined for Dictionary:


Operator Description Example
in Checks membership of a key in a dictionary 'here' in D returns True
'minni' in D returns False
del Deletes element with specified key, or entire dictionary del arabic['here’]
if no key is specified. del arabic
Raises KeyError if specified key is not present in the
dictionary.

Built-in functions for lists:


Function Description Example

CS(083)-XI 1.69 © Yogesh Kumar – (965) 65891262


XI/CS(083)/Programming in Python/2019/YK

len() Returns the length of the specified dictionary. len(arabic) returns 5

Problem solving using Dictionary:


Example 43:
To improve the vocabulary of students, an Arabic teaching institute is planning to introduce a computerized
Arabic-English-Arabic dictionary with the following features:
(i) To display the Arabic translation of an English word
(ii) To display the English translation of an Arabic word.
(iii) If an English word is not found in the dictionary, it should be placed in a list so that the teachers can
later update the dictionary.
(iv) Point number (iii) for Arabic words.
(v) To display a list of English words not found in the dictionary.
(vi) Point number (v) for Arabic words.
(vii) To update the dictionary. Only an authorized teacher should be able to update the dictionary.
Therefore, update dictionary must be preceded by a password check.
Initially the dictionaries will contain the following enteries:
English What Where Here There Why
Arabic Shuno Vain Minni Hinni Lesh

Our task is to develop a Python script to do the desired task.

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

CS(083)-XI 1.70 © Yogesh Kumar – (965) 65891262


XI/CS(083)/Programming in Python/2019/YK

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")

CS(083)-XI 1.71 © Yogesh Kumar – (965) 65891262


XI/CS(083)/Programming in Python/2019/YK

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

First pass of the comparisons goes as follows:


(i)

(ii)

(iii)

(iv)

(v)

CS(083)-XI 1.72 © Yogesh Kumar – (965) 65891262


XI/CS(083)/Programming in Python/2019/YK

(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:

So, now we have one less element to sort.

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:

CS(083)-XI 1.73 © Yogesh Kumar – (965) 65891262


XI/CS(083)/Programming in Python/2019/YK

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.

Pseudocode Bubble sort – to sort a list A in ascending order


N = len(A)
for i in range(1,N) #for N-1 passes
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

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.

CS(083)-XI 1.74 © Yogesh Kumar – (965) 65891262


XI/CS(083)/Programming in Python/2019/YK

Now, we get the sorted list as follows:


0 1 2 3 4 5 6
A
0 4 5 7 8 8 9

The above procedure can also be shown as:

Pseudocode Insertion sort – to sort a list A in ascending order


N = len(A)
for i in range(1,N) #to check element A[1] to A[N-1]
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

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)

CS(083)-XI 1.75 © Yogesh Kumar – (965) 65891262


XI/CS(083)/Programming in Python/2019/YK

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]

CS(083)-XI 1.76 © Yogesh Kumar – (965) 65891262


XI/CS(083)/Programming in Python/2019/YK

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

The list elements can be accessed:


(i) by using the string name and index numbers. For example:
Print (name[2]) displays 'n'.
Print (name[-2]) displays 'i'.
(ii) by using for loop where the range is specified by the string name. For example:
for i in name:
print(i)
displays
S
u
n
i
l

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'

Method Syntax Description and Example


index() str.index(x) Returns the index of first occurance of element x in the
string str.
Example: address.index('a') returns 8

CS(083)-XI 1.77 © Yogesh Kumar – (965) 65891262


XI/CS(083)/Programming in Python/2019/YK

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

str.index(x,start,end) Returns the index of element x in str, but search is


performed in the range str[start] to str[end-1]
Example: address.index('a',9,13) returns 12
count() str.count(x) Returns the number of times element x appears in str.
Example: address.count('1') returns 2.
isalnum() str.isalnum() Returns True if str consists of only alphabets and/or digits.
Example: "12Books".isalnum() returns True
"12 Books".isalnum() returns False
isalpha() str.isalpha() Returns True if str consists of alphabets only.
Example: "ab".isalpha() returns True
"a b".isalpha() returns False
isdigit() str.isdigit() Returns True if all characters in str are digits.
“45”.isdigit() returns True
“45.0”.isdigit() returns False
isidentifier() str.isidentifier() Returns True if str is a valid identifier in Python.
Examples: “SI”.isidentifier() returns True
“S.I.”.isidentifier() returns False
islower() str.islower() Returns True if all the alphabets in the str are in
lowercase.
Example: address.islower() returns False
“12 books”.islower() returns True
isnumeric() str.isnumeric() Returns True if all the characters of str are digits.
Example: "12".isnumeric() returns True
"12.0".isnumeric() returns False
isspace() str.isspace() Returns True if str consists of only whitespace characters
(space, ‘\t’ and ‘\n’).
Example: address.isspace() returns False
“ \t\n “.isspace() returns True
istitle() str.istitle() Returns True if str is in title case (first alphabet of each
word is in upper case)
"Ram Nagar".istitle() returns True
"Ram nagar".istitle() returns False
isupper() str.isupper() Returns True if all the alphabets in str are in uppercase.
Example: address.isupper() returns False
“INDIA 1947”.isupper() returns True
join() str.join(sequence) Returns a string formed by joining elements of the
sequence. str is inserted as the separator of elements in
the resultant string.
Example: " ".join("two eggs") returns 't w o e g g
s'

",".join("One Note") returns 'O,n,e, ,N,o,t,e'

" ".join(("two","good","friends")) returns 'two


good friends'
"-*-".join(("two","good","friends")) returns 'two-
*-good-*-friends'
split() str.split() Splits str into substrings at each space and returns the list
of substrings so obtained..
address.split() returns ['13/12,', 'Raj', 'Gadh,',
'Delhi']
str1.split(str2)
Splits str1 into substrings taking str2 as the delimiter and
returns the list of substrings so obtained..
address.split(',') returns ['13/12', ' Raj Gadh',
' Delhi']
replace() str1.replace(str2,str3) Replaces each occurance of str2 with str3 in string str1
and returns the resultant string.
“my hard work”.replace(“my”,”our”) returns ‘our

CS(083)-XI 1.78 © Yogesh Kumar – (965) 65891262


XI/CS(083)/Programming in Python/2019/YK

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

Retruns True if the slice s1[beg:end] starts with s2.


"Mix and Fix".startswith('and',4,10) returns
True
"Mix and Fix".startswith('Fi',2,8) returns
False
find() s1.find(s2) Returns the index of the first occurrence of s2 in s1.
“Mix and Fix”.find(‘ix’) returns 1
s1.find(s2,beg,end)
Returns the index of first occurrence of s2 in slice
s1[beg:end]
"Mix and Fix".find('ix',3,12) returns 9
rfind() s1.rfind(s2) Returns the index of the last occurrence of s2 in s1.
“Mix and Fix”.rfind(‘ix’) returns 9

Returns the index of last occurrence of s2 in slice


s1[beg:end]
"Mix and Fix".rfind('ix',3,12) returns 9

Following are some more examples of string methods. In these examples we assume that:
s1 = "Helllo", s2 = "Independence Day"

Statement Value / Output Statement Value / Output


s1.isalpha() True s2.isalpha() -> False False
s1.isalnum() True s2.isalnum() -> False False
s1.islower() False s2.isupper() -> False False
s1.istitle() True s2.istitle() -> True True
s1.endswith('lo') True s2.startswith('in') -> False False
s1.find('lo') 3 s2.find('nde') -> 1 1
s2.rfind('nde') -> 1 1
s2.find('nde',3) -> 6 6
s2.find('nde',-3) -> -1 -1

Operators defined for strings:


Operator Description Example
+ Concatenates two strings "aman"+"syed" returns 'amansyed'
* Repeats string 'Hi'*4 returns 'HiHiHiHi'
in Checks membership of a substring in a string 'Raj' in address returns True
not in
del Deletes specified string (variable) del address
Relational operators (==, !=, <, <=, >, >=) to compare two strings.

CS(083)-XI 1.79 © Yogesh Kumar – (965) 65891262


XI/CS(083)/Programming in Python/2019/YK

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

Built-in functions for strings:


For the examples in this table we assume the following list:
address = '13/12, Raj Gadh, Delhi'
Function Description Example
len() Returns the length of the specified list. Length of a len(color) returns 7
list means the total number of elements in the list.
max() Returns the largest element of the list list. max(color) returns ‘red’
max([12,3,14,10]) returns 14
max(['12','3','14','10']) returns ‘3’
max([12,'12']) results in TypeError
min() Returns the smallest element of the list. min(color) returns ‘red’
min([12,3,14,10]) returns 3
min(['3','10','14']) returns ‘10’
min([12,'12']) results in TypeError

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')

Like lists and tuples, slices of strings can also be unpacked.

CS(083)-XI 1.80 © Yogesh Kumar – (965) 65891262


XI/CS(083)/Programming in Python/2019/YK

P2=p1 #soft copy – same address - alias

Import copy
P3=copy.copy(p1) //hard copy

Alias vs Copy vs deep copy

CS(083)-XI 1.81 © Yogesh Kumar – (965) 65891262

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy