Function consists of list of statements that can be grouped together and run together.Function can be used to reused again and again.
Let’s syntax of function in python.
This is where the function's Document String (doc-string) goes
# Do stuff here
#return desired result
It starts with def then a space followed by the name of the function. Try to keep names simple and relevant.
Next comes a pair of parenthesis with a number of arguments separated by a comma. These arguments are the inputs for your function. You’ll be able to use these inputs in your function and reference them. After this, you put a colon.
Now here is the important step, you must indent to begin the code inside your function correctly. Python makes use of whitespace to organize code. Lots of other programming languages do not do this, so you need to be careful with it.
Next we have the doc-string, this is where you write a basic description of the function. It is not necessary but it is good practice to provide some information about the function.
After all this, you start writing the code you wish to execute.
Let’s understand function with the help of examples.
Example 1: A simple print ‘hello’ function
def hello(): print('hello') #call the function hello()
Example 2: Simple greet function
Let’s write a function that welcome people to the County
def welcomeCountry(countryName): print('Welcome to %s' %countryName) welcomeCountry('India')
Let’s see some example that use a return statement. return allows a function to return a result that can then be stored as a variable, or used in whatever manner a user wants.
Example 3: Multiply function
def multiply_num(num1,num2): return(num1*num2) # Can also save as variable due to return result = multiply_num(4,5) print(result)
Example 4: String matching function
Let’s write a function which will take input as list of String and returns names which start with ‘M’
def startWithM(String_lst): resultList= for str in String_lst: if(str=='M'): resultList.append(str) return resultList String_lst=['John','Martin','Mary','David'] # Call the function resultList=startWithM(String_lst) print(resultList)
That’s all about functions in Python
I hope you will be able to create your own functions now.