Python programming Workshop SITTTR - Kalamassery
-
Upload
shamjith-km -
Category
Education
-
view
605 -
download
9
Transcript of Python programming Workshop SITTTR - Kalamassery
PYTHON PROGRAMMING
RIYAZ P AEmail : [email protected]
TODAY’S CLASS• Introduction• What is Python ?
• Why Python ?
• Features
• Basics of Python
• Syntax
• Import
• Input Functions
• Output Functions
PYTHON PROGRAMMING 2
WHAT IS PYTHON ?
PYTHON PROGRAMMING 3
Python is a widely used general-purpose, high-level programming language.
Python is simple and powerful language
WHY PYTHON ?
PYTHON PROGRAMMING 4
WHY PYTHON ?
PYTHON PROGRAMMING 5
Ease of Use and Powerful
Community Driven
Currently it’s in the top five programming languages in the world according to TIOBE Index
Two times winner of Programming Language of the Year(2007 and 2010) by TIOBE Index
FEATURES
PYTHON PROGRAMMING 6
Simple
Free and Open Source
Powerful
Object Oriented
Dynamic, strongly typed scripting language
Portable
Interpreted
FEATURES
PYTHON PROGRAMMING 7
Embeddable
Extensive Libraries
Scalable
Extensible
CAN DO Text Handling
System Administration
GUI programming
Web Applications
Database Apps
Scientific Applications
Games
NLP
Image Processing
IoT and lot more …..
PYTHON PROGRAMMING 8
ZEN OF PYTHON
PYTHON PROGRAMMING 9
PYTHON PROGRAMMING 10
WHO USES PYTHON ?
PYTHON PROGRAMMING 11
RELEASES
PYTHON PROGRAMMING 12
Created in 1989 by Guido Van Rossum
Python 1.0 released in 1994
Python 2.0 released in 2000
Python 3.0 released in 2008
Python 2.7 is the recommended version
3.0 adoption will take a few years
HELLO WORLD
hello_world.py
print('Hello, World!')
PYTHON PROGRAMMING 13
PYTHON 2 vs PYTHON 3 print ('Python‘)
print 'Hello, World!'
print('Hello, World!')
In python 3 second statement will show an error
File "", line 1
print 'Hello, World!'
^
SyntaxError: invalid syntax
PYTHON PROGRAMMING 14
SAVING PYTHON PROGRAMS
PYTHON PROGRAMMING 15
COMMENTS
#Hello
‘’’ Hai
hello
‘’’
PYTHON PROGRAMMING 16
IMPORT When our program grows bigger, it is a good idea to break it into different modules.
A module is a file containing Python definitions and statements.
Python modules have a filename and end with the extension .py
Definitions inside a module can be imported to another module or the interactive interpreter in Python.
. We use the import keyword to do this.
PYTHON PROGRAMMING 17
IMPORT
>>> import math
>>> math.pi
3.141592653589793
>>> from math import pi
>>> pi
3.141592653589793
PYTHON PROGRAMMING 18
IMPORT While importing a module, Python looks at several places defined in sys.path.
It is a list of directory locations.
>>> import sys
>>> sys.path
['',
'C:\\Python33\\Lib\\idlelib',
'C:\\Windows\\system32\\python33.zip',
'C:\\Python33\\DLLs',
'C:\\Python33\\lib',
'C:\\Python33',
'C:\\Python33\\lib\\site-packages']
PYTHON PROGRAMMING 19
SUM OF TWO NUMBERS# Store input numbers
num1 = input('Enter first number: ') # input is built-in function
num2 = input('Enter second number: ') # input returns string
# Add two numbers
sum = float(num1) + float(num2)
# Display the sum
print('The sum of {0} and {1} is {2}'.format(num1, num2, sum))
PYTHON PROGRAMMING 20
FOR PYTHON 2 from __future__ import print_function Type this in first line to avoid errors if you use python 2.
PYTHON PROGRAMMING 21
OUTPUT
>>> print('This sentence is output to the screen')
This sentence is output to the screen
>>> a = 5
>>> print('The value of a is',a)
The value of a is 5
PYTHON PROGRAMMING 22
OUTPUT…For Python 3
print(1,2,3,4)
print(1,2,3,4,sep='*')
print(1,2,3,4,sep='#',end='&')
Output
1 2 3 4
1*2*3*4
1#2#3#4&
PYTHON PROGRAMMING 23
OUTPUT FORMATTING Sometimes we would like to format our output to make it look attractive.
This can be done by using the str.format() method.
This method is visible to any string object
>>> x = 5; y = 10
>>> print('The value of x is {} and y is {}'.format(x,y))
The value of x is 5 and y is 10
PYTHON PROGRAMMING 24
OUTPUT FORMATTING>>> print('I love {0} and {1}'.format('bread','butter'))
I love bread and butter
>>> print('I love {1} and {0}'.format('bread','butter'))
I love butter and bread
>>> print('Hello {name}, {greeting}'.format(greeting='Goodmorning',name='John'))
Hello John, Goodmorning
PYTHON PROGRAMMING 25
OUTPUT FORMATTINGWe can even format strings like the old printf() style used in C programming language.
>>> x = 12.3456789
>>> print('The value of x is %3.2f' %x)
The value of x is 12.35
>>> print('The value of x is %3.4f' %x)
The value of x is 12.3457
PYTHON PROGRAMMING 26
AREA OF TRIANGLE a = float(input('Enter first side: '))
b = float(input('Enter second side: '))
c = float(input('Enter third side: '))
# calculate the semi-perimeter
s = (a + b + c) / 2
# calculate the area
area = (s*(s-a)*(s-b)*(s-c)) ** 0.5
print('The area of the triangle is %0.2f' %area)
PYTHON PROGRAMMING 27
INPUTPython 3
Syntax
input([prompt])
>>> num = input('Enter a number: ')
Enter a number: 10
>>> num
'10'
PYTHON PROGRAMMING 28
INPUTHere, we can see that the entered value 10 is a string, not a number.
To convert this into a number we can use int() or float() functions.
>>> int('10')
10
>>> float('10')
10.0
PYTHON PROGRAMMING 29
INPUT EVAL
>>> int('2+3')
Traceback (most recent call last):
File "<string>", line 301, in runcode
File "<interactive input>", line 1, in <module>
ValueError: invalid literal for int() with base 10: '2+3'
>>> eval('2+3')
5
PYTHON PROGRAMMING 30
TEMPERATURE CONVERSION# take input from the user
celsius = float(input('Enter degree Celsius: '))
# calculate fahrenheit
fahrenheit = (celsius * 1.8) + 32
print('%0.1f degree Celsius is equal to %0.1f degree Fahrenheit' %(celsius,fahrenheit))
PYTHON PROGRAMMING 31
AVERAGE OF THREE NUMBERS
PYTHON PROGRAMMING 32
n1=float(input('1st num'))
n2=float(input('2nd num'))
n3=float(input('3rd num'))
avg=(n1+n2+n3)/3
print "Avarage os 3 numbers
{},{},{},={}\n".format(n1,n2,n3,avg)
print ("Avarage os 3 numbers %0.2f %0.2f %0.2f%0.2f"
%(n1,n2,n3,avg))
KEYWORDS
PYTHON PROGRAMMING 33
DATA TYPES Strings
Numbers
Null
Lists
Dictionaries
Booleans
PYTHON PROGRAMMING 34
Strings
PYTHON PROGRAMMING 35
Numbers
PYTHON PROGRAMMING 36
Null
PYTHON PROGRAMMING 37
Lists
PYTHON PROGRAMMING 38
Lists
PYTHON PROGRAMMING 39
Dictionaries
PYTHON PROGRAMMING 40
Dictionary Methods
PYTHON PROGRAMMING 41
Booleans
PYTHON PROGRAMMING 42
SQUARE ROOT # Python Program to calculate the square root
num = float(input('Enter a number: '))
num_sqrt = num ** 0.5
print('The square root of %0.3f is %0.3f'%(num ,num_sqrt))
PYTHON PROGRAMMING 43
SQUARE ROOT - COMPLEX # Find square root of real or complex numbers
# Import the complex math module
import cmath
num = eval(input('Enter a number: '))
num_sqrt = cmath.sqrt(num)
print('The square root of {0} is {1:0.3f}+{2:0.3f}j'.format(num,num_sqrt.real,num_sqrt.imag))
PYTHON PROGRAMMING 44
OPERATORS Arithmetic
String Manipulation
Logical Comparison
Identity Comparison
Arithmetic Comparison
PYTHON PROGRAMMING 45
Arithmetic
PYTHON PROGRAMMING 46
String Manipulation
PYTHON PROGRAMMING 47
Logical Comparison
PYTHON PROGRAMMING 48
Identity Comparison
PYTHON PROGRAMMING 49
Arithmetic Comparison
PYTHON PROGRAMMING 50
VOLUME OF CYLINDER
PYTHON PROGRAMMING 51
from math import pi
r=input("Enter Radius")
h=input("Enter Height")
vol=pi*r**2*h
print (vol)
PYTHON PROGRAMMING 52
PYTHON PROGRAMMING 53
PYTHON PROGRAMMING 54
PYTHON PROGRAMMING 55
Avoid next line in printPython 2.x
Print ”hai”,
Print ”hello”
Python 3.x
Print (‘hai’, end=‘’)
Print(‘hello’)
PYTHON PROGRAMMING 56
TODAY’S CLASS• Intendation
• Decision Making
• Control Statements
PYTHON PROGRAMMING 57
INDENTATION
Most languages don’t care about indentation
Most humans do
Python tend to group similar things together
PYTHON PROGRAMMING 58
INDENTATION
The else here actually belongs to the 2nd if statement
PYTHON PROGRAMMING 59
INDENTATION
The else here actually belongs to the 2nd if statement
PYTHON PROGRAMMING 60
INDENTATION
I knew a coder like this
PYTHON PROGRAMMING 61
INDENTATION
You should always be explicit
PYTHON PROGRAMMING 62
INDENTATION
Python embraces indentation
PYTHON PROGRAMMING 63
DECISION MAKING Decision making is anticipation of conditions occurring while execution of the program and specifying actions taken according to the conditions.
Decision structures evaluate multiple expressions which produce TRUE or FALSE as outcome.
You need to determine which action to take and which statements to execute if outcome is TRUE or FALSE otherwise.
assumes any non-zero and non-null values as TRUE, and if it is either zero or null, then it is assumed as FALSE value.
PYTHON PROGRAMMING 64
DECISION MAKING
PYTHON PROGRAMMING 65
DECISION STATEMENTS If
If Else
If Elif
Nested If
PYTHON PROGRAMMING 66
IF
PYTHON PROGRAMMING 67
var1=100
if True:
print ("1 - Got a true“)
print (var1)
var2=0
if var2:
print ("2- Got a true“)
print (var2)
print ("good bye“)
IF ELSE : ODD OR EVEN
PYTHON PROGRAMMING 68
num=input("number")
if num%2==0:
print (num,'is Even‘)
else:
print (num,'is Odd‘)
IF ELIF
PYTHON PROGRAMMING 69
num=input("Enter a number")
if num>0:
print (num,'is Positive‘)
elif num==0:
print (num,'is Zero‘)
else:
print (num,'is Negative‘)
print ('Have a nice day‘)
NESTED IF
PYTHON PROGRAMMING 70
num=input("Enter a number")
if num>0:
print (num,'is Positive')
else:
if num==0:
print (num,'is Zero')
else:
print (num,'is Negative')
print ('Have a nice day')
LARGEST OF THREE NUMBERS
PYTHON PROGRAMMING 71
a=input('1st number')
b=input('2nd number')
c=input('3rd number')
if (a>b) and (a>c):
large=a
elif (b>a) and (b>c):
large=b
else:
large=c
print ('The largest number is ',large)
QUADRATIC EQUATION
PYTHON PROGRAMMING 72
import cmath
print 'Enter the Coeifficents'
a=input("a")
b=input("b")
c=input("c")
delta=(b**2)-4*a*c
if delta>0:
sq=delta**0.5
x=(-b+sq)/(2.0*a)
y=(-b-sq)/(2.0*a)
print 'roots are \n {} \n {}'.format(x,y)
#Cont to next slide
QUADRATIC EQUATION …elif delta==0:
x=-b/(2.0*a)y=xprint 'roots are Equal'print 'roots are\n {} \n {}'.format(x,y)
else:print 'imaginary'#delta=-deltasqi=cmath.sqrt(delta)x=-b/(2.0*a)#print xprint 'roots are \n {0} + {1} j \n {0} - {1} j
'.format(x,sqi.imag)
#print sqi.imag
PYTHON PROGRAMMING 73
LOOPS For
While
While else
While Infinite Loop
While with condition at top, middle and bottom
PYTHON PROGRAMMING 74
FOR
PYTHON PROGRAMMING 75
sum=0
for i in range(11):
print i
sum+=i
print ('sum=',sum)
FOR
PYTHON PROGRAMMING 76
start=input('Enter start')
stop=input('stop')
stepindex=input('step')
for i in range(start,stop+1,stepindex):
print (i)
NUMBERS DIV BY 7 and 2
PYTHON PROGRAMMING 77
num=[]
for i in range(100,1000):
if i%7==0:
num.append(i)
print (num)
print ('\n\n\n')
num2=[]
for i in num:
if i%2==0:
num2.append(i)
print (num2)
FACTORIAL
PYTHON PROGRAMMING 78
num=input('Enter number')
f=1
if num==0:
print (f)
else:
for i in range(1,num+1):
#f*=i
f=f*i
print (f)
PRIME NUMBER
PYTHON PROGRAMMING 79
num=input('Enter number')
f=0
for i in range(2,(num/2)+1):
if num%i==0:
#print i
f=1
break
if f:
print (num,'is Not a Prime number‘)
else:
print (num,'is Prime number‘)
CONTINUE
PYTHON PROGRAMMING 80
num=[]
for i in range(100,1000):
if i%7==0:
continue
num.append(i)
print (num)
PASS
PYTHON PROGRAMMING 81
num=[]
for i in range(100,1000):
pass
For empty for loop, function and class , you need to use pass
WHILE LOOP
PYTHON PROGRAMMING 82
n=input('Enter a Number \n')
sum=0
i=1
while i<= n:
sum+=i
i+=1
print ('The Sum is ',sum)
WHILE ELSE
PYTHON PROGRAMMING 83
count=0
while count<3:
print 'inside loop'
count+=1
else:
print 'outside loop'
INFINITE LOOP
PYTHON PROGRAMMING 84
i=1 # Use Ctrl+C to exit the loop.
#Do it carefully
while True:
print i
i=i+1
VOWEL
PYTHON PROGRAMMING 85
vowels="aeiouAEIOU"
while True:
v=input("Enter a Char: ")
if v in vowels:
break
print ('not a vowel try again')
print ('thank you')
MULTIPLICATION TABLE
PYTHON PROGRAMMING 86
num=input('Enter Number: ')
i=1
while i<11:
print ('{} * {} = {}'.format(i,num,num*i))
i+=1
MULTIPLICATION TABLE
PYTHON PROGRAMMING 87
num=input('Enter Number: ')
for i in range(1,21):
print ('{} * {} = {}'.format(i,num,num*i))
LCM
PYTHON PROGRAMMING 88
n1=input('Enter 1st number ')
n2=input('Enter 2nd number ')
'''
if n1>n2:
lcm=n1
else:
lcm=n2
'''
lcm=max(n1,n2)
while True:
if (lcm%n1==0) and (lcm%n2==0):
break
lcm+=1
print ('LCM of {} and {} is {}'.format(n1,n2,lcm))
STUDENT GRADE
PYTHON PROGRAMMING 89
name=raw_input('Enter Student Name: ')
gpa=input('Enter GPA: ')
if gpa>=9:
print ('{} has got {} Grade'.format(name,'S'))
elif gpa>=8 and gpa<9 :
print ('{} has got {} Grade'.format(name,'A'))
elif gpa>=7 and gpa <8 :
print ('{} has got {} Grade'.format(name,'B'))
elif gpa>=6 and gpa<7:
print ('{} has got {} Grade'.format(name,'C'))
elif gpa>=5 and gpa<6:
print ('{} has got {} Grade'.format(name,'D'))
else:
print ('{} is Failed'.format(name))
DAYS WITH FUNCTION
PYTHON PROGRAMMING 90
days={
1:'Sun',
2:'Mon',
3:'Tue',
4:'Wed',
5:'Thu',
6:'Fri',
7:'Sat'
}
def day(d):
if days.get(d):
print ('Day is ',days.get(d))
else:
print ('Invalid Key ‘)
d=input('Enter the Day: ')
day(d)
SUM OF DIGITS
PYTHON PROGRAMMING 91
n=input('Enter the Number: ')
s=0
while n>0:
# a=n%10
# print a
s+=n%10
n/=10
print ('Sum of digit is ',s)
PALINDROME NUMBER
PYTHON PROGRAMMING 92
n=input('Enter the Number: ')
rev=0
n1=n
while n>0:
rev=rev*10+n%10
n/=10
print ('Reverse of Number is ',rev)
if rev==n1:
print ('Palindrome‘)
else:
print ('Not Palindrome‘)
ANTIGRAVITYImport antigravity
PYTHON PROGRAMMING 93
TODAY’S CLASS• Functions
• Namespace
• Name Binding
• Modules
• Packages
PYTHON PROGRAMMING 94
TARGET SCENARIO
PYTHON PROGRAMMING 95
BUILDING BLOCKS
PYTHON PROGRAMMING 96
DIVISION OF LABOUR
PYTHON PROGRAMMING 97
DIVISION OF LABOUR
PYTHON PROGRAMMING 98
ASSEMBLY LINE
PYTHON PROGRAMMING 99
DIVIDE AND CONQUER
PYTHON PROGRAMMING 100
DIVIDE AND CONQUERevery problem can be broken down into smaller/more manageable sub-problems
most computer programs that solve real-world problems are complex/large
the best way to develop and maintain a large program is to construct it from smaller pieces or components
PYTHON PROGRAMMING 101
PYTHON PROGRAM COMPONENTS functions
classes
modules collection of functions & classes
packages collection of modules
PYTHON PROGRAMMING 102
PYTHON PROGRAM COMPONENTS
PYTHON PROGRAMMING 103
Package
Module
Function
Class
FUNCTIONScollection or block of statements that you can execute
whenever and wherever you want in the program
PYTHON PROGRAMMING 104
FUNCTIONS
PYTHON PROGRAMMING 105
FUNCTIONS
PYTHON PROGRAMMING 106
WHY FUNCTIONS avoids duplicating code snippets
saves typing
easier to change the program later
PYTHON PROGRAMMING 107
FUNCTIONSdef function_name(parameters):
"""docstring"""
statement(s)
PYTHON PROGRAMMING 108
USER DEFINED FUNCTIONS
PYTHON PROGRAMMING 109
USER DEFINED FUNCTIONS
PYTHON PROGRAMMING 110
RETURN KEYWORD
PYTHON PROGRAMMING 111
VARIABLE SCOPE
PYTHON PROGRAMMING 112
x = “Rahul”
def kerala():
x =“Suresh”
print (x)
kerala()
print x
PYTHON FUNCTIONS (PARAMS vs ARGS)
PYTHON PROGRAMMING 113
Function Parameters
Function Arguments
PYTHON FUNCTIONS (ARGUMENTS) You can call a function by using the following types of formal arguments:
Required Arguments
Default Arguments
Keyword Arguments
Variable-Length Arguments
PYTHON PROGRAMMING 114
REQUIRED ARGUMENTS
PYTHON PROGRAMMING 115
Required/Mandatory Arguments passed to a function in correct positional order
def sum(x,y):return x+y
print sum(2, 3)
DEFAULT ARGUMENTS
PYTHON PROGRAMMING 116
assumes a default value if a value is not provided in the function call for that argument.
def sum(x=1,y=1):return x+y
print sum()print sum(2, 3)print sum(x=2)print sum(x=2, y=3)print sum(y=3, x=2)
KEYWORD ARGUMENTS
PYTHON PROGRAMMING 117
the caller identifies the arguments by the parameter name as keywords,with/without regard to positional order
def sum(x,y):return x+y
print sum(y=3, x=2)
VARIABLE ARGUMENTS
PYTHON PROGRAMMING 118
can handle no-argument, 1-argument, or many-arguments function calls
def sum(*addends):total=0for i in addends:
total+=ireturn total
print sum()print sum(2)print sum(2,3)print sum(2,3,4)
TRY IT OUT Program to find the sum of digits
PYTHON PROGRAMMING 119
FIBONACCI# Fibonacci numbers moduledef fib(n): # write Fibonacci series up to n
a, b = 0, 1while b < n:
print b,a, b = b, a+b
def fib2(n): # return Fibonacci series up to nresult = []a, b = 0, 1while b < n:
result.append(b)a, b = b, a+b
return result
PYTHON PROGRAMMING 120
SUM_AB FUNCTION
PYTHON PROGRAMMING 121
def sumab(a,b):
sum=0
for i in range(a,b+1):
sum=sum+i
return sum
MATRIX
PYTHON PROGRAMMING 122
# Read the Matrix
def readmat(r,c):
mat=[]
for i in range(r):
temp=[]
for j in range(c):
n=input('Enter the Number: ')
temp.append(n)
mat.append(temp)
return mat
# Calculate the sum
def matsum(r,c,a,b):
res=[]
for i in range(r):
temp=[]
for j in range(c):
sum=a[i][j]+b[i][j]
# print sum
temp.append(sum)
res.append(temp)
# print res
return res
MATRIX…# Print Matrix
def printmat(r,c,a):print 'The Matrix is \n 'for i in range(r):
for j in range(c):print a[i][j],"\t",
print '\n 'print "\n\n"
# Find Transponse
def transpose(r,c,a):trans=[]for i in range(c):
tmp=[]for j in range(r):
tmp.append(0)trans.append(tmp)
for i in range(c):for j in range(r):
trans[i][j]=a[j][i]return trans
PYTHON PROGRAMMING 123
MATRIX…# Main pgmr=input('Enter no. of rows: ')c=input('Enter no. of cols: ')#print 'Enter 1 st matrix \n'
a=readmat(r,c)print 'Enter 2nd matrix '
b=readmat(r,c)res=matsum(r,c,a,b)print 'The First Matrix'printmat(r,c,a)print 'The Second Matrix'printmat(r,c,b)print 'The Sum of Matrix'printmat(r,c,res)print 'The trnsponse Matrix't=transpose(r,c,res)printmat(c,r,t)
PYTHON PROGRAMMING 124
NAMESPACESrefers to the current snapshot of loaded names/variables/identifiers/folders
functions must be loaded into the memory before you could call them, especially when calling external functions/libraries
PYTHON PROGRAMMING 125
NAMESPACESimport math
print dir()
PYTHON PROGRAMMING 126
NAMESPACESimport math, random
print dir()
PYTHON PROGRAMMING 127
FROM NAMESPACES IMPORTING FUNCTIONSfrom math import sin, cos, tan
print dir()
PYTHON PROGRAMMING 128
NAME BINDINGImport math as m
print m.sqrt()
from math import sqrt as s
print s(2)
PYTHON PROGRAMMING 129
Handling Modules#Create demo.py
import my_module
#Create my_module.py
Print(“Entering My Module”)
Print(“Exiting My Module”)
PYTHON PROGRAMMING 130
PYTHON PROGRAMMING 131
* groups related modules
* code calling in several locations
* prevents name collision
HANDLING PACKAGES
PYTHON PROGRAMMING 132
HANDLING OF PACKAGESThe __init__.py files are required to make Python treat the directories as containing packages
PYTHON PROGRAMMING 133
HANDLING OF PACKAGES: WILL NOT WORK
PYTHON PROGRAMMING 134
HANDLING OF PACKAGES: WILL WORK
PYTHON PROGRAMMING 135
HANDLING OF PACKAGES: WILL WORK
PYTHON PROGRAMMING 136
HANDLING OF PACKAGES: WILL WORK
PYTHON PROGRAMMING 137
SUMMARY
IMPORTATION INVOCATION
import p1.p2.m p1.p2.m.f1()
from p1.p2 import m m.f1()
from p1.p2.m import f1 f1()
PYTHON PROGRAMMING 138
PYTHON PROGRAMMING 139
Divide-and-Conquer is Powerful!
SYNTAX ERRORS Syntax errors, also known as parsing errors
perhaps the most common kind of complaint you get while you are still learning Python:
>>> while True print 'Hello world'
File "<stdin>", line 1, in ?
while True print 'Hello world'
^
SyntaxError: invalid syntax
PYTHON PROGRAMMING 140
EXCEPTIONSEven if a statement or expression is syntactically correct, it may cause an error when an attempt is made to execute it.
Errors detected during execution are called exceptions and are not unconditionally fatal: you will soon learn how to handle them in Python programs.
>>> 10 * (1/0)
Traceback (most recent call last):
File "<stdin>", line 1, in ?
ZeroDivisionError: integer division or modulo by zero
PYTHON PROGRAMMING 141
EXCEPTIONStry:
◦ (statements)
except(ValueError)
PYTHON PROGRAMMING 142
EXCEPTIONSimport sys
try:
f = open('myfile.txt')
s = f.readline()
i = int(s.strip())
except IOError as e:
print "I/O error({0}): {1}".format(e.errno, e.strerror)
except ValueError:
print "Could not convert data to an integer."
except:
print "Unexpected error:", sys.exc_info()[0]
raise
PYTHON PROGRAMMING 143
OOP
PYTHON PROGRAMMING 144
OOP
PYTHON PROGRAMMING 145
CLASSESA class is just like a blueprint of a house.
An object is the actual house built from that blueprint.
You could then create numerous houses/objects from a single blueprint.
PYTHON PROGRAMMING 146
CLASSclass ClassName:
<statement-1>
.
.
.
<statement-N>
PYTHON PROGRAMMING 147
CLASS Example
PYTHON PROGRAMMING 148
class A:
def __init__(self):
pass
def somefunc(self, y):
x=4
c=x+y
print c
b= A()
A.somefunc(b,4) #Classname.method(object, variables)
PYTHON PROGRAMMING 149
THANK YOU
PYTHON PROGRAMMING 150