SlideShare uma empresa Scribd logo
1 de 200
Programming with Python
Rasan Samarasinghe
ESOFT Computer Studies (pvt) Ltd.
No 68/1, Main Street, Pallegama, Embilipitiya.
Contents
1. Python Overview
2. Python Environment
3. First Python Program
4. Python Basic Syntax
5. Python Variables
6. Standard Data Types
7. Python Operators
8. Python Decision Making
9. Python Loops
10. Python Numbers
11. Python Strings
12. Python Lists
13. Python Tuples
14. Python Dictionary
15. Python Date & Time
16. Python Functions
17. Python Modules
18. Python I/O
19. Python Exceptions
20. Python OOP
Python Overview
• A high-level, interpreted, interactive and
object-oriented scripting language.
• Designed to be highly readable which uses
English keywords.
• Fewer syntactical constructions than other
languages.
Features
• 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
Python is available on a wide variety of
platforms (Windows / Linux / Mac OS)
Python Official Website: http://www.python.org
Install Python
Setting up PATH
Running Python
1. Interactive Interpreter
2. Run script from the Command line
3. Integrated Development Environment
First Python Program
In interactive mode programming
Type and enter in Python prompt:
print ("Hello, World!")
Or just type and enter
"Hello, World!"
First Python Program
In script mode programming
Make a Python script file test.py and include code:
print ("Hello, World!")
In command shell run test.py file
C:>python_filestest.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
• Identifiers are case sensitive.
• Class names start with an uppercase letter
• Other identifiers start with a lowercase letter.
• Starting with a single leading underscore
indicates private.
• Starting with two leading underscores
indicates strongly private.
• Ends with two underscores means a language
defined special name.
Reserved Words
Lines and Indentation
Blocks of code are denoted by line indentation
if True:
print("Good")
print("Cat")
else:
print("Bad")
print("Cat")
Multi Line Statements
Use of the line continuation character 
total = item_one + 
item_two + 
item_three
Multi Line Statements
Statements contained within the [], {} or ()
brackets do not need to use the line
continuation character.
days = ['Monday', 'Tuesday', 'Wednesday',
'Thursday', 'Friday']
Quotation in Python
Python uses quotes to denote string literals
word = 'word'
sentence = "This is a sentence."
paragraph = """This is a paragraph. It is
made up of multiple lines and sentences."""
Comments in Python
A hash sign # that is not inside a string literal
begins a comment.
# first comment
print ("Hello, Rasan!") # second comment
Using Blank Lines
• A line containing only whitespace / or
comment is known as a blank line and Python
totally ignores it.
• In an interactive interpreter session an empty
physical line used to terminate a multiline
statement.
Multiple Statements
The semicolon ; allows multiple statements on
the single line.
print ("hello"); print ("Rasan!");
Command Line Arguments
test.py script to access command line arguments
import sys
print ('Number of arguments:', len(sys.argv))
print ('Argument List:', str(sys.argv))
Run script in with arguments passed into it.
C:>python_filestest.py rasan indunil samarasinghe
Python Variables
• Variables do not have to be explicitly declared
to reserve memory space.
• The declaration happens automatically when
you assign a value to a variable.
Assigning Values to Variables
counter = 100 # An integer assignment
miles = 1000.0 # A floating point
name = "Nuwan" # A string
print (counter)
print (miles)
print (name)
Multiple Assignment
Python allows you to assign a single value to
several variables simultaneously.
a = b = c = 1
a, b, c = 1, 2, "nuwan"
Standard Data Types
• Numbers
• String
• List
• Tuple
• Dictionary
Python Numbers
Number objects are created when you assign a
value to them.
var1 = 1
var2 = 10
Python Numbers
You can delete a single object or multiple
objects by using the del statement.
del var1
del var_a, var_b
Number Types in Python
Python Strings
String created with either pairs of single or
double quotes.
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!'
# Prints complete string
print (str)
# Prints first character of the string
print (str[0])
# Prints characters starting from 3rd to 5th
print (str[2:5])
Python Strings
str = 'Hello World!'
# Prints string starting from 3rd character
print (str[2:])
# Prints string two times
print (str * 2)
# Prints concatenated string
print (str + "TEST")
Python Lists
• A list contains items separated by commas
and enclosed within square brackets [].
• Lists are similar to arrays in C.
• Items belonging to a list can be of different
data type.
Creating Python Lists
mylist = [ 'abcd', 786 , 2.23, 'rasan', 70.2 ]
tinylist = [123, 'rasan']
Printing Python Lists
# Prints complete list
print (mylist)
# Prints first element
print (mylist[0])
# Prints elements from 2nd till 3rd
print (mylist[1:3])
Printing Python Lists
# Prints elements starting from 3rd
print (mylist[2:])
# Prints list two times
print (tinylist * 2)
# Prints concatenated lists
print (mylist + tinylist)
Python Tuples
• Consists of a number of values separated by
commas enclosed within brackets ( ).
• Tuples cannot be updated.
Crating Python Tuples
mytuple = ( 'abcd', 786 , 2.23, 'rasan', 70.2 )
tinytuple = (123, 'rasan')
Printing Python Tuples
# Prints complete list
print (mytuple)
# Prints first element of the list
print (mytuple[0])
# Prints elements starting from 2nd till 3rd
print (mytuple[1:3])
Printing Python Tuples
# Prints elements starting from 3rd element
print (mytuple[2:])
# Prints list two times
print (tinytuple * 2)
# Prints concatenated lists
print (mytuple + tinytuple)
Python Dictionary
• Python's dictionaries are kind of hash table
type.
• They work like associative arrays or hashes
found in Perl and consist of key value pairs.
Creating Python Dictionary
dic = {}
dic['one'] = "This is one"
dic[2] = "This is two"
Crating Python Dictionary
tinydic = {'name': 'neil','code':6734, 'dept': 'sales'}
Print Python Dictionary Values
# Prints value for 'one' key
print (dic['one'])
# Prints complete dictionary
print (tinydic)
# Prints all the keys
print (tinydic.keys())
# Prints all the values
print (tinydic.values())
Data Type Conversion
Function Description
int(x [,base]) Converts x to an integer. base specifies the base
if x is a string.
long(x [,base] ) Converts x to a long integer. base specifies the
base if x is a string.
float(x) Converts x to a floating-point number.
complex(real [,imag]) Creates a complex number.
str(x) Converts object x to a string representation.
repr(x) Converts object x to an expression string.
eval(str) Evaluates a string and returns an object.
tuple(s) Converts s to a tuple.
Data Type Conversion
Function Description
list(s) Converts s to a list.
set(s) Converts s to a set.
dict(d) Creates a dictionary. d must be a sequence of
(key,value) tuples
frozenset(s) Converts s to a frozen set.
chr(x) Converts an integer to a character.
unichr(x) Converts an integer to a Unicode character.
ord(x) Converts a single character to its integer value.
hex(x) Converts an integer to a hexadecimal string.
oct(x) Converts an integer to an octal string.
Python Operators
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)
Theelif 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)
Theelse 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:
for var in sequence:
statements(s)
Theelse Statement with For Loops
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:
for iterating_var in sequence:
for iterating_var in sequence:
statements(s)
statements(s)
Nested while loops
SYNTAX:
while expression:
while expression:
statement(s)
statement(s)
Loop Control Statements
Python Numbers
• Number data types store numeric values.
• They are immutable data types.
• Changing the value of a number data type
results in a newly allocated object.
Number Examples
Number Type Conversion
• int(x) - convert x to a plain integer.
• long(x) - convert x to a long integer.
• float(x) - convert x to a floating-point number.
Number Type Conversion
• complex(x) - convert x to a complex number
with real part x and imaginary part zero.
• complex(x, y) - convert x and y to a complex
number with real part x and imaginary part y.
Mathematical Functions (math header)
Trigonometric Functions (math module)
Random Number Functions (random module)
Python Strings
• Strings Created by enclosing characters in
quotes.
• Treats single quotes the same as double
quotes.
var1 = 'Hello World!'
var2 = "Python Programming"
Accessing Values in Strings
var1 = 'Hello World!'
var2 = "Python Programming"
print ("var1[0]: ", var1[0])
print ("var2[1:5]: ", var2[1:5])
Updating Strings
var1 = ( 'Hello World!' )
print ("Updated String :- ", var1[:6] + 'Python')
Escape Characters
String Special Operators
String Formatting Operator
String formatting operator % is unique to strings
print ("My name is %s and weight is %d kg!" %
('Khan', 25))
String Formatting Operator
String Formatting Operator
Triple Quotes
Python's triple quotes allowing strings to span
multiple lines.
paragraph = """This is a paragraph. It is
made up of multiple lines and sentences."""
Raw String
Raw strings don't treat the backslash as a special
character at all.
print (r'C:nowhere')
Unicode String
Normal strings in Python are stored internally as
8-bit ASCII
Unicode strings are stored as 16-bit Unicode.
print (u'Hello, world!')
String Methods
String Methods
String Methods
String Methods
Python Lists
• Lists be written as a list of comma separated
values between square brackets.
• Items in a list need not all have the same type.
Crating Python Lists
list1 = ['physics', 'chemistry', 1997, 2000]
list2 = [1, 2, 3, 4, 5 ]
list3 = ["a", "b", "c", "d"]
Accessing Values in Lists
list1 = ['physics', 'chemistry', 1997, 2000]
list2 = [1, 2, 3, 4, 5 ]
list3 = ["a", "b", "c", "d"]
print ("list1[0]: ", list1[0])
print ("list2[1:5]: ", list2[1:5])
Updating Lists
list = ['physics', 'chemistry', 1997, 2000]
print ("Value available at index 2 : ")
print (list[2])
list[2] = 2001
print ("New value available at index 2 : ")
print (list[2])
Delete List Elements
list1 = ['physics', 'chemistry', 1997, 2000]
print (list1)
del list1[2]
print ("After deleting value at index 2 : ")
print (list1)
Basic List Operations
Indexing, Slicing and Matrixes
L = ['spam', 'Spam', 'SPAM!']
Built-in List Functions & Methods
Python Tuples
• A tuple is a sequence of immutable Python
objects.
• Tuples are read only.
• Tuples use parentheses ()
Crating Python Tuples
tup1 = ('physics', 'chemistry', 1997, 2000)
tup2 = (1, 2, 3, 4, 5 )
tup3 = "a", "b", "c", "d"
Creating Python Tuples
Creating an empty tuple:
tup1 = ()
Tuple with one value:
tup1 = (50,)
Accessing Values in Tuples
tup1 = ('physics', 'chemistry', 1997, 2000)
tup2 = (1, 2, 3, 4, 5, 6, 7 )
print ("tup1[0]: ", tup1[0])
print ("tup2[1:5]: ", tup2[1:5])
Updating Tuples
tup1 = (12, 34.56)
tup2 = ('abc', 'xyz')
# Following action is not valid for tuples
# tup1[0] = 100
# So let's create a new tuple as follows
tup3 = tup1 + tup2
print (tup3)
Delete Tuple
tup = ('physics', 'chemistry', 1997, 2000)
print (tup)
del tup
print ("After deleting tup : ")
print (tup)
Basic Tuples Operations
Indexing, Slicing and Matrixes
L = ('spam', 'Spam', 'SPAM!')
Built-in Tuple Functions
Python Dictionary
• A dictionary can store any number of Python
objects.
• Dictionaries consist of pairs of keys and their
corresponding values.
• A dictionary is mutable.
Creating Python Dictionary
dict1 = { 'abc': 456 }
dict2 = { 'abc': 123, 98.6: 37 }
Accessing Values in Dictionary
dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'}
print ("dict['Name']: ", dict['Name'])
print ("dict['Age']: ", dict['Age'])
Updating Dictionary
dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'}
# update existing entry
dict['Age'] = 8
# Add new entry
dict['School'] = "DPS School"
Delete Dictionary Elements
dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'};
# remove entry with key 'Name'
del dict['Name'];
# remove all entries in dict
dict.clear();
# delete entire dictionary
del dict ;
Built-in Dictionary Functions and Methods
Built-in Dictionary Functions and Methods
Python Date & Time
• A python program can handle date & time in
several ways.
• Python's time and calendar modules help
track dates and times.
What is Tick?
The function time.time() returns the current
system time in ticks since 12:00am, January 1,
1970 (epoch)
What is Tick?
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)
Thetime Module
Thetime Module
Thecalendar Module
Thecalendar Module
Python Functions
A function is a block of organized, reusable code
that is used to perform a single, related action.
Defining a Function
SYNTAX:
def functionname( parameters ):
"function_docstring"
function_suite
return [expression]
Calling a Function
# Function definition
def printme( str ):
"This prints a passed string into this function"
print (str)
return
# Call to printme function
printme("I'm first call to user defined function!")
printme("Again second call to the same function")
Calling a Function
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
# Now you can call changeme function
mylist = [10,20,30]
changeme( mylist )
print ("Values outside the function: ", mylist)
Pass by value
# Function definition
def changeme( mylist ):
"This changes a passed list into this function"
mylist = [1,2,3,4]; # assign new reference in mylist
print ("Values inside the function: ", mylist)
return
# Call to changeme function
mylist = [10,20,30]
changeme( mylist )
print ("Values outside the function: ", mylist)
Function Arguments
• 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
# Call printme function
printme(); # will generate an error
Keyword arguments
# Function definition
def printinfo( name, age ):
"This prints a passed info into this function"
print ("Name: ", name)
print ("Age ", age)
return
# Call printinfo function
printinfo( age=50, name="miki" )
Default arguments
# Function definition
def printinfo( name, age = 35 ):
"This prints a passed info into this function"
print ("Name: ", name)
print ("Age ", age)
return
# Call printinfo function
printinfo( age=50, name="miki" )
printinfo( name="miki" )
Variable-length arguments
# Function definition
def printinfo( arg1, *vartuple ):
"This prints a variable passed arguments"
print ("Output is: ")
print (arg1)
for var in vartuple:
print (var)
return;
# Call printinfo function
printinfo( 10 );
printinfo( 70, 60, 50 );
Anonymous Functions
• lambda keyword used to create small
anonymous functions.
• Lambda forms can take any number of
arguments but return just one value as an
expression.
Anonymous Functions
SYNTAX:
lambda [arg1 [,arg2,.....argn]]:expression
Anonymous Functions
# Function definition
sum = lambda arg1, arg2 : arg1 + arg2;
# Call sum as a function
print ("Value of total : ", sum( 10, 20 ))
print ("Value of total : ", sum( 20, 20 ))
The return Statement
• The statement return exits a function.
• Optionally passing back an expression to the
caller.
The return Statement
# Function definition
def sum( arg1, arg2 ):
# Add both the parameters and return them."
total = arg1 + arg2
print ("Inside the function : ", total)
return total;
# Call sum function
total = sum( 10, 20 );
print ("Outside the function : ", total)
Scope of Variables
• 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;
# Call sum function
sum( 10, 20 );
print ("Outside the function global total : ", total)
Python Modules
• A module allows you to logically organize your
Python code.
• Grouping related code into a module makes
the code easier to understand and use.
Creating Python Modules
Code for a module named hello normally resides
in a file named hello.py
hello.py file
def print_func( par ):
print ("Hello : ", par)
return
The import Statement
Using a Python file as a module by executing an
import statement.
SYNTAX:
import module1[, module2[,... moduleN]
The import Statement
# Import module hello
import hello
# Call defined function of module as follows
hello.print_func("Rasan")
Thefrom...import Statement
Import specific attributes from a module into
the current namespace.
SYNTAX:
from modname import func1[, func2[, ... funcN]]
The from...import * Statement
Import all names from a module into the current
namespace
SYNTAX:
from modname import *
Locating Modules Sequence
1. The current directory.
2. If the module isn't found, Python then
searches each directory in the shell variable
PYTHONPATH.
3. If all else fails, Python checks the default
path. (UNIX: /usr/local/lib/python/)
Namespaces and Scoping
• Each function and class method has its own
local namespace.
• If a local and a global variable have the same
name, the local variable shadows the global
variable.
• Therefore global statement is used to assign a
value to a global variable within a function.
Namespaces and Scoping
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
The dir() function returns a sorted list of strings
containing the names defined by a module.
# Import built-in module math
import math
content = dir(math)
print (content)
Theglobals() and locals() Functions
• A call to locals() within a function return all
the names that can be accessed locally from
that function.
• A call to globals() within a function return all
the names that can be accessed globally from
that function.
The reload() Function
• To re-execute the top-level code in a module,
you can use the reload(module_name)
function.
• The reload() function imports a previously
imported module again.
Packages in Python
• A package is a hierarchical file directory
structure.
• It defines a single Python application
environment that consists of modules and sub
packages and so on.
Packages in Python Example
Create
1. File Pots.py available in Phone directory
having function Pots().
2. Phone/Isdn.py file having function Isdn()
3. Phone/G3.py file having function G3()
Packages in Python Example
Now, create one more file __init__.py in Phone
directory
__init__.py
from Pots import Pots
from Isdn import Isdn
from G3 import G3
Packages in Python Example
# Now import your Phone Package.
import Phone
Phone.Pots()
Phone.Isdn()
Phone.G3()
Python I/O
• Printing to the Screen
• Reading Keyboard Input
Printing to the Screen
print ("Hi there!", "How are you?")
Reading Keyboard Input
• raw_input() (Works only with python 2.x)
• input()
The raw_input Function
The raw_input() function reads one line from
standard input and returns it as a string.
str = raw_input("Enter your input: ")
print ("Received input is : ", str)
(Works only with python 2.x)
The input Function
input() function assumes the input is a valid
Python expression and returns the evaluated
result.
str = input("Enter your input: ");
print ("Received input is : ", str)
(In Python 3.x, input() replaces raw_input())
Opening and Closing Files
• The open() Function
• The close() Function
The open Function
SYNTAX:
file object = open(file_name [, access_mode][,
buffering])
File open modes
The file object attributes
File Object Methods
File Object Methods
OS Object Methods
OS Object Methods
OS Object Methods
OS Object Methods
OS Object Methods
Python Exceptions
• An exception is an event, which occurs during
the execution of a program.
• When a Python script encounters a situation
that it can't cope with, it raises an exception.
Standard Exceptions in Python
Standard Exceptions in Python
Handling an exception
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:
raise [Exception [, args [, traceback]]]
User Defined Exceptions
# create exception by deriving standard exception
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 __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)
Creating Objects
# Create first object of Employee class
emp1 = Employee("Zara", 2000)
# Create second object of Employee class
emp2 = Employee("Manni", 5000)
Accessing Attributes
emp1.displayEmployee()
emp2.displayEmployee()
print ("Total Employee %d" % Employee.empCount)
Accessing Attributes
• getattr(obj, name[, default]) : access the
attribute of object.
• hasattr(obj,name) : check if an attribute exists
or not.
• setattr(obj,name,value) : set an attribute. If
attribute does not exist, then it would be
created.
• delattr(obj, name) : delete an attribute.
Built-In Class Attributes
• __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.
Destroying Objects (Garbage Collection)
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")
Destroying Objects (Garbage Collection)
pt1 = Point()
pt2 = pt1
pt3 = pt1
# prints the ids of the objects
print (id(pt1), id(pt2), id(pt3))
del pt1
del pt2
del pt3
Class Inheritance
SYNTAX:
class SubClassName (ParentClass1[, ParentClass2, ...]):
'Optional class documentation string'
defining class members…
data attributes…
functions…
Class Inheritance
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):
Class Inheritance
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
Class Inheritance
issubclass(sub, sup) : Returns true if the given
subclass sub is a subclass of the superclass sup.
isinstance(obj, Class) : Returns true if obj is an
instance of class Class or is an instance
of a subclass of Class
Overriding Methods
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
Base Overloading Methods
Overloading Operators
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)
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

