Regular Expression

A regular expression is a special sequence of characters that helps you match or find other strings or sets of strings, using a specialized syntax held in a pattern. Regular expressions are widely used in UNIX world.

The module re provides full support for Perl-like regular expressions in Python. The re module raises the exception re.error if an error occurs while compiling or using a regular expression.

We would cover two important functions, which would be used to handle regular expressions. But a small thing first: There are various characters, which would have special meaning when they are used in regular expression. To avoid any confusion while dealing with regular expressions, we would use Raw Strings as r'expression'.

The match Function
This function attempts to match RE pattern to string with optional flags.

Here is the syntax for this function -

re.match(pattern, string, flags=0)

- pattern = This is the regular expression to be matched.
- string = This is the string, which would be searched to match the pattern at the beginning of string.
- flags = You can specify different flags using bitwise OR (|). These are modifiers, which are listed in the table below

Example

import re

line = "Cats are smarter than dogs"

matchObj = re.match( r'(.*) are (.*?) .*', line, re.M|re.I)

if matchObj:
   print "matchObj.group() : ", matchObj.group()
   print "matchObj.group(1) : ", matchObj.group(1)
   print "matchObj.group(2) : ", matchObj.group(2)
else:
   print "No match!!"

Output :

matchObj.group() :  Cats are smarter than dogs
matchObj.group(1) :  Cats
matchObj.group(2) :  smarter

Classes & Objects

Python has been an object-oriented language since it existed. Because of this, creating and using classes and objects are downright easy. This chapter helps you become an expert in using Python's object-oriented programming support.

If you do not have any previous experience with object-oriented (OO) programming, you may want to consult an introductory course on it or at least a tutorial of some sort so that you have a grasp of the basic concepts.

However, here is small introduction of Object-Oriented Programming (OOP) to bring you at speed -

Overview of OOP Terminology

Class: A user-defined prototype for an object that defines a set of attributes that characterize any object of the class. The attributes are data members (class variables and instance variables) and methods, accessed via dot notation.

Class variable: A variable that is shared by all instances of a class. Class variables are defined within a class but outside any of the class's methods. Class variables are not used as frequently as instance variables are.

Data member: A class variable or instance variable that holds data associated with a class and its objects.

Function overloading: The assignment of more than one behavior to a particular function. The operation performed varies by the types of objects or arguments involved.

Instance variable: A variable that is defined inside a method and belongs only to the current instance of a class.

Inheritance: The transfer of the characteristics of a class to other classes that are derived from it.

Instance: An individual object of a certain class. An object obj that belongs to a class Circle, for example, is an instance of the class Circle.

Instantiation: The creation of an instance of a class.

Method : A special kind of function that is defined in a class definition.

Object: A unique instance of a data structure that's defined by its class. An object comprises both data members (class variables and instance variables) and methods.

Operator overloading: The assignment of more than one function to a particular operator.

Creating Classes

The class statement creates a new class definition. The name of the class immediately follows the keyword class followed by a colon as follows -

class ClassName:
   'Optional class documentation string'
   class_suite
The class has a documentation string, which can be accessed via ClassName.__doc__.

The class_suite consists of all the component statements defining class members, data attributes and functions.

Example
Following is the example of a simple Python class -

class Employee:
   'Common base class for all employees'
   empCount = 0

   def __init__(self, name, salary):
      self.name = name
      self.salary = salary
      Employee.empCount += 1
 
   def displayCount(self):
     print "Total Employee %d" % Employee.empCount

   def displayEmployee(self):
      print "Name : ", self.name,  ", Salary: ", self.salary
The variable empCount is a class variable whose value is shared among all instances of a this class. This can be accessed as Employee.empCount from inside the class or outside the class.

The first method __init__() is a special method, which is called class constructor or initialization method that Python calls when you create a new instance of this class.

You declare other class methods like normal functions with the exception that the first argument to each method is self. Python adds the self argument to the list for you; you do not need to include it when you call the methods.

Creating Instance Objects
To create instances of a class, you call the class using class name and pass in whatever arguments its __init__ method accepts.

"This would create first object of Employee class"
emp1 = Employee("Zara", 2000)
"This would create second object of Employee class"
emp2 = Employee("Manni", 5000)
Accessing Attributes
You access the object's attributes using the dot operator with object. Class variable would be accessed using class name as follows -

emp1.displayEmployee()
emp2.displayEmployee()
print "Total Employee %d" % Employee.empCount
Now, putting all the concepts together -

#!/usr/bin/python

class Employee:
   'Common base class for all employees'
   empCount = 0

   def __init__(self, name, salary):
      self.name = name
      self.salary = salary
      Employee.empCount += 1
 
   def displayCount(self):
     print "Total Employee %d" % Employee.empCount

   def displayEmployee(self):
      print "Name : ", self.name,  ", Salary: ", self.salary

"This would create first object of Employee class"
emp1 = Employee("Zara", 2000)
"This would create second object of Employee class"
emp2 = Employee("Manni", 5000)
emp1.displayEmployee()
emp2.displayEmployee()
print "Total Employee %d" % Employee.empCount
When the above code is executed, it produces the following result -

Name :  Zara ,Salary:  2000
Name :  Manni ,Salary:  5000
Total Employee 2
You can add, remove, or modify attributes of classes and objects at any time -

emp1.age = 7  # Add an 'age' attribute.
emp1.age = 8  # Modify 'age' attribute.
del emp1.age  # Delete 'age' attribute.
Instead of using the normal statements to access attributes, you can use the following functions -

The getattr(obj, name[, default]) : to access the attribute of object.

The hasattr(obj,name) : to check if an attribute exists or not.

The setattr(obj,name,value) : to set an attribute. If attribute does not exist, then it would be created.

The delattr(obj, name) : to delete an attribute.

hasattr(emp1, 'age')    # Returns true if 'age' attribute exists
getattr(emp1, 'age')    # Returns value of 'age' attribute
setattr(emp1, 'age', 8) # Set attribute 'age' at 8
delattr(empl, 'age')    # Delete attribute 'age'
Built-In Class Attributes
Every Python class keeps following built-in attributes and they can be accessed using dot operator like any other attribute -

__dict__: Dictionary containing the class's namespace.

__doc__: Class documentation string or none, if undefined.

__name__: Class name.

__module__: Module name in which the class is defined. This attribute is "__main__" in interactive mode.

__bases__: A possibly empty tuple containing the base classes, in the order of their occurrence in the base class list.

For the above class let us try to access all these attributes -

#!/usr/bin/python

class Employee:
   'Common base class for all employees'
   empCount = 0

   def __init__(self, name, salary):
      self.name = name
      self.salary = salary
      Employee.empCount += 1
 
   def displayCount(self):
     print "Total Employee %d" % Employee.empCount

   def displayEmployee(self):
      print "Name : ", self.name,  ", Salary: ", self.salary

print "Employee.__doc__:", Employee.__doc__
print "Employee.__name__:", Employee.__name__
print "Employee.__module__:", Employee.__module__
print "Employee.__bases__:", Employee.__bases__
print "Employee.__dict__:", Employee.__dict__
When the above code is executed, it produces the following result -

Employee.__doc__: Common base class for all employees
Employee.__name__: Employee
Employee.__module__: __main__
Employee.__bases__: ()
Employee.__dict__: {'__module__': '__main__', 'displayCount':
<function displayCount at 0xb7c84994>, 'empCount': 2,
'displayEmployee': <function displayEmployee at 0xb7c8441c>,
'__doc__': 'Common base class for all employees',
'__init__': <function __init__ at 0xb7c846bc>}
Destroying Objects (Garbage Collection)
Python deletes unneeded objects (built-in types or class instances) automatically to free the memory space. The process by which Python periodically reclaims blocks of memory that no longer are in use is termed Garbage Collection.

Python's garbage collector runs during program execution and is triggered when an object's reference count reaches zero. An object's reference count changes as the number of aliases that point to it changes.

An object's reference count increases when it is assigned a new name or placed in a container (list, tuple, or dictionary). The object's reference count decreases when it's deleted with del, its reference is reassigned, or its reference goes out of scope. When an object's reference count reaches zero, Python collects it automatically.

a = 40      # Create object <40>
b = a       # Increase ref. count  of <40>
c = [b]     # Increase ref. count  of <40>

