Function In Python For Data Science
- Functions ():
What do you understand by functions ?
- It performs a predefined task or a formula
- functions take some value as input and generates
some value as output
- input -> function -> output
- it is used to reduce our effort when performing same
task again and again
- y = f(x) where f(x) = sin(x)
- Function definition - Here we create a function
- function call - Here we use the function. It works only when a function is already defined
- Function definition
def <function_name>(object1, object2, ...):
statement_1
statement_2
...
return object
- Example - Add two numbers
def add_numbers(x, y):
s = x + y
return s
a = 5
b = 10
print add_numbers(a, b)
Key concepts related to function definition and arguments
- More/less number of inputs to a function than the number of inputs in the function definition
def f1(v1, v2, v3):
.
.
return output
out = f1(5, 10) # Error - less number of inputs, 3 required, 2 given
out = f1(5, 10, 15) # No error
out = f1(5, 10, 15, 20) # Error - More inputs. 3 required, 4 given
- Named arguments as input
out = f1(v1 = 5, 10, 15)
out = f1(v1 = 5, v2 = 10, 15)
out = f1(v1 = 5, v2 = 10, v3 = 15)
out = f1(v2 = 5, v3 = 10, v1 = 15)
You can input the value of variables by using the name of the variable used in function definition
- Default arguments
def f1(v1, v2, v3=20):
.
.
return output
out = f1(5, 10) # No Error. The value of v3 is taken as 20
out = f1(5, 10, 15) # No error. The value of v3 is now 15
- Function without return statement
def add_numbers(a, b):
print a+b
add_numbers(5, 10) # This will works
out = add_numbers(5, 10) # This also works, however, the out now contains "None" value
Comments
Post a Comment