python
Function in python
In python you can create function that will execute a set of code when called.
#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.
Return from function
You can also return something from a function in Python. The example is below:
def function_name():
return "1"
val = function_name()
print val
Was this helpful?
Similar Posts
- Function argument unpacking in Python
- [Python] Range - standard function to create a list of numbers
- [Python] Function returns multiple values
- [Python] Function parameters - pack and unpack
- [Python] Eval() function
- [Python] Get nodeid, module, function name using Pytest request built-in fixture
- [Python] Default value of function argument
- [Python] Using inspect.stack() to get module name, path, function name