Successfully reported this slideshow.
We use your LinkedIn profile and activity data to personalize ads and to show you more relevant ads. You can change your ad preferences anytime.

Python programming Workshop SITTTR - Kalamassery

3,348 views

Published on

For polytechnic college lectures

Published in: Education
  • Login to see the comments

Python programming Workshop SITTTR - Kalamassery

  1. 1. PYTHON PROGRAMMING RIYAZ P A Email : riyazaahil@gmail.com
  2. 2. TODAY’S CLASS • Introduction • What is Python ? • Why Python ? • Features • Basics of Python • Syntax • Import • Input Functions • Output Functions PYTHON PROGRAMMING 2
  3. 3. WHAT IS PYTHON ? PYTHON PROGRAMMING 3  Python is a widely used general-purpose, high-level programming language.  Python is simple and powerful language
  4. 4. WHY PYTHON ? PYTHON PROGRAMMING 4
  5. 5. 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
  6. 6. FEATURES PYTHON PROGRAMMING 6  Simple  Free and Open Source  Powerful  Object Oriented  Dynamic, strongly typed scripting language  Portable  Interpreted
  7. 7. FEATURES PYTHON PROGRAMMING 7  Embeddable  Extensive Libraries  Scalable Extensible
  8. 8. CAN DO  Text Handling  System Administration  GUI programming  Web Applications  DatabaseApps  Scientific Applications  Games  NLP  ImageProcessing  IoT and lot more ….. PYTHON PROGRAMMING 8
  9. 9. ZEN OF PYTHON PYTHON PROGRAMMING 9
  10. 10. PYTHON PROGRAMMING 10
  11. 11. WHO USES PYTHON ? PYTHON PROGRAMMING 11
  12. 12. RELEASES PYTHON PROGRAMMING 12  Createdin 1989 by Guido Van Rossum  Python 1.0 releasedin 1994  Python 2.0 releasedin 2000  Python 3.0 releasedin 2008  Python 2.7 is the recommendedversion  3.0 adoption will take a fewyears
  13. 13. HELLO WORLD hello_world.py print('Hello, World!') PYTHON PROGRAMMING 13
  14. 14. PYTHON 2 vs PYTHON 3  print ('Python‘) print 'Hello, World!'  print('Hello, World!')  In python 3 second statementwill show an error File "", line 1  print 'Hello, World!'  ^ SyntaxError: invalid syntax PYTHON PROGRAMMING 14
  15. 15. SAVING PYTHON PROGRAMS  PYTHON PROGRAMMING 15
  16. 16. COMMENTS #Hello ‘’’ Hai hello ‘’’ PYTHON PROGRAMMING 16
  17. 17. 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
  18. 18. IMPORT >>> import math >>> math.pi 3.141592653589793 >>> from math import pi >>> pi 3.141592653589793 PYTHON PROGRAMMING 18
  19. 19. 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:Python33Libidlelib',  'C:Windowssystem32python33.zip',  'C:Python33DLLs',  'C:Python33lib',  'C:Python33',  'C:Python33libsite-packages'] PYTHON PROGRAMMING 19
  20. 20. 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
  21. 21. FOR PYTHON 2  from __future__ import print_function  Type this in first line to avoid errors if you use python 2. PYTHON PROGRAMMING 21
  22. 22. 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
  23. 23. 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
  24. 24. 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
  25. 25. 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
  26. 26. OUTPUT FORMATTING We 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
  27. 27. 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
  28. 28. INPUT Python 3 Syntax input([prompt]) >>> num = input('Enter a number: ') Enter a number: 10 >>> num '10' PYTHON PROGRAMMING 28
  29. 29. INPUT Here, 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
  30. 30. 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
  31. 31. 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
  32. 32. 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))
  33. 33. KEYWORDS PYTHON PROGRAMMING 33
  34. 34. DATA TYPES  Strings  Numbers  Null  Lists  Dictionaries  Booleans PYTHON PROGRAMMING 34
  35. 35. Strings PYTHON PROGRAMMING 35
  36. 36. Numbers PYTHON PROGRAMMING 36
  37. 37. Null PYTHON PROGRAMMING 37
  38. 38. Lists PYTHON PROGRAMMING 38
  39. 39. Lists PYTHON PROGRAMMING 39
  40. 40. Dictionaries PYTHON PROGRAMMING 40
  41. 41. Dictionary Methods PYTHON PROGRAMMING 41
  42. 42. Booleans PYTHON PROGRAMMING 42
  43. 43. 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
  44. 44. 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
  45. 45. OPERATORS  Arithmetic  String Manipulation  Logical Comparison  Identity Comparison  Arithmetic Comparison PYTHON PROGRAMMING 45
  46. 46. Arithmetic PYTHON PROGRAMMING 46
  47. 47. String Manipulation PYTHON PROGRAMMING 47
  48. 48. Logical Comparison PYTHON PROGRAMMING 48
  49. 49. Identity Comparison PYTHON PROGRAMMING 49
  50. 50. Arithmetic Comparison PYTHON PROGRAMMING 50
  51. 51. 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)
  52. 52. PYTHON PROGRAMMING 52
  53. 53. PYTHON PROGRAMMING 53
  54. 54. PYTHON PROGRAMMING 54
  55. 55. PYTHON PROGRAMMING 55
  56. 56. Avoid next line in print Python 2.x Print ”hai”, Print ”hello” Python 3.x Print (‘hai’, end=‘’) Print(‘hello’) PYTHON PROGRAMMING 56
  57. 57. TODAY’S CLASS • Intendation • Decision Making • Control Statements PYTHON PROGRAMMING 57
  58. 58. INDENTATION  Most languages don’t care about indentation  Most humans do  Python tend to group similar things together PYTHON PROGRAMMING 58
  59. 59. INDENTATION The else here actually belongs to the 2nd if statement PYTHON PROGRAMMING 59
  60. 60. INDENTATION The else here actually belongs to the 2nd if statement PYTHON PROGRAMMING 60
  61. 61. INDENTATION I knew a coder like this PYTHON PROGRAMMING 61
  62. 62. INDENTATION You should always be explicit PYTHON PROGRAMMING 62
  63. 63. INDENTATION Python embraces indentation PYTHON PROGRAMMING 63
  64. 64. 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
  65. 65. DECISION MAKING PYTHON PROGRAMMING 65
  66. 66. DECISION STATEMENTS  If  If Else  If Elif  Nested If PYTHON PROGRAMMING 66
  67. 67. 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“)
  68. 68. IF ELSE : ODD OR EVEN PYTHON PROGRAMMING 68 num=input("number") if num%2==0: print (num,'is Even‘) else: print (num,'is Odd‘)
  69. 69. 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‘)
  70. 70. 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')
  71. 71. 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)
  72. 72. 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
  73. 73. QUADRATIC EQUATION … elif delta==0: x=-b/(2.0*a) y=x print 'roots are Equal' print 'roots aren {} n {}'.format(x,y) else: print 'imaginary' #delta=-delta sqi=cmath.sqrt(delta) x=-b/(2.0*a) #print x print 'roots are n {0} + {1} j n {0} - {1} j '.format(x,sqi.imag) #print sqi.imag PYTHON PROGRAMMING 73
  74. 74. LOOPS  For  While  While else  While Infinite Loop  While with condition at top, middle and bottom PYTHON PROGRAMMING 74
  75. 75. FOR PYTHON PROGRAMMING 75 sum=0 for i in range(11): print i sum+=i print ('sum=',sum)
  76. 76. FOR PYTHON PROGRAMMING 76 start=input('Enter start') stop=input('stop') stepindex=input('step') for i in range(start,stop+1,stepindex): print (i)
  77. 77. 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 ('nnn') num2=[] for i in num: if i%2==0: num2.append(i) print (num2)
  78. 78. 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)
  79. 79. 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‘)
  80. 80. CONTINUE PYTHON PROGRAMMING 80 num=[] for i in range(100,1000): if i%7==0: continue num.append(i) print (num)
  81. 81. PASS PYTHON PROGRAMMING 81 num=[] for i in range(100,1000): pass For empty for loop, function and class , you need to use pass
  82. 82. 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)
  83. 83. WHILE ELSE PYTHON PROGRAMMING 83 count=0 while count<3: print 'inside loop' count+=1 else: print 'outside loop'
  84. 84. INFINITE LOOP PYTHON PROGRAMMING 84 i=1 # Use Ctrl+C to exit the loop. #Do it carefully while True: print i i=i+1
  85. 85. 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')
  86. 86. MULTIPLICATION TABLE PYTHON PROGRAMMING 86 num=input('Enter Number: ') i=1 while i<11: print ('{} * {} = {}'.format(i,num,num*i)) i+=1
  87. 87. MULTIPLICATION TABLE PYTHON PROGRAMMING 87 num=input('Enter Number: ') for i in range(1,21): print ('{} * {} = {}'.format(i,num,num*i))
  88. 88. 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))
  89. 89. 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))
  90. 90. 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)
  91. 91. 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)
  92. 92. 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‘)
  93. 93. ANTIGRAVITY Import antigravity PYTHON PROGRAMMING 93
  94. 94. TODAY’S CLASS • Functions • Namespace • Name Binding • Modules • Packages PYTHON PROGRAMMING 94
  95. 95. TARGET SCENARIO PYTHON PROGRAMMING 95
  96. 96. BUILDING BLOCKS PYTHON PROGRAMMING 96
  97. 97. DIVISION OF LABOUR PYTHON PROGRAMMING 97
  98. 98. DIVISION OF LABOUR PYTHON PROGRAMMING 98
  99. 99. ASSEMBLY LINE PYTHON PROGRAMMING 99
  100. 100. DIVIDE AND CONQUER PYTHON PROGRAMMING 100
  101. 101. DIVIDE AND CONQUER every problem can be broken down into smaller/more manageablesub- 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
  102. 102. PYTHON PROGRAM COMPONENTS  functions classes modules  collectionof functions& classes packages  collectionof modules PYTHON PROGRAMMING 102
  103. 103. PYTHON PROGRAM COMPONENTS PYTHON PROGRAMMING 103 Package Module Function Class
  104. 104. FUNCTIONS collection or block of statements that you can execute whenever and wherever you want in the program PYTHON PROGRAMMING 104
  105. 105. FUNCTIONS PYTHON PROGRAMMING 105
  106. 106. FUNCTIONS PYTHON PROGRAMMING 106
  107. 107. WHY FUNCTIONS  avoids duplicating code snippets  saves typing  easier to change the program later PYTHON PROGRAMMING 107
  108. 108. FUNCTIONS def function_name(parameters): """docstring""" statement(s) PYTHON PROGRAMMING 108
  109. 109. USER DEFINED FUNCTIONS PYTHON PROGRAMMING 109
  110. 110. USER DEFINED FUNCTIONS PYTHON PROGRAMMING 110
  111. 111. RETURN KEYWORD PYTHON PROGRAMMING 111
  112. 112. VARIABLE SCOPE PYTHON PROGRAMMING 112 x = “Rahul” def kerala(): x =“Suresh” print (x) kerala() print x
  113. 113. PYTHON FUNCTIONS (PARAMS vs ARGS)  PYTHON PROGRAMMING 113 Function Parameters Function Arguments
  114. 114. 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
  115. 115. REQUIRED ARGUMENTS  PYTHON PROGRAMMING 115 Required/MandatoryArguments passed to a function in correct positionalorder def sum(x,y): return x+y print sum(2, 3)
  116. 116. 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)
  117. 117. 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)
  118. 118. VARIABLE ARGUMENTS  PYTHON PROGRAMMING 118 can handleno-argument, 1-argument, or many-argumentsfunction calls def sum(*addends): total=0 for i in addends: total+=i return total print sum() print sum(2) print sum(2,3) print sum(2,3,4)
  119. 119. TRY IT OUT  Program to find the sum of digits PYTHON PROGRAMMING 119
  120. 120. FIBONACCI # Fibonacci numbers module def fib(n): # write Fibonacci series up to n a, b = 0, 1 while b < n: print b, a, b = b, a+b def fib2(n): # return Fibonacci series up to n result = [] a, b = 0, 1 while b < n: result.append(b) a, b = b, a+b return result PYTHON PROGRAMMING 120
  121. 121. SUM_AB FUNCTION PYTHON PROGRAMMING 121 def sumab(a,b): sum=0 for i in range(a,b+1): sum=sum+i return sum
  122. 122. 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
  123. 123. 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 "nn" # 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
  124. 124. MATRIX… # Main pgm r=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
  125. 125. NAMESPACES refers 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
  126. 126. NAMESPACES import math print dir() PYTHON PROGRAMMING 126
  127. 127. NAMESPACES import math, random print dir() PYTHON PROGRAMMING 127
  128. 128. FROM NAMESPACES IMPORTING FUNCTIONS from math import sin, cos, tan print dir() PYTHON PROGRAMMING 128
  129. 129. NAME BINDING Import math as m print m.sqrt() from math import sqrt as s print s(2) PYTHON PROGRAMMING 129
  130. 130. Handling Modules #Create demo.py import my_module #Create my_module.py Print(“Entering My Module”) Print(“Exiting My Module”) PYTHON PROGRAMMING 130
  131. 131. PYTHON PROGRAMMING 131 * groups related modules * code calling in several locations * prevents name collision
  132. 132. HANDLING PACKAGES PYTHON PROGRAMMING 132
  133. 133. HANDLING OF PACKAGES The __init__.py files are required to make Python treat the directories as containing packages PYTHON PROGRAMMING 133
  134. 134. HANDLING OF PACKAGES: WILL NOT WORK PYTHON PROGRAMMING 134
  135. 135. HANDLING OF PACKAGES: WILL WORK PYTHON PROGRAMMING 135
  136. 136. HANDLING OF PACKAGES: WILL WORK PYTHON PROGRAMMING 136
  137. 137. HANDLING OF PACKAGES: WILL WORK PYTHON PROGRAMMING 137
  138. 138. SUMMARY IMPORTATION INVOCATION importp1.p2.m p1.p2.m.f1() from p1.p2 importm m.f1() fromp1.p2.m import f1 f1() PYTHON PROGRAMMING 138
  139. 139. PYTHON PROGRAMMING 139 Divide-and-Conquer is Powerful!
  140. 140. 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
  141. 141. EXCEPTIONS Even if a statementor expression is syntactically correct, it may cause an error when an attemptis 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
  142. 142. EXCEPTIONS try: ◦ (statements) except(ValueError) PYTHON PROGRAMMING 142
  143. 143. EXCEPTIONS import 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
  144. 144. OOP PYTHON PROGRAMMING 144
  145. 145. OOP PYTHON PROGRAMMING 145
  146. 146. CLASSES A 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
  147. 147. CLASS class ClassName: <statement-1> . . . <statement-N> PYTHON PROGRAMMING 147
  148. 148. 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)
  149. 149. riyazaahil@gmail.com PYTHON PROGRAMMING 149
  150. 150. THANK YOU PYTHON PROGRAMMING 150

×