150
PYTHON PROGRAMMING RIYAZ P A Email : [email protected]

Python programming Workshop SITTTR - Kalamassery

Embed Size (px)

Citation preview

Page 1: Python programming Workshop SITTTR - Kalamassery

PYTHON PROGRAMMING

RIYAZ P AEmail : [email protected]

Page 2: Python programming Workshop SITTTR - Kalamassery

TODAY’S CLASS• Introduction• What is Python ?

• Why Python ?

• Features

• Basics of Python

• Syntax

• Import

• Input Functions

• Output Functions

PYTHON PROGRAMMING 2

Page 3: Python programming Workshop SITTTR - Kalamassery

WHAT IS PYTHON ?

PYTHON PROGRAMMING 3

Python is a widely used general-purpose, high-level programming language.

Python is simple and powerful language

Page 4: Python programming Workshop SITTTR - Kalamassery

WHY PYTHON ?

PYTHON PROGRAMMING 4

Page 5: Python programming Workshop SITTTR - Kalamassery

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

Page 6: Python programming Workshop SITTTR - Kalamassery

FEATURES

PYTHON PROGRAMMING 6

Simple

Free and Open Source

Powerful

Object Oriented

Dynamic, strongly typed scripting language

Portable

Interpreted

Page 7: Python programming Workshop SITTTR - Kalamassery

FEATURES

PYTHON PROGRAMMING 7

Embeddable

Extensive Libraries

Scalable

Extensible

Page 8: Python programming Workshop SITTTR - Kalamassery

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

Page 9: Python programming Workshop SITTTR - Kalamassery

ZEN OF PYTHON

PYTHON PROGRAMMING 9

Page 10: Python programming Workshop SITTTR - Kalamassery

PYTHON PROGRAMMING 10

Page 11: Python programming Workshop SITTTR - Kalamassery

WHO USES PYTHON ?

PYTHON PROGRAMMING 11

Page 12: Python programming Workshop SITTTR - Kalamassery

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

Page 13: Python programming Workshop SITTTR - Kalamassery

HELLO WORLD

hello_world.py

print('Hello, World!')

PYTHON PROGRAMMING 13

Page 14: Python programming Workshop SITTTR - Kalamassery

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

Page 15: Python programming Workshop SITTTR - Kalamassery

SAVING PYTHON PROGRAMS

PYTHON PROGRAMMING 15

Page 16: Python programming Workshop SITTTR - Kalamassery

COMMENTS

#Hello

‘’’ Hai

hello

‘’’

PYTHON PROGRAMMING 16

Page 17: Python programming Workshop SITTTR - Kalamassery

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

Page 18: Python programming Workshop SITTTR - Kalamassery

IMPORT

>>> import math

>>> math.pi

3.141592653589793

>>> from math import pi

>>> pi

3.141592653589793

PYTHON PROGRAMMING 18

Page 19: Python programming Workshop SITTTR - Kalamassery

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

Page 20: Python programming Workshop SITTTR - Kalamassery

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

Page 21: Python programming Workshop SITTTR - Kalamassery

FOR PYTHON 2 from __future__ import print_function Type this in first line to avoid errors if you use python 2.

PYTHON PROGRAMMING 21

Page 22: Python programming Workshop SITTTR - Kalamassery

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

Page 23: Python programming Workshop SITTTR - Kalamassery

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

Page 24: Python programming Workshop SITTTR - Kalamassery

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

Page 25: Python programming Workshop SITTTR - Kalamassery

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

Page 26: Python programming Workshop SITTTR - Kalamassery

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

Page 27: Python programming Workshop SITTTR - Kalamassery

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

Page 28: Python programming Workshop SITTTR - Kalamassery

INPUTPython 3

Syntax

input([prompt])

>>> num = input('Enter a number: ')

Enter a number: 10

>>> num

'10'

PYTHON PROGRAMMING 28

Page 29: Python programming Workshop SITTTR - Kalamassery

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

Page 30: Python programming Workshop SITTTR - Kalamassery

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