del a       # Decrease ref. count  of <40>
b = 100     # Decrease ref. count  of <40>
c[0] = -1   # Decrease ref. count  of <40>
You normally will not notice when the garbage collector destroys an orphaned instance and reclaims its space. But a class can implement the special method __del__(), called a destructor, that is invoked when the instance is about to be destroyed. This method might be used to clean up any non memory resources used by an instance.

Example
This __del__() destructor prints the class name of an instance that is about to be destroyed -

#!/usr/bin/python

class Point:
   def __init( self, x=0, y=0):
      self.x = x
      self.y = y
   def __del__(self):
      class_name = self.__class__.__name__
      print class_name, "destroyed"

pt1 = Point()
pt2 = pt1
pt3 = pt1
print id(pt1), id(pt2), id(pt3) # prints the ids of the obejcts
del pt1
del pt2
del pt3
When the above code is executed, it produces following result -

3083401324 3083401324 3083401324
Point destroyed
Note: Ideally, you should define your classes in separate file, then you should import them in your main program file using import statement.

Class Inheritance
Instead of starting from scratch, you can create a class by deriving it from a preexisting class by listing the parent class in parentheses after the new class name.

The child class inherits the attributes of its parent class, and you can use those attributes as if they were defined in the child class. A child class can also override data members and methods from the parent.

Syntax
Derived classes are declared much like their parent class; however, a list of base classes to inherit from is given after the class name -

class SubClassName (ParentClass1[, ParentClass2, ...]):
   'Optional class documentation string'
   class_suite
Example
#!/usr/bin/python

class Parent:        # define parent class
   parentAttr = 100
   def __init__(self):
      print "Calling parent constructor"

   def parentMethod(self):
      print 'Calling parent method'

   def setAttr(self, attr):
      Parent.parentAttr = attr

   def getAttr(self):
      print "Parent attribute :", Parent.parentAttr

class Child(Parent): # define child class
   def __init__(self):
      print "Calling child constructor"

   def childMethod(self):
      print 'Calling child method'

c = Child()          # instance of child
c.childMethod()      # child calls its method
c.parentMethod()     # calls parent's method
c.setAttr(200)       # again call parent's method
c.getAttr()          # again call parent's method
When the above code is executed, it produces the following result -

Calling child constructor
Calling child method
Calling parent method
Parent attribute : 200
Similar way, you can drive a class from multiple parent classes as follows -

class A:        # define your class A
.....

class B:         # define your calss B
.....

class C(A, B):   # subclass of A and B
.....
You can use issubclass() or isinstance() functions to check a relationships of two classes and instances.

The issubclass(sub, sup) boolean function returns true if the given subclass sub is indeed a subclass of the superclass sup.

The isinstance(obj, Class) boolean function returns true if obj is an instance of class Class or is an instance of a subclass of Class

Overriding Methods
You can always override your parent class methods. One reason for overriding parent's methods is because you may want special or different functionality in your subclass.

Example
#!/usr/bin/python

class Parent:        # define parent class
   def myMethod(self):
      print 'Calling parent method'

class Child(Parent): # define child class
   def myMethod(self):
      print 'Calling child method'

c = Child()          # instance of child
c.myMethod()         # child calls overridden method

When the above code is executed, it produces the following result -

Calling child method


Overloading Operators

Suppose you have created a Vector class to represent two-dimensional vectors, what happens when you use the plus operator to add them? Most likely Python will yell at you.

You could, however, define the __add__ method in your class to perform vector addition and then the plus operator would behave as per expectation -

Example
#!/usr/bin/python

class Vector:
   def __init__(self, a, b):
      self.a = a
      self.b = b

   def __str__(self):
      return 'Vector (%d, %d)' % (self.a, self.b)
 
   def __add__(self,other):
      return Vector(self.a + other.a, self.b + other.b)

v1 = Vector(2,10)
v2 = Vector(5,-2)
print v1 + v2

When the above code is executed, it produces the following result -

Vector(7,8)

Data Hiding

An object's attributes may or may not be visible outside the class definition. You need to name attributes with a double underscore prefix, and those attributes then are not be directly visible to outsiders.

Example:


#!/usr/bin/python


class JustCounter:

   __secretCount = 0

 

   def count(self):

      self.__secretCount += 1

      print self.__secretCount


counter = JustCounter()

counter.count()

counter.count()

print counter.__secretCount

When the above code is executed, it produces the following result -

1
2
Traceback (most recent call last):
  File "test.py", line 12, in <module>
    print counter.__secretCount
AttributeError: JustCounter instance has no attribute '__secretCount'
Python protects those members by internally changing the name to include the class name. You can access such attributes as object._className__attrName. If you would replace your last line as following, then it works for you -

.........................
print counter._JustCounter__secretCount

When the above code is executed, it produces the following result -

1
2
2

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.

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

Date and Time

Python is very useful in case of Date and Time. We can easily retrieve current date and time using Python.

Retrieve Time

To retrieve current time a predefined function localtime() is used. localtime() receives a parameter time.time() . Here,

time is a module,

time() is a function that returns the current system time in number of ticks since 12:00 am , January 1,1970. It is known as epoch.

Tick is simply a floating point number in seconds since epoch.

eg:

import time;
localtime = time.localtime(time.time())
print "Current Time is :", localtime

Output:

>>>
Current Time is :time.struct_time(tm_year=2014, tm_mon=6, tm_mday=18, tm_hour=12,  
tm_min=35, tm_sec=44, tm_wday=2, tm_yday=169, tm_isdst=0)
>>>

Calendar

Python provides calendar module to display Calendar.

Eg:

import calendar
print "Current month is:"
cal = calendar.month(2014, 6)
printcal

Output:

>>>
Current month is:
      June 2014
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
>>>  

Exception Handling

Exception can be said to be any abnormal condition in a program resulting to the disruption in the flow of the program.

Whenever an exception occurs the program halts the execution and thus further code is not executed. Thus exception is that error which python script is unable to tackle with.

Exception in a code can also be handled. In case it is not handled, then the code is not executed further and hence execution stops when exception occurs.

Hierarchy Of Exception:

1. ZeroDivisionError : Occurs when a number is divided by zero.
2. NameError : It occurs when a name is not found. It may be local or global.
3. IndentationError : If incorrect indentation is given.
4. IOError : It occurs when Input Output operation fails.
5. EOFError : It occurs when end of file is reached and yet operations are being performed

etc..

Exception Handling:

The suspicious code can be handled by using the try block. Enclose the code which raises an exception inside the try block. The try block is followed except statement. It is then further followed by statements which are executed during exception and in case if exception does not occur.

Syntax:

try:
    malicious code
except Exception1:
    execute code
except Exception2:
    execute code
....
....
except ExceptionN:
    execute code
else:
    In case of no exception, execute the else block code.

eg:

try:
    a=10/0
    print a
except ArithmeticError:
        print "This statement is raising an exception"
else:
    print "Welcome"

Output:

>>>  
This statement is raising an exception
>>>

Explanation:

1. The malicious code (code having exception) is enclosed in the try block.
2. Try block is followed by except statement. There can be multiple except statement with a single try block.
3. Except statement specifies the exception which occurred. In case that exception is occurred, the corresponding statement will be executed.
4. At the last you can provide else statement. It is executed when no exception is occurred.

Except with no Exception:

Except statement can also be used without specifying Exception.

Syntax:

try:
        code
    except:
        code to be executed in case exception occurs.
    else:
        code to be executed in case exception does not occur.  

eg:

try:
    a=10/0;
except:
    print "Arithmetic Exception"
else:
    print "Successfully Done"

Output:

>>>  
Arithmetic Exception
>>>

Declaring Multiple Exception

Multiple Exceptions can be declared using the same except statement:

Syntax:

try:
    code
except Exception1,Exception2,Exception3,..,ExceptionN
    execute this code in case any Exception of these occur.
else:
    execute code in case no exception occurred.
eg:

try:
    a=10/0;
except ArithmeticError,StandardError:
    print "Arithmetic Exception"
else:
    print "Successfully Done"

Output:

>>>  
Arithmetic Exception
>>>

Finally Block:

In case if there is any code which the user want to be executed, whether exception occurs or not then that code can be placed inside the finally block. Finally block will always be executed irrespective of the exception.

Syntax:

try:
    Code
finally:  
    code which is must to be executed.

eg:

try:
    a=10/0;
    print "Exception occurred"
finally:
    print "Code to be executed"

Output:

>>>  
Code to be executed
Traceback (most recent call last):
  File "C:/Python27/noexception.py", line 2, in <module>
    a=10/0;
