0% found this document useful (0 votes)
2 views

Module 1 - Introduction to Python Programming

Uploaded by

phani
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

Module 1 - Introduction to Python Programming

Uploaded by

phani
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 47

Introduction to Python Programming

www.cognixia.com
www.cognixia.com
www.cognixia.com
Introduction to Python Programming

a. History of Python
b. Python Basics – variables, identifier, indentation
c. Data Structures in Python (list , string, sets,
tuples, dictionary)
d. Statements in Python (conditional, iterative,
jump)
e. OOPS concepts
f. Exception Handling
g. Regular Expression

www.cognixia.com
www.cognixia.com
A scripting language is a “wrapper” language that integrates OS functions.

The interpreter is a layer of software logic between your code and the computer hardware
on your machine.
"Scripts" are distinct from the core code of the application, which is
usually written in a different language, and are often created or at least
Wiki Says: modified by the end-user. Scripts are often interpreted from source code
or bytecode.
The “program” has an executable form that the computer can use directly to execute the instructions.
The same program in its human-readable source code form, from which executable programs are derived
(e.g., compiled)

Python is scripting language, fast and dynamic. It is called so because of it’s scalable
interpreter, but actually it is much more than that.

www.cognixia.com
www.cognixia.com
Python is an interpreted high-level programming language for general-purpose programming
Created by Guido van Rossum and first released in 1991.

Timeline
 Python was conceived in the late 1980s and its implementation
began in December 1989 by Guido at Centrum Wiskunde &
Informatica (CWI) in Netherlands.

Launch of different versions


Python 2.0 was released on 16 October 2000 and had
2.0 many major new features, including a cycle-detecting
garbage collector and support for Unicode.

Python 3.0 (py3k) was released on 3 December 2008


3.0
after a long testing period.

Python is inherited from ABC programming and has many features including Interactive
programming, object oriented, exceptional handling and many more.

www.cognixia.com
www.cognixia.com
 Changing print so that it is a built-in function, not a statement.
 Moving reduce (but not map or filter) out of the built-in namespace
and into functools
 Adding support for optional function annotations that can be used for
