programming with python

200

Click here to load reader

Upload: rasan-samarasinghe

Post on 19-Feb-2017

1.389 views

Category:

Engineering


2 download

TRANSCRIPT

Page 1: Programming with Python

Programming with Python

Rasan SamarasingheESOFT Computer Studies (pvt) Ltd.No 68/1, Main Street, Pallegama, Embilipitiya.

Page 2: Programming with Python

Contents

1. Python Overview2. Python Environment3. First Python Program4. Python Basic Syntax5. Python Variables6. Standard Data Types7. Python Operators 8. Python Decision Making9. Python Loops10. Python Numbers

11. Python Strings12. Python Lists13. Python Tuples14. Python Dictionary15. Python Date & Time16. Python Functions17. Python Modules18. Python I/O19. Python Exceptions20. Python OOP

Page 3: Programming with Python

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.

Page 4: Programming with Python

Features

• Readability • Support Structured / OOP Styles• Easy to learn• Easy to maintain• A broad standard library• Interactive Mode

Page 5: Programming with Python

Features

• Portable• Extendable• Support Databases• GUI Programming• Scalable• Easy integration with other languages

Page 6: Programming with Python

Application of Python

• Systems Programming• GUIs• Internet Scripting• Component Integration• Database Programming• Numeric and Scientific Programming• More: Gaming, Images, Data Mining, Robots,

Excel..

Page 7: Programming with Python

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

Page 8: Programming with Python

Running Python

1. Interactive Interpreter2. Run script from the Command line3. Integrated Development Environment

Page 9: Programming with Python

First Python Program

In interactive mode programming

Type and enter in Python prompt:

print ("Hello, World!")

Or just type and enter

"Hello, World!"

Page 10: Programming with Python

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_files\test.py

Page 11: Programming with Python

Python Basic Syntax

Python IdentifiersReserved WordsLines and IndentationMulti Line StatementsQuotation in PythonComments in PythonUsing Blank LinesMultiple StatementsCommand Line Arguments

Page 12: Programming with Python

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.

Page 13: Programming with Python

Reserved Words

Page 14: Programming with Python

Lines and Indentation

Blocks of code are denoted by line indentation

if True: print("Good") print("Cat")else: print("Bad") print("Cat")

Page 15: Programming with Python

Multi Line Statements

Use of the line continuation character \

total = item_one + \ item_two + \ item_three

Page 16: Programming with Python

Multi Line Statements

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

days = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday']

Page 17: Programming with Python

Quotation in Python

Python uses quotes to denote string literals

word = 'word'sentence = "This is a sentence." paragraph = """This is a paragraph. It ismade up of multiple lines and sentences."""

Page 18: Programming with Python

Comments in Python

A hash sign # that is not inside a string literal begins a comment.

# first comment print ("Hello, Rasan!") # second comment

Page 19: Programming with Python

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.

Page 20: Programming with Python

Multiple Statements

The semicolon ; allows multiple statements on the single line.

print ("hello"); print ("Rasan!");

Page 21: Programming with Python

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_files\test.py rasan indunil samarasinghe

Page 22: Programming with Python

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.

Page 23: Programming with Python

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)

Page 24: Programming with Python

Multiple Assignment

Python allows you to assign a single value to several variables simultaneously.

a = b = c = 1

a, b, c = 1, 2, "nuwan"

Page 25: Programming with Python

Standard Data Types

• Numbers • String • List • Tuple • Dictionary

Page 26: Programming with Python

Python Numbers

Number objects are created when you assign a value to them.

var1 = 1 var2 = 10

Page 27: Programming with Python

Python Numbers

You can delete a single object or multiple objects by using the del statement.

del var1del var_a, var_b

Page 28: Programming with Python

Number Types in Python

