Python Function
Python Function
Type Description
#Code
def my_function():
print("Hello from a function")
my_function()
#code
def my_function(fname):
print(fname + " Refsnes")
my_function("Emil")
Parameter:-
A parameter is a variable defined inside the parentheses in the function definition.
It acts as a placeholder for the value you pass when you call the function.
In your code:
fname is the parameter.
Argument:-
An argument is the actual value passed to the function when it is called.
Arguments are assigned to parameters when the function is executed.
In your code:
"Emil"
# code
def my_function(fname, lname):
print(fname + " " + lname)
my_function("Emil", "Refsnes")
Arbitrary Arguments, *args:- If you do not know how many arguments that will
be passed into your function, add a * before the parameter name in the
function definition.
This way the function will receive a tuple of arguments, and can access the
items accordingly:
If the number of arguments is unknown, add a * before the parameter name:
def my_function(*kids):
print("The youngest child is " + kids[2])
#code
#code
my_function("Sweden")
my_function("India")
my_function()
my_function("Brazil")
Passing a List as an Argument:- You can send any data types of argument to a
function (string, number, list, dictionary etc.), and it will be treated as the
same data type inside the function.
E.g. if you send a List as an argument, it will still be a List when it reaches
the function:
#code
def my_function(food):
for x in food:
print(x)
my_function(fruits)
Return Values:- To let a function return a value, use the return statement.
#code
def my_function(x):
return 5 * x
print(my_function(3))
print(my_function(5))
print(my_function(9))