Page 31: Python programming Workshop SITTTR - Kalamassery

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

Page 32: Python programming Workshop SITTTR - Kalamassery

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

Page 33: Python programming Workshop SITTTR - Kalamassery

KEYWORDS

PYTHON PROGRAMMING 33

Page 34: Python programming Workshop SITTTR - Kalamassery

DATA TYPES Strings

Numbers

Null

Lists

Dictionaries

Booleans

PYTHON PROGRAMMING 34

Page 35: Python programming Workshop SITTTR - Kalamassery

Strings

PYTHON PROGRAMMING 35

Page 36: Python programming Workshop SITTTR - Kalamassery

Numbers

PYTHON PROGRAMMING 36

Page 37: Python programming Workshop SITTTR - Kalamassery

Null

PYTHON PROGRAMMING 37

Page 38: Python programming Workshop SITTTR - Kalamassery

Lists

PYTHON PROGRAMMING 38

Page 39: Python programming Workshop SITTTR - Kalamassery

Lists

PYTHON PROGRAMMING 39

Page 40: Python programming Workshop SITTTR - Kalamassery

Dictionaries

PYTHON PROGRAMMING 40

Page 41: Python programming Workshop SITTTR - Kalamassery

Dictionary Methods

PYTHON PROGRAMMING 41

Page 42: Python programming Workshop SITTTR - Kalamassery

Booleans

PYTHON PROGRAMMING 42

Page 43: Python programming Workshop SITTTR - Kalamassery

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

Page 44: Python programming Workshop SITTTR - Kalamassery

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

Page 45: Python programming Workshop SITTTR - Kalamassery

OPERATORS Arithmetic

String Manipulation

Logical Comparison

Identity Comparison

Arithmetic Comparison

PYTHON PROGRAMMING 45

Page 46: Python programming Workshop SITTTR - Kalamassery

Arithmetic

PYTHON PROGRAMMING 46

Page 47: Python programming Workshop SITTTR - Kalamassery

String Manipulation

PYTHON PROGRAMMING 47

Page 48: Python programming Workshop SITTTR - Kalamassery

Logical Comparison

PYTHON PROGRAMMING 48

Page 49: Python programming Workshop SITTTR - Kalamassery

Identity Comparison

PYTHON PROGRAMMING 49

Page 50: Python programming Workshop SITTTR - Kalamassery

Arithmetic Comparison

PYTHON PROGRAMMING 50

Page 51: Python programming Workshop SITTTR - Kalamassery

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)

Page 52: Python programming Workshop SITTTR - Kalamassery

PYTHON PROGRAMMING 52

Page 53: Python programming Workshop SITTTR - Kalamassery

PYTHON PROGRAMMING 53

Page 54: Python programming Workshop SITTTR - Kalamassery

PYTHON PROGRAMMING 54

Page 55: Python programming Workshop SITTTR - Kalamassery

PYTHON PROGRAMMING 55

Page 56: Python programming Workshop SITTTR - Kalamassery

Avoid next line in printPython 2.x

Print ”hai”,

Print ”hello”

Python 3.x

Print (‘hai’, end=‘’)

Print(‘hello’)

PYTHON PROGRAMMING 56

Page 57: Python programming Workshop SITTTR - Kalamassery

TODAY’S CLASS• Intendation

• Decision Making

• Control Statements

PYTHON PROGRAMMING 57

Page 58: Python programming Workshop SITTTR - Kalamassery

INDENTATION

Most languages don’t care about indentation

Most humans do

Python tend to group similar things together

PYTHON PROGRAMMING 58

Page 59: Python programming Workshop SITTTR - Kalamassery

INDENTATION

The else here actually belongs to the 2nd if statement

PYTHON PROGRAMMING 59

Page 60: Python programming Workshop SITTTR - Kalamassery

INDENTATION

The else here actually belongs to the 2nd if statement

PYTHON PROGRAMMING 60

Page 61: Python programming Workshop SITTTR - Kalamassery

INDENTATION

I knew a coder like this

PYTHON PROGRAMMING 61