ZeroDivisionError: integer division or modulo by zero
>>>

In the above example finally block is executed. Since exception is not handled therefore exception occurred and execution is stopped.

Raise an Exception:

You can explicitly throw an exception in Python using 'raise' statement. raise will cause an exception to occur and thus execution control will stop in case it is not handled.

Syntax:

raise Exception_class,<value>
eg:

try:
    a=10
    print a
    raise NameError("Hello")
except NameError as e:
        print "An exception occurred"
        print e

Output:

>>>  
10
An exception occurred
Hello
>>>

Explanation:

i) To raise an exception, raise statement is used. It is followed by exception class name.

ii) Exception can be provided with a value that can be given in the parenthesis. (here, Hello)

iii) To access the value "as" keyword is used. "e" is used as a reference variable which stores the value of the exception.

Custom Exception:

Refer to this section after visiting Class and Object section:

Creating your own Exception class or User Defined Exceptions are known as Custom Exception.

eg:

class ErrorInCode(Exception):
     def __init__(self, data):
   self.data = data
     def __str__(self):
        return repr(self.data)
 
try:
    raise ErrorInCode(2000)
except ErrorInCode as ae:
    print "Received error:", ae.data
Output:

>>>  
Received error : 2000
>>>  

Module

Modules are used to categorize code in Python into smaller part. A module is simply a file, where classes, functions and variables are defined. Grouping similar code into a single file makes it easy to access.

Have a look over example:

If the content of a book is not indexed or categorized into individual chapters, then the book might have turned boring and hectic. Hence, dividing book into chapters made it easy to understand.

In the same sense python modules are the files which have similar code. Thus module is simplify a python code where classes, variables and functions are defined.

Advantage:

Python provides the following advantages for using module:

1) Reusability: Module can be used in some other python code. Hence it provides the facility of code reusability.

2) Categorization: Similar type of attributes can be placed in one module.

Importing a Module:

There are different ways by which you we can import a module. These are as follows:

1) Using import statement:

"import" statement can be used to import a module.

Syntax:

import <file_name1, file_name2,...file_name(n)="">
</file_name1,>
Have a look over an example:

eg:

def add(a,b):
    c=a+b
    print c
    return

Save the file by the name addition.py. To import this file "import" statement is used.

import addition
addition.add(10,20)
addition.add(30,40)

Create another python file in which you want to import the former python file. For that, import statement is used as given in the above example. The corresponding method can be used by file_name.method (). (Here, addition. add (), where addition is the python file and add () is the method defined in the file addition.py)

Output:

>>>  
30
70
>>>

NOTE: You can access any function which is inside a module by module name and function name separated by dot. It is also known as period. Whole notation is known as dot notation.

Example of importing multiple modules:

Eg:

1) msg.py:

def msg_method():
    print "Today the weather is rainy"
    return

2) display.py:

def display_method():
    print "The weather is Sunny"
    return

3) multiimport.py:

import msg,display
msg.msg_method()
display.display_method()

Output:

>>>  
Today the weather is rainy
The weather is Sunny
>>>      

2) Using from.. import statement:

from..import statement is used to import particular attribute from a module. In case you do not want whole of the module to be imported then you can use from ?import statement.

Syntax:

from  <module_name> import <attribute1,attribute2,attribute3,...attributen>    
</attribute1,attribute2,attribute3,...attributen></module_name>

Have a look over the example:

1) area.py

Eg:

def circle(r):
    print 3.14*r*r
    return
 
def square(l):
    print l*l
    return
 
def rectangle(l,b):
    print l*b
    return
 
def triangle(b,h):
    print 0.5*b*h
    return

2) area1.py

from area import square,rectangle
square(10)
rectangle(2,5)
Output:

>>>  
100
10
>>>

3) To import whole module:

You can import whole of the module using "from? import *"

Syntax:

from <module_name> import *
</module_name>
Using the above statement all the attributes defined in the module will be imported and hence you can access each attribute.

1) area.py

Same as above example

2) area1.py

from area import *
square(10)
rectangle(2,5)
circle(5)
triangle(10,20)

Output:

>>>  
100
10
78.5
100.0
>>>

Built in Modules in Python:

There are many built in modules in Python. Some of them are as follows:

math, random , threading , collections , os , mailbox , string , time , tkinter etc..

Each module has a number of built in functions which can be used to perform various functions.

Input And Output

Python can be used to read and write data. Also it supports reading and writing data to Files.

"print" statement:

"print" statement is used to print the output on the screen.

print statement is used to take string as input and place that string to standard output.

Whatever you want to display on output place that expression inside the inverted commas. The expression whose value is to printed place it without inverted commas.

Syntax:

print "expression"  or  print expression.

eg:


a=10 
print "Welcome to the world of Python"
print a

Output:

>>>
Welcome to the world of Python
10
>>>    
Input from Keyboard:

Python offers two in-built functions for taking input from user. They are:

1) input()

2) raw_input()

1) input() functioninput() function is used to take input from the user. Whatever expression is given by the user, it is evaluated and result is returned back.

Syntax:

input("Expression")
eg:

n=input("Enter your expression ");
print "The evaluated expression is ", n

Output:

>>>
Enter your expression 10*2
The evaluated expression is  20
>>>    

2) raw_input()raw_input() function is used to take input from the user. It takes the input from the Standard input in the form of a string and reads the data from a line at once.

Syntax:

raw_input(?statement?)
eg:

n=raw_input("Enter your name ");
print "Welcome ", n

Output:

>>>
Enter your name Rajat
Welcome  Rajat
>>>  

raw_input() function returns a string. Hence in case an expression is to be evaluated, then it has to be type casted to its following data type. Some of the examples are given below:

Program to calculate Simple Interest.

prn=int(raw_input("Enter Principal"))
r=int(raw_input("Enter Rate"))
t=int(raw_input("Enter Time"))
si=(prn*r*t)/100
print "Simple Interest is ",si  

Output:

>>>
Enter Principal1000
Enter Rate10
Enter Time2
Simple Interest is  200
>>>  

#Program to enter details of an user and print them.

name=raw_input("Enter your name ")
math=float(raw_input("Enter your marks in Math"))
physics=float(raw_input("Enter your marks in Physics"))
chemistry=float(raw_input("Enter your marks in Chemistry"))
rollno=int(raw_input("Enter your Roll no"))
print "Welcome ",name
print "Your Roll no is ",rollno
print "Marks in Maths is ",math
print "Marks in Physics is ",physics
print "Marks in Chemistry is ",chemistry
print "Average marks is ",(math+physics+chemistry)/3

Output:

>>>
Enter your name rajat
Enter your marks in Math76.8
Enter your marks in Physics71.4
Enter your marks in Chemistry88.4
Enter your Roll no0987645672
Welcome  rajat
Your Roll no is  987645672
Marks in Maths is  76.8
Marks in Physics is  71.4
Marks in Chemistry is  88.4
Average marks is  78.8666666667
>>>

File Handling:

Python provides the facility of working on Files. A File is an external storage on hard disk from where data can be stored and retrieved.

Operations on Files:

1) Opening a File: Before working with Files you have to open the File. To open a File, Python built in function open() is used. It returns an object of File which is used with other functions. Having opened the file now you can perform read, write, etc. operations on the File.

Syntax:

obj=open(filename , mode , buffer)
here,

filename:It is the name of the file which you want to access.

mode:It specifies the mode in which File is to be opened.There are many types of mode. Mode depends the operation to be performed on File. Default access mode is read.

2) Closing a File:Once you are finished with the operations on File at the end you need to close the file. It is done by the close() method. close() method is used to close a File.

Syntax:

fileobject.close()

3) Writing to a File:write() method is used to write a string into a file.

Syntax:

fileobject.write(string str)

4) Reading from a File:read() method is used to read data from the File.

Syntax:

fileobject.read(value)

Here, value is the number of bytes to be read. In case, no value is given it reads till end of file is reached.

Program to read and write data from a file.

obj=open("abcd.txt","w")
obj.write("Welcome to the world of Python")
obj.close()
obj1=open("abcd.txt","r")
s=obj1.read()
print s
obj1.close()
obj2=open("abcd.txt","r")
s1=obj2.read(20)
print s1
obj2.close()
Output:

>>>
Welcome to the world of Python
Welcome to the world
>>>  

Functions

A Function is a self block of code.

