Namaste Coder πββοΈ
In this article, we will discuss user-defined functions in Python.
Read the article to get started with function π Built -in functions
Python User-Defined Functions
User-defined or say customizable functions which programmers can define as per their requirements. Also, in-built functions can be used in user-defined functions. Make sure that do naming of your functions should be proper and avoid using naming your function in name of keywords or inbuilt function.
Defining a function
Here are simple rules to define a function in Python π
- Function blocks begin with the keyword def followed by the function name and parentheses ( ( ) ).
- Any input parameters or arguments should be placed within these parentheses.
- The code block of the function starts with a colon (:) and is indented.
- The statement return [expression] exits a function, optionally passing back an expression to the caller. A return statement with no arguments is the same as return None.
Syntax
def function_name(parameters):
#statements
#return expression
Calling a Function
Defining a function only gives it a name, specifies the parameters that are to be included in the function, and structures the blocks of code. Once the basic structure of a function is finalized, you can execute it by calling it from another function or directly from the Python prompt.
def func():
print("I am inside function")
func()
print("I am outside function")
#I am inside function
#I am outside function
Pass by reference
All parameters (arguments) in the Python language are passed by reference. It means if you make a change to the parameter within a function, the change also reflects back in the calling function.
For example π
def changeList(list):
list.append([6,7])
print("List in function: ",list)
mylist=[1,2,3,4,5]
changeList(mylist)
print("List outside function: ",mylist)
#List in function: [1, 2, 3, 4, 5, [6, 7]]
#List outside function: [1, 2, 3, 4, 5, [6, 7]]
Function Arguments
You can call a function by using the following types of formal arguments π
- Required arguments
- Keyword arguments
- Default arguments
- Variable length arguments
- Variable length keyword arguments
Required Arguments
Required arguments are the arguments passed to a function in correct positional order. Here, the number of arguments in the function call should match exactly with the function definition.
To call the function printme(), you definitely need to pass one argument, otherwise it gives a syntax error as follows π
def printme(string):
print(string)
s="Python Programming"
printme(s)
#Python Programming
If we will not pass any argument than error will be raised by interpreter π²
def printme(string):
print(string)
printme()
#TypeError: printme() missing 1 required positional argument: 'string'
Keyword arguments
Keyword arguments are related to the function calls. When you use keyword arguments in a function call, the caller identifies the arguments by the parameter name. This allows you to skip arguments or place them out of order because the Python interpreter is able to use the keywords provided to match the values with parameters.
def printinfo(fname,lname,age):
print(f"your name is: {fname} {lname}")
print(f"your age is: {age}")
# While provideing parameters order doesn't matter as we are using keywords
printinfo(age=20,lname="Doe",fname="Jane")
#your name is: Jane Doe
#your age is: 20
Default arguments
A default argument is an argument that assumes a default value if a value is not provided in the function call for that argument.
The following example gives an idea on default arguments, it prints default age if it is not passed.
def printinfo(fname,lname,age=20):
print("your name is: ",fname+' '+lname)
print("your age is: ",age)
printinfo("Jane","Doe",35)
# No error as by default age will be 20
printinfo("John","Cooper")
#your name is: Jane Doe
#your age is: 35
#your name is: John Cooper
#your age is: 20
Return Statement
The statement return [expression] terminates the function and transfers the output back to the caller which has been generated by functions.
For example, while ordering food from zomato, foodpanda, swiggy, etc. delivery person acts as a return statement that delivers our order prepared by the restaurant. A return statement with no expression is equivalent to return None.
#Function with return statement
def sum(num1,num2):
total=num1+num2
print("Total inside function: ",total)
return total
num1=23
num2=17
out_total=sum(num1,num2)
print("Total outside function: ",out_total)
#Total inside function: 40
#Total outside function: 40
Variable Length Arguments
In Python we use variable length parameters while defining the function, it helps when the number of arguments isn't certain and also handles the situation if no argument is passed. asterisk(*) is used along with the parameter name.
Syntax:
def func_name( *args ) :
#function statements
Example
def func(*args):
print(args)
print(type(args))
func(1,2,3,4)
func()
#(1, 2, 3, 4)
#<class 'tuple'>
#()
#<class 'tuple'>
variable length arguments take in tuples as a parameter. Thus, python tuple properties can be applied to it in the function.
Variable Length Keyword Arguments
In Python we use variable length keyword parameters while defining the function, it helps when the number of keyword arguments isn't certain and also handles the situation if no argument is passed. Double asterisk(**) is used along with the parameter name.
Syntax
def func (**kwargs):
#function statements
def func (**kwargs):
print(kwargs)
print(type(kwargs))
func(name ="John doe" , age ="19")
#{'name': 'John doe', 'age': '19'}
#<class 'dict'>
variable length keyword arguments take in the dictionary as a parameter. Thus, python dictionary properties can be applied to it in the function.
def func (**kwargs):
for k , v in kwargs.items():
print(f"{k} --> {v}")
func(name ="John doe" , age ="19")
#name --> John doe
#age --> 19
P.S. : Will continue with the functions and discuss more in upcoming articles. Stay tunedπ§
The End
I hope you enjoyed the article and had a good learning experience.
Follow for more articles and keep sharingπ©
Keep coding