Mais conteúdo relacionado

Mais procurados

Mais procurados (20)

Introduction to-python
Introduction to-pythonIntroduction to-python
Introduction to-python
 
Intro to Python Programming Language
Intro to Python Programming LanguageIntro to Python Programming Language
Intro to Python Programming Language
 
Introduction to Python
Introduction to Python Introduction to Python
Introduction to Python
 
Overview of python 2019
Overview of python 2019Overview of python 2019
Overview of python 2019
 
Python final ppt
Python final pptPython final ppt
Python final ppt
 
Introduction To Python
Introduction To PythonIntroduction To Python
Introduction To Python
 
Python basic
Python basicPython basic
Python basic
 
Introduction to python
Introduction to pythonIntroduction to python
Introduction to python
 
Python programming | Fundamentals of Python programming
Python programming | Fundamentals of Python programming Python programming | Fundamentals of Python programming
Python programming | Fundamentals of Python programming
 
Introduction to Basics of Python
Introduction to Basics of PythonIntroduction to Basics of Python
Introduction to Basics of Python
 
Python Projects For Beginners | Python Projects Examples | Python Tutorial | ...
Python Projects For Beginners | Python Projects Examples | Python Tutorial | ...Python Projects For Beginners | Python Projects Examples | Python Tutorial | ...
Python Projects For Beginners | Python Projects Examples | Python Tutorial | ...
 