A Function can be called as a section of a program that is written once and can be executed whenever required in the program, thus making code reusability.

A Function is a subprogram that works on data and produce some output.

Types of Functions:

There are two types of Functions.

a) Built-in Functions: Functions that are predefined. We have used many predefined functions in Python.

b) User- Defined: Functions that are created according to the requirements.

Defining a Function:

A Function defined in Python should follow the following format:

1) Keyword def is used to start the Function Definition. Def specifies the starting of Function block.

2) def is followed by function-name followed by parenthesis.

3) Parameters are passed inside the parenthesis. At the end a colon is marked.

Syntax:

def <function_name>([parameters]):
</function_name>

eg:

def sum(a,b):

4) Before writing a code, an Indentation (space) is provided before every statement. It should be same for all statements inside the function.

5) The first statement of the function is optional. It is ?Documentation string? of function.

6) Following is the statement to be executed.

Invoking a Function:

To execute a function it needs to be called. This is called function calling.

Function Definition provides the information about function name, parameters and the definition what operation is to be performed. In order to execute the Function Definition it is to be called.

Syntax:

<function_name>(parameters)
</function_name>

eg:

sum(a,b)

Here sum is the function and a, b are the parameters passed to the Function Definition.

Let's have a look over an example:

eg:

#Providing Function Definition

def sum(x,y):
    "Going to add x and y"
    s=x+y
    print "Sum of two numbers is"
    print s
    #Calling the sum Function
    sum(10,20)
    sum(20,30)

Output:

>>>
Sum of two numbers is
30
Sum of two numbers is
50
>>>

NOTE: Function call will be executed in the order in which it is called.

return Statement:

return[expression] is used to send back the control to the caller with the expression.

In case no expression is given after return it will return None.

In other words return statement is used to exit the Function definition.

Eg:

def sum(a,b):
        "Adding the two values"
        print "Printing within Function"
print a+b
        return a+b

def msg():
print "Hello"
return

total=sum(10,20)
print('Printing Outside: ',total)
msg()
print "Rest of code"

Output:

>>>
Printing within Function
30
Printing outside:  30
Hello
Rest of code
>>>

Argument and Parameter:

There can be two types of data passed in the function.

1) The First type of data is the data passed in the function call. This data is called ?arguments?.

2) The second type of data is the data received in the function definition. This data is called ?parameters?.

Arguments can be literals, variables and expressions.

Parameters must be variable to hold incoming values.

Alternatively, arguments can be called as actual parameters or actual arguments and parameters can be called as formal parameters or formal arguments.

Eg:

def addition(x,y):
            print x+y
x=15
addition(x ,10)
addition(x,x)
y=20
addition(x,y)

Output:

>>>
25
30
35
>>>

Passing Parameters

Apart from matching the parameters, there are other ways of matching the parameters.

Python supports following types of formal argument:

1) Positional argument (Required argument).

2) Default argument.

3) Keyword argument (Named argument)

Positional/Required Arguments:

When the function call statement must match the number and order of arguments as defined in the function definition it is Positional Argument matching.

Eg:

#Function definition of sum
def sum(a,b):
"Function having two parameters"
c=a+b
print c

sum(10,20)
sum(20)

Output:

>>>
30

Traceback (most recent call last):
    File "C:/Python27/su.py", line 8, in <module>
        sum(20)
TypeError: sum() takes exactly 2 arguments (1 given)
>>>
</module>

Explanation:

1) In the first case, when sum() function is called passing two values i.e., 10 and 20 it matches with function definition parameter and hence 10 and 20 is assigned to a and b respectively. The sum is calculated and printed.

2) In the second case, when sum() function is called passing a single value i.e., 20 , it is passed to function definition. Function definition accepts two parameters whereas only one value is being passed, hence it will show an error.

Default Arguments

Default Argument is the argument which provides the default values to the parameters passed in the function definition, in case value is not provided in the function call.

Eg:

#Function Definition
def msg(Id,Name,Age=21):
"Printing the passed value"
print Id
print Name
print Age
return

#Function call
msg(Id=100,Name='Ravi',Age=20)
msg(Id=101,Name='Ratan')

Output:

>>>
100
Ravi
20
101
Ratan
21
>>>

Explanation:

1) In first case, when msg() function is called passing three different values i.e., 100 , Ravi and 20, these values will be assigned to respective parameters and thus respective values will be printed.

2) In second case, when msg() function is called passing two values i.e., 101 and Ratan, these values will be assigned to Id and Name respectively. No value is assigned for third argument via function call and hence it will retain its default value i.e, 21.

Keyword Arguments:

Using the Keyword Argument, the argument passed in function call is matched with function definition on the basis of the name of the parameter.

Eg:

def msg(id,name):
"Printing passed value"
print id
print name
return

msg(id=100,name='Raj')
msg(name='Rahul',id=101)

Output:

>>>
100
Raj
101
Rahul
>>>

Explanation:

1) In the first case, when msg() function is called passing two values i.e., id and name the position of parameter passed is same as that of function definition and hence values are initialized to respective parameters in function definition. This is done on the basis of the name of the parameter.

2) In second case, when msg() function is called passing two values i.e., name and id, although the position of two parameters is different it initialize the value of id in Function call to id in Function Definition. same with name parameter. Hence, values are initialized on the basis of name of the parameter.

#Calling square as a function
print "Square of number is",square(10)

Output:

>>>
Square of number is 100
>>>

Difference between Normal Functions and Anonymous Function:

Have a look over two examples:

Eg:

Normal function:

#Function Definiton
def square(x):
    return x*x
   
#Calling square function
print "Square of number is",square(10)

Anonymous function:

#Function Definiton
square=lambda x1: x1*x1

#Calling square as a function
print "Square of number is",square(10)

Explanation:

Anonymous is created without using def keyword.

lambda keyword is used to create anonymous function.

It returns the evaluated expression.

Scope of Variable:

Scope of a variable can be determined by the part in which variable is defined. Each variable cannot be accessed in each part of a program. There are two types of variables based on Scope:

1) Local Variable.

2) Global Variable.

1) Local Variables:

Variables declared inside a function body is known as Local Variable. These have a local access thus these variables cannot be accessed outside the function body in which they are declared.

Eg:

def msg():
           a=10
           print "Value of a is",a
           return

msg()
print a #it will show error since variable is local

Output:

>>>
Value of a is 10

Traceback (most recent call last):
    File "C:/Python27/lam.py", line 7, in <module>
     print a #it will show error since variable is local
NameError: name 'a' is not defined
>>>
</module>

b) Global Variable:

Variable defined outside the function is called Global Variable. Global variable is accessed all over program thus global variable have widest accessibility.

Eg:

b=20
def msg():
           a=10
           print "Value of a is",a
           print "Value of b is",b
           return

           msg()
           print b

  Output:

>>>
Value of a is 10
Value of b is 20
20
>>>

Dictionary

Dictionary is an unordered set of key and value pair.

It is an container that contains data, enclosed within curly braces.

The pair i.e., key and value is known as item.

The key passed in the item must be unique.

The key and the value is separated by a colon(:). This pair is known as item. Items are separated from each other by a comma(,). Different items are enclosed within a curly brace and this forms Dictionary.

eg:

data={100:'Ravi' ,101:'Vijay' ,102:'Rahul'}
print(data)

Output:

>>>  
{100: 'Ravi', 101: 'Vijay', 102: 'Rahul'}
>>>

Dictionary is mutable i.e., value can be updated.

Key must be unique and immutable. Value is accessed by key. Value can be updated while key cannot be changed.

Dictionary is known as Associative array since the Key works as Index and they are decided by the user.

eg:

plant={}
plant[1]='Ravi'
plant[2]='Manoj'
plant['name']='Hari'
plant[4]='Om'
print plant[2]
print plant['name']
print plant[1]
print plant  

Output:

>>>
Manoj
Hari
Ravi
{1: 'Ravi', 2: 'Manoj', 4: 'Om', 'name': 'Hari'}
>>>

Accessing Values

Since Index is not defined, a Dictionaries value can be accessed by their keys.

Syntax:

[key]

Eg:

data1={'Id':100, 'Name':'Suresh', 'Profession':'Developer'}
data2={'Id':101, 'Name':'Ramesh', 'Profession':'Trainer'}
print "Id of 1st employer is",data1['Id']
print "Id of 2nd employer is",data2['Id']
print "Name of 1st employer:",data1['Name']
print "Profession of 2nd employer:",data2['Profession']

