Python Programming Real
Python Programming Real
This Python tutorial has been written for the beginners to help them understand the basic to
advanced concepts of Python Programming Language. After completing this tutorial, you
will find yourself at a great level of expertise in Python, from where you can take yourself to
the next levels to become a world class Software Engineer.
What is Python?
Python is a very popular general-purpose interpreted, interactive, object-oriented, and
high-level programming language. Python is dynamically-typed and garbage-collected
programming language. It was created by Guido van Rossum during 1985- 1990. Like Perl,
Python source code is also available under the GNU General Public License (GPL).
Python supports multiple programming paradigms, including Procedural, Object Oriented and
Functional programming language. Python design philosophy emphasizes code readability with
the use of significant indentation.
This tutorial gives a complete understanding of Python programming language starting from
basic conceopts to advanced concepts. This tutorial will take you through simple and
practical approaches while learning Python Programming language.
Python Jobs
Today, Python is very high in demand and all the major companies are looking for great
Python Programmers to develop websites, software components, and applications or to
work with Data Science, AI, and ML technologies. When we are developing this tutorial in
2022, there is a high shortage of Python Programmers where as market demands more
number of Python Programmers due to it's application in Machine Learning, Artificial
Intelligence etc.
Today a Python Programmer with 3-5 years of experience is asking for around $150,000
annual package and this is the most demanding programming language in America.
Though it can vary depending on the location of the Job. It's impossible to list all of the
companies using Python, to name a few big companies are:
Google
Intel
NASA
PayPal
Facebook
IBM
Amazon
Netflix
Pinterest
Uber
Many more...
So, you could be the next potential employee for any of these major companies. We have
developed a great learning material for you to learn Python Programming which will help
you prepare for the technical interviews and certification exams based on Python. So, start
1
learning Python using this simple and effective tutorial from anywhere and anytime
absolutely at your pace.
Python is a MUST for students and working professionals to become a great Software
Engineer specially when they are working in Web Development Domain. I will list down
some of the key advantages of learning Python:
2
Game developer
Web designer
Python developer
Full-stack developer
Machine learning engineer
Data scientist
Data analyst
Data engineer
DevOps engineer
Software engineer
Many more other roles
Characteristics of Python
Following are important characteristics of Python Programming −
Applications of Python
The latest release of Python is 3.x. As mentioned before, Python is one of the most widely
used language over the web. I'm going to list few of them here:
Easy-to-learn − Python has few keywords, simple structure, and a clearly defined
syntax. This allows the student to pick up the language quickly.
Easy-to-read − Python code is more clearly defined and visible to the eyes.
Easy-to-maintain − Python's source code is fairly easy-to-maintain.
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.
Databases − Python provides interfaces to all major commercial databases.
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.
3
Python - Overview
Python is a high-level, interpreted, interactive and object-oriented scripting language.
Python is designed to be highly readable. It uses English keywords frequently where as
other languages use punctuation, and it has fewer syntactical constructions than other
languages.
Python is Interpreted − Python is processed at runtime by the interpreter. You do
not need to compile your program before executing it. This is similar to PERL and
PHP.
Python is Interactive − You can actually sit at a Python prompt and interact with the
interpreter directly to write your programs.
Python is Object-Oriented − Python supports Object-Oriented style or technique of
programming that encapsulates code within objects.
Python is a Beginner's Language − Python is a great language for the beginner-
level programmers and supports the development of a wide range of applications
from simple text processing to WWW browsers to games.
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 is now maintained by a core development team at the institute, although Guido van
Rossum still holds a vital role in directing its progress.
Python Features
Python's features include −
Easy-to-learn − Python has few keywords, simple structure, and a clearly defined
syntax. This allows the student to pick up the language quickly.
Easy-to-read − Python code is more clearly defined and visible to the eyes.
Easy-to-maintain − Python's source code is fairly easy-to-maintain.
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.
Databases − Python provides interfaces to all major commercial databases.
4
GUI Programming − Python supports GUI applications that can be created and
ported to many system calls, libraries and windows systems, such as Windows MFC,
Macintosh, and the X Window system of Unix.
Scalable − Python provides a better structure and support for large programs than
shell scripting.
Apart from the above-mentioned features, Python has a big list of good features, few are
listed below −
It supports functional and structured programming methods as well as OOP.
It can be used as a scripting language or can be compiled to byte-code for building
large applications.
It provides very high-level dynamic data types and supports dynamic type checking.
It supports automatic garbage collection.
It can be easily integrated with C, C++, COM, ActiveX, CORBA, and Java.
5
Python - Environment Setup
Python is available on a wide variety of platforms including Linux and Mac OS X. Let's understand
how to set up our Python environment.
Python has also been ported to the Java and .NET virtual machines
Installing Python
Python distribution is available for a wide variety of platforms. You need to download only the
binary code applicable for your platform and install Python.
If the binary code for your platform is not available, you need a C compiler to compile the source
code manually. Compiling the source code offers more flexibility in terms of choice of features that
you require in your installation.
Here is a quick overview of installing Python on various platforms −
6
Unix and Linux Installation
Here are the simple steps to install Python on Unix/Linux machine.
Open a Web browser and go to https://www.python.org/downloads/.
Follow the link to download zipped source code available for Unix/Linux.
Download and extract files.
Editing the Modules/Setup file if you want to customize some options.
Now issue the following commands:
$ run ./configure script
$ make
$ make install
This installs Python at standard location /usr/local/bin and its libraries
at /usr/local/lib/pythonXX where XX is the version of Python.
Macintosh Installation
Recent Macs come with Python installed, but it may be several years out of date.
See http://www.python.org/download/mac/ for instructions on getting the current version along with
extra tools to support development on the Mac. For older Mac OS's before Mac OS X 10.3 (released
in 2003), MacPython is available.
Jack Jansen maintains it and you can have full access to the entire documentation at his website
− http://www.cwi.nl/~jack/macpython.html. You can find complete installation details for Mac OS
installation.
Setting up PATH
Programs and other executable files can be in many directories, so operating systems provide a
search path that lists the directories that the OS searches for executables.
7
The path is stored in an environment variable, which is a named string maintained by the operating
system. This variable contains information available to the command shell and other programs.
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.
1
PYTHONPATH
It has a role similar to PATH. This variable tells the Python interpreter where to locate the
module files imported into a program. It should include the Python source library directory
and the directories containing Python source code. PYTHONPATH is sometimes preset by
the Python installer.
2
PYTHONSTARTUP
It contains the path of an initialization file containing Python source code. It is executed
every time you start the interpreter. It is named as .pythonrc.py in Unix and it contains
commands that load utilities or modify PYTHONPATH.
3
PYTHONCASEOK
It is used in Windows to instruct Python to find the first case-insensitive match in an import
8
statement. Set this variable to any value to activate it.
4
PYTHONHOME
It is an alternative module search path. It is usually embedded in the PYTHONSTARTUP
or PYTHONPATH directories to make switching module libraries easy.
Running Python
There are three different ways to start Python −
Interactive Interpreter
You can start Python from Unix, DOS, or any other system that provides you a command-line
interpreter or shell window.
Enter python the command line.
Start coding right away in the interactive interpreter.
$python # Unix/Linux
or
python% # Unix/Linux
or
C:> python # Windows/DOS
Here is the list of all the available command line options −
1
-d
It provides debug output.
2
-O
It generates optimized bytecode (resulting in .pyo files).
3
-S
Do not run import site to look for Python paths on startup.
4
-v
verbose output (detailed trace on import statements).
5
-X
disable class-based built-in exceptions (just use strings); obsolete starting
9
with version 1.6.
6
-c cmd
run Python script sent in as cmd string
7
file
run Python script from given file
or
or
10
Python - Basic Syntax
The Python syntax defines a set of rules that are used to create Python statements while
writing a Python Program. The Python Programming Language Syntax has many
similarities to Perl, C, and Java Programming Languages. However, there are some definite
differences between the languages.
11
print ("Hello, World!")
We assume that you have Python interpreter available in /usr/bin directory. Now, try to run
this program as follows −
$ chmod +x test.py # This is to make file executable
$./test.py
This produces the following result −
Hello, World!
Python Identifiers
A Python identifier is a name used to identify a variable, function, class, module or other
object. An identifier starts with a letter A to Z or a to z or an underscore (_) followed by zero
or more letters, underscores and digits (0 to 9).
Python does not allow punctuation characters such as @, $, and % within identifiers.
Python is a case sensitive programming language. Thus, Manpower and manpower are two
different identifiers in Python.
Here are naming conventions for Python identifiers −
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 identifier.
Starting an identifier with two leading underscores indicates a
strongly private identifier.
If the identifier also ends with two trailing underscores, the identifier is a language-
defined special name.
Python Reserved Words
The following list shows the Python keywords. These are reserved words and you cannot
use them as constant or variable or any other identifier names. All the Python keywords
contain lowercase letters only.
and as assert
global if import
12
in is lambda
or pass raise
print ("True")
else:
print ("False")
However, the following block generates an error −
if True:
print ("Answer")
print ("True")
else:
print ("Answer")
print ("False")
Thus, in Python all the continuous lines indented with same number of spaces would form a
block. The following example has various statement blocks −
Do not try to understand the logic at this point of time. Just make sure you understood various
blocks even if they are without braces.
import sys
try:
13
file = open(file_name, "w")
except IOError:
sys.exit()
if file_text == file_finish:
file.close
break
file.write(file_text)
file.write("\n")
file.close()
if len(file_name) == 0:
sys.exit()
try:
except IOError:
sys.exit()
file_text = file.read()
file.close()
print file_text
item_two + \
14
item_three
Statements contained within the [], {}, or () brackets do not need to use the line continuation
character. For example following statement works well in Python −
days = ['Monday', 'Tuesday', 'Wednesday',
'Thursday', 'Friday']
Quotations 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'
Comments in Python
A comment is a programmer-readable explanation or annotation in the Python source code.
They are added with the purpose of making the source code easier for humans to
understand, and are ignored by Python interpreter
Just like most modern languages, Python supports single-line (or end-of-line) and multi-line
(block) comments. Python comments are very much similar to the comments available in
PHP, BASH and Perl Programming languages.
A hash sign (#) that is not inside a string literal begins a comment. All characters after the #
and up to the end of the physical line are part of the comment and the Python interpreter
ignores them.
# First comment
This is a multiline
comment.
'''
suite
16
elif expression :
suite
else :
suite
[ etc. ]
You can also program your script in such a way that it should accept various
options. Command Line Arguments is an advanced topic and should be studied a bit later
once you have gone through rest of the Python concepts.
17
Python - Comments
Python comments are programmer-readable explanation or annotations in the Python
source code. They are added with the purpose of making the source code easier for
humans to understand, and are ignored by Python interpreter. Comments enhance the
readability of the code and help the programmers to understand the code very carefully.
Just like most modern languages, Python supports single-line (or end-of-line) and multi-line
(block) comments. Python comments are very much similar to the comments available in
PHP, BASH and Perl Programming languages.
There are three types of comments available in Python
This is a multiline
comment.
'''
return a+b
print(add.__doc__)
This produces the following result −
Function to add the value of a and b
19
Python - Variables
Python variables are the reserved memory locations used to store values with in a Python
Program. This means that when you create a variable you reserve some space in the
memory.
Based on the data type of a variable, Python interpreter allocates memory and decides
what can be stored in the reserved memory. Therefore, by assigning different data types to
Python variables, you can store integers, decimals or characters in these variables.
print (counter)
print (miles)
print (name)
Here, 100, 1000.0 and "Zara Ali" are the values assigned to counter, miles,
and name variables, respectively. When running the above Python program, this produces
the following result −
100
1000.0
Zara Ali
Delete a Variable
You can delete the reference to a number object by using the del statement. The syntax of
the del statement is −
20
del var1[,var2[,var3[....,varN]]]]
You can delete a single object or multiple objects by using the del statement. For example −
del var
Example
Following examples shows how we can delete a variable and if we try to use a deleted
variable then Python interpreter will throw an error:
counter = 100
print (counter)
del counter
print (counter)
This will produce the following result:
100
Traceback (most recent call last):
File "main.py", line 7, in <module>
print (counter)
NameError: name 'counter' is not defined
Multiple Assignment
Python allows you to assign a single value to several variables simultaneously which
means you can create multiple variables at a time. For example −
a = b = c = 100
print (a)
print (b)
print (c)
This produces the following result:
100
100
100
Here, an integer object is created with the value 1, and all three variables are assigned to
the same memory location. You can also assign multiple objects to multiple variables. For
example −
a,b,c = 1,2,"Zara Ali"
print (a)
21
print (b)
print (c)
This produces the following result:
1
2
Zara Ali
Here, two integer objects with values 1 and 2 are assigned to variables a and b
respectively, and one string object with the value "Zara Ali" is assigned to the variable c.
Example
Following are valid Python variable names:
counter = 100
_count = 100
name1 = "Zara"
name2 = "Nuha"
Age = 20
zara_salary = 100000
print (counter)
print (_count)
print (name1)
print (name2)
print (Age)
print (zara_salary)
This will produce the following result:
22
100
100
Zara
Nuha
20
100000
Example
Following are invalid Python variable names:
1counter = 100
$_count = 100
zara-salary = 100000
print (1counter)
print ($count)
print (zara-salary)
This will produce the following result:
File "main.py", line 3
1counter = 100
^
SyntaxError: invalid syntax
Python Local Variable
Python Local Variables are defined inside a function. We can not access variable outside
the function.
A Python functions is a piece of reusable code and you will learn more about function in Python
- Functions tutorial.
Following is an example to show the usage of local variables:
def sum(x,y):
sum = x + y
return sum
print(sum(5, 10))
15
Python Global Variable
Any variable created outside a function can be accessed within any function and so they
have global scope. Following is an example of global variables:
x = 5
y = 10
23
def sum():
sum = x + y
return sum
print(sum())
This will produce the following result:
15
24
Python - Data Types
Python Data Types are used to define the type of a variable. It defines what type of data we
are going to store in a variable. The data stored in memory can be of many types. For
example, a person's age is stored as a numeric value and his or her address is stored as
alphanumeric characters.
Python has various built-in data types which we will discuss with in this tutorial:
var2 = 10
var3 = 10.023
Python supports four different numerical types −
25
-0490 535633629843L -90. -.6545+0J
Python allows you to use a lowercase l with long, but it is recommended that you use
only an uppercase L to avoid confusion with the number 1. Python displays long
integers with an uppercase L.
A complex number consists of an ordered pair of real floating-point numbers denoted
by x + yj, where x and y are the real numbers and j is the imaginary unit.
Example
Following is an example to show the usage of Integer, Float and Complex numbers:
# integer variable.
a=100
# float variable.
b=20.345
# complex variable.
c=10+3j
27
Python Tuple Data Type
Python tuple is another sequence data type that is similar to a list. A Python tuple consists
of a number of values separated by commas. Unlike lists, however, tuples are enclosed
within parentheses.
The main differences between lists and tuples are: Lists are enclosed in brackets ( [ ] ) and
their elements and size can be changed, while tuples are enclosed in parentheses ( ( ) )
and cannot be updated. Tuples can be thought of as read-only lists. For example −
tuple = ( 'abcd', 786 , 2.23, 'john', 70.2 )
print (tuple[1:3]) # Prints elements of the tuple starting from 2nd till
3rd
print (tuple[2:]) # Prints elements of the tuple starting from 3rd element
Python Ranges
Python range() is an in-built function in Python which returns a sequence of numbers
starting from 0 and increments to 1 until it reaches a specified number.
We use range() function with for and while loop to generate a sequence of numbers.
Following is the syntax of the function:
range(start, stop, step)
28
Here is the description of the parameters used:
Examples
Following is a program which uses for loop to print number from 0 to 4 −
for i in range(5):
print(i)
This produce the following result −
0
1
2
3
4
Now let's modify above program to print the number starting from 1 instead of 0:
for i in range(1, 5):
print(i)
This produce the following result −
1
2
3
4
Again, let's modify the program to print the number starting from 1 but with an increment of
2 instead of 1:
for i in range(1, 5, 2):
print(i)
This produce the following result −
1
3
Python Dictionary
Python 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.
Dictionaries are enclosed by curly braces ({ }) and values can be assigned and accessed
using square braces ([]). For example −
dict = {}
29
dict['one'] = "This is one"
print(a)
print(type(a))
This produce the following result −
true
<class 'bool'>
Following is another program which evaluates the expressions and prints the return values:
30
# Returns false as a is not equal to b
a = 2
b = 4
print(bool(a==b))
print(a==b)
a = None
print(bool(a))
a = ()
print(bool(a))
# Returns false as a is 0
a = 0.0
print(bool(a))
# Returns false as a is 10
a = 10
print(bool(a))
This produce the following result −
False
False
False
False
False
True
Python Data Type Conversion
Sometimes, you may need to perform conversions between the built-in data types. To
convert data between different Python data types, you simply use the type name as a
function.
31
Conversion to int
Following is an example to convert number, float and string into integer data type:
a = int(1) # a will be 1
b = int(2.2) # b will be 2
c = int("3") # c will be 3
print (a)
print (b)
print (c)
This produce the following result −
1
2
3
Conversion to float
Following is an example to convert number, float and string into float data type:
a = float(1) # a will be 1.0
print (a)
print (b)
print (c)
This produce the following result −
1.0
2.2
3.3
Conversion to string
Following is an example to convert number, float and string into string data type:
a = str(1) # a will be "1"
print (a)
print (b)
32
print (c)
This produce the following result −
1
2.2
3.3
Data Type Conversion Functions
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.
1
int(x [,base])
Converts x to an integer. base specifies the base if x is a string.
2
long(x [,base] )
Converts x to a long integer. base specifies the base if x is a string.
3
float(x)
Converts x to a floating-point number.
4
complex(real [,imag])
Creates a complex number.
5
str(x)
Converts object x to a string representation.
6
repr(x)
Converts object x to an expression string.
7
eval(str)
Evaluates a string and returns an object.
8
tuple(s)
Converts s to a tuple.
33
9
list(s)
Converts s to a list.
10
set(s)
Converts s to a set.
11
dict(d)
Creates a dictionary. d must be a sequence of (key,value) tuples.
12
frozenset(s)
Converts s to a frozen set.
13
chr(x)
Converts an integer to a character.
14
unichr(x)
Converts an integer to a Unicode character.
15
ord(x)
Converts a single character to its integer value.
16
hex(x)
Converts an integer to a hexadecimal string.
17
oct(x)
Converts an integer to an octal string.
34
Python - Operators
Python operators are the constructs which can manipulate the value of operands. These
are symbols used for the purpose of logical, arithmetic and various other operations.
Consider the expression 4 + 5 = 9. Here, 4 and 5 are called operands and + is
called operator. In this tutorial, we will study different types of Python operators.
Arithmetic Operators
Comparison (Relational) Operators
Assignment Operators
Logical Operators
Bitwise Operators
Membership Operators
Identity Operators
+ Addition 10 + 20 = 30
- Subtraction 20 – 10 = 10
* Multiplication 10 * 20 = 200
/ Division 20 / 10 = 2
% Modulus 22 % 10 = 2
** Exponent 4**2 = 16
Example
Following is an example which shows all the above operations:
35
a = 21
b = 10
# Addition
# Subtraction
# Multiplication
# Division
# Modulus
# Exponent
# Floor Division
Example
Following is an example which shows all the above comparison operations:
a = 4
b = 5
# Equal
# Not Equal
# Greater Than
# Less Than
37
# Less Than or Equal to
= Assignment Operator a = 10
Example
Following is an example which shows all the above assignment operations:
# Assignment Operator
a = 10
38
# Addition Assignment
a += 5
# Subtraction Assignment
a -= 5
# Multiplication Assignment
a *= 5
# Division Assignment
a /= 5
# Remainder Assignment
a %= 3
# Exponent Assignment
a **= 2
a //= 3
Example
Following is an example which shows all the above bitwise operations:
40
a = 60 # 60 = 0011 1100
b = 13 # 13 = 0000 1101
# Binary AND
# Binary OR
c = a | b # 61 = 0011 1101
# Binary XOR
c = a ^ b # 49 = 0011 0001
41
Python Logical Operators
There are following logical operators supported by Python language. Assume variable a
holds 10 and variable b holds 20 then
[ Show Example ]
and Logical If both the operands are true then condition becomes (a and b) is true.
AND true.
or Logical OR If any of the two operands are non-zero then condition (a or b) is true.
becomes true.
not Logical Used to reverse the logical state of its operand. Not(a and b) is false.
NOT
not in Evaluates to true if it does not finds a variable in the specified x not in y, here
sequence and false otherwise. not in results in a
1 if x is not a
member of
sequence y.
42
is Evaluates to true if the variables on either side of the x is y,
operator point to the same object and false here is results
otherwise. in 1 if id(x)
equals id(y).
1
**
Exponentiation (raise to the power)
2
~+-
Complement, unary plus and minus (method names for the last two
are +@ and -@)
3
* / % //
Multiply, divide, modulo and floor division
4
+-
Addition and subtraction
5
>> <<
Right and left bitwise shift
6
&
Bitwise 'AND'
43
7
^|
Bitwise exclusive `OR' and regular `OR'
8
<= < > >=
Comparison operators
9
<> == !=
Equality operators
10
= %= /= //= -= += *= **=
Assignment operators
11
is is not
Identity operators
12
in not in
Membership operators
13
not or and
Logical operators
44
Python - Decision Making
Decision making is anticipation of conditions occurring while execution of the program and
specifying actions taken according to the conditions.
Decision structures evaluate multiple expressions which produce TRUE or FALSE as
outcome. You need to determine which action to take and which statements to execute if
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
if it is either zero or null, then it is assumed as FALSE value.
Python programming language provides following types of decision making statements.
Click the following links to check their detail.
1 if statements
An if statement consists of a boolean expression followed by one or
more statements.
2 if...else statements
An if statement can be followed by an optional else statement,
which executes when the boolean expression is FALSE.
45
3 nested if statements
You can use one if or else if statement inside another if or else
if statement(s).
#!/usr/bin/python
var = 100
if ( var == 100 ) : print "Value of expression is 100"
print "Good bye!"
When the above code is executed, it produces the following result −
Value of expression is 100
Good bye!
46
Python - Loops
In general, statements are executed sequentially: The first statement in a function is
executed first, followed by the second, and so on. There may be a situation when you need
to execute a block of code several number of times.
Programming languages provide various control structures that allow for more complicated
execution paths.
A loop statement allows us to execute a statement or group of statements multiple times.
The following diagram illustrates a loop statement −
1 while loop
Repeats a statement or group of statements while a given condition
is TRUE. It tests the condition before executing the loop body.
2 for loop
Executes a sequence of statements multiple times and abbreviates
the code that manages the loop variable.
3 nested loops
You can use one or more loop inside any another while, for or
47
do..while loop.
1 break statement
Terminates the loop statement and transfers execution to the
statement immediately following the loop.
2 continue statement
Causes the loop to skip the remainder of its body and immediately
retest its condition prior to reiterating.
3 pass statement
The pass statement in Python is used when a statement is required
syntactically but you do not want any command or code to execute.
48
Python - Numbers
Number data types store numeric values. They are immutable data types, means that
changing the value of a number data type results in a newly allocated object.
Number objects are created when you assign a value to them. For example −
var1 = 1
var2 = 10
You can also delete the reference to a number object by using the del statement. The
syntax of the del statement is −
del var1[,var2[,var3[....,varN]]]]
You can delete a single object or multiple objects by using the del statement. For example
−
del var
del var_a, var_b
Python supports four different numerical types −
int (signed integers) − They are often called just integers or ints, are positive or
negative whole numbers with no decimal point.
long (long integers ) − Also called longs, they are integers of unlimited size, written
like integers and followed by an uppercase or lowercase L.
float (floating point real values) − Also called floats, they represent real numbers
and are written with a decimal point dividing the integer and fractional parts. Floats
may also be in scientific notation, with E or e indicating the power of 10 (2.5e2 = 2.5 x
102 = 250).
complex (complex numbers) − are of the form a + bJ, where a and b are floats and
J (or j) represents the square root of -1 (which is an imaginary number). The real part
of the number is a, and the imaginary part is b. Complex numbers are not used much
in Python programming.
Examples
Here are some examples of numbers
49
-0x260 -052318172735L -32.54e100 3e+26J
Python allows you to use a lowercase L with long, but it is recommended that you
use only an uppercase L to avoid confusion with the number 1. Python displays long
integers with an uppercase L.
A complex number consists of an ordered pair of real floating point numbers denoted
by a + bj, where a is the real part and b is the imaginary part of the complex number.
Number Type Conversion
Python converts numbers internally in an expression containing mixed types to a common
type for evaluation. But sometimes, you need to coerce a number explicitly from one type to
another to satisfy the requirements of an operator or function parameter.
Type int(x) to convert x to a plain integer.
Type long(x) to convert x to a long integer.
Type float(x) to convert x to a floating-point number.
Type complex(x) to convert x to a complex number with real part x and imaginary
part zero.
Type complex(x, y) to convert x and y to a complex number with real part x and
imaginary part y. x and y are numeric expressions
Mathematical Functions
Python includes following functions that perform mathematical calculations.
1 abs(x)
The absolute value of x: the (positive) distance between x and zero.
2 ceil(x)
The ceiling of x: the smallest integer not less than x
3 cmp(x, y)
-1 if x < y, 0 if x == y, or 1 if x > y
4 exp(x)
The exponential of x: ex
5 fabs(x)
The absolute value of x.
50
6 floor(x)
The floor of x: the largest integer not greater than x
7 log(x)
The natural logarithm of x, for x> 0
8 log10(x)
The base-10 logarithm of x for x> 0.
9 max(x1, x2,...)
The largest of its arguments: the value closest to positive infinity
10 min(x1, x2,...)
The smallest of its arguments: the value closest to negative infinity
11 modf(x)
The fractional and integer parts of x in a two-item tuple. Both parts
have the same sign as x. The integer part is returned as a float.
12 pow(x, y)
The value of x**y.
13 round(x [,n])
x rounded to n digits from the decimal point. Python rounds away
from zero as a tie-breaker: round(0.5) is 1.0 and round(-0.5) is -1.0.
14 sqrt(x)
The square root of x for x > 0
1 choice(seq)
A random item from a list, tuple, or string.
51
2 randrange ([start,] stop [,step])
A randomly selected element from range(start, stop, step)
3 random()
A random float r, such that 0 is less than or equal to r and r is less
than 1
4 seed([x])
Sets the integer starting value used in generating random numbers.
Call this function before calling any other random module function.
Returns None.
5 shuffle(lst)
Randomizes the items of a list in place. Returns None.
6 uniform(x, y)
A random float r, such that x is less than or equal to r and r is less
than y
Trigonometric Functions
Python includes following functions that perform trigonometric calculations.
1 acos(x)
Return the arc cosine of x, in radians.
2 asin(x)
Return the arc sine of x, in radians.
3 atan(x)
Return the arc tangent of x, in radians.
4 atan2(y, x)
Return atan(y / x), in radians.
5 cos(x)
52
Return the cosine of x radians.
6 hypot(x, y)
Return the Euclidean norm, sqrt(x*x + y*y).
7 sin(x)
Return the sine of x radians.
8 tan(x)
Return the tangent of x radians.
9 degrees(x)
Converts angle x from radians to degrees.
10 radians(x)
Converts angle x from degrees to radians.
Mathematical Constants
The module also defines two mathematical constants −
1
pi
The mathematical constant pi.
2
e
The mathematical constant e.
53
Python - Strings
Strings are amongst the most popular types in Python. We can create them simply by
enclosing characters in quotes. Python treats single quotes the same as double quotes.
Creating strings is as simple as assigning a value to a variable. For example −
var1 = 'Hello World!'
var2 = "Python Programming"
#!/usr/bin/python
#!/usr/bin/python
54
Backslash Hexadecimal Description
notation character
\b 0x08 Backspace
\cx Control-x
\C-x Control-x
\e 0x1b Escape
\f 0x0c Formfeed
\M-\C-x Meta-Control-x
\n 0x0a Newline
\s 0x20 Space
\t 0x09 Tab
\x Character x
55
String Special Operators
Assume string variable a holds 'Hello' and variable b holds 'Python', then −
[] 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
range give ell
#!/usr/bin/python
%c Character
%o octal integer
Other supported symbols and functionality are listed in the following table −
57
Symbol Functionality
- left justification
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.
Live Demo
#!/usr/bin/python
58
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) −
this is a long string that is made up of
several lines and non-printable characters such as
TAB ( ) and they will show up that way when displayed.
NEWLINEs within the string, whether explicitly given like
this within the brackets [
], or just a NEWLINE within
the variable assignment will also show up.
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 −
Live Demo
#!/usr/bin/python
print 'C:\\nowhere'
When the above code is executed, it produces the following result −
C:\nowhere
Now let's make use of raw string. We would put expression in r'expression' as follows −
Live Demo
#!/usr/bin/python
print r'C:\\nowhere'
When the above code is executed, it produces the following result −
C:\\nowhere
Unicode String
Normal strings in Python are stored internally as 8-bit ASCII, while Unicode strings are
stored as 16-bit Unicode. This allows for a more varied set of characters, including special
characters from most languages in the world. I'll restrict my treatment of Unicode strings to
the following −
Live Demo
#!/usr/bin/python
59
Built-in String Methods
Python includes the following built-in methods to manipulate strings −
1 capitalize()
Capitalizes first letter of string
2 center(width, fillchar)
Returns a space-padded string with the original string centered to a
total of width columns.
4 decode(encoding='UTF-8',errors='strict')
Decodes the string using the codec registered for encoding. encoding
defaults to the default string encoding.
5 encode(encoding='UTF-8',errors='strict')
Returns encoded string version of string; on error, default is to raise a
ValueError unless errors is given with 'ignore' or 'replace'.
7 expandtabs(tabsize=8)
Expands tabs in string to multiple spaces; defaults to 8 spaces per
tab if tabsize not provided.
60
Same as find(), but raises an exception if str not found.
10 isalnum()
Returns true if string has at least 1 character and all characters are
alphanumeric and false otherwise.
11 isalpha()
Returns true if string has at least 1 character and all characters are
alphabetic and false otherwise.
12 isdigit()
Returns true if string contains only digits and false otherwise.
13 islower()
Returns true if string has at least 1 cased character and all cased
characters are in lowercase and false otherwise.
14 isnumeric()
Returns true if a unicode string contains only numeric characters and
false otherwise.
15 isspace()
Returns true if string contains only whitespace characters and false
otherwise.
16 istitle()
Returns true if string is properly "titlecased" and false otherwise.
17 isupper()
Returns true if string has at least one cased character and all cased
characters are in uppercase and false otherwise.
18 join(seq)
Merges (concatenates) the string representations of elements in
sequence seq into a string, with separator string.
19 len(string)
Returns the length of the string
61
20 ljust(width[, fillchar])
Returns a space-padded string with the original string left-justified to
a total of width columns.
21 lower()
Converts all uppercase letters in string to lowercase.
22 lstrip()
Removes all leading whitespace in string.
23 maketrans()
Returns a translation table to be used in translate function.
24 max(str)
Returns the max alphabetical character from the string str.
25 min(str)
Returns the min alphabetical character from the string str.
27 rfind(str, beg=0,end=len(string))
Same as find(), but search backwards in string.
29 rjust(width,[, fillchar])
Returns a space-padded string with the original string right-justified to
a total of width columns.
30 rstrip()
Removes all trailing whitespace of string.
31 split(str="", num=string.count(str))
62
Splits string according to delimiter str (space if not provided) and
returns list of substrings; split into at most num substrings if given.
32 splitlines( num=string.count('\n'))
Splits string at all (or num) NEWLINEs and returns a list of each line
with NEWLINEs removed.
33 startswith(str, beg=0,end=len(string))
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.
34 strip([chars])
Performs both lstrip() and rstrip() on string.
35 swapcase()
Inverts case for all letters in string.
36 title()
Returns "titlecased" version of string, that is, all words begin with
uppercase and the rest are lowercase.
37 translate(table, deletechars="")
Translates string according to translation table str(256 chars),
removing those in the del string.
38 upper()
Converts lowercase letters in string to uppercase.
39 zfill (width)
Returns original string leftpadded with zeros to a total of width
characters; intended for numbers, zfill() retains any sign given (less
one zero).
40 isdecimal()
Returns true if a unicode string contains only decimal characters and
false otherwise.
63
Python - Lists
The most basic data structure in Python is the sequence. Each element of a sequence is
assigned a number - its position or index. The first index is zero, the second index is one,
and so forth.
Python has six built-in types of sequences, but the most common ones are lists and tuples,
which we would see in this tutorial.
There are certain things you can do with all sequence types. These operations include
indexing, slicing, adding, multiplying, and checking for membership. In addition, Python has
built-in functions for finding the length of a sequence and for finding its largest and smallest
elements.
Python Lists
The list is a most versatile datatype available in Python which can be written as a list of
comma-separated values (items) between square brackets. Important thing about a list is
that items in a list need not be of the same type.
Creating a list is as simple as putting different comma-separated values between square
brackets. For example −
list1 = ['physics', 'chemistry', 1997, 2000];
list2 = [1, 2, 3, 4, 5 ];
list3 = ["a", "b", "c", "d"]
Similar to string indices, list indices start at 0, and lists can be sliced, concatenated and so
on.
#!/usr/bin/python
64
Live Demo
#!/usr/bin/python
#!/usr/bin/python
65
[1, 2, 3] + [4, 5, 6] [1, 2, 3, 4, 5, 6] Concatenation
1 cmp(list1, list2)
Compares elements of both lists.
2 len(list)
Gives the total length of the list.
3 max(list)
Returns item from the list with max value.
4 min(list)
Returns item from the list with min value.
66
5 list(seq)
Converts a tuple into list.
1 list.append(obj)
Appends object obj to list
2 list.count(obj)
Returns count of how many times obj occurs in list
3 list.extend(seq)
Appends the contents of seq to list
4 list.index(obj)
Returns the lowest index in list that obj appears
5 list.insert(index, obj)
Inserts object obj into list at offset index
6 list.pop(obj=list[-1])
Removes and returns last object or obj from list
7 list.remove(obj)
Removes object obj from list
8 list.reverse()
Reverses objects of list in place
9 list.sort([func])
Sorts objects of list, use compare func if given
67
Python - Tuples
A tuple is a collection of objects which ordered and immutable. Tuples are sequences, just
like lists. The differences between tuples and lists are, the tuples cannot be changed unlike
lists and tuples use parentheses, whereas lists use square brackets.
Creating a tuple is as simple as putting different comma-separated values. Optionally you
can put these comma-separated values between parentheses also. For example −
tup1 = ('physics', 'chemistry', 1997, 2000);
tup2 = (1, 2, 3, 4, 5 );
tup3 = "a", "b", "c", "d";
The empty tuple is written as two parentheses containing nothing −
tup1 = ();
To write a tuple containing a single value you have to include a comma, even though there
is only one value −
tup1 = (50,);
Like string indices, tuple indices start at 0, and they can be sliced, concatenated, and so on.
#!/usr/bin/python
#!/usr/bin/python
#!/usr/bin/python
69
3 in (1, 2, 3) True Membership
No Enclosing Delimiters
Any set of multiple objects, comma-separated, written without identifying symbols, i.e.,
brackets for lists, parentheses for tuples, etc., default to tuples, as indicated in these short
examples −
Live Demo
#!/usr/bin/python
1 cmp(tuple1, tuple2)
70
Compares elements of both tuples.
2 len(tuple)
Gives the total length of the tuple.
3 max(tuple)
Returns item from the tuple with max value.
4 min(tuple)
Returns item from the tuple with min value.
5 tuple(seq)
Converts a list into tuple.
71
Python - Dictionary
Each key is separated from its value by a colon (:), the items are separated by commas,
and the whole thing is enclosed in curly braces. An empty dictionary without any items is
written with just two curly braces, like this: {}.
Keys are unique within a dictionary while values may not be. The values of a dictionary can
be of any type, but the keys must be of an immutable data type such as strings, numbers,
or tuples.
#!/usr/bin/python
#!/usr/bin/python
#!/usr/bin/python
72
dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'}
dict['Age'] = 8; # update existing entry
dict['School'] = "DPS School"; # Add new entry
#!/usr/bin/python
73
#!/usr/bin/python
#!/usr/bin/python
1 cmp(dict1, dict2)
Compares elements of both dict.
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)
Produces a printable string representation of a dictionary
4 type(variable)
Returns the type of the passed variable. If passed variable is
dictionary, then it would return a dictionary type.
74
Sr.No. Methods with Description
1 dict.clear()
Removes all elements of dictionary dict
2 dict.copy()
Returns a shallow copy of dictionary dict
3 dict.fromkeys()
Create a new dictionary with keys from seq and values set to value.
4 dict.get(key, default=None)
For key key, returns value or default if key not in dictionary
5 dict.has_key(key)
Returns true if key in dictionary dict, false otherwise
6 dict.items()
Returns a list of dict's (key, value) tuple pairs
7 dict.keys()
Returns list of dictionary dict's 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)
Adds dictionary dict2's key-values pairs to dict
10 dict.values()
Returns list of dictionary dict's values
75
Python - Date & Time
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 00:00:00 hrs 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 00:00:00 hrs January 1, 1970(epoch).
Example
Live Demo
#!/usr/bin/python
import time; # This is required to include time module.
ticks = time.time()
print "Number of ticks since 12:00am, January 1, 1970:", ticks
This would produce a result something as follows −
Number of ticks since 12:00am, January 1, 1970: 7186862.73399
Date arithmetic is easy to do with ticks. However, dates before the epoch cannot be
represented in this form. Dates in the far future also cannot be represented this way - the
cutoff point is sometime in 2038 for UNIX and Windows.
What is TimeTuple?
Many of Python's time functions handle time as a tuple of 9 numbers, as shown below −
1 Month 1 to 12
2 Day 1 to 31
3 Hour 0 to 23
4 Minute 0 to 59
76
5 Second 0 to 61 (60 or 61 are leap-seconds)
The above tuple is equivalent to struct_time structure. This structure has following
attributes −
0 tm_year 2008
1 tm_mon 1 to 12
2 tm_mday 1 to 31
3 tm_hour 0 to 23
4 tm_min 0 to 59
6 tm_wday 0 to 6 (0 is Monday)
#!/usr/bin/python
77
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 −
Local current time : time.struct_time(tm_year=2013, tm_mon=7,
tm_mday=17, tm_hour=21, tm_min=26, tm_sec=3, tm_wday=2, tm_yday=198, tm_isdst=0)
Getting formatted time
You can format any time as per your requirement, but simple method to get time in
readable format is asctime() −
Live Demo
#!/usr/bin/python
import time;
#!/usr/bin/python
import calendar
cal = calendar.month(2008, 1)
print "Here is the calendar:"
print cal
This would produce the following result −
Here is the calendar:
January 2008
Mo Tu We Th Fr Sa Su
1 2 3 4 5 6
7 8 9 10 11 12 13
14 15 16 17 18 19 20
21 22 23 24 25 26 27
28 29 30 31
78
The time Module
There is a popular time module available in Python which provides functions for working
with times and for converting between representations. Here is the list of all available
methods −
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). Only use this if 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( )
Returns the current CPU time as a floating-point number of seconds.
To measure computational costs of different approaches, the value of
time.clock is more useful than that of time.time().
4 time.ctime([secs])
Like asctime(localtime(secs)) and without arguments is like asctime( )
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)
Accepts an instant expressed as a time-tuple in local time and
returns a floating-point value with the instant expressed in seconds
since the epoch.
79
8 time.sleep(secs)
Suspends the calling thread for secs seconds.
9 time.strftime(fmt[,tupletime])
Accepts an instant expressed as a time-tuple in local time and
returns a string representing the instant as specified by string fmt.
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.
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
Attribute time.tzname is a pair of locale-dependent strings, which are
the names of the local time zone without and with DST, respectively.
80
Here is a list of functions available with the calendar module −
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.
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)
Returns True if year is a leap year; otherwise, False.
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.
81
8
calendar.prcal(year,w=2,l=1,c=6)
Like print calendar.calendar(year,w,l,c).
9
calendar.prmonth(year,month,w=2,l=1)
Like print calendar.month(year,month,w,l).
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.
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).
82
Python - Functions
A function is a block of organized, reusable code that is used to perform a single, related
action. Functions provide better modularity for your application and a high degree of code
reusing.
As you already know, Python gives you many built-in functions like print(), etc. but you can
also create your own functions. These functions are called user-defined functions.
Defining a Function
You can define functions to provide the required functionality. Here are simple rules to
define a function in Python.
Function blocks begin with the keyword def followed by the function name and
parentheses ( ( ) ).
Any input parameters or arguments should be placed within these parentheses. You
can also define parameters inside these parentheses.
The first statement of a function can be an optional statement - the documentation
string of the function or docstring.
The code block within every function starts with a colon (:) and is indented.
The statement return [expression] exits a function, optionally passing back an
expression to the caller. A return statement with no arguments is the same as return
None.
Syntax
def functionname( parameters ):
"function_docstring"
function_suite
return [expression]
By default, parameters have a positional behavior and you need to inform them in the same
order that they were defined.
Example
The following function takes a string as input parameter and prints it on standard screen.
def printme( str ):
"This prints a passed string into this function"
print str
return
Calling a Function
Defining a function only gives it a name, specifies the parameters that are to be included in
the function and structures the blocks of code.
Once the basic structure of a function is finalized, you can execute it by calling it from
another function or directly from the Python prompt. Following is the example to call
printme() function −
Live Demo
83
#!/usr/bin/python
#!/usr/bin/python
#!/usr/bin/python
84
"This changes a passed list into this function"
mylist = [1,2,3,4]; # This would assig new reference in mylist
print "Values inside the function: ", mylist
return
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 −
Live Demo
#!/usr/bin/python
#!/usr/bin/python
#!/usr/bin/python
86
#!/usr/bin/python
#!/usr/bin/python
#!/usr/bin/python
88
#!/usr/bin/python
Global variables
Local variables
Global vs. Local variables
Variables that are defined inside a function body have a local scope, and those defined
outside have a global scope.
This means that local variables can be accessed only inside the function in which they are
declared, whereas global variables can be accessed throughout the program body by all
functions. When you call a function, the variables declared inside it are brought into scope.
Following is a simple example −
Live Demo
#!/usr/bin/python
90
Python - Modules
A module allows you to logically organize your Python code. Grouping related code into a
module makes the code easier to understand and use. A module is a Python object with
arbitrarily named attributes that you can bind and reference.
Simply, a module is a file consisting of Python code. A module can define functions, classes
and variables. A module can also include runnable code.
Example
The Python code for a module named aname normally resides in a file named aname.py.
Here's an example of a simple module, support.py
def print_func( par ):
print "Hello : ", par
return
91
from fib import fibonacci
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.
Locating Modules
When you import a module, the Python interpreter searches for the module in the following
sequences −
The current directory.
If the module isn't found, Python then searches each directory in the shell variable
PYTHONPATH.
If all else fails, Python checks the default path. On UNIX, this default path is normally
/usr/local/lib/python/.
The module search path is stored in the system module sys as the sys.path variable. The
sys.path variable contains the current directory, PYTHONPATH, and the installation-
dependent default.
Money = 2000
def AddMoney():
# Uncomment the following line to fix the code:
# global Money
Money = Money + 1
print Money
AddMoney()
print Money
#!/usr/bin/python
content = dir(math)
print content
When the above code is executed, it produces the following result −
['__doc__', '__file__', '__name__', 'acos', 'asin', 'atan',
'atan2', 'ceil', 'cos', 'cosh', 'degrees', 'e', 'exp',
'fabs', 'floor', 'fmod', 'frexp', 'hypot', 'ldexp', 'log',
'log10', 'modf', 'pi', 'pow', 'radians', 'sin', 'sinh',
'sqrt', 'tan', 'tanh']
Here, the special string variable __name__ is the module's name, and __file__ is the
filename from which the module was loaded.
93
The globals() and locals() Functions
The globals() and locals() functions can be used to return the names in the global and local
namespaces depending on the location from where they are called.
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.
def Pots():
print "I'm Pots Phone"
Similar way, we have another two files having different functions with the same name as
above −
Phone/Isdn.py file having function Isdn()
Phone/G3.py file having function G3()
Now, create one more file __init__.py in Phone directory −
Phone/__init__.py
To make all of your functions available when you've imported Phone, you need to put
explicit import statements in __init__.py as follows −
from Pots import Pots
from Isdn import Isdn
94
from G3 import G3
After you add these lines to __init__.py, you have all of these classes available when you
import the Phone package.
#!/usr/bin/python
Phone.Pots()
Phone.Isdn()
Phone.G3()
When the above code is executed, it produces the following result −
I'm Pots Phone
I'm 3G Phone
I'm ISDN Phone
In the above example, we have taken example of a single functions in each file, but you can
keep multiple functions in your files. You can also define different Python classes in those
files and then you can create your packages out of those classes.
95
Python - Files I/O
This chapter covers all the basic I/O functions available in Python. For more functions,
please refer to standard Python documentation.
#!/usr/bin/python
raw_input
input
The raw_input Function
The raw_input([prompt]) function reads one line from standard input and returns it as a
string (removing the trailing newline).
#!/usr/bin/python
1
r
Opens a file for reading only. The file pointer is placed at the
beginning of the file. This is the default mode.
2
rb
Opens a file for reading only in binary format. The file pointer is
placed at the beginning of the file. This is the default mode.
3
r+
Opens a file for both reading and writing. The file pointer placed at
97
the beginning of the file.
4
rb+
Opens a file for both reading and writing in binary format. The file
pointer placed at the beginning of the file.
5
w
Opens a file for writing only. Overwrites the file if the file exists. If the
file does not exist, creates a new file for writing.
6
wb
Opens a file for writing only in binary format. Overwrites the file if the
file exists. If the file does not exist, creates a new file for writing.
7
w+
Opens a file for both writing and reading. Overwrites the existing file if
the file exists. If the file does not exist, creates a new file for reading
and writing.
8
wb+
Opens a file for both writing and reading in binary format. Overwrites
the existing file if the file exists. If the file does not exist, creates a
new file for reading and writing.
9
a
Opens a file for appending. The file pointer is at the end of the file if
the file exists. That is, the file is in the append mode. If the file does
not exist, it creates a new file for writing.
10
ab
Opens a file for appending in binary format. The file pointer is at the
end of the file if the file exists. That is, the file is in the append mode.
If the file does not exist, it creates a new file for writing.
11
a+
Opens a file for both appending and reading. The file pointer is at the
end of the file if the file exists. The file opens in the append mode. If
98
the file does not exist, it creates a new file for reading and writing.
12
ab+
Opens a file for both appending and reading in binary format. The file
pointer is at the end of the file if the file exists. The file opens in the
append mode. If the file does not exist, it creates a new file for
reading and writing.
1
file.closed
Returns true if file is closed, false otherwise.
2
file.mode
Returns access mode with which file was opened.
3
file.name
Returns name of the file.
4
file.softspace
Returns false if space explicitly required with print, true otherwise.
Example
Live Demo
#!/usr/bin/python
# Open a file
fo = open("foo.txt", "wb")
print "Name of the file: ", fo.name
print "Closed or not : ", fo.closed
print "Opening mode : ", fo.mode
print "Softspace flag : ", fo.softspace
This produces the following result −
99
Name of the file: foo.txt
Closed or not : False
Opening mode : wb
Softspace flag : 0
The close() Method
The close() method of a file object flushes any unwritten information and closes the file
object, after which no more writing can be done.
Python automatically closes a file when the reference object of a file is reassigned to
another file. It is a good practice to use the close() method to close a file.
Syntax
fileObject.close()
Example
Live Demo
#!/usr/bin/python
# Open a file
fo = open("foo.txt", "wb")
print "Name of the file: ", fo.name
# Open a file
fo = open("foo.txt", "wb")
fo.write( "Python is a great language.\nYeah its great!!\n")
100
# Close opend file
fo.close()
The above method would create foo.txt file and would write given content in that file and
finally it would close that file. If you would open this file, it would have following content.
Python is a great language.
Yeah its great!!
The read() Method
The read() method reads a string from an open file. It is important to note that Python
strings can have binary data. apart from text data.
Syntax
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's take a file foo.txt, which we created above.
#!/usr/bin/python
# Open a file
fo = open("foo.txt", "r+")
str = fo.read(10);
print "Read String is : ", str
# Close opend file
fo.close()
This produces the following result −
Read String is : Python is
File Positions
The tell() method tells you the current position within the file; in other words, the next read
or write will occur at that many bytes from the beginning of the file.
The seek(offset[, from]) method changes the current file position. The offset argument
indicates the number of bytes to be moved. The from argument specifies the reference
position from where the bytes are to be moved.
If from is set to 0, it means use the beginning of the file as the reference position and 1
means use the current position as the reference position and if it is set to 2 then the end of
the file would be taken as the reference position.
Example
Let us take a file foo.txt, which we created above.
#!/usr/bin/python
101
# Open a file
fo = open("foo.txt", "r+")
str = fo.read(10)
print "Read String is : ", str
Syntax
os.rename(current_file_name, new_file_name)
Example
Following is the example to rename an existing file test1.txt −
#!/usr/bin/python
import os
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.getcwd()
103
Example
Following is the example to give current directory −
#!/usr/bin/python
import os
104
Python - Exceptions Handling
Python provides two very important features to handle any unexpected error in your Python
programs and to add debugging capabilities in them −
Exception Handling − This would be covered in this tutorial. Here is a list standard
Exceptions available in Python: Standard Exceptions.
Assertions − This would be covered in Assertions in Python tutorial.
List of Standard Exceptions −
1
Exception
Base class for all exceptions
2
StopIteration
Raised when the next() method of an iterator does not point to any
object.
3
SystemExit
Raised by the sys.exit() function.
4
StandardError
Base class for all built-in exceptions except StopIteration and
SystemExit.
5
ArithmeticError
Base class for all errors that occur for numeric calculation.
6
OverflowError
Raised when a calculation exceeds maximum limit for a numeric
type.
7
FloatingPointError
Raised when a floating point calculation fails.
8
ZeroDivisionError
Raised when division or modulo by zero takes place for all numeric
105
types.
9
AssertionError
Raised in case of failure of the Assert statement.
10
AttributeError
Raised in case of failure of attribute reference or assignment.
11
EOFError
Raised when there is no input from either the raw_input() or input()
function and the end of file is reached.
12
ImportError
Raised when an import statement fails.
13
KeyboardInterrupt
Raised when the user interrupts program execution, usually by
pressing Ctrl+c.
14
LookupError
Base class for all lookup errors.
15
IndexError
Raised when an index is not found in a sequence.
16
KeyError
Raised when the specified key is not found in the dictionary.
17
NameError
Raised when an identifier is not found in the local or global
namespace.
18
UnboundLocalError
Raised when trying to access a local variable in a function or method
106
but no value has been assigned to it.
19
EnvironmentError
Base class for all exceptions that occur outside the Python
environment.
20
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.
21
IOError
Raised for operating system-related errors.
22
SyntaxError
Raised when there is an error in Python syntax.
23
IndentationError
Raised when indentation is not specified properly.
24
SystemError
Raised when the interpreter finds an internal problem, but when this
error is encountered the Python interpreter does not exit.
25
SystemExit
Raised when Python interpreter is quit by using the sys.exit()
function. If not handled in the code, causes the interpreter to exit.
26
TypeError
Raised when an operation or function is attempted that is invalid for
the specified data type.
27
ValueError
Raised when the built-in function for a data type has the valid type of
arguments, but the arguments have invalid values specified.
107
28
RuntimeError
Raised when a generated error does not fall into any category.
29
NotImplementedError
Raised when an abstract method that needs to be implemented in an
inherited class is not actually implemented.
Assertions in Python
An assertion is a sanity-check that you can turn on or turn off when you are done with your
testing of the program.
The easiest way to think of an assertion is to liken it to a raise-if statement (or to be more
accurate, a raise-if-not statement). An expression is tested, and if the result comes up false,
an exception is raised.
Assertions are carried out by the assert statement, the newest keyword to Python,
introduced in version 1.5.
Programmers often place assertions at the start of a function to check for valid input, and
after a function call to check for valid output.
The assert Statement
When it encounters an assert statement, Python evaluates the accompanying expression,
which is hopefully true. If the expression is false, Python raises
an AssertionError exception.
The syntax for assert is −
assert Expression[, Arguments]
If the assertion fails, Python uses ArgumentExpression as the argument for the
AssertionError. AssertionError exceptions can be caught and handled like any other
exception using the try-except statement, but if not handled, they will terminate the program
and produce a traceback.
Example
Here is a function that converts a temperature from degrees Kelvin to degrees Fahrenheit.
Since zero degrees Kelvin is as cold as it gets, the function bails out if it sees a negative
temperature −
Live Demo
#!/usr/bin/python
def KelvinToFahrenheit(Temperature):
assert (Temperature >= 0),"Colder than absolute zero!"
return ((Temperature-273)*1.8)+32
print KelvinToFahrenheit(273)
print int(KelvinToFahrenheit(505.78))
print KelvinToFahrenheit(-5)
108
When the above code is executed, it produces the following result −
32.0
451
Traceback (most recent call last):
File "test.py", line 9, in <module>
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;
......................
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.
Here are few important points about the above-mentioned syntax −
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 −
109
Live Demo
#!/usr/bin/python
try:
fh = open("testfile", "w")
fh.write("This is my test file for exception handling!!")
except IOError:
print "Error: can\'t find file or read data"
else:
print "Written content in the file successfully"
fh.close()
This produces the following result −
Written content in the file successfully
Example
This example tries to open a file where you do not have write permission, so it raises an
exception −
Live Demo
#!/usr/bin/python
try:
fh = open("testfile", "r")
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"
This produces the following result −
Error: can't find file or read data
The except Clause with No Exceptions
You can also use the except statement with no exceptions defined as follows −
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.
110
The except Clause with Multiple Exceptions
You can also use the same except statement to handle multiple exceptions as follows −
try:
You do your operations here;
......................
except(Exception1[, Exception2[,...ExceptionN]]]):
If there is any exception from the given exception list,
then execute this block.
......................
else:
If there is no exception then execute this block.
Example
Live Demo
#!/usr/bin/python
try:
fh = open("testfile", "w")
fh.write("This is my test file for exception handling!!")
finally:
print "Error: can\'t find file or read data"
If you do not have permission to open the file in writing mode, then this will produce the
following result −
Error: can't find file or read data
Same example can be written more cleanly as follows −
Live Demo
#!/usr/bin/python
try:
fh = open("testfile", "w")
111
try:
fh.write("This is my test file for exception handling!!")
finally:
print "Going to close the file"
fh.close()
except IOError:
print "Error: can\'t find file or read data"
When an exception is thrown in the try block, the execution immediately passes to
the finally block. After all the statements in the finally block are executed, the exception is
raised again and is handled in the except statements if present in the next higher layer of
the try-except statement.
Argument of an Exception
An exception can have an argument, which is a value that gives additional information
about the problem. The contents of the argument vary by exception. You capture an
exception's argument by supplying a variable in the except clause as follows −
try:
You do your operations here;
......................
except ExceptionType, Argument:
You can print value of Argument here...
If you write the code to handle a single exception, you can have a variable follow the name
of the exception in the except statement. If you are trapping multiple exceptions, you can
have a variable follow the tuple of the exception.
This variable receives the value of the exception mostly containing the cause of the
exception. The variable can receive a single value or multiple values in the form of a tuple.
This tuple usually contains the error string, the error number, and an error location.
Example
Following is an example for a single exception −
Live Demo
#!/usr/bin/python
User-Defined Exceptions
Python also allows you to create your own exceptions by deriving classes from the standard
built-in exceptions.
Here is an example related to RuntimeError. Here, a class is created that is subclassed
from RuntimeError. This is useful when you need to display more specific information when
an exception is caught.
In the try block, the user-defined exception is raised and caught in the except block. The
variable e is used to create an instance of the class Networkerror.
class Networkerror(RuntimeError):
def __init__(self, arg):
self.args = arg
113
So once you defined above class, you can raise the exception as follows −
try:
raise Networkerror("Bad hostname")
except Networkerror,e:
print e.args
114