Programmingwithpython
Programmingwithpython
Rasan Samarasinghe
ESOFT Computer Studies (pvt) Ltd.
No 68/1, Main Street, Pallegama, Embilipitiya.
Contents
• Readability
• Support Structured / OOP Styles
• Easy to learn
• Easy to maintain
• A broad standard library
• Interactive Mode
Features
• Portable
• Extendable
• Support Databases
• GUI Programming
• Scalable
• Easy integration with other languages
Application of Python
• Systems Programming
• GUIs
• Internet Scripting
• Component Integration
• Database Programming
• Numeric and Scientific Programming
• More: Gaming, Images, Data Mining, Robots,
Excel..
Python Environment
Install Python
Setting up PATH
Running Python
1. Interactive Interpreter
2. Run script from the Command line
3. Integrated Development Environment
First Python Program
"Hello, World!"
First Python Program
C:\>python_files\test.py
Python Basic Syntax
Python Identifiers
Reserved Words
Lines and Indentation
Multi Line Statements
Quotation in Python
Comments in Python
Using Blank Lines
Multiple Statements
Command Line Arguments
Python Identifiers
if True:
print("Good")
print("Cat")
else:
print("Bad")
print("Cat")
Multi Line Statements
total = item_one + \
item_two + \
item_three
Multi Line Statements
word = 'word'
sentence = "This is a sentence."
paragraph = """This is a paragraph. It is
made up of multiple lines and sentences."""
Comments in Python
# first comment
print ("Hello, Rasan!") # second comment
Using Blank Lines
import sys
print (counter)
print (miles)
print (name)
Multiple Assignment
a=b=c=1
a, b, c = 1, 2, "nuwan"
Standard Data Types
• Numbers
• String
• List
• Tuple
• Dictionary
Python Numbers
var1 = 1
var2 = 10
Python Numbers
del var1
del var_a, var_b
Number Types in Python
Python Strings
word = 'word'
sentence = "This is a sentence."
paragraph = """This is a paragraph. It is
made up of multiple lines and sentences."""
Python Strings
str = 'Hello World!'
dic = {}
dic['one'] = "This is one"
dic[2] = "This is two"
Crating Python Dictionary
1. Arithmetic Operators
2. Comparison Operators
3. Assignment Operators
4. Logical Operators
5. Bitwise Operators
6. Membership Operators
7. Identity Operators
Arithmetic Operators
a = 10 b = 20
Comparison Operators
a = True b = False
Assignment Operators
Logical Operators
Bitwise Operators
a = 60 b = 13
Membership Operators
Identity Operators
Operators Precedence
Python Decision Making
If statements
SYNTAX:
if expression:
statement(s)
if...else statements
SYNTAX:
if expression:
statement(s)
else:
statement(s)
The elif Statement
SYNTAX:
if expression1:
statement(s)
elif expression2:
statement(s)
elif expression3:
statement(s)
else:
statement(s)
Nested if statements
SYNTAX:
if expression1:
statement(s)
if expression2:
statement(s)
elif expression3:
statement(s)
else
statement(s)
elif expression4:
statement(s)
else:
statement(s)
Python Loops
While loop
SYNTAX:
while expression:
statement(s)
The else Statement with While Loops
count = 0
while count < 5:
print (count, " is less than 5")
count = count + 1
else:
print (count, " is not less than 5")
For loop
SYNTAX:
num = 7
for i in range(2,num):
if num%i == 0:
print ('%d is not a prime number' % (num))
break
else:
print (num, 'is a prime number')
Nested for loops
SYNTAX:
SYNTAX:
while expression:
while expression:
statement(s)
statement(s)
Loop Control Statements
Python Numbers
print (r'C:\\nowhere')
Unicode String
print (list1)
del list1[2]
print ("After deleting value at index 2 : ")
print (list1)
Basic List Operations
Indexing, Slicing and Matrixes
tup1 = ()
tup1 = (50,)
Accessing Values in Tuples
print (tup)
del tup
print ("After deleting tup : ")
print (tup)
Basic Tuples Operations
Indexing, Slicing and Matrixes
• A dictionary is mutable.
Creating Python Dictionary
import time;
ticks = time.time()
print ("Number of ticks since 12:00am, January
1, 1970:", ticks)
TimeTuple
Python's time functions handle time as a tuple
of 9 numbers
struct_time structure
time tuple is equivalent to struct_time structure.
This structure has following attributes
Getting current time
import time;
localtime = time.asctime(
time.localtime(time.time()) )
print ("Local current time :", localtime)
The time Module
The time Module
The calendar Module
The calendar Module
Python Functions
SYNTAX:
# Function definition
def printme( str ):
"This prints a passed string into this function"
print (str)
return
1. Pass by reference
2. Pass by value
Pass by reference
# Function definition is here
def changeme( mylist ):
"This changes a passed list into this function"
mylist.append([1,2,3,4])
print ("Values inside the function: ", mylist)
return
• Required arguments
• Keyword arguments
• Default arguments
• Variable-length arguments
Required arguments
# Function definition
def printme( str ):
"This prints a passed string into this function"
print (str)
return
# Function definition
def printinfo( name, age ):
"This prints a passed info into this function"
print ("Name: ", name)
print ("Age ", age)
return
# Function definition
def printinfo( name, age = 35 ):
"This prints a passed info into this function"
print ("Name: ", name)
print ("Age ", age)
return
SYNTAX:
# Function definition
sum = lambda arg1, arg2 : arg1 + arg2;
• Global variables
• Local variables
Scope of Variables
total = 0; # This is global variable
# Function definition
def sum( arg1, arg2 ):
total = arg1 + arg2; # Here total is local variable.
print ("Inside the function local total : ", total)
return total;
hello.py file
SYNTAX:
SYNTAX:
SYNTAX:
Money = 2000
def AddMoney():
# Uncomment the following line to fix the code:
# global Money
Money = Money + 1
print (Money)
AddMoney()
print (Money)
The dir( ) Function
content = dir(math)
print (content)
The globals() and locals() Functions
Create
__init__.py
Phone.Pots()
Phone.Isdn()
Phone.G3()
Python I/O
SYNTAX:
try:
You do your operations here;
......................
except Exception1:
If there is ExceptionI, then execute this block.
except Exception2:
If there is ExceptionII, then execute this block.
......................
else:
If there is no exception then execute this block.
Except clause with no exceptions
SYNTAX:
try:
You do your operations here;
......................
except:
If there is any exception, then execute this block.
......................
else:
If there is no exception then execute this block.
The try-finally clause
SYNTAX:
try:
You do your operations here;
......................
Due to any exception, this may be skipped.
finally:
This would always be executed.
......................
Argument of an Exception
SYNTAX:
try:
You do your operations here;
......................
except ExceptionType, Argument:
You can print value of Argument here...
Raising an exception
SYNTAX:
class Networkerror(RuntimeError):
def __init__(self, arg):
self.args = arg
# raise exception
try:
raise Networkerror("Bad hostname")
except Networkerror,e:
print (e.args)
Python OOP
1. Creating Classes
2. Creating Objects
3. Accessing Attributes
4. Destroying Objects
5. Class Inheritance
6. Overriding Methods
7. Overloading Operators
8. Data Hiding
Creating Classes
class ClassName:
'Optional class documentation string'
defining class members…
data attributes…
functions…
Creating Classes
class Employee:
'Common base class for all employees'
empCount = 0
def displayCount(self):
print ("Total Employee %d" % Employee.empCount)
def displayEmployee(self):
print ("Name : ", self.name, ", Salary: ", self.salary)
Creating Objects
emp1.displayEmployee()
emp2.displayEmployee()
print ("Total Employee %d" % Employee.empCount)
Accessing Attributes
class Point:
def __del__(self):
class_name = self.__class__.__name__
print (class_name, "destroyed")
Destroying Objects (Garbage Collection)
pt1 = Point()
pt2 = pt1
pt3 = pt1
del pt1
del pt2
del pt3
Class Inheritance
SYNTAX:
def parentMethod(self):
print ('Calling parent method')
def getAttr(self):
print ("Parent attribute :", Parent.parentAttr)
def childMethod(self):
Class Inheritance
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)
Data Hiding
class JustCounter:
__secretCount = 0
def count(self):
self.__secretCount += 1
print (self.__secretCount)
counter = JustCounter()
counter.count()
counter.count()
print (counter.__secretCount)
print (counter._JustCounter__secretCount)
The End
http://twitter.com/rasansmn