Python Tutorial
Python Tutorial
Python Tutorial
Python 3.0 was released in 2008. Although this version is supposed to be backward
incompatibles, later on many of its important features have been backported to be
compatible with the version 2.7. This tutorial gives enough understanding on Python 3
version programming language. Please refer to this link for our Python 2 tutorial.
Audience
This tutorial is designed for software programmers who want to upgrade their Python skills
to Python 3. This tutorial can also be used to learn Python programming language from
scratch.
Prerequisites
You should have a basic understanding of Computer Programming terminologies. A basic
understanding of any of the programming languages is a plus.
Try the following example using Try it option available at the top right corner of the below
sample code box −
#!/usr/bin/python3
All the content and graphics published in this e-book are the property of Tutorials Point (I)
Pvt. Ltd. The user of this e-book is prohibited to reuse, retain, copy, distribute or republish
any contents or a part of contents of this e-book in any manner without written consent
of the publisher.
We strive to update the contents of our website and tutorials as timely and as precisely as
possible, however, the contents may contain inaccuracies or errors. Tutorials Point (I) Pvt.
Ltd. provides no guarantee regarding the accuracy, timeliness or completeness of our
website or its contents including this tutorial. If you discover any errors on our website or
in this tutorial, please notify us at [email protected]
i
Python 3
Table of Contents
About the Tutorial ............................................................................................................................................ i
Audience ........................................................................................................................................................... i
Prerequisites ..................................................................................................................................................... i
Execute Python Programs ................................................................................................................................ i
Copyright & Disclaimer ..................................................................................................................................... i
Table of Contents ............................................................................................................................................ ii
ii
Python 3
8. Python 3 – Loops..................................................................................................................................... 51
while Loop Statements .................................................................................................................................. 52
for Loop Statements ...................................................................................................................................... 56
Nested loops .................................................................................................................................................. 59
Loop Control Statements ............................................................................................................................... 60
break statement ............................................................................................................................................ 61
continue Statement ....................................................................................................................................... 63
pass Statement .............................................................................................................................................. 65
Iterator and Generator .................................................................................................................................. 66
iii
Python 3
iv
Python 3
v
Python 3
vi
Python 3
vii
Python 3
viii
Python 3
ix
Python 3
x
Python 3
xi
Python 3
xii
Python 3
1
1. Python 3 – What is New? Python 3
For example, if we want Python 3.x's integer division behavior in Python 2, add the
following import statement.
The print() function inserts a new line at the end, by default. In Python 2, it can be
suppressed by putting ',' at the end. In Python 3, "end=' '" appends space instead of
newline.
In Python 2
>>> x=input('something:')
something:10 #entered data is treated as number
>>> x
10
>>> x=input('something:')
something:'10' #eentered data is treated as string
2
Python 3
>>> x
'10'
>>> x=raw_input("something:")
something:10 #entered data is treated as string even without ''
>>> x
'10'
>>> x=raw_input("something:")
something:'10' #entered data treated as string including ''
>>> x
"'10'"
In Python 3
>>> x=input("something:")
something:10
>>> x
'10'
>>> x=input("something:")
something:'10' #entered data treated as string with or without ''
>>> x
"'10'"
>>> x=raw_input("something:") # will result NameError
Traceback (most recent call last):
File "", line 1, in
x=raw_input("something:")
NameError: name 'raw_input' is not defined
Integer Division
In Python 2, the result of division of two integers is rounded to the nearest integer. As a
result, 3/2 will show 1. In order to obtain a floating-point division, numerator or
denominator must be explicitly used as float. Hence, either 3.0/2 or 3/2.0 or 3.0/2.0 will
result in 1.5
Python 3 evaluates 3 / 2 as 1.5 by default, which is more intuitive for new programmers.
Unicode Representation
Python 2 requires you to mark a string with a u if you want to store it as Unicode.
Python 3 stores strings as Unicode, by default. We have Unicode (utf-8) strings, and 2
byte classes: byte and byte arrays.
3
Python 3
In Python 3, the range() function is removed, and xrange() has been renamed as range().
In addition, the range() object supports slicing in Python 3.2 and later .
raise exceprion
Python 2 accepts both notations, the 'old' and the 'new' syntax; Python 3 raises a
SyntaxError if we do not enclose the exception argument in parenthesis.
Arguments in Exceptions
In Python 3, arguments to exception should be declared with 'as' keyword.
2to3 Utility
Along with Python 3 interpreter, 2to3.py script is usually installed in tools/scripts folder.
It reads Python 2.x source code and applies a series of fixers to transform it into a valid
Python 3.x code.
a=area(10)
print "area",a
To convert into Python 3 version:
$2to3 -w area.py
Converted code :
def area(x,y=3.14): # formal parameters
a=y*x*x
print (a)
return a
a=area(10)
print("area",a)
5
2. Python 3 – Overview Python 3
Python is Interactive: You can actually sit at a Python prompt and interact with
the interpreter directly to write your programs.
History of Python
Python was developed by Guido van Rossum in the late eighties and early nineties at the
National Research Institute for Mathematics and Computer Science in the Netherlands.
Python is derived from many other languages, including ABC, Modula-3, C, C++,
Algol-68, SmallTalk, and Unix shell and other scripting languages.
Python is copyrighted. Like Perl, Python source code is now available under the
GNU General Public License (GPL).
Python 1.0 was released in November 1994. In 2000, Python 2.0 was released.
Python 2.7.11 is the latest edition of Python 2.
Meanwhile, Python 3.0 was released in 2008. Python 3 is not backward compatible
with Python 2. The emphasis in Python 3 had been on the removal of duplicate
programming constructs and modules so that "There should be one -- and
preferably only one -- obvious way to do it." Python 3.5.1 is the latest version of
Python 3.
6
Python 3
Python Features
Python's features include-
Easy-to-learn: Python has few keywords, simple structure, and a clearly defined
syntax. This allows a 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. A few
are listed below-
It provides very high-level dynamic data types and supports dynamic type
checking.
It can be easily integrated with C, C++, COM, ActiveX, CORBA, and Java.
7
3. Python 3 – Environment Setup Python 3
Try the following example using our online compiler available at CodingGround
#!/usr/bin/python3
print ("Hello, Python!")
For most of the examples given in this tutorial, you will find a Try it option on our website
code sections, at the top right corner that will take you to the online compiler. Just use it
and enjoy your learning.
Python 3 is available for Windows, Mac OS and most of the flavors of Linux operating
system. Even though Python 2 is available for many other OSs, Python 3 support either
has not been made available for them or has been dropped.
Getting Python
Windows platform
Binaries of latest version of Python 3 (Python 3.5.1) are available on this download page
Note:In order to install Python 3.5.1, minimum OS requirements are Windows 7 with SP1.
For versions 3.0 to 3.4.x, Windows XP is acceptable.
8
Python 3
Linux platform
Different flavors of Linux use different package managers for installation of new packages.
On Ubuntu Linux, Python 3 is installed using the following command from the terminal.
Mac OS
Download Mac OS installers from this URL:https://www.python.org/downloads/mac-osx/
Double click this package file and follow the wizard instructions to install.
The most up-to-date and current source code, binaries, documentation, news, etc., is
available on the official website of Python:
You can download Python documentation from the following site. The documentation is
available in HTML, PDF and PostScript formats.
Setting up PATH
Programs and other executable files can be in many directories. Hence, the operating
systems provide a search path that lists the directories that it searches for executables.
9
Python 3
The path variable is named as PATH in Unix or Path in Windows (Unix is case-
sensitive; Windows is not).
In Mac OS, the installer handles the path details. To invoke the Python interpreter
from any particular directory, you must add the Python directory to your path.
Variable Description
10
Python 3
Running Python
There are three different ways to start Python-
$python # Unix/Linux
or
python% # Unix/Linux
or
C:>python # Windows/DOS
Option Description
11
Python 3
Windows: PythonWin is the first Windows interface for Python and is an IDE with
a GUI.
Macintosh: The Macintosh version of Python along with the IDLE IDE is available
from the main website, downloadable as either MacBinary or BinHex'd files.
If you are not able to set up the environment properly, then you can take the help of your
system admin. Make sure the Python environment is properly set up and working perfectly
fine.
Note: All the examples given in subsequent chapters are executed with Python 3.4.1
version available on Windows 7 and Ubuntu Linux.
We have already set up Python Programming environment online, so that you can execute
all the available examples online while you are learning theory. Feel free to modify any
example and execute it online.
12
4. Python 3 – Basic Syntax Python 3
The Python language has many similarities to Perl, C, and Java. However, there are some
definite differences between the languages.
$ python
Python 3.3.2 (default, Dec 10 2013, 11:35:01)
[GCC 4.6.3] on Linux
Type "help", "copyright", "credits", or "license" for more information.
>>>
On Windows:
Python 3.4.3 (v3.4.3:9b73f1c3e601, Feb 24 2015, 22:43:06) [MSC v.1600 32 bit (Intel)] on
win32
Type "copyright", "credits" or "license()" for more information.
>>>
Type the following text at the Python prompt and press Enter-
If you are running the older version of Python (Python 2.x), use of parenthesis as
inprint function is optional. This produces the following result-
Hello, Python!
Let us write a simple Python program in a script. Python files have the extension.py. Type
the following source code in a test.py file-
13
Python 3
We assume that you have the Python interpreter set in PATH variable. Now, try to run
this program as follows-
On Linux
$ python test.py
Hello, Python!
On Windows
C:\Python34>Python test.py
Hello, Python!
Let us try another way to execute a Python script in Linux. Here is the modified test.py
file-
#!/usr/bin/python3
print ("Hello, Python!")
We assume that you have Python interpreter available in the /usr/bin directory. Now, try
to run this program as follows-
Hello, Python!
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.
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.
14
Python 3
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 constants or variables or any other identifier names. All the Python keywords
contain lowercase letters only.
as finally or
continue if return
del in while
elif is with
except
The number of spaces in the indentation is variable, but all statements within the block
must be indented the same amount. For example-
15
Python 3
if True:
print ("True")
else:
print ("False")
if True:
print ("Answer")
print ("True")
else:
print "(Answer")
print ("False")
Thus, in Python all the continuous lines indented with the 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 the various blocks even if they are without braces.
#!/usr/bin/python3
import sys
try:
# open file stream
file = open(file_name, "w")
except IOError:
print ("There was an error writing to", file_name)
sys.exit()
print ("Enter '", file_finish,)
print "' When finished"
while file_text != file_finish:
file_text = raw_input("Enter text: ")
if file_text == file_finish:
# close the file
file.close
break
file.write(file_text)
file.write("\n")
file.close()
file_name = input("Enter filename: ")
if len(file_name) == 0:
print ("Next time please enter something")
16
Python 3
sys.exit()
try:
file = open(file_name, "r")
except IOError:
print ("There was an error reading file")
sys.exit()
file_text = file.read()
file.close()
print (file_text)
Multi-Line Statements
Statements in Python typically end with a new line. Python, however, allows the use of
the line continuation character (\) to denote that the line should continue. For example-
total = item_one + \
item_two + \
item_three
The statements contained within the [], {}, or () brackets do not need to use the line
continuation character. For example-
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 is the beginning of a comment. All
characters after the #, up to the end of the physical line, are part of the comment and the
Python interpreter ignores them.
#!/usr/bin/python3
17
Python 3
# First comment
print ("Hello, Python!") # second comment
Hello, Python!
You can type a comment on the same line after a statement or expression-
Python does not have multiple-line commenting feature. You have to comment each line
individually as follows-
# This is a comment.
# This is a comment, too.
# This is a comment, too.
# I said that already.
In an interactive interpreter session, you must enter an empty physical line to terminate
a multiline statement.
#!/usr/bin/python3
input("\n\nPress the enter key to exit.")
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.
18
Python 3
Header lines begin the statement (with the keyword) and terminate with a colon ( : ) and
are followed by one or more lines which make up the suite. For example −
if expression :
suite
elif expression :
suite
else :
suite
$ 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 advance topic. Let us understand it.
The Python sys module provides access to any command-line arguments via
the sys.argv. This serves two purposes-
19
Python 3
Example
Consider the following script test.py-
#!/usr/bin/python3
import sys
print ('Number of arguments:', len(sys.argv), 'arguments.')
print ('Argument List:', str(sys.argv))
NOTE: As mentioned above, the first argument is always the script name and it is also
being counted in number of arguments.
getopt.getopt method
This method parses the command line options and parameter list. Following is a simple
syntax for this method-
options: This is the string of option letters that the script wants to recognize, with
options that require an argument should be followed by a colon (:).
This method returns a value consisting of two elements- the first is a list
of (option, value) pairs, the second is a list of program arguments left after the
option list was stripped.
20
Python 3
Each option-and-value pair returned has the option as its first element, prefixed
with a hyphen for short options (e.g., '-x') or two hyphens for long options (e.g., '-
-long-option').
Exception getopt.GetoptError
This is raised when an unrecognized option is found in the argument list or when an option
requiring an argument is given none.
The argument to the exception is a string indicating the cause of the error. The
attributes msg and opt give the error message and related option.
Example
Suppose we want to pass two file names through command line and we also want to give
an option to check the usage of the script. Usage of the script is as follows-
#!/usr/bin/python3
import sys, getopt
def main(argv):
inputfile = ''
outputfile = ''
try:
opts, args = getopt.getopt(argv,"hi:o:",["ifile=","ofile="])
except getopt.GetoptError:
print ('test.py -i <inputfile> -o <outputfile>')
sys.exit(2)
for opt, arg in opts:
if opt == '-h':
print ('test.py -i <inputfile> -o <outputfile>')
sys.exit()
elif opt in ("-i", "--ifile"):
inputfile = arg
elif opt in ("-o", "--ofile"):
outputfile = arg
print ('Input file is "', inputfile)
print ('Output file is "', outputfile)
if __name__ == "__main__":
main(sys.argv[1:])
21
Python 3
$ test.py -h
usage: test.py -i <inputfile> -o <outputfile>
$ test.py -i BMP -o
usage: test.py -i <inputfile> -o <outputfile>
$ test.py -i inputfile -o outputfile
Input file is " inputfile
Output file is " outputfile
22
5. Python 3 – Variable Types Python 3
Variables are nothing but reserved memory locations to store values. It means that when
you create a variable, you reserve some space in the memory.
Based on the data type of a variable, the interpreter allocates memory and decides what
can be stored in the reserved memory. Therefore, by assigning different data types to the
variables, you can store integers, decimals or characters in these variables.
The operand to the left of the = operator is the name of the variable and the operand to
the right of the = operator is the value stored in the variable. For example-
#!/usr/bin/python3
counter = 100 # An integer assignment
miles = 1000.0 # A floating point
name = "John" # A string
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 the three variables are assigned
to the same memory location. You can also assign multiple objects to multiple variables.
23
Python 3
For example-
a, b, c = 1, 2, "john"
Here, two integer objects with values 1 and 2 are assigned to the variables a and b
respectively, and one string object with the value "john" is assigned to the variable c.
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
24
Python 3
All integers in Python 3 are represented as long integers. Hence, there is no separate
number type as long.
Examples
Here are some examples of numbers-
10 0.0 3.14j
Python Strings
Strings in Python are identified as a contiguous set of characters represented in the
quotation marks. Python allows either pair 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 to the end.
The plus (+) sign is the string concatenation operator and the asterisk (*) is the repetition
operator. For example-
#!/usr/bin/python3
str = 'Hello World!'
print (str) # Prints complete string
print (str[0]) # Prints first character of the string
print (str[2:5]) # Prints characters starting from 3rd to 5th
print (str[2:]) # Prints string starting from 3rd character
print (str * 2) # Prints string two times
print (str + "TEST") # Prints concatenated string
25
Python 3
Hello World!
H
llo
llo World!
Hello World!Hello World!
Hello World!TEST
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 of the differences between them is that all the items belonging
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/python3
list = [ 'abcd', 786 , 2.23, 'john', 70.2 ]
tinylist = [123, 'john']
print (list) # Prints complete list
print (list[0]) # Prints first element of the list
print (list[1:3]) # Prints elements starting from 2nd till 3rd
print (list[2:]) # Prints elements starting from 3rd element
print (tinylist * 2) # Prints list two times
print (list + tinylist) # Prints concatenated lists
26
Python 3
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
parenthesis.
The main difference between lists and tuples is- 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/python3
tuple = ( 'abcd', 786 , 2.23, 'john', 70.2 )
tinytuple = (123, 'john')
print (tuple) # Prints complete tuple
print (tuple[0]) # Prints first element of the tuple
print (tuple[1:3]) # Prints elements starting from 2nd till 3rd
print (tuple[2:]) # Prints elements starting from 3rd element
print (tinytuple * 2) # Prints tuple two times
print (tuple + tinytuple) # Prints concatenated tuple
The following code is invalid with tuple, because we attempted to update a tuple, which is
not allowed. Similar case is possible with lists −
#!/usr/bin/python3
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 key-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.
27
Python 3
Dictionaries are enclosed by curly braces ({ }) and values can be assigned and accessed
using square braces ([]). For example-
#!/usr/bin/python3
dict = {}
dict['one'] = "This is one"
dict[2] = "This is two"
tinydict = {'name': 'john','code':6734, 'dept': 'sales'}
print (dict['one']) # Prints value for 'one' key
print (dict[2]) # Prints value for 2 key
print (tinydict) # Prints complete dictionary
print (tinydict.keys()) # Prints all the keys
print (tinydict.values()) # Prints all the values
This is one
This is two
{'dept': 'sales', 'code': 6734, 'name': 'john'}
['dept', 'code', 'name']
['sales', 6734, 'john']
Dictionaries have no concept of order among the elements. It is incorrect to say that the
elements are "out of order"; they are simply unordered.
There are several built-in functions to perform conversion from one data type to another.
These functions return a new object representing the converted value.
Function Description
28
Python 3
29
6. Python 3 – Basic Operators Python 3
Operators are the constructs, which can manipulate the value of operands. Consider the
expression 4 + 5 = 9. Here, 4 and 5 are called operands and + is called the operator.
Types of Operator
Python language supports the following types of operators-
Arithmetic Operators
Comparison (Relational) Operators
Assignment Operators
Logical Operators
Bitwise Operators
Membership Operators
Identity Operators
30
Python 3
Example
Assume variable a holds 10 and variable b holds 20, then-
#!/usr/bin/python3
a = 21
b = 10
c = 0
c = a + b
print ("Line 1 - Value of c is ", c)
c = a - b
print ("Line 2 - Value of c is ", c )
c = a * b
print ("Line 3 - Value of c is ", c)
c = a / b
print ("Line 4 - Value of c is ", c )
c = a % b
print ("Line 5 - Value of c is ", c)
a = 2
b = 3
c = a**b
print ("Line 6 - Value of c is ", c)
a = 10
b = 5
c = a//b
print ("Line 7 - Value of c is ", c)
When you execute the above program, it produces the following result-
Line 1 - Value of c is 31
Line 2 - Value of c is 11
31
Python 3
Assume variable a holds the value 10 and variable b holds the value 20, then-
(a == b)
If the values of two operands are equal, then the condition
== is not
becomes true.
true.
If the value of left operand is greater than the value of right (a > b) is
>
operand, then condition becomes true. not true.
If the value of left operand is less than the value of right (a < b) is
<
operand, then condition becomes true. true.
(a >= b)
If the value of left operand is greater than or equal to the
>= is not
value of right operand, then condition becomes true.
true.
If the value of left operand is less than or equal to the value (a <= b)
<=
of right operand, then condition becomes true. is true.
Example
Assume variable a holds 10 and variable b holds 20, then-
#!/usr/bin/python3
a = 21
b = 10
if ( a == b ):
print ("Line 1 - a is equal to b")
else:
32
Python 3
if ( a != b ):
print ("Line 2 - a is not equal to b")
else:
print ("Line 2 - a is equal to b")
if ( a < b ):
print ("Line 3 - a is less than b" )
else:
print ("Line 3 - a is not less than b")
if ( a > b ):
print ("Line 4 - a is greater than b")
else:
print ("Line 4 - a is not greater than b")
if ( a <= b ):
print ("Line 5 - a is either less than or equal to b")
else:
print ("Line 5 - a is neither less than nor equal to b")
if ( b >= a ):
print ("Line 6 - b is either greater than or equal to b")
else:
print ("Line 6 - b is neither greater than nor equal to b")
When you execute the above program, it produces the following result-
33
Python 3
//= Floor Division It performs floor division on operators and c //= a is equivalent
assign value to the left operand to c = c // a
Example
Assume variable a holds 10 and variable b holds 20, then-
#!/usr/bin/python3
a = 21
b = 10
c = 0
c = a + b
print ("Line 1 - Value of c is ", c)
c += a
print ("Line 2 - Value of c is ", c )
c *= a
print ("Line 3 - Value of c is ", c )
34
Python 3
c /= a
print ("Line 4 - Value of c is ", c )
c = 2
c %= a
print ("Line 5 - Value of c is ", c)
c **= a
print ("Line 6 - Value of c is ", c)
c //= a
print ("Line 7 - Value of c is ", c)
When you execute the above program, it produces the following result-
Line 1 - Value of c is 31
Line 2 - Value of c is 52
Line 3 - Value of c is 1092
Line 4 - Value of c is 52.0
Line 5 - Value of c is 2
Line 6 - Value of c is 2097152
Line 7 - Value of c is 99864
a = 0011 1100
b = 0000 1101
-----------------
~a = 1100 0011
Pyhton's built-in function bin() can be used to obtain binary representation of an integer
number.
35
Python 3
& Binary AND Operator copies a bit to the result, if it (a & b) (means 0000
exists in both operands 1100)
~ Binary Ones It is unary and has the effect of 'flipping' (~a ) = -61 (means
Complement bits. 1100 0011 in 2's
complement form
due to a signed
binary number.
<< Binary Left Shift The left operand’s value is moved left by a << = 240 (means
the number of bits specified by the right 1111 0000)
operand.
>> Binary Right Shift The left operand’s value is moved right a >> = 15 (means
by the number of bits specified by the 0000 1111)
right operand.
Example
#!/usr/bin/python3
a = 60 # 60 = 0011 1100
b = 13 # 13 = 0000 1101
print ('a=',a,':',bin(a),'b=',b,':',bin(b))
c = 0
c = a | b; # 61 = 0011 1101
print ("result of OR is ", c,':',bin(c))
36
Python 3
c = a ^ b; # 49 = 0011 0001
print ("result of EXOR is ", c,':',bin(c))
When you execute the above program, it produces the following result-
a= 60 : 0b111100 b= 13 : 0b1101
result of AND is 12 : 0b1100
result of OR is 61 : 0b111101
result of EXOR is 49 : 0b110001
result of COMPLEMENT is -61 : -0b111101
result of LEFT SHIFT is 240 : 0b11110000
result of RIGHT SHIFT is 15 : 0b111
and Logical If both the operands are true then condition (a and b) is
AND becomes true. False.
not Logical NOT Used to reverse the logical state of its operand. Not(a and b)
is True.
37
Python 3
Example
#!/usr/bin/python3
a = 10
b = 20
list = [1, 2, 3, 4, 5 ]
if ( a in list ):
print ("Line 1 - a is available in the given list")
else:
print ("Line 1 - a is not available in the given list")
if ( b not in list ):
print ("Line 2 - b is not available in the given list")
else:
print ("Line 2 - b is available in the given list")
c=b/a
if ( c in list ):
print ("Line 3 - a is available in the given list")
else:
print ("Line 3 - a is not available in the given list")
38
Python 3
When you execute the above program, it produces the following result-
Example
#!/usr/bin/python3
a = 20
b = 20
print ('Line 1','a=',a,':',id(a), 'b=',b,':',id(b))
if ( a is b ):
print ("Line 2 - a and b have same identity")
else:
print ("Line 2 - a and b do not have same identity")
if ( id(a) == id(b) ):
print ("Line 3 - a and b have same identity")
else:
print ("Line 3 - a and b do not have same identity")
39
Python 3
b = 30
print ('Line 4','a=',a,':',id(a), 'b=',b,':',id(b))
if ( a is not b ):
print ("Line 5 - a and b do not have same identity")
else:
print ("Line 5 - a and b have same identity")
When you execute the above program, it produces the following result-
Operator Description
40
Python 3
For example, x = 7 + 3 * 2; here, x is assigned 13, not 20 because the operator * has
higher precedence than +, so it first multiplies 3*2 and then is added to 7.
Here, the operators with the highest precedence appear at the top of the table, those with
the lowest appear at the bottom.
Example
#!/usr/bin/python3
a = 20
b = 10
c = 15
d = 5
e = ((a + b) * c) / d # (30 * 15 ) / 5
print ("Value of ((a + b) * c) / d is ", e)
e = (a + b) * (c / d) # (30) * (15/5)
print ("Value of (a + b) * (c / d) is ", e)
e = a + (b * c) / d # 20 + (150/5)
print ("Value of a + (b * c) / d is ", e)
When you execute the above program, it produces the following result-
41
Python 3
42
7. Python 3 – Decision Making Python 3
Decision structures evaluate multiple expressions, which produce TRUE or FALSE as the
outcome. You need to determine which action to take and which statements to execute if
the outcome is TRUE or FALSE otherwise.
Following is the general form of a typical decision making structure found in most of the
programming languages-
Python programming language assumes any non-zero and non-null values as TRUE, and
any zero or null values as FALSE value.
Statement Description
43
Python 3
IF Statement
The IF statement is similar to that of other languages. The if statement contains a logical
expression using which the 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. In Python, statements in a block are uniformly indented after the
: symbol. If boolean expression evaluates to FALSE, then the first set of code after the
end of block is executed.
Flow Diagram
Example
#!/usr/bin/python3
var1 = 100
if var1:
print ("1 - Got a true expression value")
print (var1)
44
Python 3
var2 = 0
if var2:
print ("2 - Got a true expression value")
print (var2)
print ("Good bye!")
IF...ELIF...ELSE Statements
An else statement can be combined with an if statement. An else statement contains a
block of code that executes if the conditional expression in the if statement resolves to 0
or a FALSE value.
The else statement is an optional statement and there could be at the most only
one else statement following if.
Syntax
The syntax of the if...else statement is-
if expression:
statement(s)
else:
statement(s)
45
Python 3
Flow Diagram
Example
#!/usr/bin/python3
amount=int(input("Enter amount: "))
if amount<1000:
discount=amount*0.05
print ("Discount",discount)
else:
discount=amount*0.10
print ("Discount",discount)
In the above example, discount is calculated on the input amount. Rate of discount is 5%,
if the amount is less than 1000, and 10% if it is above 10000. When the above code is
executed, it produces the following result-
Similar to the else, the elif statement is optional. However, unlike else, for which there
can be at the most one statement, there can be an arbitrary number of elif statements
following an if.
Syntax
if expression1:
statement(s)
elif expression2:
statement(s)
elif expression3:
statement(s)
else:
statement(s)
Core Python does not provide switch or case statements as in other languages, but we can
use if..elif...statements to simulate switch case as follows-
Example
#!/usr/bin/python3
amount=int(input("Enter amount: "))
if amount<1000:
discount=amount*0.05
print ("Discount",discount)
elif amount<5000:
discount=amount*0.10
print ("Discount",discount)
else:
discount=amount*0.15
print ("Discount",discount)
print ("Net payable:",amount-discount)
47
Python 3
Nested IF Statements
There may be a situation when you want to check for another condition after a condition
resolves to true. In such a situation, you can use the nested if construct.
Syntax
The syntax of the nested if...elif...else construct may be-
if expression1:
statement(s)
if expression2:
statement(s)
elif expression3:
statement(s)
else
statement(s)
elif expression4:
statement(s)
else:
statement(s)
Example
# !/usr/bin/python3
num=int(input("enter number"))
48
Python 3
if num%2==0:
if num%3==0:
print ("Divisible by 3 and 2")
else:
print ("divisible by 2 not divisible by 3")
else:
if num%3==0:
print ("divisible by 3 not divisible by 2")
else:
print ("not Divisible by 2 not divisible by 3")
enter number8
divisible by 2 not divisible by 3
enter number15
divisible by 3 not divisible by 2
enter number12
Divisible by 3 and 2
enter number5
not Divisible by 2 not divisible by 3
#!/usr/bin/python3
var = 100
if ( var == 100 ) : print ("Value of expression is 100")
print ("Good bye!")
50
8. Python 3 – Loops Python 3
Programming languages provide various control structures that allow more complicated
execution paths.
Python programming language provides the following types of loops to handle looping
requirements.
51
Python 3
nested loops You can use one or more loop inside any another while, or
for loop.
Syntax
The syntax of a while loop in Python programming language is-
while expression:
statement(s)
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
52
Python 3
Here, a 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
#!/usr/bin/python3
count = 0
while (count < 9):
print ('The count is:', count)
count = count + 1
53
Python 3
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.
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/python3
var = 1
while var == 1 : # This constructs an infinite loop
num = int(input("Enter a number :"))
print ("You entered: ", num)
print ("Good bye!")
54
Python 3
The above example goes in an infinite loop and you need to use CTRL+C to exit the
program.
If the else statement is used with a for loop, the else statement is executed when
the loop has exhausted iterating the list.
If the else statement is used with a while loop, the else statement is executed
when the condition becomes false.
The following example illustrates the combination of an else statement with a while
statement that prints a number as long as it is less than 5, otherwise the else statement
gets executed.
#!/usr/bin/python3
count = 0
while count < 5:
print (count, " is less than 5")
count = count + 1
else:
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/python3
flag = 1
while (flag): print ('Given flag is really true!')
print ("Good bye!")
The above example goes into an infinite loop and you need to press CTRL+C keys to exit.
55
Python 3
Syntax
for iterating_var in sequence:
statements(s)
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
56
Python 3
>>> range(5)
range(0, 5)
>>> list(range(5))
[0, 1, 2, 3, 4]
range() generates an iterator to progress integers starting with 0 upto n-1. To obtain a
list object of the sequence, it is typecasted to list(). Now this list can be iterated using the
for statement.
0
1
2
3
4
Example
#!/usr/bin/python3
for letter in 'Python': # traversal of a string sequence
print ('Current Letter :', letter)
print()
fruits = ['banana', 'apple', 'mango']
for fruit in fruits: # traversal of List sequence
print ('Current fruit :', fruit)
Current Letter : P
Current Letter : y
57
Python 3
Current Letter : t
Current Letter : h
Current Letter : o
Current Letter : n
#!/usr/bin/python3
fruits = ['banana', 'apple', 'mango']
for index in range(len(fruits)):
print ('Current fruit :', fruits[index])
print ("Good bye!")
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.
If the else statement is used with a for loop, the else block is executed only if for
loops terminates normally (and not by encountering break statement).
If the else statement is used with a while loop, the else statement is executed
when the condition becomes false.
58
Python 3
The following example illustrates the combination of an else statement with a for
statement that searches for even number in given list.
#!/usr/bin/python3
numbers=[11,33,55,39,55,75,37,21,23,41,13]
for num in numbers:
if num%2==0:
print ('the list contains an even number')
break
else:
print ('the list doesnot contain even number')
Nested loops
Python programming language allows the use of one loop inside another loop. The
following section shows a few examples to illustrate the concept.
Syntax
for iterating_var in sequence:
for iterating_var in sequence:
statements(s)
statements(s)
The syntax for a nested while loop statement in Python programming language is as
follows-
while expression:
while expression:
statement(s)
statement(s)
A final note on loop nesting is that you can put any type of loop inside 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 display multiplication tables from 1-10.
#!/usr/bin/python3
import sys
59
Python 3
for i in range(1,11):
for j in range(1,11):
k=i*j
print (k, end=' ')
print()
The print() function inner loop has end=' ' which appends a space instead of default
newline. Hence, the numbers will appear in one row.
1 2 3 4 5 6 7 8 9 10
2 4 6 8 10 12 14 16 18 20
3 6 9 12 15 18 21 24 27 30
4 8 12 16 20 24 28 32 36 40
5 10 15 20 25 30 35 40 45 50
6 12 18 24 30 36 42 48 54 60
7 14 21 28 35 42 49 56 63 70
8 16 24 32 40 48 56 64 72 80
9 18 27 36 45 54 63 72 81 90
10 20 30 40 50 60 70 80 90 100
60
Python 3
break statement
The break statement is used for premature termination of the current loop. After
abandoning the loop, execution at the next statement is resumed, just like the traditional
break statement in C.
The most common use of break is when some external condition is triggered requiring a
hasty exit from a loop. The break statement can be used in both while and for loops.
If you are using nested loops, the break statement stops the execution of the innermost
loop and starts executing the next line of the code after the block.
Syntax
The syntax for a break statement in Python is as follows-
break
Flow Diagram
61
Python 3
Example
#!/usr/bin/python3
for letter in 'Python': # First Example
if letter == 'h':
break
print ('Current Letter :', letter)
Current Letter : P
Current Letter : y
Current Letter : t
62
Python 3
The following program demonstrates the use of break in a for loop iterating over a list.
User inputs a number, which is searched in the list. If it is found, then the loop terminates
with the 'found' message.
#!/usr/bin/python3
no=int(input('any number: '))
numbers=[11,33,55,39,55,75,37,21,23,41,13]
for num in numbers:
if num==no:
print ('number found in list')
break
else:
print ('number not found in list')
any number: 33
number found in list
any number: 5
number not found in list
continue Statement
The continue statement in Python returns the control to the beginning of the current loop.
When encountered, the loop starts next iteration without executing the remaining
statements in the current iteration.
The continue statement can be used in both while and for loops.
Syntax
continue
63
Python 3
Flow Diagram
Example
#!/usr/bin/python3
Current Letter : P
64
Python 3
Current Letter : y
Current Letter : t
Current Letter : o
Current Letter : n
Current variable value : 9
Current variable value : 8
Current variable value : 7
Current variable value : 6
Current variable value : 4
Current variable value : 3
Current variable value : 2
Current variable value : 1
Current variable value : 0
Good bye!
pass Statement
It is used when a statement is required syntactically but you do not want any command
or code to execute.
The pass statement is a null operation; nothing happens when it executes. The
pass statement is also useful in places where your code will eventually go, but has not
been written yet i.e. in stubs).
Syntax
pass
Example
#!/usr/bin/python3
Current Letter : P
Current Letter : y
Current Letter : t
This is pass block
Current Letter : h
Current Letter : o
Current Letter : n
Good bye!
list=[1,2,3,4]
it = iter(list) # this builds an iterator object
print (next(it)) #prints next available element in iterator
Iterator object can be traversed using regular for statement
!usr/bin/python3
for x in it:
print (x, end=" ")
or using next() function
while True:
try:
print (next(it))
except StopIteration:
sys.exit() #you have to import sys module for this
A generator is a function that produces or yields a sequence of values using yield method.
When a generator function is called, it returns a generator object without even beginning
execution of the function. When the next() method is called for the first time, the function
starts executing, until it reaches the yield statement, which returns the yielded value. The
yield keeps track i.e. remembers the last execution and the second next() call continues
from previous value.
The following example defines a generator, which generates an iterator for all the Fibonacci
numbers.
!usr/bin/python3
66
Python 3
import sys
def fibonacci(n): #generator function
a, b, counter = 0, 1, 0
while True:
if (counter > n):
return
yield a
a, b = b, a + b
counter += 1
f = fibonacci(5) #f is iterator object
while True:
try:
print (next(f), end=" ")
except StopIteration:
sys.exit()
67
9. Python 3 – Numbers Python 3
Number data types store numeric values. They are immutable data types. This means,
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. They are
positive or negative whole numbers with no decimal point. Integers in Python 3 are
of unlimited size. Python 2 has two integer types - int and long. There is no 'long
integer' in Python 3 anymore.
float (floating point real values) : Also called floats, they represent real
numbers and are written with a decimal point dividing the integer and the 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.
68
Python 3
31
Examples
Here are some examples of numbers.
10 0.0 3.14j
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.
69
Python 3
Mathematical Functions
Python includes the following functions that perform mathematical calculations.
max(x1, x2,...) The largest of its arguments: the value closest to positive infinity.
min(x1, x2,...) The smallest of its arguments: the value closest to negative
infinity.
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.
70
Python 3
Description
The abs() method returns the absolute value of x i.e. the positive distance between x and
zero.
Syntax
Following is the syntax for abs() method-
abs( x )
Parameters
x - This is a numeric expression.
Return Value
This method returns the absolute value of x.
Example
The following example shows the usage of the abs() method.
#!/usr/bin/python3
print ("abs(-45) : ", abs(-45))
print ("abs(100.12) : ", abs(100.12))
abs(-45) : 45
abs(100.12) : 100.12
Description
The ceil() method returns the ceiling value of x i.e. the smallest integer not less than x.
Syntax
Following is the syntax for the ceil() method-
import math
math.ceil( x )
Note: This function is not accessible directly, so we need to import math module and then
we need to call this function using the math static object.
71
Python 3
Parameters
x - This is a numeric expression.
Return Value
This method returns the smallest integer not less than x.
Example
The following example shows the usage of the ceil() method.
#!/usr/bin/python3
import math # This will import math module
print ("math.ceil(-45.17) : ", math.ceil(-45.17))
print ("math.ceil(100.12) : ", math.ceil(100.12))
print ("math.ceil(100.72) : ", math.ceil(100.72))
print ("math.ceil(math.pi) : ", math.ceil(math.pi))
math.ceil(-45.17) : -45
math.ceil(100.12) : 101
math.ceil(100.72) : 101
math.ceil(math.pi) : 4
Description
The exp() method returns exponential of x: ex.
Syntax
Following is the syntax for the exp() method-
import math
math.exp( x )
Note: This function is not accessible directly. Therefore, we need to import the math
module and then we need to call this function using the math static object.
Parameters
X - This is a numeric expression.
72
Python 3
Return Value
This method returns exponential of x: ex.
Example
The following example shows the usage of exp() method.
#!/usr/bin/python3
import math # This will import math module
print ("math.exp(-45.17) : ", math.exp(-45.17))
print ("math.exp(100.12) : ", math.exp(100.12))
print ("math.exp(100.72) : ", math.exp(100.72))
print ("math.exp(math.pi) : ", math.exp(math.pi))
math.exp(-45.17) : 2.4150062132629406e-20
math.exp(100.12) : 3.0308436140742566e+43
math.exp(100.72) : 5.522557130248187e+43
math.exp(math.pi) : 23.140692632779267
Description
The fabs() method returns the absolute value of x. Although similar to the abs() function,
there are differences between the two functions. They are-
fabs() function works only on float and integer whereas abs() works with complex
number also.
Syntax
Following is the syntax for the fabs() method-
import math
math.fabs( x )
Note: This function is not accessible directly, so we need to import the math module and
then we need to call this function using the math static object.
Parameters
x - This is a numeric value.
73
Python 3
Return Value
This method returns the absolute value of x.
Example
The following example shows the usage of the fabs() method.
#!/usr/bin/python3
import math # This will import math module
print ("math.fabs(-45.17) : ", math.fabs(-45.17))
print ("math.fabs(100.12) : ", math.fabs(100.12))
print ("math.fabs(100.72) : ", math.fabs(100.72))
print ("math.fabs(math.pi) : ", math.fabs(math.pi))
math.fabs(-45.17) : 45.17
math.fabs(100) : 100.0
math.fabs(100.72) : 100.72
math.fabs(math.pi) : 3.141592653589793
Description
The floor() method returns the floor of x i.e. the largest integer not greater than x.
Syntax
Following is the syntax for the floor() method-
import math
math.floor( x )
Note: This function is not accessible directly, so we need to import the math module and
then we need to call this function using the math static object.
Parameters
x - This is a numeric expression.
Return Value
This method returns the largest integer not greater than x.
Example
74
Python 3
#!/usr/bin/python3
import math # This will import math module
print ("math.floor(-45.17) : ", math.floor(-45.17))
print ("math.floor(100.12) : ", math.floor(100.12))
print ("math.floor(100.72) : ", math.floor(100.72))
print ("math.floor(math.pi) : ", math.floor(math.pi))
math.floor(-45.17) : -46
math.floor(100.12) : 100
math.floor(100.72) : 100
math.floor(math.pi) : 3
Description
The log() method returns the natural logarithm of x, for x > 0.
Syntax
Following is the syntax for the log() method-
import math
math.log( x )
Note: This function is not accessible directly, so we need to import the math module and
then we need to call this function using the math static object.
Parameters
x - This is a numeric expression.
Return Value
This method returns natural logarithm of x, for x > 0.
Example
The following example shows the usage of the log() method.
75
Python 3
#!/usr/bin/python3
import math # This will import math module
print ("math.log(100.12) : ", math.log(100.12))
print ("math.log(100.72) : ", math.log(100.72))
print ("math.log(math.pi) : ", math.log(math.pi))
math.log(100.12) : 4.6063694665635735
math.log(100.72) : 4.612344389736092
math.log(math.pi) : 1.1447298858494002
Description
The log10() method returns base-10 logarithm of x for x > 0.
Syntax
Following is the syntax for log10() method-
import math
math.log10( x )
Note: This function is not accessible directly, so we need to import the math module and
then we need to call this function using the math static object.
Parameters
x - This is a numeric expression.
Return Value
This method returns the base-10 logarithm of x for x > 0.
Example
The following example shows the usage of the log10() method.
#!/usr/bin/python3
import math # This will import math module
print ("math.log10(100.12) : ", math.log10(100.12))
print ("math.log10(100.72) : ", math.log10(100.72))
print ("math.log10(119) : ", math.log10(119))
print ("math.log10(math.pi) : ", math.log10(math.pi))
76
Python 3
math.log10(100.12) : 2.0005208409361854
math.log10(100.72) : 2.003115717099806
math.log10(119) : 2.0755469613925306
math.log10(math.pi) : 0.49714987269413385
Description
The max() method returns the largest of its arguments i.e. the value closest to positive
infinity.
Syntax
Following is the syntax for max() method-
max( x, y, z, .... )
Parameters
x - This is a numeric expression.
y - This is also a numeric expression.
z - This is also a numeric expression.
Return Value
This method returns the largest of its arguments.
Example
The following example shows the usage of the max() method.
#!/usr/bin/python3
print ("max(80, 100, 1000) : ", max(80, 100, 1000))
print ("max(-20, 100, 400) : ", max(-20, 100, 400))
print ("max(-80, -20, -10) : ", max(-80, -20, -10))
print ("max(0, 100, -400) : ", max(0, 100, -400))
77
Python 3
Description
The method min() returns the smallest of its arguments i.e. the value closest to negative
infinity.
Syntax
Following is the syntax for the min() method-
min( x, y, z, .... )
Parameters
x - This is a numeric expression.
y - This is also a numeric expression.
z - This is also a numeric expression.
Return Value
This method returns the smallest of its arguments.
Example
The following example shows the usage of the min() method.
#!/usr/bin/python3
print ("min(80, 100, 1000) : ", min(80, 100, 1000))
print ("min(-20, 100, 400) : ", min(-20, 100, 400))
print ("min(-80, -20, -10) : ", min(-80, -20, -10))
print ("min(0, 100, -400) : ", min(0, 100, -400))
78
Python 3
Description
The modf() method returns 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.
Syntax
Following is the syntax for the modf() method-
import math
math.modf( x )
Note: This function is not accessible directly, so we need to import the math module and
then we need to call this function using the math static object.
Parameters
x - This is a numeric expression.
Return Value
This method returns the fractional and integer parts of x in a two-item tuple. Both the
parts have the same sign as x. The integer part is returned as a float.
Example
The following example shows the usage of the modf() method.
#!/usr/bin/python3
import math # This will import math module
print ("math.modf(100.12) : ", math.modf(100.12))
print ("math.modf(100.72) : ", math.modf(100.72))
print ("math.modf(119) : ", math.modf(119))
print ("math.modf(math.pi) : ", math.modf(math.pi))
79
Python 3
Return Value
This method returns the value of xy.
Example
The following example shows the usage of the pow() method.
#!/usr/bin/python3
import math # This will import math module
print ("math.pow(100, 2) : ", math.pow(100, 2))
print ("math.pow(100, -2) : ", math.pow(100, -2))
print ("math.pow(2, 4) : ", math.pow(2, 4))
print ("math.pow(3, 0) : ", math.pow(3, 0))
math.pow(100, 2) : 10000.0
math.pow(100, -2) : 0.0001
math.pow(2, 4) : 16.0
math.pow(3, 0) : 1.0
Description
round() is a built-in function in Python. It returns x rounded to n digits from the decimal
point.
Syntax
Following is the syntax for the round() method-
round( x [, n] )
Parameters
x - This is a numeric expression.
Return Value
This method returns x rounded to n digits from the decimal point.
80
Python 3
Example
The following example shows the usage of round() method.
#!/usr/bin/python3
print ("round(70.23456) : ", round(70.23456))
print ("round(56.659,1) : ", round(56.659,1))
print ("round(80.264, 2) : ", round(80.264, 2))
print ("round(100.000056, 3) : ", round(100.000056, 3))
print ("round(-100.000056, 3) : ", round(-100.000056, 3))
round(70.23456) : 70
round(56.659,1) : 56.7
round(80.264, 2) : 80.26
round(100.000056, 3) : 100.0
round(-100.000056, 3) : -100.0
Description
The sqrt() method returns the square root of x for x > 0.
Syntax
Following is the syntax for sqrt() method-
import math
math.sqrt( x )
Note: This function is not accessible directly, so we need to import the math module and
then we need to call this function using the math static object.
Parameters
x - This is a numeric expression.
Return Value
This method returns square root of x for x > 0.
Example
The following example shows the usage of sqrt() method.
81
Python 3
#!/usr/bin/python3
import math # This will import math module
print ("math.sqrt(100) : ", math.sqrt(100))
print ("math.sqrt(7) : ", math.sqrt(7))
print ("math.sqrt(math.pi) : ", math.sqrt(math.pi))
math.sqrt(100) : 10.0
math.sqrt(7) : 2.6457513110645907
math.sqrt(math.pi) : 1.7724538509055159
Function Description
Description
82
Python 3
The choice() method returns a random item from a list, tuple, or string.
Syntax
Following is the syntax for choice() method-
choice( seq )
Note: This function is not accessible directly, so we need to import the random module
and then we need to call this function using the random static object.
Parameters
seq - This could be a list, tuple, or string...
Return Value
This method returns a random item.
Example
The following example shows the usage of the choice() method.
#!/usr/bin/python3
import random
print ("returns a random number from range(100) : ",random.choice(range(100)))
print ("returns random element from list [1, 2, 3, 5, 9]) : ", random.choice([1,
2, 3, 5, 9]))
print ("returns random character from string 'Hello World' : ",
random.choice('Hello World'))
When we run the above program, it produces a result similar to the following-
Description
The randrange() method returns a randomly selected element from range(start, stop,
step).
Syntax
Following is the syntax for the randrange() method-
83
Python 3
Note: This function is not accessible directly, so we need to import the random module
and then we need to call this function using the random static object.
Parameters
start - Start point of the range. This would be included in the range. Default is 0.
stop - Stop point of the range. This would be excluded from the range.
step - Value with which number is incremented. Default is 1.
Return Value
This method returns a random item from the given range.
Example
The following example shows the usage of the randrange() method.
#!/usr/bin/python3
import random
# randomly select an odd number between 1-100
print ("randrange(1,100, 2) : ", random.randrange(1, 100, 2))
# randomly select a number between 0-99
print ("randrange(100) : ", random.randrange(100))
randrange(1,100, 2) : 83
randrange(100) : 93
Description
The random() method returns a random floating point number in the range [0.0, 1.0].
Syntax
Following is the syntax for the random() method-
random ( )
Note: This function is not accessible directly, so we need to import the random module
and then we need to call this function using the random static object.
Parameters
84
Python 3
NA
Return Value
This method returns a random float r, such that 0.0 <= r <= 1.0
Example
The following example shows the usage of the random() method.
#!/usr/bin/python3
import random
# First random number
print ("random() : ", random.random())
# Second random number
print ("random() : ", random.random())
random() : 0.281954791393
random() : 0.309090465205
Description
The seed() method initializes the basic random number generator. Call this function
before calling any other random module function.
Syntax
Following is the syntax for the seed() method-
Parameters
x - This is the seed for the next random number. If omitted, then it takes system
time to generate the next random number. If x is an int, it is used directly.
Y - This is version number (default is 2). str, byte or byte array object gets
converted in int. Version 1 used hash() of x.
Return Value
This method does not return any value.
85
Python 3
Example
The following example shows the usage of the seed() method.
#!/usr/bin/python3
import random
random.seed()
print ("random number with default seed", random.random())
random.seed(10)
print ("random number with int seed", random.random())
random.seed("hello",2)
print ("random number with string seed", random.random())
Description
The shuffle() method randomizes the items of a list in place.
Syntax
Following is the syntax for the shuffle() method-
shuffle (lst,[random])
Note: This function is not accessible directly, so we need to import the shuffle module and
then we need to call this function using the random static object.
Parameters
lst - This could be a list or tuple.
Return Value
This method returns reshuffled list.
Example
86
Python 3
#!/usr/bin/python3
import random
list = [20, 16, 10, 5];
random.shuffle(list)
print ("Reshuffled list : ", list)
random.shuffle(list)
print ("Reshuffled list : ", list)
Description
The uniform() method returns a random float r, such that x is less than or equal to r and
r is less than y.
Syntax
Following is the syntax for the uniform() method-
uniform(x, y)
Note: This function is not accessible directly, so we need to import the uniform module
and then we need to call this function using the random static object.
Parameters
x - Sets the lower limit of the random float.
y - Sets the upper limit of the random float.
Return Value
This method returns a floating point number r such that x <=r < y.
Example
The following example shows the usage of the uniform() method.
#!/usr/bin/python3
import random
87
Python 3
Let us run the above program. This will produce the following result-
Trigonometric Functions
Python includes the following functions that perform trigonometric calculations.
Function Description
Description
The acos() method returns the arc cosine of x in radians.
Syntax
88
Python 3
acos(x)
Note: This function is not accessible directly, so we need to import the math module and
then we need to call this function using the math static object.
Parameters
x - This must be a numeric value in the range -1 to 1. If x is greater than 1 then it will
generate 'math domain error'.
Return Value
This method returns arc cosine of x, in radians.
Example
The following example shows the usage of the acos() method.
#!/usr/bin/python3
import math
print ("acos(0.64) : ", math.acos(0.64))
print ("acos(0) : ", math.acos(0))
print ("acos(-1) : ", math.acos(-1))
print ("acos(1) : ", math.acos(1))
acos(0.64) : 0.876298061168
acos(0) : 1.57079632679
acos(-1) : 3.14159265359
acos(1) : 0.0
Description
The asin() method returns the arc sine of x (in radians).
Syntax
Following is the syntax for the asin() method-
asin(x)
Note: This function is not accessible directly, so we need to import the math module and
then we need to call this function usingthe math static object.
89
Python 3
Parameters
x - This must be a numeric value in the range -1 to 1. If x is greater than 1 then it will
generate 'math domain error'.
Return Value
This method returns arc sine of x, in radians.
Example
The following example shows the usage of the asin() method.
#!/usr/bin/python3
import math
print ("asin(0.64) : ", math.asin(0.64))
print ("asin(0) : ", math.asin(0))
print ("asin(-1) : ", math.asin(-1))
print ("asin(1) : ", math.asin(1))
asin(0.64) : 0.694498265627
asin(0) : 0.0
asin(-1) : -1.57079632679
asin(1) : 1.5707963267
Description
The atan() method returns the arc tangent of x, in radians.
Syntax
Following is the syntax for atan() method-
atan(x)
Note: This function is not accessible directly, so we need to import the math module and
then we need to call this function using the math static object.
Parameters
x - This must be a numeric value.
Return Value
90
Python 3
Example
The following example shows the usage of the atan() method.
#!/usr/bin/python3
import math
print ("atan(0.64) : ", math.atan(0.64))
print ("atan(0) : ", math.atan(0))
print ("atan(10) : ", math.atan(10))
print ("atan(-1) : ", math.atan(-1))
print ("atan(1) : ", math.atan(1))
atan(0.64) : 0.569313191101
atan(0) : 0.0
atan(10) : 1.4711276743
atan(-1) : -0.785398163397
atan(1) : 0.785398163397
Description
The atan2() method returns atan(y / x), in radians.
Syntax
Following is the syntax for atan2() method-
atan2(y, x)
Note: This function is not accessible directly, so we need to import the math module and
then we need to call this function using the math static object.
Parameters
y - This must be a numeric value.
x - This must be a numeric value.
Return Value
91
Python 3
Example
The following example shows the usage of atan2() method.
#!/usr/bin/python3
import math
print ("atan2(-0.50,-0.50) : ", math.atan2(-0.50,-0.50))
print ("atan2(0.50,0.50) : ", math.atan2(0.50,0.50))
print ("atan2(5,5) : ", math.atan2(5,5))
print ("atan2(-10,10) : ", math.atan2(-10,10))
print ("atan2(10,20) : ", math.atan2(10,20))
atan2(-0.50,-0.50) : -2.35619449019
atan2(0.50,0.50) : 0.785398163397
atan2(5,5) : 0.785398163397
atan2(-10,10) : -0.785398163397
atan2(10,20) : 0.463647609001
Description
The cos() method returns the cosine of x radians.
Syntax
Following is the syntax for cos() method-
cos(x)
Note: This function is not accessible directly, so we need to import the math module and
then we need to call this function using the math static object.
Parameters
x - This must be a numeric value.
Return Value
This method returns a numeric value between -1 and 1, which represents the cosine of
the angle.
Example
92
Python 3
#!/usr/bin/python3
import math
print ("cos(3) : ", math.cos(3))
print ("cos(-3) : ", math.cos(-3))
print ("cos(0) : ", math.cos(0))
print ("cos(math.pi) : ", math.cos(math.pi))
print ("cos(2*math.pi) : ", math.cos(2*math.pi))
cos(3) : -0.9899924966
cos(-3) : -0.9899924966
cos(0) : 1.0
cos(math.pi) : -1.0
cos(2*math.pi) : 1.0
Description
The method hypot() return the Euclidean norm, sqrt(x*x + y*y). This is length of vector
from origin to point (x,y)
Syntax
Following is the syntax for hypot() method-
hypot(x, y)
Note: This function is not accessible directly, so we need to import math module and then
we need to call this function using math static object.
Parameters
x - This must be a numeric value.
y - This must be a numeric value.
Return Value
This method returns Euclidean norm, sqrt(x*x + y*y).
Example
93
Python 3
#!/usr/bin/python3
import math
print ("hypot(3, 2) : ", math.hypot(3, 2))
print ("hypot(-3, 3) : ", math.hypot(-3, 3))
print ("hypot(0, 2) : ", math.hypot(0, 2))
hypot(3, 2) : 3.60555127546
hypot(-3, 3) : 4.24264068712
hypot(0, 2) : 2.0
Description
The sin() method returns the sine of x, in radians.
Syntax
Following is the syntax for sin() method-
sin(x)
Note: This function is not accessible directly, so we need to import the math module and
then we need to call this function using the math static object.
Parameters
x - This must be a numeric value.
Return Value
This method returns a numeric value between -1 and 1, which represents the sine of the
parameter x.
Example
The following example shows the usage of sin() method.
#!/usr/bin/python3
import math
print ("sin(3) : ", math.sin(3))
print ("sin(-3) : ", math.sin(-3))
print ("sin(0) : ", math.sin(0))
94
Python 3
sin(3) : 0.14112000806
sin(-3) : -0.14112000806
sin(0) : 0.0
sin(math.pi) : 1.22460635382e-16
sin(math.pi/2) : 1
Description
The tan() method returns the tangent of x radians.
Syntax
Following is the syntax for tan() method.
tan(x)
Note: This function is not accessible directly, so we need to import math module and then
we need to call this function using math static object.
Parameters
x - This must be a numeric value.
Return Value
This method returns a numeric value between -1 and 1, which represents the tangent of
the parameter x.
Example
The following example shows the usage of tan() method.
#!/usr/bin/python3
import math
print ("(tan(3) : ", math.tan(3))
print ("tan(-3) : ", math.tan(-3))
print ("tan(0) : ", math.tan(0))
print ("tan(math.pi) : ", math.tan(math.pi))
print ("tan(math.pi/2) : ", math.tan(math.pi/2))
95
Python 3
Description
The degrees() method converts angle x from radians to degrees..
Syntax
Following is the syntax for degrees() method-
degrees(x)
Note: This function is not accessible directly, so we need to import the math module and
then we need to call this function using the math static object.
Parameters
x - This must be a numeric value.
Return Value
This method returns the degree value of an angle.
Example
The following example shows the usage of degrees() method.
#!/usr/bin/python3
import math
print ("degrees(3) : ", math.degrees(3))
print ("degrees(-3) : ", math.degrees(-3))
print ("degrees(0) : ", math.degrees(0))
print ("degrees(math.pi) : ", math.degrees(math.pi))
print ("degrees(math.pi/2) : ", math.degrees(math.pi/2))
96
Python 3
degrees(3) : 171.88733853924697
degrees(-3) : -171.88733853924697
degrees(0) : 0.0
degrees(math.pi) : 180.0
degrees(math.pi/2) : 90.0
degrees(math.pi/4) : 45.0
Description
The radians() method converts angle x from degrees to radians.
Syntax
Following is the syntax for radians() method-
radians(x)
Note: This function is not accessible directly, so we need to import the math module and
then we need to call this function using the math static object.
Parameters
x - This must be a numeric value.
Return Value
This method returns radian value of an angle.
Example
The following example shows the usage of radians() method.
#!/usr/bin/python3
import math
print ("radians(3) : ", math.radians(3))
print ("radians(-3) : ", math.radians(-3))
print ("radians(0) : ", math.radians(0))
print ("radians(math.pi) : ", math.radians(math.pi))
print ("radians(math.pi/2) : ", math.radians(math.pi/2))
97
Python 3
radians(3) : 0.0523598775598
radians(-3) : -0.0523598775598
radians(0) : 0.0
radians(math.pi) : 0.0548311355616
radians(math.pi/2) : 0.0274155677808
radians(math.pi/4) : 0.0137077838904
Mathematical Constants
The module also defines two mathematical constants-
Constants Description
98
10. Python 3 – Strings Python 3
Strings are amongst the most popular types in Python. We can create them simply by
enclosing characters in quotes. Python treats single quotes the same as double quotes.
Creating strings is as simple as assigning a value to a variable. For example-
To access substrings, use the square brackets for slicing along with the index or indices to
obtain your substring. For example-
#!/usr/bin/python3
var1 = 'Hello World!'
var2 = "Python Programming"
print ("var1[0]: ", var1[0])
print ("var2[1:5]: ", var2[1:5])
var1[0]: H
var2[1:5]: ytho
Updating Strings
You can "update" an existing string by (re)assigning a variable to another string. The new
value can be related to its previous value or to a completely different string altogether.
For example-
#!/usr/bin/python3
var1 = 'Hello World!'
print ("Updated String :- ", var1[:6] + 'Python')
99
Python 3
Escape Characters
Following table is a list of escape or non-printable characters that can be represented with
backslash notation.
An escape character gets interpreted; in a single quoted as well as double quoted strings.
Backslash Hexadecimal
Description
notation character
b 0x08 Backspace
\cx Control-x
\C-x Control-x
\e 0x1b Escape
\f 0x0c Formfeed
\M-\C-x Meta-Control-x
\n 0x0a Newline
\s 0x20 Space
\t 0x09 Tab
100
Python 3
\x Character x
[] Slice - Gives the character from the given index a[1] will give e
[:] Range Slice - Gives the characters from the given a[1:4] will give ell
range
not in Membership - Returns true if a character does not M not in a will give
exist in the given string 1
r/R Raw String - Suppresses actual meaning of Escape print r'\n' prints \n
characters. The syntax for raw strings is exactly the and print
same as for normal strings with the exception of the R'\n'prints \n
raw string operator, the letter "r," which precedes
the quotation marks. The "r" can be lowercase (r) or
uppercase (R) and must be placed immediately
preceding the first quote mark.
101
Python 3
#!/usr/bin/python3
print ("My name is %s and weight is %d kg!" % ('Zara', 21))
Here is the list of complete set of symbols which can be used along with %-
%c character
%o octal integer
102
Python 3
Other supported symbols and functionality are listed in the following table-
Symbol Functionality
- left justification
103
Python 3
Triple Quotes
Python's triple quotes comes to the rescue by allowing strings to span multiple lines,
including verbatim NEWLINEs, TABs, and any other special characters.
The syntax for triple quotes consists of three consecutive single or double quotes.
#!/usr/bin/python3
When the above code is executed, it produces the following result. Note how every single
special character has been converted to its printed form, right down to the last NEWLINE
at the end of the string between the "up." and closing triple quotes. Also note that
NEWLINEs occur either with an explicit carriage return at the end of a line or its escape
code (\n) −
Raw strings do not treat the backslash as a special character at all. Every character you
put into a raw string stays the way you wrote it-
#!/usr/bin/python3
print ('C:\\nowhere')
C:\nowhere
Now let us make use of raw string. We would put expression in r'expression' as follows-
#!/usr/bin/python3
104
Python 3
print (r'C:\\nowhere')
C:\\nowhere
Unicode String
In Python 3, all strings are represented in Unicode. In Python 2 are stored internally as 8-
bit ASCII, hence it is required to attach 'u' to make it Unicode. It is no longer necessary
now.
capitalize()
1
Capitalizes first letter of string
center(width, fillchar)
2
Returns a string padded with fillchar with the original string centered to a total
of width columns.
3
Counts how many times str occurs in string or in a substring of string if starting
index beg and ending index end are given.
decode(encoding='UTF-8',errors='strict')
4
Decodes the string using the codec registered for encoding. encoding defaults
to the default string encoding.
encode(encoding='UTF-8',errors='strict')
5
Returns encoded string version of string; on error, default is to raise a
ValueError unless errors is given with 'ignore' or 'replace'.
105
Python 3
Determines if string or a substring of string (if starting index beg and ending
index end are given) ends with suffix; returns true if so and false otherwise.
expandtabs(tabsize=8)
7
Expands tabs in string to multiple spaces; defaults to 8 spaces per tab if tabsize
not provided.
8
Determine if str occurs in string or in a substring of string if starting index beg
and ending index end are given returns index if found and -1 otherwise.
isalnum()
10
Returns true if string has at least 1 character and all characters are
alphanumeric and false otherwise.
isalpha()
11
Returns true if string has at least 1 character and all characters are alphabetic
and false otherwise.
isdigit()
12
Returns true if the string contains only digits and false otherwise.
islower()
13
Returns true if string has at least 1 cased character and all cased characters
are in lowercase and false otherwise.
isnumeric()
14
Returns true if a unicode string contains only numeric characters and false
otherwise.
106
Python 3
isspace()
15
Returns true if string contains only whitespace characters and false otherwise.
istitle()
16
Returns true if string is properly "titlecased" and false otherwise.
isupper()
17
Returns true if string has at least one cased character and all cased characters
are in uppercase and false otherwise.
join(seq)
18
Merges (concatenates) the string representations of elements in sequence seq
into a string, with separator string.
len(string)
19
Returns the length of the string
ljust(width[, fillchar])
20
Returns a space-padded string with the original string left-justified to a total
of width columns.
lower()
21
Converts all uppercase letters in string to lowercase.
lstrip()
22
Removes all leading whitespace in string.
maketrans()
23
Returns a translation table to be used in translate function.
107
Python 3
max(str)
24
Returns the max alphabetical character from the string str.
min(str)
25
Returns the min alphabetical character from the string str.
26
Replaces all occurrences of old in string with new or at most max occurrences
if max given.
rfind(str, beg=0,end=len(string))
27
Same as find(), but search backwards in string.
rjust(width,[, fillchar])
29
Returns a space-padded string with the original string right-justified to a total
of width columns.
rstrip()
30
Removes all trailing whitespace of string.
split(str="", num=string.count(str))
31
Splits string according to delimiter str (space if not provided) and returns list
of substrings; split into at most num substrings if given.
splitlines( num=string.count('\n'))
32
Splits string at all (or num) NEWLINEs and returns a list of each line with
NEWLINEs removed.
108
Python 3
startswith(str, beg=0,end=len(string))
33 Determines if string or a substring of string (if starting index beg and ending
index end are given) starts with substring str; returns true if so and false
otherwise.
strip([chars])
34
Performs both lstrip() and rstrip() on string
swapcase()
35
Inverts case for all letters in string.
title()
36
Returns "titlecased" version of string, that is, all words begin with uppercase
and the rest are lowercase.
translate(table, deletechars="")
37
Translates string according to translation table str(256 chars), removing those
in the del string.
upper()
38
Converts lowercase letters in string to uppercase.
zfill (width)
39
Returns original string leftpadded with zeros to a total of width characters;
intended for numbers, zfill() retains any sign given (less one zero).
isdecimal()
40
Returns true if a unicode string contains only decimal characters and false
otherwise.
Syntax
str.capitalize()
Parameters
NA
Return Value
string
Example
#!/usr/bin/python3
str = "this is string example....wow!!!"
print ("str.capitalize() : ", str.capitalize())
Result
str.capitalize() : This is string example....wow!!!
Syntax
str.center(width[, fillchar])
Parameters
width - This is the total width of the string.
fillchar - This is the filler character.
Return Value
This method returns a string that is at least width characters wide, created by padding the
string with the character fillchar (default is a space).
Example
The following example shows the usage of the center() method.
#!/usr/bin/python3
str = "this is string example....wow!!!"
110
Python 3
Result
str.center(40, 'a') : aaaathis is string example....wow!!!aaaa
Description
The count() method returns the number of occurrences of substring sub in the range
[start, end]. Optional arguments start and end are interpreted as in slice notation.
Syntax
str.count(sub, start= 0,end=len(string))
Parameters
sub - This is the substring to be searched.
start - Search starts from this index. First character starts from 0 index. By default
search starts from 0 index.
end - Search ends from this index. First character starts from 0 index. By default
search ends at the last index.
Return Value
Centered in a string of length width.
Example
#!/usr/bin/python3
str="this is string example....wow!!!"
sub='i'
print ("str.count('i') : ", str.count(sub))
sub='exam'
print ("str.count('exam', 10, 40) : ", str.count(sub,10,40))
Result
str.count('i') : 3
str.count('exam', 4, 40) :
111
Python 3
Description
The decode() method decodes the string using the codec registered for encoding. It
defaults to the default string encoding.
Syntax
Str.decode(encoding='UTF-8',errors='strict')
Parameters
encoding - This is the encodings to be used. For a list of all encoding schemes
please visit: Standard Encodings.
errors - This may be given to set a different error handling scheme. The default
for errors is 'strict', meaning that encoding errors raise a UnicodeError. Other
possible values are 'ignore', 'replace', 'xmlcharrefreplace', 'backslashreplace' and
any other name registered via codecs.register_error()..
Return Value
Decoded string.
Example
#!/usr/bin/python3
Str = "this is string example....wow!!!";
Str = Str.encode('base64','strict');
print "Encoded String: " + Str
print "Decoded String: " + Str.decode('base64','strict')
Result
Encoded String: b'dGhpcyBpcyBzdHJpbmcgZXhhbXBsZS4uLi53b3chISE='
Decoded String: this is string example....wow!!!
Description
The encode() method returns an encoded version of the string. Default encoding is the
current default string encoding. The errors may be given to set a different error handling
scheme.
112
Python 3
Syntax
str.encode(encoding='UTF-8',errors='strict')
Parameters
encoding - This is the encodings to be used. For a list of all encoding schemes
please visit: Standard Encodings.
errors - This may be given to set a different error handling scheme. The default
for errors is 'strict', meaning that encoding errors raise a UnicodeError. Other
possible values are 'ignore', 'replace', 'xmlcharrefreplace', 'backslashreplace' and
any other name registered via codecs.register_error().
Return Value
Decoded string.
Example
#!/usr/bin/python3
import base64
Str = "this is string example....wow!!!"
Str=base64.b64encode(Str.encode('utf-8',errors='strict'))
print ("Encoded String: " , Str)
Result
Encoded String: b'dGhpcyBpcyBzdHJpbmcgZXhhbXBsZS4uLi53b3chISE='
Description
It returns True if the string ends with the specified suffix, otherwise return False optionally
restricting the matching with the given indices start and end.
Syntax
str.endswith(suffix[, start[, end]])
Parameters
suffix - This could be a string or could also be a tuple of suffixes to look for.
113
Python 3
Return Value
TRUE if the string ends with the specified suffix, otherwise FALSE.
Example
#!/usr/bin/python3
Str='this is string example....wow!!!'
suffix='!!'
print (Str.endswith(suffix))
print (Str.endswith(suffix,20))
suffix='exam'
print (Str.endswith(suffix))
print (Str.endswith(suffix, 0, 19))
Result
True
True
False
True
Description
The expandtabs() method returns a copy of the string in which the tab characters ie. '\t'
are expanded using spaces, optionally using the given tabsize (default 8)..
Syntax
str.expandtabs(tabsize=8)
Parameters
tabsize - This specifies the number of characters to be replaced for a tab character '\t'.
Return Value
This method returns a copy of the string in which tab characters i.e., '\t' have been
expanded using spaces.
Example
114
Python 3
#!/usr/bin/python3
str = "this is\tstring example....wow!!!"
print ("Original string: " + str)
print ("Defualt exapanded tab: " + str.expandtabs())
print ("Double exapanded tab: " + str.expandtabs(16))
Result
Original string: this is string example....wow!!!
Defualt exapanded tab: this is string example....wow!!!
Double exapanded tab: this is string example....wow!!!
Description
The find() method determines if the string str occurs in string, or in a substring of string
if the starting index beg and ending index end are given.
Syntax
str.find(str, beg=0 end=len(string))
Parameters
str - This specifies the string to be searched.
end - This is the ending index, by default its equal to the lenght of the string.
Return Value
Index if found and -1 otherwise.
Example
#!/usr/bin/python3
str1 = "this is string example....wow!!!"
str2 = "exam";
print (str1.find(str2))
print (str1.find(str2, 10))
print (str1.find(str2, 40))
115
Python 3
Result
15
15
-1
Description
The index() method determines if the string str occurs in string or in a substring of string,
if the starting index beg and ending index end are given. This method is same as find(),
but raises an exception if sub is not found.
Syntax
str.index(str, beg=0 end=len(string))
Parameters
str - This specifies the string to be searched.
end - This is the ending index, by default its equal to the length of the string.
Return Value
Index if found otherwise raises an exception if str is not found.
Example
#!/usr/bin/python3
str1 = "this is string example....wow!!!"
str2 = "exam";
print (str1.index(str2))
print (str1.index(str2, 10))
print (str1.index(str2, 40))
Result
15
116
Python 3
15
Traceback (most recent call last):
File "test.py", line 7, in
print (str1.index(str2, 40))
ValueError: substring not found
shell returned 1
Description
The isalnum() method checks whether the string consists of alphanumeric characters.
Syntax
Following is the syntax for isalnum() method-
str.isa1num()
Parameters
NA
Return Value
This method returns true if all the characters in the string are alphanumeric and there is
at least one character, false otherwise.
Example
The following example shows the usage of isalnum() method.
#!/usr/bin/python3
str = "this2016" # No space in this string
print (str.isalnum())
str = "this is string example....wow!!!"
print (str.isalnum())
True
False
117
Python 3
Description
The isalpha() method checks whether the string consists of alphabetic characters only.
Syntax
Following is the syntax for islpha() method-
str.isalpha()
Parameters
NA
Return Value
This method returns true if all the characters in the string are alphabetic and there is at
least one character, false otherwise.
Example
The following example shows the usage of isalpha() method.
#!/usr/bin/python3
str = "this"; # No space & digit in this string
print (str.isalpha())
str = "this is string example....wow!!!"
print (str.isalpha())
Result
True
False
Description
The method isdigit() checks whether the string consists of digits only.
Syntax
Following is the syntax for isdigit() method-
str.isdigit()
118
Python 3
Parameters
NA
Return Value
This method returns true if all characters in the string are digits and there is at least one
character, false otherwise.
Example
The following example shows the usage of isdigit() method.
#!/usr/bin/python3
str = "123456"; # Only digit in this string
print (str.isdigit())
str = "this is string example....wow!!!"
print (str.isdigit())
Result
True
False
Description
The islower() method checks whether all the case-based characters (letters) of the string
are lowercase.
Syntax
Following is the syntax for islower() method-
str.islower()
Parameters
NA
Return Value
This method returns true if all cased characters in the string are lowercase and there is at
least one cased character, false otherwise.
Example
119
Python 3
#!/usr/bin/python3
str = "THIS is string example....wow!!!"
print (str.islower())
str = "this is string example....wow!!!"
print (str.islower())
Result
False
True
Description
The isnumeric() method checks whether the string consists of only numeric characters.
This method is present only on unicode objects.
Note: Unlike Python 2, all strings are represented in Unicode in Python 3. Given below is
an example illustrating it.
Syntax
Following is the syntax for isnumeric() method-
str.isnumeric()
Parameters
NA
Return Value
This method returns true if all characters in the string are numeric, false otherwise.
Example
The following example shows the usage of isnumeric() method.
#!/usr/bin/python3
str = "this2016"
print (str.isnumeric())
str = "23443434"
120
Python 3
print (str.isnumeric())
Result
False
True
Description
The isspace() method checks whether the string consists of whitespace..
Syntax
Following is the syntax for isspace() method-
str.isspace()
Parameters
NA
Return Value
This method returns true if there are only whitespace characters in the string and there is
at least one character, false otherwise.
Example
The following example shows the usage of isspace() method.
#!/usr/bin/python3
str = " "
print (str.isspace())
str = "This is string example....wow!!!"
print (str.isspace())
Result
True
False
121
Python 3
Description
The istitle() method checks whether all the case-based characters in the string following
non-casebased letters are uppercase and all other case-based characters are lowercase.
Syntax
Following is the syntax for istitle() method-
str.istitle()
Parameters
NA
Return Value
This method returns true if the string is a titlecased string and there is at least one
character, for example uppercase characters may only follow uncased characters and
lowercase characters only cased ones. It returns false otherwise.
Example
The following example shows the usage of istitle() method.
#!/usr/bin/python3
str = "This Is String Example...Wow!!!"
print (str.istitle())
str = "This is string example....wow!!!"
print (str.istitle())
Result
True
False
Description
122
Python 3
The isupper() method checks whether all the case-based characters (letters) of the string
are uppercase.
Syntax
Following is the syntax for isupper() method-
str.isupper()
Parameters
NA
Return Value
This method returns true if all the cased characters in the string are uppercase and there
is at least one cased character, false otherwise.
Example
The following example shows the usage of isupper() method.
#!/usr/bin/python3
str = "THIS IS STRING EXAMPLE....WOW!!!"
print (str.isupper())
str = "THIS is string example....wow!!!"
print (str.isupper())
Result
True
False
Description
The join() method returns a string in which the string elements of sequence have been
joined by str separator.
Syntax
Following is the syntax for join() method-
str.join(sequence)
Parameters
123
Python 3
Return Value
This method returns a string, which is the concatenation of the strings in the sequence
seq. The separator between elements is the string providing this method.
Example
The following example shows the usage of join() method.
#!/usr/bin/python3
s = "-"
seq = ("a", "b", "c") # This is sequence of strings.
print (s.join( seq ))
Result
a-b-c
Description
The len() method returns the length of the string.
Syntax
Following is the syntax for len() method −
len( str )
Parameters
NA
Return Value
This method returns the length of the string.
Example
The following example shows the usage of len() method.
#!/usr/bin/python3
str = "this is string example....wow!!!"
print ("Length of the string: ", len(str))
124
Python 3
Result
Length of the string: 32
Description
The method ljust() returns the string left justified in a string of length width. Padding is
done using the specified fillchar (default is a space). The original string is returned if width
is less than len(s).
Syntax
Following is the syntax for ljust() method −
str.ljust(width[, fillchar])
Parameters
width - This is string length in total after padding.
fillchar - This is filler character, default is a space.
Return Value
This method returns the string left justified in a string of length width. Padding is done
using the specified fillchar (default is a space). The original string is returned if width is
less than len(s).
Example
The following example shows the usage of ljust() method.
#!/usr/bin/python3
str = "this is string example....wow!!!"
print str.ljust(50, '*')
Result
this is string example....wow!!!******************
Description
The method lower() returns a copy of the string in which all case-based characters have
been lowercased.
125
Python 3
Syntax
Following is the syntax for lower() method −
str.lower()
Parameters
NA
Return Value
This method returns a copy of the string in which all case-based characters have been
lowercased.
Example
The following example shows the usage of lower() method.
#!/usr/bin/python3
str = "THIS IS STRING EXAMPLE....WOW!!!"
print (str.lower())
Result
this is string example....wow!!!
Description
The lstrip() method returns a copy of the string in which all chars have been stripped
from the beginning of the string (default whitespace characters).
Syntax
Following is the syntax for lstrip() method-
str.lstrip([chars])
Parameters
chars - You can supply what chars have to be trimmed.
Return Value
This method returns a copy of the string in which all chars have been stripped from the
beginning of the string (default whitespace characters).
126
Python 3
Example
The following example shows the usage of lstrip() method.
#!/usr/bin/python3
str = " this is string example....wow!!!"
print (str.lstrip())
str = "*****this is string example....wow!!!*****"
print (str.lstrip('*'))
Result
this is string example....wow!!!
this is string example....wow!!!*****
Description
The maketrans() method returns a translation table that maps each character in the
intabstring into the character at the same position in the outtab string. Then this table is
passed to the translate() function.
Note: Both intab and outtab must have the same length.
Syntax
Following is the syntax for maketrans() method-
str.maketrans(intab, outtab]);
Parameters
intab - This is the string having actual characters.
outtab - This is the string having corresponding mapping character.
Return Value
This method returns a translate table to be used translate() function.
Example
The following example shows the usage of maketrans() method. Under this, every vowel
in a string is replaced by its vowel position −
#!/usr/bin/python3
intab = "aeiou"
127
Python 3
outtab = "12345"
trantab = str.maketrans(intab, outtab)
str = "this is string example....wow!!!"
print (str.translate(trantab))
Result
th3s 3s str3ng 2x1mpl2....w4w!!!
Description
The max() method returns the max alphabetical character from the string str.
Syntax
Following is the syntax for max() method-
max(str)
Parameters
str - This is the string from which max alphabetical character needs to be returned.
Return Value
This method returns the max alphabetical character from the string str.
Example
The following example shows the usage of max() method.
#!/usr/bin/python3
str = "this is a string example....really!!!"
print ("Max character: " + max(str))
str = "this is a string example....wow!!!"
print ("Max character: " + max(str))
Result
Max character: y
Max character: x
128
Python 3
Description
The min() method returns the min alphabetical character from the string str.
Syntax
Following is the syntax for min() method-
min(str)
Parameters
str - This is the string from which min alphabetical character needs to be returned.
Return Value
This method returns the max alphabetical character from the string str.
Example
The following example shows the usage of min() method.
#!/usr/bin/python3
str = "www.tutorialspoint.com"
print ("Min character: " + min(str))
str = "TUTORIALSPOINT"
print ("Min character: " + min(str))
Result
Min character: .
Min character: A
Description
The replace() method returns a copy of the string in which the occurrences of old have
been replaced with new, optionally restricting the number of replacements to max.
Syntax
Following is the syntax for replace() method-
129
Python 3
Parameters
old - This is old substring to be replaced.
max - If this optional argument max is given, only the first count occurrences are
replaced.
Return Value
This method returns a copy of the string with all occurrences of substring old replaced by
new. If the optional argument max is given, only the first count occurrences are replaced.
Example
The following example shows the usage of replace() method.
#!/usr/bin/python3
str = "this is string example....wow!!! this is really string"
print (str.replace("is", "was"))
print (str.replace("is", "was", 3))
Result
thwas was string example....wow!!! thwas was really string
thwas was string example....wow!!! thwas is really string
Description
The rfind() method returns the last index where the substring str is found, or -1 if no
such index exists, optionally restricting the search to string[beg:end].
Syntax
Following is the syntax for rfind() method-
Parameters
str - This specifies the string to be searched.
end - This is the ending index, by default its equal to the length of the string.
130
Python 3
Return Value
This method returns last index if found and -1 otherwise.
Example
The following example shows the usage of rfind() method.
#!/usr/bin/python3
str1 = "this is really a string example....wow!!!"
str2 = "is"
print (str1.rfind(str2))
print (str1.rfind(str2, 0, 10))
print (str1.rfind(str2, 10, 0))
print (str1.find(str2))
print (str1.find(str2, 0, 10))
print (str1.find(str2, 10, 0))
Result
5
5
-1
2
2
-1
Description
The rindex() method returns the last index where the substring str is found, or raises an
exception if no such index exists, optionally restricting the search to string[beg:end].
Syntax
Following is the syntax for rindex() method-
Parameters
str - This specifies the string to be searched.
131
Python 3
len - This is ending index, by default its equal to the length of the string.
Return Value
This method returns last index if found otherwise raises an exception if str is not found.
Example
The following example shows the usage of rindex() method.
#!/usr/bin/python3
str1 = "this is really a string example....wow!!!"
str2 = "is"
print (str1.rindex(str2))
print (str1.rindex(str2,10))
Result
5
Traceback (most recent call last):
File "test.py", line 5, in
print (str1.rindex(str2,10))
ValueError: substring not found
Description
The rjust() method returns the string right justified in a string of length width. Padding
is done using the specified fillchar (default is a space). The original string is returned if
width is less than len(s).
Syntax
Following is the syntax for rjust() method-
str.rjust(width[, fillchar])
Parameters
width - This is the string length in total after padding.
fillchar - This is the filler character, default is a space.
132
Python 3
Return Value
This method returns the string right justified in a string of length width. Padding is done
using the specified fillchar (default is a space). The original string is returned if the width
is less than len(s).
Example
The following example shows the usage of rjust() method.
#!/usr/bin/python3
str = "this is string example....wow!!!"
print (str.rjust(50, '*'))
Result
******************this is string example....wow!!!
Description
The rstrip() method returns a copy of the string in which all chars have been stripped
from the end of the string (default whitespace characters).
Syntax
Following is the syntax for rstrip() method-
str.rstrip([chars])
Parameters
chars - You can supply what chars have to be trimmed.
Return Value
This method returns a copy of the string in which all chars have been stripped from the
end of the string (default whitespace characters).
Example
The following example shows the usage of rstrip() method.
#!/usr/bin/python3
str = " this is string example....wow!!! "
print (str.rstrip())
str = "*****this is string example....wow!!!*****"
133
Python 3
print (str.rstrip('*'))
Result
this is string example....wow!!!
*****this is string example....wow!!!
Description
The split() method returns a list of all the words in the string, using str as the separator
(splits on all whitespace if left unspecified), optionally limiting the number of splits to num.
Syntax
Following is the syntax for split() method-
str.split(str="", num=string.count(str)).
Parameters
str - This is any delimeter, by default it is space.
Return Value
This method returns a list of lines.
Example
The following example shows the usage of split() method.
#!/usr/bin/python3
str = "this is string example....wow!!!"
print (str.split( ))
print (str.split('i',1))
print (str.split('w'))
Result
['this', 'is', 'string', 'example....wow!!!']
['th', 's is string example....wow!!!']
['this is string example....', 'o', '!!!']
134
Python 3
Description
The splitlines() method returns a list with all the lines in string, optionally including the
line breaks (if num is supplied and is true).
Syntax
Following is the syntax for splitlines() method-
str.splitlines( num=string.count('\n'))
Parameters
num - This is any number, if present then it would be assumed that the line breaks need
to be included in the lines.
Return Value
This method returns true if found matching with the string otherwise false.
Example
The following example shows the usage of splitlines() method.
#!/usr/bin/python3
str = "this is \nstring example....\nwow!!!"
print (str.splitlines( ))
Result
['this is ', 'string example....', 'wow!!!']
Description
The startswith() method checks whether the string starts with str, optionally restricting
the matching with the given indices start and end.
Syntax
Following is the syntax for startswith() method-
str.startswith(str, beg=0,end=len(string));
135
Python 3
Parameters
str - This is the string to be checked.
beg - This is the optional parameter to set start index of the matching boundary.
end - This is the optional parameter to set start index of the matching boundary.
Return Value
This method returns true if found matching with the string otherwise false.
Example
The following example shows the usage of startswith() method.
#!/usr/bin/python3
str = "this is string example....wow!!!"
print (str.startswith( 'this' ))
print (str.startswith( 'string', 8 ))
print (str.startswith( 'this', 2, 4 ))
Result
True
True
False
Description
The strip() method returns a copy of the string in which all chars have been stripped from
the beginning and the end of the string (default whitespace characters).
Syntax
Following is the syntax for strip() method −
str.strip([chars]);
Parameters
chars - The characters to be removed from beginning or end of the string.
Return Value
136
Python 3
This method returns a copy of the string in which all the chars have been stripped from
the beginning and the end of the string.
Example
The following example shows the usage of strip() method.
#!/usr/bin/python3
str = "*****this is string example....wow!!!*****"
print (str.strip( '*' ))
Result
this is string example....wow!!!
Description
The swapcase() method returns a copy of the string in which all the case-based
characters have had their case swapped.
Syntax
Following is the syntax for swapcase() method-
str.swapcase();
Parameters
NA
Return Value
This method returns a copy of the string in which all the case-based characters have had
their case swapped.
Example
The following example shows the usage of swapcase() method.
#!/usr/bin/python3
str = "this is string example....wow!!!"
print (str.swapcase())
str = "This Is String Example....WOW!!!"
print (str.swapcase())
137
Python 3
Result
THIS IS STRING EXAMPLE....WOW!!!
tHIS iS sTRING eXAMPLE....wow!!!
Description
The title() method returns a copy of the string in which first characters of all the words
are capitalized.
Syntax
Following is the syntax for title() method-
str.title();
Parameters
NA
Return Value
This method returns a copy of the string in which first characters of all the words are
capitalized.
Example
The following example shows the usage of title() method.
#!/usr/bin/python3
str = "this is string example....wow!!!"
print (str.title())
Result
This Is String Example....Wow!!!
Description
The method translate() returns a copy of the string in which all the characters have been
translated using table (constructed with the maketrans() function in the string module),
optionally deleting all characters found in the string deletechars.
138
Python 3
Syntax
Following is the syntax for translate() method-
str.translate(table[, deletechars]);
Parameters
table - You can use the maketrans() helper function in the string module to create
a translation table.
Return Value
This method returns a translated copy of the string.
Example
The following example shows the usage of translate() method. Under this, every vowel in
a string is replaced by its vowel position.
#!/usr/bin/python3
from string import maketrans # Required to call maketrans function.
intab = "aeiou"
outtab = "12345"
trantab = maketrans(intab, outtab)
str = "this is string example....wow!!!";
print (str.translate(trantab))
Result
th3s 3s str3ng 2x1mpl2....w4w!!!
Following is the example to delete 'x' and 'm' characters from the string-
#!/usr/bin/python3
from string import maketrans # Required to call maketrans function.
intab = "aeiouxm"
outtab = "1234512"
trantab = maketrans(intab, outtab)
str = "this is string example....wow!!!";
print (str.translate(trantab))
139
Python 3
Result
th3s 3s str3ng 21pl2....w4w!!!
Description
The upper() method returns a copy of the string in which all case-based characters have
been uppercased.
Syntax
Following is the syntax for upper() method −
str.upper()
Parameters
NA
Return Value
This method returns a copy of the string in which all case-based characters have been
uppercased.
Example
The following example shows the usage of upper() method.
#!/usr/bin/python3
str = "this is string example....wow!!!"
print ("str.upper : ",str.upper())
Result
str.upper : THIS IS STRING EXAMPLE....WOW!!!
Description
The zfill() method pads string on the left with zeros to fill width.
Syntax
140
Python 3
str.zfill(width)
Parameters
width - This is final width of the string. This is the width which we would get after filling
zeros.
Return Value
This method returns padded string.
Example
The following example shows the usage of zfill() method.
#!/usr/bin/python3
str = "this is string example....wow!!!"
print ("str.zfill : ",str.zfill(40))
print ("str.zfill : ",str.zfill(50))
Result
str.zfill : 00000000this is string example....wow!!!
str.zfill : 000000000000000000this is string example....wow!!!
Description
The isdecimal() method checks whether the string consists of only decimal characters.
This method are present only on unicode objects.
Note: Unlike in Python 2, all strings are represented as Unicode in Python 3. Given Below
is an example illustrating it.
Syntax
Following is the syntax for isdecimal() method-
str.isdecimal()
Parameters
NA
Return Value
141
Python 3
This method returns true if all the characters in the string are decimal, false otherwise.
Example
The following example shows the usage of isdecimal() method.
#!/usr/bin/python3
str = "this2016"
print (str.isdecimal())
str = "23443434"
print (str.isdecimal())
Result
False
True
142
11. Python 3 – Lists Python 3
The most basic data structure in Python is the sequence. Each element of a sequence is
assigned a number - its position or index. The first index is zero, the second index is one,
and so forth.
Python has six built-in types of sequences, but the most common ones are lists and tuples,
which we would see in this tutorial.
There are certain things you can do with all the sequence types. These operations include
indexing, slicing, adding, multiplying, and checking for membership. In addition, Python
has built-in functions for finding the length of a sequence and for finding its largest and
smallest elements.
Python Lists
The list is the most versatile datatype available in Python, which can be written as a list
of comma-separated values (items) between square brackets. Important thing about a list
is that the items in a list need not be of the same type.
Similar to string indices, list indices start at 0, and lists can be sliced, concatenated and
so on.
#!/usr/bin/python3
list1 = ['physics', 'chemistry', 1997, 2000]
list2 = [1, 2, 3, 4, 5, 6, 7 ]
print ("list1[0]: ", list1[0])
print ("list2[1:5]: ", list2[1:5])
list1[0]: physics
list2[1:5]: [2, 3, 4, 5]
143
Python 3
Updating Lists
You can update single or multiple elements of lists by giving the slice on the left-hand side
of the assignment operator, and you can add to elements in a list with the append()
method. For example-
#!/usr/bin/python3
list = ['physics', 'chemistry', 1997, 2000]
print ("Value available at index 2 : ", list[2])
list[2] = 2001
print ("New value available at index 2 : ", list[2])
#!/usr/bin/python3
list = ['physics', 'chemistry', 1997, 2000]
print (list)
del list[2]
print ("After deleting value at index 2 : ", list)
In fact, lists respond to all of the general sequence operations we used on strings in the
prior chapter.
144
Python 3
1 cmp(list1, list2)
145
Python 3
2 len(list)
3 max(list)
4 min(list)
5 list(seq)
Description
The len() method returns the number of elements in the list.
Syntax
Following is the syntax for len() method-
len(list)
Parameters
list - This is a list for which, number of elements are to be counted.
Return Value
This method returns the number of elements in the list.
Example
The following example shows the usage of len() method.
#!/usr/bin/python3
list1 = ['physics', 'chemistry', 'maths']
print (len(list1))
list2=list(range(5)) #creates list of numbers between 0-4
print (len(list2))
146
Python 3
3
5
Description
The max() method returns the elements from the list with maximum value.
Syntax
Following is the syntax for max() method-
max(list)
Parameters
list - This is a list from which max valued element are to be returned.
Return Value
This method returns the elements from the list with maximum value.
Example
The following example shows the usage of max() method.
#!/usr/bin/python3
list1, list2 = ['C++','Java', 'Python'], [456, 700, 200]
print ("Max value element : ", max(list1))
print ("Max value element : ", max(list2))
Description
The method min() returns the elements from the list with minimum value.
147
Python 3
Syntax
Following is the syntax for min() method-
min(list)
Parameters
list - This is a list from which min valued element is to be returned.
Return Value
This method returns the elements from the list with minimum value.
Example
The following example shows the usage of min() method.
#!/usr/bin/python3
list1, list2 = ['C++','Java', 'Python'], [456, 700, 200]
print ("min value element : ", min(list1))
print ("min value element : ", min(list2))
Description
The list() method takes sequence types and converts them to lists. This is used to convert
a given tuple into list.
Note: Tuple are very similar to lists with only difference that element values of a tuple
can not be changed and tuple elements are put between parentheses instead of square
bracket. This function also converts characters in a string into a list.
Syntax
Following is the syntax for list() method-
list( seq )
Parameters
seq - This is a tuple or string to be converted into list.
148
Python 3
Return Value
This method returns the list.
Example
The following example shows the usage of list() method.
#!/usr/bin/python3
aTuple = (123, 'C++', 'Java', 'Python')
list1 = list(aTuple)
print ("List elements : ", list1)
str="Hello World"
list2=list(str)
print ("List elements : ", list2)
1 list.append(obj)
2 list.count(obj)
3 list.extend(seq)
4 list.index(obj)
5 list.insert(index, obj)
149
Python 3
6 list.pop(obj=list[-1])
7 list.remove(obj)
8 list.reverse()
9 list.sort([func])
Description
The append() method appends a passed obj into the existing list.
Syntax
Following is the syntax for append() method-
list.append(obj)
Parameters
obj - This is the object to be appended in the list.
Return Value
This method does not return any value but updates existing list.
Example
The following example shows the usage of append() method.
#!/usr/bin/python3
list1 = ['C++', 'Java', 'Python']
list1.append('C#')
print ("updated list : ", list1)
150
Python 3
Description
The count() method returns count of how many times obj occurs in list.
Syntax
Following is the syntax for count() method-
list.count(obj)
Parameters
obj - This is the object to be counted in the list.
Return Value
This method returns count of how many times obj occurs in list.
Example
The following example shows the usage of count() method.
#!/usr/bin/python3
aList = [123, 'xyz', 'zara', 'abc', 123];
print ("Count for 123 : ", aList.count(123))
print ("Count for zara : ", aList.count('zara'))
Description
The extend() method appends the contents of seq to list.
Syntax
Following is the syntax for extend() method-
151
Python 3
list.extend(seq)
Parameters
seq - This is the list of elements
Return Value
This method does not return any value but adds the content to an existing list.
Example
The following example shows the usage of extend() method.
#!/usr/bin/python3
list1 = ['physics', 'chemistry', 'maths']
list2=list(range(5)) #creates list of numbers between 0-4
list1.extend('Extended List :', list2)
print (list1)
Description
The index() method returns the lowest index in list that obj appears.
Syntax
Following is the syntax for index() method-
list.index(obj)
Parameters
obj - This is the object to be find out.
Return Value
This method returns index of the found object otherwise raises an exception indicating
that the value is not found.
Example
The following example shows the usage of index() method.
152
Python 3
#!/usr/bin/python3
list1 = ['physics', 'chemistry', 'maths']
print ('Index of chemistry', list1.index('chemistry'))
print ('Index of C#', list1.index('C#'))
Index of chemistry 1
Traceback (most recent call last):
File "test.py", line 3, in
print ('Index of C#', list1.index('C#'))
ValueError: 'C#' is not in list
Description
The insert() method inserts object obj into list at offset index.
Syntax
Following is the syntax for insert() method-
list.insert(index, obj)
Parameters
index - This is the Index where the object obj need to be inserted.
Return Value
This method does not return any value but it inserts the given element at the given index.
Example
The following example shows the usage of insert() method.
#!/usr/bin/python3
list1 = ['physics', 'chemistry', 'maths']
list1.insert(1, 'Biology')
print ('Final list : ', list1)
153
Python 3
Description
The pop() method removes and returns last object or obj from the list.
Syntax
Following is the syntax for pop() method-
list.pop(obj=list[-1])
Parameters
obj - This is an optional parameter, index of the object to be removed from the list.
Return Value
This method returns the removed object from the list.
Example
The following example shows the usage of pop() method.
#!/usr/bin/python3
list1 = ['physics', 'Biology', 'chemistry', 'maths']
list1.pop()
print ("list now : ", list1)
list1.pop(1)
print ("list now : ", list1)
Parameters
obj - This is the object to be removed from the list.
Return Value
This method does not return any value but removes the given object from the list.
154
Python 3
Example
The following example shows the usage of remove() method.
#!/usr/bin/python3
list1 = ['physics', 'Biology', 'chemistry', 'maths']
list1.remove('Biology')
print ("list now : ", list1)
list1.remove('maths')
print ("list now : ", list1)
Description
The reverse() method reverses objects of list in place.
Syntax
Following is the syntax for reverse() method-
list.reverse()
Parameters
NA
Return Value
This method does not return any value but reverse the given object from the list.
Example
The following example shows the usage of reverse() method.
#!/usr/bin/python3
list1 = ['physics', 'Biology', 'chemistry', 'maths']
list1.reverse()
print ("list now : ", list1)
155
Python 3
Description
The sort() method sorts objects of list, use compare function if given.
Syntax
Following is the syntax for sort() method-
list.sort([func])
Parameters
NA
Return Value
This method does not return any value but reverses the given object from the list.
Example
The following example shows the usage of sort() method.
#!/usr/bin/python3
list1 = ['physics', 'Biology', 'chemistry', 'maths']
list1.sort()
print ("list now : ", list1)
156
12. Python 3 – Tuples Python 3
A tuple is a sequence of immutable Python objects. Tuples are sequences, just like lists.
The main difference between the tuples and the lists is that the tuples cannot be changed
unlike lists. Tuples use parentheses, whereas lists use square brackets.
tup1 = ();
To write a tuple containing a single value you have to include a comma, even though there
is only one value.
tup1 = (50,)
Like string indices, tuple indices start at 0, and they can be sliced, concatenated, and so
on.
#!/usr/bin/python3
tup1 = ('physics', 'chemistry', 1997, 2000)
tup2 = (1, 2, 3, 4, 5, 6, 7 )
print ("tup1[0]: ", tup1[0])
print ("tup2[1:5]: ", tup2[1:5])
tup1[0]: physics
tup2[1:5]: [2, 3, 4, 5]
157
Python 3
Updating Tuples
Tuples are immutable, which means you cannot update or change the values of tuple
elements. You are able to take portions of the existing tuples to create new tuples as the
following example demonstrates.
#!/usr/bin/python3
To explicitly remove an entire tuple, just use the del statement. For example-
#!/usr/bin/python3
tup = ('physics', 'chemistry', 1997, 2000);
print (tup)
del tup;
print "After deleting tup : "
print tup
Note: An exception is raised. This is because after del tup, tuple does not exist any more.
In fact, tuples respond to all of the general sequence operations we used on strings in the
previous chapter.
159
Python 3
No Enclosing Delimiters
No enclosing Delimiters is any set of multiple objects, comma-separated, written without
identifying symbols, i.e., brackets for lists, parentheses for tuples, etc., default to tuples,
as indicated in these short examples.
1 cmp(tuple1, tuple2)
2 len(tuple)
3 max(tuple)
4 min(tuple)
5 tuple(seq)
Description
The len() method returns the number of elements in the tuple.
Syntax
Following is the syntax for len() method-
len(tuple)
Parameters
tuple - This is a tuple for which number of elements to be counted.
160
Python 3
Return Value
This method returns the number of elements in the tuple.
Example
The following example shows the usage of len() method.
#!/usr/bin/python3
tuple1, tuple2 = (123, 'xyz', 'zara'), (456, 'abc')
print ("First tuple length : ", len(tuple1))
print ("Second tuple length : ", len(tuple2))
Description
The max() method returns the elements from the tuple with maximum value.
Syntax
Following is the syntax for max() method-
max(tuple)
Parameters
tuple - This is a tuple from which max valued element to be returned.
Return Value
This method returns the elements from the tuple with maximum value.
Example
The following example shows the usage of max() method.
#!/usr/bin/python3
tuple1, tuple2 = ('maths', 'che', 'phy', 'bio'), (456, 700, 200)
print ("Max value element : ", max(tuple1))
print ("Max value element : ", max(tuple2))
161
Python 3
Description
The min() method returns the elements from the tuple with minimum value.
Syntax
Following is the syntax for min() method-
min(tuple)
Parameters
tuple - This is a tuple from which min valued element is to be returned.
Return Value
This method returns the elements from the tuple with minimum value.
Example
The following example shows the usage of min() method.
#!/usr/bin/python3
tuple1, tuple2 = ('maths', 'che', 'phy', 'bio'), (456, 700, 200)
print ("min value element : ", min(tuple1))
print ("min value element : ", min(tuple2))
Description
The tuple() method converts a list of items into tuples.
Syntax
162
Python 3
tuple( seq )
Parameters
seq - This is a tuple to be converted into tuple.
Return Value
This method returns the tuple.
Example
The following example shows the usage of tuple() method.
#!/usr/bin/python3
list1= ['maths', 'che', 'phy', 'bio']
tuple1=tuple(list1)
print ("tuple elements : ", tuple1)
163
13. Python 3 – Dictionary Python 3
Each key is separated from its value by a colon (:), the items are separated by commas,
and the whole thing is enclosed in curly braces. An empty dictionary without any items is
written with just two curly braces, like this: {}.
Keys are unique within a dictionary while values may not be. The values of a dictionary
can be of any type, but the keys must be of an immutable data type such as strings,
numbers, or tuples.
#!/usr/bin/python3
dict['Name']: Zara
dict['Age']: 7
If we attempt to access a data item with a key, which is not a part of the dictionary, we
get an error as follows-
#!/usr/bin/python3
dict['Zara']:
Traceback (most recent call last):
File "test.py", line 4, in <module>
print "dict['Alice']: ", dict['Alice'];
KeyError: 'Alice'
164
Python 3
Updating Dictionary
You can update a dictionary by adding a new entry or a key-value pair, modifying an
existing entry, or deleting an existing entry as shown in a simple example given below.
#!/usr/bin/python3
dict['Age']: 8
dict['School']: DPS School
To explicitly remove an entire dictionary, just use the del statement. Following is a simple
example-
#!/usr/bin/python3
Note: An exception is raised because after del dict, the dictionary does not exist
anymore.
dict['Age']:
Traceback (most recent call last):
File "test.py", line 8, in <module>
165
Python 3
(a) More than one entry per key is not allowed. This means no duplicate key is allowed.
When duplicate keys are encountered during assignment, the last assignment wins. For
example-
#!/usr/bin/python3
dict['Name']: Manni
(b) Keys must be immutable. This means you can use strings, numbers or tuples as
dictionary keys but something like ['key'] is not allowed. Following is a simple example-
#!/usr/bin/python3
166
Python 3
1 cmp(dict1, dict2)
2 len(dict)
Gives the total length of the dictionary. This would be equal to the number of items
in the dictionary.
3 str(dict)
4 type(variable)
Returns the type of the passed variable. If passed variable is dictionary, then it
would return a dictionary type.
DescriptionThe method len() gives the total length of the dictionary. This
would be equal to the number of items in the dictionary.
Syntax
Following is the syntax for len() method-
len(dict)
Parameters
dict - This is the dictionary, whose length needs to be calculated.
Return Value
This method returns the length.
Example
The following example shows the usage of len() method.
#!/usr/bin/python3
167
Python 3
Length : 3
Description
The method str() produces a printable string representation of a dictionary.
Syntax
Following is the syntax for str() method −
str(dict)
Parameters
dict - This is the dictionary.
Return Value
This method returns string representation.
Example
The following example shows the usage of str() method.
#!/usr/bin/python3
dict = {'Name': 'Manni', 'Age': 7, 'Class': 'First'}
print ("Equivalent String : %s" % str (dict))
Description
The method type() returns the type of the passed variable. If passed variable is dictionary
then it would return a dictionary type.
168
Python 3
Syntax
Following is the syntax for type() method-
type(dict)
Parameters
dict - This is the dictionary.
Return Value
This method returns the type of the passed variable.
Example
The following example shows the usage of type() method.
#!/usr/bin/python3
dict = {'Name': 'Manni', 'Age': 7, 'Class': 'First'}
print ("Variable Type : %s" % type (dict))
1 dict.clear()
2 dict.copy()
3 dict.fromkeys()
Create a new dictionary with keys from seq and values set to value.
4 dict.get(key, default=None)
169
Python 3
5 dict.has_key(key)
6 dict.items()
7 dict.keys()
8 dict.setdefault(key, default=None)
Similar to get(), but will set dict[key]=default if key is not already in dict.
9 dict.update(dict2)
10 dict.values()
Description
The method clear() removes all items from the dictionary.
Syntax
Following is the syntax for clear() method-
dict.clear()
Parameters
NA
Return Value
This method does not return any value.
Example
The following example shows the usage of clear() method.
#!/usr/bin/python3
170
Python 3
Start Len : 2
End Len : 0
Description
The method copy() returns a shallow copy of the dictionary.
Syntax
Following is the syntax for copy() method-
dict.copy()
Parameters
NA
Return Value
This method returns a shallow copy of the dictionary.
Example
The following example shows the usage of copy() method.
#!/usr/bin/python3
dict1 = {'Name': 'Manni', 'Age': 7, 'Class': 'First'}
dict2 = dict1.copy()
print ("New Dictionary : ",dict2)
171
Python 3
Description
The method fromkeys() creates a new dictionary with keys from seq and values set to
value.
Syntax
Following is the syntax for fromkeys() method-
dict.fromkeys(seq[, value]))
Parameters
seq - This is the list of values which would be used for dictionary keys preparation.
value - This is optional, if provided then value would be set to this value
Return Value
This method returns the list.
Example
The following example shows the usage of fromkeys() method.
#!/usr/bin/python3
seq = ('name', 'age', 'sex')
dict = dict.fromkeys(seq)
print ("New Dictionary : %s" % str(dict))
dict = dict.fromkeys(seq, 10)
print ("New Dictionary : %s" % str(dict))
Description
The method get() returns a value for the given key. If the key is not available then returns
default value None.
Syntax
172
Python 3
dict.get(key, default=None)
Parameters
key - This is the Key to be searched in the dictionary.
default - This is the Value to be returned in case key does not exist.
Return Value
This method returns a value for the given key. If the key is not available, then returns
default value as None.
Example
The following example shows the usage of get() method.
#!/usr/bin/python3
dict = {'Name': 'Zara', 'Age': 27}
print ("Value : %s" % dict.get('Age'))
print ("Value : %s" % dict.get('Sex', "NA"))
Value : 27
Value : NA
Description
The method items() returns a list of dict's (key, value) tuple pairs.
Syntax
Following is the syntax for items() method-
dict.items()
Parameters
NA
Return Value
This method returns a list of tuple pairs.
173
Python 3
Example
The following example shows the usage of items() method.
#!/usr/bin/python
dict = {'Name': 'Zara', 'Age': 7}
print ("Value : %s" % dict.items())
Description
The method keys() returns a list of all the available keys in the dictionary.
Syntax
Following is the syntax for keys() method-
dict.keys()
Parameters
NA
Return Value
This method returns a list of all the available keys in the dictionary.
Example
The following example shows the usage of keys() method.
#!/usr/bin/python3
dict = {'Name': 'Zara', 'Age': 7}
print ("Value : %s" % dict.keys())
Description
174
Python 3
The method setdefault() is similar to get(), but will set dict[key]=default if the key is not
already in dict.
Syntax
Following is the syntax for setdefault() method-
dict.setdefault(key, default=None)
Parameters
key - This is the key to be searched.
Return Value
This method returns the key value available in the dictionary and if given key is not
available then it will return provided default value.
Example
The following example shows the usage of setdefault() method.
#!/usr/bin/python3
dict = {'Name': 'Zara', 'Age': 7}
print ("Value : %s" % dict.setdefault('Age', None))
print ("Value : %s" % dict.setdefault('Sex', None))
print (dict)
Value : 7
Value : None
{'Name': 'Zara', 'Sex': None, 'Age': 7}
Description
The method update() adds dictionary dict2's key-values pairs in to dict. This function
does not return anything.
Syntax
Following is the syntax for update() method-
dict.update(dict2)
175
Python 3
Parameters
dict2 - This is the dictionary to be added into dict.
Return Value
This method does not return any value.
Example
The following example shows the usage of update() method.
#!/usr/bin/python3
dict = {'Name': 'Zara', 'Age': 7}
dict2 = {'Sex': 'female' }
dict.update(dict2)
print ("updated dict : ", dict)
Description
The method values() returns a list of all the values available in a given dictionary.
Syntax
Following is the syntax for values() method-
dict.values()
Parameters
NA
Return Value
This method returns a list of all the values available in a given dictionary.
Example
The following example shows the usage of values() method.
#!/usr/bin/python3
dict = {'Sex': 'female', 'Age': 7, 'Name': 'Zara'}
176
Python 3
177
14. Python 3 – Date & Time Python 3
A Python program can handle date and time in several ways. Converting between date
formats is a common chore for computers. Python's time and calendar modules help track
dates and times.
What is Tick?
Time intervals are floating-point numbers in units of seconds. Particular instants in time
are expressed in seconds since 12:00am, January 1, 1970(epoch).
There is a popular time module available in Python, which provides functions for working
with times, and for converting between representations. The function time.time() returns
the current system time in ticks since 12:00am, January 1, 1970(epoch).
Example
#!/usr/bin/python3
import time; # This is required to include time module.
ticks = time.time()
print ("Number of ticks since 12:00am, January 1, 1970:", ticks)
Date arithmetic is easy to do with ticks. However, dates before the epoch cannot be
represented in this form. Dates in the far future also cannot be represented this way - the
cutoff point is sometime in 2038 for UNIX and Windows.
What is TimeTuple?
Many of the Python's time functions handle time as a tuple of 9 numbers, as shown below-
1 Month 1 to 12
2 Day 1 to 31
178
Python 3
3 Hour 0 to 23
4 Minute 0 to 59
For Example-
>>>import time
>>> print (time.localtime())
The above tuple is equivalent to struct_time structure. This structure has the following
attributes-
0 tm_year 2016
1 tm_mon 1 to 12
2 tm_mday 1 to 31
3 tm_hour 0 to 23
4 tm_min 0 to 59
6 tm_wday 0 to 6 (0 is Monday)
179
Python 3
#!/usr/bin/python3
import time
localtime = time.localtime(time.time())
print ("Local current time :", localtime)
This would produce the following result, which could be formatted in any other presentable
form-
#!/usr/bin/python3
import time
#!/usr/bin/python3
import calendar
180
Python 3
cal = calendar.month(2016, 2)
print ("Here is the calendar:")
print (cal)
1 time.altzone
The offset of the local DST timezone, in seconds west of UTC, if one is defined.
This is negative if the local DST timezone is east of UTC (as in Western Europe,
including the UK). Use this if the daylight is nonzero.
2 time.asctime([tupletime])
Accepts a time-tuple and returns a readable 24-character string such as 'Tue Dec
11 18:07:14 2008'.
3 time.clock( )
4 time.ctime([secs])
181
Python 3
5 time.gmtime([secs])
Accepts an instant expressed in seconds since the epoch and returns a time-tuple
t with the UTC time. Note : t.tm_isdst is always 0
6 time.localtime([secs])
Accepts an instant expressed in seconds since the epoch and returns a time-tuple
t with the local time (t.tm_isdst is 0 or 1, depending on whether DST applies to
instant secs by local rules).
7 time.mktime(tupletime)
8 time.sleep(secs)
9 time.strftime(fmt[,tupletime])
Parses str according to format string fmt and returns the instant in time-tuple
format.
11 time.time( )
Returns the current time instant, a floating-point number of seconds since the
epoch.
12 time.tzset()
Resets the time conversion rules used by the library routines. The environment
variable TZ specifies how this is done.
Description
The method altzone() is the attribute of the time module. This returns the offset of the
local DST timezone, in seconds west of UTC, if one is defined. This is negative if the local
182
Python 3
DST timezone is east of UTC (as in Western Europe, including the UK). Only use this if
daylight is nonzero.
Syntax
Following is the syntax for altzone() method-
time.altzone
Parameters
NA
Return Value
This method returns the offset of the local DST timezone, in seconds west of UTC, if one
is defined.
Example
The following example shows the usage of altzone() method.
#!/usr/bin/python3
import time
print ("time.altzone : ", time.altzone)
time.altzone : -23400
Description
The method asctime() converts a tuple or struct_time representing a time as returned by
gmtime() or localtime() to a 24-character string of the following form: 'Tue Feb 17
23:21:05 2009'.
Syntax
Following is the syntax for asctime() method-
time.asctime([t]))
Parameters
t - This is a tuple of 9 elements or struct_time representing a time as returned by gmtime()
or localtime() function.
183
Python 3
Return Value
This method returns 24-character string of the following form: 'Tue Feb 17 23:21:05
2009'.
Example
The following example shows the usage of asctime() method.
#!/usr/bin/python3
import time
t = time.localtime()
print ("asctime : ",time.asctime(t))
Description
The method clock() returns the current processor time as a floating point number
expressed in seconds on Unix. The precision depends on that of the C function of the same
name, but in any case, this is the function to use for benchmarking Python or timing
algorithms.
On Windows, this function returns wall-clock seconds elapsed since the first call to this
function, as a floating point number, based on the Win32 function
QueryPerformanceCounter.
Syntax
Following is the syntax for clock() method-
time.clock()
Parameters
NA
Return Value
This method returns the current processor time as a floating point number expressed in
seconds on Unix and in Windows it returns wall-clock seconds elapsed since the first call
to this function, as a floating point number.
Example
The following example shows the usage of clock() method.
184
Python 3
#!/usr/bin/python3
import time
def procedure():
time.sleep(2.5)
# measure process time
t0 = time.clock()
procedure()
print (time.clock() - t0, "seconds process time")
# measure wall time
t0 = time.time()
procedure()
print (time.time() - t0, "seconds wall time")
Note: Not all systems can measure the true process time. On such systems (including
Windows), clock usually measures the wall time since the program was started.
Description
The method ctime() converts a time expressed in seconds since the epoch to a string
representing local time. If secs is not provided or None, the current time as returned by
time() is used. This function is equivalent to asctime(localtime(secs)). Locale information
is not used by ctime().
Syntax
Following is the syntax for ctime() method-
time.ctime([ sec ])
Parameters
sec - These are the number of seconds to be converted into string representation.
Return Value
This method does not return any value.
185
Python 3
Example
The following example shows the usage of ctime() method.
#!/usr/bin/python3
import time
print ("ctime : ", time.ctime())
Description
The method gmtime() converts a time expressed in seconds since the epoch to a
struct_time in UTC in which the dst flag is always zero. If secs is not provided or None,
the current time as returned by time() is used.
Syntax
Following is the syntax for gmtime() method-
time.gmtime([ sec ])
Parameters
sec - These are the number of seconds to be converted into structure struct_time
representation.
Return Value
This method does not return any value.
Example
The following example shows the usage of gmtime() method.
#!/usr/bin/python3
import time
print ("gmtime :", time.gmtime(1455508609.34375))
186
Python 3
Description
The method localtime() is similar to gmtime() but it converts number of seconds to local
time. If secs is not provided or None, the current time as returned by time() is used. The
dst flag is set to 1 when DST applies to the given time.
Syntax
Following is the syntax for localtime() method-
time.localtime([ sec ])
Parameters
sec - These are the number of seconds to be converted into structure struct_time
representation.
Return Value
This method does not return any value.
Example
The following example shows the usage of localtime() method.
#!/usr/bin/python3
import time
print ("time.localtime() : %s" , time.localtime())
Description
The method mktime() is the inverse function of localtime(). Its argument is the struct_time
or full 9-tuple and it returns a floating point number, for compatibility with time().
187
Python 3
If the input value cannot be represented as a valid time, either OverflowError or ValueError
will be raised.
Syntax
Following is the syntax for mktime() method-
time.mktime(t)
Parameters
t - This is the struct_time or full 9-tuple.
Return Value
This method returns a floating point number, for compatibility with time().
Example
The following example shows the usage of mktime() method.
#!/usr/bin/python3
import time
t = (2016, 2, 15, 10, 13, 38, 1, 48, 0)
d=time.mktime(t)
print ("time.mktime(t) : %f" % d)
print ("asctime(localtime(secs)): %s" % time.asctime(time.localtime(d)))
time.mktime(t) : 1455511418.000000
asctime(localtime(secs)): Mon Feb 15 10:13:38 2016
Description
The method sleep() suspends execution for the given number of seconds. The argument
may be a floating point number to indicate a more precise sleep time.
The actual suspension time may be less than that requested because any caught signal
will terminate the sleep() following execution of that signal's catching routine.
Syntax
Following is the syntax for sleep() method-
188
Python 3
time.sleep(t)
Parameters
t - This is the number of seconds for which the execution is to be suspended.
Return Value
This method does not return any value.
Example
The following example shows the usage of sleep() method.
#!/usr/bin/python3
import time
print ("Start : %s" % time.ctime())
time.sleep( 5 )
print ("End : %s" % time.ctime())
Description
The method strftime() converts a tuple or struct_time representing a time as returned
by gmtime() or localtime() to a string as specified by the format argument.
If t is not provided, the current time as returned by localtime() is used. The format must
be a string. An exception ValueError is raised if any field in t is outside of the allowed
range.
Syntax
Following is the syntax for strftime() method-
time.strftime(format[, t])
Parameters
t - This is the time in number of seconds to be formatted.
189
Python 3
format - This is the directive which would be used to format given time.
Directive
%a - abbreviated weekday name
%A - full weekday name
%b - abbreviated month name
%B - full month name
%c - preferred date and time representation
%C - century number (the year divided by 100, range 00 to 99)
%d - day of the month (01 to 31)
%D - same as %m/%d/%y
%e - day of the month (1 to 31)
%g - like %G, but without the century
%G - 4-digit year corresponding to the ISO week number (see %V).
%h - same as %b
%H - hour, using a 24-hour clock (00 to 23)
%I - hour, using a 12-hour clock (01 to 12)
%j - day of the year (001 to 366)
%m - month (01 to 12)
%M - minute
%n - newline character
%p - either am or pm according to the given time value
%r - time in a.m. and p.m. notation
%R - time in 24 hour notation
%S - second
%t - tab character
%T - current time, equal to %H:%M:%S
%u - weekday as a number (1 to 7), Monday=1. Warning: In Sun Solaris Sunday=1
%U - week number of the current year, starting with the first Sunday as the first
day of the first week
190
Python 3
%V - The ISO 8601 week number of the current year (01 to 53), where week 1 is
the first week that has at least 4 days in the current year, and with Monday as the
first day of the week
%W - week number of the current year, starting with the first Monday as the first
day of the first week
Return Value
This method does not return any value.
Example
The following example shows the usage of strftime() method.
#!/usr/bin/python3
import time
t = (2015, 12, 31, 10, 39, 45, 1, 48, 0)
t = time.mktime(t)
print (time.strftime("%b %d %Y %H:%M:%S", time.localtime(t)))
Description
The method strptime() parses a string representing a time according to a format. The
return value is a struct_time as returned by gmtime() or localtime().
The format parameter uses the same directives as those used by strftime(); it defaults to
"%a %b %d %H:%M:%S %Y" which matches the formatting returned by ctime().
If string cannot be parsed according to format, or if it has excess data after parsing,
ValueError is raised.
Syntax
191
Python 3
time.strptime(string[, format])
Parameters
string - This is the time in string format which would be parsed based on the given
format.
format - This is the directive which would be used to parse the given string.
Directive
The following directives can be embedded in the format string-
%V - The ISO 8601 week number of the current year (01 to 53), where week 1 is
the first week that has at least 4 days in the current year, and with Monday as the
first day of the week
%W - week number of the current year, starting with the first Monday as the first
day of the first week
Return Value
This return value is struct_time as returned by gmtime() or localtime().
Example
The following example shows the usage of strptime() method.
#!/usr/bin/python3
import time
struct_time = time.strptime("30 12 2015", "%d %m %Y")
print ("tuple : ", struct_time)
Description
The method time() returns the time as a floating point number expressed in seconds since
the epoch, in UTC.
Note: Even though the time is always returned as a floating point number, not all systems
provide time with a better precision than 1 second. While this function normally returns
non-decreasing values, it can return a lower value than a previous call if the system clock
has been set back between the two calls.
Syntax
193
Python 3
time.time()
Parameters
NA
Return Value
This method returns the time as a floating point number expressed in seconds since the
epoch, in UTC.
Example
The following example shows the usage of time() method.
#!/usr/bin/python3
import time
print ("time.time(): %f " % time.time())
print (time.localtime( time.time() ))
print (time.asctime( time.localtime(time.time()) ))
time.time(): 1455519806.011433
time.struct_time(tm_year=2016, tm_mon=2, tm_mday=15, tm_hour=12, tm_min=33,
tm_sec=26, tm_wday=0, tm_yday=46, tm_isdst=0)
Mon Feb 15 12:33:26 2016
Description
The method tzset() resets the time conversion rules used by the library routines. The
environment variable TZ specifies how this is done.
The standard format of the TZ environment variable is (whitespace added for clarity)-
std and dst: Three or more alphanumerics giving the timezone abbreviations. These
will be propagated into time.tzname.
offset: The offset has the form: .hh[:mm[:ss]]. This indicates the value added the
local time to arrive at UTC. If preceded by a '-', the timezone is east of the Prime
Meridian; otherwise, it is west. If no offset follows dst, summer time is assumed to
be one hour ahead of standard time.
194
Python 3
start[/time], end[/time]: Indicates when to change to and back from DST. The
format of the start and end dates are one of the following:
o Jn: The Julian day n (1 <= n <= 365). Leap days are not counted, so in all years
February 28 is day 59 and March 1 is day 60.
o n: The zero-based Julian day (0 <= n <= 365). Leap days are counted, and it is
possible to refer to February 29.
o Mm.n.d: The d'th day (0 <= d <= 6) or week n of month m of the year (1 <= n
<= 5, 1 <= m <= 12, where week 5 means 'the last d day in month m' which
may occur in either the fourth or the fifth week). Week 1 is the first week in which
the d'th day occurs. Day zero is Sunday.
o time: This has the same format as offset except that no leading sign ('-' or '+')
is allowed. The default, if time is not given, is 02:00:00.
Syntax
Following is the syntax for tzset() method-
time.tzset()
Parameters
NA
Return Value
This method does not return any value.
Example
The following example shows the usage of tzset() method.
#!/usr/bin/python3
import time
import os
os.environ['TZ'] = 'EST+05EDT,M4.1.0,M10.5.0'
time.tzset()
print time.strftime('%X %x %Z')
os.environ['TZ'] = 'AEST-10AEDT-11,M10.5.0,M3.5.0'
time.tzset()
print time.strftime('%X %x %Z')
195
Python 3
There are two important attributes available with time module. They are-
1 time.timezone
Attribute time.timezone is the offset in seconds of the local time zone (without
DST) from UTC (>0 in the Americas; <=0 in most of Europe, Asia, Africa).
2 time.tzname
By default, calendar takes Monday as the first day of the week and Sunday as the last
one. To change this, call the calendar.setfirstweekday() function.
1 calendar.calendar(year,w=2,l=1,c=6)
Returns a multiline string with a calendar for year year formatted into three
columns separated by c spaces. w is the width in characters of each date; each
line has length 21*w+18+2*c. l is the number of lines for each week.
196
Python 3
2 calendar.firstweekday( )
Returns the current setting for the weekday that starts each week. By default,
when calendar is first imported, this is 0, meaning Monday.
3 calendar.isleap(year)
4 calendar.leapdays(y1,y2)
Returns the total number of leap days in the years within range(y1,y2).
5 calendar.month(year,month,w=2,l=1)
Returns a multiline string with a calendar for month month of year year, one line
per week plus two header lines. w is the width in characters of each date; each
line has length 7*w+6. l is the number of lines for each week.
6 calendar.monthcalendar(year,month)
Returns a list of lists of ints. Each sublist denotes a week. Days outside month
month of year year are set to 0; days within the month are set to their day-of-
month, 1 and up.
7 calendar.monthrange(year,month)
Returns two integers. The first one is the code of the weekday for the first day of
the month month in year year; the second one is the number of days in the month.
Weekday codes are 0 (Monday) to 6 (Sunday); month numbers are 1 to 12.
8 calendar.prcal(year,w=2,l=1,c=6)
9 calendar.prmonth(year,month,w=2,l=1)
10 calendar.setfirstweekday(weekday)
Sets the first day of each week to weekday code weekday. Weekday codes are 0
(Monday) to 6 (Sunday).
11 calendar.timegm(tupletime)
The inverse of time.gmtime: accepts a time instant in time-tuple form and returns
the same instant as a floating-point number of seconds since the epoch.
197
Python 3
12 calendar.weekday(year,month,day)
Returns the weekday code for the given date. Weekday codes are 0 (Monday) to
6 (Sunday); month numbers are 1 (January) to 12 (December).
198
15. Python 3 – Functions Python 3
A function is a block of organized, reusable code that is used to perform a single, related
action. Functions provide better modularity for your application and a high degree of code
reusing.
As you already know, Python gives you many built-in functions like print(), etc. but you
can also create your own functions. These functions are called user-defined functions.
Defining a Function
You can define functions to provide the required functionality. Here are simple rules to
define a function in Python.
Function blocks begin with the keyword def followed by the function name and
parentheses ( ( ) ).
The code block within every function starts with a colon (:) and is indented.
Syntax
def functionname( parameters ):
"function_docstring"
function_suite
return [expression]
By default, parameters have a positional behavior and you need to inform them in the
same order that they were defined.
Example
The following function takes a string as input parameter and prints it on the standard
screen.
return
Calling a Function
Defining a function gives it a name, specifies the parameters that are to be included in the
function and structures the blocks of code.
Once the basic structure of a function is finalized, you can execute it by calling it from
another function or directly from the Python prompt. Following is an example to call the
printme() function-
#!/usr/bin/python3
#!/usr/bin/python3
200
Python 3
return
# Now you can call changeme function
mylist = [10,20,30]
changeme( mylist )
print ("Values outside the function: ", mylist)
Here, we are maintaining reference of the passed object and appending values in the same
object. Therefore, this would produce the following result-
There is one more example where argument is being passed by reference and the
reference is being overwritten inside the called function.
#!/usr/bin/python3
The parameter mylist is local to the function changeme. Changing mylist within the
function does not affect mylist. The function accomplishes nothing and finally this would
produce the following result-
201
Python 3
Function Arguments
You can call a function by using the following types of formal arguments-
Required arguments
Keyword arguments
Default arguments
Variable-length arguments
Required Arguments
Required arguments are the arguments passed to a function in correct positional order.
Here, the number of arguments in the function call should match exactly with the function
definition.
To call the function printme(), you definitely need to pass one argument, otherwise it gives
a syntax error as follows-
#!/usr/bin/python3
# Function definition is here
def printme( str ):
"This prints a passed string into this function"
print (str)
return
# Now you can call printme function
printme()
printme()
TypeError: printme() missing 1 required positional argument: 'str'
Keyword Arguments
Keyword arguments are related to the function calls. When you use keyword arguments
in a function call, the caller identifies the arguments by the parameter name.
This allows you to skip arguments or place them out of order because the Python
interpreter is able to use the keywords provided to match the values with parameters. You
can also make keyword calls to the printme() function in the following ways-
#!/usr/bin/python3
My string
The following example gives a clearer picture. Note that the order of parameters does not
matter.
#!/usr/bin/python3
Name: miki
Age 50
Default Arguments
A default argument is an argument that assumes a default value if a value is not provided
in the function call for that argument. The following example gives an idea on default
arguments, it prints default age if it is not passed.
#!/usr/bin/python3
203
Python 3
Name: miki
Age 50
Name: miki
Age 35
Variable-length Arguments
You may need to process a function for more arguments than you specified while defining
the function. These arguments are called variable-length arguments and are not named in
the function definition, unlike required and default arguments.
An asterisk (*) is placed before the variable name that holds the values of all nonkeyword
variable arguments. This tuple remains empty if no additional arguments are specified
during the function call. Following is a simple example-
#!/usr/bin/python3
204
Python 3
Output is:
10
Output is:
70
60
50
Lambda forms can take any number of arguments but return just one value in the
form of an expression. They cannot contain commands or multiple expressions.
Lambda functions have their own local namespace and cannot access variables
other than those in their parameter list and those in the global namespace.
Although it appears that lambdas are a one-line version of a function, they are not
equivalent to inline statements in C or C++, whose purpose is to stack allocation
by passing function, during invocation for performance reasons.
Syntax
The syntax of lambda function contains only a single statement, which is as follows-
#!/usr/bin/python3
Value of total : 30
Value of total : 40
All the examples given above are not returning any value. You can return a value from a
function as follows-
#!/usr/bin/python3
Scope of Variables
All variables in a program may not be accessible at all locations in that program. This
depends on where you have declared a variable.
The scope of a variable determines the portion of the program where you can access a
particular identifier. There are two basic scopes of variables in Python-
Global variables
Local variables
206
Python 3
This means that local variables can be accessed only inside the function in which they are
declared, whereas global variables can be accessed throughout the program body by all
functions. When you call a function, the variables declared inside it are brought into scope.
Following is a simple example-
#!/usr/bin/python3
207
16. Python 3 – Modules Python 3
A module allows you to logically organize your Python code. Grouping related code into a
module makes the code easier to understand and use. A module is a Python object with
arbitrarily named attributes that you can bind and reference.
Simply, a module is a file consisting of Python code. A module can define functions, classes
and variables. A module can also include runnable code.
Example
The Python code for a module named aname normally resides in a file namedaname.py.
Here is an example of a simple module, support.py-
When the interpreter encounters an import statement, it imports the module if the module
is present in the search path. A search path is a list of directories that the interpreter
searches before importing a module. For example, to import the module hello.py, you
need to put the following command at the top of the script-
#!/usr/bin/python3
# Import module support
import support
# Now you can call defined function that module as follows
support.print_func("Zara")
Hello : Zara
A module is loaded only once, regardless of the number of times it is imported. This
prevents the module execution from happening repeatedly, if multiple imports occur.
208
Python 3
For example, to import the function fibonacci from the module fib, use the following
statement-
#!/usr/bin/python3
This statement does not import the entire module fib into the current namespace; it just
introduces the item fibonacci from the module fib into the global symbol table of the
importing module.
This provides an easy way to import all the items from a module into the current
namespace; however, this statement should be used sparingly.
209
Python 3
#!/usr/bin/python3
When you run the above code, the following output will be displayed.
Locating Modules
When you import a module, the Python interpreter searches for the module in the following
sequences-
If the module is not found, Python then searches each directory in the shell variable
PYTHONPATH.
If all else fails, Python checks the default path. On UNIX, this default path is
normally /usr/local/lib/python3/.
The module search path is stored in the system module sys as the sys.path variable. The
sys.path variable contains the current directory, PYTHONPATH, and the installation-
dependent default.
210
Python 3
set PYTHONPATH=c:\python34\lib;
set PYTHONPATH=/usr/local/lib/python
A Python statement can access variables in a local namespace and in the global
namespace. If a local and a global variable have the same name, the local variable
shadows the global variable.
Each function has its own local namespace. Class methods follow the same scoping
rule as ordinary functions.
Therefore, in order to assign a value to a global variable within a function, you must
first use the global statement.
The statement global VarName tells Python that VarName is a global variable.
Python stops searching the local namespace for the variable.
For example, we define a variable Money in the global namespace. Within the
function Money, we assign Money a value, therefore Python assumes Money as a local
variable.
However, we accessed the value of the local variable Money before setting it, so an
UnboundLocalError is the result. Uncommenting the global statement fixes the problem.
#!/usr/bin/python3
Money = 2000
def AddMoney():
# Uncomment the following line to fix the code:
# global Money
Money = Money + 1
print (Money)
AddMoney()
print (Money)
211
Python 3
The list contains the names of all the modules, variables and functions that are defined in
a module. Following is a simple example-
#!/usr/bin/python3
# Import built-in module math
import math
content = dir(math)
print (content)
Here, the special string variable __name__ is the module's name, and __file__is the
filename from which the module was loaded.
If locals() is called from within a function, it will return all the names that can be
accessed locally from that function.
If globals() is called from within a function, it will return all the names that can
be accessed globally from that function.
The return type of both these functions is dictionary. Therefore, names can be extracted
using the keys() function.
Therefore, if you want to reexecute the top-level code in a module, you can use
the reload() function. The reload() function imports a previously imported module again.
The syntax of the reload() function is this-
212
Python 3
reload(module_name)
Here, module_name is the name of the module you want to reload and not the string
containing the module name. For example, to reload hello module, do the following-
reload(hello)
Packages in Python
A package is a hierarchical file directory structure that defines a single Python application
environment that consists of modules and subpackages and sub-subpackages, and so on.
Consider a file Pots.py available in Phone directory. This file has the following line of
source code-
#!/usr/bin/python3
def Pots():
print ("I'm Pots Phone")
Similarly, we have other two files having different functions with the same name as above.
They are −
Phone/__init__.py
To make all of your functions available when you have imported Phone, you need to put
explicit import statements in __init__.py as follows-
After you add these lines to __init__.py, you have all of these classes available when you
import the Phone package.
#!/usr/bin/python3
# Now import your Phone Package.
import Phone
Phone.Pots()
Phone.Isdn()
Phone.G3()
213
Python 3
In the above example, we have taken example of a single function in each file, but you
can keep multiple functions in your files. You can also define different Python classes in
those files and then you can create your packages out of those classes.
214
17. Python 3 – Files I/O Python 3
This chapter covers all the basic I/O functions available in Python 3. For more functions,
please refer to the standard Python documentation.
#!/usr/bin/python3
print ("Python is really a great language,", "isn't it?")
#!/usr/bin/python3
>>> x=input("something:")
something:10
>>> x
'10'
>>> x=input("something:")
something:'10' #entered data treated as string with or without ''
>>> x
"'10'"
215
Python 3
Python provides basic functions and methods necessary to manipulate files by default. You
can do most of the file manipulation using a file object.
Syntax
file object = open(file_name [, access_mode][, buffering])
file_name: The file_name argument is a string value that contains the name of
the file that you want to access.
access_mode: The access_mode determines the mode in which the file has to be
opened, i.e., read, write, append, etc. A complete list of possible values is given
below in the table. This is an optional parameter and the default file access mode
is read (r).
Modes Description
r Opens a file for reading only. The file pointer is placed at the beginning of the
file. This is the default mode.
rb Opens a file for reading only in binary format. The file pointer is placed at the
beginning of the file. This is the default mode.
r+ Opens a file for both reading and writing. The file pointer placed at the
beginning of the file.
216
Python 3
rb+ Opens a file for both reading and writing in binary format. The file pointer
placed at the beginning of the file.
w Opens a file for writing only. Overwrites the file if the file exists. If the file
does not exist, creates a new file for writing.
wb Opens a file for writing only in binary format. Overwrites the file if the file
exists. If the file does not exist, creates a new file for writing.
w+ Opens a file for both writing and reading. Overwrites the existing file if the file
exists. If the file does not exist, creates a new file for reading and writing.
wb+ Opens a file for both writing and reading in binary format. Overwrites the
existing file if the file exists. If the file does not exist, creates a new file for
reading and writing.
a Opens a file for appending. The file pointer is at the end of the file if the file
exists. That is, the file is in the append mode. If the file does not exist, it
creates a new file for writing.
ab Opens a file for appending in binary format. The file pointer is at the end of
the file if the file exists. That is, the file is in the append mode. If the file does
not exist, it creates a new file for writing.
a+ Opens a file for both appending and reading. The file pointer is at the end of
the file if the file exists. The file opens in the append mode. If the file does
not exist, it creates a new file for reading and writing.
ab+ Opens a file for both appending and reading in binary format. The file pointer
is at the end of the file if the file exists. The file opens in the append mode. If
the file does not exist, it creates a new file for reading and writing.
Attribute Description
217
Python 3
Example
#!/usr/bin/python3
# Open a file
fo = open("foo.txt", "wb")
print ("Name of the file: ", fo.name)
print ("Closed or not : ", fo.closed)
print ("Opening mode : ", fo.mode)
fo.close()
Python automatically closes a file when the reference object of a file is reassigned to
another file. It is a good practice to use the close() method to close a file.
Syntax
fileObject.close();
Example
#!/usr/bin/python3
# Open a file
fo = open("foo.txt", "wb")
print ("Name of the file: ", fo.name)
218
Python 3
The write() method does not add a newline character ('\n') to the end of the string-
Syntax
fileObject.write(string);
Here, passed parameter is the content to be written into the opened file.
Example
#!/usr/bin/python3
# Open a file
fo = open("foo.txt", "w")
fo.write( "Python is a great language.\nYeah its great!!\n")
The above method would create foo.txt file and would write given content in that file and
finally it would close that file. If you would open this file, it would have the following
content-
219
Python 3
Syntax
fileObject.read([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 us take a file foo.txt, which we created above.
#!/usr/bin/python3
# Open a file
fo = open("foo.txt", "r+")
str = fo.read(10)
print ("Read String is : ", str)
# Close opened file
fo.close()
File Positions
The tell() method tells you the current position within the file; in other words, the next
read or write will occur at that many bytes from the beginning of the file.
The seek(offset[, from]) method changes the current file position. The 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, the beginning of the file is used as the reference position. If it is set to
1, the current position is used as the reference position. If it is set to 2 then the end of
the file would be taken as the reference position.
Example
Let us take a file foo.txt, which we created above.
#!/usr/bin/python3
220
Python 3
# Open a file
fo = open("foo.txt", "r+")
str = fo.read(10)
print ("Read String is : ", str)
To use this module, you need to import it first and then you can call any related functions.
Syntax
os.rename(current_file_name, new_file_name)
Example
Following is an example to rename an existing file test1.txt-
#!/usr/bin/python3
import os
221
Python 3
Syntax
os.remove(file_name)
Example
Following is an example to delete an existing file test2.txt-
#!/usr/bin/python3
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.
Syntax
os.mkdir("newdir")
Example
Following is an example to create a directory test in the current directory-
#!/usr/bin/python3
import os
222
Python 3
Syntax
os.chdir("newdir")
Example
Following is an example to go into "/home/newdir" directory-
#!/usr/bin/python3
import os
Syntax
os.getcwd()
Example
Following is an example to give current directory-
#!/usr/bin/python3
import os
223
Python 3
Syntax
os.rmdir('dirname')
Example
Following is an example to remove the "/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/python3
import os
File Object Methods: The file object provides functions to manipulate files.
OS Object Methods: This provides methods to process files as well as directories.
File Methods
A file object is created using open function and here is a list of functions which can be
called on this object.
S.
Methods with Description
No.
1 file.close()
Close the file. A closed file cannot be read or written any more.
2 file.flush()
224
Python 3
Flush the internal buffer, like stdio's fflush. This may be a no-op on some file-like
objects.
3 file.fileno()
Returns the integer file descriptor that is used by the underlying implementation
to request I/O operations from the operating system.
4 file.isatty()
5 next(file)
Returns the next line from the file each time it is being called.
6 file.read([size])
Reads at most size bytes from the file (less if the read hits EOF before obtaining
size bytes).
7 file.readline([size])
Reads one entire line from the file. A trailing newline character is kept in the
string.
8 file.readlines([sizehint])
Reads until EOF using readline() and return a list containing the lines. If the
optional sizehint argument is present, instead of reading up to EOF, whole lines
totalling approximately sizehint bytes (possibly after rounding up to an internal
buffer size) are read.
9 file.seek(offset[, whence])
10 file.tell()
11 file.truncate([size])
Truncates the file's size. If the optional size argument is present, the file is
truncated to (at most) that size.
12 file.write(str)
225
Python 3
13 file.writelines(sequence)
Writes a sequence of strings to the file. The sequence can be any iterable object
producing strings, typically a list of strings.
Description
The method close() closes the opened file. A closed file cannot be read or written any
more. Any operation, which requires that the file be opened will raise a ValueError after
the file has been closed. Calling close() more than once is allowed.
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
Following is the syntax for close() method-
fileObject.close()
Parameters
NA
Return Value
This method does not return any value.
Example
The following example shows the usage of close() method.
#!/usr/bin/python3
# Open a file
fo = open("foo.txt", "wb")
print ("Name of the file: ", fo.name)
# Close opened file
fo.close()
226
Python 3
Description
The method flush() flushes the internal buffer, like stdio's fflush. This may be a no-op on
some file-like objects.
Python automatically flushes the files when closing them. But you may want to flush the
data before closing any file.
Syntax
Following is the syntax for flush() method-
fileObject.flush()
Parameters
NA
Return Value
This method does not return any value.
Example
The following example shows the usage of flush() method.
#!/usr/bin/python3
# Open a file
fo = open("foo.txt", "wb")
print ("Name of the file: ", fo.name)
# Here it does nothing, but you can call it with read operation.
fo.flush()
# Close opend file
fo.close()
227
Python 3
Description
The method fileno() returns the integer file descriptor that is used by the underlying
implementation to request I/O operations from the operating system.
Syntax
Following is the syntax for fileno() method-
fileObject.fileno()
Parameters
NA
Return Value
This method returns the integer file descriptor.
Example
The following example shows the usage of fileno() method.
#!/usr/bin/python3
# Open a file
fo = open("foo.txt", "wb")
print ("Name of the file: ", fo.name)
fid = fo.fileno()
print ("File Descriptor: ", fid)
# Close opend file
fo.close()
Description
The method isatty() returns True if the file is connected (is associated with a terminal
device) to a tty(-like) device, else False.
228
Python 3
Syntax
Following is the syntax for isatty() method-
fileObject.isatty()
Parameters
NA
Return Value
This method returns true if the file is connected (is associated with a terminal device) to
a tty(-like) device, else false.
Example
The following example shows the usage of isatty() method-
#!/usr/bin/python3
# Open a file
fo = open("foo.txt", "wb")
print ("Name of the file: ", fo.name)
ret = fo.isatty()
print ("Return value : ", ret)
# Close opend file
fo.close()
Description
File object in Python 3 does not support next() method. Python 3 has a built-in function
next() which retrieves the next item from the iterator by calling its __next__() method. If
default is given, it is returned if the iterator is exhausted, otherwise StopIteration is raised.
This method can be used to read the next input line, from the file object.
Syntax
Following is the syntax for next() method-
229
Python 3
next(iterator[,default])
Parameters
iterator : file object from which lines are to be read
Return Value
This method returns the next input line.
Example
The following example shows the usage of next() method-
#!/usr/bin/python3
# Open a file
fo = open("foo.txt", "r")
print ("Name of the file: ", fo.name)
for index in range(5):
line = next(fo)
print ("Line No %d - %s" % (index, line))
# Close opened file
fo.close()
230
Python 3
Description
The method read() reads at most size bytes from the file. If the read hits EOF before
obtaining size bytes, then it reads only available bytes.
Syntax
Following is the syntax for read() method-
fileObject.read( size );
Parameters
size - This is the number of bytes to be read from the file.
Return Value
This method returns the bytes read in string.
Example
The following example shows the usage of read() method.
#!/usr/bin/python3
# Open a file
fo = open("foo.txt", "r+")
print ("Name of the file: ", fo.name)
line = fo.read(10)
print ("Read Line: %s" % (line))
# Close opened file
fo.close()
231
Python 3
Description
The method readline()reads one entire line from the file. A trailing newline character is
kept in the string. If the size argument is present and non-negative, it is a maximum byte
count including the trailing newline and an incomplete line may be returned.
Syntax
Following is the syntax for readline() method-
fileObject.readline( size );
Parameters
size - This is the number of bytes to be read from the file.
Return Value
This method returns the line read from the file.
Example
The following example shows the usage of readline() method.
#!/usr/bin/python3
# Open a file
fo = open("foo.txt", "r+")
print ("Name of the file: ", fo.name)
line = fo.readline()
print ("Read Line: %s" % (line))
line = fo.readline(5)
232
Python 3
Description
The method readlines() reads until EOF using readline() and returns a list containing the
lines. If the optional sizehint argument is present, instead of reading up to EOF, whole
lines totalling approximately sizehint bytes (possibly after rounding up to an internal buffer
size) are read.
Syntax
Following is the syntax for readlines() method-
fileObject.readlines( sizehint );
Parameters
sizehint - This is the number of bytes to be read from the file.
Return Value
This method returns a list containing the lines.
Example
The following example shows the usage of readlines() method.
233
Python 3
#!/usr/bin/python3
# Open a file
fo = open("foo.txt", "r+")
print ("Name of the file: ", fo.name)
line = fo.readlines()
print ("Read Line: %s" % (line))
line = fo.readlines(2)
print ("Read Line: %s" % (line))
# Close opened file
fo.close()
Description
The method seek() sets the file's current position at the offset. The whence argument is
optional and defaults to 0, which means absolute file positioning, other values are 1 which
means seek relative to the current position and 2 means seek relative to the file's end.
There is no return value. Note that if the file is opened for appending using either 'a' or
'a+', any seek() operations will be undone at the next write.
If the file is only opened for writing in append mode using 'a', this method is essentially a
no-op, but it remains useful for files opened in append mode with reading enabled (mode
'a+').
If the file is opened in text mode using 't', only offsets returned by tell() are legal. Use of
other offsets causes undefined behavior.
Syntax
Following is the syntax for seek() method-
fileObject.seek(offset[, whence])
234
Python 3
Parameters
offset- This is the position of the read/write pointer within the file.
whence- This is optional and defaults to 0 which means absolute file positioning,
other values are 1 which means seek relative to the current position and 2 means
seek relative to the file's end.
Return Value
This method does not return any value.
Example
The following example shows the usage of seek() method.
#!/usr/bin/python3
# Open a file
fo = open("foo.txt", "rw+")
print ("Name of the file: ", fo.name)
line = fo.readlines()
print ("Read Line: %s" % (line))
Description
The method tell() returns the current position of the file read/write pointer within the file.
Syntax
Following is the syntax for tell() method-
fileObject.tell()
Parameters
NA
Return Value
This method returns the current position of the file read/write pointer within the file.
Example
The following example shows the usage of tell() method-
#!/usr/bin/python3
fo = open("foo.txt", "r+")
print ("Name of the file: ", fo.name)
line = fo.readline()
print ("Read Line: %s" % (line))
pos=fo.tell()
print ("current position : ",pos)
236
Python 3
Current Position: 18
Description
The method truncate() truncates the file's size. If the optional size argument is present,
the file is truncated to (at most) that size.
The size defaults to the current position. The current file position is not changed. Note that
if a specified size exceeds the file's current size, the result is platform-dependent.
Note: This method will not work in case the file is opened in read-only mode.
Syntax
Following is the syntax for truncate() method-
fileObject.truncate( [ size ])
Parameters
size - If this optional argument is present, the file is truncated to (at most) that size.
Return Value
This method does not return any value.
Example
The following example shows the usage of truncate() method.
237
Python 3
#!/usr/bin/python3
fo = open("foo.txt", "r+")
print ("Name of the file: ", fo.name)
line = fo.readline()
print ("Read Line: %s" % (line))
fo.truncate()
line = fo.readlines()
print ("Read Line: %s" % (line))
Description
The method write() writes a string str to the file. There is no return value. Due to
buffering, the string may not actually show up in the file until the flush() or close() method
is called.
Syntax
Following is the syntax for write() method-
fileObject.write( str )
Parameters
str - This is the String to be written in the file.
Return Value
This method does not return any value.
238
Python 3
Example
The following example shows the usage of write() method.
#!/usr/bin/python3
# Open a file in read/write mode
fo = open("abc.txt", "r+")
print ("Name of the file: ", fo.name)
str = "This is 6th line"
# Write a line at the end of the file.
fo.seek(0, 2)
line = fo.write( str )
# Now read complete file from beginning.
fo.seek(0,0)
for index in range(6):
line = next(fo)
print ("Line No %d - %s" % (index, line))
239
Python 3
Description
The method writelines() writes a sequence of strings to the file. The sequence can be
any iterable object producing strings, typically a list of strings. There is no return value.
Syntax
Following is the syntax for writelines() method −
fileObject.writelines( sequence )
Parameters
sequence - This is the Sequence of the strings.
Return Value
This method does not return any value.
Example
The following example shows the usage of writelines() method.
#!/usr/bin/python3
# Open a file in read/write mode
fo = open("abc.txt", "r+")
print ("Name of the file: ", fo.name)
seq = ["This is 6th line\n", "This is 7th line"]
# Write sequence of lines at the end of the file.
fo.seek(0, 2)
line = fo.writelines( seq )
240
Python 3
OS File/Directory Methods
The os module provides a big range of useful methods to manipulate files and directories.
Most of the useful methods are listed here:
S.
Methods with Description
No.
1 os.access(path, mode)
241
Python 3
2 os.chdir(path)
3 os.chflags(path, flags)
4 os.chmod(path, mode)
Change the owner and group id of path to the numeric uid and gid.
6 os.chroot(path)
7 os.close(fd)
8 os.closerange(fd_low, fd_high)
Close all file descriptors from fd_low (inclusive) to fd_high (exclusive), ignoring
errors.
9 os.dup(fd)
10 os.dup2(fd, fd2)
11 os.fchdir(fd)
242
Python 3
Change the current working directory to the directory represented by the file
descriptor fd.
12 os.fchmod(fd, mode)
Change the owner and group id of the file given by fd to the numeric uid and
gid.
14 os.fdatasync(fd)
16 os.fpathconf(fd, name)
17 os.fstat(fd)
18 os.fstatvfs(fd)
Return information about the filesystem containing the file associated with file
descriptor fd, like statvfs().
19 os.fsync(fd)
20 os.ftruncate(fd, length)
243
Python 3
Truncate the file corresponding to file descriptor fd, so that it is at most length
bytes in size.
21 os.getcwd()
22 os.getcwdu()
23 os.isatty(fd)
Return True if the file descriptor fd is open and connected to a tty(-like) device,
else False.
24 os.lchflags(path, flags)
Set the flags of path to the numeric flags, like chflags(), but do not follow
symbolic links.
25 os.lchmod(path, mode)
Change the owner and group id of path to the numeric uid and gid. This function
will not follow symbolic links.
27 os.link(src, dst)
28 os.listdir(path)
Return a list containing the names of the entries in the directory given by path.
244
Python 3
Set the current position of file descriptor fd to position pos, modified by how.
30 os.lstat(path)
31 os.major(device)
32 os.makedev(major, minor)
Compose a raw device number from the major and minor device numbers.
33 os.makedirs(path[, mode])
34 os.minor(device)
35 os.mkdir(path[, mode])
36 os.mkfifo(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.
245
Python 3
Open the file file and set various flags according to flags and possibly its mode
according to mode.
39 os.openpty()
40 os.pathconf(path, name)
41 os.pipe()
Create a pipe. Return a pair of file descriptors (r, w) usable for reading and
writing, respectively.
43 os.read(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 os.readlink(path)
Return a string representing the path to which the symbolic link points.
45 os.remove(path)
46 os.removedirs(path)
246
Python 3
47 os.rename(src, dst)
48 os.renames(old, new)
49 os.rmdir(path)
50 os.stat(path)
51 os.stat_float_times([newvalue])
52 os.statvfs(path)
53 os.symlink(src, dst)
54 os.tcgetpgrp(fd)
Return the process group associated with the terminal given by fd (an open file
descriptor as returned by open()).
55 os.tcsetpgrp(fd, pg)
Set the process group associated with the terminal given by fd (an open file
descriptor as returned by open()) to pg.
56 os.tempnam([dir[, prefix]])
247
Python 3
Return a unique path name that is reasonable for creating a temporary file.
57 os.tmpfile()
58 os.tmpnam()
Return a unique path name that is reasonable for creating a temporary file.
59 os.ttyname(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 os.unlink(path)
61 os.utime(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 os.write(fd, str)
Write the string str to file descriptor fd. Return the number of bytes actually
written.
os.access() Method
Description
248
Python 3
The method access() uses the real uid/gid to test for access to path. Most operations will
use the effective uid/gid, therefore this routine can be used in a suid/sgid environment to
test if the invoking user has the specified access to path.It returns True if access is allowed,
False if not.
Syntax
Following is the syntax for access() method-
os.access(path, mode)
Parameters
path - This is the path which would be tested for existence or any access.
mode - This should be F_OK to test the existence of path, or it can be the inclusive
OR of one or more of R_OK, W_OK, and X_OK to test permissions.
o os.F_OK: Value to pass as the mode parameter of access() to test the existence
of path.
Return Value
This method returns True if access is allowed, False if not.
Example
The following example shows the usage of access() method.
#!/usr/bin/python3
import os, sys
# Assuming /tmp/foo.txt exists and has read/write permissions.
ret = os.access("/tmp/foo.txt", os.F_OK)
print ("F_OK - return value %s"% ret)
249
Python 3
os.chdir() Method
Description
The method chdir() changes the current working directory to the given path.It returns
None in all the cases.
Syntax
Following is the syntax for chdir() method-
os.chdir(path)
Parameters
path - This is complete path of the directory to be changed to a new location.
Return Value
This method does not return any value. It throws FileNotFoundError if the specified path
is not found.
Example
The following example shows the usage of chdir() method.
#!/usr/bin/python3
import os
path = "d:\\python3" #change path for linux
# Now change the directory
os.chdir( path )
# Check current working directory.
250
Python 3
retval = os.getcwd()
print ("Directory changed successfully %s" % retval)
os.chflags() Method
Description
The method chflags() sets the flags of path to the numeric flags. The flags may take a
combination (bitwise OR) of the various values described below.
Note: This method is available Python version 2.6 onwards. Most of the flags can be
changed by super-user only.
Syntax
Following is the syntax for chflags() method-
os.chflags(path, flags)
Parameters
path - This is a complete path of the directory to be changed to a new location.
flags - The flags specified are formed by OR'ing the following values-
Return Value
This method does not return any value.
Example
251
Python 3
#!/usr/bin/python3
import os
path = "/tmp/foo.txt"
# Set a flag so that file may not be renamed or deleted.
flags = os.SF_NOUNLINK
retval = os.chflags( path, flags)
print ("Return Value: %s" % retval)
os.chmod() Method
Description
The method chmod() changes the mode of path to the passed numeric mode. The mode
may take one of the following values or bitwise ORed combinations of them-
252
Python 3
Syntax
Following is the syntax for chmod() method-
os.chmod(path, mode)
Parameters
path - This is the path for which mode would be set.
mode - This may take one of the above mentioned values or bitwise ORed
combinations of them.
Return Value
This method does not return any value.
Note : Although Windows supports chmod(), you can only set the file’s read-only flag with
it (via the stat.S_IWRITE and stat.S_IREAD constants or a corresponding integer value).
All other bits are ignored.
Example
The following example shows the usage of chmod() method-
#!/usr/bin/python3
import os, sys, stat
os.chmod("/tmp/foo.txt", stat.S_IXGRP)
253
Python 3
os.chown() Method
Description
The method chown() changes the owner and group id of path to the numeric uid and gid.
To leave one of the ids unchanged, set it to -1.To set ownership, you would need super
user privilege..
Syntax
Following is the syntax for chown() method-
Parameters
path - This is the path for which owner id and group id need to be setup.
Return Value
This method does not return any value.
Example
The following example shows the usage of chown() method.
#!/usr/bin/python3
import os, sys
# Assuming /tmp/foo.txt exists.
# To set owner ID 100 following has to be done.
os.chown("/tmp/foo.txt", 100, -1)
print ("Changed ownership successfully!!")
254
Python 3
os.chroot() Method
Description
The method chroot() changes the root directory of the current process to the given path.
Available on Unix like systems only. To use this method, you would need super user
privilege.
Syntax
Following is the syntax for chroot() method-
os.chroot(path)
Parameters
path - This is the path which would be set as root for the current process.
Return Value
This method does not return any value.
Example
The following example shows the usage of chroot() method.
#!/usr/bin/python3
import os, sys
# To set the current root path to /tmp/user
os.chroot("/tmp/usr")
print ("Changed root path successfully!!")
Description
The method close() closes the associated with file descriptor fd.
Syntax
Following is the syntax for close() method-
os.close(fd)
255
Python 3
Parameters
fd - This is the file descriptor of the file.
Return Value
This method does not return any value.
Note: This function is intended for low-level I/O and must be applied to a file descriptor
as returned by os.open() or pipe().
Example
The following example shows the usage of close() method.
#!/usr/bin/python3
import os, sys
# Open a file
fd = os.open( "foo.txt", os.O_RDWR|os.O_CREAT )
# Write one string
line="this is test"
# string needs to be converted byte object
b=str.encode(line)
os.write(fd, b)
# Close opened file
os.close( fd )
print ("Closed the file successfully!!")
os.closerange() Method
Description
The method closerange() closes all file descriptors from fd_low (inclusive) to fd_high
(exclusive), ignoring errors.This method is introduced in Python version 2.6.
Syntax
Following is the syntax for closerange() method-
os.closerange(fd_low, fd_high)
Parameters
256
Python 3
Return Value
This method does not return any value.
Example
The following example shows the usage of closerange() method.
#!/usr/bin/python3
import os, sys
# Open a file
fd = os.open( "foo.txt", os.O_RDWR|os.O_CREAT )
This would create given file foo.txt and then write given content in that file. This will
produce the following result-
257
Python 3
os.dup() Method
Description
The method dup() returns a duplicate of file descriptor fd which can be used in place of
original descriptor.
Syntax
Following is the syntax for dup() method-
os.dup(fd)
Parameters
fd - This is the original file descriptor.
Return Value
This method returns a duplicate of file descriptor.
Example
The following example shows the usage of dup() method-
#!/usr/bin/python3
import os, sys
# Open a file
fd = os.open( "foo.txt", os.O_RDWR|os.O_CREAT )
line="this is test"
# string needs to be converted byte object
b=str.encode(line)
os.write(d_fd, b)
os.dup2() Method
Description
The method dup2() duplicates file descriptor fd to fd2, closing the latter first if necessary.
Note: New file description would be assigned only when it is available. In the following
example given below, 1000 would be assigned as a duplicate fd in case when 1000 is
available.
Syntax
Following is the syntax for dup2() method-
os.dup2(fd, fd2)
Parameters
fd - This is File descriptor to be duplicated.
Return Value
This method returns a duplicate of file descriptor.
Example
The following example shows the usage of dup2() method.
#!/usr/bin/python3
import os, sys
# Open a file
fd = os.open( "foo.txt", os.O_RDWR|os.O_CREAT )
line="this is test"
# string needs to be converted byte object
b=str.encode(line)
259
Python 3
os.write(fd, b)
os.fchdir() Method
Description
The method fchdir() change the current working directory to the directory represented
by the file descriptor fd. The descriptor must refer to an opened directory, not an open
file.
Syntax
Following is the syntax for fchdir() method-
os.fchdir(fd)
Parameters
fd - This is Directory descriptor.
Return Value
This method does not return any value.
260
Python 3
Example
The following example shows the usage of fchdir() method.
#!/usr/bin/python3
import os, sys
# First go to the "/var/www/html" directory
os.chdir("/var/www/html" )
os.fchmod() Method
Description
The method fchmod() changes the mode of the file given by fd to the numeric mode. The
mode may take one of the following values or bitwise ORed combinations of them-
261
Python 3
Syntax
Following is the syntax for fchmod() method-
os.fchmod(fd, mode)
Parameters
fd - This is the file descriptor for which mode would be set.
mode - This may take one of the above mentioned values or bitwise ORed
combinations of them.
Return Value
This method does not return any value. Available on Unix like operating systems only.
Example
262
Python 3
#!/usr/bin/python3
import os, sys, stat
# Now open a file "/tmp/foo.txt"
fd = os.open( "/tmp", os.O_RDONLY )
os.fchown() Method
Description
The method fchown() changes the owner and group id of the file given by fd to the numeric
uid and gid. To leave one of the ids unchanged, set it to -1.
Syntax
Following is the syntax for fchown() method-
Parameters
fd - This is the file descriptor for which owner id and group id need to be set up.
263
Python 3
Return Value
This method does not return any value. Available in Unix like operating systems only.
Example
The following example shows the usage of fchown() method.
#!/usr/bin/python3
import os, sys, stat
# Now open a file "/tmp/foo.txt"
fd = os.open( "/tmp", os.O_RDONLY )
# Set the user Id to 100 for this file.
os.fchown( fd, 100, -1)
os.fdatasync() Method
Description
The method fdatasync() forces write of file with filedescriptor fd to disk. This does not
force update of metadata. If you want to flush your buffer then you can use this method.
Syntax
Following is the syntax for fdatasync() method-
os.fdatasync(fd)
Parameters
fd - This is the file descriptor for which data to be written.
264
Python 3
Return Value
This method does not return any value.
Example
The following example shows the usage of fdatasync() method-
#!/usr/bin/python3
import os, sys
# Open a file
fd = os.open( "foo.txt", os.O_RDWR|os.O_CREAT )
# Write one string
line="this is test"
# string needs to be converted byte object
b=str.encode(line)
os.write(fd, b)
# Now you can use fdatasync() method.
# Infact here you would not be able to see its effect.
os.fdatasync(fd)
265
Python 3
os.fdopen() Method
Description
The method fdopen() returns an open file object connected to the file descriptor fd. Then
you can perform all the defined functions on file object.
Syntax
Following is the syntax for fdopen() method-
Parameters
fd - This is the file descriptor for which a file object is to be returned.
mode - This optional argument is a string indicating how the file is to be opened.
The most commonly-used values of mode are 'r' for reading, 'w' for writing
(truncating the file if it already exists), and 'a' for appending.
bufsize - This optional argument specifies the file's desired buffer size: 0 means
unbuffered, 1 means line buffered, any other positive value means use a buffer of
(approximately) that size.
Return Value
This method returns an open file object connected to the file descriptor.
Example
The following example shows the usage of fdopen() method.
#!/usr/bin/python3
import os, sys
# Open a file
fd = os.open( "foo.txt", os.O_RDWR|os.O_CREAT )
266
Python 3
os.fpathconf() Method
Description
The method fpathconf() returns system configuration information relevant to an open
file.This variable is very similar to unix system call fpathconf() and accept the similar
arguments.
Syntax
Following is the syntax for fpathconf() method-
os.fpathconf(fd, name)
Parameters
fd - This is the file descriptor for which system configuration information is to be
returned.
name - This specifies the configuration value to retrieve; it may be a string, which
is the name of a defined system value; these names are specified in a number of
267
Python 3
standards (POSIX.1, Unix 95, Unix 98, and others). The names known to the host
operating system are given in the os.pathconf_names dictionary.
Return Value
This method returns system configuration information relevant to an open file.
Example
The following example shows the usage of fpathconf() method.
#!/usr/bin/python3
import os, sys
# Open a file
fd = os.open( "foo.txt", os.O_RDWR|os.O_CREAT )
print ("%s" % os.pathconf_names)
# Now get maximum number of links to the file.
no = os.fpathconf(fd, 'PC_LINK_MAX')
print ("Maximum number of links to the file. :%d" % no)
# Now get maximum length of a filename
no = os.fpathconf(fd, 'PC_NAME_MAX')
print ("Maximum length of a filename :%d" % no)
268
Python 3
os.fstat() Method
Description
The method fstat() returns information about a file associated with the fd. Here is the
structure returned by fstat method-
st_mode: protection
Syntax
Following is the syntax for fstat() method-
os.fstat(fd)
Parameters
fd - This is the file descriptor for which system information is to be returned.
Return Value
This method returns information about a file associated with the fd.
Example
The following example shows the usage of chdir() method.
#!/usr/bin/python3
269
Python 3
os.fstatvfs() Method
Description
The method fstatvfs() returns information about the file system containing the file
associated with file descriptor fd. This returns the following structure-
f_files: inodes
270
Python 3
Syntax
Following is the syntax for fstatvfs() method-
os.fstatvfs(fd)
Parameters
fd - This is the file descriptor for which system information is to be returned.
Return Value
This method returns information about the file system containing the file associated.
Example
The following example shows the usage of fstatvfs() method.
#!/usr/bin/python3
import os, sys
# Open a file
fd = os.open( "foo.txt", os.O_RDWR|os.O_CREAT )
os.fsync() Method
Description
The method fsync() forces write of file with file descriptor fd to disk. If you're starting with
a Python file object f, first do f.flush(), and then do os.fsync(f.fileno()), to ensure that all
internal buffers associated with f are written to disk.
Syntax
Following is the syntax for fsync() method-
os.fsync(fd)
Parameters
fd - This is the file descriptor for buffer sync is required.
Return Value
This method does not return any value.
Example
The following example shows the usage of fsync() method.
#!/usr/bin/python3
import os, sys
# Open a file
fd = os.open( "foo.txt", os.O_RDWR|os.O_CREAT )
# Write one string
272
Python 3
line="this is test"
b=line.encode()
os.write(fd, b)
# Now you can use fsync() method.
# Infact here you would not be able to see its effect.
os.fsync(fd)
# Now read this file from the beginning
os.lseek(fd, 0, 0)
line = os.read(fd, 100)
b=line.decode()
print ("Read String is : ", b)
# Close opened file
os.close( fd )
print ("Closed the file successfully!!")
os.ftruncate() Method
Description
The method ftruncate() truncates the file corresponding to file descriptor fd, so that it is
at most length bytes in size.
Syntax
Following is the syntax for ftruncate() method-
os.ftruncate(fd, length)
Parameters
fd - This is the file descriptor, which needs to be truncated.
length - This is the length of the file where file needs to be truncated.
Return Value
This method does not return any value. Available on Unix like systems.
Example
273
Python 3
#!/usr/bin/python3
import os, sys
# Open a file
fd = os.open( "foo.txt", os.O_RDWR|os.O_CREAT )
os.getcwd() Method
Description
The method getcwd() returns current working directory of a process.
Syntax
Following is the syntax for getcwd() method-
os.ggetcwd(path)
Parameters
NA
274
Python 3
Return Value
This method returns the current working directory of a process.
Example
The following example shows the usage of getcwd() method-
#!/usr/bin/python3
import os, sys
# First go to the "/var/www/html" directory
os.chdir("/var/www/html" )
os.getcwdu() Method
Description
The method getcwdu() returns a unicode object representing the current working
directory.
Syntax
Following is the syntax for getcwdu() method-
os.getcwdu()
275
Python 3
Parameters
NA
Return Value
This method returns a unicode object representing the current working directory.
Example
The following example shows the usage of getcwdu() method.
#!/usr/bin/python3
import os, sys
os.isatty() Method
Description
276
Python 3
The method isatty()returns True if the file descriptor fd is open and connected to a tty(-
like) device, else False.
Syntax
Following is the syntax for isatty() method-
os.isatty( fd )
Parameters
fd - This is the file descriptor for which association needs to be checked.
Return Value
This method returns True if the file descriptor fd is open and connected to a tty(-like)
device, else False.
Example
The following example shows the usage of isatty() method.
#!/usr/bin/python3
import os, sys
# Open a file
fd = os.open( "foo.txt", os.O_RDWR|os.O_CREAT )
# Write one string
line="This is test"
b=line.encode()
os.write(fd, b)
277
Python 3
os.lchflags() Method
Description
The method lchflags() sets the flags of path to the numeric flags. This method does not
follow symbolic links unlike chflags() method. As of Python 3.3, this is equivalent to
os.chflags(path, flags, follow_symlinks=False).
Here, flags may take a combination (bitwise OR) of the following values (as defined in the
stat module):
Syntax
Following is the syntax for lchflags() method-
os.lchflags(path, flags)
Parameters
path - This is the file path for which flags to be set.
flags - This could be a combination (bitwise OR) of the above defined flags values.
Return Value
This method does not return any value. Available on Unix like systems.
Example
The following example shows the usage of lchflags() method.
278
Python 3
#!/usr/bin/python3
# Open a file
path = "/var/www/html/foo.txt"
fd = os.open( path, os.O_RDWR|os.O_CREAT )
os.lchown() Method
Description
The method lchown() changes the owner and group id of path to the numeric uid and gid.
This function will not follow symbolic links. To leave one of the ids unchanged, set it to -
1. As of Python 3.3, this is equivalent to os.chown(path, uid, gid, follow_symlinks=False).
Syntax
Following is the syntax for lchown() method-
Parameters
path - This is the file path for which ownership to be set.
279
Python 3
Return Value
This method does not return any value.
Example
The following example shows the usage of lchown() method.
#!/usr/bin/python3
import os, sys
# Open a file
path = "/var/www/html/foo.txt"
fd = os.open( path, os.O_RDWR|os.O_CREAT )
os.link() Method
Description
The method link() creates a hard link pointing to src named dst. This method is very useful
to create a copy of existing file.
Syntax
Following is the syntax for link() method-
os.link(src, dst)
280
Python 3
Parameters
src - This is the source file path for which hard link would be created.
dest - This is the target file path where hard link would be created.
Return Value
This method does not return any value. Available on Unix, Windows.
Example
The following example shows the usage of link() method.
#!/usr/bin/python3
import os, sys
# Open a file
path = "d:\\python3\\foo.txt"
fd = os.open( path, os.O_RDWR|os.O_CREAT )
os.listdir() Method
Description
The method listdir() returns a list containing the names of the entries in the directory
given by path. The list is in arbitrary order. It does not include the special entries '.' and
'..' even if they are present in the directory.
path may be either of type str or of type bytes. If path is of type bytes, the filenames
returned will also be of type bytes; in all other circumstances, they will be of type str.
Syntax
281
Python 3
os.listdir(path)
Parameters
path - This is the directory, which needs to be explored.
Return Value
This method returns a list containing the names of the entries in the directory given by
path.
Example
The following example shows the usage of listdir() method.
#!/usr/bin/python3
import os, sys
# Open a file
path = "d:\\tmp\\"
dirs = os.listdir( path )
# This would print all the files and directories
for file in dirs:
print (file)
Applicationdocs.docx
test.java
book.zip
foo.txt
Java Multiple Inheritance.htm
Java Multiple Inheritance_files
java.ppt
ParallelPortViewer
os.lseek() Method
Description
The method lseek() sets the current position of file descriptor fd to the given position pos,
modified by how.
282
Python 3
Syntax
Following is the syntax for lseek() method-
Parameters
fd - This is the file descriptor, which needs to be processed.
pos - This is the position in the file with respect to given parameter how. You give
os.SEEK_SET or 0 to set the position relative to the beginning of the file,
os.SEEK_CUR or 1 to set it relative to the current position; os.SEEK_END or 2 to
set it relative to the end of the file.
how - This is the reference point with-in the file. os.SEEK_SET or 0 means
beginning of the file, os.SEEK_CUR or 1 means the current position and
os.SEEK_END or 2 means end of the file.
os.SEEK_SET - 0
os.SEEK_CUR - 1
os.SEEK_END - 2
Return Value
This method does not return any value.
Example
The following example shows the usage of lseek() method.
#!/usr/bin/python3
import os, sys
# Open a file
fd = os.open( "foo.txt", os.O_RDWR|os.O_CREAT )
# Write one string
line="This is test"
b=line.encode()
os.write(fd, b)
# Now you can use fsync() method.
# Infact here you would not be able to see its effect.
os.fsync(fd)
# Now read this file from the beginning
os.lseek(fd, 0, 0)
283
Python 3
os.lstat() Method
Description
The method lstat() is very similar to fstat() and returns a stat_result object containing the
information about a file, but do not follow symbolic links. This is an alias for fstat() on
platforms that do not support symbolic links, such as Windows.
st_mode: protection
Syntax
Following is the syntax for lstat() method:
os.lstat(path)
Parameters
path - This is the file for which information would be returned.
Return Value
This method returns the information about a file.
Example
The following example shows the usage of lstat() method.
#!/usr/bin/python3
import os, sys
# Open a file
path = "d:\\python3\\foo.txt"
fd = os.open( path, os.O_RDWR|os.O_CREAT )
# Close opened file
os.close( fd )
# Now get the touple
info = os.lstat(path)
print ("File Info :", info)
# Now get uid of the file
print ("UID of the file :%d" % info.st_uid)
# Now get gid of the file
print ("GID of the file :%d" % info.st_gid)
285
Python 3
os.major() Method
Description
The method major() extracts the device major number from a raw device number (usually
the st_dev or st_rdev field from stat).
Syntax
Following is the syntax for major() method-
os.major(device)
Parameters
device - This is a raw device number (usually the st_dev or st_rdev field from stat).
Return Value
This method returns the device major number.
Example
The following example shows the usage of major() method.
#!/usr/bin/python3
import os, sys
path = "/var/www/html/foo.txt"
# Now get the touple
info = os.lstat(path)
# Get major and minor device number
major_dnum = os.major(info.st_dev)
minor_dnum = os.minor(info.st_dev)
print ("Major Device Number :", major_dnum)
print ("Minor Device Number :", minor_dnum)
os.makedev() Method
Description
286
Python 3
The method makedev() composes a raw device number from the major and minor device
numbers.
Syntax
Following is the syntax for makedev() method-
os.makedev(major, minor)
Parameters
major - This is Major device number.
Return Value
This method returns the device number.
Example
The following example shows the usage of makedev() method.
#!/usr/bin/python3
import os, sys
path = "/var/www/html/foo.txt"
# Now get the touple
info = os.lstat(path)
# Get major and minor device number
major_dnum = os.major(info.st_dev)
minor_dnum = os.minor(info.st_dev)
print ("Major Device Number :", major_dnum)
print ("Minor Device Number :", minor_dnum)
287
Python 3
os.makedirs() Method
Description
The method makedirs() is recursive directory creation function. Like mkdir(), but makes
all intermediate-level directories needed to contain the leaf directory.
The default mode is 0o777 (octal). On some systems, mode is ignored. Where it is used,
the current umask value is first masked out.
If exist_ok is False (the default), an OSError is raised if the target directory already exists.
Syntax
Following is the syntax for makedirs() method-
os.makedirs(path[, mode])
Parameters
path - This is the path, which needs to be created recursively.
Return Value
This method does not return any value.
Example
The following example shows the usage of makedirs() method.
#!/usr/bin/python3
import os, sys
# Path to be created
path = "d:/tmp/home/monthly/daily"
os.makedirs( path, 493 ) #decimal equivalent of 0755 used on Windows
print ("Path is created")
Path is created
os.minor() Method
Description
The method minor() extracts the device minor number from a raw device number (usually
the st_dev or st_rdev field from stat).
288
Python 3
Syntax
Following is the syntax for minor() method-
os.minor(device)
Parameters
device - This is a raw device number (usually the st_dev or st_rdev field from stat).
Return Value
This method returns the device minor number.
Example
The following example shows the usage of minor() method.
#!/usr/bin/python3
import os, sys
path = "/var/www/html/foo.txt"
# Now get the touple
info = os.lstat(path)
# Get major and minor device number
major_dnum = os.major(info.st_dev)
minor_dnum = os.minor(info.st_dev)
os.mkdir() Method
Description
The method mkdir() create a directory named path with numeric mode mode. The default
mode is 0777 (octal). On some systems, mode is ignored. Where it is used, the current
umask value is first masked out.
289
Python 3
Syntax
Following is the syntax for mkdir() method-
os.mkdir(path[, mode])
Parameters
path - This is the path, which needs to be created.
Return Value
This method does not return any value.
Example
The following example shows the usage of mkdir() method.
#!/usr/bin/python3
import os, sys
# Path to be created
path = "/tmp/home/monthly/daily/hourly"
os.mkdir( path, 0755 );
print "Path is created"
Path is created
os.mkfifo() Method
Description
The method mkfifo() create a FIFO named path with numeric mode. The default mode is
0666 (octal).The current umask value is first masked out.
FIFOs are pipes that can be accessed like regular files. FIFOs exist until they are deleted
Syntax
Following is the syntax for mkfifo() method-
os.mkfifo(path[, mode])
290
Python 3
Parameters
path - This is the path, which needs to be created.
Return Value
This method does not return any value.
Example
The following example shows the usage of mkfifo() method.
# !/usr/bin/python3
import os, sys
# Path to be created
path = "/tmp/hourly"
os.mkfifo( path, 0644 )
print ("Path is created")
Path is created
os.mknod() Method
Description
The method mknod() creates a filesystem node (file, device special file or named pipe)
named filename.
Syntax
Following is the syntax for mknod() method-
Parameters
filename - This is the filesystem node to be created.
mode - The mode specifies both the permissions to use and the type of node to be
created combined (bitwise OR) with one of the values stat.S_IFREG, stat.S_IFCHR,
stat.S_IFBLK, and stat.S_IFIFO. They can be ORed base don requirement.
device - This is the device special file created and its optional to provide.
291
Python 3
Return Value
This method does not return any value. Available on Unix like systems.
Example
The following example shows the usage of mknod() method.
# !/usr/bin/python3
import os
import stat
filename = '/tmp/tmpfile'
mode = 0600|stat.S_IRUSR
# filesystem node specified with different modes
os.mknod(filename, mode)
Let us compile and run the above program, this will create a simple file in /tmp directory
with a name tmpfile:
os.open() Method
Description
The method open() opens the file file and set various flags according to flags and possibly
its mode according to mode.The default mode is 0777 (octal), and the current umask value
is first masked out.
Syntax
Following is the syntax for open() method:
Parameters
file - File name to be opened.
flags - The following constants are options for the flags. They can be combined
using the bitwise OR operator |. Some of them are not available on all platforms.
o os.O_RDONLY: open for reading only
o os.O_WRONLY: open for writing only
o os.O_RDWR : open for reading and writing
o os.O_NONBLOCK: do not block on open
292
Python 3
Return Value
This method returns the file descriptor for the newly opened file.
Example
The following example shows the usage of open() method.
#!/usr/bin/python3
import os, sys
# Open a file
fd = os.open( "foo.txt", os.O_RDWR|os.O_CREAT )
# Write one string
line="this is test"
# string needs to be converted byte object
b=str.encode(line)
os.write(fd, b)
# Close opened file
os.close( fd)
print ("Closed the file successfully!!")
This would create given file foo.txt and then would write given content in that file and
would produce the following result-
os.openpty() Method
Description
293
Python 3
The method openpty() opens a pseudo-terminal pair and returns a pair of file
descriptors(master,slave) for the pty & the tty respectively.
The new file descriptors are non-inheritable. For a (slightly) more portable approach, use
the pty module.
Syntax
Following is the syntax for openpty() method-
os.openpty()
Parameters
NA
Return Value
This method returns a pair of file descriptors i.e., master and slave.
Example
The following example shows the usage of openpty() method.
# !/usr/bin/python3
import os
# master for pty, slave for tty
m,s = os.openpty()
print (m)
print (s)
# showing terminal name
s = os.ttyname(s)
print (m)
print( s)
3
4
3
/dev/pty0
os.pathconf() Method
Description
294
Python 3
The method pathconf() returns system configuration information relevant to a named file.
Syntax
Following is the syntax for pathconf() method-
os.pathconf(path, name)
Parameters
path - This is the file path.
name - This specifies the configuration value to retrieve; it may be a string which
is the name of a defined system value; these names are specified in a number of
standards (POSIX.1, Unix 95, Unix 98, and others). The names known to the host
operating system are given in the os.pathconf_names dictionary.
Return Value
This method returns system configuration information of a file. Available on Unix like
systems.
Example
The following example shows the usage of pathconf() method.
#!/usr/bin/python3
import os, sys
print ("%s" % os.pathconf_names)
# Retrieve maximum length of a filename
no = os.pathconf('a2.py', 'PC_NAME_MAX')
print ("Maximum length of a filename :%d" % no)
# Retrieve file size
no = os.pathconf('a2.py', 'PC_FILESIZEBITS')
print ("file size in bits :%d" % no)
295
Python 3
os.pipe() Method
Description
The method pipe() creates a pipe and returns a pair of file descriptors (r, w) usable for
reading and writing, respectively
Syntax
Following is the syntax for pipe() method-
os.pipe()
Parameters
NA
Return Value
This method returns a pair of file descriptors.
Example
The following example shows the usage of pipe() method.
#!/usr/bin/python3
import os, sys
processid = os.fork()
if processid:
# This is the parent process
# Closes file descriptor w
os.close(w)
r = os.fdopen(r)
print ("Parent reading")
296
Python 3
str = r.read()
print ("text =", str )
sys.exit(0)
else:
# This is the child process
os.close(r)
w = os.fdopen(w, 'w')
print ("Child writing")
w.write("Text written by child...")
w.close()
print ("Child closing")
sys.exit(0)
os.popen() Method
Description
The method popen() opens a pipe to or from command.The return value is an open file
object connected to the pipe, which can be read or written depending on whether mode is
'r' (default) or 'w'.The bufsize argument has the same meaning as in open() function.
Syntax
Following is the syntax for popen() method-
Parameters
command - This is command used.
297
Python 3
bufsize - If the buffering value is set to 0, no buffering will take place. If the
buffering value is 1, line buffering will be performed while accessing a file. If you
specify the buffering value as an integer greater than 1, then buffering action will
be performed with the indicated buffer size. If negative, the buffer size is the
system default(default behavior).
Return Value
This method returns an open file object connected to the pipe.
Example
The following example shows the usage of popen() method.
# !/usr/bin/python3
import os, sys
# using command mkdir
a = 'mkdir nwdir'
b = os.popen(a,'r',1)
print b
os.read() Method
Description
The method read() reads at most n bytes from file desciptor fd, return a string containing
the bytes read. If the end of file referred to by fd has been reached, an empty string is
returned.
Note: This function is intended for low-level I/O and must be applied to a file descriptor
as returned by os.open() or pipe(). To read a “file object” returned by the built-in function
open() or by popen() or fdopen(), or sys.stdin, use its read() or readline() methods.
Syntax
Following is the syntax for read() method-
os.read(fd,n)
Parameters
fd - This is the file descriptor of the file.
Return Value
This method returns a string containing the bytes read.
Example
The following example shows the usage of read() method.
# !/usr/bin/python3
import os, sys
# Open a file
fd = os.open("foo.txt",os.O_RDWR)
# Reading text
ret = os.read(fd,12)
print (ret.decode())
# Close opened file
os.close(fd)
print ("Closed the file successfully!!")
Let us compile and run the above program, this will print the contents of file foo.txt-
This is test
Closed the file successfully!!
os.readlink() Method
Description
The method readlink() returns a string representing the path to which the symbolic link
points. It may return an absolute or relative pathname.
Syntax
Following is the syntax for readlink() method-
os.readlink(path)
Parameters
path - This is the path or symblic link for which we are going to find source of the link.
Return Value
This method return a string representing the path to which the symbolic link points.
Example
299
Python 3
# !/usr/bin/python3
import os
src = 'd://tmp//python3'
dst = 'd://tmp//python2'
# This creates a symbolic link on python in tmp directory
os.symlink(src, dst)
# Now let us use readlink to display the source of the link.
path = os.readlink( dst )
print (path)
Let us compile and run the above program. This will create a symblic link to
d:\tmp\python3 and later it will read the source of the symbolic link using readlink() call.
This is an example on Windows platform and needs administrator privilege to run. Before
running this program make sure you do not have d:\tmp\python2 already available.
d:\tmp\python2
os.remove() Method
Description
The method remove() removes the file path. If the path is a directory, OSError is raised.
Syntax
Following is the syntax for remove() method-
os.remove(path)
Parameters
path - This is the path, which is to be removed.
Return Value
This method does not return any value.
Example
The following example shows the usage of remove() method.
# !/usr/bin/python3
import os, sys
os.chdir("d:\\tmp")
300
Python 3
# listing directories
print ("The dir is: %s" %os.listdir(os.getcwd()))
# removing
os.remove("test.java")
os.removedirs() Method
Description
The method removedirs() removes dirs recursively. If the leaf directory is succesfully
removed, removedirs tries to successively remove every parent directory displayed in
path. Raises OSError if the leaf directory could not be successfully removed.
Syntax
Following is the syntax for removedirs() method-
os.removedirs(path)
Parameters
path - This is the path of the directory, which needs to be removed.
Return Value
This method does not return any value.
Example
The following example shows the usage of removedirs() method.
# !/usr/bin/python3
import os, sys
301
Python 3
os.chdir("d:\\tmp")
# listing directories
print ("The dir is: %s" %os.listdir(os.getcwd()))
# removing
os.removedirs("home\\monthly\\daily")
# listing directories after removing directory
print ("The dir after removal is:" %os.listdir(os.getcwd()))
os.rename() Method
Description
The method rename() renames the file or directory src to dst. If dst is a file or
directory(already present), OSError will be raised.
Syntax
Following is the syntax for rename() method-
os.rename(src, dst)
Parameters
src - This is the actual name of the file or directory.
Return Value
This method does not return any value.
Example
The following example shows the usage of rename() method.
# !/usr/bin/python3
import os, sys
302
Python 3
os.chdir("d:\\tmp")
# listing directories
print ("The dir is: %s"%os.listdir(os.getcwd()))
# renaming directory ''tutorialsdir"
os.rename("python3","python2")
print ("Successfully renamed.")
# listing directories after renaming "python3"
print ("the dir is: %s" %os.listdir(os.getcwd()))
os.renames() Method
Description
The method renames() is recursive directory or file renaming function. It does the same
functioning as os.rename(), but it also moves a file to a directory, or a whole tree of
directories, that do not exist.
Syntax
Following is the syntax for renames() method:
os.renames(old, new)
Parameters
old - This is the actual name of the file or directory to be renamed.
new - This is the new name of the file or directory. It can even include a file to a
directory, or a whole tree of directories, that do not exist.
Return Value
This method does not return any value.
Example
The following example shows the usage of renames() method.
303
Python 3
# !/usr/bin/python3
import os, sys
os.chdir("d:\\tmp")
print ("Current directory is: %s" %os.getcwd())
# listing directories
print ("The dir is: %s"%os.listdir(os.getcwd()))
# renaming file "aa1.txt"
os.renames("foo.txt","newdir/foonew.txt")
print ("Successfully renamed.")
# listing directories after renaming and moving "foo.txt"
print ("The dir is: %s" %os.listdir(os.getcwd()))
os.chdir("newdir")
print ("The dir is: %s" %os.listdir(os.getcwd()))
os.renames() Method
Description
The method renames() is recursive directory or file renaming function. It does the same
functioning as os.rename(), but it also moves a file to a directory, or a whole tree of
directories, that do not exist.
Syntax
Following is the syntax for renames() method-
os.renames(old, new)
Parameters
old - This is the actual name of the file or directory to be renamed.
304
Python 3
new - This is the new name of the file or directory.It can even include a file to a
directory, or a whole tree of directories, that do not exist.
Return Value
This method does not return any value.
Example
The following example shows the usage of renames() method.
# !/usr/bin/python3
import os, sys
os.chdir("d:\\tmp")
print ("Current directory is: %s" %os.getcwd())
# listing directories
print ("The dir is: %s"%os.listdir(os.getcwd()))
# renaming file "aa1.txt"
os.renames("foo.txt","newdir/foonew.txt")
os.rmdir() Method
Description
305
Python 3
The method rmdir() removes the directory path. It works only when the directory is
empty, else OSError is raised.
Syntax
Following is the syntax for rmdir() method-
os.rmdir(path)
Parameters
path - This is the path of the directory, which needs to be removed.
Return Value
This method does not return any value.
Example
The following example shows the usage of rmdir() method.
# !/usr/bin/python3
import os, sys
os.chdir("d:\\tmp")
# listing directories
print ("the dir is: %s" %os.listdir(os.getcwd()))
# removing path
os.rmdir("newdir")
306
Python 3
os.stat() Method
Description
The method stat() performs a stat system call on the given path.
Syntax
Following is the syntax for stat() method-
os.stat(path)
Parameters
path - This is the path, whose stat information is required.
Return Value
Here is the list of members of stat structure-
Example
The following example shows the usage of stat() method.
# !/usr/bin/python3
import os, sys
# showing stat information of file "foo.txt"
statinfo = os.stat('foo.txt')
307
Python 3
print (statinfo)
os.stat_float_times() Method
Description
The method stat_float_times() determines whether stat_result represents time stamps as
float objects.
Syntax
Following is the syntax for stat_float_times() method-
os.stat_float_times([newvalue])
Parameters
newvalue - If newvalue is True, future calls to stat() return floats, if it is False, future call
on stat returns ints. If newvalue is not mentioned, it returns the current settings.
Return Value
This method returns either True or False.
Example
The following example shows the usage of stat_float_times() method.
#!/usr/bin/python3
import os, sys
# Stat information
statinfo = os.stat('a2.py')
print (statinfo)
statinfo = os.stat_float_times()
print (statinfo)
308
Python 3
os.statvfs() Method
Description
The method statvfs() perform a statvfs system call on the given path.
Syntax
Following is the syntax for statvfs() method-
os.statvfs(path)
Parameters
path - This is the path, whose statvfs information is required.
Return Value
Here is the list of members of statvfs structure-
Example
The following example shows the usage of statvfs() method. Availabe on Unix like
systems-
# !/usr/bin/python3
import os, sys
# showing statvfs information of file "a1.py"
stinfo = os.statvfs('a1.py')
309
Python 3
print (stinfo)
os.symlink() Method
Description
The method symlink() creates a symbolic link dst pointing to src.
Syntax
Following is the syntax for symlink() method-
os.symlink(src, dst)
Parameters
src - This is the source.
Return Value
This method does not return any value.
Example
The following example shows the usage of symlink() method-
#!/usr/bin/python3
import os
src = '/usr/bin/python3'
dst = '/tmp/python'
# This creates a symbolic link on python in tmp directory
os.symlink(src, dst)
print "symlink created"
Let us compile and run the above program, this will create a symbolic link in /tmp directory
which will be as follows-
310
Python 3
os.tcgetpgrp() Method
Description
The method tcgetpgrp() returns the process group associated with the terminal given by
fd (an open file descriptor as returned by os.open())
Syntax
Following is the syntax for tcgetpgrp() method-
os.tcgetpgrp(fd)
Parameters
fd - This is the file descriptor.
Return Value
This method returns the process group.
Example
The following example shows the usage of tcgetpgrp() method-
# !/usr/bin/python3
import os, sys
# Showing current directory
print ("Current working dir :%s" %os.getcwd())
# Changing dir to /dev/tty
fd = os.open("/dev/tty",os.O_RDONLY)
f = os.tcgetpgrp(fd)
# Showing the process group
print ("the process group associated is: ")
print (f)
os.close(fd)
print ("Closed the file successfully!!")
2670
Closed the file successfully!!
os.tcsetpgrp() Method
Description
The method tcsetpgrp() sets the process group associated with the terminal given by fd
(an open file descriptor as returned by os.open()) to pg.
Syntax
Following is the syntax for tcsetpgrp() method-
os.tcsetpgrp(fd, pg)
Parameters
fd - This is the file descriptor.
Return Value
This method does not return any value.
Example
The following example shows the usage of tcsetpgrp() method.
# !/usr/bin/python3
import os, sys
# Showing current directory
print ("Current working dir :%s" %os.getcwd())
f = os.tcgetpgrp(fd)
312
Python 3
os.close(fd)
print "Closed the file successfully!!"
os.tempnam() Method
Description
The method tempnam() returns a unique path name that is reasonable for creating a
temporary file.
Syntax
os.tempnam(dir, prefix)
Parameters
dir - This is the dir where the temporary filename will be created.
Return Value
Example
# !/usr/bin/python3
import os, sys
# prefix is tuts1 of the generated file
tmpfn = os.tempnam('/tmp/tutorialsdir,'tuts1')
313
Python 3
os.tmpfile() Method
Description
The method tmpfile() returns a new temporary file object opened in update mode (w+b).
The file has no directory entries associated with it and will be deleted automatically once
there are no file descriptors.
Syntax
Following is the syntax for tmpfile() method-
os.tmpfile
Parameters
NA
Return Value
This method returns a new temporary file object.
Example
The following example shows the usage of tmpfile() method.
# !/usr/bin/python3
import os
# The file has no directory entries associated with it and will be
# deleted automatically once there are no file descriptors.
tmpfile = os.tmpfile()
tmpfile.write('Temporary newfile is here.....')
tmpfile.seek(0)
print tmpfile.read()
314
Python 3
tmpfile.close
os.tmpnam() Method
Description
The method tmpnam() returns a unique path name that is reasonable for creating a
temporary file.
Syntax
Following is the syntax for tmpnam() method-
os.tmpnam()
Parameters
NA
Return Value
This method returns a unique path name.
Example
The following example shows the usage of tmpnam() method.
# !/usr/bin/python3
import os, sys
# Temporary file generated in current directory
tmpfn = os.tmpnam()
print "This is the unique path:"
print tmpfn
os.ttyname() Method
Description
315
Python 3
The method ttyname() returns a string, which specifies the terminal device associated
with fd. If fd is not associated with a terminal device, an exception is raised.
Syntax
Following is the syntax for ttyname() method-
os.ttyname(fd)
Parameters
fd - This is the file descriptor.
Return Value
This method returns a string which specifies the terminal device. Available on Unix like
Systems.
Example
The following example shows the usage of ttyname() method.
# !/usr/bin/python33
import os, sys
p = os.ttyname(fd)
print ("the terminal device associated is: ")
print p
print ("done!!")
os.close(fd)
print ("Closed the file successfully!!")
316
Python 3
done!!
Closed the file successfully!!
os.unlink() Method
Description
The method unlink() removes (deletes) the file path. If the path is a directory, OSError
is raised. This function is identical to the remove() mehod; the unlink name is its traditional
Unix name.
Syntax
Following is the syntax for unlink() method-
os.unlink(path)
Parameters
path - This is the path, which is to be removed.
Return Value
This method does not return any value.
Example
The following example shows the usage of unlink() method.
# !/usr/bin/python3
import os, sys
os.chdir("d:\\tmp")
# listing directories
print ("The dir is: %s" %os.listdir(os.getcwd()))
os.unlink("foo.txt")
# listing directories after removing path
print ("The dir after removal of path : %s" %os.listdir(os.getcwd()))
317
Python 3
os.utime() Method
Description
The method utime() sets the access and modified times of the file specified by path.
Syntax
Following is the syntax for utime() method-
os.utime(path, times)
Parameters
path - This is the path of the file.
times - This is the file access and modified time. If times is none, then the file
access and modified times are set to the current time. The parameter times consists
of row in the form of (atime, mtime) i.e (accesstime, modifiedtime).
Return Value
This method does not return any value.
Example
The following example shows the usage of utime() method.
# !/usr/bin/python3
import os, sys, time
os.chdir("d:\\tmp")
# Showing stat information of file
stinfo = os.stat('foo.txt')
print (stinfo)
# Using os.stat to recieve atime and mtime of file
print ("access time of foo.txt: %s" %stinfo.st_atime)
print ("modified time of foo.txt: %s" %stinfo.st_mtime)
print (time.asctime( time.localtime(stinfo.st_atime)))
# Modifying atime and mtime
os.utime("foo.txt",(1330712280, 1330712292))
print ("after modification")
print (time.asctime( time.localtime(stinfo.st_atime)))
print ("done!!")
318
Python 3
os.walk() Method
Description
The method walk() generates the file names in a directory tree by walking the tree either
top-down or bottom-up.
Syntax
Following is the syntax for the walk() method-
Parameters
top - Each directory rooted at directory, yields 3-tuples, i.e., (dirpath, dirnames,
filenames)
onerror - This can show error to continue with the walk, or raise the exception to
abort the walk.
Return Value
This method does not return any value.
Example
The following example shows the usage of walk() method.
# !/usr/bin/python3
import os
319
Python 3
os.chdir("d:\\tmp")
for root, dirs, files in os.walk(".", topdown=False):
for name in files:
print(os.path.join(root, name))
for name in dirs:
print(os.path.join(root, name))
Let us compile and run the above program. This will scan all the directories and
subdirectories bottom-to-up.
.\python2\testdir\Readme_files\Lpt_Port_Config.gif
.\python2\testdir\Readme_files\ParallelPortViever.gif
.\python2\testdir\Readme_files\softcollection.css
.\python2\testdir\Readme_files\Thumbs.db
.\python2\testdir\Readme_files\Yellov_Ball.gif
.\python2\testdir\Readme.htm
.\python2\testdir\Readme_files
.\python2\testdir
.\Applicationdocs.docx
.\book.zip
.\foo.txt
.\java.ppt
.\python2
If you will change the value of topdown to True, then it will give you the following result-
.\Applicationdocs.docx
.\book.zip
.\foo.txt
.\java.ppt
.\python2
.\python2\testdir
.\python2\testdir\Readme.htm
.\python2\testdir\Readme_files
.\python2\testdir\Readme_files\Lpt_Port_Config.gif
.\python2\testdir\Readme_files\ParallelPortViever.gif
.\python2\testdir\Readme_files\softcollection.css
.\python2\testdir\Readme_files\Thumbs.db
320
Python 3
.\python2\testdir\Readme_files\Yellov_Ball.gif
os.write() Method
Description
The method write() writes the string str to file descriptor fd. It returns the number of
bytes actually written.
Syntax
Following is the syntax for write() method-
os.write(fd, str)
Parameters
fd - This is the file descriptor.
Return Value
This method returns the number of bytes actually written.
Example
The following example shows the usage of the write() method-
# !/usr/bin/python3
import os, sys
# Open a file
fd = os.open( "f1.txt", os.O_RDWR|os.O_CREAT )
# Write one string
line="this is test"
# string needs to be converted byte object
b=str.encode(line)
ret=os.write(fd, b)
# ret consists of number of bytes written to f1.txt
print ("the number of bytes written: ", ret)
# Close opened file
os.close( fd)
print ("Closed the file successfully!!")
322
18. Python 3 – Exceptions Handling Python 3
Python provides two very important features to handle any unexpected error in your
Python programs and to add debugging capabilities in them-
Exception Handling.
Assertions.
Standard Exceptions
Here is a list of Standard Exceptions available in Python.
StopIteration Raised when the next() method of an iterator does not point to
any object.
StandardError Base class for all built-in exceptions except StopIteration and
SystemExit.
ArithmeticError Base class for all errors that occur for numeric calculation.
ZeroDivisonError Raised when division or modulo by zero takes place for all
numeric types.
323
Python 3
KeyError Raised when the specified key is not found in the dictionary.
EnvironmentError Base class for all exceptions that occur outside the Python
environment.
IOError Raised when an input/ output operation fails, such as the print
statement or the open() function when trying to open a file that
does not exist.
SystemError Raised when the interpreter finds an internal problem, but when
this error is encountered the Python interpreter does not exit.
324
Python 3
ValueError Raised when the built-in function for a data type has the valid
type of arguments, but the arguments have invalid values
specified.
RuntimeError Raised when a generated error does not fall into any category.
Assertions in Python
An assertion is a sanity-check that you can turn on or turn off when you are done with
your testing of the program.
Assertions are carried out by the assert statement, the newest keyword to Python,
introduced in version 1.5.
Programmers often place assertions at the start of a function to check for valid
input, and after a function call to check for valid output.
If the assertion fails, Python uses ArgumentExpression as the argument for the
AssertionError. AssertionError exceptions can be caught and handled like any other
exception, using the try-except statement. If they are not handled, they will terminate the
program and produce a traceback.
Example
Here is a function that converts a given temperature from degrees Kelvin to degrees
Fahrenheit. Since 0° K is as cold as it gets, the function bails out if it sees a negative
temperature −
325
Python 3
#!/usr/bin/python3
def KelvinToFahrenheit(Temperature):
assert (Temperature >= 0),"Colder than absolute zero!"
return ((Temperature-273)*1.8)+32
print (KelvinToFahrenheit(273))
print (int(KelvinToFahrenheit(505.78)))
print (KelvinToFahrenheit(-5))
32.0
451
Traceback (most recent call last):
File "test.py", line 9, in
print KelvinToFahrenheit(-5)
File "test.py", line 4, in KelvinToFahrenheit
assert (Temperature >= 0),"Colder than absolute zero!"
AssertionError: Colder than absolute zero!
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
......................
326
Python 3
except ExceptionI:
If there is ExceptionI, then execute this block.
except ExceptionII:
If there is ExceptionII, then execute this block.
......................
else:
If there is no exception then execute this block.
A single try statement can have multiple except statements. This is useful when
the try block contains statements that may throw different types of exceptions.
You can also provide a generic except clause, which handles any exception.
After the except clause(s), you can include an else-clause. The code in the else-
block executes if the code in the try: block does not raise an exception.
The else-block is a good place for code that does not need the try: block's
protection.
Example
This example opens a file, writes content in the file and comes out gracefully because there
is no problem at all.
#!/usr/bin/python3
try:
fh = open("testfile", "w")
fh.write("This is my test file for exception handling!!")
except IOError:
print ("Error: can\'t find file or read data")
else:
print ("Written content in the file successfully")
fh.close()
Example
This example tries to open a file where you do not have the write permission, so it raises
an exception-
327
Python 3
#!/usr/bin/python3
try:
fh = open("testfile", "r")
fh.write("This is my test file for exception handling!!")
except IOError:
print ("Error: can\'t find file or read data")
else:
print ("Written content in the file successfully")
try:
You do your operations here
......................
except:
If there is any exception, then execute this block.
......................
else:
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.
......................
328
Python 3
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.
......................
Note: You can provide except clause(s), or a finally clause, but not both. You cannot
use else clause as well along with a finally clause.
Example
#!/usr/bin/python3
try:
fh = open("testfile", "w")
fh.write("This is my test file for exception handling!!")
finally:
print ("Error: can\'t find file or read data")
fh.close()
If you do not have permission to open the file in writing mode, then this will produce the
following result-
#!/usr/bin/python3
try:
fh = open("testfile", "w")
try:
fh.write("This is my test file for exception handling!!")
329
Python 3
finally:
print ("Going to close the file")
fh.close()
except IOError:
print ("Error: can\'t find file or read data")
When an exception is thrown in the try block, the execution immediately passes to
the finally block. After all the statements in the finally block are executed, the exception
is raised again and is handled in the except statements if present in the next higher layer
of the try-except statement.
Argument of an Exception
An exception can have an argument, which is a value that gives additional information
about the problem. The contents of the argument vary by exception. You capture an
exception's argument by supplying a variable in the except clause as follows-
try:
You do your operations here
......................
except ExceptionType as Argument:
You can print value of Argument here...
If you write the code to handle a single exception, you can have a variable follow the name
of the exception in the except statement. If you are trapping multiple exceptions, you can
have a variable follow the tuple of the exception.
This variable receives the value of the exception mostly containing the cause of the
exception. The variable can receive a single value or multiple values in the form of a tuple.
This tuple usually contains the error string, the error number, and an error location.
Example
Following is an example for a single exception-
#!/usr/bin/python3
330
Python 3
temp_convert("xyz")
Raising an Exception
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 as a class object or a simple string. For example, to capture the above
exception, we must write the except clause as follows-
try:
Business Logic here...
except Exception as e:
Exception handling here using e.args...
331
Python 3
else:
Rest of the code here...
#!/usr/bin/python3
def functionName( level ):
if level <1:
raise Exception(level)
# The code below to this would not be executed
# if we raise the exception
return level
try:
l=functionName(-10)
print ("level=",l)
except Exception as e:
print ("error in level argument",e.args[0])
User-Defined Exceptions
Python also allows you to create your own exceptions by deriving classes from the standard
built-in exceptions.
In the try block, the user-defined exception is raised and caught in the except block. The
variable e is used to create an instance of the class Networkerror.
class Networkerror(RuntimeError):
def __init__(self, arg):
self.args = arg
So once you have defined the above class, you can raise the exception as follows-
try:
raise Networkerror("Bad hostname")
except Networkerror,e:
print e.args
332
Python 3
333
19. Python 3 – Object Oriented Python 3
Python has been an object-oriented language since the time it existed. Due to 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.
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.
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.
Object: A unique instance of a data structure that is defined by its class. An object
comprises both data members (class variables and instance variables) and
methods.
334
Python 3
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_suite consists of all the component statements defining class members,
data attributes and functions.
Example
Following is an example of a simple Python class-
class Employee:
'Common base class for all employees'
empCount = 0
def displayCount(self):
print "Total Employee %d" % Employee.empCount
def displayEmployee(self):
print ("Name : ", self.name, ", Salary: ", self.salary)
The variable empCount is a class variable whose value is shared among all the
instances of a in this class. This can be accessed as Employee.empCount 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.
335
Python 3
Accessing Attributes
You access the object's attributes using the dot operator with object. Class variable would
be accessed using class name as follows-
emp1.displayEmployee()
emp2.displayEmployee()
print ("Total Employee %d" % Employee.empCount)
#!/usr/bin/python3
class Employee:
'Common base class for all employees'
empCount = 0
def displayCount(self):
print ("Total Employee %d" % Employee.empCount)
def displayEmployee(self):
print ("Name : ", self.name, ", Salary: ", self.salary)
#This would create first object of Employee class"
emp1 = Employee("Zara", 2000)
#This would create second object of Employee class"
336
Python 3
You can add, remove, or modify attributes of classes and objects at any time-
Instead of using the normal statements to access attributes, you can use the following
functions-
337
Python 3
__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-
#!/usr/bin/python3
class Employee:
'Common base class for all employees'
empCount = 0
def displayCount(self):
print ("Total Employee %d" % Employee.empCount)
def displayEmployee(self):
print ("Name : ", self.name, ", Salary: ", self.salary)
338
Python 3
Python's garbage collector runs during program execution and is triggered when an
object's reference count reaches zero. An object's reference count changes as the number
of aliases that point to it changes.
You normally will not notice when the garbage collector destroys an orphaned instance
and reclaims its space. However, a class can implement the special method__del__(),
called a destructor, that is invoked when the instance is about to be destroyed. This
method might be used to clean up any non-memory resources used by an instance.
Example
This __del__() destructor prints the class name of an instance that is about to be
destroyed.
#!/usr/bin/python3
class Point:
def __init( self, x=0, y=0):
self.x = x
self.y = y
def __del__(self):
class_name = self.__class__.__name__
print (class_name, "destroyed")
pt1 = Point()
pt2 = pt1
pt3 = pt1
339
Python 3
Note: Ideally, you should define your classes in a separate file, then you should import
them in your main program file using import statement.
In the above example, assuming definition of a Point class is contained in point.py and there
is no other executable code in it.
#!/usr/bin/python3
import point
p1=point.Point()
Class Inheritance
Instead of starting from a scratch, you can create a class by deriving it from a pre-existing
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 −
Example
#!/usr/bin/python3
class Parent: # define parent class
parentAttr = 100
def __init__(self):
340
Python 3
def getAttr(self):
print ("Parent attribute :", Parent.parentAttr)
def childMethod(self):
print ('Calling child method')
In a similar way, you can drive a class from multiple parent classes as follows-
341
Python 3
You can use issubclass() or isinstance() functions to check a relationship of two classes
and instances.
Overriding Methods
You can always override your parent class methods. One reason for overriding parent's
methods is that you may want special or different functionality in your subclass.
Example
#!/usr/bin/python3
342
Python 3
2 __del__( self )
Destructor, deletes an object
Sample Call : del obj
3 __repr__( self )
Evaluatable string representation
Sample Call : repr(obj)
4 __str__( self )
Printable string representation
Sample Call : str(obj)
5 __cmp__ ( self, x )
Object comparison
Sample Call : cmp(obj, x)
Overloading Operators
Suppose you have created a Vector class to represent two-dimensional vectors. What
happens when you use the plus operator to add them? Most likely Python will yell at you.
You could, however, define the __add__ method in your class to perform vector addition
and then the plus operator would behave as per expectation −
Example
#!/usr/bin/python3
class Vector:
def __init__(self, a, b):
self.a = a
self.b = b
def __str__(self):
return 'Vector (%d, %d)' % (self.a, self.b)
def __add__(self,other):
return Vector(self.a + other.a, self.b + other.b)
v1 = Vector(2,10)
v2 = Vector(5,-2)
print (v1 + v2)
343
Python 3
Vector(7,8)
Data Hiding
An object's attributes may or may not be visible outside the class definition. You need to
name attributes with a double underscore prefix, and those attributes then will not be
directly visible to outsiders.
Example
#!/usr/bin/python3
class JustCounter:
__secretCount = 0
def count(self):
self.__secretCount += 1
print (self.__secretCount)
counter = JustCounter()
counter.count()
counter.count()
print (counter.__secretCount)
1
2
Traceback (most recent call last):
File "test.py", line 12, in <module>
print counter.__secretCount
AttributeError: JustCounter instance has no attribute '__secretCount'
Python protects those members by internally changing the name to include the class name.
You can access such attributes as object._className__attrName. If you would replace
your last line as following, then it works for you-
.........................
print (counter._JustCounter__secretCount)
344
Python 3
1
2
2
345
20. Python 3 – Regular Expressions Python 3
A regular expression is a special sequence of characters that helps you match or find other
strings or sets of strings, using a specialized syntax held in a pattern. Regular expressions
are widely used in UNIX world.
The module re provides full support for Perl-like regular expressions in Python. The re
module raises the exception re.error if an error occurs while compiling or using a regular
expression.
We would cover two important functions, which would be used to handle regular
expressions. Nevertheless, a small thing first: There are various characters, which would
have special meaning when they are used in regular expression. To avoid any confusion
while dealing with regular expressions, we would use Raw Strings asr'expression'.
Compilation flags
Compilation flags let you modify some aspects of how regular expressions work. Flags are
available in the re module under two names, a long name such as IGNORECASE and a
short, one-letter form such as I.
Flag Meaning
Makes several escapes like \w, \b, \s and \d match only on ASCII
ASCII, A
characters with the respective property.
346
Python 3
VERBOSE, X (for Enable verbose REs, which can be organized more cleanly and
‘extended’) understandably
Parameter Description
flags You can specify different flags using bitwise OR (|). These are
modifiers, which are listed in the table below.
The re.match function returns a match object on success, None on failure. We use
group(num) or groups() function of match object to get matched expression.
group(num=0) This method returns entire match (or specific subgroup num)
Example
#!/usr/bin/python3
import re
347
Python 3
Parameter Description
flags You can specify different flags using bitwise OR (|). These are
modifiers, which are listed in the table below.
group(num=0) This method returns entire match (or specific subgroup num)
348
Python 3
Example
#!/usr/bin/python3
import re
Example
#!/usr/bin/python3
import re
line = "Cats are smarter than dogs";
No match!!
search --> matchObj.group() : dogs
Syntax
re.sub(pattern, repl, string, max=0)
This method replaces all occurrences of the RE pattern in string with repl, substituting all
occurrences unless max is provided. This method returns modified string.
Example
#!/usr/bin/python3
import re
350
Python 3
modifiers using exclusive OR (|), as shown previously and may be represented by one of
these-
Modifier Description
re.M Makes $ match the end of a line (not just the end of the string)
and makes ^ match the start of any line (not just the start of the
string).
re.U Interprets letters according to the Unicode character set. This flag
affects the behavior of \w, \W, \b, \B.
The following table lists the regular expression syntax that is available in Python-
Pattern Description
351
Python 3
a| b Matches either a or b.
(?#...) Comment.
(?= re) Specifies position using a pattern. Does not have a range.
(?! re) Specifies position using pattern negation. Does not have a range.
352
Python 3
\S Matches nonwhitespace.
\D Matches nondigits.
Literal characters
Example Description
353
Python 3
Character classes
Example Description
354
Python 3
Repetition Cases
Example Description
Nongreedy Repetition
This matches the smallest number of repetitions-
Example Description
355
Python 3
Backreferences
This matches a previously matched group again-
Example Description
Alternatives
Example Description
Anchors
This needs to specify match position.
Example Description
\brub\B \B is nonword boundary: match "rub" in "rube" and "ruby" but not
alone
356
Python 3
357
21. Python 3 – CGI Programming Python 3
The Common Gateway Interface, or CGI, is a set of standards that define how information
is exchanged between the web server and a custom script. The CGI specs are currently
maintained by the NCSA and NCSA.
What is CGI?
The Common Gateway Interface, or CGI, is a standard for external gateway
programs to interface with information servers such as HTTP servers.
Web Browsing
To understand the concept of CGI, let us see what happens when we click a hyperlink to
browse a particular web page or URL.
Your browser contacts the HTTP web server and demands for the URL, i.e.,
filename.
The web server parses the URL and looks for the filename. If it finds the particular
file, then it sends it back to the browser, otherwise sends an error message
indicating that you requested a wrong file.
The web browser takes response from the web server and displays either, the
received file or error message.
However, it is possible to set up the HTTP server so that whenever a file in a certain
directory is requested that file is not sent back. Instead, it is executed as a program, and
whatever that output of the program, is sent back for your browser to display. This function
is called the Common Gateway Interface or CGI and the programs are called CGI scripts.
These CGI programs can be Python Script, PERL Script, Shell Script, C or C++ program,
etc.
358
Python 3
By default, the Linux server is configured to run only the scripts in the cgi-bin directory in
/var/www. If you want to specify any other directory to run your CGI scripts, comment
the following lines in the httpd.conf file −
<Directory "/var/www/cgi-bin">
AllowOverride None
Options ExecCGI
Order allow,deny
Allow from all
</Directory>
359
Python 3
<Directory "/var/www/cgi-bin">
Options All
</Directory>
The following line should also be added for apache server to treat .py file as cgi script.
Here, we assume that you have Web Server up and running successfully and you are able
to run any other CGI program like Perl or Shell, etc.
#!/usr/bin/python3
print ("Content-type:text/html")
print()
print ("<html>")
print ('<head>')
print ('<title>Hello Word - First CGI Program</title>')
print ('</head>')
print ('<body>')
print ('<h2>Hello Word! This is my first CGI program</h2>')
print ('</body>')
print ('</html>')
Note: First line in the script must be the path to Python executable. In Linux, it should be
#!/usr/bin/python3
http://www.tutorialspoint.com/cgi-bin/hello.py
This hello.py script is a simple Python script, which writes its output on STDOUT file, i.e.,
the screen. There is one important and extra feature available that is the first line to be
printed Content-type:text/html followed by a blank line. This line is sent back to the
browser and it specifies the content type to be displayed on the browser screen.
360
Python 3
By now, you must have understood the basic concept of CGI and you can write many
complicated CGI programs using Python. This script can interact with any other external
system also to exchange information such as RDBMS.
HTTP Header
The line Content-type:text/html\r\n\r\n is part of HTTP header which is sent to the
browser to understand the content. All the HTTP header will be in the following form-
There are few other important HTTP headers, which you will use frequently in your CGI
Programming.
Header Description
Content-type: A MIME string defining the format of the file being returned.
Example is Content-type:text/html
Expires: Date The date the information becomes invalid. It is used by the
browser to decide when a page needs to be refreshed. A valid
date string is in the format 01 Jan 1998 12:00:00 GMT.
Location: URL The URL that is returned instead of the URL requested. You
can use this field to redirect a request to any file.
Content-length: N The length, in bytes, of the data being returned. The browser
uses this value to report the estimated download time for a
file.
361
Python 3
CONTENT_TYPE The data type of the content. Used when the client is sending
attached content to the server. For example, file upload.
HTTP_COOKIE Returns the set cookies in the form of key & value pair.
REMOTE_ADDR The IP address of the remote host making the request. This
is useful logging or for authentication.
REMOTE_HOST The fully qualified name of the host making the request. If
this information is not available, then REMOTE_ADDR can be
used to get IR address.
REQUEST_METHOD The method used to make the request. The most common
methods are GET and POST.
SERVER_SOFTWARE The name and version of the software the server is running.
Here is a small CGI program to list out all the CGI variables. Click this link to see the
result Get Environment.
#!/usr/bin/python3
import os
print ("Content-type: text/html")
print ()
print ("<font size=+1>Environment</font><\br>";)
362
Python 3
http://www.test.com/cgi-bin/hello.py?key1=value1&key2=value2
The GET method is the default method to pass information from the browser to the
web server and it produces a long string that appears in your browser's
Location:box.
Never use GET method if you have password or other sensitive information to pass
to the server.
The GET method has size limtation: only 1024 characters can be sent in a request
string.
The GET method sends information using QUERY_STRING header and will be
accessible in your CGI Program through QUERY_STRING environment variable.
You can pass information by simply concatenating key and value pairs along with any URL
or you can use HTML <FORM> tags to pass information using GET method.
/cgi-bin/hello_get.py?first_name=Malhar&last_name=Lathkar
Given below is the hello_get.py script to handle the input given by web browser. We are
going to use the cgi module, which makes it very easy to access the passed information-
#!/usr/bin/python3
363
Python 3
print ("Content-type:text/html")
print()
print ("<html>)"
print ("<head>")
print ("<title>Hello - Second CGI Program</title>")
print ("</head>")
print ("<body>")
print ("<h2>Hello %s %s</h2>" % (first_name, last_name))
print ("</body>")
print ("</html>">)
Here is the actual output of the above form, you enter the First and the Last Name and
then click submit button to see the result.
First Name:
Submit
Last Name:
A generally more reliable method of passing information to a CGI program is the POST
method. This packages the information in exactly the same way as the GET methods, but
instead of sending it as a text string after a ? in the URL, it sends it as a separate message.
This message comes into the CGI script in the form of the standard input.
Given below is same hello_get.py script, which handles GET as well as the POST method.
#!/usr/bin/python3
print ("Content-type:text/html")
print()
print ("<html>")
print ("<head>")
print ("<title>Hello - Second CGI Program</title>")
print ("</head>")
print ("<body>")
print ("<h2>Hello %s %s</h2>" % (first_name, last_name))
print ("</body>")
print ("</html>")
Let us again take the same example as above, which passes two values using the HTML
FORM and the submit button. We use the same CGI script hello_get.py to handle this
input.
365
Python 3
Here is the actual output of the above form. You enter the First and the Last Name and
then click the submit button to see the result.
First Name:
Submit
Last Name:
Select Subject
Maths Physics
Given below is the checkbox.cgi script to handle the input given by web browser for
checkbox button.
#!/usr/bin/python3
if form.getvalue('physics'):
physics_flag = "ON"
else:
366
Python 3
physics_flag = "OFF"
print ("Content-type:text/html")
print()
print ("<html>")
print ("<head>")
print ("<title>Checkbox - Third CGI Program</title>")
print ("</head>")
print ("<body>")
print ("<h2> CheckBox Maths is : %s</h2>" % math_flag)
print ("<h2> CheckBox Physics is : %s</h2>" % physics_flag)
print ("</body>")
print ("</html>")
Here is an HTML code example for a form with two radio buttons-
Select Subject
Maths Physics
Below is radiobutton.py script to handle input given by web browser for radio button-
#!/usr/bin/python3
367
Python 3
subject = form.getvalue('subject')
else:
subject = "Not set"
print "Content-type:text/html")
print()
print ("<html>")
print ("<head>")
print ("<title>Radio - Fourth CGI Program</title>")
print ("</head>")
print ("<body>")
print ("<h2> Selected Subject is %s</h2>" % subject)
print ("</body>")
print ("</html>")
Submit
Given below is the textarea.cgi script to handle input given by web browser-
#!/usr/bin/python3
form = cgi.FieldStorage()
print "Content-type:text/html")
print()
print ("<html>")
print ("<head>";)
print ("<title>Text Area - Fifth CGI Program</title>")
print ("</head>")
print ("<body>")
print ("<h2> Entered Text Content is %s</h2>" % text_content)
print ("</body>")
Here is an HTML code example for a form with one drop-down box-
Maths Submit
Following is the dropdown.py script to handle the input given by web browser.
#!/usr/bin/python3
# Import modules for CGI handling
import cgi, cgitb
369
Python 3
print "Content-type:text/html")
print()
print ("<html>")
print ("<head>")
print ("<title>Dropdown Box - Sixth CGI Program</title>")
print ("</head>")
print ("<body>")
print ("<h2> Selected Subject is %s</h2>" % subject)
print ("</body>")
print ("</html>")
In many situations, using cookies is the most efficient method of remembering and
tracking preferences, purchases, commissions, and other information required for better
visitor experience or site statistics.
How It Works?
Your server sends some data to the visitor's browser in the form of a cookie. The browser
may accept the cookie. If it does, it is stored as a plain text record on the visitor's hard
drive. Now, when the visitor arrives at another page on your site, the cookie is available
for retrieval. Once retrieved, your server knows/remembers what was stored.
Expires: The date the cookie will expire. If this is blank, the cookie will expire when
the visitor quits the browser.
370
Python 3
Path: The path to the directory or web page that sets the cookie. This may be
blank if you want to retrieve the cookie from any directory or page.
Secure: If this field contains the word "secure", then the cookie may only be
retrieved with a secure server. If this field is blank, no such restriction exists.
Name=Value: Cookies are set and retrieved in the form of key and value pairs.
Setting up Cookies
It is very easy to send cookies to the browser. These cookies are sent along with the HTTP
Header before the Content-type field is sent. Assuming you want to set the User ID and
Password as cookies, Cookies are set as follows-
#!/usr/bin/python3
print ("Set-Cookie:UserID=XYZ;\r\n")
print ("Set-Cookie:Password=XYZ123;\r\n")
print ("Set-Cookie:Expires=Tuesday, 31-Dec-2007 23:12:40 GMT";\r\n")
print ("Set-Cookie:Domain=www.tutorialspoint.com;\r\n")
print ("Set-Cookie:Path=/perl;\n")
print ("Content-type:text/html\r\n\r\n")
...........Rest of the HTML Content....
From this example, you must have understood how to set cookies. We use Set-
Cookie HTTP header to set the cookies.
It is optional to set cookies attributes like Expires, Domain, and Path. It is notable that the
cookies are set before sending the magic line "Content-type:text/html\r\n\r\n.
Retrieving Cookies
It is very easy to retrieve all the set cookies. Cookies are stored in CGI environment
variable HTTP_COOKIE and they will have the following form-
key1=value1;key2=value2;key3=value3....
#!/usr/bin/python3
if environ.has_key('HTTP_COOKIE'):
for cookie in map(strip, split(environ['HTTP_COOKIE'], ';')):
(key, value ) = split(cookie, '=');
if key == "UserID":
user_id = value
if key == "Password":
password = value
print ("User ID = %s" % user_id)
print ("Password = %s" % password)
This produces the following result for the cookies set by the above script-
User ID = XYZ
Password = XYZ123
<html>
<body>
<form enctype="multipart/form-data"
action="save_file.py" method="post">
<p>File: <input type="file" name="filename" /></p>
<p><input type="submit" value="Upload" /></p>
</form>
</body>
</html>
File:
Upload
The above example has been disabled intentionally to save the people from uploading the
file on our server, but you can try the above code with your server.
372
Python 3
#!/usr/bin/python3
import cgi, os
import cgitb; cgitb.enable()
form = cgi.FieldStorage()
else:
message = 'No file was uploaded'
print ("""\
Content-Type: text/html\n
<html>
<body>
<p>%s</p>
</body>
</html>
""" % (message,))
If you run the above script on Unix/Linux, then you need to take care of replacing file
separator as follows, otherwise on your windows machine above open() statement should
work fine.
373
Python 3
fn = os.path.basename(fileitem.filename.replace("\\", "/" ))
For example, if you want make a FileName file downloadable from a given link, then its
syntax is as follows-
#!/usr/bin/python3
# HTTP Header
print ("Content-Type:application/octet-stream; name=\"FileName\"\r\n")
print ("Content-Disposition: attachment; filename=\"FileName\"\r\n\n")
str = fo.read()
print (str)
374
22. Python 3 – MySQL Database Access Python 3
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
SQLite
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:
Python has an in-built support for SQLite. In this section, we would learn all the concepts
using MySQL. MySQLdb module, a popular interface with MySQL is not compatible with
Python 3. Instead, we shall use PyMySQL module.
What is PyMySQL ?
PyMySQL is an interface for connecting to a MySQL database server from Python. It
implements the Python Database API v2.0 and contains a pure-Python MySQL client
library. The goal of PyMySQL is to be a drop-in replacement for MySQLdb .
375
Python 3
#!/usr/bin/python3
import PyMySQL
If it produces the following result, then it means MySQLdb module is not installed-
The last stable release is available on PyPI and can be installed with pip:
Alternatively (e.g. if pip is not available), a tarball can be downloaded from GitHub and
installed with Setuptools as follows-
Note: Make sure you have root privilege to install the above module.
Database Connection
Before connecting to a MySQL database, make sure of the following points-
376
Python 3
Example
Following is an example of connecting with MySQL database "TESTDB"-
#!/usr/bin/python3
import PyMySQL
# Open database connection
db = PyMySQL.connect("localhost","testuser","test123","TESTDB" )
Example
Let us create a Database table EMPLOYEE-
#!/usr/bin/python3
import PyMySQL
377
Python 3
cursor.execute(sql)
INSERT Operation
The INSERT Operation is required when you want to create your records into a database
table.
Example
The following example, executes SQL INSERT statement to create a record in the
EMPLOYEE table-
#!/usr/bin/python3
import PyMySQL
cursor = db.cursor()
The above example can be written as follows to create SQL queries dynamically-
#!/usr/bin/python3
import PyMySQL
except:
# Rollback in case there is any error
db.rollback()
Example
The following code segment is another form of execution where you can pass parameters
directly-
..................................
user_id = "test123"
password = "password"
READ Operation
READ Operation on any database means to fetch some useful information from the
database.
Once the database connection is established, you are ready to make a query into this
database. You can use either fetchone() method to fetch a single record
or fetchall() method to fetch multiple values from a database table.
fetchone(): It fetches the next row of a query result set. A result set is an object
that is returned when a cursor object is used to query a table.
fetchall(): It fetches all the rows in a result set. If some rows have already been
extracted from the result set, then it retrieves the remaining rows from the result
set.
rowcount: This is a read-only attribute and returns the number of rows that were
affected by an execute() method.
380
Python 3
Example
The following procedure queries all the records from EMPLOYEE table having salary more
than 1000-
#!/usr/bin/python3
import PyMySQL
381
Python 3
Update Operation
UPDATE Operation on any database means to update one or more records, which are
already available in the database.
The following procedure updates all the records having SEX as 'M'. Here, we increase the
AGE of all the males by one year.
Example
#!/usr/bin/python3
import PyMySQL
382
Python 3
DELETE Operation
DELETE operation is required when you want to delete some records from your database.
Following is the procedure to delete all the records from EMPLOYEE where AGE is more
than 20-
Example
#!/usr/bin/python3
import PyMySQL
Performing Transactions
Transactions are a mechanism that ensure data consistency. Transactions have the
following four properties-
Consistency: A transaction must start in a consistent state and leave the system
in a consistent state.
Isolation: Intermediate results of a transaction are not visible outside the current
transaction.
383
Python 3
Durability: Once a transaction was committed, the effects are persistent, even
after a system failure.
The Python DB API 2.0 provides two methods to either commit or rollback a transaction.
Example
You already know how to implement transactions. Here is a similar example-
COMMIT Operation
Commit is an operation, which gives a green signal to the database to finalize the changes,
and after this operation, no change can be reverted back.
db.commit()
ROLLBACK Operation
If you are not satisfied with one or more of the changes and you want to revert back those
changes completely, then use the rollback() method.
db.rollback()
Disconnecting Database
To disconnect the Database connection, use the close() method.
db.close()
If the connection to a database is closed by the user with the close() method, any
outstanding transactions are rolled back by the DB. However, instead of depending on any
384
Python 3
of the DB lower level implementation details, your application would be better off calling
commit or rollback explicitly.
Handling Errors
There are many sources of errors. A few examples are a syntax error in an executed SQL
statement, a connection failure, or calling the fetch method for an already cancelled or
finished statement handle.
The DB API defines a number of errors that must exist in each database module. The
following table lists these exceptions.
Exception Description
InterfaceError Used for errors in the database module, not the database itself.
Must subclass Error.
385
Python 3
Your Python scripts should handle these errors, but before using any of the above
exceptions, make sure your MySQLdb has support for that exception. You can get more
information about them by reading the DB API 2.0 specification.
386
23. Python 3 – Network Programming Python 3
Python provides two levels of access to the network services. At a low level, you can access
the basic socket support in the underlying operating system, which allows you to
implement clients and servers for both connection-oriented and connectionless protocols.
Python also has libraries that provide higher-level access to specific application-level
network protocols, such as FTP, HTTP, and so on.
This chapter gives you an understanding on the most famous concept in Networking -
Socket Programming.
What is Sockets?
Sockets are the endpoints of a bidirectional communications channel. Sockets may
communicate within a process, between processes on the same machine, or between
processes on different continents.
Sockets may be implemented over a number of different channel types: Unix domain
sockets, TCP, UDP, and so on. The socket library provides specific classes for handling the
common transports as well as a generic interface for handling the rest.
Term Description
domain The family of protocols that is used as the transport mechanism. These
values are constants such as AF_INET, PF_INET, PF_UNIX, PF_X25,
and so on.
387
Python 3
port Each server listens for clients calling on one or more ports. A port may
be a Fixnum port number, a string containing a port number, or the
name of a service.
Once you have socket object, then you can use the required functions to create your client
or server program. Following is the list of functions required-
s.bind() This method binds address (hostname, port number pair) to socket.
s.accept() This passively accept TCP client connection, waiting until connection
arrives (blocking).
388
Python 3
A Simple Server
To write Internet servers, we use the socket function available in socket module to create
a socket object. A socket object is then used to call other functions to setup a socket
server.
Now call the bind(hostname, port) function to specify a port for your service on the
given host.
Next, call the accept method of the returned object. This method waits until a client
connects to the port you specified, and then returns a connection object that represents
the connection to that client.
port = 9999
389
Python 3
# queue up to 5 requests
serversocket.listen(5)
while True:
# establish a connection
clientsocket,addr = serversocket.accept()
A Simple Client
Let us write a very simple client program, which opens a connection to a given port 12345
and a given host. It is very simple to create a socket client using the
Python's socket module function.
The following code is a very simple client that connects to a given host and port, reads
any available data from the socket, and then exits-
390
Python 3
print (msg.decode('ascii'))
Now run this server.py in the background and then run the above client.py to see the
result.
on server terminal
391
Python 3
Please check all the libraries mentioned above to work with FTP, SMTP, POP, and IMAP
protocols.
Further Readings
This was a quick start with the Socket Programming. It is a vast subject. It is
recommended to go through the following link to find more detail-
392
24. Python 3 – Sending Email using SMTP Python 3
Simple Mail Transfer Protocol (SMTP) is a protocol, which handles sending an e-mail and
routing e-mail between mail servers.
Python provides smtplib module, which defines an SMTP client session object that can be
used to send mails to any Internet machine with an SMTP or ESMTP listener daemon.
Here is a simple syntax to create one SMTP object, which can later be used to send an e-
mail-
import smtplib
smtpObj = smtplib.SMTP( [host [, port [, local_hostname]]] )
host: This is the host running your SMTP server. You can specifiy IP address of the
host or a domain name like tutorialspoint.com. This is an optional argument.
port: If you are providing host argument, then you need to specify a port, where
SMTP server is listening. Usually this port would be 25.
local_hostname: If your SMTP server is running on your local machine, then you
can specify just localhost as the option.
An SMTP object has an instance method called sendmail, which is typically, used to do
the work of mailing a message. It takes three parameters-
Example
Here is a simple way to send one e-mail using Python script. Try it once-
#!/usr/bin/python3
import smtplib
sender ='[email protected]'
receivers =['[email protected]']
Here, you have placed a basic e-mail in message, using a triple quote, taking care to
format the headers correctly. An e-mail requires a From, To, and a Subject header,
separated from the body of the e-mail with a blank line.
To send the mail you use smtpObj to connect to the SMTP server on the local machine.
Then use the sendmail method along with the message, the from address, and the
destination address as parameters (even though the from and to addresses are within the
e-mail itself, these are not always used to route the mail).
If you are not running an SMTP server on your local machine, you can the usesmtplib client
to communicate with a remote SMTP server. Unless you are using a webmail service (such
as gmail or Yahoo! Mail), your e-mail provider must have provided you with the outgoing
mail server details that you can supply them, as follows-
mail=smtplib.SMTP('smtp.gmail.com', 587)
While sending an e-mail message, you can specify a Mime version, content type and the
character set to send an HTML e-mail.
Example
Following is an example to send the HTML content as an e-mail. Try it once-
#!/usr/bin/python3
import smtplib
394
Python 3
MIME-Version: 1.0
Content-type: text/html
Subject: SMTP HTML e-mail test
try:
smtpObj = smtplib.SMTP('localhost')
smtpObj.sendmail(sender, receivers, message)
print "Successfully sent email"
except SMTPException:
print "Error: unable to send email"
A boundary is started with two hyphens followed by a unique number, which cannot appear
in the message part of the e-mail. A final boundary denoting the e-mail's final section must
also end with two hyphens.
The attached files should be encoded with the pack("m") function to have base 64
encoding before transmission.
Example
Following is an example, which sends a file /tmp/test.txt as an attachment. Try it once-
#!/usr/bin/python3
import smtplib
import base64
filename = "/tmp/test.txt"
marker = "AUNIQUEMARKER"
body ="""
This is a test email to send an attachement.
"""
# Define the main headers.
part1 = """From: From Person <[email protected]>
To: To Person <[email protected]>
Subject: Sending Attachement
MIME-Version: 1.0
Content-Type: multipart/mixed; boundary=%s
--%s
""" % (marker, marker)
%s
--%s
""" % (body,marker)
%s
--%s--
""" %(filename, filename, encodedcontent, marker)
message = part1 + part2 + part3
try:
smtpObj = smtplib.SMTP('localhost')
smtpObj.sendmail(sender, reciever, message)
396
Python 3
397
25. Python 3 – Multithreaded Programming Python 3
Running several threads is similar to running several different programs concurrently, but
with the following benefits-
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 are sometimes called light-weight processes and they do not require much
memory overhead; they are cheaper than processes.
It can temporarily be put on hold (also known as sleeping) while other threads are
running - this is called yielding.
kernel thread
user thread
Kernel Threads are a part of the operating system, while the User-space threads are not
implemented in the kernel.
There are two modules, which support the usage of threads in Python3-
_thread
threading
The thread module has been "deprecated" for quite a long time. Users are encouraged to
use the threading module instead. Hence, in Python 3, the module "thread" is not available
anymore. However, it has been renamed to "_thread" for backward compatibilities in
Python3.
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 agrs. When the function returns, the thread terminates.
398
Python 3
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/python3
import _thread
import time
while 1:
pass
399
Python 3
Program goes in an infinite loop. You will have to press ctrl-c to stop.
Although it is very effective for low-level threading, the thread module is very limited
compared to the newer threading module.
The threading module exposes all the methods of the thread module and provides some
additional methods:
threading.enumerate(): Returns a list of all the 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:
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 the run()method.
Example
#!/usr/bin/python3
400
Python 3
import threading
import time
exitFlag = 0
class myThread (threading.Thread):
def __init__(self, threadID, name, counter):
threading.Thread.__init__(self)
self.threadID = threadID
self.name = name
self.counter = counter
def run(self):
print ("Starting " + self.name)
print_time(self.name, self.counter, 5)
print ("Exiting " + self.name)
Starting Thread-1
Starting Thread-2
Thread-1: Fri Feb 19 10:00:21 2016
Thread-2: Fri Feb 19 10:00:22 2016
Thread-1: Fri Feb 19 10:00:22 2016
401
Python 3
Synchronizing Threads
The threading module provided with Python includes a simple-to-implement locking
mechanism that allows you to synchronize threads. A new lock is created by calling
the Lock() method, which returns the new lock.
The acquire(blocking) method of the new lock object is used to force the threads to run
synchronously. The optional blocking parameter enables you to control whether the thread
waits to acquire the lock.
If blocking is set to 0, the thread returns immediately with a 0 value if the lock cannot be
acquired and with a 1 if the lock was acquired. If blocking is set to 1, the thread blocks
and wait for the lock to be released.
The release() method of the new lock object is used to release the lock when it is no longer
required.
Example
#!/usr/bin/python3
import threading
import time
class myThread (threading.Thread):
def __init__(self, threadID, name, counter):
threading.Thread.__init__(self)
self.threadID = threadID
self.name = name
self.counter = counter
def run(self):
print ("Starting " + self.name)
# Get lock to synchronize threads
threadLock.acquire()
print_time(self.name, self.counter, 3)
402
Python 3
threadLock = threading.Lock()
threads = []
Starting Thread-1
Starting Thread-2
Thread-1: Fri Feb 19 10:04:14 2016
Thread-1: Fri Feb 19 10:04:15 2016
Thread-1: Fri Feb 19 10:04:16 2016
Thread-2: Fri Feb 19 10:04:18 2016
Thread-2: Fri Feb 19 10:04:20 2016
Thread-2: Fri Feb 19 10:04:22 2016
Exiting Main Thread
403
Python 3
get(): The get() removes and returns an item from the queue.
put(): The put adds item to a queue.
qsize() : The qsize() returns the number of items that are currently in the queue.
empty(): The empty( ) returns True if queue is empty; otherwise, False.
full(): the full() returns True if queue is full; otherwise, False.
Example
#!/usr/bin/python3
import queue
import threading
import time
exitFlag = 0
time.sleep(1)
Starting Thread-1
Starting Thread-2
Starting Thread-3
405
Python 3
406
26. Python 3 – XML Processing Python 3
XML is a portable, open source language that allows programmers to develop applications
that can be read by other applications, regardless of operating system and/or
developmental language.
What is XML?
The Extensible Markup Language (XML) is a markup language much like HTML or SGML.
This is recommended by the World Wide Web Consortium and available as an open
standard.
XML is extremely useful for keeping track of small to medium amounts of data without
requiring an SQL- based backbone.
The two most basic and broadly used APIs to XML data are the SAX and DOM interfaces.
Simple API for XML (SAX): Here, you register callbacks for events of interest
and then let the parser proceed through the document. This is useful when your
documents are large or you have memory limitations, it parses the file as it reads
it from the disk and the entire file is never stored in the memory.
Document Object Model (DOM) API: This is a World Wide Web Consortium
recommendation wherein the entire file is read into the memory and stored in a
hierarchical (tree-based) form to represent all the features of an XML document.
SAX obviously cannot process information as fast as DOM, when working with large files.
On the other hand, using DOM exclusively can really kill your resources, especially if used
on many small files.
SAX is read-only, while DOM allows changes to the XML file. Since these two different APIs
literally complement each other, there is no reason why you cannot use them both for
large projects.
For all our XML code examples, let us use a simple XML file movies.xml as an input-
Your ContentHandler handles the particular tags and attributes of your flavor(s) of XML. A
ContentHandler object provides methods to handle various parsing events. Its owning
parser calls ContentHandler methods as it parses the XML file.
The methods startDocument and endDocument are called at the start and the end of the
XML file. The method characters(text) is passed the character data of the XML file via the
parameter text.
The ContentHandler is called at the start and end of each element. If the parser is not in
namespace mode, the methods startElement(tag, attributes) andendElement(tag) are
408
Python 3
xml.sax.make_parser( [parser_list] )
Example
#!/usr/bin/python3
import xml.sax
409
Python 3
self.format = content
elif self.CurrentData == "year":
self.year = content
elif self.CurrentData == "rating":
self.rating = content
elif self.CurrentData == "stars":
self.stars = content
elif self.CurrentData == "description":
self.description = content
if ( __name__ == "__main__"):
# create an XMLReader
parser = xml.sax.make_parser()
# turn off namepsaces
parser.setFeature(xml.sax.handler.feature_namespaces, 0)
parser.parse("movies.xml")
*****Movie*****
Title: Enemy Behind
Type: War, Thriller
Format: DVD
Year: 2003
Rating: PG
Stars: 10
Description: Talk about a US-Japan war
*****Movie*****
Title: Transformers
Type: Anime, Science Fiction
Format: DVD
Year: 1989
Rating: R
Stars: 8
411
Python 3
For a complete detail on SAX API documentation, please refer to the standard Python SAX
APIs.
The DOM is extremely useful for random-access applications. SAX only allows you a view
of one bit of the document at a time. If you are looking at one SAX element, you have no
access to another.
Here is the easiest way to load an XML document quickly and to create a minidom object
using the xml.dom module. The minidom object provides a simple parser method that
quickly creates a DOM tree from the XML file.
The sample phrase calls the parse( file [,parser] ) function of the minidom object to parse
the XML file, designated by file into a DOM tree object.
#!/usr/bin/python3
type = movie.getElementsByTagName('type')[0]
print ("Type: %s" % type.childNodes[0].data)
format = movie.getElementsByTagName('format')[0]
print ("Format: %s" % format.childNodes[0].data)
rating = movie.getElementsByTagName('rating')[0]
print ("Rating: %s" % rating.childNodes[0].data)
description = movie.getElementsByTagName('description')[0]
print ("Description: %s" % description.childNodes[0].data)
413
Python 3
Rating: PG
Description: Vash the Stampede!
*****Movie*****
Title: Ishtar
Type: Comedy
Format: VHS
Rating: PG
Description: Viewable boredom
For a complete detail on DOM API documentation, please refer to the standard Python
DOM APIs.
414
27. Python 3 – GUI Programming (Tkinter) Python 3
Python provides various options for developing graphical user interfaces (GUIs). The most
important features are listed below.
Tkinter: Tkinter is the Python interface to the Tk GUI toolkit shipped with Python.
We would look at this option in this chapter.
wxPython: This is an open-source Python interface for wxWidgets GUI toolkit. You
can find a complete tutorial on WxPython here.
JPython: JPython is a Python port for Java, which gives Python scripts seamless
access to the Java class libraries on the local machinehttp://www.jython.org.
There are many other interfaces available, which you can find them on the net.
Tkinter Programming
Tkinter is the standard GUI library for Python. Python when combined with Tkinter provides
a fast and easy way to create GUI applications. Tkinter provides a powerful object-oriented
interface to the Tk GUI toolkit.
Creating a GUI application using Tkinter is an easy task. All you need to do is perform the
following steps −
Example
#!/usr/bin/python3
import tkinter # note that module name has changed from Tkinter in Python 2 to tkinter in
Python 3
top = tkinter.Tk()
# Code to add widgets will go here...
top.mainloop()
415
Python 3
Tkinter Widgets
Tkinter provides various controls, such as buttons, labels and text boxes used in a GUI
application. These controls are commonly called widgets.
There are currently 15 types of widgets in Tkinter. We present these widgets as well as a
brief description in the following table-
Operator Description
416
Python 3
417
Python 3
Tkinter Button
The Button widget is used to add buttons in a Python application. These buttons can display
text or images that convey the purpose of the buttons. You can attach a function or a
method to a button which is called automatically when you click the button.
Syntax
Here is the simple syntax to create this widget-
Parameters
master: This represents the parent window.
options: Here is the list of most commonly used options for this widget. These
options can be used as key-value pairs separated by commas.
Option Description
height Height of the button in text lines (for textual buttons) or pixels
(for images).
418
Python 3
highlightcolor The color of the focus highlight when the widget has focus.
justify How to show multiple text lines: LEFT to left-justify each line;
CENTER to center them; or RIGHT to right-justify.
relief Relief specifies the type of the border. Some of the values are
SUNKEN, RAISED, GROOVE, and RIDGE.
state Set this option to DISABLED to gray out the button and make it
unresponsive. Has the value ACTIVE when the mouse is over it.
Default is NORMAL.
underline Default is -1, meaning that no character of the text on the button
will be underlined. If nonnegative, the corresponding text
character will be underlined.
width Width of the button in letters (if displaying text) or pixels (if
displaying an image).
wraplength If this value is set to a positive number, the text lines will be
wrapped to fit within this length.
Methods
Following are commonly used methods for this widget-
Method Description
flash() Causes the button to flash several times between active and normal
colors. Leaves the button in the state it was in originally. Ignored if
the button is disabled.
invoke() Calls the button's callback, and returns what that function returns. Has
no effect if the button is disabled or there is no callback.
419
Python 3
Example
Try the following example yourself-
# !/usr/bin/python3
from tkinter import *
from tkinter import messagebox
top = Tk()
top.geometry("100x100")
def helloCallBack():
msg=messagebox.showinfo( "Hello Python", "Hello World")
B = Button(top, text ="Hello", command = helloCallBack)
B.place(x=50,y=50)
top.mainloop()
Tkinter Canvas
The Canvas is a rectangular area intended for drawing pictures or other complex layouts.
You can place graphics, text, widgets or frames on a Canvas.
Syntax
Here is the simple syntax to create this widget-
Parameters
master: This represents the parent window.
options: Here is the list of most commonly used options for this widget. These
options can be used as key-value pairs separated by commas.
420
Python 3
Option Description
confine If true (the default), the canvas cannot be scrolled outside of the
scrollregion.
cursor Cursor used in the canvas like arrow, circle, dot etc.
relief Relief specifies the type of the border. Some of the values are
SUNKEN, RAISED, GROOVE, and RIDGE.
scrollregion A tuple (w, n, e, s) that defines over how large an area the canvas
can be scrolled, where w is the left side, n the top, e the right side,
and s the bottom.
xscrollincrement If you set this option to some positive dimension, the canvas can be
positioned only on multiples of that distance, and the value will be
used for scrolling by scrolling units, such as when the user clicks on
the arrows at the ends of a scrollbar.
xscrollcommand If the canvas is scrollable, this attribute should be the .set() method
of the horizontal scrollbar.
yscrollcommand If the canvas is scrollable, this attribute should be the .set() method
of the vertical scrollbar.
arc . Creates an arc item, which can be a chord, a pieslice or a simple arc.
421
Python 3
image . Creates an image item, which can be an instance of either the BitmapImage or
the PhotoImage classes.
oval . Creates a circle or an ellipse at the given coordinates. It takes two pairs of
coordinates; the top left and bottom right corners of the bounding rectangle for the oval.
polygon . Creates a polygon item that must have at least three vertices.
Example
Try the following example yourself-
# !/usr/bin/python3
from tkinter import *
top = Tk()
422
Python 3
Tkinter Checkbutton
The Checkbutton widget is used to display a number of options to a user as toggle buttons.
The user can then select one or more options by clicking the button corresponding to each
option.
Syntax
Here is the simple syntax to create this widget-
Parameters
master: This represents the parent window.
options: Here is the list of most commonly used options for this widget. These
options can be used as key-value pairs separated by commas.
Option Description
423
Python 3
command A procedure to be called every time the user changes the state of
this checkbutton.
cursor If you set this option to a cursor name (arrow, dot etc.), the
mouse cursor will change to that pattern when it is over the
checkbutton.
highlightcolor The color of the focus highlight when the checkbutton has the
focus.
justify If the text contains multiple lines, this option controls how the
text is justified: CENTER, LEFT, or RIGHT.
424
Python 3
padx How much space to leave to the left and right of the checkbutton
and text. Default is 1 pixel.
pady How much space to leave above and below the checkbutton and
text. Default is 1 pixel.
relief With the default value, relief=FLAT, the checkbutton does not
stand out from its background. You may set this option to any of
the other styles
selectimage If you set this option to an image, that image will appear in the
checkbutton when it is set.
text The label displayed next to the checkbutton. Use newlines ("\n")
to display multiple lines of text.
underline With the default value of -1, none of the characters of the text
label are underlined. Set this option to the index of a character in
the text (counting from zero) to underline that character.
variable The control variable that tracks the current state of the
checkbutton. Normally this variable is an IntVar, and 0 means
cleared and 1 means set, but see the offvalue and onvalue options
above.
wraplength Normally, lines are not wrapped. You can set this option to a
number of characters and all lines will be broken into pieces no
longer than that number.
Methods
Following are commonly used methods for this widget-
425
Python 3
Method Description
flash() Flashes the checkbutton a few times between its active and normal
colors, but leaves it the way it started.
invoke() You can call this method to get the same actions that would occur if
the user clicked on the checkbutton to change its state.
Example
Try the following example yourself-
# !/usr/bin/python3
from tkinter import *
import tkinter
top = Tk()
CheckVar1 = IntVar()
CheckVar2 = IntVar()
C1 = Checkbutton(top, text = "Music", variable = CheckVar1, \
onvalue = 1, offvalue = 0, height=5, \
width = 20, )
C2 = Checkbutton(top, text = "Video", variable = CheckVar2, \
onvalue = 1, offvalue = 0, height=5, \
width = 20)
C1.pack()
C2.pack()
top.mainloop()
426
Python 3
Tkinter Entry
The Entry widget is used to accept single-line text strings from a user.
If you want to display multiple lines of text that can be edited, then you should use
the Text widget.
If you want to display one or more lines of text that cannot be modified by the
user, then you should use the Label widget.
Syntax
Here is the simple syntax to create this widget-
Parameters
master: This represents the parent window.
options: Here is the list of most commonly used options for this widget. These
options can be used as key-value pairs separated by commas.
Option Description
427
Python 3
command A procedure to be called every time the user changes the state of
this checkbutton.
cursor If you set this option to a cursor name (arrow, dot etc.), the mouse
cursor will change to that pattern when it is over the checkbutton.
highlightcolor The color of the focus highlight when the checkbutton has the
focus.
justify If the text contains multiple lines, this option controls how the text
is justified: CENTER, LEFT, or RIGHT.
relief With the default value, relief=FLAT, the checkbutton does not
stand out from its background. You may set this option to any of
the other styles
selectborderwidth The width of the border to use around selected text. The default is
one pixel.
show Normally, the characters that the user types appear in the entry.
To make a .password. entry that echoes each character as an
asterisk, set show="*".
textvariable In order to be able to retrieve the current text from your entry
widget, you must set this option to an instance of the StringVar
class.
428
Python 3
xscrollcommand If you expect that users will often enter more text than the
onscreen size of the widget, you can link your entry widget to a
scrollbar.
Methods
Following are commonly used methods for this widget-
Method Description
delete ( first, last=None ) Deletes characters from the widget, starting with
the one at index first, up to but not including the
character at position last. If the second argument
is omitted, only the single character at position
first is deleted.
icursor ( index ) Set the insertion cursor just before the character
at the given index.
429
Python 3
select_range ( start, end ) Sets the selection under program control. Selects
the text starting at the start index, up to but not
including the character at the end index. The start
position must be before the end position.
select_to ( index ) Selects all the text from the ANCHOR position up
to but not including the character at the given
index.
xview_scroll ( number, what ) Used to scroll the entry horizontally. The what
argument must be either UNITS, to scroll by
character widths, or PAGES, to scroll by chunks
the size of the entry widget. The number is
positive to scroll left to right, negative to scroll
right to left.
Example
Try the following example yourself-
# !/usr/bin/python3
from tkinter import *
top = Tk()
L1 = Label(top, text="User Name")
L1.pack( side = LEFT)
E1 = Entry(top, bd =5)
E1.pack(side = RIGHT)
top.mainloop()
430
Python 3
Tkinter Frame
The Frame widget is very important for the process of grouping and organizing other
widgets in a somehow friendly way. It works like a container, which is responsible for
arranging the position of other widgets.
It uses rectangular areas in the screen to organize the layout and to provide padding of
these widgets. A frame can also be used as a foundation class to implement complex
widgets.
Syntax
Here is the simple syntax to create this widget-
Parameters
master: This represents the parent window.
options: Here is the list of most commonly used options for this widget. These
options can be used as key-value pairs separated by commas.
Options Description
cursor If you set this option to a cursor name (arrow, dot etc.), the
mouse cursor will change to that pattern when it is over the
checkbutton.
highlightbackground Color of the focus highlight when the frame does not have focus.
highlightcolor Color shown in the focus highlight when the frame has the focus.
431
Python 3
relief With the default value, relief=FLAT, the checkbutton does not
stand out from its background. You may set this option to any
of the other styles
Example
Try the following example yourself-
# !/usr/bin/python3
from tkinter import *
root = Tk()
frame = Frame(root)
frame.pack()
bottomframe = Frame(root)
bottomframe.pack( side = BOTTOM )
root.mainloop()
432
Python 3
Tkinter Label
This widget implements a display box where you can place text or images. The text
displayed by this widget can be updated at any time you want.
It is also possible to underline part of the text (like to identify a keyboard shortcut) and
span the text across multiple lines.
Syntax
Here is the simple syntax to create this widget-
Parameters
master: This represents the parent window.
options: Here is the list of most commonly used options for this widget. These
options can be used as key-value pairs separated by commas.
Options Description
anchor This options controls where the text is positioned if the widget has
more space than the text needs. The default is anchor=CENTER, which
centers the text in the available space.
bg The normal background color displayed behind the label and indicator.
bitmap Set this option equal to a bitmap or image object and the label will
display that graphic.
cursor If you set this option to a cursor name (arrow, dot etc.), the mouse
cursor will change to that pattern when it is over the checkbutton.
font If you are displaying text in this label (with the text or textvariable
option, the font option specifies in what font that text will be displayed.
433
Python 3
fg If you are displaying text or a bitmap in this label, this option specifies
the color of the text. If you are displaying a bitmap, this is the color
that will appear at the position of the 1-bits in the bitmap.
image To display a static image in the label widget, set this option to an
image object.
justify Specifies how multiple lines of text will be aligned with respect to each
other: LEFT for flush left, CENTER for centered (the default), or RIGHT
for right-justified.
padx Extra space added to the left and right of the text within the widget.
Default is 1.
pady Extra space added above and below the text within the widget. Default
is 1.
relief Specifies the appearance of a decorative border around the label. The
default is FLAT; for other values.
text To display one or more lines of text in a label widget, set this option
to a string containing the text. Internal newlines ("\n") will force a line
break.
underline You can display an underline (_) below the nth letter of the text,
counting from 0, by setting this option to n. The default is underline=-
1, which means no underlining.
width Width of the label in characters (not pixels!). If this option is not set,
the label will be sized to fit its contents.
wraplength You can limit the number of characters in each line by setting this
option to the desired number. The default value, 0, means that lines
will be broken only at newlines.
434
Python 3
Example
Try the following example yourself-
# !/usr/bin/python3
from tkinter import *
root = Tk()
var = StringVar()
label = Label( root, textvariable=var, relief=RAISED )
Tkinter Listbox
The Listbox widget is used to display a list of items from which a user can select a number
of items
Syntax
Here is the simple syntax to create this widget-
Parameters
master: This represents the parent window.
options: Here is the list of most commonly used options for this widget. These
options can be used as key-value pairs separated by commas.
Options Description
435
Python 3
cursor The cursor that appears when the mouse is over the listbox.
highlightcolor Color shown in the focus highlight when the widget has the
focus.
selectmode Determines how many items can be selected, and how mouse
drags affect the selection:
SINGLE: You can only select one line, and you can't
drag the mouse.wherever you click button 1, that line
is selected.
436
Python 3
xscrollcommand If you want to allow the user to scroll the listbox horizontally,
you can link your listbox widget to a horizontal scrollbar.
yscrollcommand If you want to allow the user to scroll the listbox vertically,
you can link your listbox widget to a vertical scrollbar.
Methods
Methods on listbox objects include-
Options Description
delete ( first, last=None ) Deletes the lines whose indices are in the range [first,
last]. If the second argument is omitted, the single line
with index first is deleted.
get ( first, last=None ) Returns a tuple containing the text of the lines with
indices from first to last, inclusive. If the second
argument is omitted, returns the text of the line closest
to first.
insert ( index, *elements ) Insert one or more new lines into the listbox before the
line specified by index. Use END as the first argument
if you want to add new lines to the end of the listbox.
see ( index ) Adjust the position of the listbox so that the line
referred to by index is visible.
437
Python 3
xview_moveto ( fraction ) Scroll the listbox so that the leftmost fraction of the
width of its longest line is outside the left side of the
listbox. Fraction is in the range [0,1].
xview_scroll ( number, what ) Scrolls the listbox horizontally. For the what argument,
use either UNITS to scroll by characters, or PAGES to
scroll by pages, that is, by the width of the listbox. The
number argument tells how many to scroll.
yview_moveto ( fraction ) Scroll the listbox so that the top fraction of the width of
its longest line is outside the left side of the listbox.
Fraction is in the range [0,1].
yview_scroll ( number, what ) Scrolls the listbox vertically. For the what argument,
use either UNITS to scroll by lines, or PAGES to scroll
by pages, that is, by the height of the listbox. The
number argument tells how many to scroll.
Example
Try the following example yourself-
# !/usr/bin/python3
from tkinter import *
import tkinter
top = Tk()
Lb1 = Listbox(top)
Lb1.insert(1, "Python")
Lb1.insert(2, "Perl")
Lb1.insert(3, "C")
Lb1.insert(4, "PHP")
438
Python 3
Lb1.insert(5, "JSP")
Lb1.insert(6, "Ruby")
Lb1.pack()
top.mainloop()
Tkinter Menubutton
A menubutton is the part of a drop-down menu that stays on the screen all the time. Every
menubutton is associated with a Menu widget that can display the choices for that
menubutton when the user clicks on it.
Syntax
Here is the simple syntax to create this widget-
Parameters
master: This represents the parent window.
options: Here is the list of most commonly used options for this widget. These
options can be used as key-value pairs separated by commas.
Options Description
activebackground The background color when the mouse is over the menubutton.
activeforeground The foreground color when the mouse is over the menubutton.
439
Python 3
anchor This options controls where the text is positioned if the widget
has more space than the text needs. The default is
anchor=CENTER, which centers the text.
cursor The cursor that appears when the mouse is over this menubutton.
direction Set direction=LEFT to display the menu to the left of the button;
use direction=RIGHT to display the menu to the right of the
button; or use direction='above' to place the menu above the
button.
height The height of the menubutton in lines of text (not pixels!). The
default is to fit the menubutton's size to its contents.
highlightcolor Color shown in the focus highlight when the widget has the focus.
justify This option controls where the text is located when the text
doesn't fill the menubutton: use justify=LEFT to left-justify the
text (this is the default); use justify=CENTER to center it, or
justify=RIGHT to right-justify.
menu To associate the menubutton with a set of choices, set this option
to the Menu object containing those choices. That menu object
must have been created by passing the associated menubutton
to the constructor as its first argument.
440
Python 3
padx How much space to leave to the left and right of the text of the
menubutton. Default is 1.
pady How much space to leave above and below the text of the
menubutton. Default is 1.
text To display text on the menubutton, set this option to the string
containing the desired text. Newlines ("\n") within the string will
cause line breaks.
textvariable You can associate a control variable of class StringVar with this
menubutton. Setting that control variable will change the
displayed text.
wraplength Normally, lines are not wrapped. You can set this option to a
number of characters and all lines will be broken into pieces no
longer than that number.
Example
Try the following example yourself-
# !/usr/bin/python3
from tkinter import *
import tkinter
top = Tk()
mb.grid()
mb.menu = Menu ( mb, tearoff = 0 )
mb["menu"] = mb.menu
mayoVar = IntVar()
ketchVar = IntVar()
mb.menu.add_checkbutton ( label="mayo",
variable=mayoVar )
mb.menu.add_checkbutton ( label="ketchup",
variable=ketchVar )
mb.pack()
top.mainloop()
Tkinter Menu
The goal of this widget is to allow us to create all kinds of menus that can be used by our
applications. The core functionality provides ways to create three menu types: pop-up,
toplevel and pull-down.
It is also possible to use other extended widgets to implement new types of menus, such
as the OptionMenu widget, which implements a special type that generates a pop-up list
of items within a selection.
Syntax
Here is the simple syntax to create this widget-
Parameters
master: This represents the parent window.
442
Python 3
options: Here is the list of most commonly used options for this widget. These
options can be used as key-value pairs separated by commas.
Options Description
activebackground The background color that will appear on a choice when it is under
the mouse.
activeforeground The foreground color that will appear on a choice when it is under
the mouse.
cursor The cursor that appears when the mouse is over the choices, but
only when the menu has been torn off.
disabledforeground The color of the text for items whose state is DISABLED.
fg The foreground color used for choices not under the mouse.
postcommand You can set this option to a procedure, and that procedure will be
called every time someone brings up this menu.
tearoff Normally, a menu can be torn off, the first position (position 0) in
the list of choices is occupied by the tear-off element, and the
additional choices are added starting at position 1. If you set
443
Python 3
tearoff=0, the menu will not have a tear-off feature, and choices
will be added starting at position 0.
title Normally, the title of a tear-off menu window will be the same as
the text of the menubutton or cascade that lead to this menu. If
you want to change the title of that window, set the title option to
that string.
Methods
These methods are available on Menu objects-
Option Description
add( type, options ) Adds a specific type of menu item to the menu.
delete( startindex [, endindex ]) Deletes the menu items ranging from startindex to
endindex.
entryconfig( index, options ) Allows you to modify a menu item, which is identified
by the index, and change its options.
444
Python 3
Example
Try the following example yourself-
# !/usr/bin/python3
from tkinter import *
def donothing():
filewin = Toplevel(root)
button = Button(filewin, text="Do nothing button")
button.pack()
root = Tk()
menubar = Menu(root)
filemenu = Menu(menubar, tearoff=0)
filemenu.add_command(label="New", command=donothing)
filemenu.add_command(label="Open", command=donothing)
filemenu.add_command(label="Save", command=donothing)
filemenu.add_command(label="Save as...", command=donothing)
filemenu.add_command(label="Close", command=donothing)
filemenu.add_separator()
filemenu.add_command(label="Exit", command=root.quit)
menubar.add_cascade(label="File", menu=filemenu)
editmenu = Menu(menubar, tearoff=0)
editmenu.add_command(label="Undo", command=donothing)
445
Python 3
editmenu.add_separator()
editmenu.add_command(label="Cut", command=donothing)
editmenu.add_command(label="Copy", command=donothing)
editmenu.add_command(label="Paste", command=donothing)
editmenu.add_command(label="Delete", command=donothing)
editmenu.add_command(label="Select All", command=donothing)
menubar.add_cascade(label="Edit", menu=editmenu)
helpmenu = Menu(menubar, tearoff=0)
helpmenu.add_command(label="Help Index", command=donothing)
helpmenu.add_command(label="About...", command=donothing)
menubar.add_cascade(label="Help", menu=helpmenu)
root.config(menu=menubar)
root.mainloop()
Tkinter Message
This widget provides a multiline and noneditable object that displays texts, automatically
breaking lines and justifying their contents.
Its functionality is very similar to the one provided by the Label widget, except that it can
also automatically wrap the text, maintaining a given width or aspect ratio.
Syntax
446
Python 3
Parameters
master: This represents the parent window.
options: Here is the list of most commonly used options for this widget. These
options can be used as key-value pairs separated by commas.
Options Description
anchor This options controls where the text is positioned if the widget has
more space than the text needs. The default is anchor=CENTER, which
centers the text in the available space.
bg The normal background color displayed behind the label and indicator.
bitmap Set this option equal to a bitmap or image object and the label will
display that graphic.
cursor If you set this option to a cursor name (arrow, dot etc.), the mouse
cursor will change to that pattern when it is over the checkbutton.
font If you are displaying text in this label (with the text or textvariable
option, the font option specifies in what font that text will be displayed.
fg If you are displaying text or a bitmap in this label, this option specifies
the color of the text. If you are displaying a bitmap, this is the color
that will appear at the position of the 1-bits in the bitmap.
image To display a static image in the label widget, set this option to an
image object.
justify Specifies how multiple lines of text will be aligned with respect to each
other: LEFT for flush left, CENTER for centered (the default), or RIGHT
for right-justified.
447
Python 3
padx Extra space added to the left and right of the text within the widget.
Default is 1.
pady Extra space added above and below the text within the widget. Default
is 1.
relief Specifies the appearance of a decorative border around the label. The
default is FLAT; for other values.
text To display one or more lines of text in a label widget, set this option
to a string containing the text. Internal newlines ("\n") will force a line
break.
underline You can display an underline (_) below the nth letter of the text,
counting from 0, by setting this option to n. The default is underline=-
1, which means no underlining.
width Width of the label in characters (not pixels!). If this option is not set,
the label will be sized to fit its contents.
wraplength You can limit the number of characters in each line by setting this
option to the desired number. The default value, 0, means that lines
will be broken only at newlines.
Example
Try the following example yourself-
# !/usr/bin/python3
from tkinter import *
root = Tk()
var = StringVar()
label = Message( root, textvariable=var, relief=RAISED )
448
Python 3
root.mainloop()
Tkinter Radiobutton
This widget implements a multiple-choice button, which is a way to offer many possible
selections to the user and lets user choose only one of them.
Syntax
Here is the simple syntax to create this widget-
Parameters
master: This represents the parent window.
options: Here is the list of most commonly used options for this widget. These
options can be used as key-value pairs separated by commas.
Options Description
activebackground The background color when the mouse is over the radiobutton.
activeforeground The foreground color when the mouse is over the radiobutton.
anchor If the widget inhabits a space larger than it needs, this option
specifies where the radiobutton will sit in that space. The default
is anchor=CENTER.
449
Python 3
borderwidth The size of the border around the indicator part itself. Default is
2 pixels.
command A procedure to be called every time the user changes the state
of this radiobutton.
cursor If you set this option to a cursor name (arrow, dot etc.), the
mouse cursor will change to that pattern when it is over the
radiobutton.
highlightbackground The color of the focus highlight when the radiobutton does not
have focus.
highlightcolor The color of the focus highlight when the radiobutton has the
focus.
justify If the text contains multiple lines, this option controls how the
text is justified: CENTER (the default), LEFT, or RIGHT.
padx How much space to leave to the left and right of the radiobutton
and text. Default is 1.
pady How much space to leave above and below the radiobutton and
text. Default is 1.
450
Python 3
selectimage If you are using the image option to display a graphic instead of
text when the radiobutton is cleared, you can set the
selectimage option to a different image that will be displayed
when the radiobutton is set.
text The label displayed next to the radiobutton. Use newlines ("\n")
to display multiple lines of text.
underline You can display an underline (_) below the nth letter of the text,
counting from 0, by setting this option to n. The default is
underline=-1, which means no underlining.
variable The control variable that this radiobutton shares with the other
radiobuttons in the group. This can be either an IntVar or a
StringVar.
width Width of the label in characters (not pixels!). If this option is not
set, the label will be sized to fit its contents.
wraplength You can limit the number of characters in each line by setting
this option to the desired number. The default value, 0, means
that lines will be broken only at newlines.
Methods
These methods are available.
Methods Description
451
Python 3
flash() Flashes the radiobutton a few times between its active and normal
colors, but leaves it the way it started.
invoke() You can call this method to get the same actions that would occur if
the user clicked on the radiobutton to change its state.
Example
Try the following example yourself-
# !/usr/bin/python3
from tkinter import *
def sel():
selection = "You selected the option " + str(var.get())
label.config(text = selection)
root = Tk()
var = IntVar()
R1 = Radiobutton(root, text="Option 1", variable=var, value=1,
command=sel)
R1.pack( anchor = W )
label = Label(root)
label.pack()
root.mainloop()
452
Python 3
Tkinter Scale
The Scale widget provides a graphical slider object that allows you to select values from a
specific scale.
Syntax
Here is the simple syntax to create this widget-
Parameters
master: This represents the parent window.
options: Here is the list of most commonly used options for this widget. These
options can be used as key-value pairs separated by commas.
Options Description
activebackground The background color when the mouse is over the scale.
bg The background color of the parts of the widget that are outside
the trough.
bd Width of the 3-d border around the trough and slider. Default is
2 pixels.
453
Python 3
cursor If you set this option to a cursor name (arrow, dot etc.), the
mouse cursor will change to that pattern when it is over the
scale.
digits The way your program reads the current value shown in a scale
widget is through a control variable. The control variable for a
scale can be an IntVar, a DoubleVar (float), or a StringVar. If it
is a string variable, the digits option controls how many digits
to use when the numeric scale value is converted to a string.
fg The color of the text used for the label and annotations.
from_ A float or integer value that defines one end of the scale's range.
highlightbackground The color of the focus highlight when the scale does not have
focus.
highlightcolor The color of the focus highlight when the scale has the focus.
label You can display a label within the scale widget by setting this
option to the label's text. The label appears in the top left corner
if the scale is horizontal, or the top right corner if vertical. The
default is no label.
length The length of the scale widget. This is the x dimension if the
scale is horizontal, or the y dimension if vertical. The default is
100 pixels.
orient Set orient=HORIZONTAL if you want the scale to run along the
x dimension, or orient=VERTICAL to run parallel to the y-axis.
Default is horizontal.
repeatdelay This option controls how long button 1 has to be held down in
the trough before the slider starts moving in that direction
repeatedly. Default is repeatdelay=300, and the units are
milliseconds.
resolution Normally, the user will only be able to change the scale in whole
units. Set this option to some other value to change the smallest
454
Python 3
showvalue Normally, the current value of the scale is displayed in text form
by the slider (above it for horizontal scales, to the left for vertical
scales). Set this option to 0 to suppress that label.
sliderlength Normally the slider is 30 pixels along the length of the scale.
You can change that length by setting the sliderlength option to
your desired length.
takefocus Normally, the focus will cycle through scale widgets. Set this
option to 0 if you don't want this behavior.
to A float or integer value that defines one end of the scale's range;
the other end is defined by the from_ option, discussed above.
The to value can be either greater than or less than the from_
value. For vertical scales, the to value defines the bottom of the
scale; for horizontal scales, the right end.
variable The control variable for this scale, if any. Control variables may
be from class IntVar, DoubleVar (float), or StringVar. In the
latter case, the numerical value will be converted to a string.
width The width of the trough part of the widget. This is the x
dimension for vertical scales and the y dimension if the scale
has orient=HORIZONTAL. Default is 15 pixels.
Methods
Scale objects have these methods-
455
Python 3
Methods Description
Example
Try the following example yourself-
# !/usr/bin/python3
from tkinter import *
def sel():
selection = "Value = " + str(var.get())
label.config(text = selection)
root = Tk()
var = DoubleVar()
scale = Scale( root, variable = var )
scale.pack(anchor=CENTER)
label = Label(root)
label.pack()
root.mainloop()
456
Python 3
Tkinter Scrollbar
This widget provides a slide controller that is used to implement vertical scrolled widgets,
such as Listbox, Text and Canvas. Note that you can also create horizontal scrollbars on
Entry widgets.
Syntax
Here is the simple syntax to create this widget-
Parameters
master: This represents the parent window.
options: Here is the list of most commonly used options for this widget. These
options can be used as key-value pairs separated by commas.
Options Description
activebackground The color of the slider and arrowheads when the mouse is over
them.
bg The color of the slider and arrowheads when the mouse is not
over them.
bd The width of the 3-d borders around the entire perimeter of the
trough, and also the width of the 3-d effects on the arrowheads
and slider. Default is no border around the trough, and a 2-pixel
border around the arrowheads and slider.
457
Python 3
cursor The cursor that appears when the mouse is over the scrollbar.
elementborderwidth The width of the borders around the arrowheads and slider. The
default is elementborderwidth=-1, which means to use the
value of the borderwidth option.
highlightbackground The color of the focus highlight when the scrollbar does not have
focus.
highlightcolor The color of the focus highlight when the scrollbar has the focus.
jump This option controls what happens when a user drags the slider.
Normally (jump=0), every small drag of the slider causes the
command callback to be called. If you set this option to 1, the
callback isn't called until the user releases the mouse button.
repeatdelay This option controls how long button 1 has to be held down in
the trough before the slider starts moving in that direction
repeatedly. Default is repeatdelay=300, and the units are
milliseconds.
repeatinterval repeatinterval
takefocus Normally, you can tab the focus through a scrollbar widget. Set
takefocus=0 if you don't want this behavior.
Methods
Scrollbar objects have these methods-
Methods Description
458
Python 3
get() Returns two numbers (a, b) describing the current position of the
slider. The a value gives the position of the left or top edge of the
slider, for horizontal and vertical scrollbars respectively; the b value
gives the position of the right or bottom edge.
set ( first, last ) To connect a scrollbar to another widget w, set w's xscrollcommand
or yscrollcommand to the scrollbar's set() method. The arguments
have the same meaning as the values returned by the get() method.
Example
Try the following example yourself-
# !/usr/bin/python3
from tkinter import *
root = Tk()
scrollbar = Scrollbar(root)
scrollbar.pack( side = RIGHT, fill=Y )
mainloop()
459
Python 3
Tkinter Text
Text widgets provide advanced capabilities that allow you to edit a multiline text and
format the way it has to be displayed, such as changing its color and font.
You can also use elegant structures like tabs and marks to locate specific sections of the
text, and apply changes to those areas. Moreover, you can embed windows and images in
the text because this widget was designed to handle both plain and formatted text.
Syntax
Here is the simple syntax to create this widget-
Parameters
master: This represents the parent window.
options: Here is the list of most commonly used options for this widget. These
options can be used as key-value pairs separated by commas.
Options Description
cursor The cursor that will appear when the mouse is over the text
widget.
font The default font for text inserted into the widget.
fg The color used for text (and bitmaps) within the widget. You can
change the color for tagged regions; this option is just the
default.
460
Python 3
highlightbackground The color of the focus highlight when the text widget does not
have focus.
highlightcolor The color of the focus highlight when the text widget has the
focus.
insertborderwidth Size of the 3-D border around the insertion cursor. Default is 0.
insertofftime The number of milliseconds the insertion cursor is off during its
blink cycle. Set this option to zero to suppress blinking. Default
is 300.
padx The size of the internal padding added to the left and right of
the text area. Default is one pixel.
pady The size of the internal padding added above and below the text
area. Default is one pixel.
spacing1 This option specifies how much extra vertical space is put above
each line of text. If a line wraps, this space is added only before
the first line it occupies on the display. Default is 0.
461
Python 3
spacing2 This option specifies how much extra vertical space to add
between displayed lines of text when a logical line wraps.
Default is 0.
spacing3 This option specifies how much extra vertical space is added
below each line of text. If a line wraps, this space is added only
after the last line it occupies on the display. Default is 0.
wrap This option controls the display of lines that are too wide. Set
wrap=WORD and it will break the line after the last word that
will fit. With the default behavior, wrap=CHAR, any line that
gets too long will be broken at any character.
xscrollcommand To make the text widget horizontally scrollable, set this option
to the set() method of the horizontal scrollbar.
yscrollcommand To make the text widget vertically scrollable, set this option to
the set() method of the vertical scrollbar.
Methods
Text objects have these methods-
delete(startindex [,endindex])
This method deletes a specific character or a range of text.
get(startindex [,endindex])
This method returns a specific character or a range of text.
index(index)
Returns the absolute value of an index based on the given index.
462
Python 3
insert(index [,string]...)
This method inserts strings at the specified index location.
see(index)
This method returns true if the text located at the index position is visible.
Text widgets support three distinct helper structures: Marks, Tabs, and Indexes-
Marks are used to bookmark positions between two characters within a given text. We
have the following methods available when handling marks:
index(mark)
Returns the line and column location of a specific mark.
mark_gravity(mark [,gravity])
Returns the gravity of the given mark. If the second argument is provided, the
gravity is set for the given mark.
mark_names()
Returns all marks from the Text widget.
mark_set(mark, index)
Informs a new position to the given mark.
mark_unset(mark)
Removes the given mark from the Text widget.
Tags are used to associate names to regions of text which makes easy the task of
modifying the display settings of specific text areas. Tags are also used to bind event
callbacks to specific ranges of text.
tag_config
You can use this method to configure the tag properties, which include, justify(center,
left, or right), tabs(this property has the same functionality of the Text widget tabs's
property), and underline(used to underline the tagged text).
463
Python 3
tag_delete(tagname)
This method is used to delete and remove a given tag.
Example
Try the following example yourself-
# !/usr/bin/python3
from tkinter import *
root = Tk()
text = Text(root)
text.insert(INSERT, "Hello.....")
text.insert(END, "Bye Bye.....")
text.pack()
Tkinter Toplevel
Toplevel widgets work as windows that are directly managed by the window manager.
They do not necessarily have a parent widget on top of them.
464
Python 3
Syntax
Here is the simple syntax to create this widget-
Parameters
options: Here is the list of most commonly used options for this widget. These options
can be used as key-value pairs separated by commas.
Options Description
cursor The cursor that appears when the mouse is in this window.
font The default font for text inserted into the widget.
fg The color used for text (and bitmaps) within the widget. You can
change the color for tagged regions; this option is just the default.
relief Normally, a top-level window will have no 3-d borders around it. To
get a shaded border, set the bd option larger that its default value of
zero, and set the relief option to one of the constants.
Methods
Toplevel objects have these methods-
deiconify()
465
Python 3
Displays the window, after using either the iconify or the withdraw methods.
frame()
group(window)
Adds the window to the window group administered by the given window.
iconify()
protocol(name, function)
Registers a function as a callback which will be called for the given protocol.
iconify()
state()
Returns the current state of the window. Possible values are normal, iconic, withdrawn
and icon.
transient([master])
Turns the window into a temporary(transient) window for the given master or to the
window's parent, when no argument is given.
withdraw()
maxsize(width, height)
minsize(width, height)
positionfrom(who)
466
Python 3
resizable(width, height)
Defines the resize flags, which control whether the window can be resized.
sizefrom(who)
title(string)
Example
Try following example yourself-
# !/usr/bin/python3
from tkinter import *
root = Tk()
root.title("hello")
top = Toplevel()
top.title("Python")
top.mainloop()
Tkinter Spinbox
The Spinbox widget is a variant of the standard Tkinter Entry widget, which can be used
to select from a fixed number of values.
467
Python 3
Syntax
Here is the simple syntax to create this widget-
Parameters
master: This represents the parent window.
options: Here is the list of most commonly used options for this widget. These
options can be used as key-value pairs separated by commas.
Options Description
activebackground The color of the slider and arrowheads when the mouse is over
them.
bg The color of the slider and arrowheads when the mouse is not
over them.
bd The width of the 3-d borders around the entire perimeter of the
trough, and also the width of the 3-d effects on the arrowheads
and slider. Default is no border around the trough, and a 2-pixel
border around the arrowheads and slider.
cursor The cursor that appears when the mouse is over the scrollbar.
fg Text color.
from_ The minimum value. Used together with to to limit the spinbox
range.
468
Python 3
to See from.
Methods
Spinbox objects have these methods-
delete(startindex [,endindex])
469
Python 3
get(startindex [,endindex])
identify(x, y)
index(index)
insert(index [,string]...)
invoke(element)
Example
Try the following example yourself-
master = Tk()
mainloop()
470
Python 3
Tkinter PanedWindow
A PanedWindow is a container widget that may contain any number of panes, arranged
horizontally or vertically.
Each pane contains one widget and each pair of panes is separated by a moveable (via
mouse movements) sash. Moving a sash causes the widgets on either side of the sash to
be resized.
Syntax
Here is the simple syntax to create this widget-
Parameters
master: This represents the parent window.
options: Here is the list of most commonly used options for this widget. These
options can be used as key-value pairs separated by commas.
Option Description
bg The color of the slider and arrowheads when the mouse is not over
them.
bd The width of the 3-d borders around the entire perimeter of the trough,
and also the width of the 3-d effects on the arrowheads and slider.
Default is no border around the trough, and a 2-pixel border around
the arrowheads and slider.
borderwidth Default is 2.
cursor The cursor that appears when the mouse is over the window.
handlepad Default is 8.
handlesize Default is 8.
471
Python 3
sashwidth Default is 2.
Methods
PanedWindow objects have these methods-
add(child, options)
Adds a child window to the paned window.
get(startindex [,endindex])
This method returns a specific character or a range of text.
config(options)
Modifies one or more widget options. If no options are given, the method returns a
dictionary containing all current option values.
Example
Try the following example yourself. Here is how to create a 3-pane widget-
# !/usr/bin/python3
from tkinter import *
472
Python 3
m1 = PanedWindow()
m1.pack(fill=BOTH, expand=1)
m2 = PanedWindow(m1, orient=VERTICAL)
m1.add(m2)
mainloop()
Tkinter LabelFrame
A labelframe is a simple container widget. Its primary purpose is to act as a spacer or
container for complex window layouts.
This widget has the features of a frame plus the ability to display a label.
Syntax
Here is the simple syntax to create this widget-
Parameters
master: This represents the parent window.
473
Python 3
options: Here is the list of most commonly used options for this widget. These
options can be used as key-value pairs separated by commas.
Option Description
cursor If you set this option to a cursor name (arrow, dot etc.), the
mouse cursor will change to that pattern when it is over the
checkbutton.
highlightbackground Color of the focus highlight when the frame does not have focus.
highlightcolor Color shown in the focus highlight when the frame has the focus.
relief With the default value, relief=FLAT, the checkbutton does not
stand out from its background. You may set this option to any
of the other styles
Example
Try the following example yourself. Here is how to create a labelframe widget-
# !/usr/bin/python3
from tkinter import *
474
Python 3
root = Tk()
root.mainloop()
Tkinter tkMessageBox
The tkMessageBox module is used to display message boxes in your applications. This
module provides a number of functions that you can use to display an appropriate
message.
Syntax
Here is the simple syntax to create this widget-
Parameters
FunctionName: This is the name of the appropriate message box function.
title: This is the text to be displayed in the title bar of a message box.
options: options are alternative choices that you may use to tailor a standard
message box. Some of the options that you can use are default and parent. The
475
Python 3
default option is used to specify the default button, such as ABORT, RETRY, or
IGNORE in the message box. The parent option is used to specify the window on
top of which the message box is to be displayed.
You could use one of the following functions with dialogue box-
showinfo()
showwarning()
showerror ()
askquestion()
askokcancel()
askyesno ()
askretrycancel ()
Example
Try the following example yourself-
# !/usr/bin/python3
from tkinter import *
top = Tk()
top.geometry("100x100")
def hello():
messagebox.showinfo("Say Hello", "Hello World")
top.mainloop()
476
Python 3
Standard Attributes
Let us look at how some of the common attributes, such as sizes, colors and fonts are
specified.
Dimensions
Colors
Fonts
Anchors
Relief styles
Bitmaps
Cursors
Tkinter Dimensions
Various lengths, widths, and other dimensions of widgets can be described in many
different units.
Character Description
477
Python 3
c Centimeters
i Inches
m Millimeters
Length options
Tkinter expresses a length as an integer number of pixels. Here is the list of common
length options-
highlightthickness: Width of the highlight rectangle when the widget has focus .
padX padY: Extra space the widget requests from its layout manager beyond the
minimum the widget needs to display its contents in the x and y directions.
wraplength: Maximum line length for widgets that perform word wrapping.
underline: Index of the character to underline in the widget's text (0 is the first
character, 1 the second one, and so on).
Tkinter Colors
Tkinter represents colors with strings. There are two general ways to specify colors in
Tkinter-
You can use a string specifying the proportion of red, green and blue in hexadecimal
digits. For example, "#fff" is white, "#000000" is black, "#000fff000" is pure green,
and "#00ffff" is pure cyan (green plus blue).
You can also use any locally defined standard color name. The colors "white",
"black", "red", "green", "blue", "cyan", "yellow", and "magenta" will always be
available.
478
Python 3
Color options
The common color options are-
activebackground: Background color for the widget when the widget is active.
activeforeground: Foreground color for the widget when the widget is active.
background: Background color for the widget. This can also be represented as bg.
foreground: Foreground color for the widget. This can also be represented as fg.
highlightcolor: Foreground color of the highlight region when the widget has
focus.
Tkinter Fonts
There may be up to three ways to specify type style.
Example
("Helvetica", "16") for a 16-point Helvetica regular.
import tkFont
font = tkFont.Font ( option, ... )
Example
helv36 = tkFont.Font(family="Helvetica",size=36,weight="bold")
X Window Fonts
If you are running under the X Window System, you can use any of the X font names.
Tkinter Anchors
Anchors are used to define where text is positioned relative to a reference point.
Here is list of possible constants, which can be used for Anchor attribute.
NW
N
NE
W
CENTER
E
SW
S
SE
For example, if you use CENTER as a text anchor, the text will be centered horizontally
and vertically around the reference point.
Anchor NW will position the text so that the reference point coincides with the northwest
(top left) corner of the box containing the text.
Anchor W will center the text vertically around the reference point, with the left edge of
the text box passing through that point, and so on.
If you create a small widget inside a large frame and use the anchor=SE option, the widget
will be placed in the bottom right corner of the frame. If you used anchor=N instead, the
widget would be centered along the top edge.
480
Python 3
Example
The anchor constants are shown in this diagram-
Here is list of possible constants which can be used for relief attribute-
FLAT
RAISED
SUNKEN
GROOVE
RIDGE
Example
# !/usr/bin/python3
from tkinter import *
import tkinter
top = Tk()
481
Python 3
B1.pack()
B2.pack()
B3.pack()
B4.pack()
B5.pack()
top.mainloop()
Tkinter Bitmaps
This attribute to displays a bitmap. There are following type of bitmaps available-
"error"
"gray75"
"gray50"
"gray25"
"gray12"
"hourglass"
"info"
482
Python 3
"questhead"
"question"
"warning"
Example
# !/usr/bin/python3
from tkinter import *
import tkinter
top = Tk()
B1.pack()
B2.pack()
B3.pack()
B4.pack()
B5.pack()
top.mainloop()
483
Python 3
Tkinter Cursors
Python Tkinter supports quite a number of different mouse cursors available. The exact
graphic may vary according to your operating system.
"arrow"
"circle"
"clock"
"cross"
"dotbox"
"exchange"
"fleur"
"heart"
"heart"
"man"
"mouse"
"pirate"
"plus"
"shuttle"
"sizing"
"spider"
"spraycan"
"star"
"target"
"tcross"
"trek"
"watch"
484
Python 3
Example
Try the following example by moving cursor on different buttons-
# !/usr/bin/python3
from tkinter import *
import tkinter
top = Tk()
Geometry Management
All Tkinter widgets have access to the specific geometry management methods, which
have the purpose of organizing widgets throughout the parent widget area. Tkinter
exposes the following geometry manager classes: pack, grid, and place.
The pack() Method - This geometry manager organizes widgets in blocks before
placing them in the parent widget.
The place() Method -This geometry manager organizes widgets by placing them in
a specific position in the parent widget.
485
Python 3
Syntax
widget.pack( pack_options )
expand: When set to true, widget expands to fill any space not otherwise used in
widget's parent.
fill: Determines whether widget fills any extra space allocated to it by the packer,
or keeps its own minimal dimensions: NONE (default), X (fill only horizontally), Y
(fill only vertically), or BOTH (fill both horizontally and vertically).
side: Determines which side of the parent widget packs against: TOP (default),
BOTTOM, LEFT, or RIGHT.
Example
Try the following example by moving cursor on different buttons-
# !/usr/bin/python3
from tkinter import *
root = Tk()
frame = Frame(root)
frame.pack()
bottomframe = Frame(root)
bottomframe.pack( side = BOTTOM )
486
Python 3
root.mainloop()
Syntax
widget.grid( grid_options )
ipadx, ipady :How many pixels to pad widget, horizontally and vertically, inside
widget's borders.
padx, pady : How many pixels to pad widget, horizontally and vertically, outside
v's borders.
row: The row to put widget in; default the first row that is still empty.
sticky : What to do if the cell is larger than widget. By default, with sticky='',
widget is centered in its cell. sticky may be the string concatenation of zero or more
of N, E, S, W, NE, NW, SE, and SW, compass directions indicating the sides and
corners of the cell to which widget sticks.
Example
Try the following example by moving cursor on different buttons-
# !/usr/bin/python3
from tkinter import *
root = Tk( )
487
Python 3
b=0
for r in range(6):
for c in range(6):
b=b+1
Button(root, text=str(b),
borderwidth=1 ).grid(row=r,column=c)
root.mainloop()
This would produce the following result displaying 12 labels arrayed in a 3 x 4 grid-
Syntax
widget.place( place_options )
anchor : The exact spot of widget other options refer to: may be N, E, S, W, NE,
NW, SE, or SW, compass directions indicating the corners and sides of widget;
default is NW (the upper left corner of widget)
bordermode : INSIDE (the default) to indicate that other options refer to the
parent's inside (ignoring the parent's border); OUTSIDE otherwise.
relheight, relwidth : Height and width as a float between 0.0 and 1.0, as a
fraction of the height and width of the parent widget.
relx, rely : Horizontal and vertical offset as a float between 0.0 and 1.0, as a
fraction of the height and width of the parent widget.
488
Python 3
Example
Try the following example by moving cursor on different buttons-
# !/usr/bin/python3
ffrom tkinter import *
top = Tk()
L1 = Label(top, text="Physics")
L1.place(x=10,y=10)
E1 = Entry(top, bd =5)
E1.place(x=60,y=10)
L2=Label(top,text="Maths")
L2.place(x=10,y=50)
E2=Entry(top,bd=5)
E2.place(x=60,y=50)
L3=Label(top,text="Total")
L3.place(x=10,y=150)
E3=Entry(top,bd=5)
E3.place(x=60,y=150)
489
28. Python 3 – Extension Programming with C Python 3
Any code that you write using any compiled language like C, C++, or Java can be
integrated or imported into another Python script. This code is considered as an
"extension."
A Python extension module is nothing more than a normal C library. On Unix machines,
these libraries usually end in .so (for shared object). On Windows machines, you typically
see .dll (for dynamically linked library).
Windows users get these headers as part of the package when they use the binary
Python installer.
Additionally, it is assumed that you have a good knowledge of C or C++ to write any
Python Extension using C programming.
The C functions you want to expose as the interface from your module.
A table mapping the names of your functions as Python developers see them as C
functions inside the extension module.
An initialization function.
Make sure to include Python.h before any other headers you might need. You need to
follow the includes with the functions you want to call from Python.
490
Python 3
The C Functions
The signatures of the C implementation of your functions always takes one of the following
three forms-
Each one of the preceding declarations returns a Python object. There is no such thing as
a void function in Python as there is in C. If you do not want your functions to return a
value, return the C equivalent of Python's None value. The Python headers define a macro,
Py_RETURN_NONE, that does this for us.
The names of your C functions can be whatever you like as they are never seen outside of
the extension module. They are defined as static function.
Your C functions usually are named by combining the Python module and function names
together, as shown here −
This is a Python function called func inside the module module. You will be putting pointers
to your C functions into the method table for the module that usually comes next in your
source code.
struct PyMethodDef {
char *ml_name;
PyCFunction ml_meth;
int ml_flags;
char *ml_doc;
};
491
Python 3
ml_name: This is the name of the function as the Python interpreter presents
when it is used in Python programs.
ml_meth: This is the address of a function that has any one of the signatures,
described in the previous section.
ml_flags: This tells the interpreter which of the three signatures ml_meth is using.
o This flag can be bitwise OR'ed with METH_KEYWORDS if you want to allow
keyword arguments into your function.
o This can also have a value of METH_NOARGS that indicates you do not want
to accept any arguments.
ml_doc: This is the docstring for the function, which could be NULL if you do not
feel like writing one.
This table needs to be terminated with a sentinel that consists of NULL and 0 values for
the appropriate members.
Example
For the above-defined function, we have the following method mapping table-
The initialization function needs to be exported from the library you will be building. The
Python headers define PyMODINIT_FUNC to include the appropriate incantations for that
to happen for the particular environment in which we are compiling. All you have to do is
use it when defining the function.
PyMODINIT_FUNC initModule() {
Py_InitModule3(func, module_methods, "docstring...");
}
492
Python 3
#include <Python.h>
PyMODINIT_FUNC initModule() {
Py_InitModule3(func, module_methods, "docstring...");
}
Example
A simple example that makes use of all the above concepts-
#include <Python.h>
{NULL}
};
void inithelloworld(void)
{
Py_InitModule3("helloworld", helloworld_funcs,
"Extension module example!");
}
Here the Py_BuildValue function is used to build a Python value. Save above code in hello.c
file. We would see how to compile and install this module to be called from Python script.
For the above module, you need to prepare the following setup.py script −
Now, use the following command, which would perform all needed compilation and linking
steps, with the right compiler and linker commands and flags, and copies the resulting
dynamic library into an appropriate directory-
On Unix-based systems, you will most likely need to run this command as root in order to
have permissions to write to the site-packages directory. This usually is not a problem on
Windows.
Importing Extensions
Once you install your extensions, you would be able to import and call that extension in
your Python script as follows-
#!/usr/bin/python3
import helloworld
print helloworld.helloworld()
494
Python 3
The method table containing an entry for the new function would look like this-
You can use the API PyArg_ParseTuple function to extract the arguments from the one
PyObject pointer passed into your C function.
The first argument to PyArg_ParseTuple is the args argument. This is the object you will
be parsing. The second argument is a format string describing the arguments as you
expect them to appear. Each argument is represented by one or more characters in the
format string as follows.
Compiling the new version of your module and importing it enables you to invoke the new
function with any number of arguments of any type-
495
Python 3
This function returns 0 for errors, and a value not equal to 0 for success. Tuple is the
PyObject* that was the C function's second argument. Here format is a C string that
describes mandatory and optional arguments.
496
Python 3
(...) as per ... A Python sequence is treated as one argument per item.
Returning Values
Py_BuildValue takes in a format string much like PyArg_ParseTuple does. Instead of
passing in the addresses of the values you are building, you pass in the actual values.
Here is an example showing how to implement an add function-
You can return two values from your function as follows. This would be captured using a
list in Python.
Here format is a C string that describes the Python object to build. The following arguments
of Py_BuildValue are C values from which the result is built. ThePyObject* result is a new
reference.
The following table lists the commonly used code strings, of which zero or more are joined
into a string format.
498
Python 3
{...} as per ... Builds Python dictionary from C values, alternating keys
and values.
Code {...} builds dictionaries from an even number of C values, alternately keys and
values. For example, Py_BuildValue("{issi}",23,"zig","zag",42) returns a dictionary like
Python's {23:'zig','zag':42}.
499