Download as pdf or txt
Download as pdf or txt
You are on page 1of 7

Programming using Python

Amey Karkare
Dept. of CSE
IIT Kanpur

For any queries reach out to rahulgr@iitk.ac.in or rahulgarg@robustresults.com


or whatsapp 9910043510

1
Python Programming
f(unctions)
2

Programming, Functions
A Modern Smartphone
• Surf the net
• Input: Web address
• Output: Desired page
• Book tickets
• Input: userid, password, booking info,
bank info
• Output: Ticket
• Send email
• Input: email address of receiver, mail
text
• Output: --
• Take photos
• Input: --
• Output: Picture
• Talk (we can do that too!!)
• Input: Phone number
• Output: Conversation (if lucky)
• …
3

Programming, Functions
How to tackle lots of related/unrelated tasks

• Divide and Conquer


– Create well defined sub tasks
– Work on each task independently
• Development, Enhancements, Debugging
• Reuse of tasks.
– Email and Chat apps can share spell checker.
– Phone and SMS apps can share dialer
• Python facilitates this using Functions
4

Programming, Functions
Function
• An independent, self-contained entity of a program
that performs a well-defined task.
• It has
– Name: for identification
– Arguments: to pass information from outside world (rest
of the program)
– Body: processes the arguments do something useful
– Return value: To communicate back to outside world
• Sometimes not required

Programming, Functions
Why use functions?
Example : Maximum of 3 numbers
#... code to read a, b, c def max(a, b):
if (a>b): '''return max of a and b'''
if (a>c): if (a>b):
m=a return a
else: else:
m=c return b
else:
if (b>c): #... code to read a, b, c
m=b m = max(a, b)
else: m = max(m, c)
m=c # print or use m
# print or use m
What if we want to find max of a This code can be updated easily to
large number of inputs (e.g.: max of 6 numbers!) handle large number of inputs
6

Programming, Functions
Why use functions?
• Break up complex problem into small sub-
problems.
• Solve each of the sub-problems separately as a
function, and combine them together in
another function.
• One of the main tools in Python for modular
programming.
• Hide the details: Abstraction.
7

Programming, Functions

You might also like