#SIMPLE FUNCTION
def function_name():
print("Hello world")
function_name() #CALL FUNCTION
# FUNCTION WITH ARGUMENTS
def function_with_args(first_name, last_name):
print("First name is " + first_name + ". Last name is" + last_name)
function_with_args("John", "Deo") #CALL FUNCTION WITH ARGUMENTS
#CALL WITH KEYWORDS ARGUMENTS
#ARGUMENT ORDER DOES NOT MATTER
function_with_args(last_name = "Deo", first_name = "John")
#WITH ARBITARY ARGUMENTS
#USE WHEN NUMBER OF ARGUMENT PASSED IS UNKNOWN
def function_with_arbitary_args(*args):
print("Third item is " + args[2])
function_with_arbitary_args("Bat", "Bowl", "Hockey") #WILL PRINT 'HOCKEY'
#WITH ARBITARY KEYWORD ARGUMENTS
def function_with_arbitary_args(*args):
print("Third item is " + args["last_name"])
function_with_arbitary_args(first_name = "Rick", last_name = "Bowl")
You can define or create a function in Python that will run a group of statements inside that function when called. You can create a function in Python using below syntax.
def function_name:
print("I will be printed when called")
In the code snippet, we showed different ways to create and call functions in Python.
You can also pass default value to an agument when declaring a function in Python. The example is as below.
def func_name(first_name = "Rick"):
print("First name is " + Rick)
func_name("John")
#This will print - First name is John
func_name()
#This will print - First name is Rick
So default value is used in argument if the required argument is not passed. And if you did not define default value to an argument when called it will throw error.
You can also return something from a function in Python. The example is below:
def function_name():
return "1"
val = function_name()
print val
0 Comments