Functions
'''
A function is a block of code that performs a specific task whenever it is called. They may help in making programs more organized, modular, and easier to maintain.
Let's say we have to perform a block of 50 codes for many times. Then, we have to write or copy-paste the block of codes many times. To avoid such a thing, we will define and rename the block of 50 codes and use that renamed function with different variables as much as we want. This will lessen the amount of mistakes and make our code smaller.
There are two types of functions:
1. Built-in Functions
2. User-defined Functions
Built-in Functions:
These functions are defined and pre-coded in Python.
Examples:
min(), max(), len(), sum(), type(), range(), dict(), list(), tuple(), set(), print(), etc.
User-defined Functions:
We can create functions to perform specific tasks as per our needs.
'''
#Example:
'''
Let's say we need to find geometric mean of two numbers. The most beginner-friendly way is to type the code for a pair of number and then copy the code and replace the variables for another pair.
'''
a = 9
b = 24
gmean = (a*b) / (a+b)
print("The geometric mean of", a, "and", b, "is", gmean)
#output = The geometric mean of 9 and 24 is 6.545454545454546
c = 10
d = 28
gmean = (c*d) / (c+d)
print("The geometric mean of", c, "and", d, "is", gmean)
#output = The geometric mean of 10 and 28 is 7.368421052631579
#If we have to find the geometric mean of multiple such numbers, we have to define gmean for each such case and print that.
# Therefore, we make a block of code for defining the function and then apply that block of code for all the next cases without any hassle.
def gmean(a, b):
gmean = (a*b) / (a+b)
print("The geometric mean of", a, "and", b, "is", gmean)
x = 5
y = 10
gmean(x, y)
#output = The geometric mean of 5 and 10 is 3.3333333333333335
num1 = 100
num2 = 500
gmean(num1, num2)
#output = The geometric mean of 100 and 500 is 83.33333333333333
num3 = 56848
num4 = 476314
gmean(num3, num4)
#output = The geometric mean of 56848 and 476314 is 50786.624463108776
# Here, we defined the gmean function with a, b parameters which means it will take 2 parameters. In the body of the function, we define gmean and the optional print statement. Now, by simply putting gmean(number1, number2) the code will refer to the "def gmean" block of code and that will be executed.
def isGreater(a, b):
if(a>b):
print("First number is greater")
else:
print("Second number is greater or equal")
x1 = 11
y1 = 12
isGreater(x1, y1)
#output = Second number is greater or equal
x2 = 12345
y2 = 6789
isGreater(x2, y2)
#output = First number is greater
Comments
Post a Comment