informal type declarations or other purposes.
 A change in integer division functionality. (In Python 2, 5 / 2 is 2. In
Python 3, 5 / 2 is 2.5, and 5 // 2 is 2)
 Unifying the str/unicode types, representing text, and introducing a
separate immutable bytes type; and a mostly corresponding
mutable bytearray type, both of which represent arrays of bytes

www.cognixia.com
www.cognixia.com
Understanding Identifiers
A Python Identifier is a name used to identify a variable, function, class, module or other
project. Following rules need to be kept in mind while declaring Identifiers:

• Identifiers starts with a letter capital A to Z or


small a to z or an underscore (_) followed by zero Identifier naming Convention
or more letters, underscores and digits (0 to 9).
 Class names start with uppercase. All other
• Invalid Identifiers: special characters such as @,
identifiers involves lower case.
$ and %
• Should not start with number  Starting an identifier with 2 leading underscores
indicates a strongly private identifier.
• Should not be named as pre-defined reserved
keywords
 A private identifier starts with a single leading
• Identifiers are unlimited in length. Case is Underscore
significant. .

www.cognixia.com
www.cognixia.com
Variables are reserved memory locations to
store values.

Whenever a variable is created a relevant


space in memory is reserved for the created
variable.

Assigning values to variables

A=10
B=‘Hello World’
Print(A,B)

Output
10 Hello World

www.cognixia.com
www.cognixia.com
www.cognixia.com
www.cognixia.com
Correct Example
 Python blocks of code are defined by line indentation. N=10
If N:
 The number of spaces in the indentation in block should print “True”
be same with others statements within the Block else:
print “False”
 Indenting starts a block and unindenting ends it.

 No explicit braces, brackets or keywords needed. In-correct Example


N=10
 Whitespace is significant. If N:
print “Answer”
 Code blocks are started by a ‘:’ print “True”
else:
print “Answer”
print “False”

www.cognixia.com
www.cognixia.com
 Statements in Python end with a new line. However, Python allows the use
of the line continuation character (\) to denote that the line should
continue.

 Comments in Python is created with # sign for single line comment

 For multi line comment we will have to put three double quotes and insert
comment in between. """ comment """

 Statements contained within the [], {} or () brackets do not need to use the
line continuation character.

www.cognixia.com
www.cognixia.com
Python is dynamically and strongly typed which means that the data types in
python are discovered at execution time and cannot be interchanged without
conversion.

Python data types at a glance

www.cognixia.com
www.cognixia.com
 Int (Signed Integers)
Python supports 3 numerical value
 Float (Real Numbers)
types:
 Complex Numbers
Numbers can be represented in following ways:
 Binary
 Octal
 Hexadecimal

A=10 #(Integer)
B=9.75 #(Float)
C=10 + 6j #(Complex)

print(A,B)

Output
10 9.75 (10+6j)

www.cognixia.com
www.cognixia.com
A continuous set of characters within quotation (either single or double) is
known as String. Python does not support a character type instead a single
character is read as string of length one.

UserName=‘Sam Wilson’
Pwd=‘Jones123’

print(A)

print(B)

Output
Sam Wilson
Jones123

www.cognixia.com
www.cognixia.com
Tuples consists of a number of values which are separated by comma. The
values are enclosed within parenthesis.
A tuple can have objects of different data types.

A=(4,2,3.14,’jones’)

print(A)

Output
(4,2,3.14,’jones’)

www.cognixia.com
www.cognixia.com
Lists is an ordered set of elements enclosed within square brackets. The main
difference between Lists and Tuples are:

 Lists are Mutable whereas Tuples are Immutable.


 Tuples work faster than Lists.
 Lists are enclosed in brackets[] and Tuples are enclosed within
parenthesis().

A=[4,2,3.14,’jones’]

print(A)

Output
(4,2,3.14,’jones’)

www.cognixia.com
www.cognixia.com
Dictionaries contain key value pairs. Each key is separated from its value by
colon (:). Different Keys are separated by comma and all the values in a
Dictionary are enclosed within curly braces.

A={‘Name’:’John’, ‘Marks’: 79}

print(A)

Output
{‘Name’:’John’, ‘Marks’: 79}

www.cognixia.com
www.cognixia.com
A set is an unordered collection of items with every item being unique.
A set is created by placing all the items or elements inside { } and each element
is separated by comma.

A={2,3,4,4}

print(A)

Output
{2,3,4}

www.cognixia.com
www.cognixia.com
Conditional Statements are used to execute a statement or a group of
statements, when certain condition is true.

I and E small

www.cognixia.com
www.cognixia.com
The syntax and example for conditional statements are mentioned below:

Syntax: Sample code:

A=5
B=9
if condition1:
statements
if (A<B):
elif condition2:
print (‘A is less than B’)
statements
elif (A>B):
else:
print (‘A is greater than B’)
statements
else:
print (‘A is equal to B’)

www.cognixia.com
www.cognixia.com
A loop statement enables the user to execute a statement or a group of
statements, multiple times.

www.cognixia.com
www.cognixia.com
While loop is a conditional loop which will keep on iterating until certain
conditions are met.
However there is uncertainty regarding how many times the loop will iterate.

Syntax: Sample code:


i=0
while (i<5):
print (i)
i=i+1
print (“End of loop”)
while expression:
statements
Output
0
1
2
3
4
End of loop

www.cognixia.com
www.cognixia.com
For loop repeats a group of statements a specified number of times. The syntax
of for loop involves following:
 Boolean Condition
 The initial value of the counting variable
 Increment of counting variable
Syntax: Sample code:

For <variable> in <range>:


statement1
statement2 name=[‘AK’,’RT’,’SK’]
. For count in range(len(name)):
. print(name[count])
Statement

www.cognixia.com
www.cognixia.com
Nested loop indicates a loop inside a loop, It could be a while loop inside a
while loop, for loop inside a while loop, for loop inside a for loop and similar
other cases.
Sample code:

index=1
for i in range(9):
print(name(i)*i)
for j in range(0,i):
index=index+1

Output
1
22
333
4444
And so on till 8 is reached

www.cognixia.com
www.cognixia.com
Loop control statements have the ability to change the sequence of execution
of statements. When execution leaves a scope, all automatic objects that were
created in that scope are destroyed.

Control Statement Description

Terminates the loop statement and transfers execution to


Break statement
statement immediately following the loop

Causes the loop to skip the remainder of its body and resets the
Continue statement
condition prior to iterating

Pass statement is used when a statement is required syntactically


Pass statement
but no command or code is needed to be executed.

www.cognixia.com
www.cognixia.com
An OOPS program is divided into parts called objects and follows a bottom up
approach.
In OOP, objects can move and communicate with each other through member
functions. Python follows OOP concepts.

Benefits of OOP concepts in Python:


 Data becomes active
 Code is reusable
 Ability to simulate real world events much more effectively
 Ability to code faster and accurate written applications

Python is an interpreted language which means it executes code line-by-line.


So if the program has some error, that error will be shown when the line of
code will execute.

www.cognixia.com
www.cognixia.com
Class and Objects
Class is a blueprint used to create objects having same property or attribute as
its class.
An object is an instance of a class which contains variables and methods.

Relation between Classes and objects Create a class

 A class contains the code for all the object’s methods. # Create a class
class number():
 A class describes the abstract characteristics of a real-life thing. pass

 An instance is an object of a Class created at run-time. #Defining an instance of class


t=number()
 There can be multiple instances of a class. print(t)

www.cognixia.com
www.cognixia.com
Variables and Attributes in a class
Variables which are declared within a class can be used within that class only
and are referred to as ‘Local’ variables. While the ones which can be used
within any class are called ‘Global’ variables.

Class attributes are shared by all the instances of the class. There are built-in as
well as user defined attributes in python.
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

www.cognixia.com
www.cognixia.com
Private Attributes Can only be accessed inside of the class definition.

Public Attributes Can and should be freely used.

Protected Are accessible only from within the class and its subclass and main
Attributes for debugging purpose.

More about Attributes

Attributes may be read-only or writable. In the latter case, assignment to attributes is


possible. Module attributes are writable: you can write modname.the_answer = 42.
Writable attributes may also be deleted with the del statement.
For example, del modname.the_answer will remove the attribute the_answer from the
object named by modname.

www.cognixia.com
www.cognixia.com
When the attributes of an object can only be accessed inside the class, it is
called a Private Class.
Python uses two underscores to hide a method or hide a variable.

Sample code

Class sample:
def apublicmethod(self):
print(‘public method’)
def __aprivatemethod(self):
print(‘private method’)
Obj=sample()
Obj.apublicmethod()
Obj._sample__aprivatemethod()

www.cognixia.com
www.cognixia.com
Sample code

Declaring class variable


Class sample:
domain = (“Analytics”)
def Setcourse (self,name):
self.name=name
Instance of class
Ob1=sample()
Ob2=sample()
Class variable is shared by both instances Ob1 and Ob2 Output
Ob1.Setcourse (“Module1”) Analytics
Ob2.Setcourse (“Module2”) AI
print (Ob1.domain) Analytics
Ob1.domain=‘AI’
print (Ob1.domain)
print (Ob2.domain)

www.cognixia.com
www.cognixia.com
Sample code
Class sample:
def __init__ (self):
print(‘constructor’)
def __del__ (self):
print(‘destructor’)
If __name__ == “__main__”:
obj = TestClass ()
del obj
Output
Constructor
Destructor
# obj is created and manually deleted after displaying both the messages.

www.cognixia.com
www.cognixia.com
www.cognixia.com
www.cognixia.com
 Abstraction means simplifying complex
reality by modeling classes relevant to the
problem.
Abstraction  Class abstraction is defined by separating
class implementation from the use of the
class.
 Encapsulation is a mechanism for restricting
access to some of an object’s components.
Encapsulation This means that the internal components of
an object can not be seen from outside of
object’s definition.
 Refers to deriving a class from the base class
Inheritance with little or no modification in it.

www.cognixia.com
www.cognixia.com
www.cognixia.com
www.cognixia.com
Multiple Inheritance Multilevel Inheritance

www.cognixia.com
www.cognixia.com
Overriding is a very important part of OOP since it makes inheritance utilize its full power. By using
method overriding a class may "copy" another class, avoiding duplicated code, and at the same
time enhance or customize part of it. Method overriding is thus a part of the inheritance
mechanism.

class Parent(object):
def __init__(self):
self.value = 4
def get_value(self):
return self.value
class Child(Parent):
def get_value(self):
return self.value + 1
c = Child()
c.get_value()
5

www.cognixia.com
www.cognixia.com
Sometimes an object comes in many types or forms. If we have a button, there are many different
draw outputs (round button, check button, square button, button with image) but they do share
the same logic: onClick(). We access them using the same method . This idea is
called Polymorphism.

class Bear(object):
def sound(self):
print "Groarrr"
class Dog(object):
def sound(self):
print "Woof woof!" Output

def makeSound(animalType): Groarrr

animalType.sound() Woof woof!

bearObj = Bear()
dogObj = Dog()
makeSound(bearObj)
makeSound(dogObj)
www.cognixia.com
www.cognixia.com
Getters and setters are used in many object oriented programming languages to ensure the
principle of data encapsulation. They are known as mutator methods as well.

class P: >>> from mutators import P

def __init__(self,x): >>> p1 = P(42)

self.__x = x >>> p2 = P(4711)

def get_x(self): >>> p1.get_x()

return self.__x 42

def set_x(self, x): >>> p1.set_x(47)

self.__x = x >>> p1.set_x(p1.get_x()+p2.get_x())


>>> p1.get_x()
4758

www.cognixia.com
www.cognixia.com
Python has many built-in exceptions which forces a program to output an error
when something in it goes wrong.

When these exceptions occur, it causes the current process to stop and passes it to
the calling process until it is handled. If not handled, the program will crash.
For example, if function A calls function B which in turn calls function C and an
exception occurs in function C. If it is not handled in C, the exception passes
to B and then to A.

If never handled, an error message is spit out and program comes to a sudden,
unexpected halt.

www.cognixia.com
www.cognixia.com
In Python, exceptions can be handled using a try statement.
A critical operation which can raise exception is placed inside the try clause and the code that
handles exception is written in except clause. (add one more slide on assert)

# import module sys to get the type of exception


import sys
randomList = ['a', 0, 2]
for entry in randomList: Output
try: The entry is a
print("The entry is", entry)
Oops! <class 'ValueError'> occured.
Next entry.
r = 1/int(entry)
The entry is 0
break
Oops! <class 'ZeroDivisionError' > occured.
except: Next entry.
print("Oops!",sys.exc_info()[0],"occured.") The entry is 2
print("Next entry.") The reciprocal of 2 is 0.5
print()
print("The reciprocal of",entry,"is",r)

www.cognixia.com
www.cognixia.com
Explaining code on previous slide

In this program, we loop until the user enters an integer that has a valid reciprocal. The portion
that can cause exception is placed inside try block.

If no exception occurs, except block is skipped and normal flow continues. But if any exception
occurs, it is caught by the except block.

Here, we print the name of the exception using ex_info() function inside sys module and ask the
user to try again. We can see that the values 'a' and '1.3' causes ValueError and '0' causes
ZeroDivisionError.

www.cognixia.com
www.cognixia.com
In Python programming, exceptions are raised when corresponding errors occur at run time, but
we can forcefully raise it using the keyword raise.

>>> raise KeyboardInterrupt


Traceback (most recent call last):
...
KeyboardInterrupt
>>> raise MemoryError("This is an argument")
Traceback (most recent call last):
...
MemoryError: This is an argument
>>> try:
... a = int(input("Enter a positive integer: "))
... if a <= 0:
... raise ValueError("That is not a positive number!")
... except ValueError as ve:
... print(ve)
...
Enter a positive integer: -2
That is not a positive number!

www.cognixia.com
www.cognixia.com
The try statement in Python can have an optional finally clause. This clause is executed no matter
what, and is generally used to release external resources.

try:
f = open("test.txt",encoding = 'utf-8')
# perform file operations

finally:
f.close()

www.cognixia.com
www.cognixia.com
A Regular Expression is a special text string for describing a search pattern. 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.

re.match(pattern, string, flags=0) # re.match function returns a match object on success, None on failure.

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.

www.cognixia.com
www.cognixia.com
Sample Code

#!/usr/bin/python
import re
line = "Cats are smarter than dogs"
matchObj = re.match( r'(.*) are (.*?) .*', line, re.M|re.I)
if matchObj: Output
print "matchObj.group() : ", matchObj.group() matchObj.group() : Cats are smarter than dogs
print "matchObj.group(1) : ", matchObj.group(1) matchObj.group(1) : Cats
print "matchObj.group(2) : ", matchObj.group(2) matchObj.group(2) : smarter
else:
print "No match!!"

www.cognixia.com
www.cognixia.com
The search function:

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

Sample Code

#!/usr/bin/python
import re
line = "Cats are smarter than dogs";
searchObj = re.search( r'(.*) are (.*?) .*', line, re.M|re.I) Output
if searchObj: searchObj.group() : Cats are smarter than dogs
print "searchObj.group() : ", searchObj.group() searchObj.group(1) : Cats
print "searchObj.group(1) : ", searchObj.group(1) searchObj.group(2) : smarter
print "searchObj.group(2) : ", searchObj.group(2)
else:
print "Nothing found!!"

www.cognixia.com
www.cognixia.com
THANK YOU

www.cognixia.com www.cognixia.com
www.cognixia.com

You might also like