Python PDF
Python PDF
Programming
Python is a general-purpose interpreted, interactive, object-oriented, and high-level
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). This tutorial gives enough understanding on Python
programming language.
Characteristics of Python
Following are important characteristics of Python Programming −
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.
Audience
This Python tutorial is designed for software programmers who need 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.
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.
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.
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.
Getting Python
The most up-to-date and current source code, binaries, documentation, news, etc.,
is available on the official website of Python https://www.python.org/
You can download Python documentation from https://www.python.org/doc/. The
documentation is available in HTML, PDF, and PostScript formats.
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 –
Windows Installation
Here are the steps to install Python on Windows machine.
Open a Web browser and go to https://www.python.org/downloads/.
Follow the link for the Windows installer python-XYZ.msi file where XYZ is the version you
need to install.
To use this installer python-XYZ.msi, the Windows system must support Microsoft Installer
2.0. Save the installer file to your local machine and then run it to find out if your machine
supports MSI.
Run the downloaded file. This brings up the Python install wizard, which is really easy to
use. Just accept the default settings, wait until the install is finished, and you are done.
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.
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 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 −
Sr.No. Option & Description
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 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
Python Identifiers
A Python identifier is a name used to identify a variable, function, class, module or
other object. An identifier starts with a letter A to Z or a to z or an underscore (_)
followed by zero or more letters, underscores and digits (0 to 9).
Python does not allow punctuation characters such as @, $, and % within identifiers.
Python is a case sensitive programming language.
Thus, Manpower and manpower are two different identifiers in Python.
Here are naming conventions for Python identifiers −
Class names start with an uppercase letter. All other identifiers start with a lowercase
letter.
Starting an identifier with a single leading underscore indicates that the identifier is private.
Starting an identifier with two leading underscores indicates a strongly private identifier.
If the identifier also ends with two trailing underscores, the identifier is a language-defined
special name.
Reserved Words
The following list shows the Python keywords. These are reserved words and you
cannot use them as constant or variable or any other identifier names. All the Python
keywords contain lowercase letters only.
assert finally or
def if return
elif in while
else is with
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 = raw_input("Enter filename: ")
if len(file_name) == 0:
print "Next time please enter something"
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 does, however, allow the
use of the line continuation character (\) to denote that the line should continue. For
example −
total = item_one + \
item_two + \
item_three
Statements contained within the [], {}, or () brackets do not need to use the line
continuation character. For example −
days = ['Monday', 'Tuesday', 'Wednesday',
'Thursday', 'Friday']
Quotation in Python
Python accepts single ('), double (") and triple (''' or """) quotes to denote string literals,
as long as the same type of quote starts and ends the string.
The triple quotes are used to span the string across multiple lines. For example, all
the following are legal −
word = 'word'
sentence = "This is a sentence."
paragraph = """This is a paragraph. It is
made up of multiple lines and sentences."""
Comments in Python
A hash sign (#) that is not inside a string literal begins a comment. All characters after
the # and up to the end of the physical line are part of the comment and the Python
interpreter ignores them.
#!/usr/bin/python
# First comment
print "Hello, Python!" # second comment
This produces the following result −
Hello, Python!
You can type a comment on the same line after a statement or expression −
name = "Madisetti" # This is again comment
You can comment multiple lines as follows −
# This is a comment.
# This is a comment, too.
# This is a comment, too.
# I said that already.
Following triple-quoted string is also ignored by Python interpreter and can be used
as a multiline comments:
'''
This is a multiline
comment.
'''
[ 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.
Variables are nothing but reserved memory locations to store values. This means that
when you create a variable you reserve some space in 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 variables, you can store integers, decimals or characters in these variables.
#!/usr/bin/python
print counter
print miles
print name
Here, 100, 1000.0 and "John" are the values assigned to counter, miles,
and name variables, respectively. This produces the following result −
100
1000.0
John
Multiple Assignment
Python allows you to assign a single value to several variables simultaneously. For
example −
a = b = c = 1
Here, an integer object is created with the value 1, and all three variables are
assigned to the same memory location. You can also assign multiple objects to
multiple variables. For example −
a,b,c = 1,2,"john"
Here, two integer objects with values 1 and 2 are assigned to variables a and b
respectively, and one string object with the value "john" is assigned to the variable c.
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
Python supports four different numerical types −
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.
Python Strings
Strings in Python are identified as a contiguous set of characters represented in the
quotation marks. Python allows for either pairs of single or double quotes. Subsets of
strings can be taken using the slice operator ([ ] and [:] ) with indexes starting at 0 in
the beginning of the string and working their way from -1 at the end.
The plus (+) sign is the string concatenation operator and the asterisk (*) is the
repetition operator. For example −
#!/usr/bin/python
Python Lists
Lists are the most versatile of Python's compound data types. A list contains items
separated by commas and enclosed within square brackets ([]). To some extent, lists
are similar to arrays in C. One difference between them is that all the items 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/python
Python Tuples
A tuple is another sequence data type that is similar to the list. A tuple consists of a
number of values separated by commas. Unlike lists, however, tuples are enclosed
within parentheses.
The main differences between lists and tuples are: Lists are enclosed in brackets ( [
] ) and their elements and size can be changed, while tuples are enclosed in
parentheses ( ( ) ) and cannot be updated. Tuples can be thought of as read-
only lists. For example −
#!/usr/bin/python
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.
Dictionaries are enclosed by curly braces ({ }) and values can be assigned and
accessed using square braces ([]). For example −
#!/usr/bin/python
dict = {}
dict['one'] = "This is one"
dict[2] = "This is two"
1
int(x [,base])
Converts x to an integer. base specifies the base if x is a string.
2
long(x [,base] )
Converts x to a long integer. base specifies the base if x is a string.
3
float(x)
Converts x to a floating-point number.
4
complex(real [,imag])
Creates a complex number.
5
str(x)
Converts object x to a string representation.
6
repr(x)
Converts object x to an expression string.
7
eval(str)
Evaluates a string and returns an object.
8
tuple(s)
Converts s to a tuple.
9
list(s)
Converts s to a list.
10
set(s)
Converts s to a set.
11
dict(d)
Creates a dictionary. d must be a sequence of (key,value) tuples.
12
frozenset(s)
Converts s to a frozen set.
13
chr(x)
Converts an integer to a character.
14
unichr(x)
Converts an integer to a Unicode character.
15
ord(x)
Converts a single character to its integer value.
16
hex(x)
Converts an integer to a hexadecimal string.
17
oct(x)
Converts an integer to an octal string.
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
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
Let us have a look on all operators one by one.
- Subtraction Subtracts right hand operand from left hand operand. a–b=-
10
% Modulus Divides left hand operand by right hand operand and returns b%a=
remainder 0
<> If values of two operands are not equal, then condition becomes (a <> b)
true. is true.
This is
similar to
!=
operator.
> 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.
>= If the value of left operand is greater than or equal to the value of (a >= b)
right operand, then condition becomes true. is not
true.
<= If the value of left operand is less than or equal to the value of (a <= b)
right operand, then condition becomes true. is true.
+= Add AND It adds right operand to the left operand and assign the c += a is
result to left operand equivalent
to c = c +
a
-= Subtract It subtracts right operand from the left operand and assign c -= a is
AND the result to left operand equivalent
to c = c -
a
*= Multiply It multiplies right operand with the left operand and assign c *= a is
AND the result to left operand equivalent
to c = c *
a
/= Divide AND It divides left operand with the right operand and assign c /= a is
the result to left operand equivalent
to c = c /
a
%= Modulus It takes modulus using two operands and assign the result c %= a is
AND to left operand equivalent
to c = c %
a
//= Floor It performs floor division on operators and assign value to c //= a is
Division the left operand equivalent
to c = c //
a
& Binary AND Operator copies a bit to the result if it exists in both (a & b)
operands (means
0000 1100)
^ Binary XOR It copies the bit if it is set in one operand but not (a ^ b) = 49
both. (means
0011 0001)
<< Binary Left Shift The left operands value is moved left by the a << 2 =
number of bits specified by the right operand. 240 (means
1111 0000)
>> Binary Right The left operands value is moved right by the a >> 2 = 15
Shift number of bits specified by the right operand. (means
0000 1111)
and Logical If both the operands are true then condition becomes true. (a and b)
AND is true.
not Logical Used to reverse the logical state of its operand. Not(a
NOT and b) is
false.
not in Evaluates to true if it does not finds a variable in the specified x not in y,
sequence and false otherwise. here not
in results
in a 1 if x
is not a
member
of
sequence
y.
Python Identity Operators
Identity operators compare the memory locations of two objects. There are two
Identity operators explained below −
[ Show Example ]
1
**
Exponentiation (raise to the power)
2
~+-
Complement, unary plus and minus (method names for the last two are +@ and
-@)
3
* / % //
Multiply, divide, modulo and floor division
4
+-
Addition and subtraction
5
>> <<
Right and left bitwise shift
6
&
Bitwise 'AND'
7
^|
Bitwise exclusive `OR' and regular `OR'
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
1 if statements
2 if...else statements
An if statement can be followed by an optional else statement, which executes
when the boolean expression is FALSE.
3 nested if statements
You can use one if or else if statement inside another if or else if statement(s).
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!
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
3 nested loops
You can use one or more loop inside any another while, for or do..while loop.
1 break statement
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.
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
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)
2 ceil(x)
The ceiling of x: the smallest integer not less than x
3 cmp(x, y)
-1 if x < y, 0 if x == y, or 1 if x > y
4 exp(x)
The exponential of x: ex
5 fabs(x)
The absolute value of x.
6 floor(x)
The floor of x: the largest integer not greater than x
7 log(x)
The natural logarithm of x, for x> 0
8 log10(x)
The base-10 logarithm of x for x> 0.
9 max(x1, x2,...)
The largest of its arguments: the value closest to positive infinity
10 min(x1, x2,...)
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)
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)
2 asin(x)
Return the arc sine of x, in radians.
3 atan(x)
Return the arc tangent of x, in radians.
4 atan2(y, x)
Return atan(y / x), in radians.
5 cos(x)
Return the cosine of x radians.
6 hypot(x, y)
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)
Mathematical Constants
The module also defines two mathematical constants −
1
pi
The mathematical constant pi.
2
e
The mathematical constant e.
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
Updating Strings
You can "update" an existing string by (re)assigning a variable to another string. The
new value can be related to its previous value or to a completely different string
altogether. For example −
#!/usr/bin/python
Escape Characters
Following table is a list of escape or non-printable characters that can be represented
with backslash notation.
An escape character gets interpreted; in a single quoted as well as double quoted
strings.
\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
[:] Range Slice - Gives the characters from the given range a[1:4] will
give ell
not in Membership - Returns true if a character does not exist in the M not in a
given string will give 1
#!/usr/bin/python
%c character
%s string conversion via str() prior to formatting
%o octal integer
Other supported symbols and functionality are listed in the following table −
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.
#!/usr/bin/python
#!/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 −
#!/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 −
#!/usr/bin/python
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')
7 expandtabs(tabsize=8)
Expands tabs in string to multiple spaces; defaults to 8 spaces per tab if tabsize
not provided.
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
20 ljust(width[, fillchar])
Returns a space-padded string with the original string left-justified to a total of
width columns.
21 lower()
22 lstrip()
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)
Replaces all occurrences of old in string with new or at most max occurrences
if max given.
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))
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.
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.
Accessing Values in Lists
To access values in lists, use the square brackets for slicing along with the index or
indices to obtain value available at that index. For example −
#!/usr/bin/python
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/python
#!/usr/bin/python
list1 = ['physics', 'chemistry', 1997, 2000];
print list1
del list1[2];
print "After deleting value at index 2 : "
print list1
When the above code is executed, it produces following result −
['physics', 'chemistry', 1997, 2000]
After deleting value at index 2 :
['physics', 'chemistry', 2000]
Note − remove() method is discussed in subsequent section.
1 cmp(list1, list2)
2 len(list)
3 max(list)
4 min(list)
Returns item from the list with min value.
5 list(seq)
Converts a tuple into list.
1 list.append(obj)
2 list.count(obj)
4 list.index(obj)
5 list.insert(index, obj)
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
A tuple is a sequence of immutable Python objects. Tuples are sequences, just like
lists. The differences between tuples and lists are, the tuples cannot be changed
unlike lists and tuples use parentheses, whereas lists use square brackets.
Creating a tuple is as simple as putting different comma-separated values. Optionally
you can put these comma-separated values between parentheses also. For example
−
tup1 = ('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
Updating Tuples
Tuples are immutable which means you cannot update or change the values of tuple
elements. You are able to take portions of existing tuples to create new tuples as the
following example demonstrates −
#!/usr/bin/python
#!/usr/bin/python
No Enclosing Delimiters
Any set of multiple objects, comma-separated, written without identifying symbols,
i.e., brackets for lists, parentheses for tuples, etc., default to tuples, as indicated in
these short examples −
#!/usr/bin/python
1 cmp(tuple1, tuple2)
2 len(tuple)
3 max(tuple)
4 min(tuple)
Returns item from the tuple with min value.
5 tuple(seq)
Converts a list into tuple.
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
Updating Dictionary
You can update a dictionary by adding a new entry or a key-value pair, modifying an
existing entry, or deleting an existing entry as shown below in the simple example −
#!/usr/bin/python
#!/usr/bin/python
#!/usr/bin/python
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)
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.
Python includes following dictionary methods −
1 dict.clear()
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)
10 dict.values()
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/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
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)
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)
#!/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
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.
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.
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.
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).
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 −
#!/usr/bin/python
#!/usr/bin/python
#!/usr/bin/python
Function Arguments
You can call a function by using the following types of formal arguments −
Required arguments
Keyword arguments
Default arguments
Variable-length arguments
Required arguments
Required arguments are the arguments passed to a function in correct positional
order. Here, the number of arguments in the function call should match exactly with
the function definition.
To call the function printme(), you definitely need to pass one argument, otherwise it
gives a syntax error as follows −
#!/usr/bin/python
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/python
#!/usr/bin/python
Default arguments
A default argument is an argument that assumes a default value if a value is not
provided in the function call for that argument. The following example gives an idea
on default arguments, it prints default age if it is not passed −
#!/usr/bin/python
#!/usr/bin/python
Syntax
The syntax of lambda functions contains only a single statement, which is as follows
−
lambda [arg1 [,arg2,.....argn]]:expression
Following is the example to show how lambda form of function works −
#!/usr/bin/python
#!/usr/bin/python
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
#!/usr/bin/python