0% found this document useful (0 votes)
14 views7 pages

How Python Functions Part2

Part 2 of the document discusses how Python functions work, focusing on the use of the return statement, scoping, and arguments. It explains how functions can return values, the concept of local and global scopes, and how arguments are passed to functions, including the use of default arguments. The document emphasizes the importance of understanding these concepts for effective function usage in Python.

Uploaded by

sohamsett2103
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
14 views7 pages

How Python Functions Part2

Part 2 of the document discusses how Python functions work, focusing on the use of the return statement, scoping, and arguments. It explains how functions can return values, the concept of local and global scopes, and how arguments are passed to functions, including the use of default arguments. The document emphasizes the importance of understanding these concepts for effective function usage in Python.

Uploaded by

sohamsett2103
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

How Python Functions

Part 2
~ Dwijoraaj Das

In Part 1, we have seen what functions are and how they are
defined. We have seen a small example of a function add(x, y)
which prints the sum of two numbers. In this part, we are going
to be delving a little bit deeper into how functions work in the
Python language.

Returning a value
In Part 1 we have only seen a function which prints as its
output. We have discussed the keyword return without seeing
it in practice.
What return does is that it ‘return’s a value1 to the instance
where the function was called, i.e. if calling the function was
asking a question, the return keyword simply gives the answer.
Let’s look at an example:
def sum(a,b):
return a+b
What this does is return the value of the sum of the two
provided arguments2 ‘a’ and ‘b’.
Let us see it in practice:
def sum(a,b):
return a+b

print(sum(2,3))

1
Well to be more precise, it returns an object. But we will cover that part later.
2
It is called a parameter when you are defining the function i.e. the placeholders/variables are called the
parameters. However, the actual value which you put in when calling the function is called the argument.
Page 1|7
It gives us the output ‘5’. So, you may ask, what is the point if I
can just print right in the function definition itself instead of
return?
Well, you can now do more than just print the output now, you
can put it into a variable and much more.
def sum(a,b):
return a+b

x = sum(6,7)
print(x)
Which gives us the output ‘13’.
Note: Functions always return a value. Even if you do not explicitly use a return
statement, a function returns the special value None by default.

Scoping
Python uses the concept of namespaces3 to store information
about objects and their location.
An object in python is just something which holds data and
can perform actions, for example a number like 5 is an object
and so is a string like “Hello”, as well as variables containing
similar values. Most of everything we see/use in Python are
objects.
Back to the concept of namespaces; whenever you call an
object, i.e. reference it, there is a certain order in which Python
searches for the object within the code if you have more than
one object with the same name.
The order can be remembered with a simple acronym: LGB
➢ Local Scope
➢ Global Scope

3
Do not worry too much about this now, we will discuss this in more detail in later chapters.
Page 2|7
➢ Built-in Scope
The Global Scope is defined as the module enclosing the
function, but for now you can remember it as the file.
There can be multiple Local Scopes in a module (i.e. file). For
example, if you initialize a variable in a function, the variable
will only exist in the local scope of the function. Now if you try
to print the variable within the function, it will always use the
variable made within the function even if there exists another
variable of same name in the global scope. For example, the
code
a = 2
def scope():
a = 9
print(a)

scope()
will always give 9 as the output.
However, the Local Scope of the scope() function does not exist
outside the function and thus the code
a = 2
def scope():
a = 9

scope()
print(a)
will give the output 2.
And if you use a variable not defined in the Local Scope but
exists in the Global Scope then it will use the variable in the
Global Scope regardless of where the variable is called.
a = 2
def scope():
print(a)

scope()
will give the expected output of 2.

Page 3|7
However, if you want to modify a variable declared globally
inside the local scope of a function, you will have to use a new
keyword global. For example, the code
a = 2
def scope():
global a
a = 9

scope()
print(a)
will give us the output 9. The usage of the keyword is pretty
self-explanatory; you tell Python which objects you will be using
in the function from the Global Scope (and not creating new
objects of the same name in the Local Scope).

Arguments
Note: For this section of the chapter, we will be referring to both parameters and arguments
as ‘arguments’ for ease of communication. However, beware of the distinction between the
two as stated in the footnote of PAGE 1.

The arguments of a function are taken in the order of which


they are defined. Pretty self-explanatory but let us look at an
example.
def message(to, msg):
print(f"Message for {to}: \n{msg}")

message("Annie", "Are you okay?")


which gives us the output
Message for Annie:

Are you okay?

And thus, it is evident that the first argument supplied


(“Annie”) got assigned to the variable ‘to’ which happens to be
the first argument defined and the same with the second.

Page 4|7
There are two main rules arguments follow:
1. Supplied arguments are copied into objects in the local
scope and therefore any modifications to the received
arguments inside the function do not affect the original
object in any way.
2. Mutable objects can be changed in place. When you accept
a list or dictionary as an argument, you copy a list of object
references and thus if you modify the value of a reference,
you modify the original argument.
Do not worry about the second rule as of now, that is because
we will not be dealing with lists or dictionaries yet (for some
reason).
What the first rule means that you can use the local versions of
the arguments without worrying about modifying the original
values. An example will make this clearer.
def modify(number, string):
number = 456
string = "Apple Pen"
print(f"Inside:\nNumber = {number}\nString = {string}\n")

number = 123
string = "Pineapple"
print(f"Before:\nNumber = {number}\nString = {string}\n")
modify(number,string)
print(f"After:\nNumber = {number}\nString = {string}")
The above code gives us the output,
Before:

Number = 123

String = Pineapple

Inside:

Number = 456

String = Apple Pen

After:

Page 5|7
Number = 123

String = Pineapple

So, we can observe that even after putting the variables


‘number’ and ‘string’ through the modify(number,string)
function, no actual change takes place on the objects(variables)
in the global scope and the change is purely in the local scope.
Arguments are just objects. This is obvious but essential to
keep in mind. And since arguments are just pointers
(placeholders) for objects, the exact type of argument which
needs to be passed does not need to be defined unlike in most
other programming languages.
If we have a function,
def multiply(x,y):
return x*y
Then if we pass multiply(2,3), then we get result 6. If we give
multiply(‘Ha’,5) then we get result ‘HaHaHaHaHa’ (String
operations will be covered in later chapters).

Apart from the traditional way of assigning arguments in the


order of their definition, python offers a number of other ways
to assign arguments to a function.
The most basic way (and the only way we are going to be
looking at in this part) is explicitly stating which value is
assigned to which parameter. And in this case, the order of the
arguments does not matter at all. For example, you could have
called the multiply function as multiply(x=2,y=3) and it would have
meant the exact same as multiply(y=3, x=2).

Default Arguments
Within the function definition, Python allows you to set
defaults for the arguments. Normally, when calling a function,
Page 6|7
you need to provide as many arguments specified by the
function definition. But if defaults are set for certain
arguments, you can omit them and the function will still
execute. The way to do so has been demonstrated by an
example:
def area_of_circle(radius, pi=3.14):
return radius*radius*pi

Here, the radius cannot be omitted as it does not have a default


value but you can omit the value of pi as there is a default of
3.14 provided. Thus, the format for default arguments is
def func(ARG=VALUE)
where VALUE is the default value to be applied to the argument
ARG if it is not supplied during the function call.
Note that you can only specify default arguments towards the
end, i.e. after the arguments without a default. And so
def area_of_circle(pi=3.14, radius):
return radius*radius*pi

will not work.


This will be it for Part 2. Further information regarding
functions and arguments will be provided in later parts.
Thank You.

Page 7|7

You might also like