Output:

>>>
Id of 1st employer is 100
Id of 2nd employer is 101
Name of 1st employer is Suresh
Profession of 2nd employer is Trainer
>>>

Updation

The item i.e., key-value pair can be updated. Updating means new item can be added. The values can be modified.

Eg:

data1={'Id':100, 'Name':'Suresh', 'Profession':'Developer'}
data2={'Id':101, 'Name':'Ramesh', 'Profession':'Trainer'}
data1['Profession']='Manager'
data2['Salary']=20000
data1['Salary']=15000
print data1
print data2

Output:

>>>
{'Salary': 15000, 'Profession': 'Manager','Id': 100, 'Name': 'Suresh'}
{'Salary': 20000, 'Profession': 'Trainer', 'Id': 101, 'Name': 'Ramesh'}
>>>

Deletion

del statement is used for performing deletion operation.

An item can be deleted from a dictionary using the key.

Syntax:

del  [key]

Whole of the dictionary can also be deleted using the del statement.

Eg:

data={100:'Ram', 101:'Suraj', 102:'Alok'}
del data[102]
print data
del data
print data   #will show an error since dictionary is deleted.

Output:

>>>
{100: 'Ram', 101: 'Suraj'}

Traceback (most recent call last):
  File "C:/Python27/dict.py", line 5, in
   print data
NameError: name 'data' is not defined
>>>

Tuple

A tuple is a sequence of immutable objects, therefore tuple cannot be changed.

The objects are enclosed within parenthesis and separated by comma.

Tuple is similar to list. Only the difference is that list is enclosed between square bracket, tuple between parenthesis and List have mutable objects whereas Tuple have immutable objects.

eg:

>>> data=(10,20,'ram',56.8)
>>> data2="a",10,20.9

>>> data
(10, 20, 'ram', 56.8)

>>> data2
('a', 10, 20.9)
>>>

NOTE: If Parenthesis is not given with a sequence, it is by default treated as Tuple.

There can be an empty Tuple also which contains no object.

eg:

tuple1=()

For a single valued tuple, there must be a comma at the end of the value.

eg:

Tuple1=(10,)

Tuples can also be nested.

eg:

tupl1='a','gaurav',10.56
tupl2=tupl1,(10,20,30)
print tupl1
print tupl2

Output:

>>>  
('a', 'gaurav', 10.56)
(('a', 'gaurav', 10.56), (10, 20, 30))
>>>

Accessing Tuple

Tuple can be accessed in the same way as List.

Some examples are given below:

eg:

data1=(1,2,3,4)
data2=('x','y','z')
print data1[0]
print data1[0:2]
print data2[-3:-1]
print data1[0:]
print data2[:2]

Output:

>>>  
1
(1, 2)
('x', 'y')
(1, 2, 3, 4)
('x', 'y')
>>>

Tuple Operations

Various Operations can be performed on Tuple. Operations performed on Tuple are given as:

a) Adding Tuple:

Tuple can be added by using the concatenation operator(+) to join two tuples.

eg:

data1=(1,2,3,4)
data2=('x','y','z')
data3=data1+data2
print data1
print data2
print data3
Output:

>>>
(1, 2, 3, 4)
('x', 'y', 'z')
(1, 2, 3, 4, 'x', 'y', 'z')
>>>
Note: The new sequence formed is a new Tuple.

b) Replicating Tuple:

Replicating means repeating. It can be performed by using '*' operator by a specific number of time.

Eg:

tuple1=(10,20,30);
tuple2=(40,50,60);
print tuple1*2
print tuple2*3
Output:

>>>
(10, 20, 30, 10, 20, 30)
(40, 50, 60, 40, 50, 60, 40, 50, 60)
>>>

c) Tuple slicing:

A subpart of a tuple can be retrieved on the basis of index. This subpart is known as tuple slice.

Eg:

data1=(1,2,4,5,7)
print data1[0:2]
print data1[4]
print data1[:-1]
print data1[-5:]
print data1

Output:

>>>
(1, 2)
7
(1, 2, 4, 5)
(1, 2, 4, 5, 7)
(1, 2, 4, 5, 7)
>>>

Note: If the index provided in the Tuple slice is outside the list, then it raises an IndexError exception.

Other Operations:

a) Updating elements in a List:

Elements of the Tuple cannot be updated. This is due to the fact that Tuples are immutable. Whereas the Tuple can be used to form a new Tuple.

Eg:

data=(10,20,30)
data[0]=100
print data
Output:


>>>
Traceback (most recent call last):
  File "C:/Python27/t.py", line 2, in
    data[0]=100
TypeError: 'tuple' object does not support item assignment
>>>

Creating a new Tuple from existing:

Eg:

data1=(10,20,30)
data2=(40,50,60)
data3=data1+data2
print data3

Output:

>>>
(10, 20, 30, 40, 50, 60)
>>>

b) Deleting elements from Tuple:

Deleting individual element from a tuple is not supported. However the whole of the tuple can be deleted using the del statement.

Eg:

data=(10,20,'rahul',40.6,'z')
print data
del data      #will delete the tuple data
print data  #will show an error since tuple data is already deleted
Output:

>>>
(10, 20, 'rahul', 40.6, 'z')
Traceback (most recent call last):
  File "C:/Python27/t.py", line 4, in
    print data
NameError: name 'data' is not defined
>>>

List

1. Python lists are the data structure that is capable of holding different type of data.

2. Python lists are mutable i.e., Python will not create a new list if we modify an element in the list.

3. It is a container that holds other objects in a given order. Different operation like insertion and deletion can be performed on lists.

4. A list can be composed by storing a sequence of different type of values separated by commas.

5. A python list is enclosed between square([]) brackets.

6. The elements are stored in the index basis with starting index as 0.

eg:

data1=[1,2,3,4];
data2=['x','y','z'];
data3=[12.5,11.6];
data4=['raman','rahul'];
data5=[];
data6=['abhinav',10,56.4,'a'];

Accessing Lists

A list can be created by putting the value inside the square bracket and separated by comma.

Syntax:

<list_name>=[value1,value2,value3,...,valuen];

For accessing list :

<list_name>[index]

Different ways to access list:

Eg:

data1=[1,2,3,4];
data2=['x','y','z'];
print(data1[0])
print(data1[0:2])
print(data2[-3:-1])
print(data1[0:])
print(data2[:2])

Output:

>>>
1
[1, 2]
['x', 'y']
[1, 2, 3, 4]
['x', 'y']
>>>

Note: List do not store the elements directly at the index. In fact a reference is stored at each index which subsequently refers to the object stored somewhere in the memory. This is due to the fact that some objects may be large enough than other objects and hence they are stored at some other memory location.

List Operations:

Various Operations can be performed on List. Operations performed on List are given as:

a) Adding Lists:

Lists can be added by using the concatenation operator(+) to join two lists.

Eg:

list1=[10,20]
list2=[30,40]
list3=list1+list2
print(list3)

Output:

>>>  
[10, 20, 30, 40]
>>>

Note: '+'operator implies that both the operands passed must be list else error will be shown.

Eg:

list1=[10,20]
list1+30
print (list1)

Output:

Traceback (most recent call last):
        File "C:/Python27/lis.py", line 2, in <module>
            list1+30

b) Replicating lists:

Replicating means repeating . It can be performed by using '*' operator by a specific number of time.

Eg:

list1=[10,20]
print(list1*1)

Output:

>>>  
[10, 20]
>>>

c) List slicing:

A subpart of a list can be retrieved on the basis of index. This subpart is known as list slice.

Eg:

list1=[1,2,4,5,7]
print(list1[0:2])
print(list1[4])
list1[1]=9
print(list1)

Output:

>>>  
[1, 2]
7
[1, 9, 4, 5, 7]
>>>

Note: If the index provided in the list slice is outside the list, then it raises an IndexError exception.

Other Operations:

Apart from above operations various other functions can also be performed on List such as Updating, Appending and Deleting elements from a List:

a) Updating elements in a List:

To update or change the value of particular index of a list, assign the value to that particular index of the List.

Syntax:

<list_name>[index]=<value>

Eg:

data1=[5,10,15,20,25]
print("Values of list are: ")
print(data1)
data1[2]="Multiple of 5"
print("Values of list are: ")
print(data1)

Output:

>>>  
Values of list are:  
[5, 10, 15, 20, 25]
Values of list are:  
[5, 10, 'Multiple of 5', 20, 25]
>>>