Introduction python
Introduction pythonIntroduction python
Introduction python
 
Python presentation by Monu Sharma
Python presentation by Monu SharmaPython presentation by Monu Sharma
Python presentation by Monu Sharma
 
Python Programming Language | Python Classes | Python Tutorial | Python Train...
Python Programming Language | Python Classes | Python Tutorial | Python Train...Python Programming Language | Python Classes | Python Tutorial | Python Train...
Python Programming Language | Python Classes | Python Tutorial | Python Train...
 
Python by Rj
Python by RjPython by Rj
Python by Rj
 
Presentation on python
Presentation on pythonPresentation on python
Presentation on python
 
Python
PythonPython
Python
 
Python
PythonPython
Python
 
Basics of python
Basics of pythonBasics of python
Basics of python
 
Python Basics
Python BasicsPython Basics
Python Basics
 

Destaque

Destaque (20)

Programming with Python - Basic
Programming with Python - BasicProgramming with Python - Basic
Programming with Python - Basic
 
Functional Programming With Python (EuroPython 2008)
Functional Programming With Python (EuroPython 2008)Functional Programming With Python (EuroPython 2008)
Functional Programming With Python (EuroPython 2008)
 
Python/Django Training
Python/Django TrainingPython/Django Training
Python/Django Training
 
Learn 90% of Python in 90 Minutes
Learn 90% of Python in 90 MinutesLearn 90% of Python in 90 Minutes
Learn 90% of Python in 90 Minutes
 
