Introduction in python
We already have a glimpse of built-in functions in python. In this article, we will discuss user-defined functions in detail.
Imagine, you have some lines of code which need to be repeated at various parts of your code, you will feel comfortable if we write those lines in one place and give a name to them. Now, whenever we need to write those lines we can just call them by their name. Exactly, the same process is called functions.
Now, will see how to manually create such functions and their importance and usage of them.
Python functions creation contains two main parts,
- Function definition
- Function call
In the built-in function, the first step is already done for you so, we only call the functions. But in the user-defined function, we need to define the function by ourselves and call them whenever required.
Function definition and function call
Syntax for function definition
def funtion_name(<optional parameters>): Statements Optional return statement
- In line 1, we write def as a keyword as for starting a function followed by a function name, we can same a function with the same conditions as a variable name, after with we write round brackets within with the parameters are totally optional and end the line with a colon.
- In the next lines, we will write some of the statements indented in such a way that these blockers will run only upon function call.
- The last line of the function can have a return statement which is again optional. If we are not writing a return statement it will return none to the function call.
The syntax for function call
- We are calling the function with the help of a function call and a list of values as arguments to be used inside the function.
Non-parametrized functions are functions without parameters.
def add(): num1=int(input("Enter a number: ")) num2=int(input("Enter another number: ")) ans=num1+num2 return ans answer=add() print(answer)
In the above code snippet,
- Line 1, uses the def keyword to indicate that a function is being defined. Execution of the def statement merely creates the definition of add(). All the following lines that are indented (lines 2 to 5) become part of the body of add() and are stored as its definition, but they aren’t executed yet.
- Line 6, is a bit of whitespace between the function definition and the first line of the main program. While it isn’t syntactically necessary, it is nice to have to improve the readability of the code.
- Line 7, is the first line of the main program. This line calls the add function. So, now the line numbers 1-5 are executed one by one. In line 5, the return statement is executed which will return the answer to the function call of line 7 and that value is saved in the variable answer.
- Now, you can print the answer which was returned from the function.
Parameters in the function can be done in many ways, we can see it one by one with detail and example.
The easiest way to assign parameters is with help of positional arguments.
In the function definition, you specify a comma-separated list of parameters inside the parentheses.
When the function is called we can specify the corresponding values to the parameters in the same order.
def welcome(name,age): print("Welcome",name, "of",age,"years old.") welcome("XXX",17)
In the above code snippet,
- Line 1, uses the def keyword to indicate that a function is being defined. Execution of the def statement merely creates the definition of welcome(). All the following lines that are indented (line 2) become part of the body of welcome() and are stored as its definition, but they aren’t executed yet.
- Line 4, makes the function call to the welcome(). Now while calling the function we are passing two arguments XXX and 17 for the parameters which is available in the function definition. So the first argument automatically goes to the first parameter and now the parameter name had the value XXX same way second argument 17 goes and sits for the second parameter age and works accordingly.
In short, if we already know the number of parameters and order of the parameters then positional parameters are best suited.
If the number of parameters differs from the number of arguments, python will throw an error.
PLEASE NOTE Parameter is the term used to represent the list of items passed inside the parentheses on function definition. The argument is the term used to represent the list of items inside parameters during a function call.
When you’re calling a function, you can specify arguments in the form <keyword>=<value>. In that case, each <keyword> must match a parameter in the Python function definition.
For Example, In the above example, we can also call the same function as
Here, the order is not going to affect it as we have mentioned the keywords correctly.
If we do a small mistake in the keyword, then it will throw an error.
You can also call a function by combining both positional and keyword arguments provided all the positional arguments should come first followed by the keyword argument.
A function definition can be written as <name>=<value>, then <value> becomes a default value for that parameter. This value is taken into consideration when we are calling the function without specifying the value of that parameter.
def welcome(name="XXX",age=18): print("Welcome",name, "of",age,"years old.") welcome("YYY") #Welcome YYY of 18 years old. welcome(age=20) #Welcome XXX of 20 years old. welcome() #Welcome XXX of 18 years old.
In the above code snippet,
- Line 1, function definition is done and parameters have default values, as name=” XXX” and age =18.
- Line 4, we have called the function with only one argument, so by default that is assigned to the first parameter and since the second argument is missing we take the default value as the second argument.
- InLine 5, we use a keyword argument to specify the age, since we don’t the name, we will be considering the default value
- In Line 6, no arguments are passed, so both are taking the default value.
A return statement is used to end the execution of the function call and “returns” the result (value of the expression following the return keyword) to the caller. The statements after the return statements will not be executed. If the return statement is without any expression, then the special value None is returned.
A return statement can not be used outside the function.
A docstring is used to supply documentation for a function. It can contain the function’s purpose, what arguments it takes, information about return values, or any other information you think would be useful.
When the first statement in the body of a Python function is a string literal(Enclosing withing three double quotes), it’s known as the function’s docstring.
def add(num1,num2): """This function is used to add two numbers and return the answer""" ans=num1+num2 return ans
If the docstring fits on one line, then the closing quotes should be on the same line as the opening quotes.
Multi-line docstrings are used for lengthier documentation. A multi-line docstring should consist of a summary line, followed by a blank line, followed by a more detailed description. The closing quotes should be on a line by themselves
def add(num1,num2): """This function is used to add two numbers and return the answer num1- First number given by the user num2- The second number is given by the user returns the answer containing the sum of both the numbers """ ans=num1+num2 return ans
When a docstring is defined, the Python interpreter assigns it to a special attribute of the function called __doc__.
We can print the documentation as function_name.__doc__
Another way to print the documentation is print(help(function_name))
In the future, we can discuss advanced topics of functions like having variable-length parameters/arguments, lambda functions, and annotations in detail.
- Write a program using functions to calculate the perimeter of basic shapes according to user input.
- First, ask the user which shape they need to find the perimeter. According to users, input calls different functions for different shapes.
- Use the return statement to get the answer and print them.
- Write a function to find the maximum of two numbers and make the default value to be 0.
- In the ATM task, we already did modify the program in such a way that you use the functions for the functionality for deposit withdrawal and balance check.
Thus, we have discussed in detail user-defined functions. Feel free to use the comment box to discuss any doubts and explore more about user-defined functions.