Featured
- Get link
- X
- Other Apps
Function
Function is common to all programming language. A function is a block of organized code that we implement when we want over and over again at different places. Fuction is reusable. Instead of writing large code again and again we can use function
They make our code more modular and increase the reusability
There are two types of functions:
1) builtin function
2) user defined function
Builtin function:
Builtin function are function which are already present in python where we can use it but cannot over write or modify it. Function like print(), min(), max() etc..
User defined function:
User defined function are function provided or created by users in order to solve there problem or for the user requirements
Rules to define a function in python:
1. Every function block begin with the keyword def followed by the function name and parentheses()
2. Input parameters (argument) through which we pass values to a function are defined inside these parameters
3. A colon(:) is used to make the end of function header
4. Optional documentation string(docstring) to describe what the function does
5. One or more valid python statement make up the function body and all statemymust have same indentation level
6. An optional return statement to return a value from the function
example:
Fuction:
print("hello")
hello()
Output: hello
Function with parameters:
print (num1+num2)
print_sum(20,30)
Print_sum(10,20)
30
Function with default parameters:
print(text)
say("hello tech Language")
Output: hello tech Language
Function with variable parameters:
We use *(asterik) symbol for many variables
result=0
for x in number:
result=result+x
print(result)
print("sum of given variables are:")
print_sum(10,20,30,40)
Output: sum of given variables are:
100
Function arguments:
Following types of formal argument are used in python:
1) Required arguments
2) keyword arguments
3) Default arguments
4) Arbitrary arguments
Arguments are nothing but value we pass through function
->In required arguments function parameters value and argument value should be same or else it shows error,let look into it
Print(str,num1)
return;
print("hi",10)
print(10,"hi")
print(10) // error
Output: TypeError: my_print() takes exactly 2 argument (1 given)
In above example the error occurred because in last print statement only one argument is given but here the function take 2 argument
->In keyword arguments the caller identifies the argument by parameter name. It allows skipping argument or placing them out of order because the python interpreter usees keywords to match the values with parameters
->default and Arbitrary arguments you can see above. Arbitrary argument is nothing but using many variables (*)
If you have any doubt feel free to comment in comment box
- Get link
- X
- Other Apps
Comments
Post a Comment