Module 5
Functions in
Python
MLO:
● Understand Functions In Programming
● Know The Different Types Of Functions In Python
● Use The def Keyword To Define Functions.
keywords:
● def keyword
● Built -in
functions-input(),int(),pow()
,max(),min(),print(),
● str(),type(),round(),range()
● User defined functions
● Parameters
● arguments
#functions without parameters
def greet():
print("Welcome to programming")
greet()
#functions with parameters
def greet(n):
print("Good morning",n)
n=input("Enter your name")
greet(n)
#function to add 2 numbers
def add(a,b):
print("Sum = ",a+b)
a=int(input("Enter the first number "))
b=int(input("Enter the second number "))
add(a,b)
# program to create a menu-driven
calculator
def add():
a=int(input("Enter the first number "))
b=int(input("Enter the second number "))
print("Sum = ",a+b)
def subtract():
a=int(input("Enter the first number "))
b=int(input("Enter the second number "))
print("Difference = ",a-b)
def multiply():
a=int(input("Enter the first number "))
b=int(input("Enter the second number "))
print("Product = ",a*b)
def divide():
a=int(input("Enter the first number "))
b=int(input("Enter the second number "))
print("Quotient = ",a/b)
print("Remainder = ",a%b)
ch=int(input("1. Add\[Link]\[Link]\[Link]\nEnter your choice"))
if ch==1:
add()
elif ch==2:
subtract()
elif ch==3:
multiply()
elif ch==4:
divide()
else:
print("invalid input")
A function is an organized and reusable block of code used to perform a
specific task.
Functions provide better modularity for your application with a high degree of
code reuse.
It helps to break your program into smaller and modular chunks. As your
program grows larger and larger, functions make it more organized and
manageable.
Advantages:
● Splits code into simple modules.
● Eliminates duplication of code.
● Code reuse.
● Provides better structure for the programming.
● Makes editing and debugging easier.
● Different functions can be developed independently according to needs.
2. Functions that come built into the Python language itself are called built-in
functions,and are readily available to us.
for eg:
● input( )-Reads a line from the input,
● int( )- Converts a number or string into an integer.
● range( )- Returns an iterable sequence.
On the other hand, functions created by users to perform certain specific task
are referred to as user-defined functions.
eg:
def my_addition(x,y):
sum = x + y
return sum
. BUILT-IN FUNCTIONS IN PYTHON:
1. input( )-Reads a line from the input,
2. int( )- Converts a number or string into an integer.
3. range( )- Returns an iterable sequence.
4. pow()- returns the power of a number raised to a number
5. print()- prints object to the stream
6. max()- return the largest number in an iterable
7. min()-returns the smallest number in an iterable
8. str()- return the string version
9. type()- returns the type of the object/variable
10. round()- returns the rounded floating point value
11. len()-returns the length of an object.