b) Appending elements to a List:

append() method is used to append i.e., add an element at the end of the existing elements.

Syntax:

<list_name>.append(item)

Eg:

list1=[10,"rahul",'z']
print "Elements of List are: "
print list1
list1.append(10.45)
print "List after appending: "
print list1

Output:

>>>  
Elements of List are:  
[10, 'rahul', 'z']
List after appending:  
[10, 'rahul', 'z', 10.45]
>>>

c) Deleting Elements from a List:

del statement can be used to delete an element from the list. It can also be used to delete all items from startIndex to endIndex.

Eg:

list1=[10,'rahul',50.8,'a',20,30]
print list1
del list1[0]
print list1
del list1[0:3]
print list1

Output:

>>>  
[10, 'rahul', 50.8, 'a', 20, 30]
['rahul', 50.8, 'a', 20, 30]
[20, 30]
>>>

Strings

Strings are the simplest and easy to use in Python.

String pythons are immutable.

We can simply create Python String by enclosing a text in single as well as double quotes. Python treat both single and double quotes statements same.

Accessing Strings:

In Python, Strings are stored as individual characters in a contiguous memory location.
The benefit of using String is that it can be accessed from both the directions in forward and backward.
Both forward as well as backward indexing are provided using Strings in Python.
Forward indexing starts with 0,1,2,3,....
Backward indexing starts with -1,-2,-3,-4,....

Simple program to retrieve String in reverse as well as normal form.

name="Gaurav"
length=len(name)
i=0
for n in range(-1,(-length-1),-1):
    print(name[i],"\t",name[n])
    i+=1

Output :

>>>>>>>>>>>>>>>>
G v
a a
u r
r u
a a
v G
>>>>>>>>>>>>>>

Strings Operators

There are basically 3 types of Operators supported by String:

1. Basic Operators

There are two types of basic operators in String. They are "+" and "*".

String Concatenation Operator : (+)

The concatenation operator (+) concatenate two Strings and forms a new String.

eg:

fullName = "Gaurav" + "Khanna"
print(fullName)

Output :

GauravKhanna

NOTE: Both the operands passed for concatenation must be of same type, else it will show an error.

Replication Operator : (*)

Replication operator uses two parameter for operation. One is the integer value and the other one is the String.

The Replication operator is used to repeat a string number of times. The string will be repeated the number of times which is given by the integer value.

Eg:

>>> 5*"Gaurav"

Output:

'GauravGauravGauravGauravGaurav'

NOTE: We can use Replication operator in any way i.e., int * string or string * int. Both the parameters passed cannot be of same type.

2. Membership Operators

There are two types of Membership operators:

1) in : "in" operator return true if a character or the entire substring is present in the specified string, otherwise false.

2) not in : "not in" operator return true if a character or entire substring does not exist in the specified string, otherwise false.

Eg:

>>> str1="notjustatester"
>>> str2='sssit'
>>> str3="seomount"
>>> str4='not'
>>> st5="it"
>>> str6="seo"

>>> str4 in str1
True

>>> str5 in str2
True

>>> str6 in str3
True

>>> str4 not in str1
False

>>> str1 not in str4
True

3. Relational Operators:

All the comparison operators i.e., (<,><=,>=,==,!=,<>) are also applicable to strings. The Strings are compared based on the ASCII value or Unicode(i.e., dictionary Order).

Eg:

>>> "GAURAV"=="GAURAV"
True

>>> "gaurav">='Gaurav'
True

>>> "Z"<>"z"
True

Explanation:

The ASCII value of a is 97, b is 98, c is 99 and so on. The ASCII value of A is 65,B is 66,C is 67 and so on. The comparison between strings are done on the basis on ASCII value.

For Loop

for Loop is used to iterate a variable over a sequence(i.e., list or string) in the order that they appear.

Syntax:

for <variable> in <sequence>:

Output:

1
 
7
 
9

Explanation:

Firstly, the first value will be assigned in the variable.

Secondly all the statements in the body of the loop are executed with the same value.

Thirdly, once step second is completed then variable is assigned the next value in the sequence and step second is repeated.

Finally, it continues till all the values in the sequence are assigned in the variable and processed.

#Program to display table of Number

num=2
for a in range (1,6):
    print (num * a)

Output:

2  
4
6  
8
10

#Program to find sum of Natural numbers from 1 to 10.

sum=0
for n in range(1,11):
    sum += n
print(sum)

Output:

55  

While Loop

while Loop is used to execute number of statements or body till the condition passed in while is true. Once the condition is false, the control will come out of the loop.

Syntax:

while <expression>:
        Body

Here, body will execute multiple times till the expression passed is true. The Body may be a single statement or multiple statement.

Eg:

a = 10
while a > 0:
    print("Value of a is", a)
    a -= 2
print('Loop is Completed')

Output:

>>>  
Value of a is 10
Value of a is 8
Value of a is 6
Value of a is 4
Value of a is 2
Loop is Completed
>>>

Explanation:

Firstly, the value in the variable is initialized.

Secondly, the condition/expression in the while is evaluated. Consequently if condition is true, the control enters in the body and executes all the statements . If the condition/expression passed results in false then the control exists the body and straight away control goes to next instruction after body of while.

Thirdly, in case condition was true having completed all the statements, the variable is incremented or decremented. Having changed the value of variable step second is followed. This process continues till the expression/condition becomes false.

Finally Rest of code after body is executed.

#Program to add digits of a number:

n = 153
sum = 0
while n > 0:
    r = n % 10
    sum += r
    n = n / 10
print(sum)

Output:

>>>  
9
>>> 

Break Statement

break statement is a jump statement that is used to pass the control to the end of the loop.

When break statement is applied the control points to the line following the body of the loop , hence applying break statement makes the loop to terminate and controls goes to next line pointing after loop body.

Example :

for i in [1,2,3,4,5]:
    if i==4:
        print('Element found')
        break
    print(i)

Output :

>>>>>>
1
2
3
Element found
>>>>>>

Continue Statement

continue Statement is a jump statement that is used to skip the present iteration and forces next iteration of loop to take place. It can be used in while as well as for loop statements.

Example :

a=0
while a<=5:
    a=a+1
    if a%2==0:
        continue
    print(a)
print("End of Loop")

Output :

>>>>>>>>
1
3
5
End of Loop
>>>>>>>>

Pass Statement

Pass Statement

The pass statement is a null operation; nothing happens when it executes. The pass is also useful in places where your code will eventually go, but has not been written yet (e.g., in stubs for example):

Syntax:

pass

Example :

for i in [1,2,3,4,5]:
    if i==3:
        pass
        print('Pass when value is',i)
    print (i)

Output:

>>>  
1
2
Pass when value is 3
3
4
5
>>>

Example 2 :

for letter in 'Python':
   if letter == 'h':
      pass
      print('This is pass block')
   print('Current Letter :', letter)

print("Good bye!")

Output :

Current Letter : P
Current Letter : y
Current Letter : t
This is pass block
Current Letter : h
Current Letter : o
Current Letter : n
Good bye!

If Else Statments

1. If Statements

The if statement in python is same as c language which is used test a condition. If condition is true, statement of if block is executed otherwise it is skipped.

Syntax of python if statement:

if(condition):
   statements

Example :

a=10
if a==10:
print  ("Hello User")

Output:

Hello User

2. If Else Statements

Syntax:

if(condition):  False
             statements
    else:   True
              statements

Example :

year=2000
if year%4==0:
    print  ("Year is Leap")
else:
    print ("Year is not Leap")

Output:

Year is Leap

3. If Else If Statement:

When we need to check for multiple conditions to be true then we use elif Statement.

This statement is like executing a if statement inside a else statement.

Syntax:

If statement:
    Body
elif statement:
    Body
else:
    Body  

Example:

a = 10
if a >= 20:
    print('Condition is True')
elif a >= 15:
    print('Checking second value')
else:
    print('All Conditions are false')

Output:

All Conditions are false. 

Different Domains for Testing

Domain is nothing but the subject area in which you project belongs to. It may be banking, finance, sales, health, media, telecom, Insurance, Medical, Advertising, Travel, etc.

This is important for a tester because one should know what are the user requirements say in banking, working procedures, commerce background, exposure to brokerage etc and should test application accordingly, then only you can say that your testing is enough because then you have covered scenarios from user perspective.