Page 62: Python programming Workshop SITTTR - Kalamassery

INDENTATION

You should always be explicit

PYTHON PROGRAMMING 62

Page 63: Python programming Workshop SITTTR - Kalamassery

INDENTATION

Python embraces indentation

PYTHON PROGRAMMING 63

Page 64: Python programming Workshop SITTTR - Kalamassery

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

Page 65: Python programming Workshop SITTTR - Kalamassery

DECISION MAKING

PYTHON PROGRAMMING 65

Page 66: Python programming Workshop SITTTR - Kalamassery

DECISION STATEMENTS If

If Else

If Elif

Nested If

PYTHON PROGRAMMING 66

Page 67: Python programming Workshop SITTTR - Kalamassery

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

Page 68: Python programming Workshop SITTTR - Kalamassery

IF ELSE : ODD OR EVEN

PYTHON PROGRAMMING 68

num=input("number")

if num%2==0:

print (num,'is Even‘)

else:

print (num,'is Odd‘)

Page 69: Python programming Workshop SITTTR - Kalamassery

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

Page 70: Python programming Workshop SITTTR - Kalamassery

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

Page 71: Python programming Workshop SITTTR - Kalamassery

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)

Page 72: Python programming Workshop SITTTR - Kalamassery

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

Page 73: Python programming Workshop SITTTR - Kalamassery

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

Page 74: Python programming Workshop SITTTR - Kalamassery

LOOPS For

While

While else

While Infinite Loop

While with condition at top, middle and bottom

PYTHON PROGRAMMING 74

Page 75: Python programming Workshop SITTTR - Kalamassery

FOR

PYTHON PROGRAMMING 75

sum=0

for i in range(11):

print i

sum+=i

print ('sum=',sum)

Page 76: Python programming Workshop SITTTR - Kalamassery

FOR

PYTHON PROGRAMMING 76

start=input('Enter start')

stop=input('stop')

stepindex=input('step')

for i in range(start,stop+1,stepindex):

print (i)

Page 77: Python programming Workshop SITTTR - Kalamassery

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)

Page 78: Python programming Workshop SITTTR - Kalamassery

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)

Page 79: Python programming Workshop SITTTR - Kalamassery

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

Page 80: Python programming Workshop SITTTR - Kalamassery

CONTINUE

PYTHON PROGRAMMING 80

num=[]

for i in range(100,1000):

if i%7==0:

continue

num.append(i)

print (num)

Page 81: Python programming Workshop SITTTR - Kalamassery

PASS

PYTHON PROGRAMMING 81

num=[]

for i in range(100,1000):

pass

For empty for loop, function and class , you need to use pass

Page 82: Python programming Workshop SITTTR - Kalamassery

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)

Page 83: Python programming Workshop SITTTR - Kalamassery

WHILE ELSE

PYTHON PROGRAMMING 83

count=0

while count<3:

print 'inside loop'

count+=1

else:

print 'outside loop'

Page 84: Python programming Workshop SITTTR - Kalamassery

INFINITE LOOP

PYTHON PROGRAMMING 84

i=1 # Use Ctrl+C to exit the loop.

#Do it carefully

while True:

print i

i=i+1

Page 85: Python programming Workshop SITTTR - Kalamassery

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

Page 86: Python programming Workshop SITTTR - Kalamassery

MULTIPLICATION TABLE

PYTHON PROGRAMMING 86

num=input('Enter Number: ')

i=1

while i<11:

print ('{} * {} = {}'.format(i,num,num*i))

i+=1

Page 87: Python programming Workshop SITTTR - Kalamassery

MULTIPLICATION TABLE

PYTHON PROGRAMMING 87

num=input('Enter Number: ')

for i in range(1,21):

print ('{} * {} = {}'.format(i,num,num*i))

Page 88: Python programming Workshop SITTTR - Kalamassery

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

Page 89: Python programming Workshop SITTTR - Kalamassery

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

Page 90: Python programming Workshop SITTTR - Kalamassery

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)

Page 91: Python programming Workshop SITTTR - Kalamassery

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)