Introduction to Python
Introduction to PythonIntroduction to Python
Introduction to Python
 
Class 6: Lists & dictionaries
Class 6: Lists & dictionariesClass 6: Lists & dictionaries
Class 6: Lists & dictionaries
 
Slicing
SlicingSlicing
Slicing
 
Tuples
TuplesTuples
Tuples
 
Dictionaries in Python
Dictionaries in PythonDictionaries in Python
Dictionaries in Python
 
Python Workshop Part 2. LUG Maniapl
Python Workshop Part 2. LUG ManiaplPython Workshop Part 2. LUG Maniapl
Python Workshop Part 2. LUG Maniapl
 
Lists
ListsLists
Lists
 
web programming Unit VIII complete about python by Bhavsingh Maloth
web programming Unit VIII complete about python  by Bhavsingh Malothweb programming Unit VIII complete about python  by Bhavsingh Maloth
web programming Unit VIII complete about python by Bhavsingh Maloth
 
DITEC - Expose yourself to Internet & E-mail (second update)
DITEC - Expose yourself to Internet & E-mail (second update) DITEC - Expose yourself to Internet & E-mail (second update)
DITEC - Expose yourself to Internet & E-mail (second update)
 
Intro to Python Workshop San Diego, CA (January 19, 2013)
Intro to Python Workshop San Diego, CA (January 19, 2013)Intro to Python Workshop San Diego, CA (January 19, 2013)
Intro to Python Workshop San Diego, CA (January 19, 2013)
 
DITEC - Expose yourself to Internet & E-mail (updated)
DITEC - Expose yourself to Internet & E-mail (updated)DITEC - Expose yourself to Internet & E-mail (updated)
DITEC - Expose yourself to Internet & E-mail (updated)
 
DITEC - Expose yourself to Internet & E-mail
DITEC - Expose yourself to Internet & E-mailDITEC - Expose yourself to Internet & E-mail
DITEC - Expose yourself to Internet & E-mail
 
DITEC - Programming with C#.NET
DITEC - Programming with C#.NETDITEC - Programming with C#.NET
DITEC - Programming with C#.NET
 
DITEC - Software Engineering
DITEC - Software EngineeringDITEC - Software Engineering
DITEC - Software Engineering
 
Intro to Python
Intro to PythonIntro to Python
Intro to Python
 
DISE - Windows Based Application Development in C#
DISE - Windows Based Application Development in C#DISE - Windows Based Application Development in C#
DISE - Windows Based Application Development in C#
 

Semelhante a Programming with Python

Semelhante a Programming with Python (20)

1. python programming
1. python programming1. python programming
1. python programming
 
Python slide.1
Python slide.1Python slide.1
Python slide.1
 
CPPDS Slide.pdf
CPPDS Slide.pdfCPPDS Slide.pdf
CPPDS Slide.pdf
 
2022-23TYBSC(CS)-Python Prog._Chapter-1.pptx
2022-23TYBSC(CS)-Python Prog._Chapter-1.pptx2022-23TYBSC(CS)-Python Prog._Chapter-1.pptx
2022-23TYBSC(CS)-Python Prog._Chapter-1.pptx
 
Python basics
Python basicsPython basics
Python basics
 
python1.ppt
python1.pptpython1.ppt
python1.ppt
 
ENGLISH PYTHON.ppt
ENGLISH PYTHON.pptENGLISH PYTHON.ppt
ENGLISH PYTHON.ppt
 
Python introduction
Python introductionPython introduction
Python introduction
 
Kavitha_python.ppt
Kavitha_python.pptKavitha_python.ppt
Kavitha_python.ppt
 
Python 3.pptx
Python 3.pptxPython 3.pptx
Python 3.pptx
 
python1.ppt
python1.pptpython1.ppt
python1.ppt
 
python1.ppt
python1.pptpython1.ppt
python1.ppt
 
Python Basics
Python BasicsPython Basics
Python Basics
 
python1.ppt
python1.pptpython1.ppt
python1.ppt
 
Lenguaje Python
Lenguaje PythonLenguaje Python
Lenguaje Python
 
pysdasdasdsadsadsadsadsadsadasdasdthon1.ppt
pysdasdasdsadsadsadsadsadsadasdasdthon1.pptpysdasdasdsadsadsadsadsadsadasdasdthon1.ppt
pysdasdasdsadsadsadsadsadsadasdasdthon1.ppt
 
coolstuff.ppt
coolstuff.pptcoolstuff.ppt
coolstuff.ppt
 
python1.ppt
python1.pptpython1.ppt
python1.ppt
 
Introductio_to_python_progamming_ppt.ppt
Introductio_to_python_progamming_ppt.pptIntroductio_to_python_progamming_ppt.ppt
Introductio_to_python_progamming_ppt.ppt
 
python1.ppt
python1.pptpython1.ppt
python1.ppt
 

Mais de Rasan Samarasinghe

Mais de Rasan Samarasinghe (20)

Managing the under performance in projects.pptx
Managing the under performance in projects.pptxManaging the under performance in projects.pptx
Managing the under performance in projects.pptx
 
Agile project management with scrum
Agile project management with scrumAgile project management with scrum
Agile project management with scrum
 
Introduction to Agile
Introduction to AgileIntroduction to Agile
Introduction to Agile
 
IT Introduction (en)
IT Introduction (en)IT Introduction (en)
IT Introduction (en)
 
Application of Unified Modelling Language
Application of Unified Modelling LanguageApplication of Unified Modelling Language
Application of Unified Modelling Language
 
Advanced Web Development in PHP - Understanding REST API
Advanced Web Development in PHP - Understanding REST APIAdvanced Web Development in PHP - Understanding REST API
Advanced Web Development in PHP - Understanding REST API
 
Advanced Web Development in PHP - Understanding Project Development Methodolo...
Advanced Web Development in PHP - Understanding Project Development Methodolo...Advanced Web Development in PHP - Understanding Project Development Methodolo...
Advanced Web Development in PHP - Understanding Project Development Methodolo...
 
Advanced Web Development in PHP - Code Versioning and Branching with Git
Advanced Web Development in PHP - Code Versioning and Branching with GitAdvanced Web Development in PHP - Code Versioning and Branching with Git
Advanced Web Development in PHP - Code Versioning and Branching with Git
 
DIWE - Working with MySQL Databases
DIWE - Working with MySQL DatabasesDIWE - Working with MySQL Databases
DIWE - Working with MySQL Databases
 
DIWE - Using Extensions and Image Manipulation
DIWE - Using Extensions and Image ManipulationDIWE - Using Extensions and Image Manipulation
DIWE - Using Extensions and Image Manipulation
 
DIWE - File handling with PHP
DIWE - File handling with PHPDIWE - File handling with PHP
DIWE - File handling with PHP
 
DIWE - Advanced PHP Concepts
DIWE - Advanced PHP ConceptsDIWE - Advanced PHP Concepts
DIWE - Advanced PHP Concepts
 
DIWE - Fundamentals of PHP
DIWE - Fundamentals of PHPDIWE - Fundamentals of PHP
DIWE - Fundamentals of PHP
 
DIWE - Programming with JavaScript
DIWE - Programming with JavaScriptDIWE - Programming with JavaScript
DIWE - Programming with JavaScript
 
DIWE - Coding HTML for Basic Web Designing
DIWE - Coding HTML for Basic Web DesigningDIWE - Coding HTML for Basic Web Designing
DIWE - Coding HTML for Basic Web Designing
 
DIWE - Multimedia Technologies
DIWE - Multimedia TechnologiesDIWE - Multimedia Technologies
DIWE - Multimedia Technologies
 
