Singh S. Programming With Python. and Its Applications To Physical Systems 2023
Singh S. Programming With Python. and Its Applications To Physical Systems 2023
Preface xv
Acknowledgement xvii
1. Introduction 1–30
7. Functions 121–154
8. List 155–204
9. Dictionaries 205–224
References 341–342
Index 343–344
vii
Detailed Contents
Preface xv
Acknowledgement xvii
1. Introduction 1–30
1.1 What is a Computer? 1
1.2 Basics of Programming Languages 1
1.2.1 Machine Language 2
1.2.2 Assembly Language 3
1.2.3 High Level Languages 3
1.3 Interpreter and Compiler 5
1.4 Algorithms and Flowcharts 6
1.4.1 Writing Algorithms 6
1.4.2 Flowcharts 6
1.5 Writing Algorithms and Flowcharts for A Few Important Problems 7
1.5.1 Reversing the Digits of a Given Integer 7
1.5.2 To Verify Whether an Integer is a Prime Number or Not 8
1.5.3 To Organize a given Set of Numbers in Ascending Order 10
1.5.4 To Find the Square Root of an Integer 11
1.5.5 To Find the Factorial for a Given Number 12
1.5.6 To Generate the Fibonacci Series for n Terms 14
1.5.7 To Find the Value of the Power of a Number
Raised by Another Integer 16
1.5.8 To Reverse the Order Elements of an Array 18
1.5.9 To Find the Largest Number in an Array 20
1.5.10 To Solve a Quadratic Equation 21
1.6 Why Python? 22
1.7 Installing Python 23
1.7.1 Windows 24
1.7.2 Linux and UNIX 25
1.7.3 Macintosh 25
ix
x Detailed Contents
7. Functions 121–154
7.1 Types of Functions 122
7.1.1 Built in Functions 122
7.1.2 User Defined Functions 123
7.2 Incremental Development 127
7.3 Nesting of Functions 130
xii Detailed Contents
9. Dictionaries 205–224
9.1 Definition 205
9.2 Creating a Dictionary 206
9.3 Adding, Modifying, and Retrieving Values 207
9.4 The Dictionary Methods 209
9.5 Deleting Items 212
9.6 Looping Items 212
9.7 Equality Test 212
9.8 Dictionaries of Dictionaries 213
9.9 Sets 213
9.10 Accessing Sets With Common Functions 215
9.11 Subset and Superset in Sets 216
9.12 Relational operators in Sets 216
9.13 Set Operations 217
Exercises 220
xv
xvi Preface
M. Shubhakanta Singh
Acknowledgement
M. Shubhakanta Singh
xvii
1
Introduction
programming languages differ in their closeness to the machine and in the way
they are structured. Most of the programs have a highly structured set of rules.
The primary classifications of programming languages are:
1. Machine Language
2. Assembly Language and
3. High level languages.
Ada Named after Ada Lovelace, who worked on mechanical general-purpose com-
puters. The Ada language was developed for the Department of Defense and
is used mainly in defense projects.
Java Developed by Sun Microsystems, now part of Oracle. It is widely used for
developing platform-independent Internet applications.
Pascal Named after Blaise Pascal, who pioneered calculating machines in the seven-
teenth century. It is a simple, structured, general-purpose language primarily
for teaching programming.
Python A simple general-purpose scripting language good for writing short programs.
Visual Basic Visual Basic was developed by Microsoft and it enables the programmers to
rapidly develop Windows-based applications.
1.3 Interpreter and Compiler 5
Source Object
Compiler Executer Output
Code Code
fig. 1.3 A compiler translates source code into object code at one go,
which is run by a hardware executor.
1.4.2 flowcharts
A flowchart is a pictorial representation of an algorithm. A flowchart is drawn
using the following notations.
Perform calculations
and processing Processing
Flowchart:
Sample Flowchart 1 Sample Flowchart 2
Reverse f- 0 Reverse f- 0
While n;:,: 0
No
Rem f- Remainder of
n/10 (n%10)
n f- Quotient of n/10 (n/10)
Reverse f- Reverse x 10 +
Rem Reverse f- Reverse x 10 + Rem
n = n+ 1
(i) divide n by i
(ii) if remainder is zero, then print the no is not prime and exit the
process.
Step 6 : If none of the remainder are zero, print n is a prime no.
Step 7 : Stop.
Flowchart:
D<O
Print "Enter a
Positive no".
While i ~.JN
Print N is
Print N is a Prime NOT Prime
i +-1
j +-2
While is n-1
Whilej sn
temp= a[i]
a[i]=aU]
aU] = temp
Stop
1.5 Writing Algorithms and Flowcharts for A Few Important Problems 11
Step 2 : Read the integer n for which the square root has to be found.
Step 3 : Pair the digits of n from the right side and group them using bars.
Step 4 : Find the square root of the number which is less than or equal to
the first pair.
Step 5 : Place the square root in the divisor and the no. below the first pair.
The divisor is put as quotient.
Step 6 : Subtract the first pairs and bring down the next pair of digits.
Step 7 : Double the quotient and put a blank digit to the right of the doubled
quotient.
Step 8 : Guess the digit such that multiplying the no. formed with the digit
and the digit itself yields a product less than or equal to the formed
divided.
Step 11 : Stop.
12 Chapter 1 Introduction
Flowchart:
Start
Yes
Print m
Yes
Stop
Flowchart:
Start
i +- 1
Factorial +- 1
While i :s:n
Factorial +- Factorial x i
Next i
Print Factorial
Stop
14 Chapter 1 Introduction
Analysis:
Factorial of a given number is the product of numbers from 1 to that number,
say n. It can be found out by multiplying all the numbers from 1 to that number
for which factorial has to be found out, i.e,
n! = 1 * 2 * 3 … *(n – 1) * n
where n is a positive integer.
Example: Consider n =5
Factorial of 1 = 1
Factorial of 2 = 1 * 2 = 2
Factorial of 3 = 1 * 2 * 3 = 6
= factorial of 2 *3
Factorial of 5 = 1 * 2 * 3 * 4 * 5
= factorial of 4 * 5
= 120
Hence 5! = 120
Flowchart:
Start
First_term +- 0
Second_term +- 1
Third_term +- 0
i +--3
While i !> n
First_term +- Second_term
Second_term +- Third_term
Next i
Analysis: In a Fibonacci sequence, the last two numbers are added to generate
the sequence. The initial first two digited are taken as 0 and 1.
Let us generate a Fibonacci sequence for 8 terms:
First_term, f1 = 0
Second_term, f2 = 1
Third_term, f3 = f1 + f2 = 0 + 1 =1
Proceeding in this way:
f4 = f2 + f3 = 1 + 1 = 2
f5 = f3 + f4 = 1 + 2 = 3
f6 = f4 + f5 = 2 + 3 = 5
f7 = f5 + f6 = 3 + 5 = 8
f8 = f6 + f7 = 5 + 8 = 13 so on.
16 Chapter 1 Introduction
Power +---1
Whilei~ n
Flowchart 2:
,
____
/ R_e_a_d_th_e_B_aT"se_n_um_b_er_m__,/
l
Read the Power number n
Yes
No Yes
Yes No No Yes
Stop
Analysis: Reversing an array is simply by swapping the first and the last
element of the array. Swapping the second element and second last element of
the array and so on.
For example: Let us consider an array of integers:
12 5 34 7 89
Reversing the elements, we get the new array (not sorting the elements),
89 7 34 5 12
Flowchart:
Start
i +- 1
temp+- a(i)
a(i) +- a(n-i+1)
a(n-i+1) +- temp
Next i
Stop
20 Chapter 1 Introduction
Step 1 : Start.
Step 2 : Read the values of a, b and c in the Equation ax2 + bx + c = 0;
Step 3 : If a = 0 and b = 0, print No Root Exists and stop.
Step 4 : If a = 0 and b ≠ 0 then calculate root as – c/b and print it as a Linear
Equation.
Step 5 : Compute Dino = square root of (b2 – 4 ac)
Step 6 : If D < 0, print the Roots are Imaginary and stop.
Step 7 : If D = 0, print the Roots are Real and Equal.
Step 8 : Calculate Root 1 (= Root 2) ← (–b)/(2*a) .
Step 9 : Print Root 1 and Root 2 and Stop.
Step 10 : If D > 0, print the Roots are Unequal.
Step 11 : Calculate Root 1 ← (– b + √Dino)/(2*a).
Step 12 : Calculate Root 2 ← (–b – √Dino)/(2*a).
Step 13 : Print Root 1 and Root 2 as roots of the Equation.
Step 14 : Stop.
Analysis: The roots of a quadratic equation can be found out using the
formula:
− b ± b2 − 4ac
x = ... (1)
2a
If a = 0 and b = 0, then there will be no root of the equation. And if a = 0 and
b ≠ 0, then –c/b will be the root of the linear equation.
− b + b2 − 4ac − b − b2 − 4ac
x1 = x2 =
2a 2a
22 Chapter 1 Introduction
Yes
Dino ~ b*b-4*a*c
root~ -c/b
Yes
Print root
Root1 ~ (-b+J"Dino)/(2*a)
No
Root2 ~ (-b--.Joino)/(2*a)
that does something useful. However, a language that is easy to learn but does
not allow us to do fairly complex tasks is not worth much either. With Python,
we can start writing useful scripts that can accomplish complex tasks almost
immediately.
The second reason we consider Python to be an excellent language is its
readability. Python relies on whitespace (tabs) to determine where code
blocks begin and end. The indentation helps the eyes quickly follow the flow of
a program. Python also tends to be “word-based,” meaning that while Python
uses its share of special characters, features are often implemented as keywords
or with libraries. The emphasis on words rather than special characters helps
the reading and comprehension of code.
Another element of Python’s excellence comes not from the language itself,
but from the python community. In the Python community, there is much
consensus about the way to accomplish certain tasks and the idioms that one
should (and should not) use. While the language itself may support certain
phrasings for accomplishing something, the consensus of the community may
steer one away from that phrasing. For example, from module import*
at the top of a module is valid Python statement. However, the community
frowns upon this and recommends that we use either: import module
or: from module import resource. Importing all the contents
of a module into another module’s namespace can cause serious annoyance
when one try to figure out how a module works, what functions it is calling,
and where those functions come from. This particular convention will help
us writing code that is clearer and will allow people to have a more pleasant
maintenance experience. Following common conventions for writing a code is
considered the best practice.
Easy access to numerous third-party packages is another real advantage
of Python. In addition to the many libraries in the Python Standard Library,
there are a number of libraries and utilities that are easily accessible on the
internet that one can install with a single shell command. The Python Package
Index, PyPI (http://pypi.python.org), is a place where anyone who has written
a Python package can upload it for others to use. At present, there are over
4,000 packages available for download and use.
1.7.1 Windows
To install Python on a Windows machine, follow these steps:
1. Open a web browser and go to http://www.python.org.
2. Click the Download link.
3. You should see several links here, with names such as Python 2.7.x and
Python 3.0.x Windows installer. Click the Windows installer link to
download the installer file. (If you’re running on an Itanium or AMD
machine, you need to choose the appropriate installer.)
4. Store the Windows Installer file somewhere on your computer, such as
C:\download\python-2.5.x.msi. (Just create a directory where you can
find it later.)
5. Run the downloaded file by double-clicking it. This brings up the
Python install wizard, which is really easy to use. Just accept the
default settings, wait until the installation is finished, and the program
is ready for use.
Assuming that the installation went well, we now have a new program in our
Windows Start menu. Run the Python Integrated Development Environment
(IDLE) by selecting Start ➤ Programs ➤ Python2.7 ➤ IDLE (Python GUI).
We should now see a window that looks like the one shown in Fig. 1.5.
fig. 1.5
1.7.3 macintosh
If you’re using a Macintosh with a recent version of Mac OS X, you’ll have
a version of Python installed already. Just open the Terminal application and
enter the command python to start it. Even if you would like to install a newer
version of Python, you should leave this one alone, as it is used in several
26 Chapter 1 Introduction
parts of the operating system. You could use either MacPorts (http://
macports.org) or Fink (http://finkproject.org), or you could use
the distribution from the Python web site, by following these steps:
1. Go to the standard download page (see Steps 1 and 2 from the Windows
instructions earlier in this chapter).
2. Follow the link for the Mac OS X installer. There should also be a link
to the MacPython download page, which has more information. The
MacPython page also has versions of Python for older versions of the
Mac OS.
3. Once you’ve downloaded the installer .dmg file, it will probably mount
automatically. If not, simply double-click it. In the mounted disk
image, you’ll find an installer package (.mpkg) file. If you double-click
this, the installation wizard will open, which will take you through the
necessary steps.
eXerCIses
1.1 State True or False:
(i) Machine language is close to the programmer.
(ii) Machine language is difficult to write.
(iii) High level language is more close to the machine.
(iv) Assembler translates high level language to machine language.
(v) Machine languages are composed of 0’s and 1’s.
(vi) Assembly and machine languages are known as low level languages.
(vii) Compilers occupy more memory than interpreters.
(viii) Interpreter is faster than compiler.
(ix) Python is an example of high level languages.
(x) Python use both Interpreter and Compiler.
(xi) High level languages are easy to write programs.
1.2. What is an assembler?
1.3. What language does the CPU understand?
1.4. What is a source program?
Exercises 29
2.1 KeyWords
In Python, every word is classified as either a keyword or an identifier. All
keywords have fixed meanings and these meanings cannot be changed.
Keywords are the basic building blocks for program statements and must be
written in lowercase. They are reserved words that cannot be used as variable
names. The lists of all keywords are listed in Table 2.1.
Note: For different versions of Python (2.x, 3.y, etc.), the number of keywords
may vary slightly. We can check the keywords with the following commands:
>>> import keyword
>>> print keyword.kwlist
[‘and’, ‘as’, ‘assert’, ‘break’, ‘class’, ‘continue’,
‘def’, ‘del’, ‘elif’, ‘else’, ‘except’, ‘exec’,
‘finally’, ‘for’, ‘from’, ‘global’, ‘if’, ‘import’,
‘in’, ‘is’, ‘lambda’, ‘not’, ‘or’, ‘pass’, ‘print’,
‘raise’, ‘return’, ‘try’, ‘while’, ‘with’, ‘yield’]
32 Chapter 2 Identifiers and Data Types
2.2 IdentIfIers
Identifiers refer to the names of variables, functions and lists. These are user
defined names and consist of a sequence of letters and digits, with a letter as a
first character. Both uppercase and lowercase are permitted, although lowercase
letters are commonly used. The underscore character is also permitted in
identifiers. It is usually as a link between two words in long identifiers (e.g.
average_weight etc.).
>>> type(123)
<type ‘int’>
>>> type(123.456)
<type ‘float’>
>>> type(1234L)
<type ‘long’>
>>> type(12.45 + 67.89 j)
<type ‘complex’>
>>> type(“Hello”)
<type ‘str’>
Not surprisingly, strings belong to the type str and integers belong to the
type int. Numbers with a decimal point belong to a type called float, because
these numbers are represented in a format called floating-point. Complex
numbers are also supported; imaginary numbers are written with a suffix of
“j” or “J”. Complex numbers with a nonzero real component are written
as “(real + imagj)”, or can be created with the “complex(real,
imag)” function.
Constant meaning
‘\a’ audible alert (bell)
‘\b’ back space
‘\n’ new line
‘\r’ carriage return
‘\t’ horizontal tab
‘\’ ’ single quote
‘\” ’ double quote
‘\?’ question mark
‘\\’ backslash
‘\0’ null
2.6 Variables 35
Let us see how it works in python. Using the python interpreter, let us start
with a string
>>> print ‘\aHello world’
Hello world
Here you will hear a beep sound with the output.
>>> print ‘Hello\b world’
Hell world
>>> print ‘Hello\n world’
Hello
World
>>> print ‘Hello\r world’
World
>>> print ‘Hello\t world’
Hello World
>>> print ‘\’Hello world’
‘Hello World
>>> print ‘\Hello world’
\Hello World
>>> print ‘\\Hello world’
\Hello World
Note: Here \H is not a backslash character constant, so we get the same out-
put in the last two examples. If H were one of the escape sequences, then the
output will be different.
For example:
>>> print ‘\new world’
ew World
>>> print ‘\\new world’
\new World
2.6 VarIaBLes
A variable is a data name that may be used to store a data value. Unlike
constants that remain unchanged during the execution of a program, a variable
may take different values at different times during execution.
A variable name can be chosen by the programmer in a meaningful way so as
to reflect its function or nature in the program. Some examples are:
36 Chapter 2 Identifiers and Data Types
Average
total
Total
sl_no
As mentioned earlier in identifiers, variable names may consists of letters,
digits and the underscore character, subject to the conditions mentioned in
Table 2.1.
Now let us write a program using the concept of the variable. To calculate the
area of a circle, we require two variables, radius and area.
>>> radius = 5
>>> area = 3.1415 * radius * radius
>>> print area
78.537500
In this example the statement radius = 5 assigns 5 to the variable radius.
So now radius references the value 5. The next statement
area = 3.1415 * radius * radius
uses the value in radius to compute the expression and assigns the result
into the variable area. Again, let us calculate the second area with the same
variable names:
>>> radius = 10
>>> area = 3.1415 * radius * radius
>>> print area
314.150000
Can we see any difference between Identifiers and variables? They look like
same. The difference is that variables are used to reference values that may be
changed in the program whereas Identifier simply stored their values in the
memory and does not changed. Variables may reference different values also.
For example, in the above code, radius is initialized to 5.0 and then changed to
10.0, and area is computed as 378.537500 and then reset to 314.150000.
eXerCIses
2.1. State True or False:
(a) Any valid printable ASCII character can be used in an identifier.
(b) Declaration of variables can appear anywhere in a program.
(c) Python treats the variables total and Total to be same.
(d) The underscore can be used anywhere in an identifier.
2.6 Variables 37
IntroduCtIon
Python supports a rich set of built-in-operators. An Operator is a special symbol
that tells the computer to perform certain mathematical and logical operations
like addition and multiplication. Operators form a part of the mathematical and
logical expressions. An expression is a sequence of operands and operators
that reduces to a single value.
Python operators can be classified into a number of categories. They include:
1. Arithmetic operators 2. Relational operators
3. Logical operators 4. Assignment operators
Operator meaning
* Multiplication
** Exponentiation
/ Division
// Pure integer division
% Modulo Division
+ Addition or unary plus
- Subtraction or unary minus
∧ Bitwise operator(XOR)
40 Chapter 3 Operators and Expressions
Integer division truncates the fractional part. The modulo division operation
produces the remainder of an integer as well as float divisions.
Operator meaning
> is greater than
>= is greater than or equal to
< is less than
<= is less than or equal to
== is equal to
!= is not equal to
Let us try to use some of the relational examples using python interpreter.
>>> 6 > 5
True
>>> 6 > 8
False
>>> 5 >= 5
True
>>> 8 == 8
True
>>> 9 != 8
True
Note: There should not be any blank or space in between the operators.
For example 7 >= 5 is valid whereas 7 > = 5 is not a valid expression. The
operators <, <=, > and >= operators will raise a Type Error exception
when any operand is a complex number.
Some of these operators deserve some special attention and will be described
in the following sections. Let us try to use some of these operators with strings
and lists.
We can use the equality operator (==) for comparing two strings:
>>> “abc” == “abc”
True
>>> “abc” == “abd”
False
What will happen if we use a single equality sign, as they do in mathematics?
let’s try it:
>>> “abc” = “abc”
SyntaxError: can’t assign to literal
The single equality sign is the assignment operator, which is used to change
things, which is not what we want to do when comparing things.
Operator meaning
or logical OR
and logical AND
not logical NOT
The logical operators and and or are used when we want to test more than
one condition and make decisions. For example,
x > y and y > z is a valid expression.
Note: not has a lower priority than non-Boolean operators, so not a == b
is interpreted as not (a == b), and a == not b is a syntax error.
>>> n = 4
>>> a += (n+1)
>>>print a
19
Now the new value of a is 19 not 14. However the value of n remains 4. If we
want to change the value of a to 14, we can assign it again, as follows:
>>> a= 14
>>> a -= (n+1)
>>>print a
9
The result of the expression of a /= (n+1) will be same as a //= (n+1) because
we are using only integer data types. But we can see the difference when we
use the floating point numbers. Consider a = 14.5 n = 4.3, then
>>> a = 14.5
>>> n = 4.3
>>> a /= (n+1)
>>> print a
2.7538490566
>>> a = 14.5
>>> a //= (n+1)
>>> print a
2.0
The advantages for using shorthand assignment operators are:
1. What appears on the left hand side need not be repeated on the right
hand side and therefore easier to write.
2. The statement is more concise and easier to read.
3. The statement is more efficient.
Note: Expressions and statements
An expression is a combination of values, variables, and operators. So x
+ 8 is a legal expression (assuming that the variable x has been assigned a
value).
A statement is a unit of code that the Python interpreter can execute. We
have seen two kinds of statement: print and assignment.
Technically an expression is also a statement, but it is probably simpler
to think of them as different things. The important difference is that an
expression has a value; a statement does not.
3.5 Interactive mode and Script mode 49
For example, when we write the following code segment in the script mode
print 1
x = 2
print x
produces the output
1
2
The assignment statement does not produce output in the script mode.
y = a - b / (3 + c) * (2 - 1)
z = a - (b / (3 + c) * 2) - 1
print ‘x = ‘, x
print ‘y = ‘, y
print ‘z = ‘, z
Output of the above program:
x = 14
y = 10
z = 7
>>> 1 // 2
0
The double slash consistently performs integer division, even with floats:
>>> 1.0 // 2.0
0.0
This problem is solved in Python 3. In this updated version, the division
operator performs floating point division even with integer operands. So 1/2
or 1.0/2.0 is 0.5.
3.9 hoW to traCK errors?
Python displays lot of information when an error occurs, but it can be
overwhelming, especially when there are many frames on the stack. The most
useful parts are usually:
• What kind of error it was, and
• Where it occurred.
Syntax errors are usually easy to find. Whitespace errors can be tricky because
spaces and tabs are invisible and we are used to ignoring them. For example
>>> y = 6
File “<stdin>”, line 1
y=6
^
IndentationError: unexpected indent
In this example, the error is that the line is indented by one space. But the error
message points to y, which is misleading. In general, error messages indicate
where the problem was discovered, but the actual error might be earlier in the
code, sometimes on a previous line.
Again, when we try to use some built-in-functions, like
>>> sqrt(5)
Traceback (most recent call last):
File “<stdin>”, line 1, in <module>
NameError: name ‘sqrt’ is not defined
In this example, it mentioned that the function sqrt() can’t be imported.
Traceback (most recent call last):
File “snr.py”, line 5, in ?
decibels = 10 * math.log10(ratio)
ValueError: math domain error
54 Chapter 3 Operators and Expressions
>>> radius = 5
>>> area = 3.1415 + radius + radius
>>> print area
13.1415
The result is not what we want. However there is no syntax or runtime errors.
eXerCIses
3.1. State whether the following statements are true or false:
(i) Arithmetic operators do not have the same level of precedence.
(ii) The modulo operator (%) can be used only with integers.
(iii) The operators >=, !=, = and <= all enjoy the same level of priority.
(iv) In Python, if a data item is zero, it is considered as False.
(v) A unary expression consists of only one operand with no operators.
(vi) In Python, an expression statement can be terminated by a period.
(vii) When evaluation of mixed expressions, an implicit cast is generated
automatically.
(viii) An explicit cast can be used to change the expression.
(ix) Parentheses can be used to change the order of evaluation expressions.
(x) Python supports 6 relational operators.
3.2. State whether the following statements are true or false:
(i) The statement b = + 20 is valid.
(ii) The expression 10 + 6/5 * 5/6 evaluates to 10.
(iii) The expression (10 + 6/5) * 5/6 evaluates to 10.
(iv) The statement a = 1/3 + 1/3 + 1/3 assigns 1 to a.
(v) The statement b = 1.0/3 + 1/3.0 + 1.0/3.0 assigns 1.0 to b.
(vi) The statement c = 1.0/3.0 * 3.0 gives 1.0 to c.
3.3. Which of the expressions are true?
(i) !(10+10) <= 10 (ii) !(10+10 <= 10)
(iii) 6 + 9 == 16 or 2 + 7 == 9 (iv) 6 + 9 == 16 and 2 + 7 == 9
4 != 6 and !(7+8+9 == 24 or 7 == 9–2)
3.4. Which of the following arithmetic expressions are valid? If valid, give the
value of the expression; otherwise give reason.
(i) 45/4%3 (ii) +12/4 + 12
(iii) 12.5 % 4 (iv) 45 / int(6.89)
(v) 14 % 4 + 4 % 14 (vi) float(56/6) + –5
(vii) 45 + –8
56 Chapter 3 Operators and Expressions
(velocity)2
(iv) Energy = mass acceleration * height + .
2
3.6. Write a Python program to exchange the values of x, y and z such that x has the
value of y, y has the value of z, and z has the value of x.
[Hints: x = 12. y = 34, z = 56
Output: x = 34, y = 56 and z = 12]
3.7. Write a Python program that reads a floating point number(real number) and
then displays the rightmost digit of the integral part of the number.
[Hints: Input 1234.56, Output = 4]
3.8. Write a Python program that will obtain the length and width from the user
and compute its area and perimeter.
3.9. Write a Python program to evaluate the distance travelled by a vehicle in
regular intervals of time, t which is given by the following equation:
(at2)
distance = ut +
2
where u is the initial velocity (metres per second), a is the acceleration (metres
per second2).
3.10. Write a Python program to read a five digit integer and print the sum of its
digits.
4
Managing Input and
Output Operations
IntroduCtIon
Reading, processing and writing of data are the three essential functions of a
computer program. Most programs take some input and display the processed
data, known as results on a suitable medium (may be on the screen or in a file).
In the previous chapters, we have used a method of providing data to the
program variables through the assignment statements such as a = 123, x = ‘c’;
and so on.
What happens here is that the first line (raw_input()) is executed in the
interactive interpreter. It waits an input from the user. When we type 123 and
press Enter, the value is stored in x. We can see this value using the print
statement.
Again let us try this function in some meaningful way.
>>> name = raw_input(“ Enter your Name: ”)
Enter your Name: Shubha
>>> print name
Shubha
Here, it prints out the string “ Enter your Name: ” as a new prompt.
When we enter a string of characters and press Enter, the resulting value of
input is stored in name variable. In both examples, we used variables like x
and name.
This function can also be used without assigning a variable. The basic
difference is that in this case the value we enter will be printed out
automatically.
>>> raw_input(“ Enter your Name: ”)
Enter your Name: Shubha
‘Shubha’
When we work with script mode, it is better to assign to a variable. Otherwise
we cannot see the output. Let us try these examples in script mode.
# Without using argument
no = raw_input()
print no
# using arguments
name = raw_input(“Enter your name:”)
print name
raw_input(“Enter your Age:”)
Output of this program:
123
123
Enter your name: xyz
xyz
Enter your Age: 40
4.1 Managing Inputs 59
B. input() functions
Let us use this input function in a meaningful way:
>>> x = input(“x = ”)
x = 30
>>> y = input(“y = ”)
y = 40
>>> print x * y
1200
The advantage of using input function is that we can supply the values at run
time.
Note: We can use the input function raw_input() in the same way
>>> x = raw_input(“x = ”)
x = 30
>>> y = raw_input(“y = ”)
y = 40
>>> print x * y
1200
But the best option is that for strings it is better to use raw_input() and for
numbers input() works well. For example:
a=raw_input(“Enter the value of a :”)
b=raw_input(“Enter the value of b :”)
if a-b !=0 :
print ‘a and b are not same’
when you run this program, you will get the following error message:
1 a=raw_input(“Enter the value of a :”)
2 b=raw_input(“Enter the value of b :”)
----> 3 if a-b !=0 :
4 print ‘a and b are not same’
TypeError: unsupported operand type(s) for -: ‘str’
and ‘str’
The problem is that the values of a and b are treated as strings. So subtraction
of strings are not possible. If you change the sign with positive, you will not
get the error but the result may not be what you expect.
To solve this problem, we have many options. The simplest options are either
change the values to integers or simply use the input() function as follows:
60 Chapter 4 Managing Input and Output Operations
OR
>>> str1 = “Hello World!\n”
>>> str2 = str(str1) #In str()- ‘\n’ is equivalent
>>> print str2 #to a new line
Hello World!
>>> str3 = repr(str1)#In repr()-‘\n’ is NOT a new
>>> print str3 #line
‘Hello World!\n’
The repr() of a string adds string quotes and backslashes whereas str()
does not.
Strings, in particular, have two distinct representations. Some examples are:
>>> s = ‘Programming in Python’
>>> print str(s)
Programming in Python
>>> print repr(s)
‘Programming in Python’
However, in numeric values, as shown in the following example, we may use
either str() or repr() functions.
>>> a = 10.25
>>> b = 5000
>>> s1 = ‘The value of a is ’ + repr(a) + ‘, and b is
’ + repr(b) + ‘.’
>>> print s1
The value of a is 10.25, and b is 5000.
>>> s2 = ‘The value of a is ’ + str(a) + ‘, and b is
’ + str(b) + ‘.’
>>> print s2
The value of a is 10.25, and b is 5000.
Again, The argument to repr() may be any Python object, for example:
>>> print repr((a, b, (‘Tuple’, ‘Example’)))# Tuple
as argument
(10.25, 5000, (‘Tuple’, ‘Example’))
>>> print repr([a, b, [‘List’, ‘Example’]])# List as
argument
4.2 Managing Outputs 63
On the other hand, if we used ljust() function, output can be align as left
justified.
for x in range(1, 11):
print repr(x).ljust(2), repr(x*x).ljust(3),\
repr(x*x*x).ljust(4)
1 1 1 1 1 1
2 4 8
3 9 27 1just (2) 1just (3) 1just (4)
4 16 64
5 25 125
6 36 216
7 49 343
8 64 512
9 81 729
10 100 1000
The above examples demonstrate the repr.rjust() and repr.
rjust() (same as str.rjust() and str.ljust())methods of
string objects, which right-justifies a string in a field of a given width by padding
it with spaces on the left and left justifies a string on the right respectively.
However, one space between each column was added by the print()
statement. It always adds spaces between its arguments.
Another method str.center()also works in the same way. These methods
just return a new string. If the input string is too long, they don’t truncate it,
but return it unchanged. If we really want truncation we can always add a slice
operation, as in x.ljust(n)[:m]. The following example explains about
the usages of this slice notation.
for x in range(1, 11):
x=x+0.24
print repr(x).rjust(2), repr(x*x).rjust(3)[:4], \
repr(x*x*x).rjust(4)[:5]
The output of the above program:
1.24 1.53 1.906
2.24 5.01 11.23
3.24 10.4 34.01
4.24 17.9 76.22
4.2 Managing Outputs 65
The brackets and characters within them (called format fields) are replaced
with the objects passed into the str.format() method. A number in the
brackets can be used to refer to the position of the object passed into the str.
format() method.
>>> print “{0} and {1} ”.format(“Position1”,”Position2”)
Position1 and Position2
>>> print “{1} and {0} “.format(“Position1”,”Position2”)
Position2 and Position1
If keyword arguments are used in the str.format() method, their values
are referred to by using the name of the argument. For example:
>>> print ‘We {var1} learning{var2}.’.format(var1=’
are’, var2=’Python’)
We are learning Python.
C. Important conversions:
‘!a’ (apply ascii()), ‘!s’ (apply str()) and ‘!r’ (apply repr()) can be used to
convert the value before it is formatted:
>>> import math
>>> print ‘The value of PI is approx.= {}.’.format(math.pi)
The value of PI is approx.= 3.14159265359.
>>> print ‘The value of PI is approx.= {!r}.’.format(math.pi)
The value of PI is approx.= 3.141592653589793.
An optional ‘:’ and format specifier can follow the field name. This allows
greater control over how the value is formatted. The following example rounds
Pi to three places after the decimal.
>>> print ‘The value of PI is approx.=
{0:.3f}.’.format(math.pi)
The value of PI is approx.= 3.142.
4.3 Frequently used Formatting Specifiers 67
10 2 f Format specifier
Precision
The following table illustrate the output of the above different format
specifications.
10
1 2 . 3 5
1 2 3 4 5 6 7 8 . 9
1 2 . 3 0
8 9 . 0 0
Here a square box denotes a blank space. Note that the decimal point is counted
as one space. The format(“10.2f”) function formats the number into a
string whose width is 10, including a decimal point and two digits after the
point. The number is rounded to two decimal places. Thus there are seven digits
allocated before the decimal point. If there are fewer than seven digits before
the decimal point, spaces are inserted before the number. If there are more
than seven digits before the decimal point, the number’s width is automatically
increased. For example, format(12345678.923, “10.2f”) returns
12345678.92, which has a width of 11.
We can omit the width specifier. If so, it defaults to 0. In this case, the width is
automatically set to the size needed for formatting the number. For example:
print format(57.467657, “10.2f”)
print format(57.467657, “.2f”)
will give output as
57.47
57.47
The following table shows the detail of the output.
5 7 . 4 7
5 7 . 4 7
B. Formatting in Scientific Notation
If we change the conversion code from f to e, the number will be formatted in
scientific notation. For example:
print format(12.345678, “10.2e”)
print format(12345678.9876, “10.2e”)
print format(12.3, “10.2e”)
print format(89, “10.2e”)
The formatted output is:
1.23e+01
1.23e+07
1.23e+01
8.90e+01
4.3 Frequently used Formatting Specifiers 69
The following table illustrates the output of the above different format
specifications.
10
1 . 2 3 e + 0 1
1 . 2 3 e + 0 7
1 . 2 3 e + 0 1
8 . 9 0 e + 0 1
The format 10.2% causes the number to be multiplied by 100 and displayed
with a % sign following it. The total width includes the % sign counted as one
space.
D. Justifying Format
By default, the format of a number is right justified. We have shown earlier
that by using rjust() and ljust() methods, we can adjust right and left
70 Chapter 4 Managing Input and Output Operations
justification of the outputs. On the other hand, we can put the symbol < in the
format specifier to specify that the item be left-justified in the resulting format
within the specified width. For example,
print format(12.345678, “10.2f”) # RIGHT Justified
print format(12.345678, “<10.2f”) # LEFT Justified
12.35
12.35
The following table illustrates the output of the above format specifications.
10
1 2 . 3 5
1 2 . 3 5
E. Formatting Integers
The conversion codes d, x, o, and b can be used to format an integer in decimal,
hexadecimal, octal, or binary numbers respectively. We can also specify a
width for the conversion. For example,
print format(12345, “10d”)
print format(12345, “<10d”)
print format(12345, “10x”)
print format(12345, “<10x”)
The outputs of the above codes are as follows:
12345
12345
3039
3039
The format specifier 10d specifies that the integer is formatted into a decimal
with a width of ten spaces. The format specifier 10x specifies that the integer is
formatted into a hexadecimal integer with a width of ten spaces.
F. Formatting Strings
We can use the conversion code s to format a string with a specified width. For
example,
print format(“Learning Python”, “20s”)
print format(“Learning Python”, “<20s”)
print format(“Learning Python”, “>20s”)
print format(“Welcome to Python Programming”, “>20s”)
4.3 Frequently used Formatting Specifiers 71
The format specifier 20s specifies that the string is formatted within a width
of 20. By default, a string is left justified. So, the symbol < has no meaning
in string formatting. To right-justify it, we can put the symbol > in the
format specifier. If the string is longer than the specified width, the width is
automatically increased to fit the string.
On the other hand, we can use the formatting operator of a tuple or a mapping
(like a dictionary) with special treatment. We haven’t looked at mappings
(such as dictionaries) yet, so let’s focus on tuples here. We’ll use mappings in
forthcoming Chapters, where they’re discussed in greater detail.
If the right operand is a tuple, each of its elements is formatted separately, and
we need a conversion specifier for each of the values. For example:
>>> print ‘%s plus %s equals %s’ (5, 5, 10)
5 plus 5 equals 10
The % character marks the beginning of the conversion specifier. And if we
don’t enclose the values in Parentheses, the following error will come up.
>>> print ‘%s plus %s equals %s’ % 5, 5, 10
TypeError: not enough arguments for format string
The most commonly used conversion types are summarized in Table 4.1.
table 4.1: String Formatting Conversion Types
o Unsigned octal
u Unsigned decimal
(Contd...)
72 Chapter 4 Managing Input and Output Operations
Price of Apples = ` 50
The number 50 will be printed at the place of %d. Also check carefully the role
of modulo operator (%).
>>> print ‘Hexadecimal price of Apples = %x’ % 50
Hexadecimal price of Apples = 32
>>> from math import pi
>>> print ‘Value of Pi = %f’ % pi
Value of Pi = 3.141593
>>> print ‘Estimate of pi = %i’ % pi #Same with %d
Estimate of pi = 3
>>> print ‘Using str = %s’ % 50
Using str = 50
>>> print ‘Using str = %s’ % ‘Python’
Using str = Python
>>> print ‘Using repr: %r’ % 50L
Using repr: 50L
>>> print ‘Using repr: %r’ % ‘Python’
Using repr: ‘Python’
4.3 Frequently used Formatting Specifiers 73
% 0 10 2 f Format specifier
Conversion code
Conversion
specifier
Flag Precision
Field width
74 Chapter 4 Managing Input and Output Operations
Let us see with some examples. Before the field width and precision numbers,
we may put a “flag,” which may be either zero, blank, plus or minus. A zero
means that the number will be zero-padded:
>>> print ‘%010.2f’ % 123.456
0000123.46
Here the leading zero in 010 in the preceding code does not mean that the
width specifier is an octal number, as it would in a normal Python number.
From the conversion specifier, Python knows that it is not an Octal number,
just as the width specifier. However, if you write as follows:
>>> print 010
8
Here it is an octal number. The basic difference is that it is not enclosed within
the string quotes and here is no conversion specifier(%).
Again by using a minus sign (–) in the value of flag will left-aligns the value:
>>> print ‘%-10.2f’ % 123.456
123.46
By defining these width values, we can align positive and negative numbers:
>>> print (‘%d’ % 123) + ‘\n’ + (‘%d’ % -123) # No values of
123 # field width
-123
>>> print (‘% 5d’ % 123) + ‘\n’ + (‘% 5d’ % -123)# With field
123 # width 5
-123
Example 4.1: Formatting Example
#The following example prints out a formatted price list with a given width
width = input(‘Please enter width: ’)
item_width = width - 10
format = ‘%-*s%10.2f’
print ‘_’ * width
print ‘%-*s%10s’ % (item_width, ‘Item’, ‘Price’)
print ‘-’ * width
print ‘%-*s%10.2f’ % (item_width, ‘Tomato’, 56.75)
print format % (item_width, ‘Potato’, 40.00)
print format % (item_width, ‘Waterlemon’, 25.50)
print format % (item_width, ‘Cucumber’, 7.75)
print format % (item_width, ‘Garlic(per Kg)’, 120)
print ‘=’ * width
The output of the above program is:
Exercises 75
Item Price
------------------------------
Tomato 56.75
Potato 40.00
Waterlemon 25.50
Cucumber 7.75
Garlic(per Kg) 120.00
==============================
In this example, the width of the Item is ‘width – 10’ because 10 is reserved for
the Price column. By default, the strings are right aligned, so using minus(–)
sign we can right aligned for the Item column.
Note: However, if we used format() method, then the strings are left aligned,
so we used < and > operators for left and right alignments respectively.
From the above examples, we can conclude that the orders of these format
specifier items are crucial.
• The % character: This marks the beginning of the conversion specifier.
• Conversion flags: These are optional and may be -, indicating left
alignment; +, indicating that a sign should precede the converted value;
“ ” (a space character), indicating that a space should precede positive
numbers; or 0, indicating that the conversion should be zero-padded.
• The minimum field width: This is also optional and specifies that the
converted string will be at least this wide. If this is an * (asterisk), the
width will be read from the tuple value.
• A . (dot) followed by the precision: This is also optional. If a real
number is converted, this many decimals should be shown. If a string
is converted, this number is the maximum field width. If this is an *
(asterisk), the precision will be read from the tuple value.
• The conversion type: This can be any of the types listed in Table 4.1.
eXerCIses
4.1. State whether the following statements are true or false.
(i) The input list in a input() function may contain one or more variables.
(ii) The input() function can’t be use for reading a single character from
the keyboard.
(iii) The format specification %+-6d prints an integer left justified in a field
width of 6 with a sign, if the number is positive.
76 Chapter 4 Managing Input and Output Operations
(iv) If the field width of a format specifier is larger than the actual width of
the value, the value is printed right justified in the field.
(v) The print list in a input() function can contain function calls.
(vi) The input() function is used for reading integer values only.
(vii) The input() function cab be used for reading both integer and
numeric values.
(viii) The format specification %5s will print only the first 5 characters of a
given string to be printed.
4.2. Show the printout of the following statements:
print(format(57.467657, “9.3f”))
print(format(12345678.923, “9.1f”))
print(format(57.4, “.2f”))
print(format(57.4, “10.2f”))
4.3. Show the output of the following statements:
print(format(57.467657, “9.3e”))
print(format(12345678.923, “9.1e”))
print(format(57.4, “.2e”))
print(format(57.4, “10.2e”))
4.4. Show the printout of the following statements:
print(format(5789.467657, “9.3f”))
print(format(5789.467657, “<9.3f”))
print(format(5789.4, “.2f”))
print(format(5789.4, “<.2f”))
print(format(5789.4, “>9.2f”))
4.5. Show the printout of the following statements:
print(format(0.457467657, “9.3%”))
print(format(0.457467657, “<9.3%”))
4.6. Show the printout of the following statements:
print(format(45, “5d”))
print(format(45, “<5d”))
print(format(45, “5x”))
print(format(45, “<5x”))
4.7. Show the printout of the following statements:
print(format(“Programming is fun”, “25s”))
print(format(“Programming is fun”, “<25s”))
print(format(“Programming is fun”, “>25s”))
Exercises 77
4.8. What is the return value from invoking the format function?
4.9. What happens if the size of the actual item is greater than the width in the
format specifier?
4.10. What is the difference between input () and raw_input() functions? Explain
with an example.
4.11. Write a Python program to read the following numbers, round them off to the
nearest integers and print out the results in integer form:
67.7 65.11 –12.89 –23.56 89.90 89.10
4.12. Write a Python program that prints the value 12.345678 in exponential format
with the following specifications:
(i) correct to three decimal places.
(ii) correct to five decimal places.
(iii) correct to seven decimal places.
4.13. Write a Python program that prints the value 12.345678 in fixed point format
with the following specifications:
(i) correct to two decimal places.
(ii) correct to four decimal places.
(iii) correct to zero decimal places.
5
decision making
and Branching
IntroduCtIon
Most of the programs we executed in the previous chapters are a set of
statements which are normally executed sequentially in the order in which
they appear. However, in practice, we have a number of situations where they
may have to change the order of execution of statements based on certain
conditions. This involves a kind of decision making to see whether a particular
condition has occurred or not leading to what is known as Branching.
5.1 If statement
The if statement is used to control the flow of execution of statements. It
is a two way decision making statement and is used in conjunction with an
expression. It takes the following form:
if (test condition):
In the above syntax, colon is a must.
It allows the computer to evaluate
the expression first and then,
depending on whether the value of
the expression (relation or condition)
is TRUE or FALSE, it transfers the
control of the statement. This point
of program has two paths to follow,
known as branching, one for the
true condition and the other for the
false condition as shown in Fig. 5.1.
fig. 5.1. Two way branching.
80 Chapter 5 Decision Making and Branching
statement-y
Example 5.1: Write a python program to read four values a, b, c and d from
the terminal and evaluate the ratio of (a+b) to (c–d) and print the result if c–d
is not equal to zero.
Solution: When we write more than one statement inside the statement-block,
proper indent must be maintained. No other brackets are required.
a=input(“Enter the value of a :”)
b=input(“Enter the value of b :”)
c=input(“Enter the value of c :”)
d=input(“Enter the value of d :”)
if ((c-d) != 0) :
ratio = float(a+b)/float(c-d) # Statement-block
print ‘Ratio =’, ratio # Statement-block
print ‘Program Ends’ # Statement-y
Let us consider an example of counting the number of boys and girls in a class.
We use code 1 for girls and code 2 for boys. The program segment may be
written as:
………
………
if code == 1 :
girls = girls + 1
print ‘\n Distinction.\n’
else :
boys = boys + 1
………
………
The first test determines whether the student is a girl or not. It yes, the number
of girls is increased by one and the program continues to the second test. Once
a student is identified as a girl, there is no need to test again for a boy. A student
can be either a girl or a boy, not both.
Let us consider the example discussed in Example 5.1. When the denominator
(c–d) is zero, the ratio is not calculated. In such cases, we can improve this by
adding an else clause as follows:
a=input(“Enter the value of a :”)
b=input(“Enter the value of b :”)
84 Chapter 5 Decision Making and Branching
the else clause belongs to the outer if statement. Interpreter will not give
error in such logical error.
75 to 100 Distinction
60 to 74 First Division
50 to 59 Second Division
40 to 49 Third Division
0 to 39 Fail
Solution:
marks=input(“Enter the average marks of the student:”)
if marks >=75 and marks<=100 :
print ‘\n Distinction.’
elif marks >=60 and marks<75 :
print ‘\n First Division.’
5.1 If Statement 89
a += 1
b -= 1
print “a =”, a
print “b =”, b
What will be the values of a and b when (i) n = 1 and (ii) n = 0 ?
5.4. Rewrite each of the following without using compound relations:
(a) if (marks >= 60 and marks <75):
print ‘First Division.’
(b) if (number < 0 or number > 100):
print “Out of Range”
else:
print “ The number lies between 0
and 100.”
(c) if ((marks > 75 and marks <=100) or
Total = 560):
print “Distinction.”
else:
print “Try Again!”
5.5. Assuming a = 1, state whether the following logical expressions are true or
false.
(i) a == 1 and a > 1 and !a
(ii) a == 1 or a > 1 and !a
(iii) a == 1 and a > 1 or !a
(iv) a == 1 or a > 1 or !a
5.6. Assuming that x = 2, y = 0 and z = 1, what will be their values after executing
the following code segments?
(a) if (x or y or z):
y = 5
else:
z = 0
(b) if (x and y):
x = 12
else:
y = 20
(c) if (x):
if(y):
94 Chapter 5 Decision Making and Branching
z = 100
else:
z = 10
(d) if (x == 0 or x and y):
if(!y):
z = 123
else:
z = 80
(e) if (x == 0 or x and y):
if(!y):
z = 123
else:
z = 80
5.7. What will be the output of the following code segments? Assume x = 6, y = 5
and z = 12
1. if x%2 == 0:
if x%3 == 0:
print ‘Divisible by 2 and 3’
else:
print ‘Divisible by 2 and not by 3’
elif x%3 == 0:
print ‘Divisible by 3 and not by 2’
2. if x < y and x < z:
print ‘x is least’
elif y < z:
print ‘y is least’
else:
print ‘z is least’
3. if x == 6 :
print “ Python ”
if x == 12:
print “ Anaconda ”
else:
print “ Spyder ”
else :
print “Program Ends.”
5.2 Boolean Values (True or False) 95
IntroduCtIon
If we want to execute a program segment repeatedly, then we can use the
concept of loops. The looping capabilities enable us to develop concise
programs containing repetitive process (for both known and unknown number
of repetitions). In looping, sequences of statements are executed until some
conditions of termination of the loop are satisfied.
A program loop therefore consists of two segments, one known as the control
statement and the other one is known as the body of the loop. The control
statement tests certain conditions and then directs the repeated execution of
the statements contained in the body of the loop. The flow chart in Fig. 6.1
illustrate this.
Entry
Test False
conditions ?
True
The test conditions should be carefully stated to perform the desired number of
loop executions. The test condition will transfer the control out of the loop. In
case, due to some reason it does not do so, the control sets up an infinite loop
and the body is executed again and again.
In general, a looping process consists of the following four steps:
1. Setting and initialization of the condition variable.
2. Execution of the statements in the body of the loop.
3. Test for a specified value of the condition variable for execution of the
loop.
4. Updating the condition variable.
Python provides two ways for performing loop operations. They are:
1. The while loop statement
2. The for loop statement.
The test condition is evaluated first and if it is true, then the body of
the loop is executed. After execution of the body, the test condition is once
again evaluated and if it is true, the body is executed once again. This process
is repeated again and again until the test condition becomes false. When the
condition becomes false the control is transferred out of the loop. On exit, the
program continues with the statement immediately after the body of the loop.
In Python, as we mentioned earlier, indent takes an important role. After the
while statement, an indent (four blank spaces) is a must and it represents the
starting of the body of the loop. The body of the loop may have one or more
statements. The colon at the end of the while statement is mandatory. In the
above loop, the statement-x is out of the loop and it represents the next
statement after the loop. So, this statement-x will execute only when the
condition becomes false.
Few examples are given to make clear these concepts of loops
6.1 The While Loop Statement 99
Example 6.4: Write a Python program to generate the Fibonacci series (0, 1,
1, 2, 3, 5, 8,…) using a while loop.
Solution: We can write an initial sub-sequence of the Fibonacci series as
follows:
# Fibonacci series:
a, b = 0, 1 # multiple assignment here a = 0 and b =1.
while b < 1000:
print b,
a, b = b, a+b
Output of the above program:
mainly we use the range() or xrange() functions. The body of the for
loop may have a single statement or more statements. The statement-x
represents the statement after the for loop.
Let us start with a few examples.
Example 6.5: Printing each word in a list of strings using for loop.
words = [‘this’, ‘is’, ‘an’, ‘example’] # A sequence (list)
for word in words:
print word,
The word is a variable name of our choice and words is the list we defined.
Here for and in are reserve keywords and we can’t change them. To
understand this concept clearly, we can write the above segment of program
as follows:
xyz = [‘this’, ‘is’, ‘an’, ‘example’] # A sequence (list)
for a in xyz:
print a,
See the difference in the above two program segments and we can differentiate
between the reserve keywords and variable names.
The output of the above program is :
this is an example
Note 1: if we omit the comma at the end of the print
statement, the words will be printing vertically,
as follows:
this
is
an
example
Note 2:Modify the above list as follows and see the
difference
(i) words = [‘this is an example’]
for word in words:
print word,
(ii)words = ‘this is an example’
for word in words:
print word,
Now analyze why you get two different outputs
6.2 The for loop statement 103
However, the word “Qack” is misspelled. We can fix this error by using an if-
else statement as follows:
prefixes = ‘JKLMNOPQ’
suffix = ‘ack’
for letter in prefixes:
if letter == ‘Q’ :
print letter + ‘u’ + suffix
else :
print letter + suffix
Now we can get “Quack” instead of “Qack”.
Example 6.8: The following example counts the number of times the letter a
appears in a string:
word = ‘banana’
count = 0
for letter in word:
if letter == ‘a’:
count = count + 1
print count
The variable count is initialized to 0 and then incremented each time an a is
found. When the loop exits, count contains the result—the total number of a’s.
Example 6.9: Encapsulate this code in a function named count, and generalize
it so that it accepts the string and the letter as arguments.
def count(string, letter):
count = 0
for character in string:
if character == letter:
count = count + 1
return count
str1=’banana’
letter =’a’
counter = count(str1, letter)
print ‘No of the character’,’”’,letter,’”’,’ present
=’, counter
In the above program, we directly initialized the two strings str1 and
letter as ‘banana’ and ‘a’ respectively. However we can generalize it
again by using raw_input() function.
6.2 The for loop statement 105
for i in drange(min_val,max_val,step_size):
print i,
The output of the above program is:
1.0 1.1 1.2 1.3 1.4 1.5 1.6 1.7 1.8 1.9
The function drange() can be used as range()function.
The basic difference is that the drange() function
is not a built-in-function.
When the loops are nested, the break would only exit from the loop containing
it. That is, the break will exit only a single loop.
In Fig. 6.3, if the given condition, condition-1 is true, the break will exit
only from the inner loop and will execute the statement, statement-y not
statement-z.
Example 6.12: Write a Python program to find the square root of positive
numbers.
Solution: This program accepts only positive numbers. If we enter a negative
number, it jumps out of the loop with a message “Negative numbers can’t have
square roots....!”.
from math import sqrt
no = input(“Enter a number :”)
while True :
sqr_rt = sqrt(no)
print “The square root of the number”,
no, “is”,sqr_rt
no = input(“Enter a number :”)
if no < 0 :
print “ Negative numbers can’t have square
roots....!” break
6.6 Skipping a part of a Loop 111
statement-x statement-x
(a) (b)
The use of continue statement in while loop causes the control to go directly
to the test condition, condition-1, and then to continue the iterative process.
In case of for loop, if the condition, condition-1, is true, it will not
execute the remaining statements, instead it will start the next iteration.
Example 6.13: Rewrite Example 6.12 using the continue statement.
Solution: In this case let us slightly modify the above example 6.12 using the
continue statement.
112 Chapter 6 Decision Making and Looping
while True :
no = input(“Enter a number :”)
if no == 99999 :
break
if not (no < 0) :
sqr_rt = sqrt(no)
print “The square root of the number “ ,no,”
is “,sqr_rt
print “End of Program.”
if n % x == 0 :
print n, ‘equals’, x, ‘*’, n/x
break
else :
print n, ‘ is a prime number.’
Output of this program :
2 is a prime number.
3 is a prime number.
4 equals 2 * 2
5 is a prime number.
6 equals 2 * 3
7 is a prime number.
8 equals 2 * 4
9 equals 3 * 3
Note 1: The execution of the above program is as follows:
(a) The value of n starts with 2. So, the value of x in the range
(2, 2) is empty. Thus the inner loop will not execute and the else part is
executed. So we got the output “2 is a prime number.”.
(b) Again, when n = 3, the value possible value of x from range(2,3) is
2 only. So the inner loop will execute only once. However the test
condition of the if statement turns out to be false and there will be no
more execution of the inner loop, so we got the output “3 is a prime
number.”.
(c) When n = 4, the possible values of x from range(2, 3) are 2 and 3
only. So the inner loop will execute two times. However the first test
condition when x = 2 is true (i.e. 4 % 2 = 0), so the statements inside
the if statement will execute. And we got the output “4 equals 2 * 2”.
The next loop when x = 3 will not execute because the break statement
terminate the inner loop.
(d) Lastly, let us consider for n = 5. After this we are sure that you can
analyze yourself for the remaining values of n. As before the possible
values of x are 2, 3 and 4. So we know that the inner for loop will
execute three times (i.e., 5%2, 5%3 and 5%4). However, all the three
conditions turn out to be false, so we got the output from the else part
of the inner for loop.
Note 2: Precautions to be taken in using the else clause
Suppose if you write your program, in the following way shown in Fig. 6.6, the
Python interpreter will not give error message because it is not a syntax error.
Such type of error is known as Logical error.
In these cases, the else clause belongs to the if statement not for the loops.
Let us write the above program 6.14 in this way to see the difference in the
outputs:
6.7 The else Clauses on Loops 115
Fig. 6.6 wrong else clause with while and for loops
for n in range(2,10) :
for x in range(2,n) :
if n % x == 0 :
print n, ‘equals’, x, ‘*’, n/x
break
else : # see the difference here
print n, ‘ is a prime number.’
The output will look like this
3 is a prime number.
4 equals 2 * 2
5 is a prime number.
5 is a prime number.
5 is a prime number.
6 equals 2 * 3
7 is a prime number.
7 is a prime number.
7 is a prime number.
7 is a prime number.
7 is a prime number.
8 equals 2 * 4
9 is a prime number.
9 equals 3 * 3
116 Chapter 6 Decision Making and Looping
Example 6.15: Write a Python program to find the square root of a given
number.
Solution: One way of computing square roots is Newton’s method. Suppose
that we want to know the square root of a. If we start with almost any estimate,
x, we can compute a better estimate with the following formula:
x + a/x
y =
2
Suppose, we want to get the square root of 4, then let a is 4 and x is 3.
a=4.0
x=3.0
epsilon = 0.00001
i=1
while True:
print ‘iteration = ’, i,
print ‘x = ’, x
y = (x+a/x) /2
if abs(y-x) < epsilon :
break
x=y
i=i+1
Output of the program:
When a =4.0
iteration = 1 x = 3.0
iteration = 2 x = 2.16666666667
iteration = 3 x = 2.00641025641
iteration = 4 x = 2.00001024003
iteration = 5 x = 2.00000000003
when a = 50.0
iteration = 1 x = 3.0
iteration = 2 x = 9.83333333333
iteration = 3 x = 7.45903954802
iteration = 4 x = 7.08115772137
iteration = 5 x = 7.0710750004
when a = 80.0
6.7 The else Clauses on Loops 117
iteration = 1 x = 3.0
iteration = 2 x = 14.8333333333
iteration = 3 x = 10.1132958801
iteration = 4 x = 9.0118372744
iteration = 5 x = 8.94452519234
iteration = 6 x = 8.94427191359
Important Point to Remember:
If you know how to use for loop, then see the program segment given below:
def getWordscore(word, n):
score = 0
for char in word:
score = score + SCRABBLE_LETTER_VALUES[char]
if len(word) == n:
return ((score * len(word)) + 50)
else:
return score * len(word)
The above program can be written as :
def getWordscore(word, n):
return (len(word) * sum(SCRABBLE_LETTER_VALUES[i] for i in
word)) + (50 if len(word) == n else 0)
So, here are different ways of writing the programs. The best method is to
understand easily to other new programmers.
eXerCIses
6.1. State whether the following statements are true or false.
(i) In a loop, if the body is executed n times, then the test condition is
executed n+1 times.
(ii) The number of times a control variable is updated always equal the
number of loop iterations.
(iii) In a for loop expression, the starting value of the control variable must
be less than its ending value.
(iv) While loops can be used to replace for loops without any change in the
body of the loop.
(v) The use of continue statement is considered as unstructured programming.
(vi) The colon at the end of the while statement is not mandatory.
(vii) The len() function can’t be used in while loops.
(viii) The break statement is used to skip a part of the statements in a loop.
118 Chapter 6 Decision Making and Looping
(ix) The else statement can’t be used with for or while loop.
(x) In a nested loop the break stamen will come out only from the inner
loop.
(xi) Traversing in a list can be done without using a for loop.
6.2. Write the output of each of the following range() functions.
(i) print range(5,10)
(ii) print range(0,10,3)
(iii) print range(0,10,2)
(iv) print range(2,2)
6.3. What would be the output of each of the following code segment?
(i) words2 = [“room”, “window”,”door”]
for i in range(len(words2)) :
print i, words[i]
(ii) words3 = “This is my name.”
for i in range(len(words3)) :
print i, words3[i]
6.4. Convert the following for loop to a while loop statement.
sum = 0
for i in range(101):
sum = sum + i
6.5. Convert the following while loop into a for loop statement.
sum = 0
i = 1
while sum < 101:
sum = sum + i
i += 1
6.6. Count the number of iterations in the following loops:
(i) i = 0
while i < n:
i += 1
(ii) for i in range(n):
Print i
(iii) i = 3
while i < n:
i += 1
(iv) i = 3
while i < n:
i = i + 3
6.7 The else Clauses on Loops 119
6.15. Write a Python program to compute the value of Euler’s number e, which is
used as the base of natural logarithm. The formula is given by:
1 1 1 1 1
e = 1+ + + + + ... +
1! 2! 3! 4! n!
The loop must terminate when the difference between two successive values
of e is less than 0.00001.
6.16. Write Python programs to evaluate the following functions to 0.00001%
accuracy.
x3 x5 x7 x9
(a) sin x = x – + – + – ...
3! 5! 7! 9!
x2 x4 x6 x8
(b) cos x = 1 – + – + – ...
2! 4! 6! 8!
7
functions
IntroduCtIon
If we need to do the same work again, we could type the entire program again
or place it in a loop. However, loops are most useful when we are repeating
the same thing, but writing the same loop repeatedly in different parts of our
program with slightly modified values in each one is not a proper way for a
good programmer. For example, we need to find the sum of integers from
1 to 15, 21 to 40, and 38 to 60. If we write a program to add these three sets of
numbers, our code might look like this:
sum = 0
for i in range(1, 16):
sum = sum + i
print “sum from 1 to 15 is”, sum
sum = 0
for i in range(21, 41):
sum = sum + i
print “sum from 21 to 40 is”, sum
sum = 0
for i in range(38, 61):
sum = sum + i
print(“sum from 38 to 60 is”, sum)
We have observed that the code is very similar, except that the starting and
ending integers are different. Instead of writing these repetitive codes again
and again, we can write a simplified code and then reuse it. This task can be
done with the help of a function.
122 Chapter 7 Functions
Python has functions that enable us to gather sections of code into more
convenient groupings that can be called on when we have a need for them.
In this chapter, we will learn how to create and use our own functions. We can
write our functions so that we can later interrogate them for information about
how they behave and what we intend for them to do. So we will be learning
in detail:
• How to design a function?
• How to integrate a function in a program?
• How functions communicate to each other?
• How nesting of functions can be achieved?
As the examples in this book get longer, typing the entire code block begins to
be a burden. A single mistake causes us to retype in the entire block of code.
When the program becomes very large and complex, the task of debugging,
testing and maintaining becomes more difficult. So, if we divide a program
into smaller segments or functional parts, then it is easier for us to code and
debug them. Later, we can combine all the segments into a single unit.
We write programs that are saved as source code into files that can be opened,
edited, and run without a great deal of work, whenever we want. To reach this
far more convenient state of affairs, from here on we should type the programs
into the main Editor window, and save the examples into a single folder from
which we can reference them and run them anytime.
Note: We will be using the Editor provided by Enthought Canopy. We can use
any one of the editors mentioned in Chapter 1. The Canopy editor is shown in
Fig. 7.1
Function Call:
A function can be called using the function name followed by a list of actual
arguments or parameters, if any, enclosed in parentheses. For example the
function defined in Example 7.1 can be called as follows:
circle_area = area(5)
print circle_area
We can illustrate as:
Function definition Invoke a function
2. If we are using more than one parameter, the list of the parameters must
be separated by commas. For example :
def volume(length, breadth, thickness):
3. If the numbers of parameters are mismatch between the function
definition and calling program, interpreter will generate an error.
Example 7.2: Write a “compare” function that returns
(a) 1 if x > y,
(b) 0 if x = y, and
(c) –1 if x < y.
Answer: The function compare may be written as :
def compare(x,y) :
if x > y :
return 1
7.2 Incremental Development 127
elif x == y:
return 0
else :
return -1
x= compare (10,70)
print x;
Note: To check this program using Python shell, we can do in two ways:
>>> compare(10,70) # or
>>> print compare(10,70)
Here we need two arguments for comparison the two values of x and y. On
the other hand this function requires three return values according to the three
conditions. It is a good idea to ensure that every possible path through the
program has a return statement.
distance = ( x2 − x1 )2 + ( y2 − y1 )2
The first step is to think the number of inputs parameters and the return value
in the function definition. In this case, the inputs are two points, which we can
represent using four numbers x1, y1, x2 and y2. The return value is the distance,
which is a floating-point value. Before we write the complete program let us
write the following program segment.
def distance (x1,y1,x2,y2):
dx = x2 - x1
dy = y2 - y1
p rint “dx is=”,dx # double quote
#print ‘dy is=’, dy # single quote
print ‘dy is=%f’ % (dy) # format string
# dy is=4.000000
text = distance(1,2,4,6)
print text
128 Chapter 7 Functions
A few important points can be noted here: when we use print function,
we can use both single and double quotes. Another way is to use format
string, which is more convenient for displaying decimal values. Again, the
last output line None means that the function does not return anything. If a
function does not return anything python will return None.
If the function is working properly, it should display ‘dx is =3’ and ‘dy is= 4’.
If so, we know that the function is getting the right arguments and performing
the first computation correctly. If not, there are only a few lines to check.
Next we compute the sum of squares of dx and dy:
def distance (x1,y1,x2,y2) :
dx = x2 - x1
dy = y2 - y1
print “dx is=”,dx # double quote
print ‘dy is=’, dy # single quote
ds = dx**2 + dy**2 # same as dx*dx + dy * dy
print ‘squared is: ‘, ds
return 0.0 # return should be in the same indent,
# can’t outside function
x = distance(1,2,4,6)
print x # print distance(1,2,4,6)
Output of this Program segment:
dx is= 3
dy is= 4
squared is: 25
0.0 # see this 0.0 instead of None
When we check the output at this stage, if it shows 25, then we can compute
the square root of ds. For computing square root, we can use the built in
function provided by python, sqrt(), which is available in math module.
Here are two ways for importing the math module, as explained below:
• from math import sqrt
• import math
7.2 Incremental Development 129
The first one is used when we import only sqrt()function. And the second
one is used when we want to import more than one function. The syntax for
using them is explained in the following program
from math import sqrt
def distance (x1,y1,x2,y2) :
dx = x2 - x1
dy = y2 - y1
print “dx is=”,dx # double quote
print ‘dy is=’, dy # single quote
ds = dx**2 + dy**2
print ‘squared is:’, ds
#result = math.sqrt(ds) #import math
result = sqrt(ds) #from math import sqrt
x = distance(1,2,4,6)
print x
Ouput of this program segment:
dx is= 3
dy is= 4
squared is: 25
5.0
Note: When we use from math import sqrt, we can call simply
sqrt(ds). And if we use import math, then we have to use the name
of the module like math.sqrt(ds). If we omit this import statement we
will get a message like,
# NameError: global name ‘math’ is not defined
The final version of the function normally doesn’t display anything when it
runs; it only returns a value, see the following program. The print statements
we wrote are useful for debugging, but once we get the function working, we
should remove them. Code like that is called scaffolding because it is helpful
for building the program but is not part of the final product.
# Final Program
from math import sqrt
def distance (x1,y1,x2,y2) :
dx = x2 - x1
dy = y2 - y1
130 Chapter 7 Functions
ds = dx**2 + dy**2
result = sqrt(ds)
return result
Final_Length = distance(1,2,4,6)
print “\n Length =”, Final_Length
Final Output
Length = 5.0
x
Example 7.5: Evaluate the expression for any given values of x, y and z.
y–z
Also explain how your program will care when the values of y and z are equal.
Our first step is to check the values of y and z is equal or not. If they are equal,
then we have to print a message saying that the expression can’t be evaluated.
We wrote a function to compare the values:
def is_equal(x, y):
if x == y:
return True
else:
return False
def expression(x,y,z) :
if is_equal (y,z) :
print “Expression can’t be evaluated.”
Print “because 1/0 is infinity (not defined)”
else :
result = float(x/(y-z))
return result
x = expression(5,6,7)
print ‘x = ‘, x
y= expression(5,7,7)
print ‘y =’, y
Here, the first step is to check the number of arguments. In this case we need
3 arguments of x, y and z. The incremental development of the program is
explained below:
def is_between(x,y,z):
if z >= y:
if y >= x:
return True
else:
return False
z1= is_between(2,3,6)
print z1 # True
x1= is_between(12,3,6)
print x1 # None because no return statement is there
y1= is_between(2,12,6)
print y1 # False
In the above program, we are using two if statements and only one else
part. In such case, all the conditions can’t be fulfilled. For example, the value
of x1, when x is larger than y and z, python returns None.
The final program may be written as :
def is_between(x,y,z):
if z >= y:
if y >= x:
return True
else : # to avoid None
return False
else:
return False
big_x= is_between(12,3,6)
print big_x # output will be False
big_y= is_between(2,13,6)
print big_x # output will be False
big_z= is_between(2,3,16)
print big_x # output will be True
134 Chapter 7 Functions
Explanation: Let us see how the recursive function executes the flow of
sequence. We pass 5 as the value of n. In the first if statement n is not equal to
0 so it evaluates the else part, and it looks like
fact = 5 * factorial(4)
The function factorial (4) will be executed by calling the same function again.
So, the new value of fact will be
fact = 5 * 4 * factorial(3)
Thus, by calling the function again and again, we will get
fact = 5 * 4 * 3 * factorial(2)
fact = 5 * 4 * 3 * 2 * factorial(1)
fact = 5 * 4 * 3 * 2 * 1 * factorial(0)
When n = 0 it will return 1 in the place of factorial (0). Thus the value of fact
will be
fact = 5 * 4 * 3 * 2 * 1 * 1 =120
Note: If we can’t get the correct output, adding a print statement just before
each return statement displays the return value. Also, if possible, check the
result by hand. If the function seems to be working, look at the function call
to make sure the return value is being used correctly or not. Adding print
statements at the beginning and end of a function can help make the flow of
execution more visible.
Here is a version of factorial with many print statements:
def factorial(n):
space = ‘ ‘ * (4 * n)
print space, ‘factorial’, n
if n == 0:
print space, ‘returning 1’
return 1
else:
result = n * factorial(n-1)
print space, ‘returning’, result
return result
x=factorial(5)
print ‘Factorial = ’, x
136 Chapter 7 Functions
Figure 7.2 shows the call graph for fibonacci with n = 5. A call graph shows
a set of function frames, with lines connecting each frame to the frames of the
functions it calls. At the top of the graph, fibonacci with n = 5 calls fibonacci
with n = 4 and n = 3. In turn, fibonacci with n = 4 calls fibonacci with n = 3
and n = 2. Again, fibonacci with n = 3 calls fibonacci with n = 2 and n = 1.
And so on.
Count how many times fibonacci(0) and fibonacci(1) are called. This is an
inefficient solution to the problem, and it gets worse as the argument gets
bigger. Such problems can be taken care by the concept of dictionary discussed
in Chapter 9.
Example 7.9: To check a given string is palindrome or not.
A palindrome is a word that is spelled the same backward and forward, like
“madam” and “malayalam”. Recursively, a word is a palindrome if the first
and last letters are the same and the middle is a palindrome.
The following are functions that take a string argument and return the first,
last, and middle letters:
# Checking for palindrome:
def first(word):
″″″Returns the first character of a string.″″″
return word[0]
def last(word):
138 Chapter 7 Functions
Example 7.12: Another way to solve this problem just using multiplication
(and remainder) is to note that
exp
(
baseexp = base 2 ) 2 if exp > 0 and exp is even
return None
elif exp == 1:
return result
elif (exp % 2 == 0):
result = (base*base)**(exp/2)
return result
else :
result = base*(base**(exp-1))
return result
t = SimplePowerNew(2,6) # For even exponent
print ’2 to the power 6 =’, t
t1 = SimplePowerNew(2,5) # For even exponent
print ’2 to the power 5 =’, t1
Output of the above program:
2 to the power 6 = 64
2 to the power 5 = 32
Example 7.13: Write a Python program to find the greatest common divisor of
two positive integers. For example,
gcd(2, 12) = 2
gcd(12, 2) = 2
gcd(6, 12) = 6
gcd(9, 12) = 3
gcd(17, 12) = 1
(i) Without using recursive function
(ii) Using recursive function.
Solution:
We can write an iterative function, gcd2(a, b), that implements this idea.
One easy way to do this is to begin with a test value equal to the smaller of
the two input arguments, and iteratively reduce this test value by 1 until you
either reach a case where the test divides both a and b without remainder,
or you reach 1. Another important condition is that the interchanging of the
two values of the parameters will not change the GCD value. For example
gcd (2, 12) is 2 and gcd (12, 2) will also be 2. We can implement it by
interchanging the two values, as follows:
7.5 Recursion Function 143
def gcdRecur(a,b):
if b == 0:
return a
else :
return gcdRecur(b, a%b)
t = gcdRecur(2, 12)
print ‘The GCD of (2, 12) is ’, t
t1= gcdRecur(12, 2) #= 2
print ‘The GCD of (12, 2) is ’, t1
t2 = gcdRecur(6, 12) #= 6
print ‘The GCD of (6, 12) is ’, t2
t3 = gcdRecur(9, 12) #= 3
print ‘The GCD of (9, 12) is ’, t3
t4 = gcdRecur(17, 12) # = 1
print ‘The GCD of (17, 12) is ’, t4
Output of the above Program:
The GCD of (2, 12) is 2
The GCD of (12, 2) is 2
The GCD of (6, 12) is 6
The GCD of (9, 12) is 3
The GCD of (17, 12) is 1
should be placed in the same directory with other programs. A module can
contain more than one function. Each function in a module must have a
different name. If we define two functions with the same name in a module
then the latter function definition will get the prevailage.
For example, the random and math are the modules defined in the Python
library, and thus they can be imported into any Python program. Now let us try
to define a module. Example 7.14 shows a program that prompts the user to
enter two integers and displays their sum of the first number up to the second
number.
Let us save the following code in the file sum1.py
Example 7.14: Sum of Integers: sum1.py
def sum( no1, no2):
sum = 0
for i in range(no1, no2 + 1):
sum = sum + i
return sum
The newly created module “sum1” is ready for use now. We can import this
module like any other module in a program or script. Let us demonstrate the
use of this sum function to a new program sum_module.py.
# sum_module.py
from sum1 import sum # Calling the module
print “Sum from 1 to 15 is”, sum(1,16)
print “Sum from 21 to 40 is”, sum(21, 41)
print “Sum from 38 to 60 is”, sum(38, 61)
We can also import the sum1 module using the following statement:
import sum1 # NOT like “from sum1 import sum”
If we import in this way, then we would have to invoke sum function using dot
operator as, sum1.sum(). The complete program is shown below:
import sum1
print “Sum from 1 to 15 is”, sum1.sum(1,16)
print “Sum from 21 to 40 is”, sum1.sum(21, 41)
print “Sum from 38 to 60 is”, sum1.sum(38, 61)
The output of the above program:
Sum from 1 to 15 is 136
Sum from 21 to 40 is 651
Sum from 38 to 60 is 1188
7.8 Global and Local variables 147
function2()
# Print global variable outside the function
print “ Global Variable (outside function)= “,Global_
Variable
# displays 123
Output of the above program:
Global Variable = 456
Global Variable (outside function)= 123
We can bind a local variable in the global scope. We can also create a variable
inside a function and use it outside the function. To do either, we can use a
global statement, as shown in the following example.
Example 7.17: Local to Global variable
x = 100
def function3():
global x
x = x + 50
print “x (Inside function)= ”, x # displays 150
function3()
print “x (Outside function)= ”, x # # also displays 150
Here the value of the global variable x is the same inside and outside of the
function. It is possible because of the keyword global.
Note: It is not a good practice to allow global variables to be modified in a
function, because by doing so it can make programs more prone to errors.
However, the advantage of defining global constants is that all functions in the
module can share them.
Example 7.18: Role of local variables
x = input(“Enter a number: ”)
if x > 5:
y = 10
print “y =”, y # This gives an error if y is not
created
The variable y will be created if the value of x > 5 otherwise the program will
give an error “Nameerror: name ‘y’ is not defined” because
y is not created.
7.9 Default Arguments 149
If we enter any number greater than 5, then we can assign the value of y as 10,
as follows:
Enter a number: 78
y = 10
On the other hand, let us try to find the value of a local variable created using
a loop, as follows:
sum = 0
for i in range(10):
sum += i
print “Value of i =”, i
Here the variable i is created in the loop. After the loop is finished, the latest
value of i was 9, so when we print the value of i outside the loop, it will give
the value of 9 as:
Value of i = 9
eXerCIses
7.1. State the following are true or false:
(a) A function header begins with the def keyword followed by function’s
name and parameters, and ends with a semicolon.
(b) Parameters are optional; that is, a function does not have to contain any
parameters.
(c) A function is called a void or None function if it does not return a value.
(d) A return statement can also be used in a void function for terminating the
function and returning to the function’s caller.
(e) The arguments that are passed to a function may or may not have the
same number, type, and order as the parameters in the function header.
(f) A value-returning function can also be invoked as a statement in Python.
(g) The scope of a local variable starts from its creation and exists until the
function returns.
(h) Global variables are created outside all functions and are accessible to
all functions in their scope.
(i) The return statement can return multiple values.
(j) It is most likely result in logical error if there is a mismatch in data types
between the actual and formal arguments.
7.2. Which of the following function headers are invalid and why?
(a) def CalculateArea(height , width = 5):
(b) def CalculateArea(height = 5 , width):
(c) def CalculateArea(5 , width = 5):
(d) def CalculateArea(height = 5 , 5):
(e) def CalculateArea(5 , 5):
7.3. Find out the logical and syntax errors, if any, in the following program
segments:
(a) def sum( no1, no2):
sum = 0
for i in range(no1, no2 + 1):
sum += i
return result
(b) def sum( no1, no2):
result = 0
for i in range(no1, no2 + 1):
result = result + i
return result
152 Chapter 7 Functions
return 1
elif no == 0:
return 0
elif no < 0:
return –1
function1(2, 3)
7.6. Show the output of the following code:
def main():
print(min(5, 6))
def min(n1, n2):
smallest = n1
if n2 < smallest:
smallest = n2
main()
7.7. Find out error, if any, in the following function definition:
def CalculateArea(height , width=5):
area = width * height
print “Width = “, width, “\tHeight = “,\
height, “\tArea = “, area
7.8. Assuming that exercise 7.7 has no error, which of the function calls are valid
and why?
CalculateArea()
CalculateArea(width = 5.6)
CalculateArea(height = 9)
CalculateArea(width = 7, height = 5)
CalculateArea(4.5, 3.5)
CalculateArea(4, width = 4)
CalculateArea(width = 4, 4)
7.9. Show the output of the following code:
def fun(w = 10, h = 20):
print w, h
fun()
fun(w = 5)
fun(h = 24)
fun(4, 5)
154 Chapter 7 Functions
IntroduCtIon
The preceding chapters so far have described structured commands and problem
solving involving generally simple variables. Python like other programming
languages has user friendly features for large numbers of variables or arrays
and subscripted variables. In Python they can be proceed using List statements.
This chapter describes the usefulness of List in Python programming. The
basics of how to create a list and common operations of list that frequently
used are explained in detail. How to access list elements by using indexed
variables and creating a sublist from a larger list with the help of the slicing
operator are also described with examples. Commonly used operations like
traversing the elements in a list using a for loop, comparing the contents of
two lists, invoking the list’s important built-in methods, copying the contents
from one list to another and applications of list in program development are
explained with examples. It also include various applications of the important
techniques of Sorting, Selection and Insertion sort, in lists with diagrams. The
concept of representing data in a two dimensional list, accessing elements by
using row and column indexes and concepts of multidimensional lists are also
included with illustrative examples.
8.1 defInItIon
Python has six built-in types of sequences. They are lists, tuples, strings,
unicode strings, buffer objects, and xrange objects. This chapter concentrates
on lists. A list is a sequence of values. The values in a list are called elements
or sometimes items. The items of a list are separated by commas. The values
of a list may be of any type. There are several ways to create a new list; the
simplest is to enclose the elements in square brackets ([ and ]), for example:
156 Chapter 8 List
Lists are represented by boxes with the word “list” outside and the elements
of the list inside. strings1 refers to a list with three elements indexed 0, 1
and 2. List for numbers contains three elements; the diagram shows that the
value of the second element has been reassigned from 34 to 78.
Some of the properties of List indices are:
• Any integer expression can be used as an index.
• If you try to read or write an element that does not exist, you get an
IndexError.
• If an index has a negative value, it counts backward from the end of the
list.
This loop traverses the list and updates each element. The range()and
len() are python built in functions. len() returns the number of elements
in the list. The range() function returns a list of indices from 0 to n – 1,
where n is the length of the list. Each time through the loop i gets the index of
the next element. The initial value of i is 0 as we mentioned. The assignment
statement in the body uses the variable i to read the old value of the element
and to assign the new value in the list. Here in this example, the old value is
multiplied by 2. Let us write a program segment to explain this:
strings1 = [‘Computer’, ‘Maths’, ‘Physics’]
numbers = [12,78,56]
mixed = [‘shubha’, 1, 45, 78, ‘Kanta’]
for string in strings1 :
print string
for number in numbers :
print number
for i in mixed :
print i
number2=[2,3,4,5,6] # defining a new list
print number2
for i in range(len(number2)) :
number2[i] = number2[i] * 2
print number2
Output of the above program segment is:
Computer
Maths
Physics
12
78
56
shubha
1
45
78
Kanta
[2, 3, 4, 5, 6]
[4, 6, 8, 10, 12]
8.4 Nested List 161
Note: A for loop over an empty list never executes the body:
for j in [ ]:
print ‘This line won’t executes at all.’
The len()returns four for the above nested list. It gives length of one for
the inner list though it has more than one element. Note the difference of print
statements with loop and without loop. And another interesting part is that
when we multiply by 2, strings elements and inner lists get doubled of its
length. Let us see more on list operations.
162 Chapter 8 List
Note: Python has a basic notion of a kind of data structure called a container,
which is basically any object that can contain other objects. The two main
kinds of containers are sequences (such as lists and tuples) and mappings
(such as dictionaries). While the elements of a sequence are numbered, each
element in a mapping has a name (also called a key). A container type is
neither a sequence nor a mapping.
Example 8.1: Write a Python program that asks you for a year, a month (as a
number from 1 to 12), and a day (1 to 31), and then prints out the date with the
proper month name and so on.
Solution:
#Print out a date, given year, month, and day as numbers
months = [
‘January’,
‘February’,
‘March’,
‘April’,
‘May’,
‘June’,
‘July’,
‘August’,
‘September’,
‘October’,
‘November’,
8.7 List Functions 165
‘December’
]
# A list with one ending for each number from 1 to 31
endings = [‘st’, ‘nd’, ‘rd’] + 17 * [‘th’] \
+ [‘st’, ‘nd’, ‘rd’] + 7 * [‘th’] \
+ [‘st’]
year = raw_input(‘Year: ‘)
month = raw_input(‘Month (1-12): ‘)
day = raw_input(‘Day (1-31): ‘)
month_number = int(month)
day_number = int(day)
# Remember to subtract 1 from month and day to get a
# correct index
month_name = months[month_number-1]
ordinal = day + endings[day_number-1]
print month_name + ‘ ‘ + ordinal + ‘, ‘ + year
Output of this program:
Year: 1990
Month (1-12): 7
Day (1-31): 9
July 9th, 1990
Note: A Python list’s size is flexible. It can grow and shrink on demand.
methods Descriptions
append(s) Add an element, s to the end of the list.
extend(s) Appends all the elements of list, s to the calling list.
sort() Sort the elements in the list in ascending order.
count(s) Returns the number of times element, s appears in the list.
Contd...
8.8 List Methods 167
index(s) Returns the index of the first occurrence of element, x in the list.
insert(s1,s2) Insert the element s2 at a given index, s1. Note that the first element in the list has
index 0 (not 1).
pop(s) Removes the element at the given position, s and returns it. If the position is not
specified, pop()removes the last element of the list and return it.
remove(s) Removes the first occurrence of the element, s from the list. Here s represents the
element not the index of the element.
reverse() Reverse the elements in the list.
Python provides methods that operate on lists. The append(x) adds a new
element x to the end of a list:
>>> a = [1, 2, 3, 4]
>>> a.append(5)
>>> print a# In Python shell, we can omit print
# statement
[1, 2, 3, 4, 5]
If we give the argument as a list in append(s) method rather than an integer
or character, it will give us a nested list, as follows:
>>> a = [1, 2, 3, 4]
>>> b = [6, 7, 8]
>>> a.append(b)
>>> a
[1, 2, 3, 4, [6, 7, 8]]
The extend() takes a list as an argument and appends all of the elements:
>>> b = [1, 2, 3]
>>> c = [4, 5]
>>> b.extend(c) # here argument is a list.
>>> print b
[1, 2, 3, 4, 5]
This example leaves c unmodified and appends only at b list.
Note: If we use the argument of the extend() method as an integer value
rather than a list, we will get an error message as follows:
>>> list1 =[1, 2, 3, 4]
>>> list1.extend(12)
Traceback (most recent call last):
File “<pyshell#26>”, line 1, in ?
list1.extend(12)
TypeError: list.extend() argument must be a sequence
168 Chapter 8 List
removing it from the position of the list. If no argument is given, then the last
element will be removed.
>>> list1 = [1, 3, 5, 8, 7, 10, 20]
>>> list1.pop(5) # with argument: 5 is the
position of 10
# the element in the list.
>>> list1# the new list after removing the
element
[1, 3, 5, 8, 7, 20]
>>> list1.pop()# without argument
20
>>> list1 # the last element is removed.
[1, 3, 5, 8, 7]
The remove() method removes the element permanently from the list.
>>> list1 = [12, 3, 34, 6, 56, 99, 85, 78, 90]
>>> list1.remove(85)
>>> list1
[12, 3, 34, 6, 56, 99, 78, 90]
Note 1: If the element is not in the list, it will give an error message as follows:
>>> list1.remove(86)
Traceback (most recent call last):
File “<pyshell#45>”, line 1, in ?
list1.remove(86)
ValueError: list.remove(x): x not in list
Note 2: The basic difference between pop() and remove() methods is
that the element removed by pop() can be reused by assigning it to a variable
whereas the element removed by remove() method is permanently deleted.
The reverse() method can be called as follows:
>>> list1 = [12, 3, 34, 6, 56, 99, 78, 90]
>>> list1.reverse()
>>> list1
[90, 78, 99, 56, 6, 34, 3, 12]
Here are some examples that use append(), extend() and sort()
methods
170 Chapter 8 List
def left_shift(lst) :
temp = lst[0];
print “After Left Shift :” ,
for i in range(1, len(lst)):
lst[i-1] = lst[i]
8.12 Simplifying coding with List 173
lst[len(lst) - 1] = temp
print lst
list1 = [2, 3, 45, 6, 78]
print “Before left Shift : “, list1
left_shift(list1)
Output of the above program:
Before left Shift : [2, 3, 45, 6, 78]
After left Shift : [3, 45, 6, 78, 2]
B. Right Shift
There are many ways for implementing the right shift of the elements in a list.
One of the easiest ways to perform a right shift is shown below.
def Right_shift(lst):
no_of_elements = len(lst)-1
Last_value = lst[no_of_elements]
print “After Right Shift :” ,
for i in range(no_of_elements, 0,-1):
lst[no_of_elements] = lst[no_of_
elements-1]
no_of_elements -= 1
lst[0] = Last_value
print lst
list2 = [2, 3, 45, 6, 78]
print “Before Right Shift : “, list2
Right_shift(list2)
Output of the above Program:
Before Right Shift : [2, 3, 45, 6, 78]
After Right Shift : [78, 2, 3, 45, 6]
index. The following sample code prompts the user to enter a month number
and displays its month name:
months = [“January”, “February”, “March”,…,“December”]
month_number = input(“Enter a month number ( 1 to 12 ) :”)
print(“The month is :”, months[month_number – 1])
If the months list is not used, we would have to determine the month name
using a lengthy multi-way if-else statements as follows:
if month_number == 1 :
print “ The month is January”
elif month_number == 2:
print “ The month is February”
elif month_number == 3:
print “ The month is March”
…
else :
print “ The month is December”
Example 8.2: Write a function called SUM that takes a list of integers and add
up the elements.
Answer:
def SUM(t): # t should be a list
total = 0
for x in t : # we can use “range(len(t))” also.
total += x # equivalent to “total = total + x”
#print total # debugging line, remove after
# program works properly
return total
t=[1, 2, 3, 4]
s=SUM(t)
print ‘Sum of the elements of the list = ‘,s
print “\nThe sum of the elements using built in
function:”
print sum(t) # Built in Functions
s=sum(t) # An operation like this that combines
#a sequence of elements into a single value is
#sometimes called reduce.
(Please keep the # symbol at the beginning of
the line.)
print s
8.12 Simplifying coding with List 175
Note 1:
The Python interpreter cannot determine the end of the statement written in
multiple lines. We can place the line continuation symbol (\) at the end of a
line to tell the interpreter that the statement is continued on the next line. For
example, the following statement
sum = 1 + 2 + 3 + 4 + \
5 + 6
is equivalent to
sum = 1 + 2 + 3 + 4 + 5 + 6
In the above program, we used the continuation symbol to tell the interpreter
that the statement is continued on the next line.
NUMBER_OF_ELEMENTS = input(“For how many
numbers do you \ want to find Average?”)
Note 2: The built-in function eval():
We can use the function eval to evaluate and convert it to a numeric value.
For example, eval(“34.567”) returns 34.567, eval(“1234”)
returns 1234, and eval(“5 + 8”) returns 13.
Again,
variable = input(“Enter a value:”)
The value entered is a string. So we can convert into numeric value as:
variable = eval(input(“Enter a value: ”))
178 Chapter 8 List
fig. 8.2 Before the assignment statement, list1 and list2 had separate memory
locations. After the assignment statement, the list1 reference value is passed to
list2 (i.e., they have the same memory locations).
Here is an example to illustrate this concept:
>>> list1 = [2,3,4,5]
>>> list2 = [5,4,6,7,8]
>>> id(list1) # The reference of list1
12512716
>>> id(list2) # The reference of list2
12850348
>>> list2 = list1
>>> id(list2)
12512716
The two lists list1 and list2 are created with different references. After
assigning list1 to list2, list2’s id is same as list1’s id. Now list1
and list2 refer to the same object.
8.14 Passing Lists to Functions 179
Since a list is mutable object, the contents of a list may change in the functions.
For example:
The linear search function compares the key with each element in the list.
The elements can be in any order. Since the execution time of a linear search
increases linearly as the number of list elements increases. A linear search is
therefore inefficient method especially when the list is a large one.
+
[OJ [1 J [2J [3J [4 J
+
[5J [6J [7J [8J [9J
+
[1 OJ
+
[OJ [1 J [2J
+
[3J [4J
+
[5J [6J [7J [8J [9J [1 OJ
fig. 8.3 A binary search eliminates half of the list after each comparison.
182 Chapter 8 List
in the worst-case scenario when using the binary search approach, we need
comparisons to find an element in the sorted list. In the worst case for a list
of 1024 elements, the binary search requires only 11 comparisons, whereas a
linear search requires 1,023 comparisons in the worst case.
Let us start with an example. Consider a list, list1=[3, 16, 28, 32,
46, 50, 58, 62, 73, 87, 92], with key = 46. The Fig. 8.3
shows the constructive steps of the search method. The portion of the list being
searched shrinks by half after each comparison. Let low and high denote the
first index and last index of the list , respectively. Initially, low is 0 and high is
len(list1)–1. Let mid denote the index of the middle element, so mid is (low
+ high) // 2.
The next task is to implement it in Python.
def BinarySearch(key, list1) :
low = 0
high = len(list1) - 1
while high >= low :
mid = (high + low) // 2
if key < list1[mid] :
high = mid -1
elif key == list1[mid]:
print “Key is found”,
return mid# we can return key also.
else :
low = mid + 1
print “Not Found :”,
return -1 # if not found in the list
list1=[3, 16, 28, 32, 46, 50, 58, 62, 73, 87, 92]
result = BinarySearch(46, list1)
print result
result1 = BinarySearch(47, list1)
print result1
8.16 Sorting Lists 183
12 45 3 89 7 11 9
Select the smallest element and swap
it with the first no. in the list. Here
First no. = 12; smallest no.= 3 t t
The no. 3is now in the correct
position and no longer needs to be 1@1 45 112 89 7 11 9
considered. So it is circled.
:t t
Select the smallest element 7 and
swap it with the first no. 45 in the I@ I 01 12 89 45 11 I 91
remaining list. Here 7 is in correct
:t
position and so we circled.
i
Select the smallest element 9 and
swap it with the first element 12 in 1@10 I ®I 45 45 11 112 I
the remaining list. Here 9 is in correct
position and so we circled.
:t i
Select the smallest element 11 and
swapit with the first element89 in 1@10 I ®I @ 45 89 I12 I
the remaining list. Here 11 is in correct
position and so we circled.
:t t
Select the smallest element 12 and 1@10 I @I @ @ 89 145 I
swap it with the first element45 in
the remaining list. Here 12 is in correct
position and so we circled.
Since 89 is the only one element in the list, the sort is completed .
fig. 8.4 The Selection sort repeatedly selects the smallest element and
swaps it with the first element in the remaining list.
The next step is to implement with Python. We know that the important part
is to find the smallest element in the list and swap it with the first element and
continue it till the last element. The Python program is given below:
def SelectionSort( list1) :
print “Steps of Selection Sort:”
for i in range(len(list1) - 1) :
8.16 Sorting Lists 185
smallest_element = list1[i]
index_to_smallest = i
#To find the smallest element in the List
for j in range(i+1, len(list1)) :
if smallest_element > list1[j] :
smallest_element = list1[j]
index_to_smallest = j
#Swap list1[i] with list1[index_to_smallest]
# if necessary
if index_to_smallest != i :
list1[index_to_smallest] = list1[i]
list1[i] = smallest_element
list1 = [12, 45, 3, 89, 7, 11, 9]
print “List elements before sorting:”, list1
SelectionSort(list1)
print “List elements after sorting:”, list1
Output of the above program :
List elements before sorting: [12, 45, 3, 89, 7,
11, 9]
Steps of Selection Sort:
[12, 45, 3, 89, 7, 11, 9]
[3, 45, 12, 89, 7, 11, 9]
[3, 7, 12, 89, 45, 11, 9]
[3, 7, 9, 89, 45, 11, 12]
[3,457, 9, 11, 45, 89, 12]
[3, 7, 9, 11, 12, 89, 45]
List elements after sorting: [3, 7, 9, 11, 12, 45,
89]
t t
Step 6: The sorted sublist is 3
[3, 7, 11, 12, 45, 89]. Insert the
element 9 into the sublist.
fig. 8.5 The Insertion Sort repeatedly inserts a new element into a sorted list.
marks = [
[67, 89, 82, 90],
[87, 66, 78, 75],
[78, 76, 80, 82],
[80, 88, 76, 72]
]
In this way, a two-dimensional list can be used to store two-dimensional data.
In other words, it is considered as nested list.
import random
matrix = [] # Create an empty list
Rows = input(“Enter the number of rows: ”)
Columns = input(“Enter the number of columns: ”)
for row in range(Rows):
matrix.append([]) # Add an empty new row
for column in range(Columns):
matrix[row].append(random.randint(1, 50))
print “\n The new matrix is :”
print matrix
Output of the above program:
Enter the number of rows: 3
Enter the number of columns: 3
The new matrix is :
[[17, 46, 11], [36, 17, 33], [49, 7, 37]]
Enter the number of rows: 2
Enter the number of columns: 2
The new matrix is :
[[41, 10], [41, 25]]
Use a variable named total to store the sum. Initially, total is 0. Add each
element in the list to total by using a loop like this:
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
total = 0 #initialized to zero
for row in matrix:
for value in row:
total = total + value
print “Total = “, total # Print the total
Output of the above program:
Total = 45
Note 1: For One dimensional list, we can do it very
easily as follows:
matrix = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
total = 0
for value in matrix:
total = total + value # same as total +=
value
print “Total = ”, total
will display
Total = 55
Note 2: If we used the built-in function, then,
matrix = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
print sum(matrix)
fig. 8.7 A two dimensional matrix showing the column with dotted line.
8.17 Two-Dimensional Lists 193
The distance between two points (x1, y1) and (x2, y2) can be computed
using the formula
distance between two points = √ (x2 - x1)2 + (y2 - y1)2
This can be done with the following program segment.
def distance(x1, y1, x2, y2):
return ((x2 - x1) * (x2 - x1) + (y2 - y1) * (y2 - y1)) ** 0.5
or
from math import sqrt
def distance(x1, y1, x2, y2):
return (sqrt((x2 - x1) * (x2 - x1) + (y2 - y1) * (y2 - y1)))
Next step is to find the nearest points from the given set of points. This can
be done with the help of the function, distances(x1, y1, x2, y2)
explain above. Another function nearestPoints(points)returns
the indexes of the two nearest points in the two-dimensional list points.
The program uses the variable shortestDistance to store the distance
between the two nearest points, and the indexes of these two points in the
points list are stored in p1 and p2. The following Python program explains
about this function.
def nearestPoints(points):
# p1 and p2 are the indexes in the points list
p1, p2 = 0, 1 # Initial two points
#Initialize shortestDistance =[0,0],[0,1]&[1,0],
[1,1]
198 Chapter 8 List
shortestDistance = distance(points[p1][0],
points[p1][1], points[p2][0], points[p2][1])
# Compute distance between every two points
for i in range(len(points)):
for j in range(i + 1, len(points)):
d = distance(points[i][0], points[i][1],
points[j][0], points[j][1])
if shortestDistance > d:
p1, p2 = i, j #Update p1, p2
shortestDistance = d #New shortestDistance
return p1, p2
In the above program, for each point at index i, the program computes the
distance between points[i] and points[j] for all j > i. Whenever
a shorter distance is found, the variable shortestDistance and p1 and
p2 are updated.
The complete program is shown below. The program prompts the user to enter
the points and then displays the nearest two points. The points are read from
the console and stored in a two-dimensional list named points. The program
invokes the nearestPoints(points) function to return the indexes of
the two nearest points in the list.
def distance(x1, y1, x2, y2):
return ((x2 - x1) * (x2 - x1) + (y2 - y1) * y2 -
y1)) ** 0.5
def nearestPoints(points):
# p1 and p2 are the indexes in the points list
p1, p2 = 0, 1 # Initial two points
#Initialize shortestDistance=[0,0],[0,1]&[1,0],
[1,1]
shortestDistance = distance(points[p1][0],
points[p1][1], points[p2][0], points[p2][1])
8.18 Application: Finding the Closest Pair 199
co_ordinates[i][j][k]
The above figure depicts the meaning of the values in the list.
A multidimensional list is a list in which each element is another list. More
specifically, a three-dimensional list consists of a list of two-dimensional
lists, and a two-dimensional list consists of a list of one-dimensional lists.
For example, co_ordinates[0] and co_ordinates[1] are two-
dimensional lists, while co_ordinates [0][1] co_ordinates [1][0],
and co_ordinates [1][1] are one-dimensional lists and each contains two
elements. len(co_ordinates) is 4, len(co_ordinates [0]) is 2, and
len(co_ordinates [0][0]) is 2.
8.19 Multidimensional Lists 201
def printMatrix(m):
for i in range(len(m)):
for j in range(len(m[i])):
for k in range(len(m[j])):
print m[i][j][k],
print
matrix1 = [
[[0, 0], [0, 1]],
[[0, 0], [0, 1]]
]
printMatrix(matrix1)
f(matrix1)
print “Matrix after adding a value:”
printM(matrix1)
Output of the above program:
0 0
0 1
0 0
0 1
202 Chapter 8 List
8.2. Given a list, list1 = [10, 11, 12, 13, 14], what is the list after
applying each of the following statements? Assume that each line of code is
independent.
list1.append(20)
list1.insert(1, 25)
list1.extend([21, 22])
list1.remove(3)
list1.pop(2)
list1.pop()
list1.sort()
list1.reverse()
random.shuffle(list1)
8.3. Given a list, list1 = [10, 11, 12, 13, 14], what is the list after
applying each of the following statements?
list1.index(1)
list1.count(1)
list1.count(list1)
sum(list1)
len(list1)
max(list1)
min(list1)
8.4. Given list1 = [10, 11, 12, 13, 14] and list2 = [18, 19,
20], what is the return value of each of the following statements?
list1 + list2
2 * list2
list2 * 2
list1[1 : 3]
list1[3]
8.5. How do you create an empty list and a list with the two integers
1 and 2?
8.6. Given list1 = [10, 11, 12, 13, 14, 0], how many elements
are in list1? What is the index of the last element in list1? What is
list1[2]? What is list1[-2]?
8.7. Write a function named shuffle1() to shuffle a list without using random.
shuffle (list1)method. Write a Python program that prompts the user
to enter a list of numbers, invokes the function to shuffle the numbers, and
displays the numbers.
8.8. Write a function find_gcd() that returns the greatest common divisor
(GCD) of integers in a list. Write a Python program that prompts the user to
enter five numbers, invokes the function to find the GCD of these numbers,
and displays the GCD.
204 Chapter 8 List
IntroduCtIon
A dictionary is a new concept in Python that stores a collection of key/value
pairs. The advantages of dictionary are it enables fast retrieval, deletion, and
updating of the value by using the key. This chapter describes the basics of
Dictionary. How to create dictionaries and common operations that used
frequently are explained with examples. Traversing keys in a dictionary using
a for loop, comparing whether two dictionaries have the same content or not
and commonly used methods are also described with examples. The concepts
of sets are also illustrate with examples.
9.1 defInItIon
In Python, A dictionary is defined as a collection of key and value
pairs. A dictionary is like a list, but it is more general. In a list, the indices
have to be “integers”; in a dictionary they can be (almost) any type. Mapping
Key Value
…
…
Key Value
between a set of indices (which are called keys) and a set of values is the
defining things about dictionary. In a dictionary, each key maps to a value. The
association of a key and a value is called a “key-value pair” or sometimes an
“ITEM” as shown in Fig. 9.1.
9.2 CreatIng a dICtIonary
We can create a dictionary by enclosing the items inside a pair of curly braces
({ }). Each item consists of a key, followed by a colon, followed by a value.
The items are separated by commas. For example, the following statement:
eng2hin = {‘one’ : ‘aek’}
creates a dictionary with one item. The item is in the form key : value. The key
is one, and its corresponding value is aek.
For example, let us build a dictionary that map from English to Hindi words,
so the keys and the values are all strings. The function dict()creates a new
empty dictionary. Dictionaries are like lists except that the “indices” need not
be integers—they can be values of any immutable type. Since they are not
ordered, we call them keys rather than indices. Literals of type dict() are
enclosed in curly braces, and each element is written as a key followed by a
colon followed by a value. Because dict()is the name of a built-in function,
we should avoid using it as a variable name.
>>> eng2hin = dict()
>>> eng2hin
{}
Another way to create an empty dictionary can be done as follows, without
using the dict( ) method:
eng2hin = { }
There are different ways for creating dictionaries. One of the examples of
nested dictionaries are as follows:
>>> nestDict = {‘first’: { 42: 1, type(‘ ‘): 2 },
‘second’: []}
Here nestDict is a nested dictionary. The first key has a dictionary value.
Another interesting property of Python is that we can use the type() function
as a key in the dictionary as shown in the above inner dictionary. Let us see
how to access the key a value pair of the nested directory.
>>> print nestDict # or >>> nestDict
{‘second’: [], ‘first’: {42: 1, <type ‘str’>: 2}}
>>> nestDict[‘first’][42] # will print
1
9.3 Adding, Modifying, and Retrieving Values 207
Some of the important ways to create dictionaries using the constructor dict
( ) are as follows:
>>> Dict2 = dict(name=’Bob’, age=45, job=(‘mgr’,
‘dev’))
>>> Dict2 # This will print in the following way:
{‘job’: (‘mgr’, ‘dev’), ‘age’: 45, ‘name’: ‘Bob’}
The point to be noted in the above example is that when we assign to a variable
i.e., age = 45, age becomes key and 45 is its value.
We can also use the zip( ) method to create a dictionary: type constructor.
>>> Dict3 = dict(zip(‘abc’, [1, 2, 3]))
>>> Dict3
{‘a’: 1, ‘c’: 3, ‘b’: 2}
We may create a dictionary by passing key/value pair with the dict( ) method:
>>> Dict4 = dict([[‘a’, 1], [‘b’, 2], [‘c’, 3]])
>>> Dict4
{‘a’: 1, ‘c’: 3, ‘b’: 2}
ord( ) method returns the corresponding ASCII(American Standard Code
for Information Interchange) value of the character. For example, ASCII value
for A is 65 and a is 97. We may use this method in creating dictionary as
follows:
>>> Dict5 = {c: ord(c) for c in ‘apple’}
>>> Dict5
{‘a’: 97, ‘p’: 112, ‘e’: 101, ‘l’: 108}
If the key is already in the dictionary, the following statement replaces the
value for the key.
>>> eng2hin[‘one’] = ‘aek’
>>> eng2hin
{‘one’: ‘aek’}
In general, the order of items in a dictionary is unpredictable. But that’s not a
problem because the elements of a dictionary are never indexed with integer
indices. For example,
>>> eng2hin = {‘one’ : ‘aek’, ‘two’ : ‘do’, ‘three’
: ‘teen’}
>>> eng2hin
{‘three’: ‘teen’, ‘two’: ‘do’, ‘one’: ‘aek’}
Again, we can use the keys to look up the corresponding values:
>>> eng2hin[‘two’]
do # no quotes
>>> eng2hin[‘three’]
teen # not eak as we think.
If the key isn’t in the dictionary, you get an exception:
>>> eng2hin[‘five’]
KeyError: ‘five’
Dictionary enables fast retrieval, deletion, and updating of the value by using
the key. The values in a dictionary don not have any particular order but are
stored under a key, which may be a number, a string, or even a tuple (we will
discuss tuple in the next chapter).
We can use the method keys() to return a list containing the keys of a
dictionary. For example,
>>> eng2hin.keys()
will print a list of the keys of the dictionary eng2hin, as follows.
[‘three’, ‘two’, ‘one’]
A dictionary is more appropriate than a list in many situations. Here are some
examples of uses of Python dictionaries:
• Representing the state of a game board, with each key being a tuple of
coordinates
• Storing file modification times, with file names as keys
• A digital telephone/address book
9.4 The Dictionary Methods 209
Note: The key can be any immutable type; strings and numbers can always
be keys. Tuples can be used as keys if they contain only strings, numbers,
or tuples; if a tuple contains any mutable object either directly or indirectly,
it cannot be used as a key. We can’t use lists as keys, since lists can be
modified in place using index assignments, slice assignments, or methods
like append() and extend().
table 9.1
methods Descriptions
len(d) returns the number of items (length) in d.
d.items() returns a sequence of tuples. Each tuple is (key, value) for an item.
d.pop(k) Removes the item for the key k from d and returns its value.
d.setdefault(k, v1) Same as d.get(k, v), but also assigns key to default if it is not found
in d.
dict.fromkeys()
Let us take up a few examples to show the use of the above methods in
dictionaries. Let us recall the above dictionary eng2hin
>>> eng2hin = {‘one’ : ‘aek’, ‘two’ : ‘do’, ‘three’
: ‘teen’}
To get the number of items (length)of the dictionary,
>>> len(eng2hin) # or print len(eng2hin)
3
The len() method returns the number of key-value pairs.
210 Chapter 9 Dictionaries
To get the values of a dictionary we can use the method values() as follows:
>>> vals = eng2hin.values() # No arguments in the
function call
>>> print vals
[‘teen’, ‘do’, ‘aek’]
One of the important methods of using in dictionary is the get() method. It
returns the corresponding value of the key, if the key is present (first argument).
Otherwise, it will show a message (from the second argument), as follows:
>>> eng2hin.get(‘one’, ‘Not found’)
aek
>>> eng2hin.get(‘four’, ‘Not found’)
Not found
We can omit the second argument. If we omit this, the get() method returns
None. For example:
>>> eng2hin.get(‘one’)
aek
>>> eng2hin.get(‘four’)
None
The advantage of “in” operator is that it tells you whether something appears
as a “key” in the dictionary (NOT values). For example:
>>> ‘one’ in eng2hin
True
>>> ‘eak’ in eng2hin
False
Note : The “in operator” uses different algorithms for lists and dictionaries.
For lists, it uses a search algorithm, as the list gets longer, the search time
gets longer in direct proportion. For dictionaries, Python uses an algorithm
called a “hash-table” that has a remarkable property.
The items() method returns the list of tuples. We can use this method in the
following way:
>>> eng2hin = {‘one’ : ‘aek’, ‘two’ : ‘do’, ‘three’
: ‘teen’}
>>> eng2hin
{‘three’: ‘teen’, ‘two’: ‘do’, ‘one’: ‘aek’}
>>> eng2hin.items()
[(‘three’, ‘teen’), (‘two’, ‘do’), (‘one’, ‘aek’)]
Note: Can you see the difference in the above example?
9.4 The Dictionary Methods 211
Again, if we want to clear the content of the directory, we can use the clear ()
method. It removes all items from the dictionary.
>>> eng2hin = {‘one’ : ‘aek’, ‘two’ : ‘do’, ‘three’
: ‘teen’}
>>> eng2hin.clear()
{}
Again invoking pop() method removes the item in the dictionary with the
corresponding key. The advantage of this method is that we can assign the
deleted value to a variable and can be reused again afterwards, if required.
>>> eng2hin = {‘one’ : ‘aek’, ‘two’ : ‘do’, ‘three’
: ‘teen’}
>>> x = eng2hin.pop(‘one’)
>>> eng2hin
{‘three’: ‘teen’, ‘two’: ‘do’}
>>> x
aek
Another method popitem() randomly returns a selected key/value pair as a
tuple and removes the selected item from the dictionary.
>>> eng2hin = {‘one’ : ‘aek’, ‘two’ : ‘do’, ‘three’
: ‘teen’}
>>> y = eng2hin.popitem()
>>> eng2hin
{‘two’: ‘do’, ‘one’: ‘aek’}
>>> y
(‘three’, ‘teen’)
To copy a dictionary to another dictionary, we can use the copy( ) method
as follows:
>>> eng2hin = {‘one’ : ‘aek’, ‘two’ : ‘do’, ‘three’
: ‘teen’}
>>> Dict7= eng2hin.copy()
>>> Dict7
{‘one’: ‘aek’, ‘three’: ‘teen’, ‘two’: ‘do’}
The getdefault( ) method is same as get( ) method. The advantage is
that it will also assign a key if it is not found in the dictionary.
>>> eng2hin = {‘one’ : ‘aek’, ‘two’ : ‘do’, ‘three’:
‘teen’}
212 Chapter 9 Dictionaries
>>> d1 != d2
False
In this example, d1 and d2 contain the same items regardless of the order of
the items in a dictionary.
Note : We cannot use the relational operators (>, >=, <=, and <) to compare
dictionaries because the items are not ordered as other sequences.
9.9 sets
Sets are use for storing a collection of elements. We can create a set of elements
by enclosing the elements inside a pair of curly braces ({ }) as we used in
dictionaries. The elements are also separated by commas. Unlike lists and
dictionaries, the elements in a set are non-duplicates and are not placed in any
particular order. When our application does not require about the order of the
elements, using a set to store elements is more efficient than using lists due to
Python’s implementations.
Now let us see how to use sets in the following examples.
We can create an empty set using the set() method
>>> s1 = set()
214 Chapter 9 Dictionaries
>>> print s1
set([])
Again we can create a set with four elements using the curly bracket, as follows:
>>> s2 = {1, 2, 3, 4}
>>> print s2
set([1, 2, 3, 4])
We also can create a set from a tuple:
>>> s3 = set((1, 2, 3, 4))
>>> print s3
set([1, 2, 3, 4])
In the same way, we can create a set from a given list:
>>> s4 = set([1, 2, 3, 4])
>>> print s4
set([1, 2, 3, 4])
# Another way to create a set from a list generated using a loop
>>> s5 = set([x * 2 for x in range(1, 10)])
>>> print s5
set([2, 4, 6, 8, 10, 12, 14, 16, 18])
One of the important properties of a set is that it is non-duplicate.
>>> s6 = set([1, 3, 3, 5, 5])
>>> print s6
set([1, 3, 5])
On the other hand, we can create a list or a tuple from a set by using the syntax
list(set) or tuple(set) respectively. For example,
>>> s7 = {1, 4, 7, 9} # not [1, 4, 7, 9]
>>> s8 = list(set(s7))
>>> print s8
[9, 7, 4, 1]
>>> s9 = (1, 4, 7, 9)
>>> s10 = tuple(set(s9))
>>> print s10
(1, 4, 9, 7)
9.10 Accessing Sets With Common Functions 215
We have seen that there are different ways for creating sets. We can also create
a set from a string. Each character in the string becomes an element in the set(if
no duplicate characters are there). For example:
>>> s11 = set(“abcabcd”)
>>> s11
set([‘a’, ‘c’, ‘b’, ‘d’])
Note that although the character a b and c appears twice in the string, it appears
only once in the set because a set does not store duplicate elements.
A set can also contain the elements of mixed data types. For example,
>>> s12 = {1, 2, 3, ‘a’, ‘b’, ‘c’}
>>> print s12
set([‘a’, 1, ‘c’, 3, 2, ‘b’])
Note: If the element is not in the set, the remove(e) method will throw a
KeyError exception.
Now, Let us consider two sets, s1 and s2. If s1 is a proper subset of s2, every
element in s1 is also in s2, and at least one element in s2 is not in s1.
If s1 is a proper subset of s2, then s1 < s2 returns True, as shown below:
>>> s1 = {1, 2, 3, 4}
>>> s2 = {1, 4, 5, 2, 6, 3}
>>> print s1 < s2
True
Note: the set attribute has no sort() method and indexing is also not
allowed in sets.
Again, if we want to use the less than or equal to operator (<=) in set, then
>>> s1 = {1, 2, 3, 4}
>>> s2 = {1, 2, 3, 4, 5, 6}
>>> print s1 <= s2 # Actually, the print keyword is
not needed
True
>>> s3 = {1, 2, 3, 4}
>>> s1 <= s3
False
In the above example, s1 <= s2 returns True because s1 is a subset of s2.
However, in the second example it returns False because s1 is not less than
s3.
If s1 is a proper superset of s2, the s1> s2 returns True, as follows:
>>> s1 = {1, 4, 5, 2, 6, 3}
>>> s2 = {1, 2, 3, 4}
>>> print s1 > s2
True
>>> print s1 >= s2
True
The statement s1 >= s2 also returns True because s1 is also a superset of s2.
methods meaning
union (or |) Return all the elements from both sets
intersection (or &) Return the elements that appear in both sets
difference (or –) Return the elements from first set only
symmetric difference (or ^) Return the elements contained in either set, but not in both
sets
The union of two sets is a set that contains all the elements from both sets.
We can use the union method or the | operator to perform this operation. For
example:
>>>s1 = {1, 2, 3, 4}
>>> s2 = {1, 5, 6, 7}
>>> print s1.union(s2)
set([1, 2, 3, 4, 5, 6, 7]) # same as {1, 2, 3, 4, 5,
6, 7}
>>> print s1 | s2 # Another way to use set union
{1, 2, 3, 4, 5, 6, 7}
The intersection of two sets is a set that contains the elements that appear in
both sets. We can use the intersection method or the & operator to perform
this operation. For example:
>>> s1 = {1, 2, 3, 4}
>>> s2 = {1, 5, 6, 7}
>>> print s1.intersection(s2) # set([1]) = {1}
{1}
>>> print s1 & s2 # Another way to use set intersection
{1}
The difference between set1 and set2 is a set that contains the elements in set1
but not in set2. We can use the difference method or the minus (–) operator to
perform this operation. For example:
>>> s1 = {1, 2, 3, 4}
>>> s2 = {1, 5, 6, 7}
>>> print s1.difference(s2)
set([2, 3, 4]) #same as {2, 3, 4}
>>> print s1 - s2 # Another way to call difference
method
set([2, 3, 4])
9.13 Set Operations 219
The symmetric difference (or exclusive- or) of two sets is a set that contains
the elements in either set, but not in both sets. You can use the symmetric_
difference method or the ^ operator to perform this operation. For example:
>>> s1 = {1, 4, 5, 2, 6, 3}
>>> s2 = {1, 2, 3, 4}
>>> print s1.symmetric_difference(s2)
set([5, 6])
>>> print s1 ^ s2
set([5, 6])# {5, 6}
Note that these set methods return a resulting set, but they do not change the
elements in the sets. For example:
>>> print s1
{1, 4, 5, 2, 6, 3}
>>> print s2
{1, 2, 3, 4}
Example 9.1: Illustrating the uses of Set
The following program illustrate the details of set in Python
set1 = {“Programming”, “Python”} # Create a set from
a string
print ‘set1=’, set1
eXerCIses
9.1. State the following are true or false.
(a) A dictionary can be used to store key/value pairs.
(b) The value in a dictionary can be retrieved using a key.
(c) The keys are like an index operator. In a list, the indexes are integers
only.
Exercises 221
(d) In a dictionary, the keys can be any hashable objects such as numbers
and strings.
(e) del () method can be used to delete an item for the given key.
(f) A while loop can be use to traverse all keys in a dictionary.
(g) The len() function returns the number of items in a dictionary.
(h) We can not use the in and not in operators to test if a key is in a dictionary.
(i) The operators == and != are used to test if two dictionaries are the same.
(j) Sets are like lists and use them for storing a collection of elements.
(k) The elements in a set are non-duplicates and are not placed in any
particular order.
(l) The add() method can be used to add an element to a set.
(m) The remove() method cannot use to remove an element from the list.
(n) The len, min, max, and sum functions can be applied to a set.
(o) A for loop can use to traverse the elements in a set.
9.2. Which of the following dictionaries are created correctly?
d = {1:[10, 20], 3:[30, 40]}
d = {[10, 20]:1, [30, 40]:3}
d = {(10, 20):1, (30, 40):3}
d = {1:”apple”, 3:”egg”}
d = {“apple”:1, “egg”:3}
9.3. Suppose a dictionary named mixed is {“apple”:3, “egg”:2}. What do the
following statements do?
(a) mixed[“tomato”] = 5
(b) mixed[“apple”] = 5
(c) mixed[“apple”] += 5
(d) del students[“apple”]
9.4. Suppose a dictionary named students is {“john”:3, “peter”:2}. What do the
following statements do?
(a) print(len(students))
(b) print(students.keys())
(c) print(students.values())
(d) print(students.items())
9.5. How to create an empty dictionary?
9.6. Each item in a dictionary has two parts. What are they called?
9.7. How do you create an empty set?
9.8. Can a list, set, or tuple have elements of different types?
222 Chapter 9 Dictionaries
10.1 defInItIon
In Python, A tuple is a sequence of immutable values. Tuples are sequences,
just like lists. The differences between tuples and lists are, the tuples cannot
be changed unlike lists and tuples use parentheses, whereas lists use square
brackets. Once a tuple is created, we cannot add new elements, delete elements,
or reorder the elements in the tuple.
Hence if there is no need to change the contents of a list, it is better to use a
tuple to prevent elements from being added, deleted, or replaced accidentally.
A tuple is very much like a list, except that its elements are fixed. Furthermore,
tuples are more efficient than lists due to Python’s implementations.
Syntactically, a tuple is a comma-separated list of values. For example:
>>> t1 = ‘a’, ‘b’, ‘c’,’d’
Although it is not necessary, it is common to enclose tuples in parentheses:
>>> t = (‘a’, ‘b’, ‘c’, ‘d’, ‘e’)
To create a tuple with a single element, we have to include a final comma:
>>> t1 = ‘x’,
>>> type(t1)
<type ‘tuple’>
If we omit comma, then a value in parentheses is not a tuple:
>>> t2 = (‘x’)
>>> type(t2)
<type ‘str’>
226 Chapter 10 Tuples
Like strings, tuples are ordered sequences of elements. The difference is that
the elements of a tuple need not be characters. The individual elements can be
of any type, and need not be of the same type. For example:
>>> t3 = (1, ‘two’, 3, ‘four’)
We can use either single or double quotes for representing strings in tuples.
For example:
>>> t4 =‘a’,’b’,’c’
>>> print t4
(‘a’, ‘b’, ‘c’)
>>> t5 = “a”,“b”,“c”
>>> print t5
(‘a’, ‘b’, ‘c’)
Another way to create a tuple is to use the built-in function tuple, known as
Python objects. With no argument, we can create an empty tuple:
>>> t6 = tuple()
>>> print t6
()
If the argument is a sequence (string, list or tuple), the result is a tuple with the
elements of the sequence:
>>> t7 = tuple(‘Python’) # using strings as elements
>>> print t7
(‘P’, ‘y’, ‘t’, ‘h’, ‘o’, ‘n’)
>>>t8 = tuple([‘P’,’y’,’t’,’h’,’o’,’n’])#using list
as arguments
>>> print t8
t9 = tuple([1,2,3,4,5]) # using list of numbers as
arguments
>>> print t9
>>> t10 = tuple((‘T’,’e’,’s’,’t’))# tuple as arguments
>>> print t10
(‘T’, ‘e’, ‘s’, ‘t’)
Tuple is the name of a built-in function, so we should avoid using it as a
variable name, though this is not an error. For example:
>>> tuple = 123 # must be avoided
10.1 Definition 227
Most of the list operators also work on tuples. Like list indices, tuple indices
start at 0, and they can be sliced, concatenated, and so on. For example:
>>> t11 = (1, ‘two’, 3,‘four’)
>>> t12 = (t11, 5.75)
>>> print t12
((1, ‘two’, 3, ‘four’), 5.75)
In the above example, the second assignment statement binds the name t12 to
a tuple that contains the tuple, t11 and the float 5.75. This is possible because a
tuple, like everything else in Python, is an object, so tuples can contain tuples.
>>> t13 = (t11 + t12)
>>> print t13
(1, ‘two’, 3, ‘four’, (1, ‘two’, 3, ‘four’), 5.75)
The above statement prints the expression generated by concatenating the
values bound to t11 and t12, which is a tuple with six elements (not nine
elements).
>>> print t13[3]
four
>>> print t13[4]
(1, ‘two’, 3, ‘four’)
The statement t13[3] prints the fourth element (as always in Python, indexing
starts at 0), and t13[4] prints the fifth elements, here it is a tuple, of the
concatenated tuple.
The following statement creates and prints a slice of that tuple:
>>> print t13[2:5]
(3, ‘four’, (1, ‘two’, 3, ‘four’))
Note: The main difference between lists and tuples is that the elements in a
list can be changed but not in a tuple. This means a list might be more useful
when elements are to be added or removed. But a tuple can be useful when
there is no need for a change the sequence. Reasons for the latter are usually
rather technical, because, some built-in functions return tuples. Tuples are
used as dictionary keys but not lists, because the keys cannot be modified.
If we try to modify one of the elements of the tuple, we get an error:
>>> t14 = (‘a’, ‘b’, ‘c’, ‘d’)
>>> t14[0] = ‘A’
TypeError: object doesn’t support item assignment
228 Chapter 10 Tuples
While the elements of a tuple cannot be modified but the elements of one tuple
can be replaced with the elements of another. For example:
>>> t14 = (‘A’,) + t14[1:]
>>> print t14
(‘A’, ‘b’, ‘c’, ‘d’)
Note: Sometimes nested tuples may be confusing. So to get rid of nested
tuples, we can use as follows:
>>> t11 = (1, ‘two’, 3,‘four’)
>>> t12 = t11 + (5.75,)
>>> print t12
(1, ‘two’, 3, ‘four’, 5.75)
The + sign can only concatenate tuple (not “float”) to tuple. So we have to
convert the float value to a tuple.
Operation Description
x in tuple, t True if element x is in tuple, t.
x not in tuple, t True if element x is NOT in tuple, t.
t1 + t2 Concatenates two tuples t1 and t2
t * n or n * t n copies of tuples t are concatenated.
t[ i ] ith element in tuple, t
t[ i : j ] slices of tuple, t from index i to j–1.
len(t) returns the length of the tuple, t.
min(t) returns the smallest element in tuple, t.
max(t) returns the largest element in tuple, t.
sum(t) returns the sum of all numbers in tuple, t.
for loop Traverse elements from left to right in a for loop.
Relational operators:
Compares two tuples
<, <=, >, >=, ==, !=
cmp(t1, t2) Compares two tuples (or objects) t1 and t2
Note: We can create a list from a tuple using the list() method:
>>> list1 = list(t3)
>>> print list1
[1, 2, 3, 4, 5, ‘a’, ‘b’, ‘c’]
We can use the sort() function in a list, but not
in a tuple :
>>> list1.sort()
Tuples have fixed elements which mean that we cannot add new elements,
delete elements, replace the elements, or shuffle the elements in a tuple.
Some special cases:
As we mentioned that a tuple contains a fixed list of elements. An individual
element in a tuple may be mutable.
For example, the following code creates a tuple of circles, and changes the
first circle’s radius to 15.
>>> from CircleFromGeometricObject import Circle
>>> circles = (Circle(5), Circle(8), Circle(10))
>>> circles[0].setRadius(15) # change to 15
>>> circles[0].getRadius() # show the radius
15
Again cmp(t1, t2) compares two tuples and return an integer according
to the outcome. The return value is positive if t1 > t2, zero if t1
== t2 and negative if t1 < t2.
>>> t1 = [“python”]
>>> t2 = [“high”]
>>> print is_match(t1, t2)
False
result = []
for length, word in t:
result.append(word)
return result
# First Run
words = [ ‘abcd’, ‘pqr’, ‘ijklmnop’, ‘a’, ‘university’]
r = sort_by_length(words)
print r
# Second Run : To show the tie break condition
words1 = [ ‘abcd’, ‘pqrs’,’a’, ‘g’]
r1 = sort_by_length(words1)
print r1
Output of the above program:
# output of the first run
[(4, ‘abcd’), (3, ‘pqr’), (8, ‘ijklmnop’), (1,
‘a’), (10, ‘university’)]
[‘university’, ‘ijklmnop’, ‘abcd’, ‘pqr’, ‘a’]
eXerCIses
10.1. State whether the following are true or false.
(a) A tuple is like a fixed list. We cannot add, delete, or replace elements in
a tuple.
(b) Since a tuple is a sequence, the common operations for sequences can be
used for tuples.
10.7 Relationships between Dictionaries and Tuples 239
10.12. Find out errors (if any) in the following code segment?
t1= (1,2,3)
print sum(t1)
print sum(1,2,3)
print sum((1,2,3))
10.13. Write a program that reads a list of words and prints all the sets of words that
are anagrams.
Here is an example of what the output might look
like:
[‘deltas’,’desalt’, ‘lasted’, ‘salted’, ‘slated’,
‘staled’]
[‘retainers’, ‘ternaries’]
[‘generating’, ‘greatening’]
[‘resmelts’, ‘smelters’, ‘termless’]
Hint: you might want to build a dictionary that maps from a set of letters to
a list of words that can be spelled with those letters. The question is, how can
you represent the set of letters in a way that can be used as a key?
10.14. Modify the previous program so that it prints the largest set of anagrams first,
followed by the second largest set, and so on.
10.15. What are the differences between a list and a tuple? How do you create a tuple
from a list? How do you create a list from a tuple?
11
files
11.1 IntroduCtIon
This chapter will describe how to read and write data from and to a file. Data
used in a program is temporary and it is lost when the program terminates
unless the data is specifically saved. To permanently store the data created in a
program, we need to save it in a file on a disk or some other permanent storage
devices. The file can be transported and read later by other programs.
In Chapter Four, we read values from the input device using input(),
raw_input(), and printing with print() methods. In this chapter, we
go one step further and let our programs catch a glimpse of the world of files
and streams.
Other programs are persistent means they run for most of the time; they keep
at least some of their data in permanent storage and when they shut down and
restart, they pick up where they left off. Examples of persistent programs are
operating systems, which run pretty much whenever a computer is on, and web
servers, which run all the time, waiting for requests to come in on the network.
One of the simplest ways for programs to maintain their data is by reading and
writing text files.
Although it is not technically precise and correct, we can envision a text file
as consisting of a sequence of characters and a binary file as consisting of
a sequence of bits. Characters in a text file are encoded using a character
encoding scheme such as ASCII and Unicode. For example, the decimal
integer 123 is stored as the sequence of the three characters 1, 2, and 3, in a
text file, and the same integer is stored as a byte-type value 7B in a binary file,
because decimal 123 equals hex 7B (7 × 16 + 11) The advantage of binary files
is that they are more efficient to process than text files. However, Computers
do not differentiate between binary files and text files. All files are stored in
binary format, and thus all files are essentially binary files. Text IO (input and
output) is built upon binary IO to provide a level of abstraction for character
encoding and decoding.
11.3 aBsoLute and reLatIVe fILename
A file is placed in a directory (also called “folder”) in the file system. An
absolute filename contains a filename with its complete path and drive letter.
For example, C:\Documents and Settings\Python\Output.txt is the absolute
filename for the file Output.txt on the Windows operating system. Here, C:\
Documents and Settings\Python is referred to as the directory path to the file.
Absolute filenames are machine dependent. On the UNIX or Linux platform,
the absolute filename may be /home/ Python/Output.txt, where /home/ Python/
is the directory path to the file Output.txt.
A relative filename is relative to its current working directory. The complete
directory path for a relative file name is omitted. For example, File1.py is
a relative filename. If its current working directory is C:\Documents and
Settings\Python, the absolute filename would be C:\Documents and Settings\
Python\File1.py.
Every running program has a “current directory,” which is the default directory
for most operations. For example, when you open a file for reading, Python
looks for it in the current directory.
The os module provides functions for working with files and directories (“os”
stands for “operating system”). os.getcwd returns the name of the current
working directory. For example:
>>> import os
>>> cwd = os.getcwd()
>>> print cwd
/home/Python
cwd stands for “current working directory.” The result in this example is /
home/Python, which is the home directory of a user named Python. A string
like cwd that identifies a file is called a path.
11.4 Opening a File 245
mode Description
w Opens a file for writing. If the file is already exits, its old contents are clears out.
a Opens a file for appending data from the end of the file.
For example, to write a file, we have to open it with mode ‘w’ as a second
parameter:
>>> fout = open(‘Output.txt’, ‘w’)
>>> print fout
<open file ‘Output.txt’, mode ‘w’ at 0x04050288>
If the file already exists, opening it in write mode clears out the old data and
starts fresh, so we should be careful. If the file doesn’t exist, a new one is
created.
To read a file in the current directory, the following statement opens a file
named Output.txt:
>>> fin = open(“Output.txt”, “r”)
we can also use the absolute filename to open the file in Windows, as follows:
input=open(r“ C:\Documents and Settings\Python\
Output.txt ”, “r”)
The statement opens the file ‘Output.txt’that is in the C:\Documents
and Settings\Python directory for reading. The r prefix before the
absolute filename specifies that the string is a raw string, which causes the
Python interpreter to treat backslash characters as literal backslashes. Without
the r prefix, we would have to write the statement using an escape sequence
as follows:
input=open(“C:\\Documents and Settings\\Python\\
Output.txt”,”r”)
The ‘+’ can be added to any of the other modes to indicate that both reading
and writing is allowed. So, for example, ‘r+’ can be used when opening a text
file for reading and writing.
11.5 Writing Data 247
The program opens a file named Test1.txt using the w mode for writing
data. If the file does not exist, the open()methods creates a new file. If the
file already exists, the contents of the file will be overwritten with new data.
When a file is opened for writing or reading, a special marker called a file
pointer is positioned internally in the file. A read or write operation takes place
at the pointer’s location.
When a file is opened, the file pointer is set at the beginning of the file. When
we read or write data to the file, the file pointer moves forward.
248 Chapter 11 Files
Figure 11.1 shows the position of the file pointer after each write.
Most of the innocent people\n
File Pointer
in this world are small children\n
and drunk people.\n
fig. 11.1 Showing the position of the file pointer when writing to the file.
Contd...
11.6 Some commonly used methods for File handling 249
The best way to read a text file line by line is to not read it at all—instead,
allow the for loop to automatically advance to the next line on each iteration.
The file object’s iterator will do the work of automatically loading lines as we
go. The following example reads a file line by line and printing the uppercase
version of each line along the way, without ever explicitly reading from the
file at all:
for line in open(‘test4.txt’):
print line.upper(),
#print(line.upper(), sep = ‘,’, end =‘ ’)
Notice that the print uses end =’ ‘ here to suppress adding a newline,
\n, because line strings already have one (without this, our output would be
double-spaced). However, these sep = ‘,’ and end =‘ ’ are not
supported in Python 2.7. The easiest way to solve this problem in Python 2.7
is to use the comma operator. The best way to read text files is line by line
since: it’s the simplest way to code, it might be the fastest to run, and is the
most efficient of memory usage.
On the other hand, the older, original way to achieve the same effect with a for
loop is to call the file readlines() method to load the file’s content into
memory as a list of line strings:
for line in open(‘test4.txt’).readlines():
print(line.upper())
Note: When we run the following program segment, we get the output with
newlines, as follows:
>>> for i in range(5):
... print i
...
0
1
2
3
4
250 Chapter 11 Files
line = replacePunctuations(line)
words = line.split()
for word in words:
if word in wordCounts:
wordCounts[word] += 1
else:
wordCounts[word] = 1
eXerCIses
11.1. State whether the following are true or false:
(a) A file must be opened before it can be used.
(b) All files must be explicitly closed.
(c) Using seek() method we can start reading the file from the beginning.
(d) When an existing file is open using w mode, the contents of the file are
deleted.
(e) It is an error to open a file for reading when it does not exist.
(f) The read() and readline() methods can be used to read data from a file.
(g) The write() method is used to write only strings to a file.
(h) The readlines() methods can not used in reading integer values from a
file
q.write(‘Khan\n’)
q.write(‘Singh’)
q.close()
q = open(‘Names.txt’, ‘r’)
for line in q:
print line[:-1]
q.close()
11.3. Using the file ‘Names.txt’ opened in ex.11.1, write the outputs of the
following program segments:
(a) p = open(‘Names.txt’, “r”)
str1= p.read(3)
print str1
(b) p = open(‘Names.txt’, “r”)
str1= p.read()
print str1
(c) p = open(‘Names.txt’, “r”)
str1= p.readline()
print str1
(d) p = open(‘Names.txt’, “r”)
str1= p.readlines()
print str1
11.5. Using the file ‘test4.txt’ opened in ex.11.3, justify the outputs of the following
program segments:
(a) for line in open(‘test4.txt’):
print line.upper() # No Comma
(b) for line in open(‘test4.txt’):
print line.upper(), # with Comma
256 Chapter 11 Files
11.6. The following program open a file called myfile.txt. Then we write only
two lines of strings in the file. And we want to see the contents of the file using
readline() method. By calling readline() method 3 times, can we see
the output correctly? Justify your answer.
file1 = open(‘myfile.txt’, ‘w’)
file1.write(‘Welcome to File\n’)
file1.write(‘handling in Python\n’)
file1.close()
file1 = open(‘myfile.txt’)
file1.readline()
file1.readline()
file1.readline()
11.7. What is the output of the following program? Assume that the file datafile.
txt is already exists in the directory ‘C:\Python.
import pprint
pprint.pprint(open(r’C:\Python\somefile.txt’).
readlines())
11.8. How do you open a file for reading, for writing, and for appending,
respectively?
11.9. What is wrong about creating a file object using the following statement?
File1 = open(“c:\python\test.txt”, “r”)
11.10. When you open a file for reading, what happens if the file does not exist?
11.11. What happens when you open a file for writing, if the file already exists?
11.12. What method do you use to read all data from a file into a string?
11.13. What method do you use to read a line?
11.14. What method do you use to read all lines from a file into a list?
11.15. What function do you use to write data to a file?
11.16. How do you determine whether a file exists or not?
11.17. How do you write and read numeric data?
11.18. How do you denote a raw string literal in the program?
11.19. When reading data, how do you know if it is the end of the file?
11.20. Will your program have a runtime error if you invoke read() or readline() at
the end of the file?
11.21. Write a Python program to copy the contents of one file to another file.
Exercises 257
11.22. Write a Python program that compares two files and return True if they are
equal and False if they are not equal. Do not use built in function cmp().
11.23. Write a Python program that appends one file at the end of the another file.
11.24. Write a Python program that reads a file containing integers and appends at its
end the sum of all the integers.
11.25. Write a program that removes all the occurrences of a specified string from a
text file. The program should prompt the user to enter a filename and a string
to be removed.
11.26. Write a program that will count the number of characters, words, and lines in
a file. Words are separated by a white space character.
12
Computational Physics–
Application in Physical Systems
12.1 IntroduCtIon
Physics is a corner-stone of every technological field. When we have a solid
understanding of physics, and the computational know-how to calculate
solutions to complex problems, success is sure to follow us in the high-tech
environment of this century. In this chapter we give a brief introduction to
Computational Physics and how it can be used in solving simple to complex
physical systems with specific Python implementation. A brief idea on how
to use Monte Carlo Technique and Runge-Kutta fourth order method to solve
physical problems with Python is also given.
When the mass reaches the equilibrium position it overshoots i.e., it keeps
on going and stops at some point in the opposite direction. Once again it
proceeds for its return trip. This to and fro motion is called oscillation.
An interesting aspect of this motion is that this system oscillates with a
fixed frequency whatever amplitude you may give to it.
The force law for this motion is
F = – kx (1)
where F represents the restoring force (implied by negative sign), and k is the
intrinsic property of the spring. The equation of motion of the mass can be
obtained by applying Newton’s law of motion as
ma= – kx (2)
1/2
k
We define w0 = which is called the natural angular frequency of
m
the system.
Solving with Numerical Method:
If we know the initial conditions, i.e., displacement and velocity at some
instant t, we can find these quantities at all the times. Given the eq. (2), the
velocity can be written as
2
v(t) = −ω 0 ∫ x (t ) dt
And displacement then can be calculated as
x(t) = ∫ v (t )dt = ω 02 ∫ ∫ x (t ) dt dt
which has an integrand we don’t know as yet. So what are we to solve?
For the case of the loaded spring, we can guess what would be the solution i.e.
either x(t) = cos (w0t) or x(t) = sin (w0t)
or more generally
x (t) = A cos (ω0t) + Bω0 (3)
where A and B are two unknown parameters. Obviously, this is not the unique
solution and initial conditions are needed to fix the parameters. Let the initial
conditions be:
x(t) = x0 and v(t) = v0 at t = 0 (4)
This yields,
v0 dx(t)
A = x0, B = Q v(t) = using eq. (3)
w0 dt
Another form of the solution may be written as
x (t) = A cos (ω0t + φ)
where A and φ are constants called amplitude and phase respectively. These
can also be fixed by the initial conditions of eq. (4).
262 Chapter 12 Computational Physics – Application in Physical Systems
The program can be run with the required inputs. Here is the sample data that
we entered of our choice.
Spring constant = 1 Nm–1 Mass of the object = 1 kg
Initial position =0m Initial velocity = 1 m s –1
Time step = 0.01 s Maximum time = 10 s
Output of the above program:
FIRST RUN: SECOND RUN:
Enter the value of Spring constant: 2 Enter the value of Spring constant:1
Enter the initial position:0 Enter the initial position:0
Enter the initial velocity of the Enter the initial velocity of the
particle:3 particle:1
Enter the mass of the particle:1 Enter the mass of the particle:1
Enter the maximum time:20 Enter the maximum time:10
Enter the time step:0.01 Enter the time step:0.01
264 Chapter 12 Computational Physics – Application in Physical Systems
2
Q) Q) 0.5
u u
C C
.l!l 0 0.0
en ~
i5 -1 i5 -0.5
-2 -1 .0
-3 -1 .5
0 5 15 0 2 4 6 8 10
10 20
nme
nme
There are three distinct situations which can be identified for a damped
oscillator:
undamped (when c = 0)
c2 k
over-damped (when 2 > ) and
4m m
c2 k
critically damped when 2 =
4m m
Python Implementation
Next step is to implement a Python program using this algorithm. Most of the
codes are almost same with the Simple Harmonic Oscillator as we have done
earlier except the damping coefficient. In our program we used a new function
subplot() to draw the graph in to rows.
The complete Python program is shown below:
import pylab as pl
k = input(“Enter the value of Spring constant :”)
x = input(“Enter the initial position :”)
v = input(“Enter the initial velocity of the particle:”)
m = input(“Enter the mass of the particle :”)
tmax = input(“Enter the maximum time :”)
h = input(“Enter the time step :”)
c = input(“Enter the damping constant :”)
t = 0
a = 0
X = []
T = []
V = []
while (t <= tmax) :
a = -(k*x)/m - (c*v)
X.append(x)
T.append(t)
V.append(v)
v = v + a*h
x = x + v*h
t = t + h
pl.subplot(2,1,1)
pl.plot(T,X)
pl.xlabel(“Time”)
pl.ylabel(“Distance”)
pl.title(“Time vs Distance”)
pl.axhline(0, 0, 1)
pl.subplot(2,1,2)
12.3 Oscillatory Motion 267
pl.plot(X, V, ‘r’)
pl.xlabel(“Distance”)
pl.ylabel(“Velocity”)
pl.title(“Distance vs Velocity”)
pl.axhline(0, 0, 1)
pl.axvline(0, 0, 1)
pl.show()
The above program have executed with the parameters which are shown below:
Spring constant = 1Nm–1 Mass of the object = 1 kg
Damping coefficient = 0.5 N m–1s Initial position =0m
Initial velocity = 1 m s–1 Time step h = 0.01s
Maximum time = 20 s
Output of the above program is shown below. The second graph
shows the Phase space trajectory.
Enter the value of Spring constant :1
Enter the initial position :0
Enter the initial velocity of the particle:1
Enter the mass of the particle :1
Enter the maximum time :20
Enter the time step :.01
Enter the damping constant :.5
Time vs distance
0.8
0.6
(I) 0.4
0
C
0.2
.l9
(J)
0 0.0
-0.2
-0.4
0 5 10 15 20
Distance vs velocity
1.0
0.5
z,
·u
0
0.2
~
-0.5
-0.4 -0.2 0.0 0.2 0.4 0.6 0.8
Distance
268 Chapter 12 Computational Physics – Application in Physical Systems
Note: Two basic plot types which you will find are used very often are (x, y)
line and scatter plots. Some code for making these two types of plots is as
follows:
A. For line Plot B. For scattered Plots
1. import numpy as np By changing the line
2. import pylab as pl number 8 with the fol-
3. # Make an array of x
lowing code, we can get
values
scattered graph very
easily.
4. x = [1, 2, 3, 4, 5]
5. # Make an array of y pl.plot(x, y, ’ro’)
values
6. y = [1, 4, 9, 16, 25]
7. # use pylab to plot x This will plot x and y
and y as red circles
8. pl.plot(x, y)
9. # show the plot on the
screen
10. pl.show()
12.4.1 Introduction
In 1926, SchrÖdinger presented a phenomenological wave theory
to describe the microscopic world and laid the foundation of wave
mechanics. According to this theory, the wave equation is defined as,
h2
– ∇y (x, t) = [E – V(x, t)] – y(x, t) (1)
2m
This second order differential equation in essence describes the one
dimensional non-relativistic motion of a particle of mass m and energy E
in a potential V(x, t). Without V(x, t) this equation describes free particle
motion quantum mechanically. Inclusion of V(x, t) indirectly accounts for the
interaction among particles in a force field in which the particle is moving.
The function y(x, t) denotes the wavefunction of the particle, properties of
which are described completely by the Schrodinger equation only when
suitable boundary conditions along with the continuity condition are imposed.
12.4 Stationary States and Time Independent SchrÖdinger Equation 269
0 for | x | ≤ a
(b) Square Well potential: V(x) =
V0 for | x | > a
V (x) =.!.loc2
2
V(x) ={O for lxl $ a
V0 for lxl > a
-a +a
(a) Parabolic potential (b) Square well Potential
0 for | x | ≤ a
(c) Hard Sphere Potential: V(x) =
∞ for | x | > a
-a 0 a X 0 X
,,,,,,
11 I I
11
I I
I I
I I
,,
,,,,,,
II
11
,,,,
11
0 X
(e) L-J (6-12) Potential (f) Master Potential
present value and the previous value, in which the true energy eigenvalue lies.
Once this range is determined, we repeat the run with smaller energy increment
and narrow down the energy interval in which the true eigenvalue lies.
The Algorithm employing this method is given below:
1
Step 1 : Define potential V(x) = – 2 x2
Step 2 : Choose maximum range for x.
Step 3 : Choose parity of the wavefunction: odd/even.
Step 4 : Guess energy eigenvalue.
Step 5 : Choose step size, h.
Step 6 : Choose initial value of the wavefunction and its first derivative
according to the choice of parity of the wavefunction.
Step 7 : Begin loop over x.
Step 8 : Let ϕ and ϕ′ denote the wavefunction and its derivative at some
position, say x. Determine fourth-order Runge-Kutta coefficients:
k1 = ϕ′
p1 = –2[E – V(x)]ϕ
1
k2 = ϕ′ + 2 p1h
1 1
p2 = – E − V x + h ϕ + k1h
2 2
1
k3 = ϕ′ + 2 p2h
1 1
p3 = – 2 E − V x + h ϕ + k2 h
2 2
k4 = ϕ′ + p3h
p4 = – 2[E – V (x + h)] (ϕ + k3h)
Python Implementation
A program based on this algorithm is given below, which plots the
eigenfunction vs. x for the harmonic oscillator potential ( To be Verify again)
# using 4th order Runge-Kutta method
import pylab as pl
SIZE = 5000
FLAG = 0
def POTFN(x):
return (0.5*x*x)
while(1):
parity = raw_input(“Choose parity of state
desired: ODD/EVEN := ”)
parity = parity.lower()
n=len(parity)
if (parity != “odd” or parity != “even”):
print ‘parity= ‘,parity
break
else :
print “Enter parity again :”
if parity != “odd” :
phi=1.0
phi_prime=0.0
else :
phi=0.0
phi_prime=1.0
phi=0.0 # The Odd parity condition
phi_prime=1.0
xmax = input(“Enter maximum x:”)
h = input(“Enter the step size :”)
E_Guess = input(“Enter the Guess Energy of the State
:”)
xmin=0.0
X=[]
E=E_Guess
274 Chapter 12 Computational Physics – Application in Physical Systems
phiold= []
Phi_prime = []
while E_Guess <=1.51:
while xmin<xmax :
k1=phi_prime
p1=2.0*(POTFN(xmin)-E)*phi
k2=phi_prime + 0.5*p1*h
p2=2.0*(POTFN(xmin+0.5*h)-E)*(phi+0.5*k1*h)
k3=phi_prime + 0.5*p2*h
p3=2.0*(POTFN(xmin+0.5*h)-E)*(phi+0.5*k2*h)
qk4=phi_prime + p3*h
p4=2.0*(POTFN(xmin+h)-E)*(phi+k3*h)
phi=phi+h*(k1+2*k2+2*k3+k4)/6.0
phi_prime += h*(p1+2*p2+2*p3+p4)/6.0
phiold.append(phi)
Phi_prime.append(phi_prime)
xmin=xmin+h;
X.append(xmin)
#print ‘X=’,X,
#print ‘length =’, len(X)
#print ‘phiold =’, phiold,
#print ‘length1=’, len(phiold)
print ‘Energy = ’, E_Guess
pl.plot(X, phiold)
pl.show()
E_Guess += .1
E = E_Guess
print ‘Energy = ’, E_Guess
We run the program again to find the energy eigenvalue of the
harmonic oscillator. In Fig. 1, we show the graphs of the wavefunctions
obtained for different trial energies. We determine the wavefunction at
different lattice points. By suitable modification of the above program,
numerical output can be obtained. These are displayed in Table 12.1
for the following choice of the parameters:
Parity of state = even
Maximum x = 10
table 12.1
275
10 7 3.36E+17 5.11E+17 6.76E+17 6 1.52E+17 2.47E+17 5.60E+16 -1.14E+17 2.73E+15 1.69E+16
276 Chapter 12 Computational Physics – Application in Physical Systems
-j-----ae==::=::~~~~~===
1.475
~ O.OOE+016
1.178
1.472
~ -5.00E+016
>
~ -1 .00E+017
-1 .50E+017
-2.00E+017
-2.50E+017
-3.00E+017 -+------.----r----.------.-----r---.-~----1
9.4 9.6 9.8 10.0
Distance (X)
Wave function for 1 dimensional
H.O with narrowed down range
1.00E+015
1.4721 ai
1.4722 "-
'<I:
1.4723
5.00E+014 1.4724 .9
1.4725
1.4726
r::'<I:
C: 1.4727
0 II
0.00E+000 1.4728
~ w
C: 1.4729
<Ii
~ Q)
Q) :::,
> -5.00E+014 iii
>
~ >,
e>
Q)
C:
Q)
-1 .00E+015
0
iii
:s
-1.50E+015 Jg
9.2 9.3 9.4 9.7 9.8 9.9 10.0 £
9.5 9.6
Distance (X)
fig. 12.2
12.5 Fractals 277
12.5 fraCtaLs
It is common in nature to notice objects, called fractals, that do not have well-
defined geometric shapes, but nevertheless appear regular and pleasing to the
eye. These objects have dimensions that are fractions, and occur in plants,
sea shells, polymers, thin films, colloids, and aerosols. We will not study the
scientific theories that lead to fractal geometry, but rather will look at how
some simple models and rules produce fractals. To the extent that these models
generate structures that look like those in nature, it is reasonable to assume that
the natural processes must be following similar rules arising from the basic
physics or biology that creates the objects.
12.5.1 fractional dimension (math)
Benoit Mandelbrot, who first studied the fractional-dimension figures with
the supercomputers at IBM Research, gave them the name fractal. Some
geometric objects, such as the Koch curves, are exact fractals with the same
dimension for all their parts. Other objects, such as bifurcation curves, are
statistical fractals in which elements of randomness occur and the dimension
can be defined only locally or on the average.
Consider an abstract “object” such as the density of charge within an atom.
There are an infinite number of ways to measure the “size” of this object,
for example; each moment of the distribution provides a measure of the
size, and there are an infinite number of moments. Likewise, when we deal
with complicated objects that have fractional dimensions, there are different
definitions of dimension, and each may give a somewhat different dimension.
In addition, the fractal dimension is often defined by using a measuring box
whose size approaches zero. In realistic applications there may be numerical
or conceptual difficulties in approaching such a limit, and for this reason a
precise value of the fractional dimension may not be possible.
Our first definition of fractional dimension df (or Hausdorf–Besicovitch
dimension) is based on our knowledge that a line has dimension 1; a triangle,
dimension 2, and a cube, dimension 3. It seems perfectly reasonable to ask
if there is some mathematical formula, which agrees with our experience for
regular objects, yet can also be used for determining fractional dimensions.
For simplicity, let us consider objects that have the same length L on each side,
as do equilateral triangles and squares, and which have uniform density.
The dimension of an object is determined by the dependence of its total mass
upon its length:
df
M(L) ∝ L (1)
where the power df is the fractal dimension. As you may verify, this rule works
with the 1D, 2D, and 3D regular figures of our experience, so it is a reasonable
278 Chapter 12 Computational Physics – Application in Physical Systems
where ri is a random number between 0 and 1, and where the integer function
outputs the closest integer smaller than, or equal to, the argument. After 15,000
points, you should obtain a collection of dots like Fig. 12.4.
Python Implementation of Sierpinsky Implementation :
import pylab as pl
import random
max_iteration = 30000 # number of iterations
a1 = 20.0 # vertex 1
b1 = 20.0
a2 = 320.0 # vertex 2
b2 = 20.0
a3 = 170.0 # vertex 3
b3 = 280.0
pl.plot(x,y,’.’)
pl.title(‘Sierpinski Gasket for 30000 points’)
pl.show()
280 Chapter 12 Computational Physics – Application in Physical Systems
250 250
200 200
150 150
100 100
50 50
We see that as we continue the construction process, the density of each new
structure is ¾ that of the previous one. This is unusual. Yet in eqn. (2) we have
derived that
d –2
r ∝ CL f
(4)
Equation (2) implies that a plot of the logarithm of the density ρ the logarithm
of the length for successive structures, yields a straight line of slope:
D log r
df – 2 =
D log L
As applied to our problem:
3
D log r (L) log1 − log
4
df = 2 + D log L = 2 +
log1 − log 2
= 1.58494
As is evident in Fig. 1b, as the gasket gets larger and larger (and consequently
more massive), it contains more and more open space. So even though its
mass approaches infinity as L → ∞, its density approaches zero! And since a
two-dimensional figure like a solid triangle has a constant density as its length
increases, a 2D figure would have a slope equal to 0. Since the Sierpinski
gasket has a slope df – 2 ≅ −0.41504, it fills space to a lesser extend than a 2D
object, but more than does a 1D object; it is a fractal.
fig. 12.5
2% r < 0.02
15% 0.02 ≤ r ≤ 0.17
(B)
P=
13% 0.17 < r ≤ 0.3
70% 0.3 < r <1
The above two equations (A) and (B) can be combined into one as follows:
Although Eqn. (A) makes the basic idea clearer, Eqn. (C) is easier to program.
The starting point in Barnsley’s fern (Fig. 12.5) is (x1, y1) = (0.5, 0.0), and
the points are generated by repeated iterations. An important property of this
fern is that it is not completely self-similar, as you can see by noting how
different are the stems and the fronds. Nevertheless, the stem can be viewed
as a compressed copy of a frond, and the fractal obtained with (A) is still self-
affine, yet with a dimension that varies in different parts of the figure.
284 Chapter 12 Computational Physics – Application in Physical Systems
Python Implementation
The Python program may be implemented as follows:
import pylab as pl
import random
max_iteration = 30000 # number of iterations
x0 = 0.5; # starting point
y0 = 0.0;
x = []
y = []
x.append(x0)
y.append(y0)
for i in range(max_iteration) :
# r = random.uniform(0,1)
r = random.random()
if r < 0.02:
x1 = 0.5
y1 = 0.27*y[i]
elif (r >= 0.02 and r <= 0.17):
x1 = -0.139*x[i] + 0.263*y[i] + 0.57
y1 = 0.246*x[i] + 0.224*y[i] - 0.036
elif (r >0.17 and r <= 0.3):
x1 = 0.17*x[i] - 0.215*y[i] +0.408
y1 = 0.222*x[i] + 0.176*y[i] + 0.0893
else:
x1 = 0.781*x[i] + 0.034*y[i] + 0.1075
12.6 Random Numbers in Computer Simulation 285
Barnsley' i ~~
~30~00~o~·
1
.0
0.8
0.6
0.4
0.2
0.0
where m is a large number and the square bracket stands for keeping fractional
part of the product of m and xi. Now the square will be filled densely. You
may check this feature for any number m. For m = 10, the graph is
shown in Fig. 12.6(b). However, one can easily note that some correlation
exists amongst the successive numbers. The basic choice of f(xi) is the key
to a good pseudorandom number generator.
fig. 12.6 (a) Function for Choosing random fig. 12.6 (b) Function for another
number generator f(x) = x *x random number generator
0.8
0.6
0.4
0.2
0.0
1 2 3 4 5 6 7 8 9 10
import random
number = input(“Enter the total number of Random
numbers to be generated :”)
a = input(“Enter the magic Number :”)
c = input(“Constant to be added, c :”)
m = input(“An Integer for modulo operation preferably
large prime no., m :”)
x = input(“Enter a Seed :”)
X = [] # For drawing graph –X Axis
Y = [] # For drawing graph –Y Axis
for i in range(1, number+1):
x1 = (a*x + c) % float(m)
x = x1
ran_no = x1 /float(m)
print ran_no,
Y.append(ran_no)
X.append(random.uniform(0,1))
#X.append(i)
pl.plot(X,Y,’.’)
pl.show()
(ii) efficiency, (iii) reproducibility and (iv) passing out certain statistical
tests. All of which are impossible to be found in a set of pseudo-random
numbers. We shall discuss important statistical tests which can be employed
to test the randomness of the set of random numbers produced. The tests are:
(i) Uniformity Test,
(ii) Auto-correlation Test,
(iii) Periodicity Test, and
(iv) Serial-Correlation Test.
Uniformity Test
This is a well known statistical test to divide a given data into classes of equal
sizes. The data is scanned and put in different classes. By plotting a bar chart,
one can visualize whether each class has the same number of random numbers
or not. Numerically, one can calculate chi-square (χ2), a quantitative measure
of the agreement between the observed and expected distribution, as
1 Classes
(Observed i − Expi )2
χ2 = ∑
No. of Classes 1 (Expi )2
(C)
For each set of the 100 random numbers generated with different methods, this
test is performed for classes of 5, 10 and 25; and χ2 is given in Table below.
generator of Classes 5 10 15
mid square method (with seed 3761) 1.04 0.96 0.86
Multiplicative congruential method
Magic numbers: a = 1317, c = 3917, 0.12 0.24 0.28
m =. 713, seed = 7361
Auto-correlation Test
Auto-correlation test checks the serial auto-correlation between two
number; by calculating auto-correlation function which describes the
correlation between the two random numbers at different places in the
generated sequence. It is defined as
< xi xi + k > − < xi > < xi + k >
C(k)=
< xi xi > − < xi > < xi >
where xi is the ith term in the sequence and < ... > represents the mean. If
xi and Xi +k are not correlated then
<xixi+k > – < xi > < xi+k > = 0
and C (k) = 0. Here, we give an algorithm to find such correlations.
Algorithm for Auto-correlation Test :
Step 1 : Initialize the sum to find average and average square.
Step 2 : Start a loop over random number N.
Step 3 : Sum the numbers.
Step 4 : Sum the square of numbers.
Step 5 : Loop started at step 2 ends.
Step 6 : Find mean of squares.
Step 7 : Give the interval between two random numbers in the generator
sequence with which auto-correlation is to be checked.
Step 8 : Initialize the sum of the products of consecutive random number
in pairs step interval chosen.
Step 9 : Initialize the sum of the successive random numbers separated by
the interval chosen for looking for correlation.
Step 10 : Calculate the no. of random numbers, NL, upto which pairs can be
found.
Step 11 : Start a loop over NL.
Step 12 : Calculate sum of the product of the consecutive random number
pairs separated by intervals.
12.7 Monte Carlo Method 297
Square root of this quantity called standard deviation, σ, tells us that a given
measurement can deviate for a fixed numbers of shots in an interval (m – σ,
m + σ), where m is the mean of the measurements
Σ i mi
m =
N
We see that the standard deviation a varies with N as
1
σ∝
N
i.e. greater the number of measurements, more precisely can we locate the true
value.
12.7.4 Application of the Monte Carlo Method: Finding the
Value of p
What is p? One can define it as the area of a unit circle. The following algorithm
helps us to calculate the value of p. We shall exploit the symmetry of the
problem and instead of finding area of the full unit circle, we calculate area of
the first quadrant of the unit circle and multiply the result finally by four.
Step 1 : Start a random number generator.
Step 2 : Give the number of times hitting to be done, say N.
Step 3 : Initialize counter, m, to count the random number lying within the unit
circle.
Step 4 : Begin a loop to shoot N times.
Step 5 : Fetch two random numbers for x and y such that
0 ≤ x ≤ l and 0 ≤ y ≤ l.
Step 6 : If (x2 + y2) ≤1 i.e., the pair (x, y) lies within the quarter = circle,
increment the counter m = m + 1.
12.7 Monte Carlo Method 301
def RK4(f,g,h ):
fout = open(“RK421.txt”, “w”)
x=0
y=1
z=0
n=1
dt=0.005
while(n<=20000):
k1=dt*f(x,y,z)
l1=dt*g(x,y,z)
m1=dt*h(x,y,z)
k2=dt*f(x+k1/2,y+k1/2,z+m1/2)
l2=dt*g(x+k1/2,y+k1/2,z+m1/2)
m2=dt*h(x+k1/2,y+k1/2,z+m1/2)
k3=dt*f(x+k2/2,y+l2/2,z+m2/2)
l3=dt*g(x+k2/2,y+l2/2,z+m2/2)
m3=dt*h(x+k2/2,y+l2/2,z+m2/2)
k4=dt*f(x+k3,y+l3,z+m3)
12.8 Lorenz Equation 303
l4=dt*g(x+k3,y+l3,z+m3)
m4=dt*h(x+k3,y+l3,z+m3)
x+=(k1+k2*2+k3*2+k4)/6
y+=(l1+l2*2+l3*2+l4)/6
z+=(m1+m2*2+m3*2+m4)/6
n=n+1
print x,y,z #correct answer
if n>500 :
fout.write(str(x))
fout.write(“\t”)
fout.write(str(y))
fout.write(“\t”)
fout.write(str(z))
fout.write(“\t”)
fout.write(“\n”)
return x,y,z
def f(x,y,z) :
return sigma*(y-x)
def g(x,y,z) :
return (r*x-y-x*z)
def h(x,y,z) :
return (x*y-b*z)
x,y,z = RK4(f,g,h)
eXerCIses
12.1 The logistic map is a simple non-linear (see quadratic term) iterative
mapping, often to study how complex, chaotic behaviour can arise in a
deterministic system. The equation of the system is given
xn+1 = rxn(1 – xn) for 0 < r < 4 and 0 < r < 1
(a) Plot xn vs. n for different values of r, r = 1, r = 2.8, r = 3.4 and
r = 4 (make a subplots (2, 2) with appropriate labels). For a given
value of r and x0 ∈ [0, 1], find the sequences x1, x2, x3 … . This
process is called iteration.
(b) Plot the return map (xn vs. xn+1) for the above values of r.
(c) Plot the cobweb diagram for above values of r.
Note: Procedure of making cobweb diagram:
Given a map xn+1 = f (xn) and an initial condition x0, draw a vertical
line until it intersects the graph of f; that height is the output x1.
From x1, draw a horizontal line until it intersect the diagonal line
(xn+1 = xn). Repeat the procedure to get the x2 from x1. Continue
the process n times to generate the first n points in the orbit.
(d) Plot the bifurcation diagram of logistic map by varying r from
0 to 4.
Note: Procedure of making bifurcation diagram:
For each value of r, iterate the map 30 steps. Remove transients
(discard first 20 points) and take 10 points to plot xn vs. r.
Exercises 305
(a) Plot the attractors (yn vs xn) at (a = 1.4, b = 0.3) and (a = 0.2,
b = 1.01).
(b) Plot the bifurcation diagram of the system. Fixed b = 0.3 and vary
a from zero to 1.5.
12.5. Lorenz equations : Ed Lorenz (1963) derived the following set of
equations for 3-dimensional system from a drastically simplified model
of convection rolls in the atmosphere,
dx
dt
= s(y – x)
dy
= rx – x – xz
dt
dz
dt = xy – bz
8
Simulate and visualize this system for s = 10, b = and r = 28.
3
(a) Plot the 2D attractors x(t) vs. z(t) and y(t) vs. z(t)
(b) Plot the 3D attractor x(t), y(t), z(t).
(c) Plot the time series x(t), y(t), z(t) vs. t.
(d) Lorenz map: To compare results to those obtained with for 1-D
maps, Lorenz used a trick to obtained a map from a flow. Lets
construct Lorenz map: Take z(t) and find the successive local
maxima zn of z(t). Plot the return map zn+1 vs. zn.
Appendix I:
Objective Type Questions
G.‘hello’ == str1
(a)can’t assign in this way
(b)True
(c)False (d) error
H. ‘a’ in str3
(a)True (b) False
(c)Can’t say (d) error
I. str4 = str1 + str3
‘low’ in str4
(a)True (b) False
(c)Can’t say (d) error
J. str3[:-1]
(a)world (b) worl
(c)ello (d) can’t say
K. str4[1:9]
(a)elloworl (b) elloworld
(c)error (d) can’t say
L. str4[1:9:2]
(a)hlool (b) hloo
(c)elwr (d) elwrd
M. str4[:: -1]
(a)hellod (b) worldh
(c)helloworld (d) dlrowolleh
6. For each of the following expressions, indicate the value that prints out
when the expression is evaluated.
A. temp = ‘32’
if temp > 85:
print “Hot”
elif temp > 62:
print “Comfortable”
else:
print “Cold”
(a) Cold (b) Comfortable
(c)Hot (d) None of all
B. var =’Panda’
if var == ’panda’:
print “Cute!”
elif var == “Panda”:
print “Regal!”
else:
print “Ugly...”
(a)Cute! (b) Regal!
(c)Ugly... (d) None of all
310 Appendix I: Objective Type Questions
C. temp = 120
if temp > 85:
print “Hot”,
elif temp > 100:
print “REALLY HOT!”,
elif temp > 60:
print “Comfortable”,
else:
print “Cold”
(a) REALLY HOT! (b) Comfortable
(c)Hot (d) Hot REALLY HOT!
7. The values in a list are called _________
(a) elements (b) items
(c) both (i) and (ii) (d) None of the above
8. The output of the program segment is
numbers = [12, 34, 56]
numbers[1] = 78
print numbers
(a) [12, 78, 56] (b) [12, 34, 56]
(c) [78, 34, 56] (d) None of the above
9. The output of the program segment is
strings1 = [‘Computer’, ‘Maths’, ‘Physics’]
strings1[2] = ‘Chem’
print strings1
(a) [‘Computer’, ‘Maths’, ‘Physics’]
(b) [‘Computer’, ‘Maths’, ‘Chem’]
(c) Syntax error is expected
(d) None of the above
10. The relationship between indices and elements of a list is called a _____
(a) tapping (b) grouping (c) indexing (d) mapping
11. Some of the properties of List indices are :
A. Any integer expression can be used as an index.
B. Any character expression can be used as an index.
C. If you try to read or write an element that does not
exist, you get an IndexError.
D. If an index has a negative value, it counts backward from the end
of the list.
(a) All are correct
(b) Only A, B and C are correct
(c) Only A, C and D are correct
(d) Only B, C and D are correct
Objective Type Questions 311
else:
return False
for i in filter(checkthis, values):
print i,
(a) 1 2 1 3 3 (b) 1 2 3
(c) True (d) False
47. The above example 46 made a small changes inside the for loop.
What will be the output ?
values = [1, 2, 1, 3, 3]
numbers = set(values)
def checkthis(num):
if num in numbers:
return True
else:
return False
for i in filter(checkthis, numbers):
print i,
(a) 1 2 1 3 3 (b) 1 2 3
(c) True (d) False
48. What sequence of numbers will be printed?
no1 = [2, 3, 4, 5]
def function1(num):
return num ** 2
for i in map(function1, no1):
print i
(a) 2 3 4 5 (b) 4 6 8 10
(c) 4 9 16 25 (d) Syntax Error
49. What gets printed by the code snippet below?
import math
print math.floor(5.5)
(a) 5 (b) 5.0
(c) 5.5 (d) 6.0
50. The output of the following program segment is:
x = “test”
y = 2
print x + y
(a) test2 (b) test 2
(c) testtest (d) Error is expected
51. What gets printed by the code snippet below?
def Function2():
“This is a test of __doc__ “
Objective Type Questions 317
return 1
print Function2.__doc__[8:14]
(a) Function2 (b) This is
(c) a test (d) Error is expected
52. What does the role of the following code?
sys.path.append(‘/root/test1’)
(a) Changes the location that the python executable is run from.
(b) Changes the current working directory.
(c) Adds a new directory to search for python modules
that are imported.
(d) Removes all directories for test1.
53. Which of the following print statements will print all the names in
the list on a separate line?
names = [‘Ramesh’, ‘Rajesh’, ‘Bob’, ‘Dilip’, ‘Mike’]
(a) print “\n”.join(names)
(b) print names.join(“\n”)
(c) print names.concatenate(“\n”)
(d) print names.append(“\n”)
54. What gets printed?
foo = (3, 4, 5)
print type(foo)
(a) int (b) list (c) tuple (d) both (a) and (c)
55. The output of the following program is:
confusion = {}
confusion[1] = 5
confusion[‘1’] = 10
confusion[1] += 2
sum = 0
for k in confusion:
sum += confusion[k]
print sum
(a) 7 (b) 9 (c) 15 (d) 17
56. What is the output of the following program segment?
dir1 = {1:’1’, 2:’2’, 3:’3’}
dir1 = {}
print len(dir1)
(a) 3 (b) 0 (c) 6 (d) Syntax Error
57. What is the output of the following program segment?
dir2 = {1:’1’, 2:’2’, 3:’3’}
del dir2[1]
318 Appendix I: Objective Type Questions
dir2[1] = ‘10’
del dir2[2]
print len(dir2)
(a) 1 (b) 2
(c) 3 (d) Error is Expected
58. The output of the following program segment is :
names = [‘Khan’, ‘Amir’, ‘Charles’, ‘Rajesh’]
print names[-1][-1],
print names[1][1]
(a) Khan Rajesh (b) A m
(c) s h (d) h m
59. What gets printed?
numbers = [1, 2, 3, 4]
numbers.append([5,6,7])
print len(numbers)
(a) 5 (b) 4 (c) 7 (d) Syntax Error
60. If we change the last line in the above example , as follows, the output
will be:
numbers = [1, 2, 3, 4]
numbers.append([5,6,7])
print numbers
(a) [1, 2, 3, 4, 5, 6, 7] (b) [1, 2, 3, 4, [5, 6, 7]]
(c) {1, 2, 3, 4, [5, 6, 7]} (d) (1, 2, 3, 4, [5, 6, 7])
61. The “in” operator can be used in:
(a) list (b) set
(c) dictionary (d) All of the above
62. The output of the following program segment is:
list1 = [1, 2, 3, 4]
list2 = [5, 6, 7, 8]
print len(list1 + list2)
(a) 5 (b) 8 (c) 36 (d) 4
63. The output of the following program segment is:
def addItem(New_list):
New_list += [1]
list1 = [1, 2, 3, 4]
addItem(list1)
print len(list1)
(a) 5 (b) 8
(c) 4 (d) Error is expected
Objective Type Questions 319
64. If we add print New_list the above example, Program 63, in the
function definition, the output will be:
def addItem(New_list):
New_list += [1]
print New_list
list1 = [1, 2, 3, 4]
addItem(list1)
(a) [1, 2, 3, 4] (b) [2, 3, 4, 5]
(c) [1, 2, 3, 4, 1] (d) [1, 1, 2, 3, 4]
65. What gets printed?
tuple1 = (1, 2, 3, 4)
tuple1.append((5, 6, 7))
print len(tuple1)
(a) 5 (b) 8
(c) 4 (d) Syntax Error
66. What will be the return type of this function?
def function3(arg11, *arg2):
print type(arg2)
function3(‘abc’, ‘defg’, ‘123’)
(a) int (b) list
(c) tuple (d) string
67. What is the return type of this function?
def function4(arg1, **arg2):
print type(arg2)
function4(‘Title’, a=’123’,b=’456’, c=’789’)
(a) dictionary (b) list
(c) tuple (d) string
68. What is the value of the agr1 in the above example, Program 67?
def function4(arg1, **arg2):
print arg1
function4(‘Title’, a=’123’,b=’456’, c=’789’)
(a) Title (b) 123
(c) 456 (d) 789
69. What is the value of the agr1 in the above example, Program 67?
def function4(arg1, **arg2):
print arg2
function4(‘Title’, a=‘123’,b=‘456’, c=‘789’)
(a) {‘a’: ‘Title’, ‘c’: ‘456’, ‘b’: ‘123’}
(b) {‘a’: ‘123’, ‘c’: ‘789’, ‘b’: ‘456’}
(c) {‘a’: ‘123’, ‘c’: ‘789’, ‘b’: ‘456’, ‘Title’ : None}
(d) None of these
320 Appendix I: Objective Type Questions
75. What will be the output, assuming that the user enters the following at
the prompt?
#: test
a = input(“#: ”) # Type test
print a
(a) test (b) #:test (c) t (d) Error
ansWers
1. (a) 2. (b) 3. (c) 4.A. (a) 4.B. (b) 4.C. (c)
4.D. (b) 4.E. (d) 4.F. (c) 5.A. (c) 5.B. (d) 5.C. (a)
5.D. (d) 5.E. (b) 5.F. (a) 5.G. (b) 5.H. (b) 5.I. (a)
5.J. (b) 5.K. (a) 5.L. (c) 5.M. (d) 6.A. (c) 6.B. (b)
6.C. (c) 7. (c) 8. (a) 9. (b) 10. (d) 11. (c)
12. (d) 13. (a) 14. (b) 15. (b) 16. (d) 17. (a)
18. (c) 19. (d) 20. (a) 21. (b) 22. (b) 23. (a)
24. (b) 25. (b) 26. (a) 27. (b) 28. (d) 29. (c)
30. (b) 31. (b) 32. (c) 33. (c) 34. (a) 35. (c)
36. (b) 37. (a) 38. (d) 39. (c) 40. (c) 41. (d)
42. (a) 43. (b) 44. (c) 45. (d) 46. (a) 47. (b)
48. (c) 49. (b) 50. (d) 51. (c) 52. (c) 53. (a)
54. (c) 55. (d) 56. (b) 57. (2) 58. (d) 59. (5)
60. (b) 61. (d) 62. (8) 63. (5) 64. (c) 65. (d)
66. (c) 67. (a) 68. (a) 69. (b) 70. (c) 71. (d)
72. (a) 73. (b) 74. (d) 75. (d)
Appendix II:
Descriptive Type Questions
Note: Instead of using our user defined function init(), we can use the
built in function input() as follows:
def reverse( no) :
rev = 0
while no > 0 :
remender = no % 10
no = no // 10
rev = remender + 10 * rev
return rev
no = input(“ \n The Input Number is : “)
a = reverse(no)
print a
Note: If you want to learn more about recursive function, run the
following program and correct the output.
gcd1 = GCD1(a, b)
print ‘GCD is :’, gcd1
Output of the above program :
Enter the first number :24
Enter the second number :56
GCD is : 8
Enter the first number :56
Enter the second number :24
GCD is : 8
Third Method : The traditional one
def gcd2(m, n) :
if (n > m) :
m = m + n
n = m - n
m = m - n
while (m % n != 0 ) :
temp = n
n = m % n
m = temp
return n
a = input( “Enter the first number :”)
b = input( “Enter the second number :”)
gcd1 = gcd2(a, b)
#gcd1 = gcd2(24,56) # we can test in this way
#gcd1 = gcd2(56,24) # here first is greater than
second number.
print ‘The GCD(HCF) is ‘, gcd1
The output of the above program is :
enter the first number :56
Enter the second number :24
The GCD(HCF) is 8
Note: You can try for different numbers
including zeros and negative numbers.
328 Appendix II: Descriptive Type Questions
if test :
print “The Number is Prime Number.”
else :
print “The Number is NOT a Prime Number.”
main()
5. Write a python program to generate prime numbers between 1 to
100.
Check the indents in this program properly. For example the
if(counter == 2) :will be outside the for loop and the increment
of i, “i += 1;” will be outside the if statement as well as
outside the for loop.
def generate_prime(no) :
i = 1
while i <=no :
counter = 0
for j in range(1,i+1) :
if(i%j == 0) :
counter += 1;
if(counter == 2) :
print “%4d\t” % i;
i += 1;
n = input (“Enter the maximum value : “)
print “The Prime Numbers are: “
generate_prime(n)
Output of the above program :
Enter the maximum value : 20
The Prime Numbers are:
2 3 5 7 11 13 17 19
We may write these programs in different ways, using list, tuples and
dictionaries. Some of the different methods are shown below :
Method 1:
import math
def isPrime(n):
for i in range(2, int(math.sqrt(n)+1)):
330 Appendix II: Descriptive Type Questions
if n % i == 0:
return False
return True
print 2
for n in range(3, 50):
if isPrime(n):
print n
Output of the above program :
2 3 5 7 11 13 17 19 23 29 31 37
43 47
Method 2 : (output will be in the form of list )
def is_prime(num):
”””Returns True if the number is prime
else False.”””
if num == 0 or num == 1:
return False
for x in range(2, num):
if num % x == 0:
return False
else: # this else part is for ‘for loop’ not for if
# statement
return True
print filter(is_prime, range(1, 20))
Output of the above program :
[2 3 5 7 11 13 17 19]
NOTE : if we put the else part for if state-
ment, output will be in this form :
[3, 5, 7, 9, 11, 13, 15, 17, 19]
Method 3 : (generating prime numbers in one line)
print [x for x in range(2,100) if not [t for t
in range(2,x) if not x%t]]
Output of the above program :
[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41,
43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97]
Descriptive Type Questions 331
A. Insertion sort :
Method 1:
def insertion_sort(a):
if len(a) <= 1:
return a
key = 2
while key < len(a):
_key = key
while a[_key] < a[_key-1] and _key > 0:
tmp = a[_key]
a[_key] = a[_key-1]
a[_key-1] = tmp
_key -= 1
print a # To see the steps of sorting
key += 1
return a
a = [3, 5, 2, 1, 2]
print insertion_sort(a)
The output of the above program is :
[3, 2, 5, 1, 2]
[2, 3, 5, 1, 2]
[2, 3, 1, 5, 2]
[2, 1, 3, 5, 2]
[1, 2, 3, 5, 2]
[1, 2, 3, 2, 5]
[1, 2, 2, 3, 5]
[1, 2, 2, 3, 5]
NOTE : Just to see how the sorting technique
works, we are using the ‘print a’ statement.
If we remove this line, only the last line will
be shown.
Method 2 : (input values using random numbers)
import random
Array = random.sample(range(30), 7)
Descriptive Type Questions 333
print Array
First = 0
Last = len(Array) - 1
PositionOfNext = Last - 1
while PositionOfNext >= First:
Next = Array[PositionOfNext]
Current = PositionOfNext
while (Current < Last) and (Array[Current]
> Array[Current + 1]):
Current = Current + 1
Array[Current - 1], Array[Current] =
Array[Current], Array[Current -1]
#print Array
Array[Current] = Next
PositionOfNext = PositionOfNext - 1
print Array
Output of the above program :
(with Array = random.sample(range(30), 5))
[8, 24, 4, 10, 27]
[4, 8, 10, 24, 27]
(with Array = random.sample(range(30), 7))
[23, 24, 17, 25, 28, 18, 20]
[17, 18, 20, 23, 24, 25, 28]
NOTE : Just to see how the sorting technique
works, we are using the ‘print Array’ state-
ment inside the inner while loop. If we remove
this line, the details of the sorting sequence
will not be shown.
[17, 24, 10, 12, 28, 26, 27]
[17, 24, 10, 12, 26, 28, 27]
[17, 24, 10, 12, 26, 27, 28]
[17, 10, 24, 12, 26, 27, 28]
[17, 10, 12, 24, 26, 27, 28]
[10, 17, 12, 24, 26, 27, 28]
[10, 12, 17, 24, 26, 27, 28]
[10, 12, 17, 24, 26, 27, 28]
334 Appendix II: Descriptive Type Questions
B. Bubble Sort :
Method 1(for beginners) : This method just shows the sorting
technique of Bubble sort. Here we don’t use any function :
list1 = [12, 5, 13, 8, 9, 65]
i=0
while i < len(list1)-1:
if list1[i] > list1[i+1]:
x = list1[i]
list1[i] = list1[i+1]
list1[i+1] = x
print list1
i=0
continue
else:
i+=1
print(list1)
The output of the above program is :
[5, 12, 13, 8, 9, 65]
[5, 12, 8, 13, 9, 65]
[5, 8, 12, 13, 9, 65]
[5, 8, 12, 9, 13, 65]
[5, 8, 9, 12, 13, 65]
[5, 8, 9, 12, 13, 65]
Method 2 : In this Bubble Sorting method, the larger element shifts all
the way to the end. And decrement the end counter, “n” so that we will
not have to compare it again. The while loop will continue as long as
there are possible exchanges are available.
def bubble_sort(list1):
exchanged = True
iteration = 0
n = len(list1)
while(exchanged):
iteration += 1
exchanged = False
Descriptive Type Questions 335
return False
return True
def check_Fibonacci(no):
first_num = 1
second_num = 1
third_num = 0
counter = 0
while (1):
third_num = first_num + second_num
if (isPrime(third_num)== True):
counter += 1
print third_num
if (counter == no):
break
first_num = second_num
second_num = third_num
print” How many prime numbers you want from the
Fibonacci series:”
n = input(“Enter the number :”)
print(“The prime numbers are : “)
check_Fibonacci(n)
Output of the above program segment is:
How many prime numbers you want from the Fi-
bonacci series:
Enter the number :15
The prime numbers are :
2 5 13 21 55 89 233 377 987 1597 4181 6765
17711 28657 75025
Method 2 : In this program we generate all the Fibonacci numbers
using a list. And store in it using append() function. After that
we call one by one the Fibonacci numbers from the list and check it
whether the number is prime number or not.
from math import sqrt
def fibonacci(no) :
338 Appendix II: Descriptive Type Questions
a=[0, 1]
first_term = 0
second_term = 1
print “The Fibonacci Series is:\n”
#print first_term, second_term
for i in range(no) :
third_term=first_term + second_term
first_term=second_term
second_term=third_term
#print “ %-6ld\t” %third_term;
a.append(third_term);
print a
print(“\n\nThe Prime Numbers in the Fibonacci
Series are:\n”)
for j in range (3,n+1):
for z in range (2, int(sqrt(a[j])+1)):
if a[j] % z == 0 :
break
else :
print a[j],
n = input( “\nEnter a Number :”)
fibonacci(n)
Output of the above program segment is :
Enter a Number :14
The Fibonacci Series is:
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144,
233, 377, 610]
The Prime Numbers in the Fibonacci Series are:
2 3 5 13 89 233
7. Write a python program to accept a string and convert the given
string into a dictionary. From that dictionary, using the concept
of reverse lookup, print all the corresponding keys with its
corresponding values.
def histogram(s):
Descriptive Type Questions 339
d = dict() # d = {}
for c in s:
if c not in d:
d[c] = 1
else:
d[c] += 1
return d
def reverse_lookup(d, v):
list1 =[]
for k in d:
if d[k] == v:
list1.append(k)
return list1
raise ValueError, ‘Value does not appear in
the directory.’
s = raw_input(“ Enter a String :”)
s1 = histogram(s)
v = s1.values() # values
new_v =[]
for i in v :
if i not in new_v :
new_v.append(i)
for i in new_v :
k = reverse_lookup( s1, i)
print “\nThe keys and values are “, i, “ -->”
for i in k :
print i,
Output of the above program is :
Enter a String :parrot
The keys and values are 1 -->
a p t o
The keys and values are 2 -->
r
references
1. https://www.python.org/
2. E Balagurusamy, Programming in ANSI C, The McGraw-Hill
Companies,2008.
3. Danial Liang, Y, Introduction to Programming using Python, Pearson,
2013.
4. Allen Downey, Think Python, Green Tea Press, 2014.
5. Magnus Lie Hetland, Beginning Python, Apress, 2008.
6. http://www.mypythonquiz.com/question.php
7. http://stackoverflow.com/
Index
A Isinstance 144
append(s) 166 Issubset 216
append(x) 167 Issuperse 216
Items 155
B
bound 269 K
Keys 206
C
call graph 137 L
count(s) 166, 168 Len() 166
critically damped 265 List is 155
D M
Damping 264 Mapping 158
Dictionary Methods 209 Max() 166
Divmod 229, 230 Min() 166
Mutable 158
E
Extend() 167
N
Nested list 156
Extend(s) 166
I O
Ord( ) 207
In operator 159
Over-damped 265
Indent 80
Index(s) 167 P
Index(x) 168 Pop(s) 167
IndexError 159 Proper subset 217
Insert () 168 R
Insert(s1, s2) 167 Randint() 251
Remove() 169
344 Index
Remove(s) 167 T
Reverse() 167 Type 206
Runtime Errors 54
U
S Unbound 269
Scaffolding 129 Undamped 265
Semantic Errors 54
V
Sequences 155
Value 206
Sets 213
Shuffle() 166 Z
Sort() 166, 168 Zip 234, 236
Subplot() 266 Zip( ) 207
Symbols
Syntax Errors 54