1. Banking, Financial Services and Insurance : The term BFSI is used very commonly by IT/ITES/BPO Organizations which refers to the services provided by these companies in these domains. Banking includes core banking, retail, corporate and cards. Financial Services include stock-broking, Payment gateways, mutual funds etc. Insurance covers both life and non life.

2. HealthCare : Health care as know in American terms includes several sectors which are very much dedicated to provide services and products in order to improve individual health. This includes health care equipment and pharmaceuticals, services, biotechnology and life sciences. According to United Nations standards, the word health care refers to hospital activities, medical and dental services and other activities related to human health.

3. E-Commerce : Buying and selling of goods services on the internet is termed as “E-Commerce”. Sometimes, the word “e-Business and e-Commerce” are often used interchangeably.

The main aspects of e-Commerce are:

- Online retail selling (e-tailing) on websites with online catalogs
- Usage of demographic data through web contacts
- EDI (Electronic Data Interchange), business to business exchange of data
- Reaching customers through email, social networking and instant messaging
- Buying and selling through business to business
- Maintaining security of business transactions

4. Telecom : Telecom (Telecommunication) is a term used for the process of exchange and transmission of messages electronically. Telecom sector is growing at a greater speed by doubling its growth every passing year. At present, there are many new developments happening, one of the most interesting development is the ingress to 3G technology. MTNL, BSNL, VSNL are the public players involved in the country along with the private players such as Airtel, Vodafone, Idea , Tata, Reliance entering into foreign markets as well.

5. SAAS/Cloud

Comments

Python supports two types of comments:

1) Single lined comment:

In case user wants to specify a single line comment, then comment must start with #

Example :

# This is single line comment.

2) Multi lined Comment:

Multi lined comment can be given inside triple quotes.

Example :

''''' This
    Is
    Multipline comment'''

Example :

#single line comment

print "Hello Python"
'''''This is
multiline comment'''  

Operators

Operators are particular symbols which operate on some values and produce an output.

The values are known as Operands.

Example :

4 + 5 = 9
Here 4 and 5 are Operands and (+) , (=) signs are the operators. They produce the output 9.

Python supports the following operators:

1. Arithmetic Operators

e.g.

>>> 10+20
30
>>> 20-10
10
>>> 10*2
20
>>> 10/2
5
>>> 10%3
1
>>> 2**3
8
>>> 10//3
3
>>>

2. Relational Operators

e.g.

>>> 10<20
True
>>> 10>20
False
>>> 10<=10
True
>>> 20>=15
True
>>> 5==6
False
>>> 5!=6
True
>>> 10<>2
True
>>>

3. Assignment Operators

e.g

>>> c=10
>>> c
10
>>> c+=5
>>> c
15
>>> c-=5
>>> c
10
>>> c*=2
>>> c
20
>>> c/=2
>>> c
10
>>> c%=3
>>> c
1
>>> c=5
>>> c**=2
>>> c
25
>>> c//=2
>>> c
12
>>>

4. Logical Operators

Example :

a=5>4 and 3>2
print a
b=5>4 or 3<2
print b
c=not(5>4)
print c

Output:

>>>  
True
True
False
>>>



5. Membership Operators

Example :

a=10
b=20
list=[10,20,30,40,50];

if (a in list):
    print "a is in given list"
else:
    print "a is not in given list"
if(b not in list):
    print "b is not given in list"
else:
    print "b is given in list"

Output:

>>>  
a is in given list
b is given in list
>>>

6. Identity Operators

Example :

a=20
b=20
if( a is b):
    print  ?a,b have same identity?
else:
    print ?a, b are different?
b=10
if( a is not b):
    print  ?a,b have different identity?
else:
    print ?a,b have same identity?
Output:

>>>  
a,b have same identity
a,b have different identity
>>>  

Literals

Literals can be defined as a data that is given in a variable or constant.

Python support the following literals:

I. String literals:

String literals can be formed by enclosing a text in the quotes. We can use both single as well as double quotes for a String.

Eg:

"Gaurav" , '12345'

Types of Strings:

There are two types of Strings supported in Python:

a)Single line String- Strings that are terminated within a single line are known as Single line Strings.

Eg:

>>> text1='hello'

b)Multi line String- A piece of text that is spread along multiple lines is known as Multiple line String.

There are two ways to create Multiline Strings:

1) Adding black slash at the end of each line.

Eg:

>>> text1='hello\
user'
>>> text1
'hellouser'
>>>

2)Using triple quotation marks:-

Eg:

>>> str2='''''welcome
to
SSSIT'''
>>> print str2
welcome
to
SSSIT
>>>

II.Numeric literals:

Numeric Literals are immutable. Numeric literals can belong to following four different numerical types.

III. Boolean literals:

A Boolean literal can have any of the two values: True or False.

IV. Special literals.

Python contains one special literal i.e., None.

None is used to specify to that field that is not created. It is also used for end of lists in Python.

Eg:

>>> val1=10
>>> val2=None

>>> val1
10

>>> val2

>>> print val2
None
>>>

V.Literal Collections.

Collections such as tuples, lists and Dictionary are used in Python.

List:

List contain items of different data types. Lists are mutable i.e., modifiable.

The values stored in List are separated by commas(,) and enclosed within a square brackets([]). We can store different type of data in a List.

Value stored in a List can be retrieved using the slice operator([] and [:]).

The plus sign (+) is the list concatenation and asterisk(*) is the repetition operator.

Eg:

>>> list=['gaurav',678,20.4,'saurav']
>>> list1=[456,'ravi']
>>> list
['gaurav', 678, 20.4, 'saurav']

>>> list[1:3]
[678, 20.4]

>>> list+list1
['gaurav', 678, 20.4, 'saurav', 456, 'ravi']

>>> list1*2
[456, 'ravi', 456, 'ravi']
>>>  

Variables

Variable is a name of the memory location where data is stored. Once a variable is stored that means a space is allocated in memory.

Assigning values to Variable:

We need not to declare explicitly variable in Python. When we assign any value to the variable that variable is declared automatically.

The assignment is done using the equal (=) operator.

Eg:

a=10
name='Gaurav'
salary=21583.885
print (a)
print(name)
print(salary)

Output:

>>>
10
Gaurav
21583.885
>>>

Multiple Assignment:

Multiple assignment can be done in Python at a time.

There are two ways to assign values in Python:

1. Assigning single value to multiple variables:

Eg:

x=y=z=50
print x
print y
print z

Output:

>>>
50
50
50
>>>

2.Assigning multiple values to multiple variables:

Eg:

a,b,c=5,10,15

print a
print b
print c

Output:

>>>
5
10
15
>>>

The values will be assigned in the order in which variables appears.

Basic Fundamentals:

This section contains the basic fundamentals of Python like :

i)Tokens and their types.

ii) Comments

a)Tokens:

Tokens can be defined as a punctuator mark, reserved words and each individual word in a statement.

Token is the smallest unit inside the given program.

There are following tokens in Python:

Keywords
Identifiers
Literals
Operators

Tuples:

- Tuple is another form of collection where different type of data can be stored.
- It is similar to list where data is separated by commas. Only the difference is that list uses square bracket and tuple uses parenthesis.
- Tuples are enclosed in parenthesis and cannot be changed.

Eg:

>>> tuple=('rahul',100,60.4,'deepak')

>>> tuple1=('sanjay',10)

>>> tuple
('rahul', 100, 60.4, 'deepak')

>>> tuple[2:]
(60.4, 'deepak')

>>> tuple1[0]
'sanjay'

>>> tuple+tuple1
('rahul', 100, 60.4, 'deepak', 'sanjay', 10)
>>>

Dictionary:

- Dictionary is a collection which works on a key-value pair.
- It works like an associated array where no two keys can be same.
- Dictionaries are enclosed by curly braces ({}) and values can be retrieved by square bracket([]).

Eg:

>>> dictionary={'name':'charlie','id':100,'dept':'it'}

>>> dictionary
{'dept': 'it', 'name': 'charlie', 'id': 100}

>>> dictionary.keys()
['dept', 'name', 'id']

>>> dictionary.values()
['it', 'charlie', 100]
>>>  

Python Example

Python code is simple and easy to run. Here is a simple Python code that will print "Welcome to Python".

A simple python example is given below.

>>> a="Welcome To Python"
>>> print a
Welcome To Python
>>>  

Explanation:

Here we are using IDLE to write the Python code. Detail explanation to run code is given in Execute Python section.

A variable is defined named "a" which holds "Welcome To Python".

