Python Programming
Python Programming
Sc – Computer Science
PAPER X - PYTHON PROGRAMMING
Subject Code – 33B
UNIT-I
Python Overview
Python is a high-level, interpreted, interactive and object-oriented scripting language. Python is designed to be highly readable. It
uses English keywords frequently where as other languages use punctuation, and it has fewer syntactical constructions than other
languages.
Python is Interpreted − Python is processed at runtime by the interpreter. You do not need to compile your program
before executing it. This is similar to PERL and PHP.
Python is Interactive − You can actually sit at a Python prompt and interact with the interpreter directly to write your
programs.
Python is Object-Oriented − Python supports Object-Oriented style or technique of programming that encapsulates
code within objects.
Python is a Beginner's Language − Python is a great language for the beginner-level programmers and supports the
development of a wide range of applications from simple text processing to WWW browsers to games.
Python Features
Python's features include −
Easy-to-learn − Python has few keywords, simple structure, and a clearly defined syntax. This allows the student to pick
up the language quickly.
Easy-to-read − Python code is more clearly defined and visible to the eyes.
A broad standard library − Python's bulk of the library is very portable and cross-platform compatible on UNIX,
Windows, and Macintosh.
Interactive Mode − Python has support for an interactive mode which allows interactive testing and debugging of
snippets of code.
Portable − Python can run on a wide variety of hardware platforms and has the same interface on all platforms.
Extendable − You can add low-level modules to the Python interpreter. These modules enable programmers to add to or
customize their tools to be more efficient.
GUI Programming − Python supports GUI applications that can be created and ported to many system calls, libraries
and windows systems, such as Windows MFC, Macintosh, and the X Window system of Unix.
Scalable − Python provides a better structure and support for large programs than shell scripting.
Apart from the above-mentioned features, Python has a big list of good features, few are listed below −
It can be used as a scripting language or can be compiled to byte-code for building large applications.
It provides very high-level dynamic data types and supports dynamic type checking.
Python - Numbers
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 del statement. 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
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 f ollowed 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.
Number Type Conversion
Python converts numbers internally in an expression containing mixed types to a common type for evaluation. But sometimes, yo u
need to coerce a number explicitly from one type to another to satisfy the requirements of an operator or function parameter.
Type complex(x) to convert x to a complex number with real part x and imaginary part zero.
Type complex(x, y) to convert x and y to a complex number with real part x and imaginary part y. x and y are numeric
expressions
Mathematical Functions
Python includes following functions that perform mathematical calculations.
1 abs(x)
The absolute value of x: the (positive) distance between x and zero.
2 ceil(x)
The ceiling of x: the smallest integer not less than x
3 cmp(x, y)
-1 if x < y, 0 if x == y, or 1 if x > y
4 exp(x)
The exponential of x: ex
5 fabs(x)
The absolute value of x.
6 floor(x)
The floor of x: the largest integer not greater than x
7 log(x)
The natural logarithm of x, for x> 0
8 log10(x)
The base-10 logarithm of x for x> 0.
9 max(x1, x2,...)
The largest of its arguments: the value closest to positive infinity
10 min(x1, x2,...)
The smallest of its arguments: the value closest to negative infinity
11 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.
12 pow(x, y)
The value of x**y.
13 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.
14 sqrt(x)
The square root of x for x > 0
1 choice(seq)
A random item from a list, tuple, or string.
3 random()
A random float r, such that 0 is less than or equal to r and r is less than 1
4 seed([x])
Sets the integer starting value used in generating random numbers. Call this function before
calling any other random module function. Returns None.
5 shuffle(lst)
Randomizes the items of a list in place. Returns None.
6 uniform(x, y)
A random float r, such that x is less than or equal to r and r is less than y
Trigonometric Functions
Python includes following functions that perform trigonometric calculations.
1 acos(x)
Return the arc cosine of x, in radians.
2 asin(x)
Return the arc sine of x, in radians.
3 atan(x)
Return the arc tangent of x, in radians.
4 atan2(y, x)
Return atan(y / x), in radians.
5 cos(x)
Return the cosine of x radians.
6 hypot(x, y)
Return the Euclidean norm, sqrt(x*x + y*y).
7 sin(x)
Return the sine of x radians.
8 tan(x)
Return the tangent of x radians.
9 degrees(x)
Converts angle x from radians to degrees.
10 radians(x)
Converts angle x from degrees to radians.
Mathematical Constants
The module also defines two mathematical constants −
1 pi
The mathematical constant pi.
2 e
The mathematical constant e.
Type the following text at the Python prompt and press the Enter −
If you are running new version of Python, then you would need to use print statement with parenthesis as in print ("Hello,
Python!");. However in Python version 2.4.3, this produces the following result −
Hello, Python!
We assume that you have Python interpreter set in PATH variable. Now, try to run this program as follows −
$ python [Link]
Let us try another way to execute a Python script. Here is the modified [Link] file −
#!/usr/bin/python
We assume that you have Python interpreter available in /usr/bin directory. Now, try to run this program as follows −
Python Identifiers
A Python identifier is a name used to identify a variable, function, class, module or other object. An identifier starts with a letter A to
Z or a to z or an underscore (_) followed by zero or more letters, underscores and digits (0 to 9).
Python does not allow punctuation characters such as @, $, and % within identifiers. Python is a case sensitive programming
language. Thus, Manpower and manpower are two different identifiers in Python.
Here are naming conventions for Python identifiers −
Class names start with an uppercase letter. All other identifiers start with a lowercase letter.
Starting an identifier with a single leading underscore indicates that the identifier is private.
Starting an identifier with two leading underscores indicates a strongly private identifier.
If the identifier also ends with two trailing underscores, the identifier is a language-defined special name.
Reserved Words
The following list shows the Python keywords. These are reserved words and you cannot use them as constant or variabl e or any
other identifier names. All the Python keywords contain lowercase letters only.
and exec not
assert finally or
def if return
elif in while
else is with
if True:
print "Answer"
print "True"
else:
print "Answer"
print "False"
Thus, in Python all the continuous lines indented with same number of spaces would form a block. The following example has
various statement blocks −
Note − Do not try to understand the logic at this point of time. Just make sure you understood various blocks even if they are
without braces.
#!/usr/bin/python
import sys
try:
# open file stream
print file_text
Multi-Line Statements
Statements in Python typically end with a new line. Python does, however, allow the use of the line continuation character ( \) to
denote that the line should continue. For example −
total = item_one + \
item_two + \
item_three
Statements contained within the [], {}, or () brackets do not need to use the line continuation character. For example −
days = ['Monday', 'Tuesday', 'Wednesday',
'Thursday', 'Friday']
Quotation in Python
Python accepts single ('), double (") and triple (''' or """) quotes to denote string literals, as long as the same type of quote starts
and ends the string.
The triple quotes are used to span the string across multiple lines. For example, all the following are legal −
word = 'word'
sentence = "This is a sentence."
paragraph = """This is a paragraph. It is
made up of multiple lines and sentences."""
Comments in Python
A hash sign (#) that is not inside a string literal begins a comment. All characters after the # and up to the end of the physical line
are part of the comment and the Python interpreter ignores them.
#!/usr/bin/python
# First comment
print "Hello, Python!" # second comment
You can type a comment on the same line after a statement or expression −
name = "Madisetti" # This is again comment
#!/usr/bin/python
Here, "\n\n" is used to create two new lines before displaying the actual line. Once the user presses the key, the program ends.
This is a nice trick to keep a console window open until the user is done with an application.
$ python -h
usage: python [option] ... [-c cmd | -m mod | file | -] [arg] ...
Options and arguments (and corresponding environment variables):
-c cmd : program passed in as string (terminates option list)
-d : debug output from parser (also PYTHONDEBUG=x)
-E : ignore environment variables (such as PYTHONPATH)
-h : print this help message and exit
[ etc. ]
You can also program your script in such a way that it should accept various options. Command Line Arguments is an advanced
topic and should be studied a bit later once you have gone through rest of the Python concepts.
print counter
print miles
print name
Here, 100, 1000.0 and "John" are the values assigned to counter, miles, and name variables, respectively. This produces the
following result −
100
1000.0
John
Multiple Assignment
Python allows you to assign a single value to several variables simultaneously. For example −
a=b=c=1
Here, an integer object is created with the value 1, and all three variables are assigned to the same memory location. You can also
assign multiple objects to multiple variables. For example −
a,b,c = 1,2,"john"
Here, two integer objects with values 1 and 2 are assigned to variables a and b respectively, and one string object with the value
"john" is assigned to the variable c.
Standard Data Types
The data stored in memory can be of many types. For example, a person's age is stored as a numeric value and his or her address
is stored as alphanumeric characters. Python has various standard data types that are used to define the operations possible on
them and the storage method for each of them.
Python has five standard data types −
Numbers
String
List
Tuple
Dictionary
Python Numbers
Number data types store numeric values. 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 del statement. 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
long (long integers, they can also be represented in octal and hexadecimal)
Examples
Here are some examples of numbers −
A complex number consists of an ordered pair of real floating-point numbers denoted by x + yj, where x and y are the real
numbers and j is the imaginary unit.
Python Strings
Strings in Python are identified as a contiguous set of characters represented in the quotation marks. Python allows for eith er pairs
of single or double quotes. Subsets of strings can be taken using the slice operator ([ ] and [:] ) with indexes starting at 0 in the
beginning of the string and working their way from -1 at the end.
The plus (+) sign is the string concatenation operator and the asterisk (*) is the repetition operator. For example −
#!/usr/bin/python
Python Lists
Lists are the most versatile of Python's compound data types. A list contains items separated by commas and enclosed within
square brackets ([]). To some extent, lists are similar to arrays in C. One difference between them is that all the items bel onging to
a list can be of different data type.
The values stored in a list can be accessed using the slice operator ([ ] and [:]) with indexes starting at 0 in the beginning of the list
and working their way to end -1. The plus (+) sign is the list concatenation operator, and the asterisk (*) is the repetition operator.
For example −
#!/usr/bin/python
Python Tuples
A tuple is another sequence data type that is similar to the list. A tuple consists of a number of values separated by commas.
Unlike lists, however, tuples are enclosed within parentheses.
The main differences between lists and tuples are: Lists are enclosed in brackets ( [ ] ) and their elements and size can be
changed, while tuples are enclosed in parentheses ( ( ) ) and cannot be updated. Tuples can be thought of as read-only lists. For
example −
#!/usr/bin/python
tuple = ( 'abcd', 786 , 2.23, 'john', 70.2 )
tinytuple = (123, 'john')
print tuple # Prints the complete tuple
print tuple[0] # Prints first element of the tuple
print tuple[1:3] # Prints elements of the tuple starting from 2nd till 3rd
print tuple[2:] # Prints elements of the tuple starting from 3rd element
print tinytuple * 2 # Prints the contents of the tuple twice
print tuple + tinytuple # Prints concatenated tuples
The following code is invalid with tuple, because we attempted to update a tuple, which is not allowed. Similar case is possi ble with
lists −
#!/usr/bin/python
tuple = ( 'abcd', 786 , 2.23, 'john', 70.2 )
list = [ 'abcd', 786 , 2.23, 'john', 70.2 ]
tuple[2] = 1000 # Invalid syntax with tuple
list[2] = 1000 # Valid syntax with list
Python Dictionary
Python's dictionaries are kind of hash table type. They work like associative arrays or hashes found in Perl and consist of k ey-
value pairs. A dictionary key can be almost any Python type, but are usually numbers or strings. Values, on the other hand, can be
any arbitrary Python object.
Dictionaries are enclosed by curly braces ({ }) and values can be assigned and accessed using square braces ([]). For example −
#!/usr/bin/python
dict = {}
dict['one'] = "This is one"
dict[2] = "This is two"
Dictionaries have no concept of order among elements. It is incorrect to say that the elements are "out of order"; they are s imply
unordered.
1 int(x [,base])
Converts x to an integer. base specifies the base if x is a string.
2 long(x [,base] )
Converts x to a long integer. base specifies the base if x is a string.
3 float(x)
Converts x to a floating-point number.
4 complex(real [,imag])
Creates a complex number.
5 str(x)
Converts object x to a string representation.
6 repr(x)
Converts object x to an expression string.
7 eval(str)
Evaluates a string and returns an object.
8 tuple(s)
Converts s to a tuple.
9 list(s)
Converts s to a list.
10 set(s)
Converts s to a set.
11 dict(d)
Creates a dictionary. d must be a sequence of (key,value) tuples.
12 frozenset(s)
Converts s to a frozen set.
13 chr(x)
Converts an integer to a character.
14 unichr(x)
Converts an integer to a Unicode character.
15 ord(x)
Converts a single character to its integer value.
16 hex(x)
Converts an integer to a hexadecimal string.
17 oct(x)
Converts an integer to an octal string.
Types of Operator
Python language supports the following types of operators.
Arithmetic Operators
Assignment Operators
Logical Operators
Bitwise Operators
Membership Operators
Identity Operators
Let us have a look on all operators one by one.
- Subtraction Subtracts right hand operand from left hand operand. a – b = -10
% Modulus Divides left hand operand by right hand operand and returns remainder b%a=0
** Exponent Performs exponential (power) calculation on operators a**b =10 to the power
20
// Floor Division - The division of operands where the result is the quotient in which the digits 9//2 = 4 and 9.0//2.0
after the decimal point are removed. But if one of the operands is negative, the result is = 4.0, -11//3 = -4, -
floored, i.e., 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. (a != b) is 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 true.
condition becomes true.
< If the value of left operand is less than the value of right operand, then condition (a < b) is true.
becomes true.
>= If the value of left operand is greater than or equal to the value of right operand, (a >= b) is not true.
then condition becomes 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.
Python Assignment Operators
Assume variable a holds 10 and variable b holds 20, then −
[ Show Example ]
+= Add AND It adds right operand to the left operand and assign the result to left
c += a is equivalent to c = c +
operand
a
-= Subtract It subtracts right operand from the left operand and assign the result
c -= a is equivalent to c = c -
AND to left operand
a
*= Multiply AND It multiplies right operand with the left operand and assign the result
c *= a is equivalent to c = c *
to left operand
a
/= Divide AND It divides left operand with the right operand and assign the result to
c /= a is equivalent to c = c /
left operand
a
%= Modulus It takes modulus using two operands and assign the result to left
c %= a is equivalent to c = c
AND operand
%a
//= Floor It performs floor division on operators and assign value to the left
c //= a is equivalent to c = c //
Division operand
a
& Binary AND Operator copies a bit to the result if it exists in both (a & b) (means 0000
operands 1100)
^ Binary XOR It copies the bit if it is set in one operand but not both. (a ^ b) = 49 (means
0011 0001)
<< Binary Left Shift The left operands value is moved left by the number of bits a << 2 = 240
specified by the right operand. (means 1111 0000)
>> Binary Right Shift The left operands value is moved right by the number of a >> 2 = 15 (means
bits specified by the right operand. 0000 1111)
and If both the operands are true then condition becomes true. (a and b)
is true.
Logical
AND
not in Evaluates to true if it does not finds a variable in the specified sequence x not in y,
and false otherwise. here not
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 the same x is y,
object and false otherwise. here is results
in 1 if id(x)
equals id(y).
is not Evaluates to false if the variables on either side of the operator point to the x is not y,
same object and true otherwise. here is
not results in
1 if id(x) is not
equal to id(y).
1 **
Exponentiation (raise to the power)
2 ~+-
Complement, unary plus and minus (method names for the last two are +@
and -@)
3 * / % //
Multiply, divide, modulo and floor division
4 +-
Addition and subtraction
5 >> <<
Right and left bitwise shift
6 &
Bitwise 'AND'
7 ^|
Bitwise exclusive `OR' and regular `OR'
9 <> == !=
Equality operators
10 = %= /= //= -= += *= **=
Assignment operators
11 is is not
Identity operators
12 in not in
Membership operators
13 not or and
Logical operators
List
A list is a collection which is ordered and changeable. In Python lists are written with square brackets.
Example
Create a List:
thislist = ["apple", "banana", "cherry"]
print(thislist)
Access Items
You access the list items by referring to the index number:
Example
Print the second item of the list:
thislist = ["apple", "banana", "cherry"]
print(thislist[1])
Negative Indexing
Negative indexing means beginning from the end, -1 refers to the last item, -2 refers to the second last item etc.
Example
Print the last item of the list:
thislist = ["apple", "banana", "cherry"]
print(thislist[-1])
Range of Indexes
You can specify a range of indexes by specifying where to start and where to end the range.
When specifying a range, the return value will be a new list with the specified items.
Example
Return the third, fourth, and fifth item:
thislist = ["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"]
print(thislist[2:5])
Note: The search will start at index 2 (included) and end at index 5 (not included).
Remember that the first item has index 0.
By leaving out the start value, the range will start at the first item:
Example
This example returns the items from the beginning to "orange":
thislist = ["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"]
print(thislist[:4])
By leaving out the end value, the range will go on to the end of the list:
Example
This example returns the items from "cherry" and to the end:
thislist = ["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"]
print(thislist[2:])
Example
This example returns the items from index -4 (included) to index -1 (excluded)
thislist = ["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"]
print(thislist[-4:-1])
Change Item Value
To change the value of a specific item, refer to the index number:
Example
Change the second item:
thislist = ["apple", "banana", "cherry"]
thislist[1] = "blackcurrant"
print(thislist)
Python Tuples
Tuple
A tuple is a collection which is ordered and unchangeable. In Python tuples are written with round brackets.
Example
Create a Tuple:
thistuple = ("apple", "banana", "cherry")
print(thistuple)
Example
Print the second item in the tuple:
thistuple = ("apple", "banana", "cherry")
print(thistuple[1])
Negative Indexing
Negative indexing means beginning from the end, -1 refers to the last item, -2 refers to the second last item etc.
Example
Print the last item of the tuple:
thistuple = ("apple", "banana", "cherry")
print(thistuple[-1])
Range of Indexes
You can specify a range of indexes by specifying where to start and where to end the range.
When specifying a range, the return value will be a new tuple with the specified items.
Example
Return the third, fourth, and fifth item:
thistuple = ("apple", "banana", "cherry", "orange", "kiwi", "melon", "mango")
print(thistuple[2:5])
Note: The search will start at index 2 (included) and end at index 5 (not included).
Remember that the first item has index 0.
Python Sets
Set
Note: Sets are unordered, so you cannot be sure in which order the items will appear.
Access Items
You cannot access items in a set by referring to an index, since sets are unordered the items has no index.
But you can loop through the set items using a for loop, or ask if a specified value is present in a set, by using the
in keyword.
Example
Loop through the set, and print the values:
thisset = {"apple", "banana", "cherry"}
for x in thisset:
print(x)
apple
banana
cherry
Example
Check if "banana" is present in the set:
thisset = {"apple", "banana", "cherry"}
print("banana" in thisset)
True
Change Items
Once a set is created, you cannot change its items, but you can add new items.
Add Items
To add one item to a set use the add() method.
To add more than one item to a set use the update() method.
Example
Add an item to a set, using the add() method:
thisset = {"apple", "banana", "cherry"}
[Link]("orange")
print(thisset)
Example
Add multiple items to a set, using the update() method:
3
Remove Item
To remove an item in a set, use the remove(), or the discard() method.
Example
Remove "banana" by using the remove() method:
thisset = {"apple", "banana", "cherry"}
[Link]("banana")
print(thisset)
Note: If the item to remove does not exist, remove() will raise an error.
Example
Remove "banana" by using the discard() method:
thisset = {"apple", "banana", "cherry"}
[Link]("banana")
print(thisset)
Note: If the item to remove does not exist, discard() will NOT raise an error.
You can also use the pop(), method to remove an item, but this method will remove the last item. Remember that sets are
unordered, so you will not know what item that gets removed.
The return value of the pop() method is the removed item.
Example
Remove the last item by using the pop() method:
thisset = {"apple", "banana", "cherry"}
x = [Link]()
print(x)
print(thisset)
Note: Sets are unordered, so when using the pop() method, you will not know which item that gets removed.
Example
The clear() method empties the set:
thisset = {"apple", "banana", "cherry"}
[Link]()
print(thisset)
Example
The del keyword will delete the set completely:
thisset = {"apple", "banana", "cherry"}
del thisset
print(thisset)
You can use the union() method that returns a new set containing all items from both sets, or the update()method that
inserts all the items from one set into another:
Example
The union() method returns a new set with all items from both sets:
set1 = {"a", "b" , "c"}
set2 = {1, 2, 3}
set3 = [Link](set2)
print(set3)
Example
The update() method inserts the items in set2 into set1:
set1 = {"a", "b" , "c"}
set2 = {1, 2, 3}
[Link](set2)
print(set1)
Note: Both union() and update() will exclude any duplicate items.
There are other methods that joins two sets and keeps ONLY the duplicates, or NEVER the duplicates, check the full list of set
methods in the bottom of this page.
The set() Constructor
Set Methods
Python has a set of built-in methods that you can use on sets.
Method Description
difference_update() Removes the items in this set that are also included in another, specified set
intersection_update() Removes the items in this set that are not present in other, specified set(s)
symmetric_difference_update() inserts the symmetric differences from this set and another
update() Update the set with the union of this set and others
Python Dictionaries
Dictionary
A dictionary is a collection which is unordered, changeable and indexed.
In Python dictionaries are written with curly brackets, and they have keys and values.
Example
Create and print a dictionary:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
print(thisdict)
{'brand': 'Ford', 'model': 'Mustang', 'year': 1964}
Accessing Items
You can access the items of a dictionary by referring to its key name, inside square brackets:
Example
Mustang
There is also a method called get() that will give you the same result:
Example
Get the value of the "model" key:
x = [Link]("model")
Mustang
Change Values
You can change the value of a specific item by referring to its key name:
Example
Change the "year" to 2018:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
thisdict["year"] = 2018
print(thisdict)
{'brand': 'Ford', 'model': 'Mustang', 'year': 2018}
When looping through a dictionary, the return value are the keys of the dictionary, but there are methods to return
the values as well.
Example
Print all key names in the dictionary, one by one:
for x in thisdict:
print(x)
brand
model
year
Example
Print all values in the dictionary, one by one:
for x in thisdict:
print(thisdict[x])
Ford
Mustang
1964
Example
You can also use the values() method to return values of a dictionary:
for x in [Link]():
print(x)
Ford
Mustang
1964
Example
Loop through both keys and values, by using the items() method:
for x, y in [Link]():
print(x, y)
brand Ford
model Mustang
year 1964
Example
Check if "model" is present in the dictionary:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
if "model" in thisdict:
print("Yes, 'model' is one of the keys in the thisdict dictionary")
Dictionary Length
To determine how many items (key-value pairs) a dictionary has, use the len() function.
Example
Print the number of items in the dictionary:
print(len(thisdict))
Adding Items
Adding an item to the dictionary is done by using a new index key and assigning a value to it:
Example
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
thisdict["color"] = "red"
print(thisdict)
{'model': 'Mustang', 'year': 1964, 'color': 'red', 'brand': 'Ford'} el': 'Mustang', 'y
Removing Items
There are several methods to remove items from a dictionary:
Example
The pop() method removes the item with the specified key name:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
[Link]("model")
print(thisdict)
Example
The popitem() method removes the last inserted item (in versions before 3.7, a random item is removed instead):
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
[Link]()
print(thisdict)
Example
The del keyword removes the item with the specified key name:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
del thisdict["model"]
print(thisdict)
Example
The del keyword can also delete the dictionary completely:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
del thisdict
print(thisdict) #this will cause an error because "thisdict" no longer exists.
Example
The clear() method empties the dictionary:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
[Link]()
print(thisdict)
Copy a Dictionary
You cannot copy a dictionary simply by typing dict2 = dict1, because: dict2 will only be a reference to dict1, and changes made
in dict1 will automatically also be made in dict2.
There are ways to make a copy, one way is to use the built-in Dictionary method copy().
Example
Make a copy of a dictionary with the copy() method:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
mydict = [Link]()
print(mydict)
Example
Make a copy of a dictionary with the dict() function:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
mydict = dict(thisdict)
print(mydict)
Nested Dictionaries
A dictionary can also contain many dictionaries, this is called nested dictionaries.
Example
Create a dictionary that contain three dictionaries:
myfamily = {
"child1" : {
"name" : "Emil",
"year" : 2004
},
"child2" : {
"name" : "Tobias",
"year" : 2007
},
"child3" : {
"name" : "Linus",
"year" : 2011
}
}
Or, if you want to nest three dictionaries that already exists as dictionaries:
Example
Create three dictionaries, then create one dictionary that will contain the other three dictionaries:
child1 = {
"name" : "Emil",
"year" : 2004
}
child2 = {
"name" : "Tobias",
"year" : 2007
}
child3 = {
"name" : "Linus",
"year" : 2011
}
myfamily = {
"child1" : child1,
"child2" : child2,
"child3" : child3
}
Example
thisdict = dict(brand="Ford", model="Mustang", year=1964)
# note that keywords are not string literals
# note the use of equals rather than colon for the assignment
print(thisdict)
Dictionary Methods
Python has a set of built-in methods that you can use on dictionaries.
Method Description
items() Returns a list containing a tuple for each key value pair
setdefault() Returns the value of the specified key. If the key does not exist: insert the key, with the specified value
Python programming language assumes any non-zero and non-null values as TRUE, and if it is either zero or null, then it is
assumed as FALSE value.
Python programming language provides following types of decision making statements. Click the following links to check their
detail.
1 if statements
2 if...else statements
3 nested if statements
#!/usr/bin/python
var = 100
if ( var == 100 ) : print "Value of expression is 100"
print "Good bye!"
Python IF Statement
It is similar to that of other languages. The if statement contains a logical expression using which data is compared and a decision
is made based on the result of the comparison.
Syntax
if expression:
statement(s)
If the boolean expression evaluates to TRUE, then the block of statement(s) inside the if statement is executed. If boolean
expression evaluates to FALSE, then the first set of code after the end of the if statement(s) is executed.
Flow Diagram
Example
#!/usr/bin/python
var1 = 100
if var1:
print "1 - Got a true expression value"
print var1
var2 = 0
if var2:
print "2 - Got a true expression value"
print var2
print "Good bye!"
Python - Loops
In general, statements are executed sequentially: The first statement in a function is executed first, followed by the second, and
so on. There may be a situation when you need to execute a block of code several number of times.
Programming languages provide various control structures that allow for more complicated execution paths.
A loop statement allows us to execute a statement or group of statements multiple times. The following diagram illustrates a
loop statement −
Python programming language provides following types of loops to handle looping requirements.
1 while loop
Repeats a statement or group of statements while a given condition is TRUE. It tests the condition before executing the loop body.
2 for loop
Executes a sequence of statements multiple times and abbreviates the code that manages the loop variable.
3 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. Let us go through the
loop control statements briefly
1 break statement
Terminates the loop statement and transfers execution to the statement immediately following the loop.
2 continue statement
Causes the loop to skip the remainder of its body and immediately retest its condition prior to reiterating.
3 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.
A while loop statement in Python programming language repeatedly executes a target statement as long as a given condition
is true.
Syntax
The syntax of a while loop in Python programming language is −
while expression:
statement(s)
Here, statement(s) may be a single statement or a block of statements. The condition may be any expression, and true is any
non-zero value. The loop iterates while the condition is true.
When the condition becomes false, program control passes to the line immediately following the loop.
In Python, all the statements indented by the same number of character spaces after a programming construct are considered
to be part of a single block of code. Python uses indentation as its method of grouping statements.
Flow Diagram
Here, key point of the while loop is that the loop might not ever run. When the condition is tested and the result is false, the loop
body will be skipped and the first statement after the while loop will be executed.
Example
Live Demo
#!/usr/bin/pytho
n
count = 0
while (count < 9):
The block here, consisting of the print and increment statements, is executed repeatedly until count is no longer less than 9.
With each iteration, the current value of the index count is displayed and then increased by 1.
A loop becomes infinite loop if a condition never becomes FALSE. You must use caution when using while loops because of the
possibility that this condition never resolves to a FALSE value. This results in a loop that never ends. Such a loop is called an
infinite loop.
An infinite loop might be useful in client/server programming where the server needs to run continuously so that client programs
can communicate with it as and when required.
#!/usr/bin/python
var = 1
Live Demo
#!/usr/bin/pytho
n
count = 0
else:
When the above code is executed, it produces the following result −
print count, " is not less than 5"
0 is less than 5
1 is less than 5
2 is less than 5
3 is less than 5
4 is less than 5
5 is not less than 5
#!/usr/bin/python
flag = 1
It has the ability to iterate over the items of any sequence, such as a list or a string. Syntax
If a sequence contains an expression list, it is evaluated first. Then, the first item in the sequence is assigned to the iterating
variable iterating_var. Next, the statements block is executed. Each item in the list is assigned to iterating_var, and the
statement(s) block is executed until the entire sequence is exhausted.
Flow Diagram
Example
Live Demo
#!/ur/bin/python
An alternative way of iterating through each item is by index offset into the sequence itself. Following is a simple
example −
Live Demo
#!/usr/bin/pytho
n
fruits = ['banana', 'apple', 'mango']
for index in range(len(fruits)):
Here, we took the assistance of the len() built-in function, which provides the total number of elements in the tuple as
well as the range() built-in function to give us the actual sequence to iterate over.
The following example illustrates the combination of an else statement with a for statement that searches for prime numbers f rom
10 through 20.
Live Demo
#!/usr/bin/pytho
n
for num in range(10,20): #to iterate between 10 to 20
break
When the above code is executed, it produces the following result −
10 equals 2 * 5
11 is a prime number
12 equals 2 * 6
13 is a prime number
14 equals 2 * 7
15 equals 3 * 5
16 equals 2 * 8
17 is a prime number
18 equals 2 * 9
19 is a prime number
Python programming language allows to use one loop inside another loop. Following section shows few examples to illustrate
the concept.
Syntax
statements(s)
statements(s)
The syntax for a nested while loop statement in Python programming language is as follows −
statement(s)
statement(s)
A final note on loop nesting is that you can put any type of loop inside of any other type of loop. For example a for loop can be
inside a while loop or vice versa.
Example
The following program uses a nested for loop to find the prime numbers from 2 to 100 −
Live Demo
#!/usr/bin/pytho
n
i =2
while(i < 100):
j =2
if not(i%j): break j
=j +1
print
if "Good bye!": print i, " is prime"
(j > i/j)
i =When
i +the1 above code is executed, it produces following result −
2 is prime
3 is prime
5 is prime
7 is prime
11 is prime
13 is prime
17 is prime
19 is prime
Good bye!
23 is prime
29 is prime
31 is prime
37 is prime
41 is prime
43 is prime
47 is prime
53 is prime
59 is prime
61 is prime
67 is prime
71 is prime
73 is prime
79 is prime
83 is prime
89 is prime
97 is prime
Python Functions
Function
def <function_name>([<parameters>]):
<statement(s)>
The components of the definition are explained in the table below:
Component Meaning
def The keyword that informs Python that a function is being defined
: Punctuation that denotes the end of the Python function header (the name and
parameter list)
The final item, <statement(s)>, is called the body of the function. The body is a block of statements that will be executed
when the function is called. The body of a Python function is defined by indentation in accordance with the off-side rule. This is the
same as code blocks associated with a control structure, like an if or while statement.
The syntax for calling a Python function is as follows:
<function_name>([<arguments>])
<arguments> are the values passed into the function. They correspond to the <parameters> in the Python function
definition. You can define a function that doesn’t take any arguments, but the parentheses are still required. Both a function
definition and a function call must always include parentheses, even if they’re empty.
Creating a Function
Example
def my_function():
print("Hello from a function")
Calling a Function
Example
def my_function():
print("Hello from a function")
my_function()
Result
Example
def my_function(fname):
print(fname + " Refsnes")
my_function("Emil")
my_function("Tobias")
my_function("Linus")
Result
Emil Refsnes
Tobias Refsnes
Linus Refsnes
Parameters or Arguments?
The terms parameter and argument can be used for the same thing: information that are passed into a function.
A parameter is the variable listed inside the parentheses in the function definition.
An argument is the value that is sent to the function when it is called.
Number of Arguments
By default, a function must be called with the correct number of arguments. Meaning that if your function expects 2
arguments, you have to call the function with 2 arguments, not more, and not less.
Example
Emil Refsnes
If you try to call the function with 1 or 3 arguments, you will get an error:
Example
If you do not know how many arguments that will be passed into your function, add a * before the parameter name in the
function definition.
This way the function will receive a tuple of arguments, and can access the items accordingly:
Example
def my_function(*kids):
print("The youngest child is " + kids[2])
Keyword Arguments
You can also send arguments with the key = value syntax.
This way the order of the arguments does not matter.
Example
If you do not know how many keyword arguments that will be passed into your function, add two asterisk: **before the
parameter name in the function definition.
This way the function will receive a dictionary of arguments, and can access the items accordingly:
Example
If the number of keyword arguments is unknown, add a double ** before the parameter name:
def my_function(**kid):
print("His last name is " + kid["lname"])
Note: Arbitrary Kword Arguments are often shortened to **kwargs in Python documentations.
Example
I am from Sweden
I am from India
I am from Norway
I am from Brazil
You can send any data types of argument to a function (string, number, list, dictionary etc.), and it will be treated as the
same data type inside the function.
E.g. if you send a List as an argument, it will still be a List when it reaches the function:
Example
def my_function(food):
for x in food:
print(x)
fruits = ["apple", "banana", "cherry"]
my_function(fruits)
Result
apple
banana
cherry
Return Values
Result
15
25
45
The pass Statement
function definitions cannot be empty, but if you for some reason have a function definition with no content, put in
the pass statement to avoid getting an error.
Example
def myfunction():
pass
Result
The first thing a programmer must be aware of is that parameters and arguments are clearly two different things although peop le
use them synonymously.
Parameters are the variables that are defined or used inside parentheses while defining a function, whereas arguments are the
value passed for these parameters while calling a function. Arguments are the values that are passed to the function at run -time so
that the function can do the designated task using these values.
Now that you know about Python function arguments and parameters, let’s have a look at a simple program to highlight more before
discussing the types of arguments that can be passed to a function.
There are three types of Python function arguments using which we can call a function.
1. Default Arguments
2. Keyword Arguments
3. Variable-length Arguments
Sometimes we may want to use parameters in a function that takes default values in case the user doesn’t want to
provide a value for them.
For this, we can use default arguments which assumes a default value if a value is not supplied as an argument while
calling the function. In parameters list, we can give default values to one or more parameters.
An assignment operator ‘=’ is used to give a default value to an argument. Here is an example.
def sum(a=4, b=2): #2 is supplied as default argument
""" This function will print sum of two numbers
if the arguments are not supplied
it will add the default value """
print (a+b)
In function, the values passed through arguments are assigned to parameters in order, by their position.
With Keyword arguments, we can use the name of the parameter irrespective of its position while calling the function to
supply the values. All the keyword arguments must match one of the arguments accepted by the function.
Here is an example.
def print_name(name1, name2):
""" This function prints the name """
print (name1 + " and " + name2 + " are friends")
Variable-length Arguments
Sometimes you may need more arguments to process function then you mentioned in the definition. If we don’t know in
advance about the arguments needed in function, we can use variable-length arguments also called arbitrary arguments.
For this an asterisk (*) is placed before a parameter in function definition which can hold non-keyworded variable-length
arguments and a double asterisk (**) is placed before a parameter in function which can hold keyworded variable-length
arguments.
If we use one asterisk (*) like *var, then all the positional arguments from that point till the end are collected as
a tuple called ‘var’ and if we use two asterisks (**) before a variable like **var, then all the positional arguments from that
point till the end are collected as a dictionary called ‘var’.
Here is an example.
def display(*name, **address):
for items in name:
print (items)
for items in [Link]():
print (items)
Python also accepts function recursion, which means a defined function can call itself.
Recursion is a common mathematical and programming concept. It means that a function calls itself. This has the benefit
of meaning that you can loop through data to reach a result.
The developer should be very careful with recursion as it can be quite easy to slip into writing a function which never
terminates, or one that uses excess amounts of memory or processor power.
However, when written correctly recursion can be a very efficient and mathematically-elegant approach to programming.
In this example, tri_recursion() is a function that we have defined to call itself ("recurse"). We use the kvariable as the
data, which decrements (-1) every time we recurse. The recursion ends when the condition is not greater than 0 (i.e. when
it is 0).
To a new developer it can take some time to work out how exactly this works, best way to find out is by testing and
modifying it.
Example
Recursion Example
def tri_recursion(k):
if(k > 0):
result = k + tri_recursion(k - 1)
print(result)
else:
result = 0
return result
print("\n\nRecursion Example Results")
tri_recursion(6)
Result
Recursion Example Results
1
3
6
10
15
21
Python Lambda
A lambda function can take any number of arguments, but can only have one expression.
Syntax
Example
A lambda function that adds 10 to the number passed in as an argument, and print the result:
x = lambda a : a + 10
print(x(5))
Result
15
Example
A lambda function that multiplies argument a with argument b and print the result:
x = lambda a, b : a * b
print(x(5, 6))
Result
30
Example
A lambda function that sums argument a, b, and c and print the result:
x = lambda a, b, c : a + b + c
print(x(5, 6, 2))
Result
13
The power of lambda is better shown when you use them as an anonymous function inside another function.
Say you have a function definition that takes one argument, and that argument will be multiplied with an unknown number:
def myfunc(n):
return lambda a : a * n
Use that function definition to make a function that always doubles the number you send in:
Example
def myfunc(n):
return lambda a : a * n
mydoubler = myfunc(2)
print(mydoubler(11))
Result
22
Or, use the same function definition to make a function that always triples the number you send in:
Example
def myfunc(n):
return lambda a : a * n
mytripler = myfunc(3)
print(mytripler(11))
Result
33
Or, use the same function definition to make both functions, in the same program:
Example
def myfunc(n):
return lambda a : a * n
mydoubler = myfunc(2)
mytripler = myfunc(3)
print(mydoubler(11))
print(mytripler(11))
Result
22
33
Note: Use lambda functions when an anonymous function is required for a short period of time.
Generator Function
It is fairly simple to create a generator in Python. It is defined like a normal function, but with a yield statement instead of
a return statement.
If a function contains at least one yield statement (it may contain other yield or return statements), it becomes a generator
function. Both yield and return will return some value from a function.
The difference is that while a return statement terminates a function entirely, yield statement pauses the function saving all its
states and later continues from there on successive calls.
Example-1
n += 1
print('This is printed second')
yield n
n += 1
print('This is printed at last')
yield n
import random
def lottery():
# returns 6 numbers between 1 and 40
for i in range(6):
yield [Link](1, 40)
Decorators
Python's decorators allow you to extend and modify the behavior of a callable (functions, methods, and classes) without
permanently modifying the callable itself. Any sufficiently generic functionality you can “tack on” to an existing class or f unction's
behavior makes a great use case for decoration.
In fact, any object which implements the special __call__() method is termed callable. So, in the most basic sense, a decorator is a
def make_pretty(func):
def inner():
print("I got decorated")
func()
return inner
def ordinary():
print("I am ordinary")
>>> ordinary()
I am ordinary
pretty = make_pretty(ordinary)
The function ordinary() got decorated and the returned function was given the name pretty.
We can see that the decorator function added some new functionality to the original function. This is similar to packing a gift. The
decorator acts as a wrapper. The nature of the object that got decorated (actual gift inside) does not alter. But now, it looks pretty
This is a common construct and for this reason, Python has a syntax to simplify this.
We can use the @ symbol along with the name of the decorator function and place it above the definition of the function to be
@make_pretty
def ordinary():
print("I am ordinary")
is equivalent to
def ordinary():
print("I am ordinary")
ordinary = make_pretty(ordinary)
Before getting on to namespaces, first, let’s understand what Python means by a name.
A name in Python is just a way to access a variable like in any other languages.
However, Python is more flexible when it comes to the variable declaration.
num = 5
str = 'Z'
seq = [0, 1, 1, 2, 3, 5]
def function():
print('It is a function.')
foo = function
foo()
You can also assign a name and then reuse it. Check the below example; it is alright for a name to point to different values.
test = -1
print("type <test> :=", type(test))
test = "Pointing to a string now"
print("type <test> :=", type(test))
test = [0, 1, 1, 2, 3, 5, 8]
print("type <test> :=", type(test))
And here is the output follows.
A namespace is a simple system to control the names in a program. It ensures that names are unique and won’t lead
to any conflict.
Also, add to your knowledge that Python implements namespaces in the form of dictionaries. It maintains a name-to-
object mapping where names act as keys and the objects as values. Multiple namespaces may have the same name but
pointing to a different variable. Check out a few examples of namespaces for more clarity.
Local Namespace
This namespace covers the local names inside a function. Python creates this namespace for every function called in
a program. It remains active until the function returns.
Global Namespace
This namespace covers the names from various imported modules used in a project. Python creates this namespace
for every module included in your program. It’ll last until the program ends.
Built-in Namespace
This namespace covers the built-in functions and built-in exception names. Python creates it as the interpreter starts
and keeps it until you exit.
Namespaces make our programs immune from name conflicts. However, it doesn’t give us a free ride to use a variable name
anywhere we want. Python restricts names to be bound by specific rules known as a scope. The scope determines the parts of
the program where you could use that name without any prefix.
Python outlines different scopes for locals, function, modules, and built-ins. Check out from the below list.
A local scope, also known as the innermost scope, holds the list of all local names available in the current function.
A scope for all the enclosing functions, it finds a name from the nearest enclosing scope and goes outwards.
A module level scope, it takes care of all the global names from the current module.
The outermost scope which manages the list of all the built-in names. It is the last place to search for a name that you
cited in the program.
Scope resolution for a given name begins from the inner-most function and then goes higher and higher until the program finds
the related object. If the search ends without any outcome, then the program throws a NameError exception.
Let’s now see some examples which you can run inside any Python IDE or with IDLE.
a_var = 10
print("begin()-> ", dir())
def foo():
b_var = 11
print("inside foo()-> ", dir())
foo()
end()-> ['__builtins__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', 'a_var', 'foo']
In this example, we used the dir() function. It lists all the names that are available in a Python program then.
In the first print() statement, the dir() only displays the list of names inside the current scope. While in the second print(), it finds
only one name, “b_var,” a local function variable.
Calling dir() after defining the foo() pushes it to the list of names available in the global namespace.
In the next example, we’ll see the list of names inside some nested functions. The code in this block continues from the prev ious
block.
def outer_foo():
outer_var = 3
def inner_foo():
inner_var = 5
print(dir(), ' - names in inner_foo')
outer_var = 7
inner_foo()
print(dir(), ' - names in outer_foo')
outer_foo()
The output is as follows.
The above example defines two variables and a function inside the scope of outer_foo(). Inside the inner_foo(), the dir() fun ction
only displays one name i.e. “inner_var”. It is alright as the “inner_var” is the only variable defined in there.
If you reuse a global name inside a local namespace, then Python creates a new local variable with the same name.
a_var = 5
b_var = 7
def outer_foo():
global a_var
a_var = 3
b_var = 9
def inner_foo():
global a_var
a_var = 4
b_var = 8
print('a_var inside inner_foo :', a_var)
print('b_var inside inner_foo :', b_var)
inner_foo()
print('a_var inside outer_foo :', a_var)
print('b_var inside outer_foo :', b_var)
outer_foo()
print('a_var outside all functions :', a_var)
print('b_var outside all functions :', b_var)
Here goes the output of the above code after execution.
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 st atements
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.
Example
This example opens a file, writes content in the, file and comes out gracefully because there is no problem at all −
Live Demo
#!/usr/bin/python
try:
fh = open("testfile", "w")
[Link]("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"
[Link]()
Example
This example tries to open a file where you do not have write permission, so it raises an exception −
Live Demo
#!/usr/bin/python
try:
fh = open("testfile", "r")
[Link]("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:
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.
#!/usr/bin/python
try:
fh = open("testfile", "w")
[Link]("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 −
Error: can't find file or read data
Same example can be written more cleanly as follows −Live Demo
#!/usr/bin/python
try:
fh = open("testfile", "w")
try:
[Link]("This is my test file for exception handling!!")
finally:
print "Going to close the file"
[Link]()
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 −Live Demo
#!/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");
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.
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):
[Link] = arg
So once you defined above class, you can raise the exception as follows −
try:
raise Networkerror("Bad hostname")
except Networkerror,e:
print [Link]
Example-1
a = 12
s = "hello"
try:
print("inside try")
print(a + s) # will raise TypeError
print("Printed using original data types")
except TypeError: # will handle only TypeError
print("inside except")
print(str(a) + s)
print("Printed using type-casted data types")
Example-2
try:
if (3 + 4 - 5) > 0:
a=3
[Link]("hello") # throws AttributeError
else:
print("hello" + 4) # throws TypeError
except (AttributeError, TypeError) as e:
print("Error occurred:", e)
Example-3
try:
if (3 + 4 - 5) > 0:
a=3
[Link]("hello") # throws Attribute Error
else:
print("hello" + 4) # throws TypeError
except (AttributeError, TypeError) as e:
print("Error occurred:", e)
finally:
print("try except block successfully executed"
Example-4
try:
if (3 + 4 - 5) < 0:
a=3
print(a + 5) # simple addition
else:
print("hello" + "4") # string concatenation
except (AttributeError, TypeError) as e:
print("Error occurred:", e)
finally:
print("try except block successfully executed")
UNIT-III
Modules and Packages
What is a Module?
A python module can be defined as a python program file which contains a python code including python functions, class, or
variables. In other words, we can say that our python code file saved with the extension (.py) is treated as the module. We m ay
have a runnable code inside the python module.
Modules in Python provides us the flexibility to organize the code in a logical way.
To use the functionality of one module into another, we must have to import the specific module.
Example
In this example, we will create a module named as [Link] which contains a function func that contains a code to print some message
on the console.
Here, we need to include this module into our main module to call the method displayMsg() defined in the module named file.
Loading the module in our python code
We need to load the module in our python code to use its functionality. Python provides two types of statements as defined below.
The import statement is used to import all the functionality of one module into another. Here, we must notice that we can use the
functionality of any python source file by importing that file as the module into another python source file.
We can import multiple modules with a single import statement, but a module is loaded once regardless of the number of times, it
has been imported into our file.
Hence, if we need to call the function displayMsg() defined in the file [Link], we have to import that file as a module into our module
as shown in the example below.
Example:
import file;
name = input("Enter the name?")
[Link](name)
Output:
Instead of importing the whole module into the namespace, python provides the flexibility to import only the specific attribu tes of a
module. This can be done by using from? import statement. The syntax to use the from-import statement is given below.
Consider the following module named as calculation which contains three functions as summation, multiplication, and divide.
[Link]:
[Link]:
from calculation import summation
#it will import only the summation() from [Link]
a = int(input("Enter the first number"))
b = int(input("Enter the second number"))
print("Sum = ",summation(a,b)) #we do not need to specify the module name while accessing summation()
Output:
The from...import statement is always better to use if we know the attributes to be imported from the module in advance. It d oesn't
let our code to be heavier. We can also import all the attributes from a module by using *.
Renaming a module
Python provides us the flexibility to import some module with a specific name so that we can use this name to use that module in our
python source file.
Example
Output:
Enter a?10
Enter b?20
Sum = 30
The dir() function returns a sorted list of names defined in the passed module. This list contains all the sub-modules, variables and
functions defined in this module.
Example
import json
List = dir(json)
print(List)
Output:
As we have already stated that, a module is loaded once regardless of the number of times it is imported into the python source file.
However, if you want to reload the already imported module to re-execute the top-level code, python provides us the reload()
function. The syntax to use the reload() function is given below.
reload(<module-name>)
for example, to reload the module calculation defined in the previous example, we must use the following line of code.
reload(calculation)
Python packages
The packages in python facilitate the developer with the application development environment by providing a hierarchical directory
structure where a package contains sub-packages, modules, and sub-modules. The packages are used to categorize the
application level code efficiently.
Let's create a package named Employees in your home directory. Consider the following steps.
2. Create a python source file with name [Link] on the path /home/Employees.
[Link]
def getITNames():
List = ["John", "David", "Nick", "Martin"]
return List;
3. Similarly, create one more python file with name [Link] and create a function getBPONames().
4. Now, the directory Employees which we have created in the first step contains two python modules. To make this directory a
package, we need to include one more file here, that is __init__.py which contains the import statements of the modules defin ed in
this directory.
__init__.py
6. To use the modules defined inside the package Employees, we must have to import this in our python source file. Let's create a
simple python source file at our home directory (/home) which uses the modules defined in this package.
[Link]
import Employees
print([Link]())
Output:
We can have sub-packages inside the packages. We can nest the packages up to any level depending upon the application
requirements.
OOPS IN PYTHON
Python has been an object-oriented language since it existed. Because of this, creating and using classes and objects are
downright easy. This chapter helps you become an expert in using Python's object-oriented programming support.
If you do not have any previous experience with object-oriented (OO) programming, you may want to consult an introductory
course on it or at least a tutorial of some sort so that you have a grasp of the basic concepts.
However, here is small introduction of Object-Oriented Programming (OOP) to bring you at speed −
Class − A user-defined prototype for an object that defines a set of attributes that characterize any object of the class.
The attributes are data members (class variables and instance variables) and methods, accessed via dot notation.
Class variable − A variable that is shared by all instances of a class. Class variables are defined within a class but
outside any of the class's methods. Class variables are not used as frequently as instance variables are.
Data member − A class variable or instance variable that holds data associated with a class and its objects.
Function overloading − The assignment of more than one behavior to a particular function. The operation performed
varies by the types of objects or arguments involved.
Instance variable − A variable that is defined inside a method and belongs only to the current instance of a class.
Inheritance − The transfer of the characteristics of a class to other classes that are derived from it.
Instance − An individual object of a certain class. An object obj that belongs to a class Circle, for example, is an instance
of the class Circle.
Object − A unique instance of a data structure that's defined by its class. An object comprises both data members (class
variables and instance variables) and methods.
Operator overloading − The assignment of more than one function to a particular operator.
Creating Classes
The class statement creates a new class definition. The name of the class immediately follows the keyword class followed by a
colon as follows −
class ClassName:
'Optional class documentation string'
class_suite
The class has a documentation string, which can be accessed via ClassName.__doc__.
The class_suite consists of all the component statements defining class members, data attributes and functions.
Example
class Employee:
'Common base class for all employees'
empCount = 0
def displayCount(self):
print "Total Employee %d" % [Link]
def displayEmployee(self):
print "Name : ", [Link], ", Salary: ", [Link]
The variable empCount is a class variable whose value is shared among all instances of a this class. This can be
accessed as [Link] from inside the class or outside the class.
The first method __init__() is a special method, which is called class constructor or initialization method that Python calls
when you create a new instance of this class.
You declare other class methods like normal functions with the exception that the first argument to each method is self.
Python adds the self argument to the list for you; you do not need to include it when you call the methods.
To create instances of a class, you call the class using class name and pass in whatever arguments its __init__ method accepts.
Accessing Attributes
You access the object's attributes using the dot operator with object. Class variable would be accessed using class name as
follows −
[Link]()
[Link]()
print "Total Employee %d" % [Link]
Now, putting all the concepts together −
Live Demo
#!/usr/bin/python
class Employee:
'Common base class for all employees'
empCount = 0
def displayCount(self):
print "Total Employee %d" % [Link]
def displayEmployee(self):
print "Name : ", [Link], ", Salary: ", [Link]
The setattr(obj,name,value) − to set an attribute. If attribute does not exist, then it would be created.
__module__ − Module name in which the class is defined. This attribute is "__main__" in interactive mode.
__bases__ − A possibly empty tuple containing the base classes, in the order of their occurrence in the
base class list.
For the above class let us try to access all these attributes –
Live Demo
#!/usr/bin/python
class Employee:
'Common base class for all employees'
empCount = 0
def displayCount(self):
print "Total Employee %d" % [Link]
def displayEmployee(self):
print "Name : ", [Link], ", Salary: ", [Link]
Python Inheritance
Inheritance allows us to define a class that inherits all the methods and properties from another class.
Parent class is the class being inherited from, also called base class.
Child class is the class that inherits from another class, also called derived class.
Example
Create a class named Person, with firstname and lastname properties, and a printname method:
class Person:
def __init__(self, fname, lname):
[Link] = fname
[Link] = lname
def printname(self):
print([Link], [Link])
#Use the Person class to create an object, and then execute the printname method:
x = Person("John", "Doe")
[Link]()
Try it Yourself »
Example
Create a class named Student, which will inherit the properties and methods from the Person class:
class Student(Person):
pass
Note: Use the pass keyword when you do not want to add any other properties or methods to the class.
Now the Student class has the same properties and methods as the Person class.
Example
Use the Student class to create an object, and then execute the printname method:
x = Student("Mike", "Olsen")
[Link]()
Try it Yourself »
We want to add the __init__() function to the child class (instead of the pass keyword).
Note: The __init__() function is called automatically every time the class is being used to create a new object.
Example
Add the __init__() function to the Student class:
class Student(Person):
def __init__(self, fname, lname):
#add properties etc.
When you add the __init__() function, the child class will no longer inherit the parent's __init__() function.
Note: The child's __init__() function overrides the inheritance of the parent's __init__() function.
To keep the inheritance of the parent's __init__() function, add a call to the parent's __init__() function:
Example
class Student(Person):
def __init__(self, fname, lname):
Person.__init__(self, fname, lname)
Try it Yourself »
Now we have successfully added the __init__() function, and kept the inheritance of the parent class, and we are ready to
add functionality in the __init__() function.
Example
class Student(Person):
def __init__(self, fname, lname):
super().__init__(fname, lname)
Try it Yourself »
By using the super() function, you do not have to use the name of the parent element, it will automatically inherit the
methods and properties from its parent.
Add Properties
Example
Add a property called graduationyear to the Student class:
class Student(Person):
def __init__(self, fname, lname):
super().__init__(fname, lname)
[Link] = 2019
Try it Yourself »
In the example below, the year 2019 should be a variable, and passed into the Student class when creating student objects.
To do so, add another parameter in the __init__() function:
Example
Add a year parameter, and pass the correct year when creating objects:
class Student(Person):
def __init__(self, fname, lname, year):
super().__init__(fname, lname)
[Link] = year
Add Methods
Example
Add a method called welcome to the Student class:
class Student(Person):
def __init__(self, fname, lname, year):
super().__init__(fname, lname)
[Link] = year
def welcome(self):
print("Welcome", [Link], [Link], "to the class of", [Link])
Try it Yourself »
If you add a method in the child class with the same name as a function in the parent class, the inheritance of the parent
method will be overridden.
Class Inheritance
Instead of starting from scratch, you can create a class by deriving it from a preexisting class by listing the parent
class in parentheses after the new class name.
The child class inherits the attributes of its parent class, and you can use those attributes as if they were defined in
the child class. A child class can also override data members and methods from the parent.
Syntax
Derived classes are declared much like their parent class; however, a list of base classes to inherit from is given
after the class name −
ExampleLive Demo
#!/usr/bin/python
def parentMethod(self):
print 'Calling parent method'
def getAttr(self):
print "Parent attribute :", [Link]
def childMethod(self):
print 'Calling child method'
The issubclass(sub, sup) boolean function returns true if the given subclass sub is indeed a subclass of
the superclass sup.
The isinstance(obj, Class) boolean function returns true if obj is an instance of class Class or is an
instance of a subclass of Class
The version of a method that is executed will be determined by the object that is used to invoke it. If an object of a
parent class is used to invoke the method, then the version in the parent class will be executed, but if an object of the
subclass is used to invoke the method, then the version in the child class will be executed. In other words, it is the
type of the object being referred to (not the type of the reference variable) that determines which version of an
overridden method will be executed.
Example:
# Python program to demonstrate
# method overriding
# Defining parent class
class Parent():
# Constructor
def __init__(self):
[Link] = "Inside Parent"
# Constructor
def __init__(self):
[Link] = "Inside Child"
# Driver's code
obj1 = Parent()
obj2 = Child()
[Link]()
[Link]()
Output:
Inside Parent
Inside Child
You can always override your parent class methods. One reason for overriding parent's methods is because you
may want special or different functionality in your subclass.
Example
Live Demo
#!/usr/bin/python
METHOD TYPES
Generally, there are three types of methods in Python:
1. Instance Methods.
2. Class Methods
3. Static Methods
1. Instance Method
This is a very basic and easy method that we use regularly when we create classes in python. If we want to print an instance
variable or instance method we must create an object of that required class.
If we are using self as a function parameter or in front of a variable, that is nothing but the calling instance itself.
As we are working with instance variables we use self keyword.
Note: Instance variables are used with instance methods.
Look at the code below
def avg(self):
return (self.a + self.b) / 2
s1 = Student(10, 20)
print( [Link]() )
Output:
15.0
In the above program, a and b are instance variables and these get initialized when we create an object for the Student class. If we
want to call avg() function which is an instance method, we must create an object for the class.
If we clearly look at the program, the self keyword is used so that we can easily say that those are instance variables and methods.
2. Class Method
classsmethod() function returns a class method as output for the given function.
Here is the syntax for it:
classmethod(function)
The classmethod() method takes only a function as an input parameter and converts that into a class method.
There are two ways to create class methods in python:
1. Using classmethod(function)
2. Using @classmethod annotation
A class method can be called either using the class (such as C.f()) or using an instance (such as C().f()). The instance is ignored
except for its class. If a class method is called from a derived class, the derived class object is passed as the implied first argument.
As we are working with ClassMethod we use the cls keyword. Class variables are used with class methods.
Look at the code below.
@classmethod
def info(cls):
return [Link]
print([Link]())
Output:
Student
In the above example, name is a class variable. If we want to create a class method we must use @classmethod decorator
and cls as a parameter for that function.
3. Static Method
A static method can be called without an object for that class, using the class name directly. If you want to do something extra with a
class we use static methods.
For example, If you want to print factorial of a number then we don't need to use class variables or instance variables to pr int the
factorial of a number. We just simply pass a number to the static method that we have created and it returns the factorial.
@staticmethod
def info():
return "This is a student class"
print([Link]())
Output
This a student class
class Person:
def __init__(self, name, age=0):
[Link] = name
self.__age = age
def display(self):
print([Link])
print(self.__age)
class Person:
def __init__(self, name, age=0):
[Link] = name
self.__age = age
def __displayAge(self):
print([Link])
print(self.__age)
UNIT-IV
Python - Files I/O
This chapter covers all the basic I/O functions available in Python. For more functions, please refer to standard Python
documentation.
The simplest way to produce output is using the print statement where you can pass zero or more expressions separated by
commas. This function converts the expressions you pass into a string and writes the result to standard output as follows −
#!/usr/bin/python
Python provides two built-in functions to read a line of text from standard input, which by default comes from the keyboard. These
functions are −
raw_input
input
#!/usr/bin/python
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 −
Enter your input: Hello Python
Received input is : Hello Python
The input([prompt]) function is equivalent to raw_input, except that it assumes the input is a valid Python expression and returns
the evaluated result to you.
#!/usr/bin/python
This would produce the following result against the entered input −
Enter your input: [x*5 for x in range(2,10,2)]
Recieved input is : [10, 20, 30, 40]
Until now, you have been reading and writing to the standard input and output. Now, we will see how to use actual data files.
Python provides basic functions and methods necessary to manipulate files by default. You can do most of the file manipulatio n
using a file object.
Before you can read or write a file, you have to open it using Python's built-in open() function. This function creates a file object,
which would be utilized to call other support methods associated with it.
Syntax
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).
1
r
Opens a file for reading only. The file pointer is placed at the beginning of the
file. This is the default mode.
2
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.
3
r+
Opens a file for both reading and writing. The file pointer placed at the
beginning of the file.
4
rb+
Opens a file for both reading and writing in binary format. The file pointer
placed at the beginning of the file.
5
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.
6
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.
7
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.
8
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.
9
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.
10
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.
11
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.
12
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.
Once a file is opened and you have one file object, you can get various information related to that file.
1
[Link]
2
[Link]
3
[Link]
4
[Link]
Example
#!/usr/bin/python
# Open a file
fo = open("[Link]", "wb")
print "Name of the file: ", [Link]
print "Closed or not : ", [Link]
print "Opening mode : ", [Link]
print "Softspace flag : ", [Link]
The close() method of a file object flushes any unwritten information and closes the file object, after which no more writing can be
done.
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
[Link]()
Example
#!/usr/bin/python
# Open a file
fo = open("[Link]", "wb")
print "Name of the file: ", [Link]
The file object provides a set of access methods to make our lives easier. We would see how to use read() and write() methods to
read and write files.
The write() method writes any string to an open file. It is important to note that Python strings can have binary data and not just
text.
The write() method does not add a newline character ('\n') to the end of the string −
Syntax
[Link](string)
Here, passed parameter is the content to be written into the opened file.
Example
#!/usr/bin/python
# Open a file
fo = open("[Link]", "wb")
[Link]( "Python is a great language.\nYeah its great!!\n")
The above method would create [Link] 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.
Python is a great language.
Yeah its great!!
The read() method reads a string from an open file. It is important to note that Python strings can have binary data. apart from text
data.
Syntax
[Link]([count])
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 [Link], which we created above.
#!/usr/bin/python
# Open a file
fo = open("[Link]", "r+")
str = [Link](10);
print "Read String is : ", str
# Close opend file
[Link]()
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 offset argument 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
#!/usr/bin/python
# Open a file
fo = open("[Link]", "r+")
str = [Link](10)
print "Read String is : ", str
Python os module provides methods that help you perform file-processing operations, such as renaming and deleting files.
To use this module you need to import it first and then you can call any related functions.
The rename() method takes two arguments, the current filename and the new filename.
Syntax
[Link](current_file_name, new_file_name)
Example
#!/usr/bin/python
import os
You can use the remove() method to delete files by supplying the name of the file to be deleted as the argument.
Syntax
[Link](file_name)
Example
#!/usr/bin/python
import os
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.
You can use the mkdir() method of the os module to create directories in the current directory. You need to supply an argument to
this method which contains the name of the directory to be created.
Syntax
[Link]("newdir")
Example
#!/usr/bin/python
import os
You can use the chdir() method to change the current directory. The chdir() method takes an argument, which is the name of the
directory that you want to make the current directory.
Syntax
[Link]("newdir")
Example
#!/usr/bin/python
import os
Syntax
[Link]()
Example
#!/usr/bin/python
import os
The rmdir() method deletes the directory, which is passed as an argument in the method.
Syntax
[Link]('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
There are three important sources, which provide a wide range of utility methods to handle and manipulate files & directories on
Windows and Unix operating systems. They are as follows −
File Object Methods: The file object provides functions to manipulate files.
OS Object Methods: This provides methods to process files as well as directories.
UNIT-V
Python - MySQL Database Access
The Python standard for database interfaces is the Python DB-API. Most Python database interfaces adhere to this standard.
You can choose the right database for your application. Python Database API supports a wide range of database servers such as
−
GadFly
mSQL
MySQL
PostgreSQL
Microsoft SQL Server 2000
Informix
Interbase
Oracle
Sybase
Here is the list of available Python database interfaces: Python Database Interfaces and APIs. You must download a separate DB
API module for each database you need to access. For example, if you need to access an Oracle database as well as a MySQL
database, you must download both the Oracle and the MySQL database modules.
The DB API provides a minimal standard for working with databases using Python structures and syntax wherever possible. This
API includes the following −
The os Python module provides a big range of useful methods to manipulate files and directories. Most of the useful methods are
listed here −
1 [Link](path, mode)
2 [Link](path)
4 [Link](path, mode)
Change the owner and group id of path to the numeric uid and gid.
6 [Link](path)
7 [Link](fd)
8 [Link](fd_low, fd_high)
Close all file descriptors from fd_low (inclusive) to fd_high (exclusive), ignoring
errors.
9 [Link](fd)
10 os.dup2(fd, fd2)
11 [Link](fd)
Change the current working directory to the directory represented by the file
descriptor fd.
12 [Link](fd, mode)
Change the owner and group id of the file given by fd to the numeric uid and
gid.
14 [Link](fd)
16 [Link](fd, name)
Return system configuration information relevant to an open file. name
specifies the configuration value to retrieve.
17 [Link](fd)
18 [Link](fd)
Return information about the filesystem containing the file associated with file
descriptor fd, like statvfs().
19 [Link](fd)
20 [Link](fd, length)
Truncate the file corresponding to file descriptor fd, so that it is at most length
bytes in size.
21 [Link]()
22 [Link]()
23 [Link](fd)
Return True if the file descriptor fd is open and connected to a tty(-like) device,
else False.
24 [Link](path, flags)
Set the flags of path to the numeric flags, like chflags(), but do not follow
symbolic links.
25 [Link](path, mode)
Change the owner and group id of path to the numeric uid and gid. This
function will not follow symbolic links.
27 [Link](src, dst)
28 [Link](path)
Return a list containing the names of the entries in the directory given by path.
29 [Link](fd, pos, how)
Set the current position of file descriptor fd to position pos, modified by how.
30 [Link](path)
31 [Link](device)
32 [Link](major, minor)
Compose a raw device number from the major and minor device numbers.
33 [Link](path[, mode])
34 [Link](device)
35 [Link](path[, mode])
36 [Link](path[, mode])
Create a FIFO (a named pipe) named path with numeric mode mode. The
default mode is 0666 (octal).
Create a filesystem node (file, device special file or named pipe) named
filename.
Open the file file and set various flags according to flags and possibly its mode
according to mode.
39 [Link]()
40 [Link](path, name)
41 [Link]()
Create a pipe. Return a pair of file descriptors (r, w) usable for reading and
writing, respectively.
42 [Link](command[, mode[, bufsize]])
43 [Link](fd, n)
Read at most n bytes from file descriptor fd. Return a string containing the
bytes read. If the end of the file referred to by fd has been reached, an empty
string is returned.
44 [Link](path)
Return a string representing the path to which the symbolic link points.
45 [Link](path)
46 [Link](path)
47 [Link](src, dst)
48 [Link](old, new)
49 [Link](path)
50 [Link](path)
51 os.stat_float_times([newvalue])
52 [Link](path)
53 [Link](src, dst)
54 [Link](fd)
Return the process group associated with the terminal given by fd (an open file
descriptor as returned by open()).
55 [Link](fd, pg)
Set the process group associated with the terminal given by fd (an open file
descriptor as returned by open()) to pg.
56 [Link]([dir[, prefix]])
Return a unique path name that is reasonable for creating a temporary file.
57 [Link]()
58 [Link]()
Return a unique path name that is reasonable for creating a temporary file.
59 [Link](fd)
Return a string which specifies the terminal device associated with file
descriptor fd. If fd is not associated with a terminal device, an exception is
raised.
60 [Link](path)
61 [Link](path, times)
Set the access and modified times of the file specified by path.
Generate the file names in a directory tree by walking the tree either top-down
or bottom-up.
63 [Link](fd, str)
Write the string str to file descriptor fd. Return the number of bytes actually
written.
Multiple threads within a process share the same data space with the main thread and can therefore share information or
communicate with each other more easily than if they were separate processes.
Threads sometimes called light-weight processes and they do not require much memory overhead; they are cheaper
than processes.
A thread has a beginning, an execution sequence, and a conclusion. It has an instruction pointer that keeps trac k of where within
its context it is currently running.
It can temporarily be put on hold (also known as sleeping) while other threads are running - this is called yielding.
This method call enables a fast and efficient way to create new threads in both Linux and Windows.
The method call returns immediately and the child thread starts and calls function with the passed list of args. When function
returns, the thread terminates.
Here, args is a tuple of arguments; use an empty tuple to call function without passing any arguments. kwargs is an optional
dictionary of keyword arguments.
Example
#!/usr/bin/python
import thread
import time
while 1:
pass
The newer threading module included with Python 2.4 provides much more powerful, high-level support for threads than the thread
module discussed in the previous section.
The threading module exposes all the methods of the thread module and provides some additional methods −
[Link]() − Returns the number of thread objects in the caller's thread control.
[Link]() − Returns a list of all thread objects that are currently active.
In addition to the methods, the threading module has the Thread class that implements threading. The methods provided by
the Thread class are as follows −
start() − The start() method starts a thread by calling the run method.
join([time]) − The join() waits for threads to terminate.
To implement a new thread using the threading module, you have to do the following −
Then, override the run(self [,args]) method to implement what the thread should do when started.
Once you have created the new Thread subclass, you can create an instance of it and then start a new thread by invoking
the start(), which in turn calls run() method.