Page 92: Python programming Workshop SITTTR - Kalamassery

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

Page 93: Python programming Workshop SITTTR - Kalamassery

ANTIGRAVITYImport antigravity

PYTHON PROGRAMMING 93

Page 94: Python programming Workshop SITTTR - Kalamassery

TODAY’S CLASS• Functions

• Namespace

• Name Binding

• Modules

• Packages

PYTHON PROGRAMMING 94

Page 95: Python programming Workshop SITTTR - Kalamassery

TARGET SCENARIO

PYTHON PROGRAMMING 95

Page 96: Python programming Workshop SITTTR - Kalamassery

BUILDING BLOCKS

PYTHON PROGRAMMING 96

Page 97: Python programming Workshop SITTTR - Kalamassery

DIVISION OF LABOUR

PYTHON PROGRAMMING 97

Page 98: Python programming Workshop SITTTR - Kalamassery

DIVISION OF LABOUR

PYTHON PROGRAMMING 98

Page 99: Python programming Workshop SITTTR - Kalamassery

ASSEMBLY LINE

PYTHON PROGRAMMING 99

Page 100: Python programming Workshop SITTTR - Kalamassery

DIVIDE AND CONQUER

PYTHON PROGRAMMING 100

Page 101: Python programming Workshop SITTTR - Kalamassery

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

Page 102: Python programming Workshop SITTTR - Kalamassery

PYTHON PROGRAM COMPONENTS functions

classes

modules collection of functions & classes

packages collection of modules

PYTHON PROGRAMMING 102

Page 103: Python programming Workshop SITTTR - Kalamassery

PYTHON PROGRAM COMPONENTS

PYTHON PROGRAMMING 103

Package

Module

Function

Class

Page 104: Python programming Workshop SITTTR - Kalamassery

FUNCTIONScollection or block of statements that you can execute

whenever and wherever you want in the program

PYTHON PROGRAMMING 104

Page 105: Python programming Workshop SITTTR - Kalamassery

FUNCTIONS

PYTHON PROGRAMMING 105

Page 106: Python programming Workshop SITTTR - Kalamassery

FUNCTIONS

PYTHON PROGRAMMING 106

Page 107: Python programming Workshop SITTTR - Kalamassery

WHY FUNCTIONS avoids duplicating code snippets

saves typing

easier to change the program later

PYTHON PROGRAMMING 107

Page 108: Python programming Workshop SITTTR - Kalamassery

FUNCTIONSdef function_name(parameters):

"""docstring"""

statement(s)

PYTHON PROGRAMMING 108

Page 109: Python programming Workshop SITTTR - Kalamassery

USER DEFINED FUNCTIONS

PYTHON PROGRAMMING 109

Page 110: Python programming Workshop SITTTR - Kalamassery

USER DEFINED FUNCTIONS

PYTHON PROGRAMMING 110

Page 111: Python programming Workshop SITTTR - Kalamassery

RETURN KEYWORD

PYTHON PROGRAMMING 111

Page 112: Python programming Workshop SITTTR - Kalamassery

VARIABLE SCOPE

PYTHON PROGRAMMING 112

x = “Rahul”

def kerala():

x =“Suresh”

print (x)

kerala()

print x

Page 113: Python programming Workshop SITTTR - Kalamassery

PYTHON FUNCTIONS (PARAMS vs ARGS)

PYTHON PROGRAMMING 113

Function Parameters

Function Arguments

Page 114: Python programming Workshop SITTTR - Kalamassery

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

Page 115: Python programming Workshop SITTTR - Kalamassery

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)

Page 116: Python programming Workshop SITTTR - Kalamassery

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)

Page 117: Python programming Workshop SITTTR - Kalamassery

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)

Page 118: Python programming Workshop SITTTR - Kalamassery

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)

Page 119: Python programming Workshop SITTTR - Kalamassery

TRY IT OUT Program to find the sum of digits

PYTHON PROGRAMMING 119

Page 120: Python programming Workshop SITTTR - Kalamassery

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