Page 29: Programming with 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 ismade up of multiple lines and sentences."""

Page 30: Programming with Python

Python Strings

str = 'Hello World!' # Prints complete stringprint (str)

# Prints first character of the stringprint (str[0])

# Prints characters starting from 3rd to 5th print (str[2:5])

Page 31: Programming with Python

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")

Page 32: Programming with Python

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.

Page 33: Programming with Python

Creating Python Lists

mylist = [ 'abcd', 786 , 2.23, 'rasan', 70.2 ] tinylist = [123, 'rasan']

Page 34: Programming with Python

Printing Python Lists

# Prints complete list print (mylist)

# Prints first element print (mylist[0])

# Prints elements from 2nd till 3rd

print (mylist[1:3])

Page 35: Programming with Python

Printing Python Lists

# Prints elements starting from 3rd

print (mylist[2:])

# Prints list two times print (tinylist * 2)

# Prints concatenated lists print (mylist + tinylist)

Page 36: Programming with Python

Python Tuples

• Consists of a number of values separated by commas enclosed within brackets ( ).

• Tuples cannot be updated.

Page 37: Programming with Python

Crating Python Tuples

mytuple = ( 'abcd', 786 , 2.23, 'rasan', 70.2 ) tinytuple = (123, 'rasan')

Page 38: Programming with Python

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])

Page 39: Programming with Python

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)

Page 40: Programming with Python

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.

Page 41: Programming with Python

Creating Python Dictionary

dic = {} dic['one'] = "This is one" dic[2] = "This is two"

Page 42: Programming with Python

Crating Python Dictionary

tinydic = {'name': 'neil','code':6734, 'dept': 'sales'}

Page 43: Programming with Python

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())

Page 44: Programming with Python

Data Type ConversionFunction 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.

Page 45: Programming with Python

Data Type ConversionFunction 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) tuplesfrozenset(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.

Page 46: Programming with Python

Python Operators

1. Arithmetic Operators 2. Comparison Operators 3. Assignment Operators 4. Logical Operators 5. Bitwise Operators 6. Membership Operators 7. Identity Operators

Page 47: Programming with Python

Arithmetic Operators a = 10 b = 20

Page 48: Programming with Python

Comparison Operators a = True b = False

Page 49: Programming with Python

Assignment Operators

Page 50: Programming with Python

Logical Operators

Page 51: Programming with Python

Bitwise Operators a = 60 b = 13

Page 52: Programming with Python

Membership Operators

Page 53: Programming with Python

Identity Operators

Page 54: Programming with Python

Operators Precedence

Page 55: Programming with Python

Python Decision Making

Page 56: Programming with Python

If statements

SYNTAX:

if expression: statement(s)

Page 57: Programming with Python

if...else statements

SYNTAX:

if expression: statement(s) else: statement(s)

Page 58: Programming with Python

The elif Statement

SYNTAX:

if expression1: statement(s) elif expression2: statement(s) elif expression3: statement(s) else: statement(s)

Page 59: Programming with Python

Nested if statementsSYNTAX:

if expression1: statement(s) if expression2: statement(s) elif expression3: statement(s) else statement(s) elif expression4: statement(s) else: statement(s)

Page 60: Programming with Python

Python Loops

Page 61: Programming with Python

While loop

SYNTAX:

while expression: statement(s)

Page 62: Programming with Python

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")

Page 63: Programming with Python

For loop

SYNTAX:

for var in sequence: statements(s)

Page 64: Programming with Python

The else Statement with For Loops

num = 7for 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')

Page 65: Programming with Python

Nested for loops

SYNTAX:

for iterating_var in sequence: for iterating_var in sequence: statements(s) statements(s)

Page 66: Programming with Python

Nested while loops

SYNTAX:

while expression: while expression: statement(s) statement(s)

Page 67: Programming with Python

Loop Control Statements

Page 68: Programming with Python

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.

Page 69: Programming with Python

Number Examples

Page 70: Programming with Python

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.

Page 71: Programming with Python

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.

Page 72: Programming with Python

Mathematical Functions (math header)

Page 73: Programming with Python

Trigonometric Functions (math module)

Page 74: Programming with Python

Random Number Functions (random module)

Page 75: Programming with Python

Python Strings

• Strings Created by enclosing characters in quotes.

• Treats single quotes the same as double quotes.

var1 = 'Hello World!' var2 = "Python Programming"

Page 76: Programming with Python

Accessing Values in Strings

var1 = 'Hello World!' var2 = "Python Programming" print ("var1[0]: ", var1[0])print ("var2[1:5]: ", var2[1:5])

Page 77: Programming with Python

Updating Strings

var1 = ( 'Hello World!' )print ("Updated String :- ", var1[:6] + 'Python')

Page 78: Programming with Python

Escape Characters

Page 79: Programming with Python

String Special Operators

Page 80: Programming with Python

String Formatting Operator

String formatting operator % is unique to strings

print ("My name is %s and weight is %d kg!" % ('Khan', 25))

Page 81: Programming with Python

String Formatting Operator

Page 82: Programming with Python

String Formatting Operator

Page 83: Programming with Python

Triple Quotes

Python's triple quotes allowing strings to span multiple lines.

paragraph = """This is a paragraph. It ismade up of multiple lines and sentences."""

Page 84: Programming with Python

Raw String

Raw strings don't treat the backslash as a special character at all.

print (r'C:\\nowhere')

Page 85: Programming with Python

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!')

Page 86: Programming with Python

String Methods

Page 87: Programming with Python

String Methods

Page 88: Programming with Python

String Methods

Page 89: Programming with Python

String Methods

Page 90: Programming with Python

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.

Page 91: Programming with Python

Crating Python Lists

list1 = ['physics', 'chemistry', 1997, 2000]list2 = [1, 2, 3, 4, 5 ]list3 = ["a", "b", "c", "d"]

Page 92: Programming with Python

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])

Page 93: Programming with Python

Updating Lists

list = ['physics', 'chemistry', 1997, 2000] print ("Value available at index 2 : ")print (list[2])list[2] = 2001print ("New value available at index 2 : ")print (list[2])

Page 94: Programming with Python

Delete List Elements

list1 = ['physics', 'chemistry', 1997, 2000] print (list1)del list1[2]print ("After deleting value at index 2 : ")print (list1)

Page 95: Programming with Python

Basic List Operations

Page 96: Programming with Python

Indexing, Slicing and Matrixes

L = ['spam', 'Spam', 'SPAM!']

Page 97: Programming with Python

Built-in List Functions & Methods

Page 98: Programming with Python

Python Tuples

• A tuple is a sequence of immutable Python objects.

• Tuples are read only.

• Tuples use parentheses ()

Page 99: Programming with Python

Crating Python Tuples

tup1 = ('physics', 'chemistry', 1997, 2000) tup2 = (1, 2, 3, 4, 5 )tup3 = "a", "b", "c", "d"

Page 100: Programming with Python

Creating Python Tuples

Creating an empty tuple:

tup1 = ()

Tuple with one value:

tup1 = (50,)

Page 101: Programming with Python

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])

Page 102: Programming with Python

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 + tup2print (tup3)

Page 103: Programming with Python

Delete Tuple

tup = ('physics', 'chemistry', 1997, 2000) print (tup) del tupprint ("After deleting tup : ")print (tup)

Page 104: Programming with Python

Basic Tuples Operations

Page 105: Programming with Python

Indexing, Slicing and Matrixes

L = ('spam', 'Spam', 'SPAM!')

Page 106: Programming with Python

Built-in Tuple Functions

Page 107: Programming with Python

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.

Page 108: Programming with Python

Creating Python Dictionary

dict1 = { 'abc': 456 }dict2 = { 'abc': 123, 98.6: 37 }

Page 109: Programming with Python

Accessing Values in Dictionary

dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'} print ("dict['Name']: ", dict['Name'])print ("dict['Age']: ", dict['Age'])

Page 110: Programming with Python

Updating Dictionary

dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'} # update existing entry dict['Age'] = 8

# Add new entry dict['School'] = "DPS School"

Page 111: Programming with Python

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 ;

Page 112: Programming with Python

Built-in Dictionary Functions and Methods

Page 113: Programming with Python

Built-in Dictionary Functions and Methods

Page 114: Programming with Python

Python Date & Time

• A python program can handle date & time in several ways.

• Python's time and calendar modules help track dates and times.

Page 115: Programming with Python

What is Tick?

The function time.time() returns the current system time in ticks since 12:00am, January 1, 1970 (epoch)

Page 116: Programming with Python

What is Tick?

import time; ticks = time.time() print ("Number of ticks since 12:00am, January 1, 1970:", ticks)

Page 117: Programming with Python

TimeTuple

Python's time functions handle time as a tuple of 9 numbers

Page 118: Programming with Python

struct_time structure

time tuple is equivalent to struct_time structure. This structure has following attributes

Page 119: Programming with Python

Getting current time

import time; localtime = time.asctime( time.localtime(time.time()) ) print ("Local current time :", localtime)

Page 120: Programming with Python

The time Module

Page 121: Programming with Python

The time Module

Page 122: Programming with Python

The calendar Module

Page 123: Programming with Python

The calendar Module

Page 124: Programming with Python

Python Functions

A function is a block of organized, reusable code that is used to perform a single, related action.

Page 125: Programming with Python

Defining a Function

SYNTAX:

def functionname( parameters ): "function_docstring" function_suite return [expression]

Page 126: Programming with Python

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")

Page 127: Programming with Python

Calling a Function

1. Pass by reference2. Pass by value

Page 128: Programming with Python

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)

Page 129: Programming with Python

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)

Page 130: Programming with Python

Function Arguments

• Required arguments • Keyword arguments • Default arguments • Variable-length arguments

Page 131: Programming with Python

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

Page 132: Programming with Python

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" )

Page 133: Programming with Python

Default arguments

# Function definitiondef 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" )

Page 134: Programming with Python

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 );

Page 135: Programming with Python

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.

Page 136: Programming with Python

Anonymous Functions

SYNTAX:

lambda [arg1 [,arg2,.....argn]]:expression

Page 137: Programming with Python

Anonymous Functions

# Function definitionsum = lambda arg1, arg2 : arg1 + arg2; # Call sum as a function print ("Value of total : ", sum( 10, 20 ))print ("Value of total : ", sum( 20, 20 ))

Page 138: Programming with Python

The return Statement

• The statement return exits a function.

• Optionally passing back an expression to the caller.

Page 139: Programming with Python

The return Statement

# Function definitiondef 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)

Page 140: Programming with Python

Scope of Variables

• Global variables • Local variables

Page 141: Programming with Python

Scope of Variables

total = 0; # This is global variable# Function definitiondef 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)

Page 142: Programming with Python

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.

Page 143: Programming with Python

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

Page 144: Programming with Python

The import Statement

Using a Python file as a module by executing an import statement.

SYNTAX:

import module1[, module2[,... moduleN]

Page 145: Programming with Python

The import Statement

# Import module hello import hello # Call defined function of module as follows hello.print_func("Rasan")

Page 146: Programming with Python

The from...import Statement

Import specific attributes from a module into the current namespace.

SYNTAX:

from modname import func1[, func2[, ... funcN]]

Page 147: Programming with Python

The from...import * Statement

Import all names from a module into the current namespace

SYNTAX:

from modname import *

Page 148: Programming with Python

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/)

Page 149: Programming with 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.

Page 150: Programming with Python

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)

Page 151: Programming with Python

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)

Page 152: Programming with Python

The globals() 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.

Page 153: Programming with Python

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.

Page 154: Programming with Python

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.

Page 155: Programming with Python

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()

Page 156: Programming with Python

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

Page 157: Programming with Python

Packages in Python Example

# Now import your Phone Package. import Phone Phone.Pots() Phone.Isdn() Phone.G3()

Page 158: Programming with Python

Python I/O

• Printing to the Screen• Reading Keyboard Input

Page 159: Programming with Python

Printing to the Screen

print ("Hi there!", "How are you?")

Page 160: Programming with Python

Reading Keyboard Input

• raw_input() (Works only with python 2.x)• input()

Page 161: Programming with Python

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)

Page 162: Programming with Python

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())

Page 163: Programming with Python

Opening and Closing Files

• The open() Function• The close() Function

Page 164: Programming with Python

The open Function

SYNTAX:

file object = open(file_name [, access_mode][, buffering])

Page 165: Programming with Python

File open modes

Page 166: Programming with Python

The file object attributes

Page 167: Programming with Python

File Object Methods

Page 168: Programming with Python

File Object Methods

Page 169: Programming with Python

OS Object Methods

Page 170: Programming with Python

OS Object Methods

Page 171: Programming with Python

OS Object Methods

Page 172: Programming with Python

OS Object Methods

Page 173: Programming with Python

OS Object Methods

Page 174: Programming with Python

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.

Page 175: Programming with Python

Standard Exceptions in Python

Page 176: Programming with Python

Standard Exceptions in Python

Page 177: Programming with 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.

Page 178: Programming with Python

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.

Page 179: Programming with Python

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. ......................

Page 180: Programming with Python

Argument of an Exception

SYNTAX:

try: You do your operations here; ...................... except ExceptionType, Argument: You can print value of Argument here...

Page 181: Programming with Python

Raising an exception

SYNTAX:

raise [Exception [, args [, traceback]]]

Page 182: Programming with Python

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)

Page 183: Programming with Python

Python OOP

1. Creating Classes2. Creating Objects3. Accessing Attributes4. Destroying Objects5. Class Inheritance6. Overriding Methods7. Overloading Operators8. Data Hiding

Page 184: Programming with Python

Creating Classes

class ClassName: 'Optional class documentation string' defining class members… data attributes… functions…

Page 185: Programming with Python

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)

Page 186: Programming with Python

Creating Objects

# Create first object of Employee class emp1 = Employee("Zara", 2000)

# Create second object of Employee classemp2 = Employee("Manni", 5000)

Page 187: Programming with Python

Accessing Attributes

emp1.displayEmployee() emp2.displayEmployee() print ("Total Employee %d" % Employee.empCount)

Page 188: Programming with Python

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.

Page 189: Programming with Python

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.

Page 190: Programming with Python

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")

Page 191: Programming with Python

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

Page 192: Programming with Python

Class Inheritance

SYNTAX:

class SubClassName (ParentClass1[, ParentClass2, ...]): 'Optional class documentation string' defining class members… data attributes… functions…

Page 193: Programming with Python

Class Inheritanceclass 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):

Page 194: Programming with Python

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

Page 195: Programming with Python

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

Page 196: Programming with Python

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

Page 197: Programming with Python

Base Overloading Methods

Page 198: Programming with Python

Overloading Operatorsclass 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)

Page 199: Programming with Python

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)

Page 200: Programming with Python

The End

http://twitter.com/rasansmn