0% found this document useful (0 votes)
10 views

Function

Notes for class 12 Computer Sciences CBSE on Function

Uploaded by

rajnee choudhary
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views

Function

Notes for class 12 Computer Sciences CBSE on Function

Uploaded by

rajnee choudhary
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 11

FUNCTION IN PYTHON

 A function is a block of code which only runs when it is called.


 You can pass data, known as parameters, into a function.
 A function can return data as a result.

Some Benefits of Using Functions

 Increase Code Readability

 Increase Code Reusability


 function definitions cannot be empty, but if you for some reason
have a function definition with no content, put in the pass
statement to avoid getting an error.

Creating a Function

In Python a function is defined using the def keyword:

def my_function():

print("Hello from a function")

Calling a Function

To call a function, use the function name followed by parenthesis:

def my_function():

print("Hello from a function")

my_function()

OUTPUT

Hello from a function

Types of Python Functions

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:

These functions are defined by users to perform specific tasks.

Defined using the def keyword, followed by the function name and
parentheses.

Example:

def greet(name):

return f"Hello, {name}!"

3.Functions defined in modules

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

Information can be passed into functions as 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):

print(fname + " Refsnes")

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.

 A parameter is the variable listed inside the parentheses in the


function definition.
 An argument is the value that is sent to the function when it is called.

Number of Arguments

By default, a function must be called with the correct number of arguments.


Meaning that if your function expects 2 arguments, you have to call the
function with 2 arguments, not more, and not less.

Example

This function expects 2 arguments, and gets 2 arguments:

def my_function(fname, lname):

print(fname + " " + lname)

my_function("Emil", "Refsnes")

Types of Python PASSING PARAMETERS

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

A default argument is a parameter that assumes a default value if a


value is not provided in the function call for that argument. The
following example illustrates Default arguments to write functions in
Python.

def myFun(x, y=50):

print("x: ", x)

print("y: ", y)

myFun(10)
OUTPUT

x: 10

y: 50

2. Keyword arguments (named arguments)

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.

def student(firstname, lastname):

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.

def nameAge(name, age):

print("Hi, I am", name)

print("My age is ", age)

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

Returning Values from Function

 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

def add(a, b):


return a + b

res = add(2, 3)
print("Result of add function is {}",res)

Returning Multiple Values


In Python, we can return multiple values from a function. Following are
different ways.

Using Tuple: A Tuple is a comma separated sequence of items. It is


created with or without (). Tuples are immutable. See this for details of
tuple.
def circleInfo(r):
""" Return (circumference, area) of a circle of radius r """
c = 2 * 3.14159 * r
a = 3.14159 * r * r
return (c, a)

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:

1. Omit the return statement and rely on the default behavior of


returning None.
2. Use a bare return without a return value, which also returns None.
3. Return None explicitly.

Example
def omit_return_stmt():
... # Omit the return statement
... pass
...
>>> print(omit_return_stmt())
None

>>> def bare_return():


... # Use a bare return
... return
...
>>> print(bare_return())
None

>>> def return_none_explicitly():


... # Return None explicitly
... return None
...
>>> print(return_none_explicitly())
None
Global and Local Variables in Python
Python Global variables are those which are not defined inside any
function and have a global scope whereas Python local variables are those
which are defined inside a function and their scope is limited to that
function only.
In other words, we can say that local variables are accessible only inside
the function in which it was initialized whereas the global variables are
accessible throughout the program and inside every function.

Python Local Variables


Local variables in Python are those which are initialized inside a function
and belong only to that particular function. It cannot be accessed
anywhere outside the function.
def f():
s = "I love Geeksforgeeks"
print(s)
f()
Output
I love Geeksforgeeks

Python Global Variables


These are those which are defined outside any function and which are
accessible throughout the program, i.e., inside and outside of every
function.
1.def f():
print("Inside Function", s)
s = "I love Geeksforgeeks"
f()
print("Outside Function", s)
OUTPUT
Inside Function I love Geeksforgeeks
Outside Function I love Geeksforgeeks
2.def f():
s = "Me too."
print(s)
s = "I love Geeksforgeeks"
f()
print(s)
Output
Me too.
I love Geeksforgeeks

3.
def f():
s += 'GFG'
print("Inside Function", s)
s = "I love Geeksforgeeks"
f()
Output:
UnboundLocalError: local variable 's' referenced before assignment

Difference b/w Local Variable Vs. Global Variables

Comparision
Global Variable Local Variable
Basis

Definition declared outside the functions declared within the functions

They are created when the


They are created the execution
function starts its execution
Lifetime of the program begins and are
and are lost when the function
lost when the program is ended
ends
Data Sharing Offers Data Sharing It doesn’t offers Data Sharing

Can be access throughout the Can access only inside the


Scope
code function

Parameters parameter passing is not


parameter passing is necessary
needed necessary

A fixed location selected by the


Storage They are kept on the stack
compiler

once changed the variable


Once the value changes it is
Value don’t affect other functions of
reflected throughout the code
the program

Void function and Non Void Function


The function which doesn't return any value is called void function and
function which return some values is called non void function.
Void function may or may not use return keyword and print statement is
written inside the function definition only.

Mutable/Immutable Properties of passed Data Objects

 Python’s variable are not storage containers, rather Python


variables are like memory references, they refer to the memory
address where the value is stored.
 Depending upon the mutability/Immutability of its data type, a
variable behaves differently. That is, if a variable is referring to an
immutable type, then any change in its value will also change the
memory address it is referring to, but is a variable is referring to
mutable type then any change in the value of mutable types will not
change the memory address.

Passing Immutable type


def myfun(a):
print(“Inside myfun()”)
print(“value received in ‘a’ as”,a)
a=a+2
print(“Value of ‘a’ now changes to ”,a)
print(“returning from myfun()”)
#___main____
Num=3
Print(“calling function by passing num with value”,num)
myfun (num)
Print(“Back from myfun(),Value of ‘num’ is ”, num)

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

Passing Mutable type

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]

You might also like