Function
Function
Creating a Function
def my_function():
Calling a Function
def my_function():
my_function()
OUTPUT
Python functions are categorized based on their definition and usage. Here
are the primary types:
1.Built-in Functions:
These are the functions that come pre-defined with Python. Examples include
print(), len(), type(), int(), etc.They provide commonly needed functionality
without the need for additional code.
2.User-defined Functions:
Defined using the def keyword, followed by the function name and
parentheses.
Example:
def greet(name):
These functions are pre defined in particular modules and can only be used
when the corresponding module is imported .For example for using sin() ,
you need to import module math in your program.
Arguments
Arguments are specified after the function name, inside the parentheses. You
can add as many arguments as you want, just separate them with a comma.
def my_function(fname):
my_function("Emil")
my_function("Tobias")
my_function("Linus")
OUTPUT
Emil Refsnes
Tobias Refsnes
Linus Refsnes
Parameters or Arguments
The terms parameter and argument can be used for the same thing:
information that are passed into a function.
Number of Arguments
Example
my_function("Emil", "Refsnes")
Python supports various types of arguments that can be passed at the time
of the function call. In Python, we have the following function argument
types in Python:
1. Default argument
print("x: ", x)
print("y: ", y)
myFun(10)
OUTPUT
x: 10
y: 50
The idea is to allow the caller to specify the argument name with
values so that the caller does not need to remember the order of
parameters.
print(firstname, lastname)
student(firstname='Geeks', lastname='Practice')
student(lastname='Practice', firstname='Geeks')
OUTPUT
Geeks Practice
Geeks Practice
3. Positional arguments
We used the Position argument during the function call so that the first
argument (or value) is assigned to name and the second argument (or
value) is assigned to age. By changing the position, or if you forget the
order of the positions, the values can be used in the wrong places.
print("Case-1:")
nameAge("Suraj", 27)
print("\nCase-2:")
nameAge(27, "Suraj")
OUTPUT
Case-1:
Hi, I am Suraj
My age is 27
Case-2:
Hi, I am 27
My age is Suraj
A return statement is used to end the execution of the function call and
“returns” the result (value of the expression following the return
keyword) to the caller.
The statements after the return statements are not executed.
If the return statement is without any expression, then the special
value None is returned.
A return statement is overall used to invoke a function so that the
passed statements can be executed.
Return statement can not be used outside the function.
def fun():
statements
.
.
return [expression]
Example
def cube(x):
r=x**3
return r
cube(5)
Example
res = add(2, 3)
print("Result of add function is {}",res)
print(circleInfo(10))
Output:
(62.8318, 314.159)
Using a list: A list is like an array of items created using square
brackets. They are different from arrays as they can contain items of
different types. Lists are different from tuples as they are mutable. See
this for details of list.
def fun():
str = "geeksforgeeks"
x = 20
return [str, x];
list = fun()
print(list)
Output:
['geeksforgeeks', 20]
Using a Dictionary: A Dictionary is similar to hash or map in other
languages. See this for details of dictionary.
def fun():
d = dict();
d['str'] = "GeeksforGeeks"
d['x'] = 20
return d
d = fun()
print(d)
Output:
{'x': 20, 'str': 'GeeksforGeeks'}
Returning “None”
if you don’t add an explicit return statement with an explicit return value to a
given function, then Python will add it for you. That value will be None.
Some behaviour:
Example
def omit_return_stmt():
... # Omit the return statement
... pass
...
>>> print(omit_return_stmt())
None
3.
def f():
s += 'GFG'
print("Inside Function", s)
s = "I love Geeksforgeeks"
f()
Output:
UnboundLocalError: local variable 's' referenced before assignment
Comparision
Global Variable Local Variable
Basis
Output
calling function by passing num with value 3
Inside myfun()
value received in ‘a’ as 3
Value of ‘a’ now changes to 5
returning from myfun()
Back from myfun(),Value of ‘num’ is 3
def myfun(myList1):
print("Inside myfun()")
print("List received in ‘a’ as",myList1)
myList1[0]+=2
print("List withing called function, after changes: ",myList1)
return
#___main____
List1=[1]
print("List before function call",List1)
myfun (List1)
print("List after function call", List1)
Output
List before function call [1]
Inside myfun()
List received in ‘a’ as [1]
List withing called function, after changes: [3]
List after function call [3]