Till now we have seen that in order to use a block of code in different sections of our programme , we'll need to basically re-write the whole code . This is where the role of a function comes into play . Functions are basically a block of code that performs some operation and returns the result wherever it is called. So instead of writing a particular block of code multiple times , simply using a function is a much better alternative.
The components of a function are explained below.
Let us take a simple example where our function prints "hello world". To call a function ,remember to write the function name along with parenthesis.
def py4u():
print("hello world")
py4u() # calling a function
hello world
Let us take an example where we use the return statement in a function.
def py4u():
return 20
my_var = py4u()
print(3*my_var)
60
Most of the times , some arguments will be passed to the function and the function will use these parameters to perform some operation. Let us see this with help of an example.
In the example given below , the function is given a name and it returns a concatinated statement - 'hello! ' + name .
def py4u(name):
return 'hello! '+name
print(py4u('jack'))
hello! jack
Let us take an example where we pass in 2 numbers to a function and it returns its product.
def py4u(num1,num2):
return num1 * num2
print(py4u(10,20))
200
A parameter can also be assigned a default value , meaning when no value is passed to this parameter , its default value is used.In the code below , i have set the the value of num2 = 20 .
def py4u(num1,num2=20):
return num1 * num2
print(py4u(20))
400
def py4u(num1=20,num2):
return num1 * num2
print(py4u(20))