Page 121: Python programming Workshop SITTTR - Kalamassery

SUM_AB FUNCTION

PYTHON PROGRAMMING 121

def sumab(a,b):

sum=0

for i in range(a,b+1):

sum=sum+i

return sum

Page 122: Python programming Workshop SITTTR - Kalamassery

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

Page 123: Python programming Workshop SITTTR - Kalamassery

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

Page 124: Python programming Workshop SITTTR - Kalamassery

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

Page 125: Python programming Workshop SITTTR - Kalamassery

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

Page 126: Python programming Workshop SITTTR - Kalamassery

NAMESPACESimport math

print dir()

PYTHON PROGRAMMING 126

Page 127: Python programming Workshop SITTTR - Kalamassery

NAMESPACESimport math, random

print dir()

PYTHON PROGRAMMING 127

Page 128: Python programming Workshop SITTTR - Kalamassery

FROM NAMESPACES IMPORTING FUNCTIONSfrom math import sin, cos, tan

print dir()

PYTHON PROGRAMMING 128

Page 129: Python programming Workshop SITTTR - Kalamassery

NAME BINDINGImport math as m

print m.sqrt()

from math import sqrt as s

print s(2)

PYTHON PROGRAMMING 129

Page 130: Python programming Workshop SITTTR - Kalamassery

Handling Modules#Create demo.py

import my_module

#Create my_module.py

Print(“Entering My Module”)

Print(“Exiting My Module”)

PYTHON PROGRAMMING 130

Page 131: Python programming Workshop SITTTR - Kalamassery

PYTHON PROGRAMMING 131

* groups related modules

* code calling in several locations

* prevents name collision

Page 132: Python programming Workshop SITTTR - Kalamassery

HANDLING PACKAGES

PYTHON PROGRAMMING 132

Page 133: Python programming Workshop SITTTR - Kalamassery

HANDLING OF PACKAGESThe __init__.py files are required to make Python treat the directories as containing packages

PYTHON PROGRAMMING 133

Page 134: Python programming Workshop SITTTR - Kalamassery

HANDLING OF PACKAGES: WILL NOT WORK

PYTHON PROGRAMMING 134

Page 135: Python programming Workshop SITTTR - Kalamassery

HANDLING OF PACKAGES: WILL WORK

PYTHON PROGRAMMING 135

Page 136: Python programming Workshop SITTTR - Kalamassery

HANDLING OF PACKAGES: WILL WORK

PYTHON PROGRAMMING 136

Page 137: Python programming Workshop SITTTR - Kalamassery

HANDLING OF PACKAGES: WILL WORK

PYTHON PROGRAMMING 137

Page 138: Python programming Workshop SITTTR - Kalamassery

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

Page 139: Python programming Workshop SITTTR - Kalamassery

PYTHON PROGRAMMING 139

Divide-and-Conquer is Powerful!

Page 140: Python programming Workshop SITTTR - Kalamassery

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

Page 141: Python programming Workshop SITTTR - Kalamassery

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

Page 142: Python programming Workshop SITTTR - Kalamassery

EXCEPTIONStry:

◦ (statements)

except(ValueError)

PYTHON PROGRAMMING 142

Page 143: Python programming Workshop SITTTR - Kalamassery

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

Page 144: Python programming Workshop SITTTR - Kalamassery

OOP

PYTHON PROGRAMMING 144

Page 145: Python programming Workshop SITTTR - Kalamassery

OOP

PYTHON PROGRAMMING 145

Page 146: Python programming Workshop SITTTR - Kalamassery

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

Page 147: Python programming Workshop SITTTR - Kalamassery

CLASSclass ClassName:

<statement-1>

.

.

.

<statement-N>

PYTHON PROGRAMMING 147

Page 148: Python programming Workshop SITTTR - Kalamassery

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)

Page 149: Python programming Workshop SITTTR - Kalamassery

[email protected]

PYTHON PROGRAMMING 149

Page 150: Python programming Workshop SITTTR - Kalamassery

THANK YOU

PYTHON PROGRAMMING 150