0% found this document useful (0 votes)
4K views34 pages

Working With Functions

Functions allow programmers to break large programs into smaller, more manageable units. They make programs easier to handle by dealing with only a small part at a time and avoiding ambiguity. Functions also help reduce program size and make code more readable and understandable. In Python, functions are defined at the top of a program followed by top-level statements that are executed from the start. When a function is called, an execution frame is created to execute the function body before returning control to the caller.

Uploaded by

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

Working With Functions

Functions allow programmers to break large programs into smaller, more manageable units. They make programs easier to handle by dealing with only a small part at a time and avoiding ambiguity. Functions also help reduce program size and make code more readable and understandable. In Python, functions are defined at the top of a program followed by top-level statements that are executed from the start. When a function is called, an execution frame is created to execute the function body before returning control to the caller.

Uploaded by

kunsang
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 34

WORKING WITH

FUNCTIONS
Introduction
• Large programs are generally avoided because it is
difficult to manage a single list of instruction. Thus a large
program is broken down into smaller units known as
functions.
• The most important to use functions is to make program
handling easier as only a small part of the program is
dealt with a time, thereby avoiding ambiguity.
• Another reason to use functions is to reduce program
size. Function make a program more readable and
understandable to a programmer thereby making program
management much easier.
def calcSomething(x):
result=2*x*2
return result
a=int(input(“Enter a number:”))
print(calcsomething(a))
Structure of a Python Program

In a Python program, generally all function definitions are


given at the top followed by statements which are not part
of any functions. These statements are not indented at all.
These are often called the top-level statements( the ones
with no indentation). The python interpreter starts execution
of a program/scripts from the top-level statements. The top
level statements are part of the main program. Internally
Python gives a special name to top-level statements as
__main__
The structure of a Python program is generally like the one
shown below:
Python stores this name in a built-in variable
called __name__(i.e., you need not declare this
def function1(): vairable; you can directly use it). You can see it
: yourself. In the __main__ segment of your
program if you give a statement like:
def function2(): Print(__name__)

:
def function3():
:
:
#top-level statements here
statement1 Python names the segment with
top-level statements begins
statement2 execution of a program from the
top-level statements i.e., from
: __main__

:
For example:
def greet():
print(“Hi there!”)
print(“At the top-most level right now”)
print(“Inside”,__name__)

• Upon executing above program, Python will


display

• At the top-most level right now


Notice word ‘__main__’ in the
• Inside __main__ output by Python interpreter.
This is the result of
statement:
Prinprint(…,__name__)
Flow of Execution in a Function Call
• Let us now talk about how the control flows (i.e., the flow
of execution of statements) in case of a function call. You
already know that a function is called (or invoked, or
executed) by providing the function name, followed by the
values being sent enclosed in paraenthese. For instance,
to invoke a function whose header looks like:
def sum(x,y):
The function call statement may look like as shown
below:
sum(a,b)
Where a,b are the values being passed to the function
sum().
The Flow of Execution refers to the order in which
statements are executed during a program run.
Recall that a block is a piece of Python program text that us
executed as a unit (denoted by line indentation) A function
body is also a block. In python, a block is executed in an
execution frame.
An execution frame contains:
• Some internal information(used for debugging)
• Name of the function
• Value passed to function
• Variables created within function
• Information about the next instruction to be executed
Whenever a function call statement is encountered, an
execution frame for the called function is created and the
control (program control) is transferred to it. Within the
function’s execution frame, the statements in the function-
body are executed, and the return statement or the last
statement of function body, the control returns to the
statement wherefrom the function was called, i.e., as:
def func():
:
return
#__main__
: Last statement of the functioon
definition will send the control
func() back to wherefrom the function
Function call will was called
send the control- print(…)
flow to the function
definition
Arguments and Parameters
• Arguments: Python refers to the values being passed as
arguments.
• Parameters: Values being received as parameters

• So you can say that arguments appear in function call


statement and parameters appear in function header.
Arguments in python can be one these values type:
 Literals
Variables
Expressions

But the parameters in python have to be some variables to


hold incoming values.

• The alternative names for argument are actual


parameter and actual argument.
• The alternative names for parameter are formal
parameter and formal argument.
def multiply (a,b):
print(a*b)
The following are some valid function call statements:

multiply(3,4) #both literals arguments

P=9
multiply(p,5) #one literal and one variable argument

multiply(p,p+1) #one variable and one expression argument

But a function header like the one shown below is invalid:


def multiply(a+1,b,): # Error! A function header
cannot have expression. It can have just names or
identifiers to hold the
incoming values.
:
Passing Parameters

Python supports three types of formal arguments/parameters:


1. positional arguments(Required arguments)
2. Default arguments
3. Keywords(or named )arguments
Positional Arguments
def check(a,b,c):
:
:
Then possible function call for this can be:
Check(z,y,x) #3 values(all variables)passed
Check(2,x,y) #3 values(literal+variable)passed
Check(2,5,7) #3 values (all Literals)passed