Esoft Metro Campus - Programming with C++
Esoft Metro Campus - Programming with C++Esoft Metro Campus - Programming with C++
Esoft Metro Campus - Programming with C++
 
Esoft Metro Campus - Certificate in c / c++ programming
Esoft Metro Campus - Certificate in c / c++ programmingEsoft Metro Campus - Certificate in c / c++ programming
Esoft Metro Campus - Certificate in c / c++ programming
 
Esoft Metro Campus - Certificate in java basics
Esoft Metro Campus - Certificate in java basicsEsoft Metro Campus - Certificate in java basics
Esoft Metro Campus - Certificate in java basics
 
DISE - Software Testing and Quality Management
DISE - Software Testing and Quality ManagementDISE - Software Testing and Quality Management
DISE - Software Testing and Quality Management
 

Último

Verification of thevenin's theorem for BEEE Lab (1).pptx
Verification of thevenin's theorem for BEEE Lab (1).pptxVerification of thevenin's theorem for BEEE Lab (1).pptx
Verification of thevenin's theorem for BEEE Lab (1).pptx
chumtiyababu
 
"Lesotho Leaps Forward: A Chronicle of Transformative Developments"
"Lesotho Leaps Forward: A Chronicle of Transformative Developments""Lesotho Leaps Forward: A Chronicle of Transformative Developments"
"Lesotho Leaps Forward: A Chronicle of Transformative Developments"
mphochane1998
 
Standard vs Custom Battery Packs - Decoding the Power Play
Standard vs Custom Battery Packs - Decoding the Power PlayStandard vs Custom Battery Packs - Decoding the Power Play
Standard vs Custom Battery Packs - Decoding the Power Play
Epec Engineered Technologies
 
Integrated Test Rig For HTFE-25 - Neometrix
Integrated Test Rig For HTFE-25 - NeometrixIntegrated Test Rig For HTFE-25 - Neometrix
Integrated Test Rig For HTFE-25 - Neometrix
Neometrix_Engineering_Pvt_Ltd
 
Kuwait City MTP kit ((+919101817206)) Buy Abortion Pills Kuwait
Kuwait City MTP kit ((+919101817206)) Buy Abortion Pills KuwaitKuwait City MTP kit ((+919101817206)) Buy Abortion Pills Kuwait
Kuwait City MTP kit ((+919101817206)) Buy Abortion Pills Kuwait
jaanualu31
 
DeepFakes presentation : brief idea of DeepFakes
DeepFakes presentation : brief idea of DeepFakesDeepFakes presentation : brief idea of DeepFakes
DeepFakes presentation : brief idea of DeepFakes
MayuraD1
 

Último (20)

Verification of thevenin's theorem for BEEE Lab (1).pptx
Verification of thevenin's theorem for BEEE Lab (1).pptxVerification of thevenin's theorem for BEEE Lab (1).pptx
Verification of thevenin's theorem for BEEE Lab (1).pptx
 
Employee leave management system project.
Employee leave management system project.Employee leave management system project.
Employee leave management system project.
 
"Lesotho Leaps Forward: A Chronicle of Transformative Developments"
"Lesotho Leaps Forward: A Chronicle of Transformative Developments""Lesotho Leaps Forward: A Chronicle of Transformative Developments"
"Lesotho Leaps Forward: A Chronicle of Transformative Developments"
 
Thermal Engineering-R & A / C - unit - V
Thermal Engineering-R & A / C - unit - VThermal Engineering-R & A / C - unit - V
Thermal Engineering-R & A / C - unit - V
 
Standard vs Custom Battery Packs - Decoding the Power Play
Standard vs Custom Battery Packs - Decoding the Power PlayStandard vs Custom Battery Packs - Decoding the Power Play
Standard vs Custom Battery Packs - Decoding the Power Play
 
Engineering Drawing focus on projection of planes
Engineering Drawing focus on projection of planesEngineering Drawing focus on projection of planes
Engineering Drawing focus on projection of planes
 
Work-Permit-Receiver-in-Saudi-Aramco.pptx
Work-Permit-Receiver-in-Saudi-Aramco.pptxWork-Permit-Receiver-in-Saudi-Aramco.pptx
Work-Permit-Receiver-in-Saudi-Aramco.pptx
 
Integrated Test Rig For HTFE-25 - Neometrix
Integrated Test Rig For HTFE-25 - NeometrixIntegrated Test Rig For HTFE-25 - Neometrix
Integrated Test Rig For HTFE-25 - Neometrix
 
A CASE STUDY ON CERAMIC INDUSTRY OF BANGLADESH.pptx
A CASE STUDY ON CERAMIC INDUSTRY OF BANGLADESH.pptxA CASE STUDY ON CERAMIC INDUSTRY OF BANGLADESH.pptx
A CASE STUDY ON CERAMIC INDUSTRY OF BANGLADESH.pptx
 
A Study of Urban Area Plan for Pabna Municipality
A Study of Urban Area Plan for Pabna MunicipalityA Study of Urban Area Plan for Pabna Municipality
A Study of Urban Area Plan for Pabna Municipality
 
NO1 Top No1 Amil Baba In Azad Kashmir, Kashmir Black Magic Specialist Expert ...
NO1 Top No1 Amil Baba In Azad Kashmir, Kashmir Black Magic Specialist Expert ...NO1 Top No1 Amil Baba In Azad Kashmir, Kashmir Black Magic Specialist Expert ...
NO1 Top No1 Amil Baba In Azad Kashmir, Kashmir Black Magic Specialist Expert ...
 
Design For Accessibility: Getting it right from the start
Design For Accessibility: Getting it right from the startDesign For Accessibility: Getting it right from the start
Design For Accessibility: Getting it right from the start
 
Thermal Engineering -unit - III & IV.ppt
Thermal Engineering -unit - III & IV.pptThermal Engineering -unit - III & IV.ppt
Thermal Engineering -unit - III & IV.ppt
 
AIRCANVAS[1].pdf mini project for btech students
AIRCANVAS[1].pdf mini project for btech studentsAIRCANVAS[1].pdf mini project for btech students
AIRCANVAS[1].pdf mini project for btech students
 
kiln thermal load.pptx kiln tgermal load
kiln thermal load.pptx kiln tgermal loadkiln thermal load.pptx kiln tgermal load
kiln thermal load.pptx kiln tgermal load
 
School management system project Report.pdf
School management system project Report.pdfSchool management system project Report.pdf
School management system project Report.pdf
 
Kuwait City MTP kit ((+919101817206)) Buy Abortion Pills Kuwait
Kuwait City MTP kit ((+919101817206)) Buy Abortion Pills KuwaitKuwait City MTP kit ((+919101817206)) Buy Abortion Pills Kuwait
Kuwait City MTP kit ((+919101817206)) Buy Abortion Pills Kuwait
 
COST-EFFETIVE and Energy Efficient BUILDINGS ptx
COST-EFFETIVE  and Energy Efficient BUILDINGS ptxCOST-EFFETIVE  and Energy Efficient BUILDINGS ptx
COST-EFFETIVE and Energy Efficient BUILDINGS ptx
 
DeepFakes presentation : brief idea of DeepFakes
DeepFakes presentation : brief idea of DeepFakesDeepFakes presentation : brief idea of DeepFakes
DeepFakes presentation : brief idea of DeepFakes
 
Unit 4_Part 1 CSE2001 Exception Handling and Function Template and Class Temp...
Unit 4_Part 1 CSE2001 Exception Handling and Function Template and Class Temp...Unit 4_Part 1 CSE2001 Exception Handling and Function Template and Class Temp...
Unit 4_Part 1 CSE2001 Exception Handling and Function Template and Class Temp...
 

