Function in python with example:
A function in Python is a block of code that performs a specific task and can be called and reused multiple times throughout a program. Functions help in breaking down a program into smaller, manageable and reusable parts, making code easier to read, understand and maintain.
In Python, a function is defined using the "def" keyword followed by the function name and a set of parentheses containing zero or more parameters. The function body is indented below the function definition.
Here's an example of a simple Python function that takes two arguments and returns their sum:
def add_numbers(a, b):
return a + b
Once this function is defined, it can be called by using its name and passing in the required arguments:
result = add_numbers(5, 7)
print(result)
# Output: 12
In this example, the add_numbers function takes two arguments a and b and returns their sum using the return statement. The function is called with the arguments 5 and 7, and the returned value is stored in the result variable.
Another Example of Function
def calculate_average(numbers):
total = sum(numbers)
count = len(numbers)
if count == 0:
return 0
else:
return total / count
In this example, the calculate_average function takes a list of numbers as its argument, calculates the average of the numbers, and returns the result. The function first calculates the sum of the numbers using the built-in sum function, and then calculates the length of the list using the built-in len function. If the list is empty, the function returns 0 to avoid a division by zero error. Otherwise, the function returns the average of the numbers by dividing the total by the count.
Here's an example of calling this function with a list of numbers:
numbers = [3, 6, 9, 12, 15]
average = calculate_average(numbers)
print(average)
# Output: 9.0
In this example, the numbers list contains five numbers, and the calculate_average function is called with this list as its argument. The returned value of 9.0 is then stored in the average variable.
#Function properties:
#1)A Function can be called for multiple times
def display():
"""function to display a msg"""
print("Hello....")
print("Good Evening!!!!")
display()
display()
display()
Advantage of functions: Code-reusability
#2) The order in which the functions are defined and the order in which they are called
# need not be the same
def English():
print("ABCDEFGHIJ.........")
def Maths():
print("123456789.........")
def chemistry():
print("H2O is the chemical name of water")
Maths()
chemistry()
English()
Maths()
#3) A Function can call another function
def hyd():
print("Hello hyd.....!!!!")
mumbai()
def mumbai():
print("Hello mumbai...!!!")
hyd()
#4) we cannot make function call before the function definition
display1()
display2()
def display1():
print("Hello")
def show():
print("Good Evening!!!")
#5)Defining a function in another function
def compute():
print("Hello India!!!")
def show():
print("Hello world!!!")
show()
compute()