i.e., the first parameter receives the value of first


argument, second parameter, the value of second argument
and so on.,
1. In function call 1 above:
•a will get value of x;
•b will get value of y;
•c will get value of z

2. In function call 2 above:


•a will get value of 2;
•b will get value of x;
•c will get value of y

3. In function call 2 above:


•a will get value of 2;
•b will get value of x;
•c will get value of y

Thus, through such function call,


 The arguments must be provided for all parameters(Required).
 The values of arguments are matched with parameters, position (order) wise
(positional).
Default Arguments
def interest( prin, time, rate=0.1 ):

Now, if any function call appear as follows:


interest(5400,2) # third argument missing

Or
interest(5400,2,0.15) #no argument missing
That means the defualt values (values assigned
in function header) are considered only if no
values is provided for that parameter in the
function call statement.
Following are examples of function headers with
default values:
• def interest(prin, time, rate=0.10): #legal

• def interest(prin, time=2, rate):


#illegal(default parameter before required
parameter)

• def interest(prin=2000, time, rate):


• #illegal(default parameter before required
parameter)
• def interest(prin, time=2, rate=0.10):#legal
• def interest(prin=200, time=2, rate=0.10):
#legal
Keyword (named) Arguments
• you can write any argument in any order provided
you name the arguments when calling the function, as
show below:

Interest (prin=2000, time=2, rate=0.10)

Interest (time=2, prin=2000, rate=0.10)

Interest (time=2, rate=0.10, prin=2000)


Program 3.2

Program to calculate simple interest using a


function interest() that can receive principal
amount, time and rate and returns calculated
simple interest. Do specify default values for
rate and time as 10% and 2 years respectively.
RETURNING VALUES FROM FUNCTIONS

• There can broadly two types of function in Python:


1. Functions returning some values(non-void functions)
2. Functions not returning any value(void functions)
Functions returning some value (Non-void functions)

• The functions that return some computed result in terms


of a value, fall in this category. The computed value is
returned using return statement as per syntax:

return <value>

• The value being returned can be one of the following:


1. A literal
2. A variable
3. An expression
For example, following are some legal return statements:
1. return 5
2. return 6+4
3. return a
4. return a**3
5. return (a+8**2)/b
6. return a+b/c
• When you call a function that is returning a value, the returned value is made available to the
caller function/program by internally substituting the function call statement. Confused? Well,
don’t be.

Suppose if we have a function:

def sum(x,y):
s=x+y
return s
And we are invoking this functions as:

Result=print(sum(5,3)) #the returned value from sum()


will replace this function call
• After the function call to sum() function is successfully completed, (i.e.,
the return statement of function has given the computed sum of 5 and 3) the
returned value(8 in our case )will internally substitute the function call
statement. This is, now the above statement will become(internally):

• Result=8 # this is the returned value after successfully


completion of sum(5,3), thus result will now store
value 8
Returning Multiple Values
Python lets you return more than one value from a function.

To return multiple values from a function, you have to


ensure following things:
1. The return statement inside function body should be of
the form given below:

return <value1/expression1/variable1>, <value2/expression2/variable2>,.


2. The function call statement should receive
or use the returned values in one of the
following ways:

a. Either receive the returned values in form a tuple


variable, i.e., as shown below

def squared(x,y,z):
return x*x,y*y,z*z
t=squared(2,3,4)
print(t)
b. Or you can directly unpack the received values of tuple
by specifying the same number of variables on the lef-hand
side of the assignment in function call, e.g:

def squared(x,y,z):
return x*x,y*y,z*z
v1,v2,v3=squared(2,3,4)
print(“The returned values are as under:”)
print(v1,v2,v3)
Program 3.3: program that receives two numbers
in a function and returns the result of all
arithmetic operations(+,-,*,/,%) on these
numbers.
Scope of Variable
• In programming terms, we can say that, scope
refers to part(s) of program within which a
name is legal and accessible.
• There are broadly two kinds of scope in
Python:

1. Global Scope
2. Local Scope
Global Scope
• A name declared in top level segment
(__main__) of a program is said to have a
global scope and is usable inside the whole
program and all block (function, other block)
contained within the program.

• A global variable is a variable defined in the


‘main’ program (__main__ section). Such
variables are said to have global scope.
Local Scope
• A name declared in a function-body is said to
have local scope i.e., it can be used only
within this function and the other blocks
contained under it. The names of formal
arguments also have local scope

• A local variable is a variable defined within


a function. Such variables are said to have
local scope.
Scope Example 1
• Consider the following Python program:
Scope Example 2
• Consider the following Python program:
First Assignment
1. 3.8.1 Name Resolution (Resolving Scope of a Name).
2. 3 Cases. Page number: 112-115

Note: write one example for each cases and submit it


before next Wednesday class through email.

E-mail : [email protected]
Mutability/Immutability of Arguments/Parameters and
Function Calls
• Sample Code 1.1
• Passing an immutable Type Value to a function.

You might also like