Programming with Python

  • 1. Programming with Python Rasan Samarasinghe ESOFT Computer Studies (pvt) Ltd. No 68/1, Main Street, Pallegama, Embilipitiya.
  • 2. Contents 1. Python Overview 2. Python Environment 3. First Python Program 4. Python Basic Syntax 5. Python Variables 6. Standard Data Types 7. Python Operators 8. Python Decision Making 9. Python Loops 10. Python Numbers 11. Python Strings 12. Python Lists 13. Python Tuples 14. Python Dictionary 15. Python Date & Time 16. Python Functions 17. Python Modules 18. Python I/O 19. Python Exceptions 20. Python OOP
  • 3. Python Overview • A high-level, interpreted, interactive and object-oriented scripting language. • Designed to be highly readable which uses English keywords. • Fewer syntactical constructions than other languages.
  • 4. Features • Readability • Support Structured / OOP Styles • Easy to learn • Easy to maintain • A broad standard library • Interactive Mode
  • 5. Features • Portable • Extendable • Support Databases • GUI Programming • Scalable • Easy integration with other languages
  • 6. Application of Python • Systems Programming • GUIs • Internet Scripting • Component Integration • Database Programming • Numeric and Scientific Programming • More: Gaming, Images, Data Mining, Robots, Excel..
  • 7. Python Environment Python is available on a wide variety of platforms (Windows / Linux / Mac OS) Python Official Website: http://www.python.org Install Python Setting up PATH
  • 8. Running Python 1. Interactive Interpreter 2. Run script from the Command line 3. Integrated Development Environment
  • 9. First Python Program In interactive mode programming Type and enter in Python prompt: print ("Hello, World!") Or just type and enter "Hello, World!"
  • 10. First Python Program In script mode programming Make a Python script file test.py and include code: print ("Hello, World!") In command shell run test.py file C:>python_filestest.py
  • 11. 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
  • 12. Python Identifiers • Identifiers are case sensitive. • Class names start with an uppercase letter • Other identifiers start with a lowercase letter. • Starting with a single leading underscore indicates private. • Starting with two leading underscores indicates strongly private. • Ends with two underscores means a language defined special name.
  • 14. Lines and Indentation Blocks of code are denoted by line indentation if True: print("Good") print("Cat") else: print("Bad") print("Cat")
  • 15. Multi Line Statements Use of the line continuation character total = item_one + item_two + item_three
  • 16. Multi Line Statements Statements contained within the [], {} or () brackets do not need to use the line continuation character. days = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday']
  • 17. Quotation in Python Python uses quotes to denote string literals word = 'word' sentence = "This is a sentence." paragraph = """This is a paragraph. It is made up of multiple lines and sentences."""
  • 18. Comments in Python A hash sign # that is not inside a string literal begins a comment. # first comment print ("Hello, Rasan!") # second comment
  • 19. Using Blank Lines • A line containing only whitespace / or comment is known as a blank line and Python totally ignores it. • In an interactive interpreter session an empty physical line used to terminate a multiline statement.
  • 20. Multiple Statements The semicolon ; allows multiple statements on the single line. print ("hello"); print ("Rasan!");
  • 21. Command Line Arguments test.py script to access command line arguments import sys print ('Number of arguments:', len(sys.argv)) print ('Argument List:', str(sys.argv)) Run script in with arguments passed into it. C:>python_filestest.py rasan indunil samarasinghe
  • 22. Python Variables • Variables do not have to be explicitly declared to reserve memory space. • The declaration happens automatically when you assign a value to a variable.
  • 23. Assigning Values to Variables counter = 100 # An integer assignment miles = 1000.0 # A floating point name = "Nuwan" # A string print (counter) print (miles) print (name)
  • 24. Multiple Assignment Python allows you to assign a single value to several variables simultaneously. a = b = c = 1 a, b, c = 1, 2, "nuwan"
  • 25. Standard Data Types • Numbers • String • List • Tuple • Dictionary
  • 26. Python Numbers Number objects are created when you assign a value to them. var1 = 1 var2 = 10
  • 27. Python Numbers You can delete a single object or multiple objects by using the del statement. del var1 del var_a, var_b
  • 28. Number Types in Python
  • 29. Python Strings String created with either pairs of single or double quotes. word = 'word' sentence = "This is a sentence." paragraph = """This is a paragraph. It is made up of multiple lines and sentences."""
  • 30. Python Strings str = 'Hello World!' # Prints complete string print (str) # Prints first character of the string print (str[0]) # Prints characters starting from 3rd to 5th print (str[2:5])
  • 31. Python Strings str = 'Hello World!' # Prints string starting from 3rd character print (str[2:]) # Prints string two times print (str * 2) # Prints concatenated string print (str + "TEST")
  • 32. Python Lists • A list contains items separated by commas and enclosed within square brackets []. • Lists are similar to arrays in C. • Items belonging to a list can be of different data type.
  • 33. Creating Python Lists mylist = [ 'abcd', 786 , 2.23, 'rasan', 70.2 ] tinylist = [123, 'rasan']
  • 34. Printing Python Lists # Prints complete list print (mylist) # Prints first element print (mylist[0]) # Prints elements from 2nd till 3rd print (mylist[1:3])
  • 35. Printing Python Lists # Prints elements starting from 3rd print (mylist[2:]) # Prints list two times print (tinylist * 2) # Prints concatenated lists print (mylist + tinylist)
  • 36. Python Tuples • Consists of a number of values separated by commas enclosed within brackets ( ). • Tuples cannot be updated.
  • 37. Crating Python Tuples mytuple = ( 'abcd', 786 , 2.23, 'rasan', 70.2 ) tinytuple = (123, 'rasan')
  • 38. Printing Python Tuples # Prints complete list print (mytuple) # Prints first element of the list print (mytuple[0]) # Prints elements starting from 2nd till 3rd print (mytuple[1:3])
  • 39. Printing Python Tuples # Prints elements starting from 3rd element print (mytuple[2:]) # Prints list two times print (tinytuple * 2) # Prints concatenated lists print (mytuple + tinytuple)
  • 40. Python Dictionary • Python's dictionaries are kind of hash table type. • They work like associative arrays or hashes found in Perl and consist of key value pairs.
  • 41. Creating Python Dictionary dic = {} dic['one'] = "This is one" dic[2] = "This is two"
  • 42. Crating Python Dictionary tinydic = {'name': 'neil','code':6734, 'dept': 'sales'}
  • 43. Print Python Dictionary Values # Prints value for 'one' key print (dic['one']) # Prints complete dictionary print (tinydic) # Prints all the keys print (tinydic.keys()) # Prints all the values print (tinydic.values())
  • 44. Data Type Conversion Function Description int(x [,base]) Converts x to an integer. base specifies the base if x is a string. long(x [,base] ) Converts x to a long integer. base specifies the base if x is a string. float(x) Converts x to a floating-point number. complex(real [,imag]) Creates a complex number. str(x) Converts object x to a string representation. repr(x) Converts object x to an expression string. eval(str) Evaluates a string and returns an object. tuple(s) Converts s to a tuple.
  • 45. Data Type Conversion Function Description list(s) Converts s to a list. set(s) Converts s to a set. dict(d) Creates a dictionary. d must be a sequence of (key,value) tuples frozenset(s) Converts s to a frozen set. chr(x) Converts an integer to a character. unichr(x) Converts an integer to a Unicode character. ord(x) Converts a single character to its integer value. hex(x) Converts an integer to a hexadecimal string. oct(x) Converts an integer to an octal string.
  • 46. Python Operators 1. Arithmetic Operators 2. Comparison Operators 3. Assignment Operators 4. Logical Operators 5. Bitwise Operators 6. Membership Operators 7. Identity Operators
  • 48. Comparison Operators a = True b = False
  • 58. Theelif Statement SYNTAX: if expression1: statement(s) elif expression2: statement(s) elif expression3: statement(s) else: statement(s)
  • 59. 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)
  • 62. Theelse 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")
  • 63. For loop SYNTAX: for var in sequence: statements(s)
  • 64. Theelse Statement with For Loops 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')
  • 65. Nested for loops SYNTAX: for iterating_var in sequence: for iterating_var in sequence: statements(s) statements(s)
  • 66. Nested while loops SYNTAX: while expression: while expression: statement(s) statement(s)
  • 68. Python Numbers • Number data types store numeric values. • They are immutable data types. • Changing the value of a number data type results in a newly allocated object.
  • 70. Number Type Conversion • int(x) - convert x to a plain integer. • long(x) - convert x to a long integer. • float(x) - convert x to a floating-point number.
  • 71. Number Type Conversion • complex(x) - convert x to a complex number with real part x and imaginary part zero. • complex(x, y) - convert x and y to a complex number with real part x and imaginary part y.
  • 74. Random Number Functions (random module)
  • 75. Python Strings • Strings Created by enclosing characters in quotes. • Treats single quotes the same as double quotes. var1 = 'Hello World!' var2 = "Python Programming"
  • 76. Accessing Values in Strings var1 = 'Hello World!' var2 = "Python Programming" print ("var1[0]: ", var1[0]) print ("var2[1:5]: ", var2[1:5])
  • 77. Updating Strings var1 = ( 'Hello World!' ) print ("Updated String :- ", var1[:6] + 'Python')
  • 80. String Formatting Operator String formatting operator % is unique to strings print ("My name is %s and weight is %d kg!" % ('Khan', 25))
  • 83. Triple Quotes Python's triple quotes allowing strings to span multiple lines. paragraph = """This is a paragraph. It is made up of multiple lines and sentences."""
  • 84. Raw String Raw strings don't treat the backslash as a special character at all. print (r'C:nowhere')
  • 85. Unicode String Normal strings in Python are stored internally as 8-bit ASCII Unicode strings are stored as 16-bit Unicode. print (u'Hello, world!')
  • 90. Python Lists • Lists be written as a list of comma separated values between square brackets. • Items in a list need not all have the same type.
  • 91. Crating Python Lists list1 = ['physics', 'chemistry', 1997, 2000] list2 = [1, 2, 3, 4, 5 ] list3 = ["a", "b", "c", "d"]
  • 92. Accessing Values in Lists list1 = ['physics', 'chemistry', 1997, 2000] list2 = [1, 2, 3, 4, 5 ] list3 = ["a", "b", "c", "d"] print ("list1[0]: ", list1[0]) print ("list2[1:5]: ", list2[1:5])
  • 93. Updating Lists list = ['physics', 'chemistry', 1997, 2000] print ("Value available at index 2 : ") print (list[2]) list[2] = 2001 print ("New value available at index 2 : ") print (list[2])
  • 94. Delete List Elements list1 = ['physics', 'chemistry', 1997, 2000] print (list1) del list1[2] print ("After deleting value at index 2 : ") print (list1)
  • 96. Indexing, Slicing and Matrixes L = ['spam', 'Spam', 'SPAM!']
  • 98. Python Tuples • A tuple is a sequence of immutable Python objects. • Tuples are read only. • Tuples use parentheses ()
  • 99. Crating Python Tuples tup1 = ('physics', 'chemistry', 1997, 2000) tup2 = (1, 2, 3, 4, 5 ) tup3 = "a", "b", "c", "d"
  • 100. Creating Python Tuples Creating an empty tuple: tup1 = () Tuple with one value: tup1 = (50,)
  • 101. Accessing Values in Tuples tup1 = ('physics', 'chemistry', 1997, 2000) tup2 = (1, 2, 3, 4, 5, 6, 7 ) print ("tup1[0]: ", tup1[0]) print ("tup2[1:5]: ", tup2[1:5])
  • 102. Updating Tuples tup1 = (12, 34.56) tup2 = ('abc', 'xyz') # Following action is not valid for tuples # tup1[0] = 100 # So let's create a new tuple as follows tup3 = tup1 + tup2 print (tup3)
  • 103. Delete Tuple tup = ('physics', 'chemistry', 1997, 2000) print (tup) del tup print ("After deleting tup : ") print (tup)
  • 105. Indexing, Slicing and Matrixes L = ('spam', 'Spam', 'SPAM!')
  • 107. Python Dictionary • A dictionary can store any number of Python objects. • Dictionaries consist of pairs of keys and their corresponding values. • A dictionary is mutable.
  • 108. Creating Python Dictionary dict1 = { 'abc': 456 } dict2 = { 'abc': 123, 98.6: 37 }
  • 109. Accessing Values in Dictionary dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'} print ("dict['Name']: ", dict['Name']) print ("dict['Age']: ", dict['Age'])
  • 110. Updating Dictionary dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'} # update existing entry dict['Age'] = 8 # Add new entry dict['School'] = "DPS School"
  • 111. Delete Dictionary Elements dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'}; # remove entry with key 'Name' del dict['Name']; # remove all entries in dict dict.clear(); # delete entire dictionary del dict ;
  • 114. Python Date & Time • A python program can handle date & time in several ways. • Python's time and calendar modules help track dates and times.
  • 115. What is Tick? The function time.time() returns the current system time in ticks since 12:00am, January 1, 1970 (epoch)
  • 116. What is Tick? import time; ticks = time.time() print ("Number of ticks since 12:00am, January 1, 1970:", ticks)
  • 117. TimeTuple Python's time functions handle time as a tuple of 9 numbers
  • 118. struct_time structure time tuple is equivalent to struct_time structure. This structure has following attributes
  • 119. Getting current time import time; localtime = time.asctime( time.localtime(time.time()) ) print ("Local current time :", localtime)
  • 124. Python Functions A function is a block of organized, reusable code that is used to perform a single, related action.
  • 125. Defining a Function SYNTAX: def functionname( parameters ): "function_docstring" function_suite return [expression]
  • 126. Calling a Function # Function definition def printme( str ): "This prints a passed string into this function" print (str) return # Call to printme function printme("I'm first call to user defined function!") printme("Again second call to the same function")
  • 127. Calling a Function 1. Pass by reference 2. Pass by value
  • 128. 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 # Now you can call changeme function mylist = [10,20,30] changeme( mylist ) print ("Values outside the function: ", mylist)
  • 129. Pass by value # Function definition def changeme( mylist ): "This changes a passed list into this function" mylist = [1,2,3,4]; # assign new reference in mylist print ("Values inside the function: ", mylist) return # Call to changeme function mylist = [10,20,30] changeme( mylist ) print ("Values outside the function: ", mylist)
  • 130. Function Arguments • Required arguments • Keyword arguments • Default arguments • Variable-length arguments
  • 131. Required arguments # Function definition def printme( str ): "This prints a passed string into this function" print (str) return # Call printme function printme(); # will generate an error
  • 132. Keyword arguments # Function definition def printinfo( name, age ): "This prints a passed info into this function" print ("Name: ", name) print ("Age ", age) return # Call printinfo function printinfo( age=50, name="miki" )
  • 133. Default arguments # Function definition def printinfo( name, age = 35 ): "This prints a passed info into this function" print ("Name: ", name) print ("Age ", age) return # Call printinfo function printinfo( age=50, name="miki" ) printinfo( name="miki" )
  • 134. Variable-length arguments # Function definition def printinfo( arg1, *vartuple ): "This prints a variable passed arguments" print ("Output is: ") print (arg1) for var in vartuple: print (var) return; # Call printinfo function printinfo( 10 ); printinfo( 70, 60, 50 );
  • 135. Anonymous Functions • lambda keyword used to create small anonymous functions. • Lambda forms can take any number of arguments but return just one value as an expression.
  • 136. Anonymous Functions SYNTAX: lambda [arg1 [,arg2,.....argn]]:expression
  • 137. Anonymous Functions # Function definition sum = lambda arg1, arg2 : arg1 + arg2; # Call sum as a function print ("Value of total : ", sum( 10, 20 )) print ("Value of total : ", sum( 20, 20 ))
  • 138. The return Statement • The statement return exits a function. • Optionally passing back an expression to the caller.
  • 139. The return Statement # Function definition def sum( arg1, arg2 ): # Add both the parameters and return them." total = arg1 + arg2 print ("Inside the function : ", total) return total; # Call sum function total = sum( 10, 20 ); print ("Outside the function : ", total)
  • 140. Scope of Variables • Global variables • Local variables
  • 141. 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; # Call sum function sum( 10, 20 ); print ("Outside the function global total : ", total)
  • 142. Python Modules • A module allows you to logically organize your Python code. • Grouping related code into a module makes the code easier to understand and use.
  • 143. Creating Python Modules Code for a module named hello normally resides in a file named hello.py hello.py file def print_func( par ): print ("Hello : ", par) return
  • 144. The import Statement Using a Python file as a module by executing an import statement. SYNTAX: import module1[, module2[,... moduleN]
  • 145. The import Statement # Import module hello import hello # Call defined function of module as follows hello.print_func("Rasan")
  • 146. Thefrom...import Statement Import specific attributes from a module into the current namespace. SYNTAX: from modname import func1[, func2[, ... funcN]]
  • 147. The from...import * Statement Import all names from a module into the current namespace SYNTAX: from modname import *
  • 148. Locating Modules Sequence 1. The current directory. 2. If the module isn't found, Python then searches each directory in the shell variable PYTHONPATH. 3. If all else fails, Python checks the default path. (UNIX: /usr/local/lib/python/)
  • 149. Namespaces and Scoping • Each function and class method has its own local namespace. • If a local and a global variable have the same name, the local variable shadows the global variable. • Therefore global statement is used to assign a value to a global variable within a function.
  • 150. Namespaces and Scoping Money = 2000 def AddMoney(): # Uncomment the following line to fix the code: # global Money Money = Money + 1 print (Money) AddMoney() print (Money)
  • 151. The dir( ) Function The dir() function returns a sorted list of strings containing the names defined by a module. # Import built-in module math import math content = dir(math) print (content)
  • 152. Theglobals() and locals() Functions • A call to locals() within a function return all the names that can be accessed locally from that function. • A call to globals() within a function return all the names that can be accessed globally from that function.
  • 153. The reload() Function • To re-execute the top-level code in a module, you can use the reload(module_name) function. • The reload() function imports a previously imported module again.
  • 154. Packages in Python • A package is a hierarchical file directory structure. • It defines a single Python application environment that consists of modules and sub packages and so on.
  • 155. Packages in Python Example Create 1. File Pots.py available in Phone directory having function Pots(). 2. Phone/Isdn.py file having function Isdn() 3. Phone/G3.py file having function G3()
  • 156. Packages in Python Example Now, create one more file __init__.py in Phone directory __init__.py from Pots import Pots from Isdn import Isdn from G3 import G3
  • 157. Packages in Python Example # Now import your Phone Package. import Phone Phone.Pots() Phone.Isdn() Phone.G3()
  • 158. Python I/O • Printing to the Screen • Reading Keyboard Input
  • 159. Printing to the Screen print ("Hi there!", "How are you?")
  • 160. Reading Keyboard Input • raw_input() (Works only with python 2.x) • input()
  • 161. The raw_input Function The raw_input() function reads one line from standard input and returns it as a string. str = raw_input("Enter your input: ") print ("Received input is : ", str) (Works only with python 2.x)
  • 162. The input Function input() function assumes the input is a valid Python expression and returns the evaluated result. str = input("Enter your input: "); print ("Received input is : ", str) (In Python 3.x, input() replaces raw_input())
  • 163. Opening and Closing Files • The open() Function • The close() Function
  • 164. The open Function SYNTAX: file object = open(file_name [, access_mode][, buffering])
  • 166. The file object attributes
  • 174. Python Exceptions • An exception is an event, which occurs during the execution of a program. • When a Python script encounters a situation that it can't cope with, it raises an exception.
  • 177. Handling an exception 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.
  • 178. 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.
  • 179. 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. ......................
  • 180. Argument of an Exception SYNTAX: try: You do your operations here; ...................... except ExceptionType, Argument: You can print value of Argument here...
  • 181. Raising an exception SYNTAX: raise [Exception [, args [, traceback]]]
  • 182. User Defined Exceptions # create exception by deriving standard exception class Networkerror(RuntimeError): def __init__(self, arg): self.args = arg # raise exception try: raise Networkerror("Bad hostname") except Networkerror,e: print (e.args)
  • 183. 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
  • 184. Creating Classes class ClassName: 'Optional class documentation string' defining class members… data attributes… functions…
  • 185. Creating Classes 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)
  • 186. Creating Objects # Create first object of Employee class emp1 = Employee("Zara", 2000) # Create second object of Employee class emp2 = Employee("Manni", 5000)
  • 188. Accessing Attributes • getattr(obj, name[, default]) : access the attribute of object. • hasattr(obj,name) : check if an attribute exists or not. • setattr(obj,name,value) : set an attribute. If attribute does not exist, then it would be created. • delattr(obj, name) : delete an attribute.
  • 189. Built-In Class Attributes • __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.
  • 190. Destroying Objects (Garbage Collection) 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")
  • 191. Destroying Objects (Garbage Collection) pt1 = Point() pt2 = pt1 pt3 = pt1 # prints the ids of the objects print (id(pt1), id(pt2), id(pt3)) del pt1 del pt2 del pt3
  • 192. Class Inheritance SYNTAX: class SubClassName (ParentClass1[, ParentClass2, ...]): 'Optional class documentation string' defining class members… data attributes… functions…
  • 193. Class Inheritance 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):
  • 194. Class Inheritance 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
  • 195. Class Inheritance issubclass(sub, sup) : Returns true if the given subclass sub is a subclass of the superclass sup. isinstance(obj, Class) : Returns true if obj is an instance of class Class or is an instance of a subclass of Class
  • 196. Overriding Methods 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
  • 198. Overloading Operators 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)
  • 199. 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)

Notas do Editor

  1. for n in range(1, 100): for d in range(2, n): if n%d == 0: break else: print(n)
  2. n = 1 while n <= 100: d = 2 while d < n: if n%d == 0: break d = d+1 else: print(n) n = n+1
  3. import math x = math.acos(0.5) print(x) #------------------ import math x = math.asin(0.5) print(x)
  4. import random n = random.randrange(1,10,3) print(n) #--------------------------------------------- import random x = [5,6,4,2,6] random.shuffle(x) print(x) #--------------------------------- import random x = random.uniform(1,5) # rand between 1 and 5 print(x) #---------------------------
  5. def functionName( level ): if level < 1: raise "Invalid level!", level # The code below to this would not be executed # if we raise the exception #--------------------- try: Business Logic here... except "Invalid level!": Exception handling here... else: Rest of the code here...
  6. print(getattr(emp1, 'name')) # attribute as a string