Python is a high-level, interpreted, interactive and object-oriented scripting language.
Python was
designed to be highly readable which uses English keywords frequently where as other
languages use punctuation and it has fewer syntactical constructions than other languages.
•Python is Interpreted: This means that it is processed at runtime by the interpreter and you do
not need to compile your program before executing it. This is similar to PERL and PHP.
•Python is Interactive: This means that you can actually sit at a Python prompt and interact with
the interpreter directly to write your programs.
•Python is Object-Oriented: This means that Python supports Object-Oriented style or
technique of programming that encapsulates code within objects.
•Python is Beginner's Language: Python is a great language for the beginner programmers
and supports the development of a wide range of applications from simple text processing to
WWW browsers to games.
• 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 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
• Easy-to-learn: Python has relatively few keywords, simple structure, and a clearly defined syntax.
This allows the student to pick up the language in a relatively short period of time.
• Easy-to-read: Python code is much more clearly defined and visible to the eyes.
• Easy-to-maintain: Python's success is that its source code is fairly easy-to-maintain.
• A broad standard library: One of Python's greatest strengths is the bulk of the library is very
portable and cross-platform compatible on UNIX, Windows and Macintosh.
• Interactive Mode: Support for an interactive mode in which you can enter results from a terminal
right to the language, allowing 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.
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 following identifier naming convention for Python:
•Class names start with an uppercase letter and all other identifiers with a
lowercase letter.
•Starting an identifier with a single leading underscore indicates by convention
that the identifier is meant to be 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 reserved words in Python. These reserved words may not
be used as constant or variable or any other identifier names. All the Python keywords
contain lowercase letters only.
and exec not
assert finally or
break for pass
class from print
continue global raise
def if return
del import try
elif in while
else is with
except lambda yield
Lines and Indentation:
One of the first caveats programmers encounter when learning Python is the fact that there are no braces to indicate
blocks of code for class and function definitions or flow control. Blocks of code are denoted by line indentation, which is
rigidly enforced.
The number of spaces in the indentation is variable, but all statements within the block must be indented the same
amount. Both blocks in this example are fine:
Comments in Python
A hash sign (#) that is not inside a string literal begins a comment. All characters after the # and up to the
physical line end are part of the comment and the Python interpreter ignores them.
#!/usr/bin/python
# First comment
print "Hello, Python!"; # second comment
This will produce the following result:
Hello, Python!
A comment may be 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.
Multiple Statements on a Single Line
The semicolon ( ; ) allows multiple statements on the single line given that neither statement starts a new
code block. Here is a sample snip using the semicolon:
import sys; x = 'foo'; [Link](x + '\n')
Assigning Values to Variables:
Python variables do not have to be explicitly declared to reserve memory space. The declaration happens
automatically when you assign a value to a variable. The equal sign (=) is used to assign values to variables.
The operand to the left of the = operator is the name of the variable and the operand to the right of the =
operator is the value stored in the variable. For example:
counter = 100 # An integer assignment
miles = 1000.0 # A floating point
name = "John" # A string
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, and one string object with
the value "john" is assigned to the variable c.
Standard Data Types
The data stored in memory can be of many types. For example, a person's age is stored as a numeric value and his or her
address is stored as alphanumeric characters. Python has various standard types that are used to define the operations
possible on them and the storage method for each of them.
Python has five standard data types:
Numbers
String
List
Tuple
Dictionary
Python Numbers
Number data types store numeric values..
Number objects are created when you assign a value to them. For example:
var1 = 1
var2 = 10
You can also delete the reference to a number object by using the del statement. The syntax of the del statement is:
del var1[,var2[,var3[....,varN]]]]
You can delete a single object or multiple objects by using the del statement. For example:
del var
del var_a, var_b
• Python supports four different numerical types
• int (signed integers)
• long (long integers [can also be represented in octal and
hexadecimal])
• float (floating point real values)
• complex (complex numbers)
Python Strings
• Strings in Python are identified as a contiguous set of characters in
between 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:
• str = 'Hello World!'
• print str # Prints complete string
• print str[0] # Prints first character of the string
• print str[2:5] # Prints characters starting from 3rd to 5th
• print str[2:] # Prints string starting from 3rd character
• print str * 2 # Prints string two times
• print str + "TEST" # Prints concatenated string
• This will produce the following result:
• Hello World!
•H
• llo
• llo World!
• Hello World!Hello World!
• Hello World!TEST
Python Lists
• Lists are the most versatile of Python's compound data types. A list contains items separated by commas and
enclosed within square brackets ([]). To some extent, lists are similar to arrays in C. One 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:
• list = [ 'abcd', 786 , 2.23, 'john', 70.2 ]
• tinylist = [123, 'john']
• print list # Prints complete list
• print list[0] # Prints first element of the list
• print list[1:3] # Prints elements starting from 2nd till 3rd
• print list[2:] # Prints elements starting from 3rd element
• print tinylist * 2 # Prints list two times
• print list + tinylist # Prints concatenated lists
• This will produce the following result:
• ['abcd', 786, 2.23, 'john', 70.200000000000003]
• abcd
• [786, 2.23]
• [2.23, 'john', 70.200000000000003]
• [123, 'john', 123, 'john']
• ['abcd', 786, 2.23, 'john', 70.200000000000003, 123, 'john']
Python Tuples
• 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.
• tuple = ( 'abcd', 786 , 2.23, 'john', 70.2 )
• tinytuple = (123, 'john')
• print tuple # Prints complete list
• print tuple[0] # Prints first element of the list
• print tuple[1:3] # Prints elements starting from 2nd till 3rd
• print tuple[2:] # Prints elements starting from 3rd element
• print tinytuple * 2 # Prints list two times
• print tuple + tinytuple # Prints concatenated lists
• Following is invalid with tuple, because we attempted to update a
tuple, which is not allowed. Similar case is possible with lists
• tuple = ( 'abcd', 786 , 2.23, 'john', 70.2 )
• list = [ 'abcd', 786 , 2.23, 'john', 70.2 ]
• tuple[2] = 1000 # Invalid syntax with tuple
• list[2] = 1000 # Valid syntax with list
Python Dictionary
• Python dictionary is a data structure which contains a key and a
corresponding value, it is created using {} braces.
• tinydict = {'name': 'john','code':6734, 'dept': 'sales'}
• print tinydict # Prints complete dictionary
• print [Link]() # Prints all the keys
• print [Link]() # Prints all the values
Result
• {'dept': 'sales', 'code': 6734, 'name': 'john'}
• ['dept', 'code', 'name']
• ['sales', 6734, 'john']
Decision structures
1) If -expression
It is similar to that of other languages. The if statement contains a logical expression using which
data is compared and a decision is made based on the result of the comparison.
Syntax
if expression:
statement(s)
An else statement can be combined with an if statement. An else statement contains the block of
code that executes if the conditional expression in the if statement resolves to 0 or a FALSE value.
2) If-else expression
The else statement is an optional statement and there could be at most only one else statement
following if .
Syntax
if expression:
statement(s)
else:
statement(s)
• There may be a situation when you want to check for multiple condition. In
such a situation, you can use the nested if construct.
Syntax
• The syntax of the nested if...elif...else construct may be:
if expression1:
statement(s)
elif expression2:
statement(s)
elif expression3:
statement(s)
elif expression4:
statement(s)
else:
statement(s)
Looping structures
• Python programming language provides following types of loops to
handle looping requirements.
• 1) while loop Repeats a statement or group of statements while a
given condition is true. It tests the condition before executing the
loop body.
• 2) for loop Executes a sequence of statements multiple times and
abbreviates the code that manages the loop variable.
• 3) nested loops You can use one or more loop inside any another
while, for or do..while loop.
• A while loop statement in Python programming language repeatedly
executes a target statement as long as a given condition is true.
Syntax:
• The syntax of a while loop in Python programming language is:
while expression:
statement(s)
• Here, statement(s) may be a single statement or a block of statements. The
condition may be any expression, and true is any non-zero value. The loop
iterates while the condition is true.
• When the condition becomes false, program control passes to the line
immediately following the loop.
• In Python, all the statements indented by the same number of character
spaces after a programming construct are considered to be part of a single
block of code. Python uses indentation as its method of grouping
statements.
count = 0
while (count < 9):
print 'The count is:', count
count = count + 1
print "Good bye!"
for statement
It has the ability to iterate over the items of any sequence, such as a list or a string.
Syntax
for iterating_var in sequence:
statements(s)
• If a sequence contains an expression list, it is evaluated first. Then, the first item in the sequence is
assigned to the iterating variable iterating_var. Next, the statements block is executed. Each item in
the list is assigned to iterating_var, and the statement(s) block is executed until the entire sequence
is exhausted.
• for letter in 'Python': # First Example
print 'Current Letter :', letter
fruits = ['banana', 'apple', 'mango']
for fruit in fruits: # Second Example
print 'Current fruit :', fruit
print "Good bye!"
for num in range(10,20): #to iterate between 10 to 20 step 1 upto (20-1)
10,11,12,13…………………..19
for I in range(10,20,5): # to iterate between 10 to (20-1) with step 5
10,15
• 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 are 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() func on −
# Function definition is here
• def printme( str ):
"This prints a passed string into this function"
print str;
return;
# Now you can call printme function
printme("I'm first call to user defined function!");
printme("Again second call to the same function");
• The following example gives more clear picture. Note that the order of
parameters does not matter.
• # Function definition is here
• def printinfo( name, age ):
• "This prints a passed info into this function"
• print "Name: ", name;
• print "Age ", age;
• return;
# Now you can call printinfo function
printinfo( age=48, name=“suhel" );
When the above code is executed, it produces the following result −
Name: suhel
Age: 48
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 [Link]. Here's an example of a simple module, [Link]
def print_func( par ):
print “Welcome : ", par
return
The import Statement
• You can use any Python source file as a module by executing an import statement in some
other Python source file. The import has the following syntax:
import module1[, module2[,... moduleN]
• When the interpreter encounters an import statement, it imports the module if the
module is present in the search path. A search path is a list of directories that the
interpreter searches before importing a module. For example, to import the module
[Link], you need to put the following command at the top of the script
• #!/usr/bin/python
• # Import module support
import support
# Now you can call defined function that module as follows
support.print_func(“suhel")
When the above code is executed, it produces the following result −
Welcome : suhel