In this article, you’ll see how to use a function in Python. The function is a set of code that we define once and can reuse many times.
How to create a function in Python
The def
keyword is used to define a function in Python. In the following example, my_fun()
is the name of the function.
# define a function def my_fun(): print("AiHints") # call the function my_fun()
Output:
AiHints
Python Function arguments
You can use arguments to pass information in a function.
# define a function def my_fun(name): print("Hello", name) # call the function my_fun("Hussain") my_fun("John") my_fun("Smith")
Output:
Hello Hussain Hello John Hello Smith
Multiple Arguments
You can also define a function with multiple arguments.
# define a function def my_fun(a, b): print(a + b) print(a - b) print(a * b) print(a / b) # call the function my_fun(20, 10)
Output:
30 10 200 2.0
Number of arguments is unknown
When the number of arguments is unknown, you can use * in the parenthesis before the argument.
# define a function def my_fun(*names): print("Hello", names[2]) # call the function my_fun("Hussain", "John", "Smith", "Satish")
Output:
Hello Smith
Another Example
# define a function def my_fun(**Skills): print("His Skills are", Skills["first"], "and", Skills["second"]) # call the function my_fun(first = "Python", second = "R", third = "SQL")
Output:
His Skills are Python and R
Order of the arguments
The following example will give you an idea that in some cases the order of the arguments does not matter.
# define a function def my_fun(c, a, b): print("The value of a is", a) # call the function my_fun(b = 10, c = 20, a = 30)
Output:
The value of a is 30
List in Function
You can also use a list in the function. The following two examples will be helpful to understand how to use a list and loop in the function.
# define a function def my_fun(Skills): for x in Skills: print(x) # call the function my_fun(["Python", "R", "SQL"])
Output:
Python R SQL
Another Example
def my_fun(Skills): for x in Skills: print(x) Languages = ["Python", "R", "SQL"] # call the function my_fun(Languages)
Output:
Python R SQL
Return in Function
You should use the return
keyword in the following situation.
# define a function def my_fun(a): return 5 * a # call the function print(my_fun(5)) print(my_fun(10))
Output:
25 50
If you will not use return then the output will be:
# define a function def my_fun(a): 5 * a # call the function print(my_fun(5)) print(my_fun(10))
None None
I highly recommend you get the “Python Crash Course Book” to learn Python.