Working With Functions
Working With Functions
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
:
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__)
P=9
multiply(p,5) #one literal and one variable argument
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
return <value>
def sum(x,y):
s=x+y
return s
And we are invoking this functions as:
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.
E-mail : [email protected]
Mutability/Immutability of Arguments/Parameters and
Function Calls
• Sample Code 1.1
• Passing an immutable Type Value to a function.