User-defined functions
User-defined functions
Python allows you to create your own functions. To do so first we need to define the name of the function using the 'def' keyword. Then we have to make a block of code that will run when we call the function. Remember that just defining a function is not enough, we also have to call it in the code.
---------------------------------------------------
Code:-
def myfunc(): #making the function
x = "This is an output from my user-defined function."
print(x)
myfunc() #calling the function
Output:-
This is an output from my user-defined function.
----------------------------------------------------
Here a question arises that what is the use of defining functions. It is useful when you have to use a long set of code many times in a whole program. You just need to define the function once and then use it as many times as you want.
To make a function that takes some arguments and returns an output you need to declare variables separated by comma(,) inside the parentheses and then use those variables inside your function. Then you need to use the 'return' keyword to return a result back from that function that can be used by the outer code.
---------------------------------------------------
Code:-
def mysum(x,y):
return x+y
print(mysum(5,6))
Output:-
11
--------------------------------------------------------
Thanks for this amazing guide on beginners python.
ReplyDeleteThanks for this amazing guide on python.
ReplyDelete