"print" statement is used to print the content. Therefore "print a" statement will print the content of the variable. Therefore, the output "Welcome To Python" is produced.

Python 3.4 Example

In python 3.4 version, you need to add parenthesis () in a string code to print it.

>>> a=("Welcome To Python Example")
>>> print a
Welcome To Python Example
>>>

Features

There are a lot of features provided by python programming language.

1) Easy to Use:

Python is easy to very easy to use and high level language. Thus it is programmer-friendly language.

2) Expressive Language:

Python language is more expressive. The sense of expressive is the code is easily understandable.

3) Interpreted Language:

Python is an interpreted language i.e. interpreter executes the code line by line at a time. This makes debugging easy and thus suitable for beginners.

4) Cross-platform language:

Python can run equally on different platforms such as Windows, Linux, Unix , Macintosh etc. Thus, Python is a portable language.

5) Free and Open Source:

Python language is freely available(www.python.org).The source-code is also available. Therefore it is open source.

6) Object-Oriented language:

Python supports object oriented language. Concept of classes and objects comes into existence.

7) Extensible:

It implies that other languages such as C/C++ can be used to compile the code and thus it can be used further in your python code.

8) Large Standard Library:

Python has a large and broad library.

9) GUI Programming:

Graphical user interfaces can be developed using Python.

10) Integrated:

It can be easily integrated with languages like C, C++, JAVA etc.

What is Python

Python is an object-oriented, high level language, interpreted, dynamic and multipurpose programming language.

Python is easy to learn yet powerful and versatile scripting language which makes it attractive for Application Development.

Python's syntax and dynamic typing with its interpreted nature, make it an ideal language for scripting and rapid application development in many areas.

Python supports multiple programming pattern, including object oriented programming, imperative and functional programming or procedural styles.

Python is not intended to work on special area such as web programming. That is why it is known as multipurpose because it can be used with web, enterprise, 3D CAD etc.

We don't need to use data types to declare variable because it is dynamically typed so we can write a=10 to declare an integer value in a variable.

Python makes the development and debugging fast because there is no compilation step included in python development and edit-test-debug cycle is very fast.

Packages

Packages are used in Java in order to prevent naming conflicts, to control access, to make searching/locating and usage of classes, interfaces, enumerations and annotations easier, etc.

A Package can be defined as a grouping of related types (classes, interfaces, enumerations and annotations ) providing access protection and name space management.

Some of the existing packages in Java are::

java.lang - bundles the fundamental classes

java.io - classes for input , output functions are bundled in this package

Programmers can define their own packages to bundle group of classes/interfaces, etc. It is a good practice to group related classes implemented by you so that a programmer can easily determine that the classes, interfaces, enumerations, annotations are related.

Since the package creates a new namespace there won't be any name conflicts with names in other packages. Using packages, it is easier to provide access control and it is also easier to locate the related classes.

Creating a package:

While creating a package, you should choose a name for the package and include a package statement along with that name at the top of every source file that contains the classes, interfaces, enumerations, and annotation types that you want to include in the package.

The package statement should be the first line in the source file. There can be only one package statement in each source file, and it applies to all types in the file.

If a package statement is not used then the class, interfaces, enumerations, and annotation types will be placed in the current default package.

To compile the Java programs with package statements you have to do use -d option as shown below.

javac -d Destination_folder file_name.java

Then a folder with the given package name is created in the specified destination, and the compiled class files will be placed in that folder

Example:

Let us look at an example that creates a package called animals. It is a good practice to use names of packages with lower case letters to avoid any conflicts with the names of classes, interfaces.

Below given package example contains interface named animals:

/* File name : Animal.java */
package animals;
interface Animal {
   public void eat();
   public void travel();
}

Now, let us implement the above interface in the same package animals:

package animals;

/* File name : MammalInt.java */
public class MammalInt implements Animal{

   public void eat(){
      System.out.println("Mammal eats");
   }

   public void travel(){
      System.out.println("Mammal travels");
   }

   public int noOfLegs(){
      return 0;
   }

   public static void main(String args[]){
      MammalInt m = new MammalInt();
      m.eat();
      m.travel();
   }
}

Now compile the java files as shown below:

$ javac -d . Animal.java
$ javac -d . MammalInt.java

Now a package/folder with the name animals will be created in the current directory and these class files will be placed in.

You can execute the class file with in the package and get the result as shown below.

$ java animals.MammalInt
ammal eats
ammal travels

The import Keyword:

If a class wants to use another class in the same package, the package name does not need to be used. Classes in the same package find each other without any special syntax.

Example:

Here, a class named Boss is added to the payroll package that already contains Employee. The Boss can then refer to the Employee class without using the payroll prefix, as demonstrated by the following Boss class.

package payroll;

public class Boss
{
   public void payEmployee(Employee e)
   {
      e.mailCheck();
   }
}
What happens if the Employee class is not in the payroll package? The Boss class must then use one of the following techniques for referring to a class in a different package.

The fully qualified name of the class can be used. For example:

payroll.Employee
The package can be imported using the import keyword and the wild card (*). For example:

import payroll.*;
The class itself can be imported using the import keyword. For example:

import payroll.Employee;
Note: A class file can contain any number of import statements. The import statements must appear after the package statement and before the class declaration.

The Directory Structure of Packages:
Two major results occur when a class is placed in a package:

The name of the package becomes a part of the name of the class, as we just discussed in the previous section.

The name of the package must match the directory structure where the corresponding bytecode resides.

Here is simple way of managing your files in Java:

Put the source code for a class, interface, enumeration, or annotation type in a text file whose name is the simple name of the type and whose extension is .java. For example:

// File Name :  Car.java

package vehicle;

public class Car {
   // Class implementation.  
}

Now, put the source file in a directory whose name reflects the name of the package to which the class belongs:

....\vehicle\Car.java
Now, the qualified class name and pathname would be as below:

Class name -> vehicle.Car

Path name -> vehicle\Car.java (in windows)

In general, a company uses its reversed Internet domain name for its package names. Example: A company's Internet domain name is apple.com, then all its package names would start with com.apple. Each component of the package name corresponds to a subdirectory.

Example: The company had a com.apple.computers package that contained a Dell.java source file, it would be contained in a series of subdirectories like this:

....\com\apple\computers\Dell.java
At the time of compilation, the compiler creates a different output file for each class, interface and enumeration defined in it. The base name of the output file is the name of the type, and its extension is .class

For example:

// File Name: Dell.java

package com.apple.computers;
public class Dell{
     
}
class Ups{
     
}
Now, compile this file as follows using -d option:

$javac -d . Dell.java
This would put compiled files as follows:

.\com\apple\computers\Dell.class
.\com\apple\computers\Ups.class

You can import all the classes or interfaces defined in \com\apple\computers\ as follows:

import com.apple.computers.*;

Like the .java source files, the compiled .class files should be in a series of directories that reflect the package name. However, the path to the .class files does not have to be the same as the path to the .java source files. You can arrange your source and class directories separately, as:

<path-one>\sources\com\apple\computers\Dell.java

<path-two>\classes\com\apple\computers\Dell.class

By doing this, it is possible to give the classes directory to other programmers without revealing your sources. You also need to manage source and class files in this manner so that the compiler and the Java Virtual Machine (JVM) can find all the types your program uses.

The full path to the classes directory, <path-two>\classes, is called the class path, and is set with the CLASSPATH system variable. Both the compiler and the JVM construct the path to your .class files by adding the package name to the class path.

Say <path-two>\classes is the class path, and the package name is com.apple.computers, then the compiler and JVM will look for .class files in <path-two>\classes\com\apple\compters.

A class path may include several paths. Multiple paths should be separated by a semicolon (Windows) or colon (Unix). By default, the compiler and the JVM search the current directory and the JAR file containing the Java platform classes so that these directories are automatically in the class path.

Set CLASSPATH System Variable:
To display the current CLASSPATH variable, use the following commands in Windows and UNIX (Bourne shell):

In Windows -> C:\> set CLASSPATH

In UNIX -> % echo $CLASSPATH

To delete the current contents of the CLASSPATH variable, use :

In Windows -> C:\> set CLASSPATH=

In UNIX -> % unset CLASSPATH; export CLASSPATH

To set the CLASSPATH variable:

In Windows -> set CLASSPATH=C:\users\jack\java\classes

In UNIX -> % CLASSPATH=/home/jack/java/classes; export CLASSPATH