Documente Academic
Documente Profesional
Documente Cultură
Multiline/Continuation Statements
In the above example, backslash (\) character has been added at the end of each statement,
which allows the text to split into multiple lines and hence the output is obtained as shown.
3
Clarity and Simplicity of Expression
Expression in a program is a sequence of operators and operands to do an arithmetic or logical
computation such as comparing two values, defining a variable or an object and performing
arithmetic calculations using one or more variables.
If any expression becomes very big or very complex, we must write it in two steps rather than
in a single step. This will make the expression simple and more accurate. Simple expressions
are also easily readable and can be understood by others without making any extra effort.
For example,
X = (A + B) / (A – B) – (U + VY) / (X + Y)
We can simplify it and write as:
X1 = (A + B) / (A – B)
X2 = (U + VY) / (X + Y)
X = X1 – X2
• Use library functions to make programs more powerful.
For example,
To find the value of x4
Instead of evaluating it using the expression as x*x*x*x
We can use formula available in Python as power(x,4)
SOLVED QUESTIONS
1. What are comments in Python? Is there any difference between multiline strings and multiline comments?
Ans. A comment starts with a # symbol and ends with the end of line. Comments are non-executable statements
which are ignored by the Python Interpreter. Multiline strings can be used as multiline comments, but
these are not actually comments.
2. What is the output of—
33 == 33.0
Ans. True shall be returned as the output as comparison operator evaluates true and false. And in Python we
need not specify whether the number is int or float.
3. What will be the output of the following code?
x = 2
y = 10
x *= y * x + 1
Ans. 42; evaluated as x *= y * x + 1 means x = x * (y * x + 1)
Computer Science with Python—XI
4. Which of the following mathematical symbols are part of the Python character set?
+, -, ^, /, ;, !, ≠, →, μ, ≤, =, <=
Ans. The symbols +, –, ^, =, <= and / form part of mathematical symbols in the Python character set.
UNSOLVED QUESTIONS
1. What is a character set in Python? What are different categories of character set in Python? Give two
examples of each category.
2. Differentiate between multiline strings and multiline comments.
3. What does the continuation character (\) signify?
4. How does simplification of statements in Python increase the overall program efficiency?
4
Computational
Thinking
(New Chapter)
INTRODUCTION
What is Computational
Computers can be used to help us solve problems. However, Thinking?
before a problem can be tackled, the problem itself and the
ways in which it could be solved need to be understood.
When we write a program, we are writing a set of instructions
to solve a problem involving data processing. These instructions
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 for 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.
But every day, in all aspects of our lives, we perform computational thinking. Think of the
following actions and decisions that go into them:
• You want to make yourself a cup of tea or coffee.
• You want to buy a car.
• You want to change career.
• You want to move to another city.
• You want to buy a house.
• You want to write a book.
• You want to create an app.
All the above situations require thought processing for finding the best solution and, thus,
computational thinking becomes a crucial aspect.
WHAT IS COMPUTATIONAL THINKING?
Computational Thinking allows us to take a complex problem, understand what the problem is,
and develop possible solutions. We can then present these solutions in a way that a computer,
a human, or both, can understand.
The process of planning and reaching the goals involves computational thinking of some kind.
Computational thinking involves taking that complex problem and breaking it down into a series
of small, more manageable problems (decomposition). Each of these smaller problems can
then be looked at individually, considering how similar problems have been solved previously
(pattern recognition) and focusing only on the important details, while ignoring irrelevant
information (abstraction). Next, simple steps or rules to solve each of the smaller problems
can be designed (algorithms).
Let us discuss the components of Computational Thinking in detail.
COMPUTATIONAL THINKING
Decomposition Abstraction
Computer Science with Python—XI
6
Decomposition
Decomposition is the process of breaking down a complex
Problem Data Set
problem or system into smaller, more easily solved parts.
These smaller problems are solved one after another until
the bigger complex problem is solved.
This stage involves breaking down the problem into smaller
task 0 task 1 task 2 task 3
components so that they can be tackled easily. The more
Fig. 2: Decomposition Process
you can break down a problem, the easier it is to solve.
Some real-life examples of decomposition process are:
When we taste an unfamiliar dish and identify several ingredients based on the flavour, we
are decomposing that dish into its individual ingredients.
When we give someone directions to our house, we are decomposing the process of getting
from one place to another (e.g., city, state, etc.).
When we break a course project into several steps, we are decomposing the task into smaller,
more manageable sub-tasks.
In mathematics, we can decompose a number such as 256.37 as follows:
2*102+5*101+6*100+3*10–1+7*10–2
Let’s look at a more specific example, the equation to work out the roots of a quadratic equation.
–b ± b2 – 4ac
x=
2a
On first look it might appear a little scary, but if we decompose it, we should stand a better
chance of solving it:
1. b2 2. 4ac
3. b2 – 4ac 4. b2 – 4ac
5. -b + b2 – 4ac 6. 2a
–b + b2 – 4ac -b - b2 - 4ac
7. x = 8. repeat for
2a 2a
By noting the steps down to solve a problem, we can often recognise patterns, and by giving a
list of steps, we are one step closer to creating an algorithm.
This stage also allows you to develop a better understanding of the problem you face by
identifying all the components in detail.
Pattern Recognition
Pattern Recognition is the next process in succession that helps
Computational Thinking
7
What are patterns?
Imagine that we want to draw a series of cats.
All cats share common characteristics. Among other things they all have eyes, tails and fur.
They also like to eat fish and make meowing sounds.
Because we know that all cats have eyes, tails and fur, we can make a good attempt at drawing
a cat, simply by including these common characteristics.
In computational thinking, these characteristics are known as patterns. Once we know how to
describe one cat, we can describe others simply by following this pattern. The only things
that are different are the specifics:
• one cat may have green eyes, a long tail and black fur
• another cat may have yellow eyes, a short tail and striped fur
Long Green Ginger
Fluffy Tail Yellow Eyes Black Fur
Stumpy Orange Tabby
• If we want to draw a number of cats, finding a pattern to describe cats in general, for example,
they all have eyes, tails and fur, makes this task quicker and easier.
• We know that all cats follow this pattern, so we don’t have to stop each time we start to
draw a new cat to work this out. From the patterns we know cats follow, we can quickly
draw several cats.
Drivers look for patterns in traffic to decide whether and when to switch lanes.
People look for patterns in stock prices to decide when to buy and sell.
Scientists look for patterns in data to derive theories and Models.
We look for patterns and learn from them to avoid repeating the same mistake.
Patterns are shared characteristics that occur in each individual problem. What similarities
do you observe? Finding these similarities in small decomposed problems can help us solve
complex problems more efficiently.
8
Abstraction
“Abstraction” refers to focusing on the important information only, ignoring
irrelevant detail. To reach a solution, we need to ignore unnecessary
characteristics in order to focus on those that we do. It helps to identify
specific similarities and differences among similar problems to work
towards a solution.
So what is this important information that we need to focus on? In
abstraction, the focus is mainly on general characteristics that are Fig. 4: Abstraction
common to each element, instead of specific details. Common examples
of abstraction process can be:
A world map is an abstraction of the earth in terms of longitude and latitude, helping us
describe the location and geography of a place.
A sign of an aisle in a store—e.g., Walmart—is an abstraction of the items available in that
aisle.
When we write a book report, we summarize and discuss only the theme or key aspects of
the book, it is abstraction.
Once you have the general characteristics, you can create a “model” of the problem; a model
being the general idea of the problem we are trying to solve.
Once we have a model, we can design an algorithm.
Algorithm Writing
You’ve broken down the big problem into smaller, easily manageable
problems. You’ve identified similarities between these problems.
You’ve focused on relevant details and left behind anything
irrelevant.
Now it’s time to develop step-by-step instructions to solve each of the
smaller problems, or the rules to follow when solving the problem.
These simple steps or rules are used to program a computer to help Fig. 5: Algorithm Writing
solve a complex problem in the best possible way. They are also called
“algorithms”.
Definition: An algorithm is a plan, a set of step-by-step instructions used to solve a problem.
Writing an algorithm requires extensive planning for it to work correctly. The solution your
computer offers is as good as the algorithm you write. If the algorithm is not good, then your
solution will not be good either.
Computational thinking is extremely important not only while working with computers but
in other applications also. Computational thinking even works well in the classroom teaching
as well. The implementation of computational thinking in a classroom can be compared with
various important subjects.
9
Computational Thinking Concept Subject Area Application
Break down a problem into parts or Literature: Break down the analysis of a poem into analysis of
steps metre, rhyme, imagery, structure, tone, diction and meaning.
Recognize and find patterns or Economics: Find cycle patterns in the rise and fall in the
trends country's economy.
Develop instructions to solve a Culinary Arts: Write a recipe for others to use.
problem or steps for a task
Mathematics: Figure out the rules for factoring 2nd-order
Generalize patterns and trends into polynomials
rules, principles, or insights Chemistry: Determine the rules for chemical bonding and
interactions.
In the left column, notice that all of the skills are computational thinking skills or concepts.
However, in the right column, those skills are being used in literature, economics, the culinary
arts, and music. The basic skills of computer scientists and the way they think are computational
thinking. The area in which you apply computational thinking can be any subject area or topic,
even the subject area or topic you teach. These ways of thinking can be used anytime you want
to develop a process or algorithm to solve a problem.
MEMORY BYTES
Computational Thinking allows us to take a complex problem, understand what the problem is, and develop
possible solutions.
Decomposition, pattern matching, abstraction and algorithms are the four pillars of Computational Thinking.
Decomposition is the process of breaking down a complex problem or system into smaller, more manageable
parts.
Pattern matching refers to looking for similarities among and within problems.
Algorithm refers to the rules to follow to solve a problem.
Computational Thinking enables us to work out exactly what to tell the computer to do.
SOLVED QUESTIONS
1. What are the four main parts of computational thinking?
Ans. • Decomposition
• Pattern Recognition
• Pattern generalization and abstraction
• Algorithm design
Computer Science with Python—XI
10
3. Can you come up with an algorithm to make a cup of tea?
Ans. (i) put water into kettle (ii) turn kettle on
(iii) get a cup and saucer (iv) put tea bag into cup
(v) when water gets boiled, add to cup (vi) stir with spoon
(vii) remove tea bag (viii) add milk, if needed
4. Define the term computational thinking.
Ans. Computational Thinking allows us to take a complex problem, understand what the problem is, and
develop possible solutions. We can then present these solutions in a way that a computer, a human, or
both, can understand.
5. What is decomposition?
Ans. Decomposition is one of the four cornerstones of Computer Science. It involves breaking down a complex
problem or system into smaller parts that are more manageable and easy to understand. The smaller
parts can then be examined and solved, or designed individually, as they are simpler to work with.
6. Why is decomposition important?
Ans. If a problem is not decomposed, it is much harder to solve. Dealing with many different stages all at once
is much more difficult than breaking down a problem into a number of smaller problems and solving each
problem one at a time. Breaking down the problem into smaller parts means that each smaller problem
can be examined in more detail.
7. Why do we need pattern recognition?
Ans. Pattern recognition is one of the four cornerstones of CT. It involves finding the similarities or patterns
among small, decomposed problems that can help us solve more complex problems efficiently.
8. Why is abstraction important?
Ans. Abstraction allows us to create a general idea of what the problem is and how to solve it. The process
instructs us to remove all specific details, and any patterns that will not help us solve our problem. This
helps us form our idea of the problem. This idea is known as a ‘model’.
9. Explain the characteristics of computational thinking.
Ans. The salient features of computational thinking are:
• Formulating problems in a way that enables us to use a computer and other tools to help solve them.
• Logically organizing and analyzing data.
• Representing data through abstractions such as models and simulations.
• Automating solutions through algorithmic thinking (a series of ordered steps).
• Identifying, analyzing, and implementing possible solutions with the goal of achieving the most
efficient and effective combination of steps and resources.
• Generalizing and transferring this problem-solving process to a wide variety of problems.
UNSOLVED QUESTIONS
1. What are some computational thinking skills?
2. How are computational thinking skills applied in finding solutions that can be interpreted into software
applications?
3. What is an example of computational thinking?
4. How can I use computational thinking for problem-solving?
Computational Thinking
INTRODUCTION
As our programs become larger and more complex,
the need to organize our code becomes greater. A
large and complex program should be divided into
files/functions that perform a specific task. As we
write more and more functions in a program, we
should consider organizing the functions by storing
them in modules.
A module is simply a file that contains Python code.
When we break a program into modules, each module
should contain functions that perform related tasks.
For example, suppose we are writing an accounting
system. We would store all the account receivable
functions in their own module, all the account payable
functions in their own module, and all the payroll
Fig. 1: Python Libraries
functions in their own module. This approach, which
is called modularization, makes the program easier to understand, test and maintain.
Even tiny real-world applications contain thousands of lines of code. In fact, applications that
contain millions of lines of code are somewhat common. Imagine trying to work with a file large
enough to contain millions of lines of code—you’d never find anything. In short, we need some
method to organize the code into small pieces that are easier to manage, much like the examples
in this book. The Python solution is to place the code in separate code groupings called modules.
Commonly-used modules that contain source code for generic needs are called libraries.
Therefore, when we speak about working with libraries in Python, we are, in fact, working with
modules that are created inside the package(s) or say, library. Thus, a Python program comprises
three main components:
Library or Package
Module
Functions/Sub-modules
Relation between a module, package and
library in Python: Package
MODULE IN PYTHON
Modules are used to categorize Python code into smaller parts. A module is simply a Python
file where statements, classes, objects, functions, constants and variables are defined. Grouping
similar code into a single file makes it easy to access. For example, if the content of a book is not
indexed or categorized into individual chapters, the book will become boring and complicated.
Hence, dividing the book into chapters makes it easy to understand. In the same way, Python
modules are files which have a similar code. Thus, a module simplifies a Python code where
classes, variables and functions are defined.
CTM: A module is a file consisting of Python code that can define functions, classes and variables
related to a particular task. A module allows us to organize our code by grouping related code, which
makes the code easier to understand and use.
A module name is the file name with the .py extension. When we have a file named empty.py,
empty is the module name. The __name__ is a variable that holds the name of the module being
referenced.
The current module, the module being executed (also called the main module), has a special
name: ‘__main__’. With this name, it can be referenced from the Python code.
A module’s file name should end in .py. If the module’s file name does not end with .py as the
extension, we will not be able to import it into other programs. A module’s name cannot be
the same as a Python keyword. Naming a module as ‘for’, ‘while’, etc., would result in an error.
13
IMPORTING PYTHON MODULES
The most common way to create a module is to define a separate file containing the code we
want to group separately from the rest of the application. For example, we might want to create
a print routine that an application uses in a number of places. The print routine isn’t designed
to work on its own but is part of the application as a whole. We want to separate it because the
application uses it at numerous places and we could potentially use the same code in another
application. The ability to reuse code ranks high on the list of reasons to create modules.
Modules also make it easier to reuse the same code in more than one program. If we have
written a set of functions that is needed in several different programs, we can place those
functions in a module. Then, we can import the module in each program that needs to call one
of the functions. There are different ways by which we can import a module. We can use any
Python source file as a module by executing an import statement.
Standard library of Python is extended as module(s) to a programmer. Definitions from the
module can be used within the code of a program. To use these modules in a program, a
programmer needs to import the module into other modules or into the main module using
any of the following three constructs:
(i) “import” statement can be used to import a module. It is the simplest and most
common way to use modules in our code. It gives access to all attributes (like
variables, constants, etc.) and methods present in the module.
import <module_name>
In case of accessing specific modules, it can be modified as:
import module1[, module2 [, ...moduleN]
To access particular methods from any module, the statement shall be:
<module_name>.<function_name>
(ii) Python’s from statement lets us import specific attributes or individual objects
from a module into the current (calling) module or namespace.
from <module_name> import <function_name(s)>
Or
from <module_name> import function_name1
[,...function_name2[,...function_nameN]]
To use/access/invoke a function, we will specify the module name and name of the function
Computer Science with Python—XI
14
Let’s look at a few simple examples.
Example 1: Let’s say we have a Python file called area.py which has a few functions in it for
calculating the area of a circle, square and rectangle. Use those functions again in some other
programs.
Fig. 3(a): Area Module
We have created the “area” module (Fig. 3(a)) which is a user-created module, not from the
Python library.
Note: Always remember that the module area.py should be in the same default root folder
where math.py also resides.
However, this program uses the standard math module for using pi() function that belongs to it.
Now, we shall call these modules in another program (Fig. 3(b)) named “math1.py”.
Fig. 3(c): Output of Module ‘math1.py’
15
When we will run this program, the sub-modules, namely circle_area(), square_area() and
rectangle_area(), shall be called from module area using the statements:
area.circle_area()
area.square_area()
area.rectangle_area()
They shall generate the output as shown in Fig. 3(c).
Retrieving objects from a Module
There is another function dir() which, when applied to a module, gives you the names of all
that is defined inside the module.
Example 2: To retrieve the listing of all the objects present inside the user-created module
“area”.
As shown above, in order to obtain information about a module (area in this case), the usage
of dir() function, with name of the module to be retrieved as the parameter, shall result in
the display of all its respective objects, viz. name of the sub-modules, variables and constants
(if any) present in the module.
Example 3: Modification of Example 1—to calculate the area of the circle only. This can be done
using the “from” statement along with the name of the sub-module to be called specifically.
16
from...import statement is used to import a particular attribute (sub-routine) from a
module. In case you do not want the whole of the module to be imported, then you can use
from...? import statement as we have done in the above example. In order to calculate area of
the circle, circle_area() function is being called from module “area”.
CTM: For modules having a large number of functions, it is recommended to use from instead of import.
Now let’s see the third format of importing a module using from...import*.
The import* statement allows a user to import everything from the file or module. This
construct will import all Python definitions into the namespace of another module.
However, this construct is not recommended to be used much as it may result in namespace
pollution. We may have several objects of the same name and their definitions can be
overridden.
Example 4: Modification of Example 3—to import all the sub-modules from module “area”.
import * gives
access to all functions
in area module
You can use all the
functions in area
module directly
Thus, from all of the above examples, we have observed that import statement in Python can
be represented in any of the following for importing a module in some other program:
(a) import test: imports the module “test” and creates a reference to that module in the current
Introduction to Python Modules
calling program (or namespace). After executing this statement, you can use test.name
to refer to the objects defined in module ‘test’.
(b) import test1, test2, test3: This statement shall import three modules, namely test1,
test2 and test3 in current namespace. As a result, all the definitions of these modules
are available and can be used as:
<module_name>.<name>
sub-module/any object
17
(c) from test import * : When you use import * statement, it shall import all the sub-modules
or objects defined in the module ‘test’ into the current namespace. So, after executing this
statement, you are required to simply give the name of the object to be referred to, defined
in the module test. In other words, <name> would now be used as name only, without
specifying module’s name (i.e., test.name is not required to be given). If name was already
defined, it is replaced by the new version, the one imported from the module.
(d) from test import t1,t2,t3: This
statement shall import the module test Learning Tip: Whenever we are using a module
and create references in the current in our program, for that module, its compiled file
will be generated and stored in the hard disk
namespace to the given objects. In permanently.
other words, you can now use t1,
t2, and t3 in your program without
specifying their module’s name along with them.
MODULE ALIASING
You can create an alias when you import a module by using the as keyword. Thus, Python
provides the salient feature of renaming a module at the time of import.
Syntax:
import <module-name> as <alias_name>
Practical Implementation–1
Develop a program calculator for performing addition and multiplication operations using
modules and importing these modules in the program.
Computer Science with Python—XI
18
Practical Implementation–2
Modify the above program by using alias name for the module “test”.
As is evident from the same output obtained from the above two programs, we can say that
alias name works well with Python modules.
Here, test is the original module name and m is the alias name. We can easily access members
of the main module by using the alias name m.
MEMBER ALIASING
Like module aliasing, member aliasing is also supported and implemented in Python modules.
Practical Implementation–3
Modify the previous program for implementing aliasing with the members of the module.
Once we have defined an alias name, we should use alias name only and use of original module
name should be avoided as it may create ambiguity and may result in an unexpected output or
sometimes even an error, as shown below.
Introduction to Python Modules
19
Practical Implementation–4
Write a program in Python that calculates the following:
• Area of a circle
• Circumference of a circle
• Area of a rectangle
• Perimeter of a rectangle
Create respective modules for each of the operations and call them separately using a
menu-driven program.
There are obviously two categories of calculations required in this program: those related
to circles, and those related to rectangles. You could write all circle-related functions in one
module and all rectangle-related functions in another module.
Circle Module
Rectangle Module
Computer Science with Python—XI
20
21
Introduction to Python Modules
LOCATING MODULES
When you import a module, the Python interpreter searches for the module in the following
sequence:
• The current directory.
• If the module isn’t found, Python then searches each directory in the shell variable
PYTHONPATH.
• If all else fails, Python checks the default path, which is the location where Python has been
installed on your computer system.
Thus, PYTHONPATH is the variable that tells the interpreter where to locate the module files
imported into a program. Hence, it must include the Python source library directory and the
directories containing Python source code. You can manually set PYTHONPATH, but usually the
Python installer will preset it.
CTM: Modules are the most important building blocks for any application in Python and work on divide
and conquer approach.
22
Let us discuss built-in modules in detail.
BUILT-IN FUNCTIONS
Built-in functions are the predefined functions that are already available in Python. Functions
provide efficiency and structure to a programming language. Python has many useful built-in
functions to make programming easier, faster, and more powerful. These are always available
in the standard library and for using them, we don’t have to import any module (file).
Let us discuss math and datetime modules which are one of the most commonly used built-in
modules in Python.
To access/use any of the function present in the imported module, you have to specify the
name of the module followed by the name of the function, separated by a dot (also known as
a period). This format is called dot notation.
For example,
result = math.sqrt(64) #Gives output as 8 which gets
stored in variable 'result'
sqrt() is one of the functions that belongs to math module. This function accepts an argument
and returns the square root of the argument. Thus, the above statement calls the sqrt() passing
64 as an argument and returns the square root of the number passed as the argument, i.e., 8
which is then assigned to the variable ‘result’.
math Module
Let us understand a few more functions from the math module.
Module
pie
math sqrt function
sin function
Interpreter cos function
...
import math
Source code
For example,
>>> print("math.ceil(3.4):", math.ceil(3.4))
Output: math.ceil(3.4): 4
floor(x): Returns the largest integer that is less than or equal to x.
>>> math.floor(-45.17)
–46
>>> math.floor(100.12)
100
>>> math.floor(100.72)
100 23
pow(x,y): It returns the value of xy, where x and y are numeric expressions.
>>> print("math.pow(3, 3):", math.pow(3, 3))
math.pow(3, 3): 27.0
>>> math.pow(100, –2)
0.0001
>>> math.pow(2, 4)
16.0
>>> math.pow(3, 0)
1.0
sqrt(x): Returns the square root of x.
>>> print("math.sqrt(65):", math.sqrt(65))
math.sqrt(65): 8.06225774829855
>>> math.sqrt(100)
10.0
>>> math.sqrt(7)
2.6457513110645907
Alternatively,
>>> print("math.sqrt(65):", round(math.sqrt(65),2))
math.sqrt(65): 8.06
fabs(x): Returns the absolute value of x, represented as–
math.fabs(x)
where, x can be any numeric value.
For example,
>>>print(math.fabs(500.23))
500.23
>>>print(math.fabs(-200))
200
>>>print(math.fabs(-15.6343))
15.6343
help function
If you forget how to use a standard function, Python's library utilities can help. In this case,
Python's help() library functions is extremely relevant. It is used to know the purpose of a
function and how it is used.
For example,
>>>import math
>>>print(help(math.cos))
Help on built-in function cos in module math:
cos(...)
Computer Science with Python—XI
None
cos(x)
Return the cosine of x (measured in radians).
random module (Generating Random Numbers)
The programming concepts we have learnt so far involved situations where we were aware of
the definite output to be obtained when a particular task was to be executed, which is described
as a deterministic approach. But there are certain situations/applications that involve games or
simulations which work on a non-deterministic approach. In these types of situations, random
numbers are extensively used such as:
1. Pseudorandom numbers on lottery scratch cards.
24
2. Recaptcha (like in login forms) uses a random number generator to define which image is
to be shown to the user.
3. Computer games involving throwing of a dice, picking a number, or flipping a coin.
4. Shuffling deck of playing cards, etc.
In Python, random numbers are not enabled implicitly; therefore, we need to invoke random
module explicitly or to invoke random code library in order to generate random numbers.
• import statement is the first statement to be given in a program for generating random numbers:
import random
The various functions associated with this module are explained as follows:
randrange(): This method generates an integer between its lower and upper
argument. By default, the lower argument is 0.
For example,
ran_number = random.randrange(30)
Alternatively,
This line of code shall generate random numbers from 0 to 29. Let us see another example:
Example 1: To select a random subject from a list of subjects.
random()
This function generates a random number from 0 to 1 such as 0.5643888123456754. This
function can be used to generate pseudorandom floating point values. It takes no parameters
and returns values uniformly distributed between 0 and 1 (including 0, but excluding 1). Let
us take some examples to gain better clarity about this function:
Example 2:
Introduction to Python Modules
25
POINT TO REMEMBER
This is to be kept in mind that every time we are executing this program, it shall display a different value
as random() method always picks up any value from the given range.
As is evident from the above statements, each time random() generates a different number, the
random() function can also be written with the following alternative approach:
Example 3: Program to calculate the sum of the digits of a random three-digit number.
Explanation:
The random() function generates a random fractional number between 0 and 1. When a random
number generated using random() gets multiplied by 900, a random number is obtained
between 0 and 899. When you add 100 to it, you get a number between 100 and 999.
Then, the fractional part gets discarded using int() and gets printed on the shell window. In
the next statement, the first digit (the most significant) of the number is extracted by dividing
it with 100 (a = n//100).
The last digit of the number is extracted by dividing it by 10. The remaining number then gets
divided by 10 and the quotient is again mod with 10 to get ten’s digit and the remainder is again
mod with 10 and this process gets repeated till all the digits are extracted and finally added together.
In the last statement, the sum of digits is calculated and displayed on the screen.
randint()
This function accepts two parameters, a and b, as the lowest and highest number; returns
a number ‘N’ in the inclusive range [a,b], which signifies a<=N<=b, where the endpoints are
included in the range. This function generates a random integer number between two given
numbers. This function is best suited for guessing number applications. The syntax is:
random.randint(a,b)
Here, a is the lower bound and b is the upper bound. In case you input a number N, then the
result generated will be a <= N <= b. Please make sure that the upper limit is included in
Computer Science with Python—XI
randint() function.
Example 4: To generate a number between 0 and 9.
26
Example 5: Write a function that fills a list with numbers. (Using randint())
statistics module
The statistics module implements many common statistical formulas for efficient calculations
using Python’s various numerical types (int, float, Decimal, and Fraction).
It provides functions for calculating mathematical statistics of numeric (Real-valued)
data. Before using the functions of this module, it is required to be imported first using the
statement—import statistics.
The following popular statistical functions are defined in this module:
mean(): The mean() method calculates the arithmetic mean of the numbers in a list.
For example,
>>> import statistics
>>> statistics.mean([4,6,7,8,10,45])
Introduction to Python Modules
13.333333333333334
median(): The median() method returns the middle value of numeric data in a list.
This function finds the centre value, and if the data set has an even number of values,
it averages the two middle items.
For example,
>>> import statistics
>>> statistics.median([1,2,3,8,9])
3
>>> statistics.median([1,2,3,7,8,9])
5.0 27
MEMORY BYTES
A module is a file containing Python code. A package, however, is like a directory that holds sub-packages and
modules.
A package must hold the file __init__.py. This does not apply to modules.
To import everything from a module, we use the wildcard *. But this does not work with packages.
A module is a separately saved unit whose functionality can be reused at will.
A Python module can contain objects like docstrings, variables, constants, classes, objects, statements, functions
and has the .py extension.
A Python module can be imported in a program using import statement.
There are two forms of import statements:
• import <modulename>
• from <module> import <object>
The random module of Python provides random number generation functionality.
A math module of Python provides math functionality.
By default, Python names the segment with top-level statements (main program) as _main_.
Python resolves the scope of a name using LEGB rule, i.e., it checks environments in the order: Local, Enclosing,
Global and Built-in.
SOLVED QUESTIONS
1. Python has certain functions that you can readily use without having to write any special code. What
types of functions are these?
Ans. The predefined functions that are always available for use are known as Python’s built-in functions.
Examples of some built-in functions are: len(), type(), int(), input(), etc.
2. What is a Python module? What is its significance?
Ans. A “module” is a chunk of Python code that exists in its own (.py) file and is intended to be used by Python
code outside itself. Modules allow one to bundle together code in a form in which it can be easily used
later. Modules can be “imported” in other programs so that the functions and other definitions in
imported modules become available to code that imports them.
3. What are docstrings? How are they useful?
Ans. A docstring is just a regular Python triple-quoted string that is the first thing in a function body/a module/
a class. When executing a function body (or a module/class), the docstring doesn’t do anything like
comment, but Python stores it as part of the function documentation. This documentation can later be
displayed using the help() function.
So, even though docstrings appear like comments (no execution), they are different from comments.
4. What happens when Python encounters an import statement in a program? What would happen if there
Computer Science with Python—XI
is one more import statement for the same module, already imported in the same program?
Ans. When Python encounters an import statement, it does the following:
(i) Code of the imported module is interpreted and executed.
(ii) Defined functions and variables created in the module are now available to the program that imported
the module.
(iii) For imported module, a new namespace is set up with the same name as that of the module.
Any duplicate import statement for the same module in the same program is ignored by Python.
5. What is an argument? Give an example.
Ans. An argument is data passed to a function through function call statement. For example, in the statement
print(math.sqrt(25)), the integer 25 is an argument.
28
6. What is the utility of built-in function help()?
Ans. Python’s built-in function help() is very useful. When it is provided with a program name or a module
name or a function name as an argument, it displays the documentation of the argument as help. It also
displays the docstring within its passed-argument’s definition.
For example,
>>>help(math)
will display the documentation related to module math.
It can even take function name as argument,
For example,
>>>help(math.sqrt())
The above code will list the documentation of math.sqrt() function only.
7. Write a function that:
(i) Asks the user to input a diameter of a sphere (centimetres, inches, etc.)
(ii) Sets a variable called radius to one-half of that number.
(iii) Calculates the volume of a sphere using this radius and the formula:
Volume = 4/3 pi*r*3
(iv) Prints a statement estimating that this is the volume of the sphere; include the appropriate unit
information in litres or quarts. Note that there are 1000 cubic cm in a litre and 57.75 cubic inches in
a quart.
(v) Returns this same amount as the output of the function.
Ans. def compute_volume():
import math
diameter = float(input("Please enter the diameter in inches:"))
radius = diameter/2
Volume_in_cubic_inches = ((4/3) * math.pi) * (radius ** 3))
Volume_in_quarts = Volume_in_cubic_inches/57.75
print("The sphere contains", Volume_in_quarts, 'quarts')
return(Volume_in_quarts)
8. What will be the output of the following code?
def interest (prnc, time=2, rate = 0.10):
return (prnc * time * rate)
print(interest(6100, 1))
print(interest(5000, rate =0.05))
print(interest(5000, 3, 0.12))
print(interest(time = 4, prnc = 5000))
Ans. 610.0
500.0
1800.0
2000.0
9. What is the utility of Python standard library’s math module and random module?
Ans. (i) Math module: The math module is used for math-related functions that work with all number types
Introduction to Python Modules
29
11. Observe the following code and answer the question based on it.
# the math_operation module
def add (a,b):
return a + b
def substract (a,b):
return a – b
Fill in the blanks for the following code:
1. math_operation
# get the name of the module.
2. print (_____________)
# output: math_operation
# Add 1 and 2
3. print (_____________(1, 2))
# output 3
Ans. 1. input 2. math_operation__name__
3. math_operation.add
12. Consider the code given in Q.6 and on the basis of it, complete the code given below:
# import the subtract function
# from the math_operation module
1. __________________
# subtract 1 from 2
2. print(_______(2, 1))
# output : 1
# Import everything from math_operations
3. _______________________
print(subtract (2, 1))
# output: 1
print(add (1, 1))
# output : 2
Ans. 1. from math_operation import subtract 2. subtract
3. from math_operation import *
13. Why is the use of import all statements not recommended?
Ans. While using import all statements, you can overwrite functions and this can be dangerous, especially if
you don’t maintain that module.
14. What is a Python module?
Ans. A module is a script in Python that defines import statements, functions, classes, and variables. It also
holds executable Python code. ZIP files and DLL files can be modules too. The module holds its name as
a string that is in a global variable.
Computer Science with Python—XI
30
17. What is the output of the following piece of code?
#mod1
def change(a):
b=[x*2 for x in a]
print(b)
#mod2
def change(a):
b=[x*x for x in a]
print(b)
from mod1 import change
from mod2 import change
#main
s=[1,2,3]
change(s)
Note: Both the modules mod1 and mod2 are placed in the same program.
(a) [2,4,6] (b) [1,4,9]
(c) [2,4,6], [1,4,9] (d) There is a name clash
Ans. (d)
Explanation: A name clash is when two different entities with the same identifier become part of the
same scope. Since both the modules have the same function name, there is a name clash.
18. What is the output of the following piece of code?
from math import factorial
print(math.factorial(5))
(a) 120
(b) Nothing is printed
(c) Error, method factorial doesn’t exist in math module
(d) Error, the statement should be: print(factorial(5))
Ans. (d)
Explanation: In the “from-import” form of import, the imported identifiers (in this case factorial()) aren’t
specified along with the module name.
19. Which of the following is not an advantage of using modules?
(a) Provides a means of reusing program code
(b) Provides a means of dividing up tasks
(c) Provides a means of reducing the size of the program
(d) Provides a means of testing individual parts of the program
Ans. (c)
Explanation: The total size of the program remains the same regardless of whether modules are used or
not. Modules simply divide the program.
20. Consider the set of height measurements (in feet) of students in a class:
Student Height
Introduction to Python Modules
Rishabh 5.9
Anna 5.5
Rinku 6.1
Tapish 6.0
Ajay 7.2
Write a Python program to calculate the average height of students in the class and median value using
Statistics module.
31
Ans. # To calculate the average height of the students in a class
import statistics heights = [5.9, 5.5, 6.1, 6.0, 7.2] # the height data
avg = statistics.mean(heights)
print("Average height in the class:",avg)
median_value = statistics.median(heights)
print("Median value for heights:",median_value)
Output:
Average height in the class: 6.14
Median value for heights: 6.0
21. Write a Python program to guess a number between 1 and 9.
Ans. import random
target_num, guess_num = random.randint(1, 10), 0
while target_num != guess_num:
guess_num = int(input("Guess a number between 1 and 10 \
until you get it right:"))
print(target_num)
target_num = random.randint(1, 10)
print('Well guessed!')
Explanation: In the above code, the user is asked to guess a number, which is then fetched and gets
stored inside the variable “guess_num”. If the user guesses wrong then the prompt appears again and
the user continues to input another number repetitively until the guess is correct. On successful guess,
the user will get a “Well guessed!” message, and the program will exit.
UNSOLVED QUESTIONS
1. What is a Python library? Explain with example.
2. Write a module to input total number of days and find the total number of months and remaining days
after months, and display it in another program.
3. What is a module? What is the file extension of a Python module?
4. How do you reuse the functions defined in a module in your program?
5. In how many ways can you import objects from a module?
6. How are the following two statements different from each other?
(i) Import math
(ii) From math import *
7. What is the utility of math module?
8. How does Python resolve the scope of a name or identifier?
9. A program having multiple functions is considered better designed than a program without any
functions. Why?
10. Write a module called calculate_area() that takes base and height as an input argument and returns an
Computer Science with Python—XI
32
13. Why is from import * statement not recommended for importing Python modules in an external program?
14. Write a function to calculate volume of a box with appropriate default values for its parameters. Your
function should have the following input parameters:
(a) Length of box (b) Width of box
(c) Height of box
Test it by writing complete program to invoke it.
15. Consider the temperature given below for the month of June in North India. Calculate the average
temperature and median value. This temperature gets dipped with a variation of 20° C in the month of
December. Write a Python program to calculate the changed median value and average temperature.
Location Temperature (in °C)
Delhi 41
Shimla 32
Chandigarh 43
Rohtak 40
Srinagar 28
SriGanganagar 45
16. Consider the amount of donations received by a charitable organisation given as under:
donations = [100, 60, 70, 900, 100, 200, 500, 500, 503, 600, 1000, 1200]
Now write a Python program to calculate the average amount obtained and median of the above data.
17. Write a Python program to generate a random number between 0 and 9.
33
Structured Query
Language (SQL)
(Chapter 11)
SORTING IN SQL—ORDER BY
The SQL ORDER BY clause is used to sort the data in ascending or descending order, based
on one or more columns. The ORDER BY keyword is used to sort the result-set by one or
more fields in a table. This clause sorts the records in the ascending order (ASC) by default.
Therefore, in order to sort the records in descending order, DESC keyword is to be used. Sorting
using ORDER BY clause can be done on multiple columns, separated by comma.
Syntax for ORDER BY clause:
SELECT <column-list> FROM <table_name> [WHERE <condition>]
ORDER BY <column_name> [ASC|DESC];
Here, WHERE clause is optional. Rollno Name Marks
For example, 8. Akshay Dureja 90
• To display the roll number, name and marks of students 3. Ankit Sharma 76
on the basis of their marks in the ascending order. 2. Deep Singh 98
mysql> SELECT Rollno, Name, Marks FROM student 6. Diksha Sharma 80
ORDER BY Name; 7. Gurpreet Kaur NULL
• To display the roll number, name and marks of all the 5. Payal Goel 82
students in the descending order of their marks and 10. Prateek Mittal 75
ascending order of their names. 4. Radhika Gupta 78
mysql> SELECT Rollno, Name, Marks FROM student 1. Raj Kumar 93
ORDER BY Marks DESC, Name; 9. Shreya Anand 70
Sorting on Column Alias
If a column alias is defined for a column, it can be used for displaying rows in ascending or
descending order using ORDER BY clause.
For example, SELECT Rollno, Name, Marks AS Marks_obtained
FROM student
Alias name
ORDER BY Marks_obtained;
AGGREGATE FUNCTIONS
Till now we have studied about single row functions which work on a single value. SQL also
provides multiple row functions which work on multiple values. So, we can apply SELECT
query on a group of records rather than the entire table. Therefore, these functions are called
aggregate functions or group functions.
Generally, the following aggregate functions are applied on groups as described below:
Table 1: Aggregate Functions in SQL
S.No. Function Description/Purpose
1. MAX() Returns the maximum/highest value among the values in the given column/expression.
2. MIN() Returns the minimum/lowest value among the values in the given column/expression.
3. SUM() Returns the sum of the values under the specified column/expression.
4. AVG() Returns the average of the values under the specified column/expression.
5. COUNT() Returns the total number of values/records under the specified column/expression.
Consider a table Employee (Employee code, employee name, job, salary and city) with the
following structure:
Ecode Name Salary Job City
E1 Ritu Jain 5000 Manager Delhi
E2 Vikas Verma 4500 Executive Jaipur
E3 Rajat Chaudhary 6000 Clerk Kanpur
E4 Leena Arora 7200 Manager Bangalore
E5 Shikha Sharma 8000 Accountant Kanpur
1. MAX()
MAX() function is used to find the highest value among the given set of values of any column
or expression based on column. MAX() takes one argument which can be either a column
name or any valid expression involving a particular column from the table.
For example,
mysql> Select MAX(Salary) from EMPLOYEE;
Output:
+----------------+
| MAX(Salary)|
+----------------+
| 8000 |
+----------------+
This command on execution shall return the maximum value from the specified column
(Salary) of the table Employee, which is 8000.
4. AVG()
AVG() function is used to find the average value of any column or expression based on a
column. Like sum(), it also accepts the entire range of values of a particular column to
be taken average of, or even a valid expression based on this column name. Like SUM()
function, the AVG() function always takes argument of integer type only. Average of String
and Date type data is not defined.
For example,
mysql> Select AVG(Salary) from EMPLOYEE;
+----------------+
| AVG(Salary) |
+----------------+
| 6140 |
+----------------+
This command on execution shall return the average of the salaries of all the employees from
the specified column (Salary) of the table Employee, which is 6140.
5. COUNT()
COUNT() function is used to count the number of values in a column. COUNT() takes one
argument which can be any column name, or an expression based on a column, or an asterisk (*).
When the argument is a column name or an expression based on column, COUNT() returns
the number of non-NULL values in that column. If the argument is asterisk (*), then COUNT()
Computer Science with Python—XI
counts the total number of records/rows satisfying the condition, if any, in the table.
For example,
1. mysql> Select COUNT(*) from EMPLOYEE;
+----------------+
| COUNT(*) |
+----------------+
| 5 |
+----------------+
This command on execution shall return the total number of records in the table Employee,
which is 5.
36
2. mysql> Select COUNT(DISTINCT City) from EMPLOYEE;
+-------------------------------+
| COUNT(DISTINCT City) |
+-------------------------------+
| 4 |
+-------------------------------+
This command on execution shall return the total number of records on the basis of city with
no duplicate values, i.e., Kanpur is counted only once; the second occurrence is ignored by
mySQL because of the DISTINCT clause. Thus, the output will be 4 instead of 5.
37
SOLVED QUESTIONS
1. Consider the following two tables: STATIONERY and CONSUMER.
Table: Stationery
S_ID StationeryName Company Price StockDate
DP01 Dot Pen ABC 10 2011-03-31
PL02 Pencil XYZ 6 2010-01-01
ER05 Eraser XYZ 7 2010-02-14
PL01 Pencil CAM 5 2009-01-09
GP02 Gel Pen ABC 15 2009-03-19
Note:
• S_ID is the Primary Key.
Table: Consumer
C_ID ConsumerName Address P_ID
01 Good Learner Delhi PL01
06 Write Well Mumbai GP02
12 Topper Delhi DP01
15 Write & Draw Delhi PL02
16 Motivation Bengaluru PL01
Note:
• C_ID is the Primary Key.
• P_ID is the Foreign Key referencing S_ID of Stationery table.
Write SQL statements for the queries (i) to (iii) and output for (iv) and (v):
(i) To display details of all the Stationery items in the Stationery table in descending order of StockDate.
(ii) To display details of that Stationery item whose Company is XYZ and price is below 10.
(iii) To increase the price of all the Stationery items in Stationery table by 2.
(iv) Select COUNT(DISTINCT Address) from Consumer;
(v) Select StationeryName, price * 3 from Stationery
where Company = ‘CAM’;
Ans. (i) Select * from Stationery
order by StockDate desc;
(ii) Select * from Stationery
where Company = ‘XYZ’ and Price < 10;
(iii) Update Stationery
Set Price = Price + 2;
(iv) 3
(v) Pencil 15
2. Answer the questions given below on the the basis of the following tables SHOP and ACCESSORIES.
Table: SHOP
Id SName Area
S01 ABC Computronics CP
S02 All Infotech Media GK II
S03 Tech Shoppe CP
S04 Geek Tenco Soft Nehru Place
Computer Science with Python—XI
UNSOLVED QUESTIONS
1. Consider the following tables STORE and SUPPLIERS. Write SQL commands for the statements (a) to (d)
and give outputs for SQL queries (e) to (g).
Table: STORE
ItemNo Item Scode Qty Rate LastBuy
2005 Sharpener Classic 23 60 8 31-Jun-09
2003 Ball Pen 0.25 22 50 25 01-Feb-10
2002 Gel Pen Premium 21 150 12 24-Feb-10
2006 Gel Pen Classic 21 250 20 11-Mar-09
2001 Eraser Small 22 220 6 19-Jan-09
2004 Eraser Big 22 110 8 02-Dec-09
2009 Ball Pen 0.5 21 180 18 03-Nov-09
Table: SUPPLIERS
Scode Sname
21 Premium Stationery
23 Soft Plastics
22 Tetra Supply
(a) To display details of all the items in the Store table in ascending order of LastBuy.
(b) To display Itemno and item name of those items from store table whose rate is more than 15 rupees.
(c) To display the details of those items whose supplier code is 22 or Quantity in store is more than 110
from the table Store.
(d) To display minimum rate of items for each Supplier individually as per Scode from the table Store.
(e) SELECT COUNT(DISTINCT Scode) FROM STORE;
(f) SELECT Rate*Qty FROM STORE WHERE Itemno=2004;
(g) SELECT MAX(LastBuy)FROM STORE;
2. Consider the given table and answer the questions.
Table: SchoolBus
Rtno Area_Covered Capacity Noofstudents Distance Transporter Charges
1 Vasant Kunj 100 120 10 Shivam travels 100000
2 Hauz Khas 80 80 10 Anand travels 85000
3 Pitampura 60 55 30 Anand travels 60000
4 Rohini 100 90 35 Anand travels 100000
5 Yamuna Vihar 50 60 20 Bhalla Co. 55000
6 Krishna Nagar 70 80 30 Yadav Co. 80000
7 Vasundhara 100 110 20 Yadav Co. 100000
8 Paschim Vihar 40 40 20 Speed travels 55000
Computer Science with Python—XI