When we are working with big project, those project will be divide into modules and again module will be cut down into units, these units are called tasks. Every tasks contains the functions. Functions means collection of statements which performs a specific tasks, and these task are reusable
We have seen many functions like: print(), range(),....if you look into print()..its functionality is to print message on the screen, range() does...The range() function is used to generate a sequence of numbers over time. At its simplest, it accepts an integer and returns a range object (a type of iterable). In Python 2, the range() returns a list which is not very efficient to handle large data. (optional) Starting point of the sequence.
There are two steps to be followed for designing:
Function definition
Function call
1. Function definition:
Def function_name():
….
(i.) How system understands the it is function name, by seeing the parenthesis.
(ii.) : (colon) which indicates that function contains the multiple statements
Example for step 1:
def Fun():
print(“Hello”)
print(“How are you”)
To execute the above my function, we should call explicitly:
By giving the name of the function
Fun()
For suppose after some time I want to print the same output, then no need to write again, i can reuse the code by calling the function.
A function not only perform task, it also returns the value if we want.
Example 2: Reusability:
Case 1: I have defined a function, its functionality is to find the largest number
#File max.py
def max(a,b,c):
lar=a #assume that a is the largest number
if b>lar:#if b is greater than lar
lar=b #b is the largest
if c>lar:#if c is greater value
lar=c
return(lar)
Case2: Go to other file in the same folder, you can reuse
Filename: 2.py
a=int(input("enter any value"))
b=int(input("enter b value"))
c=int(input("enter c value"))
lar=max(a,b,c)
print(lar)
"""
enter any value2
enter b value3
enter c value4
4
"""
Case 3: if I want to find out the largest of 3 values:
Function call is ans1=max(a,b,c)
If I want to find the largest of 6 values, I have to call 3 times
Function call is
ans1=max(a,b,c)
ans2=max(d,e,f)
ans3=max(ans1,ans2)
If i want to find the largest of 9 values, i have to call 4 times
ans1=max(a,b,c)
ans2=max(d,e,f)
ans3=max(g,h,i)
ans4=max(ans1,ans2,ans3)
Example:
Now I want to find out the largest of 9 values:
Then no need to define again, just we need to call 4 times:
#To find the largest of 9 values.
#we can reuse the max() in the same directory
ans1=max(10,20,30)
ans2=max(40,50,70)
ans3=max(90,2,35)
ans4=max(ans1,ans2,ans3)
print(ans4)
"""
90
"""
For example, in future if you want to modify the code, just c
When you start working on any project, these functions are very important. It is always a good programming if you want to write a function better write specific for that.
See the related video: https://youtu.be/Gdx870Q6FjM
Next: Function call
No comments:
Post a Comment