Chapter 7
Chapter 7
After studying this lesson, you will have better understanding of,
How to analyze a problem and develop an algorithm
Control structures and their use
Drawing Flow charts, writing pseudo codes and conversions between them
Finding alternate solutions to a problem
Programming in Python
Evolution of programming languages
Analyzing a problem
The raw materials that are used to solve a problem are known as the 'input'. The result obtained after solving a
problem is known as the 'output'. Converting input to output is called the 'process'. A process takes place step
by step and it is very important to understand the order of the process. When Analyzing a problem, the input,
process and output are identified separately.
Example -
Problem 1 : Preparing a letter which can be posted.
Input : A sheet of paper suitable to write the letter on and a pen An envelope and a stamp Glue
Process : 1. Writing the letter
2. Folding the letter and putting it into the envelope
3. Pasting the envelope
4. Writing the recipient's address on the envelope
5. Sticking the stamp
Output : A letter ready to be posted.
Note: Steps No. 4 and 5 in this process can be interchanged. However, the other steps should be followed in
the order indicated.
Problem 3 : Dividing 40 page and 80 page books from a parcel of books between two siblings - Sanduni and
Anupama.
Input :
Process :
Output :
1
Problem 4 : Adding two numbers
Input :
Process :
Output :
Input :
Process :
Output :
Input :
Process :
Output :
Input :
Process :
Output :
2
Example
Imagine you come to school by school bus. If the bus breaks down on your way to school, you certainly will
think of other alternative ways to reach school.
1. Coming to school by another school bus which goes to your school
2. If you have money, reaching the school by CTB or private bus
3. Walking to school along the road
4. Walking to school using a short-cut
5. If you have a way to inform your parents, get their support to reach the school
6. Reaching the school by car or motor bike with the support of a trustworthy person
You may select a good solution out of these if it is mandatory to go to school that day.
Thus, if there are many solutions (set) to a particular problem, it is suitable to consider these and select an
appropriate solution.
All the solutions pertaining to a problem are called solution space. In computer programming also, various
solutions should be identified and an appropriate solution should be selected. Then, we can create a short,
simple program.
Example 1
Let us examine the solution space to find the perimeter of a rectangle.
Let us analyze the input, process and output related to this problem.
Out of these solutions, a person who has knowledge only of addition, can select the 1st solution as the most
appropriate. A person who has knowledge of multiplication and addition can select the 3rd solution out of the
2nd and 3rd solutions as the most appropriate. The person for this is, it has the minimum number of additions
and multiplications.
Example 2
Indicating that a student has failed if the score for the ICT subject is less than 35, and indicating pass if the
score is 35 or above.
Input : Marks
Process : Comparing the mark scored with 35
3
Example 3
Finding the larger number from between two numbers. Let us consider the two input numbers as n1 and n2.
Thus, it is important to select the appropriate solutions out of the available alternative solutions.
An algorithm is a method to show the steps in solving a problem. An algorithm is a step-by-step procedure for
solving a problem. The need for this is to present a way to solve the problem with a plan.
Step (1), (2) and (3) in this algorithm should be followed in the given order. Step (4) and (5) can be
interchanged. The reason for this is, you can either stick the stamp after writing the address or write the
address after sticking the stamp.
Thus, there are steps in an algorithm which should be followed in a strict sequential order. Sometimes, if the
order of some steps is changed, it does not affect the process and the output is same.
Activity
There are 183 students in a primary school. The principal has decided to hold an inter-house sports meet
dividing them into three houses – Olu, Nelum and Manel. Develop an algorithm to the divide the students into
the three houses.
i. Sequence
If the steps from the beginning to the end of an algorithm are carried out in a strict order, it is called a
sequence.
4
Example -
1. Climbing up or down step by step when going on a staircase
2. Students who were admitted to grade 1 of the school continue studies till grade 13
ii. Selection
Selection is a situation where step(s) are executed depending on whether a condition of an algorithm is
satisfied or not. There are two choices; if the condition is satisfied, one is selected and if it is not satisfied, the
other selection is selected.
Examples of selection
1. Admitting a child to Grade 1:
If a child is below 5 years as at 31st of January that year
The child cannot be admitted to school
If not
The child can be admitted to school
2. Passing a subject:
If the mark is 35 or more
It is a Pass
If not
It is a Fail
3. Buying a book
If you have money equal to or more than the price of the book
You can buy the book
If not
You cannot buy the book
Activity
1. If a Sri Lankan citizen gets the right to vote after completing the age of 18, select the most suitable
word for the blanks given below.
If not,
iii. Repetition
If one or several steps of an algorithm are repeated until a condition is satisfied, it is called repetition.
Examples
1. Let us consider the process of a class teacher marking the attendance register.
(1). Call the first name on the register
(2). Mark 1 if the student is present
(3). Mark 0 if the student is absent
(4). Call the name of the next student
(5). Repeat step (2) or (3) and (4) till the last name of the register is called
2. Let us consider the process of reading a paragraph and calculating the number of words you read.
(1). Read the first word of the paragraph
(2). Number of words = 1
(3). Read the next word
5
(4). Add 1 to the number of words
(5). Repeat step (3) and (4) till the end of the paragraph
(6) After reading the paragraph, indicate the number of words.
1.3.1 Flowcharts
Flowcharts are used to present how the algorithm is built step by step in a dramatic manner. The symbols
given in table are used to indicate different functions.
Sequence
In sequence the steps from the beginning to the end are executed in order.
E.g. 1 - Finding the area of a circle.
Selection
The selection indicates the flow of direction
depending on a condition being satisfied or not
E.g. - Finding whether a number is odd or even
6
Repetition
If one or several Steps are repeated till a condition is satisfied or are continued till is satisfied.
E.g. - Finding the total of some numbers
Activity
Draw flow charts to solve the problems given below.
1. Find the perimeter and area of a rectangle.
2. It is decided to add Rs.5000 to the basic salary of the employees of a company. Calculate the new salary.
3. When posting a letter, postal fare is charged according to its weight. The standard fare should be paid for
letters which are equal to or less than the standard weight. An additional fare should be charged if the weight
is more than the standard weight.
4. Indicate the first 12 multiples of 7
7
E.g. 2 - Finding whether a number is odd or even
BEGIN
READ number as N
CALCULATE Remainder after number is divided by 2
IF Remainder = 0 THEN
DISPLAY “Even number”
ELSE
DISPLAY “Odd number”
ENDIF
END.
8
Following are some of the facts about the above pseudo code.
Observation
When a value is assigned to a variable, the previous value is lost.
When the statement Total = Total + Number is executed, the value assigned to the Number variable is
added with the value assigned to Total variable and the result obtained is assigned to the Total
variable.
Total = Total + Number is not a mathematical formula.
9
1.3.3 Converting Flow charts to Pseudo codes
An algorithm can be presented in a flow chart as well as in a pseudo code. Hence, let us examine how a flow
chart can be converted to a pseudo code.
10
E.g. 2 - Finding the smallest number from 10 numbers
Python programming
Identifiers
An identifier is a term used to represent a variable, constant or a program. The following are some rules that should be
followed in declaring an identifier.
Reserved words in Pascal cannot be used as an identifier name. In any programming language
reserved words cannot be used as identifiers.
E.g. PRINT, INPUT are not valid
Should start with an English letter. (E.g. A-Z, a-z)
After the first letter of the identifier, letters (A-Z, a-z) or numbers (0-9) and underscore ( _ ) can be
used.
E.g. Student_name
Not case sensitive (E.g. – Art, art, ART will be the same identifier)
There should not be any space between words.
E.g. - Student Name - Not valid
The special characters such as the following should not be included in an identifier.
~!@#$%^&*()-+={}[]:;’”<>?,./|\
But, only underscore ( _ ) is valid.
Use of meaningful terms for identifiers can make program easily understood.
Examples for valid identifiers
Sum, SUM, Total_Nos, Num1, FirstName, Last_Name
Examples of identifiers that are not valid
$75, Average Marks, 9A, Last-name
11
Reserved words
The reserved words in Python, are defined in Python language. Hence, reserved words are not used as
identifiers.
Reserved words are different from language to language. The following arereserved words used in Pascal.
You may not name your variables any of the following words as they mean special things in Python:
Do NOT use any of the following words either (although they are not strictly Python reserved words, they
conflict with the names of commonly-used Python functions):
You should also avoid all the names defined in the math library (you must avoid them if you import the
library):
When a program is executed, the input and output should be stored in computer memory. The space needed
for each is defined according to the data type. Hence, it is essential for a programmer to have knowledge of
data types.
12
Variables and constants
Variable
A variable is an identifier which changes the values given to it when the program is being executed.
var1 = 1
var2 = 10
Important
Constants
The identifiers which do not change their values while the program is executed are called constants.
Observation
When executing a program, a variable can take different values. However, the value of a
constant remains unchanged.
Types of Operator
Python language supports the following types of operators.
Arithmetic Operators
Comparison (Relational) Operators
Assignment Operators
Logical Operators
Bitwise Operators
Membership Operators
Identity Operators
Let us have a look on all operators one by one.
13
Python Arithmetic Operators
Assume variable a holds 10 and variable b holds 20, then −
- Subtraction Subtracts right hand operand from left hand operand. a – b = -10
% Modulus Divides left hand operand by right hand operand and returns b%a=0
remainder
// Floor Division - The division of operands where the result is the 9//2 = 4 and
quotient in which the digits after the decimal point are removed. 9.0//2.0 = 4.0, -
But if one of the operands is negative, the result is floored, i.e., 11//3 = -4, -
rounded away from zero (towards negative infinity): 11.0//3 = -4.0
== If the values of two operands are equal, then the condition becomes true. (a == b) is not
true.
!= If values of two operands are not equal, then condition becomes true.
<> If values of two operands are not equal, then condition becomes true. (a <> b) is true.
This is similar to
!= operator.
> If the value of left operand is greater than the value of right operand, then (a > b) is not
condition becomes true. true.
< If the value of left operand is less than the value of right operand, then (a < b) is true.
condition becomes true.
>= If the value of left operand is greater than or equal to the value of right (a >= b) is not
operand, then condition becomes true. true.
<= If the value of left operand is less than or equal to the value of right operand, (a <= b) is true.
then condition becomes true.
14
Python Assignment Operators
Assume variable a holds 10 and variable b holds 20, then −
= Assigns values from right side operands to left side operand c = a + b assigns
value of a + b into c
+= Add AND It adds right operand to the left operand and assign the result to left c += a is equivalent
operand to c = c + a
-= Subtract AND It subtracts right operand from the left operand and assign the result c -= a is equivalent
to left operand to c = c - a
*= Multiply AND It multiplies right operand with the left operand and assign the result c *= a is equivalent
to left operand to c = c * a
/= Divide AND It divides left operand with the right operand and assign the result to c /= a is equivalent
left operand to c = c / ac /= a is
equivalent to c = c /
a
%= Modulus AND It takes modulus using two operands and assign the result to left c %= a is equivalent
operand to c = c % a
**= Exponent Performs exponential (power) calculation on operators and assign c **= a is
AND value to the left operand equivalent to c = c
** a
//= Floor Division It performs floor division on operators and assign value to the left c //= a is equivalent
operand to c = c // a
a = 0011 1100
b = 0000 1101
-----------------
a&b = 0000 1100
a|b = 0011 1101
a^b = 0011 0001
~a = 1100 0011
There are following Bitwise operators supported by Python language
& Binary AND Operator copies a bit to the result if it exists in both operands (a & b) (means
0000 1100)
^ Binary XOR It copies the bit if it is set in one operand but not both. (a ^ b) = 49 (means
15
0011 0001)
~ Binary Ones It is unary and has the effect of 'flipping' bits. (~a ) = -61 (means
Complement 1100 0011 in 2's
complement form
due to a signed
binary number.
<< Binary Left Shift The left operands value is moved left by the number of bits a << = 240 (means
specified by the right operand. 1111 0000)
>> Binary Right Shift The left operands value is moved right by the number of bits a >> = 15 (means
specified by the right operand. 0000 1111)
in Evaluates to true if it finds a variable in the specified sequence and false x in y, here in results
otherwise. in a 1 if x is a
member of
sequence y.
not in Evaluates to true if it does not finds a variable in the specified sequence x not in y, here not
and false otherwise. in results in a 1 if x is
not a member of
sequence y.
is Evaluates to true if the variables on either side of the operator point to x is y, here is results in
the same object and false otherwise. 1 if id(x) equals id(y).
is not Evaluates to false if the variables on either side of the operator point to x is not y, here is
the same object and true otherwise. not results in 1 if id(x)
is not equal to id(y).
16
Operator Description
~+- Complement, unary plus and minus (method names for the last two are +@ and -@)
Selection
IF statement
Python programming language provides following types of decision making statements. Click the following
links to check their detail.
17
Statement Description
#!/usr/bin/python
var = 100
Repetition
Python programming language provides following types of loops to handle looping requirements.
18
Loop Type Description
nested loops You can use one or more loop inside any another while, for or
do..while loop.
Python supports the following control statements. Click the following links to check their detail.
break statement Terminates the loop statement and transfers execution to the
statement immediately following the loop.
continue statement Causes the loop to skip the remainder of its body and immediately
retest its condition prior to reiterating.
pass statement The pass statement in Python is used when a statement is required
syntactically but you do not want any command or code to execute.
Number data types store numeric values. They are immutable data types, means that changing the value of a
number data type results in a newly allocated object.
Number objects are created when you assign a value to them. For example −
var1 = 1
var2 = 10
You can also delete the reference to a number object by using the delstatement. The syntax of the del
statement is −
del var1[,var2[,var3[....,varN]]]]
You can delete a single object or multiple objects by using the del statement. For example:
del var
del var_a, var_b
19
int (signed integers): They are often called just integers or ints, are positive or negative whole numbers with no
decimal point.
long (long integers ): Also called longs, they are integers of unlimited size, written like integers and followed by an
uppercase or lowercase L.
float (floating point real values) : Also called floats, they represent real numbers and are written with a decimal
point dividing the integer and fractional parts. Floats may also be in scientific notation, with E or e indicating the
power of 10 (2.5e2 = 2.5 x 102 = 250).
complex (complex numbers) : are of the form a + bJ, where a and b are floats and J (or j) represents the square
root of -1 (which is an imaginary number). The real part of the number is a, and the imaginary part is b. Complex
numbers are not used much in Python programming.
Examples
Here are some examples of numbers
Python allows you to use a lowercase L with long, but it is recommended that you use only an uppercase L to avoid
confusion with the number 1. Python displays long integers with an uppercase L.
A complex number consists of an ordered pair of real floating point numbers denoted by a + bj, where a is the real
part and b is the imaginary part of the complex number.
Mathematical Functions
Python includes following functions that perform mathematical calculations.
20
Function Returns ( description )
abs(x) The absolute value of x: the (positive) distance between x and zero.
max(x1, x2,...) The largest of its arguments: the value closest to positive infinity
min(x1, x2,...) The smallest of its arguments: the value closest to negative infinity
modf(x) The fractional and integer parts of x in a two-item tuple. Both parts have the same
sign as x. The integer part is returned as a float.
round(x [,n]) x rounded to n digits from the decimal point. Python rounds away from zero as a
tie-breaker: round(0.5) is 1.0 and round(-0.5) is -1.0.
Python Strings
Strings are amongst the most popular types in Python. We can create them simply by enclosing characters in
quotes. Python treats single quotes the same as double quotes. Creating strings is as simple as assigning a
value to a variable. For example −
To access substrings, use the square brackets for slicing along with the index or indices to obtain your
substring. For example −
#!/usr/bin/python
21
When the above code is executed, it produces the following result −
var1[0]: H
var2[1:5]: ytho
Updating Strings
You can "update" an existing string by (re)assigning a variable to another string. The new value can be
related to its previous value or to a completely different string altogether. For example −
#!/usr/bin/python
Escape Characters
Following table is a list of escape or non-printable characters that can be represented with backslash notation.
An escape character gets interpreted; in a single quoted as well as double quoted strings.
Backslash Hexadecimal Description
notation character
\b 0x08 Backspace
\cx Control-x
\C-x Control-x
\e 0x1b Escape
\f 0x0c Formfeed
\M-\C-x Meta-Control-x
\n 0x0a Newline
\s 0x20 Space
\t 0x09 Tab
\x Character x
22
String Special Operators
Assume string variable a holds 'Hello' and variable b holds 'Python', then −
* Repetition - Creates new strings, concatenating multiple copies of the same string a*2 will give -
HelloHello
[] Slice - Gives the character from the given index a[1] will give e
[:] Range Slice - Gives the characters from the given range a[1:4] will give
ell
in Membership - Returns true if a character exists in the given string H in a will give 1
not in Membership - Returns true if a character does not exist in the given string M not in a will
give 1
r/R Raw String - Suppresses actual meaning of Escape characters. The syntax for raw print r'\n' prints
strings is exactly the same as for normal strings with the exception of the raw string \n and print
operator, the letter "r," which precedes the quotation marks. The "r" can be R'\n'prints \n
lowercase (r) or uppercase (R) and must be placed immediately preceding the first
quote mark.
#!/usr/bin/python
print "My name is %s and weight is %d kg!" % ('Zara', 21)
Here is the list of complete set of symbols which can be used along with % −
%c character
23
%o octal integer
- left justification
# add the octal leading zero ( '0' ) or hexadecimal leading '0x' or '0X', depending
on whether 'x' or 'X' were used.
m.n. m is the minimum total width and n is the number of digits to display after the
decimal point (if appl.)
Triple Quotes
Python's triple quotes comes to the rescue by allowing strings to span multiple lines, including verbatim
NEWLINEs, TABs, and any other special characters.
The syntax for triple quotes consists of three consecutive single or double quotes.
#!/usr/bin/python
para_str = """this is a long string that is made up of
several lines and non-printable characters such as
TAB ( \t ) and they will show up that way when displayed.
NEWLINEs within the string, whether explicitly given like
this within the brackets [ \n ], or just a NEWLINE within
the variable assignment will also show up."""
24
print para_str
When the above code is executed, it produces the following result. Note how every single special character
has been converted to its printed form, right down to the last NEWLINE at the end of the string between the
"up." and closing triple quotes. Also note that NEWLINEs occur either with an explicit carriage return at the
end of a line or its escape code (\n) −
Raw strings do not treat the backslash as a special character at all. Every character you put into a raw string
stays the way you wrote it −
#!/usr/bin/python
print 'C:\\nowhere'
C:\nowhere
Now let's make use of raw string. We would put expression in r'expression' as follows −
#!/usr/bin/python
print r'C:\\nowhere'
C:\\nowhere
Unicode String
Normal strings in Python are stored internally as 8-bit ASCII, while Unicode strings are stored as 16-bit
Unicode. This allows for a more varied set of characters, including special characters from most languages in
the world. I'll restrict my treatment of Unicode strings to the following −
#!/usr/bin/python
print u'Hello, world!'
Hello, world!
As you can see, Unicode strings use the prefix u, just as raw strings use the prefix r.
25
Python Lists
The most basic data structure in Python is the sequence. Each element of a sequence is assigned a number -
its position or index. The first index is zero, the second index is one, and so forth.
Python has six built-in types of sequences, but the most common ones are lists and tuples, which we would
see in this tutorial.
There are certain things you can do with all sequence types. These operations include indexing, slicing,
adding, multiplying, and checking for membership. In addition, Python has built-in functions for finding the
length of a sequence and for finding its largest and smallest elements.
Python Lists
The list is a most versatile datatype available in Python which can be written as a list of comma-separated
values (items) between square brackets. Important thing about a list is that items in a list need not be of the
same type.
Creating a list is as simple as putting different comma-separated values between square brackets. For
example −
Similar to string indices, list indices start at 0, and lists can be sliced, concatenated and so on.
#!/usr/bin/python
list1 = ['physics', 'chemistry', 1997, 2000];
list2 = [1, 2, 3, 4, 5, 6, 7 ];
list1[0]: physics
list2[1:5]: [2, 3, 4, 5]
Updating Lists
You can update single or multiple elements of lists by giving the slice on the left-hand side of the assignment
operator, and you can add to elements in a list with the append() method. For example −
26
#!/usr/bin/python
list = ['physics', 'chemistry', 1997, 2000];
#!/usr/bin/python
list1 = ['physics', 'chemistry', 1997, 2000];
print list1
del list1[2];
print "After deleting value at index 2 : "
print list1
In fact, lists respond to all of the general sequence operations we used on strings in the prior chapter.
27
[1, 2, 3] + [4, 5, 6] [1, 2, 3, 4, 5, 6] Concatenation
Python Tuples
A tuple is a sequence of immutable Python objects. 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.
Creating a tuple is as simple as putting different comma-separated values. Optionally you can put these
comma-separated values between parentheses also. For example −
tup1 = ();
To write a tuple containing a single value you have to include a comma, even though there is only one value
tup1 = (50,);
Like string indices, tuple indices start at 0, and they can be sliced, concatenated, and so on.
#!/usr/bin/python
28
tup1 = ('physics', 'chemistry', 1997, 2000);
tup2 = (1, 2, 3, 4, 5, 6, 7 );
tup1[0]: physics
tup2[1:5]: [2, 3, 4, 5]
Updating Tuples
Tuples are immutable which means you cannot update or change the values of tuple elements. You are able
to take portions of existing tuples to create new tuples as the following example demonstrates −
#!/usr/bin/python
tup1 = (12, 34.56);
tup2 = ('abc', 'xyz');
To explicitly remove an entire tuple, just use the del statement. For example:
#!/usr/bin/python
tup = ('physics', 'chemistry', 1997, 2000);
print tup
del tup;
print "After deleting tup : "
print tup
29
This produces the following result. Note an exception raised, this is because after del tup tuple does not exist
any more −
In fact, tuples respond to all of the general sequence operations we used on strings in the prior chapter −
No Enclosing Delimiters
Any set of multiple objects, comma-separated, written without identifying symbols, i.e., brackets for lists,
parentheses for tuples, etc., default to tuples, as indicated in these short examples −
#!/usr/bin/python
print 'abc', -4.24e93, 18+6.6j, 'xyz'
x, y = 1, 2;
print "Value of x , y : ", x,y
30
When the above code is executed, it produces the following result −
Python Dictionary
Each key is separated from its value by a colon (:), the items are separated by commas, and the whole thing
is enclosed in curly braces. An empty dictionary without any items is written with just two curly braces, like
this: {}.
Keys are unique within a dictionary while values may not be. The values of a dictionary can be of any type,
but the keys must be of an immutable data type such as strings, numbers, or tuples.
#!/usr/bin/python
dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'}
dict['Name']: Zara
dict['Age']: 7
If we attempt to access a data item with a key, which is not part of the dictionary, we get an error as follows
−
#!/usr/bin/python
dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'}
dict['Alice']:
Traceback (most recent call last):
File "test.py", line 4, in <module>
print "dict['Alice']: ", dict['Alice'];
KeyError: 'Alice'
Updating Dictionary
You can update a dictionary by adding a new entry or a key-value pair, modifying an existing entry, or
deleting an existing entry as shown below in the simple example −
#!/usr/bin/python
31
dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'}
dict['Age']: 8
dict['School']: DPS School
To explicitly remove an entire dictionary, just use the del statement. Following is a simple example −
#!/usr/bin/python
dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'}
This produces the following result. Note that an exception is raised because after del dict dictionary does not
exist any more −
dict['Age']:
Traceback (most recent call last):
File "test.py", line 8, in <module>
print "dict['Age']: ", dict['Age'];
TypeError: 'type' object is unsubscriptable
32
(a) More than one entry per key not allowed. Which means no duplicate key is allowed. When duplicate keys
encountered during assignment, the last assignment wins. For example −
#!/usr/bin/python
dict = {'Name': 'Zara', 'Age': 7, 'Name': 'Manni'}
dict['Name']: Manni
(b) Keys must be immutable. Which means you can use strings, numbers or tuples as dictionary keys but
something like ['key'] is not allowed. Following is a simple example:
#!/usr/bin/python
dict = {['Name']: 'Zara', 'Age': 7}
What is Tick?
Time intervals are floating-point numbers in units of seconds. Particular instants in time are expressed in
seconds since 12:00am, January 1, 1970(epoch).
There is a popular time module available in Python which provides functions for working with times, and for
converting between representations. The function time.time() returns the current system time in ticks since
12:00am, January 1, 1970(epoch).
Example
#!/usr/bin/python
import time; # This is required to include time module.
ticks = time.time()
print "Number of ticks since 12:00am, January 1, 1970:", ticks
Date arithmetic is easy to do with ticks. However, dates before the epoch cannot be represented in this form.
Dates in the far future also cannot be represented this way - the cutoff point is sometime in 2038 for UNIX
and Windows.
What is TimeTuple?
Many of Python's time functions handle time as a tuple of 9 numbers, as shown below −
1 Month 1 to 12
2 Day 1 to 31
3 Hour 0 to 23
4 Minute 0 to 59
The above tuple is equivalent to struct_time structure. This structure has following attributes −
0 tm_year 2008
1 tm_mon 1 to 12
2 tm_mday 1 to 31
3 tm_hour 0 to 23
4 tm_min 0 to 59
6 tm_wday 0 to 6 (0 is Monday)
34
To translate a time instant from a seconds since the epoch floating-point value into a time-tuple, pass the
floating-point value to a function (e.g., localtime) that returns a time-tuple with all nine items valid.
#!/usr/bin/python
import time;
localtime = time.localtime(time.time())
print "Local current time :", localtime
This would produce the following result, which could be formatted in any other presentable form −
#!/usr/bin/python
import time;
#!/usr/bin/python
import calendar
cal = calendar.month(2008, 1)
print "Here is the calendar:"
print cal
Python Functions
A function is a block of organized, reusable code that is used to perform a single, related action. Functions
provide better modularity for your application and a high degree of code reusing.
As you already know, Python gives you many built-in functions like print(), etc. but you can also create your
own functions. These functions are called user-defined functions.
Defining a Function
You can define functions to provide the required functionality. Here are simple rules to define a function in
Python.
Function blocks begin with the keyword def followed by the function name and parentheses ( ( ) ).
Any input parameters or arguments should be placed within these parentheses. You can also define
parameters inside these parentheses.
The first statement of a function can be an optional statement - the documentation string of the function
or docstring.
The code block within every function starts with a colon (:) and is indented.
The statement return [expression] exits a function, optionally passing back an expression to the caller. A
return statement with no arguments is the same as return None.
Syntax
def functionname( parameters ):
"function_docstring"
function_suite
return [expression]
By default, parameters have a positional behavior and you need to inform them in the same order that they
were defined.
Example
The following function takes a string as input parameter and prints it on standard screen.
Calling a Function
Defining a function only gives it a name, specifies the parameters that are to be included in the function and
structures the blocks of code.
Once the basic structure of a function is finalized, you can execute it by calling it from another function or
directly from the Python prompt. Following is the example to call printme() function −
#!/usr/bin/python
# Function definition is here
36
def printme( str ):
"This prints a passed string into this function"
print str
return;
# Now you can call printme function
printme("I'm first call to user defined function!")
printme("Again second call to the same function")
#!/usr/bin/python
# Function definition is here
def changeme( mylist ):
"This changes a passed list into this function"
mylist.append([1,2,3,4]);
print "Values inside the function: ", mylist
return
# Now you can call changeme function
mylist = [10,20,30];
changeme( mylist );
print "Values outside the function: ", mylist
Here, we are maintaining reference of the passed object and appending values in the same object. So, this
would produce the following result −
There is one more example where argument is being passed by reference and the reference is being
overwritten inside the called function.
#!/usr/bin/python
# Function definition is here
def changeme( mylist ):
"This changes a passed list into this function"
mylist = [1,2,3,4]; # This would assig new reference in mylist
37
print "Values inside the function: ", mylist
return
# Now you can call changeme function
mylist = [10,20,30];
changeme( mylist );
print "Values outside the function: ", mylist
The parameter mylist is local to the function changeme. Changing mylist within the function does not
affect mylist. The function accomplishes nothing and finally this would produce the following result:
Function Arguments
You can call a function by using the following types of formal arguments:
Required arguments
Keyword arguments
Default arguments
Variable-length arguments
Required arguments
Required arguments are the arguments passed to a function in correct positional order. Here, the number of
arguments in the function call should match exactly with the function definition.
To call the function printme(), you definitely need to pass one argument, otherwise it gives a syntax error as
follows −
#!/usr/bin/python
# Function definition is here
def printme( str ):
"This prints a passed string into this function"
print str
return;
# Now you can call printme function
printme()
Keyword arguments
38
Keyword arguments are related to the function calls. When you use keyword arguments in a function call,
the caller identifies the arguments by the parameter name.
This allows you to skip arguments or place them out of order because the Python interpreter is able to use the
keywords provided to match the values with parameters. You can also make keyword calls to
the printme() function in the following ways –
#!/usr/bin/python
# Function definition is here
def printme( str ):
"This prints a passed string into this function"
print str
return;
# Now you can call printme function
printme( str = "My string")
My string
The following example gives more clear picture. Note that the order of parameters does not matter.
#!/usr/bin/python
# Function definition is here
def printinfo( name, age ):
"This prints a passed info into this function"
print "Name: ", name
print "Age ", age
return;
# Now you can call printinfo function
printinfo( age=50, name="miki" )
Name: miki
Age 50
Default arguments
A default argument is an argument that assumes a default value if a value is not provided in the function call
for that argument. The following example gives an idea on default arguments, it prints default age if it is not
passed −
#!/usr/bin/python
39
# Function definition is here
def printinfo( name, age = 35 ):
"This prints a passed info into this function"
print "Name: ", name
print "Age ", age
return;
# Now you can call printinfo function
printinfo( age=50, name="miki" )
printinfo( name="miki" )
Name: miki
Age 50
Name: miki
Age 35
Variable-length arguments
You may need to process a function for more arguments than you specified while defining the function.
These arguments are called variable-lengtharguments and are not named in the function definition, unlike
required and default arguments.
An asterisk (*) is placed before the variable name that holds the values of all nonkeyword variable
arguments. This tuple remains empty if no additional arguments are specified during the function call.
Following is a simple example −
#!/usr/bin/python
# Function definition is here
def printinfo( arg1, *vartuple ):
"This prints a variable passed arguments"
print "Output is: "
print arg1
for var in vartuple:
print var
return;
# Now you can call printinfo function
40
printinfo( 10 )
printinfo( 70, 60, 50 )
Output is:
10
Output is:
70
60
50
Lambda forms can take any number of arguments but return just one value in the form of an expression. They
cannot contain commands or multiple expressions.
An anonymous function cannot be a direct call to print because lambda requires an expression
Lambda functions have their own local namespace and cannot access variables other than those in their
parameter list and those in the global namespace.
Although it appears that lambda's are a one-line version of a function, they are not equivalent to inline
statements in C or C++, whose purpose is by passing function stack allocation during invocation for
performance reasons.
Syntax
The syntax of lambda functions contains only a single statement, which is as follows −
#!/usr/bin/python
# Function definition is here
sum = lambda arg1, arg2: arg1 + arg2;
# Now you can call sum as a function
print "Value of total : ", sum( 10, 20 )
print "Value of total : ", sum( 20, 20 )
Value of total : 30
Value of total : 40
41
All the above examples are not returning any value. You can return a value from a function as follows −
#!/usr/bin/python
# Function definition is here
def sum( arg1, arg2 ):
# Add both the parameters and return them."
total = arg1 + arg2
print "Inside the function : ", total
return total;
# Now you can call sum function
total = sum( 10, 20 );
print "Outside the function : ", total
Scope of Variables
All variables in a program may not be accessible at all locations in that program. This depends on where you
have declared a variable.
The scope of a variable determines the portion of the program where you can access a particular identifier.
There are two basic scopes of variables in Python −
Global variables
Local variables
Global vs. Local variables
Variables that are defined inside a function body have a local scope, and those defined outside have a global
scope.
This means that local variables can be accessed only inside the function in which they are declared, whereas
global variables can be accessed throughout the program body by all functions. When you call a function, the
variables declared inside it are brought into scope. Following is a simple example −
#!/usr/bin/python
total = 0; # This is global variable.
# Function definition is here
def sum( arg1, arg2 ):
# Add both the parameters and return them."
total = arg1 + arg2; # Here total is local variable.
print "Inside the function local total : ", total
return total;
42
# Now you can call sum function
sum( 10, 20 );
print "Outside the function global total : ", total
Python Modules
A module allows you to logically organize your Python code. Grouping related code into a module makes
the code easier to understand and use. A module is a Python object with arbitrarily named attributes that you
can bind and reference.
Simply, a module is a file consisting of Python code. A module can define functions, classes and variables. A
module can also include runnable code.
Example
The Python code for a module named aname normally resides in a file named aname.py. Here's an example
of a simple module, support.py
When the interpreter encounters an import statement, it imports the module if the module is present in the
search path. A search path is a list of directories that the interpreter searches before importing a module. For
example, to import the module hello.py, you need to put the following command at the top of the script −
#!/usr/bin/python
# Import module support
import support
# Now you can call defined function that module as follows
support.print_func("Zara")
Hello : Zara
43
A module is loaded only once, regardless of the number of times it is imported. This prevents the module
execution from happening over and over again if multiple imports occur.
For example, to import the function fibonacci from the module fib, use the following statement −
This statement does not import the entire module fib into the current namespace; it just introduces the item
fibonacci from the module fib into the global symbol table of the importing module.
This provides an easy way to import all the items from a module into the current namespace; however, this
statement should be used sparingly.
Locating Modules
When you import a module, the Python interpreter searches for the module in the following sequences −
If the module isn't found, Python then searches each directory in the shell variable PYTHONPATH.
If all else fails, Python checks the default path. On UNIX, this default path is normally /usr/local/lib/python/.
The module search path is stored in the system module sys as the sys.pathvariable. The sys.path variable
contains the current directory, PYTHONPATH, and the installation-dependent default.
set PYTHONPATH=c:\python20\lib;
set PYTHONPATH=/usr/local/lib/python
44
Namespaces and Scoping
Variables are names (identifiers) that map to objects. A namespace is a dictionary of variable names (keys)
and their corresponding objects (values).
A Python statement can access variables in a local namespace and in the global namespace. If a local and a
global variable have the same name, the local variable shadows the global variable.
Each function has its own local namespace. Class methods follow the same scoping rule as ordinary
functions.
Python makes educated guesses on whether variables are local or global. It assumes that any variable
assigned a value in a function is local.
Therefore, in order to assign a value to a global variable within a function, you must first use the global
statement.
The statement global VarName tells Python that VarName is a global variable. Python stops searching the
local namespace for the variable.
For example, we define a variable Money in the global namespace. Within the function Money, we
assign Money a value, therefore Python assumes Money as a local variable. However, we accessed the value
of the local variable Moneybefore setting it, so an UnboundLocalError is the result. Uncommenting the
global statement fixes the problem.
#!/usr/bin/python
Money = 2000
def AddMoney():
# Uncomment the following line to fix the code:
# global Money
Money = Money + 1
print Money
AddMoney()
print Money
The list contains the names of all the modules, variables and functions that are defined in a module.
Following is a simple example −
#!/usr/bin/python
# Import built-in module math
import math
content = dir(math)
45
print content
Here, the special string variable __name__ is the module's name, and __file__is the filename from which the
module was loaded.
If locals() is called from within a function, it will return all the names that can be accessed locally from that
function.
If globals() is called from within a function, it will return all the names that can be accessed globally from
that function.
The return type of both these functions is dictionary. Therefore, names can be extracted using the keys()
function.
Therefore, if you want to reexecute the top-level code in a module, you can use the reload() function. The
reload() function imports a previously imported module again. The syntax of the reload() function is this −
reload(module_name)
Here, module_name is the name of the module you want to reload and not the string containing the module
name. For example, to reload hello module, do the following −
reload(hello)
Packages in Python
A package is a hierarchical file directory structure that defines a single Python application environment that
consists of modules and subpackages and sub-subpackages, and so on.
Consider a file Pots.py available in Phone directory. This file has following line of source code −
#!/usr/bin/python
46
def Pots():
print "I'm Pots Phone"
Similar way, we have another two files having different functions with the same name as above −
Phone/__init__.py
To make all of your functions available when you've imported Phone, you need to put explicit import
statements in __init__.py as follows −
After you add these lines to __init__.py, you have all of these classes available when you import the Phone
package.
#!/usr/bin/python
# Now import your Phone Package.
import Phone
Phone.Pots()
Phone.Isdn()
Phone.G3()
In the above example, we have taken example of a single functions in each file, but you can keep multiple
functions in your files. You can also define different Python classes in those files and then you can create
your packages out of those classes.
47
#!/usr/bin/python
print "Python is really a great language,", "isn't it?"
raw_input
input
The raw_input Function
The raw_input([prompt]) function reads one line from standard input and returns it as a string (removing the
trailing newline).
#!/usr/bin/python
str = raw_input("Enter your input: ");
print "Received input is : ", str
This prompts you to enter any string and it would display same string on the screen. When I typed "Hello
Python!", its output is like this −
#!/usr/bin/python
str = input("Enter your input: ");
print "Received input is : ", str
This would produce the following result against the entered input −
48
Python provides basic functions and methods necessary to manipulate files by default. You can do most of
the file manipulation using a file object.
Syntax
file object = open(file_name [, access_mode][, buffering])
file_name: The file_name argument is a string value that contains the name of the file that you want to
access.
access_mode: The access_mode determines the mode in which the file has to be opened, i.e., read, write,
append, etc. A complete list of possible values is given below in the table. This is optional parameter and the
default file access mode is read (r).
buffering: If the buffering value is set to 0, no buffering takes place. If the buffering value is 1, line buffering is
performed while accessing a file. If you specify the buffering value as an integer greater than 1, then buffering
action is performed with the indicated buffer size. If negative, the buffer size is the system default(default
behavior).
Here is a list of the different modes of opening a file −
Modes Description
r Opens a file for reading only. The file pointer is placed at the beginning of the file. This is the default
mode.
rb Opens a file for reading only in binary format. The file pointer is placed at the beginning of the file. This is
the default mode.
r+ Opens a file for both reading and writing. The file pointer placed at the beginning of the file.
rb+ Opens a file for both reading and writing in binary format. The file pointer placed at the beginning of the
file.
w Opens a file for writing only. Overwrites the file if the file exists. If the file does not exist, creates a new
file for writing.
wb Opens a file for writing only in binary format. Overwrites the file if the file exists. If the file does not exist,
creates a new file for writing.
w+ Opens a file for both writing and reading. Overwrites the existing file if the file exists. If the file does not
exist, creates a new file for reading and writing.
wb+ Opens a file for both writing and reading in binary format. Overwrites the existing file if the file exists. If
the file does not exist, creates a new file for reading and writing.
a Opens a file for appending. The file pointer is at the end of the file if the file exists. That is, the file is in
the append mode. If the file does not exist, it creates a new file for writing.
ab Opens a file for appending in binary format. The file pointer is at the end of the file if the file exists. That
is, the file is in the append mode. If the file does not exist, it creates a new file for writing.
49
a+ Opens a file for both appending and reading. The file pointer is at the end of the file if the file exists. The
file opens in the append mode. If the file does not exist, it creates a new file for reading and writing.
ab+ Opens a file for both appending and reading in binary format. The file pointer is at the end of the file if
the file exists. The file opens in the append mode. If the file does not exist, it creates a new file for
reading and writing.
Attribute Description
file.softspace Returns false if space explicitly required with print, true otherwise.
Example
#!/usr/bin/python
# Open a file
fo = open("foo.txt", "wb")
print "Name of the file: ", fo.name
print "Closed or not : ", fo.closed
print "Opening mode : ", fo.mode
print "Softspace flag : ", fo.softspace
Python automatically closes a file when the reference object of a file is reassigned to another file. It is a good
practice to use the close() method to close a file.
Syntax
fileObject.close();
Example
#!/usr/bin/python
50
# Open a file
fo = open("foo.txt", "wb")
print "Name of the file: ", fo.name
The write() method does not add a newline character ('\n') to the end of the string −
Syntax
fileObject.write(string);
Here, passed parameter is the content to be written into the opened file.
Example
#!/usr/bin/python
# Open a file
fo = open("foo.txt", "wb")
fo.write( "Python is a great language.\nYeah its great!!\n");
# Close opend file
fo.close()
The above method would create foo.txt file and would write given content in that file and finally it would
close that file. If you would open this file, it would have following content.
Syntax
fileObject.read([count]);
51
Here, passed parameter is the number of bytes to be read from the opened file. This method starts reading
from the beginning of the file and if count is missing, then it tries to read as much as possible, maybe until
the end of file.
Example
Let's take a file foo.txt, which we created above.
#!/usr/bin/python
# Open a file
fo = open("foo.txt", "r+")
str = fo.read(10);
print "Read String is : ", str
# Close opend file
fo.close()
File Positions
The tell() method tells you the current position within the file; in other words, the next read or write will
occur at that many bytes from the beginning of the file.
The seek(offset[, from]) method changes the current file position. The offsetargument indicates the number of
bytes to be moved. The from argument specifies the reference position from where the bytes are to be moved.
If from is set to 0, it means use the beginning of the file as the reference position and 1 means use the current
position as the reference position and if it is set to 2 then the end of the file would be taken as the reference
position.
Example
Let us take a file foo.txt, which we created above.
#!/usr/bin/python
# Open a file
fo = open("foo.txt", "r+")
str = fo.read(10);
print "Read String is : ", str
To use this module you need to import it first and then you can call any related functions.
Syntax
os.rename(current_file_name, new_file_name)
Example
Following is the example to rename an existing file test1.txt:
#!/usr/bin/python
import os
# Rename a file from test1.txt to test2.txt
os.rename( "test1.txt", "test2.txt" )
Syntax
os.remove(file_name)
Example
Following is the example to delete an existing file test2.txt −
#!/usr/bin/python
import os
53
# Delete file test2.txt
os.remove("text2.txt")
Directories in Python
All files are contained within various directories, and Python has no problem handling these too.
The os module has several methods that help you create, remove, and change directories.
Syntax
os.mkdir("newdir")
Example
Following is the example to create a directory test in the current directory −
#!/usr/bin/python
import os
Syntax
os.chdir("newdir")
Example
Following is the example to go into "/home/newdir" directory −
#!/usr/bin/python
import os
Syntax
os.getcwd()
54
Example
Following is the example to give current directory −
#!/usr/bin/python
import os
Syntax:
os.rmdir('dirname')
Example
Following is the example to remove "/tmp/test" directory. It is required to give fully qualified name of the
directory, otherwise it would search for that directory in the current directory.
#!/usr/bin/python
import os
File Object Methods: The file object provides functions to manipulate files.
ython provides two very important features to handle any unexpected error in your Python programs and to
add debugging capabilities in them −
Exception Handling: This would be covered in this tutorial. Here is a list standard Exceptions available in
Python: Standard Exceptions.
55
EXCEPTION NAME DESCRIPTION
StopIteration Raised when the next() method of an iterator does not point to any object.
StandardError Base class for all built-in exceptions except StopIteration and SystemExit.
ArithmeticError Base class for all errors that occur for numeric calculation.
OverflowError Raised when a calculation exceeds maximum limit for a numeric type.
ZeroDivisonError Raised when division or modulo by zero takes place for all numeric types.
EOFError Raised when there is no input from either the raw_input() or input() function and the
end of file is reached.
KeyboardInterrupt Raised when the user interrupts program execution, usually by pressing Ctrl+c.
NameError Raised when an identifier is not found in the local or global namespace.
UnboundLocalError Raised when trying to access a local variable in a function or method but no value has
EnvironmentError been assigned to it.
Base class for all exceptions that occur outside the Python environment.
IOError Raised when an input/ output operation fails, such as the print statement or the open()
IOError function when trying to open a file that does not exist.
Raised for operating system-related errors.
SystemError Raised when the interpreter finds an internal problem, but when this error is
encountered the Python interpreter does not exit.
SystemExit Raised when Python interpreter is quit by using the sys.exit() function. If not handled in
the code, causes the interpreter to exit.
Raised when Python Raised when an operation or function is attempted that is invalid for the specified data
interpreter is quit by type.
using the sys.exit()
function. If not handled
56
in the code, causes the
interpreter to exit.
ValueError Raised when the built-in function for a data type has the valid type of arguments, but
the arguments have invalid values specified.
RuntimeError Raised when a generated error does not fall into any category.
NotImplementedError Raised when an abstract method that needs to be implemented in an inherited class is
not actually implemented.
Assertions in Python
An assertion is a sanity-check that you can turn on or turn off when you are done with your testing of the
program.
The easiest way to think of an assertion is to liken it to a raise-if statement (or to be more accurate, a raise-if-
not statement). An expression is tested, and if the result comes up false, an exception is raised.
Assertions are carried out by the assert statement, the newest keyword to Python, introduced in version 1.5.
Programmers often place assertions at the start of a function to check for valid input, and after a function call
to check for valid output.
If the assertion fails, Python uses ArgumentExpression as the argument for the AssertionError.
AssertionError exceptions can be caught and handled like any other exception using the try-except statement,
but if not handled, they will terminate the program and produce a traceback.
Example
Here is a function that converts a temperature from degrees Kelvin to degrees Fahrenheit. Since zero degrees
Kelvin is as cold as it gets, the function bails out if it sees a negative temperature −
#!/usr/bin/python
def KelvinToFahrenheit(Temperature):
assert (Temperature >= 0),"Colder than absolute zero!"
return ((Temperature-273)*1.8)+32
print KelvinToFahrenheit(273)
print int(KelvinToFahrenheit(505.78))
print KelvinToFahrenheit(-5)
What is Exception?
An exception is an event, which occurs during the execution of a program that disrupts the normal flow of
the program's instructions. In general, when a Python script encounters a situation that it cannot cope with, it
raises an exception. An exception is a Python object that represents an error.
When a Python script raises an exception, it must either handle the exception immediately otherwise it
terminates and quits.
Handling an exception
If you have some suspicious code that may raise an exception, you can defend your program by placing the
suspicious code in a try: block. After the try: block, include an except: statement, followed by a block of
code which handles the problem as elegantly as possible.
Syntax
Here is simple syntax of try....except...else blocks −
try:
You do your operations here;
......................
except ExceptionI:
If there is ExceptionI, then execute this block.
except ExceptionII:
If there is ExceptionII, then execute this block.
......................
else:
If there is no exception then execute this block.
A single try statement can have multiple except statements. This is useful when the try block contains statements
that may throw different types of exceptions.
You can also provide a generic except clause, which handles any exception.
After the except clause(s), you can include an else-clause. The code in the else-block executes if the code in the try:
block does not raise an exception.
The else-block is a good place for code that does not need the try: block's protection.
58
Example
This example opens a file, writes content in the, file and comes out gracefully because there is no problem at
all −
#!/usr/bin/python
try:
fh = open("testfile", "w")
fh.write("This is my test file for exception handling!!")
except IOError:
print "Error: can\'t find file or read data"
else:
print "Written content in the file successfully"
fh.close()
Example
This example tries to open a file where you do not have write permission, so it raises an exception −
#!/usr/bin/python
try:
fh = open("testfile", "r")
fh.write("This is my test file for exception handling!!")
except IOError:
print "Error: can\'t find file or read data"
else:
print "Written content in the file successfully"
try:
You do your operations here;
......................
except:
If there is any exception, then execute this block.
......................
else:
59
If there is no exception then execute this block.
This kind of a try-except statement catches all the exceptions that occur. Using this kind of try-except
statement is not considered a good programming practice though, because it catches all exceptions but does
not make the programmer identify the root cause of the problem that may occur.
try:
You do your operations here;
......................
except(Exception1[, Exception2[,...ExceptionN]]]):
If there is any exception from the given exception list,
then execute this block.
......................
else:
If there is no exception then execute this block.
try:
You do your operations here;
......................
Due to any exception, this may be skipped.
finally:
This would always be executed.
......................
You cannot use else clause as well along with a finally clause.
Example
#!/usr/bin/python
try:
fh = open("testfile", "w")
fh.write("This is my test file for exception handling!!")
finally:
print "Error: can\'t find file or read data"
If you do not have permission to open the file in writing mode, then this will produce the following result:
try:
fh = open("testfile", "w")
try:
fh.write("This is my test file for exception handling!!")
finally:
print "Going to close the file"
fh.close()
except IOError:
print "Error: can\'t find file or read data"
When an exception is thrown in the try block, the execution immediately passes to the finally block. After all
the statements in the finally block are executed, the exception is raised again and is handled in
the except statements if present in the next higher layer of the try-except statement.
Argument of an Exception
An exception can have an argument, which is a value that gives additional information about the problem.
The contents of the argument vary by exception. You capture an exception's argument by supplying a
variable in the except clause as follows −
try:
You do your operations here;
......................
except ExceptionType, Argument:
You can print value of Argument here...
If you write the code to handle a single exception, you can have a variable follow the name of the exception
in the except statement. If you are trapping multiple exceptions, you can have a variable follow the tuple of
the exception.
This variable receives the value of the exception mostly containing the cause of the exception. The variable
can receive a single value or multiple values in the form of a tuple. This tuple usually contains the error
string, the error number, and an error location.
Example
Following is an example for a single exception −
#!/usr/bin/python
# Define a function here.
def temp_convert(var):
try:
return int(var)
except ValueError, Argument:
print "The argument does not contain numbers\n", Argument
# Call above function here.
temp_convert("xyz");
61
This produces the following result −
Raising an Exceptions
You can raise exceptions in several ways by using the raise statement. The general syntax for
the raise statement is as follows.
Syntax
raise [Exception [, args [, traceback]]]
Here, Exception is the type of exception (for example, NameError) and argument is a value for the exception
argument. The argument is optional; if not supplied, the exception argument is None.
The final argument, traceback, is also optional (and rarely used in practice), and if present, is the traceback
object used for the exception.
Example
An exception can be a string, a class or an object. Most of the exceptions that the Python core raises are
classes, with an argument that is an instance of the class. Defining new exceptions is quite easy and can be
done as follows −
Note: In order to catch an exception, an "except" clause must refer to the same exception thrown either class
object or simple string. For example, to capture above exception, we must write the except clause as follows
−
try:
Business Logic here...
except "Invalid level!":
Exception handling here...
else:
Rest of the code here...
User-Defined Exceptions
Python also allows you to create your own exceptions by deriving classes from the standard built-in
exceptions.
Here is an example related to RuntimeError. Here, a class is created that is subclassed from RuntimeError.
This is useful when you need to display more specific information when an exception is caught.
62
In the try block, the user-defined exception is raised and caught in the except block. The variable e is used to
create an instance of the class Networkerror.
class Networkerror(RuntimeError):
def __init__(self, arg):
self.args = arg
So once you defined above class, you can raise the exception as follows −
try:
raise Networkerror("Bad hostname")
except Networkerror,e:
print e.args
63