Sie sind auf Seite 1von 20

Functions are common to all programming languages and it can be defined as a block of re-usable code

to perform specific tasks. Python itself is huge library of built-in functions . These functions perform a
predefined task and can be called upon in any program, as per requirement. But sometimes if you
don’t find such utility function, then it should be built-in by the user. These type of functions are called
user-defined functions.

What is User-Defined Function?


A function is a piece of code in a program. A function performs a specific task. A function is used by
invoking it via a function call. For example; let us consider a method called math.sqrt():

Class name
Method name
import math Parameter/argument

y = math.sqrt(144.0)
When this statement is executed, the method math.sqrt is called to calculate the square root of
the number contained in the parenthesis (144.00).
Advantages of User-Defines Functions
Functions in Python are first-class citizens. It means that functions have equal status with other objects in
Python. The major advantages of UDFs are:

 Reduces duplication of code. Functions can make a program smaller by eliminating repetitive code.
Later, if you want to make a change, you have to make it only at one place. Once you write and
debug, you can reuse it.
 Breaking up of complex problems into simpler pieces. Dividing a long program into functions allows
you to debug the parts one at a time and then assemble them into a working whole.
 Improved clarity of the code. Creating a new function gives you an opportunity to name a group of
statements, which makes your program easier to read and debug.
 Hiding information. Functions hide vital information into main program.
 Assignments. Functions can be assigned to variables, stored in collections or passed as arguments.
This brings additional flexibility to the language.
 Called many times. When you define a function, you specify the name and the sequence of
statements which can be called many times.
Defining UDFs
In Python a user-defined function's declaration begins with the keyword def and followed by the
function name and a parentheses [ ( ) ].
Function Header
The general format is:
Function body
def function_name ([formal_parameters]):
...
statements-to-be-executed
...
[return <value(s)>]
Indented area
Here,
 The first line of the function definition is called the header; the rest is called the body. The function is declared with
the keyword def. The function header has to end with a colon (:) and the body has to be indented.
 The function_name must be a user-defined name or an identifier or variable name.
 The format_parameters or arguments (which is placed in square braces ([ ])) are optional. Parameters are specified
within the pair of parentheses in the function definition, separated by commas.
 When you provide formal parameters as placeholders they accept values sent to them by the calling function. When
a function is called, the parameters that are passed to it are called actual parameters.
 The body of the function consists of one or more Python statements with at least — 4 spaces indentation.
 The return statement is optional. If you want to return a value or values, then use return with the value/values by
separating comma.
 To end the function body, you have to enter an empty line in interactive mode but this is not necessary in a script
mode.
Declaring UDF at Interactive Mode
A function can be written in an interactive mode or in a script mode. The following function is written in
interactive mode:
>>> def hello():
print (“Hello World!”)
print (“Hello from my function!”)

Calling an UDF
Declaring UDF as Module
The modules in Python have the .py extension. You can create your own Python modules since modules
are comprised of Python .py files.
To create a module,
• Click Ctrl+N to open the python Editor window.
• Type the following:
def hello():
print (“Hello World!”)
print (“Hello from my function!”)
hello() # Calling the module
Function called
• Save the file as Demo.py.
• Execute the file.

A function at
interactive mode

Function called with the name of the


function and displays the output

Hello.py program output


Invoking/Calling Function
A user-defined function does not execute on its own. It must be called in somewhere. A user-defined
function can be invoked like any other function in Python. We can call a function by writing,
 the function name
 the values passed to it (if parameter is declared), that are to be accepted by its arguments, enclosed
within the parentheses
 The syntax for calling the new function is the same as for built-in functions.
We can call a function:
 In the same program where the function is declared.
 Using import directives.

Calling a function in same program

To execute the function, you can call the function the name within parentheses. The general
format is:

def hello() : # parent function


….
….

hello() # Function call

Primary function
executed first
Continues…
Let us see the previous example :

Primary function called

Press F5 key to execute the Demo.py When we Execution style of hello() function
execute the script with F5 key, it will produce the two
line output immediately at Python Shell window: 2. Control transferred into function
Hello World!
Hello from my function!
def hello() :
3. Function body statements
How does the function executed? executed

When F5 key is pressed: print ("Hello World!")


print ("Hello from my function!")
 The function hello() is invoked.
 Then the control passes to hello() function.
 Inside the body of the function hello(), the hello()
Python statement lines are executed. 1. Main program execution started
 Finally, the function produces two lines of result. here
Example: Write a program to demonstrate a simple function (called as void function)
declaration to find the sum of two numbers.

# A simple function call to find sum of two numbers


# Declares the function body 2. Control transferred into function

def Add_TwoNum():
X = int(input("Enter first number: "))
Y = int(input("Enter second number: "))
Result = X + Y 3. Function body statements executed

print ("The sum of %d and %d is %d" % (X, Y, Result))

Add_TwoNum()
1. Main program execution started here

Output:
Save the file as Test.py and Press F5 key and do the following at interactive mode:
>>> Add_TwoNum()
Enter first number: 34
Enter second number: 51
The sum of 34 and 51 is 85
Using import statement
You can use any Python source file as a module by executing an import statement in some other
Python source file or in interactive mode. To import our previously defined module Test we type the
following in the Python interactive prompt.

Import the module Test.py


>>> import Test

Here, import Test imports the module Test and creates a reference to that module in the current
namespace. From the caller, objects in the Test module are only accessible when prefixed with
<module_name> via dot notation (.) as shown in the figure given below:

Dot (.) notation


Importing module as an alternate name

Python has the provision to import entire module under an alternate name. The syntax is:
import <module_name> as <alt_name>
For example:
>>> import Test as T # T as alternate name of the module pandas
>>> T.Add_TwoNum()
Enter first number: 34
Enter second number: 51
The sum of 34 and 51 is 85
Function Returning Value(s)
A function that returns a value is called a fruitful function. The opposite of a fruitful function is a void
function.
The return keyword is used to return values from a function. A function may or may not return a value. If
a function does not have a return keyword, it will send a None value, i.e., equivalent to return None.
None is a special type in Python that represents nothingness. For example, it is used to indicate that a
variable has no value if it has a value of None.

Let us see a simply example to calculate sum of two numbers using a function called Add_TwoNum():

def Add_TwoNum():
X = int(input("Enter first number: "))
Y = int(input("Enter second number: "))
return X + Y Returns the sum of X and Y

Result = Add_TwoNum()
print ("The sum is:", Result)
Enter first number: 34
Enter second number: 51
The sum is: 85
Returning more than one values
We can return more than one value from a function. The objects, after the return keyword, are
separated by commas. For example, suppose a list called Marks contains five subject marks like
[98, 67, 87, 89, 87] and you want to find the total (MarkSum) and percentage (MarkPer) of a
student’s marks using function by returning more than one value.
So the program code is:

Function returning two values

Returned values received through two variables


Try this:
Rewrite the following code after removing the syntactical errors (if any). Underline each
correction.
def chksum:
x=input("Enter a number")
if (x%2 = 0):
for i range(2*x):
print (i, end = ' ')
loop else:
print ("#", end = ' ')

Rewrite the following code after removing the syntactical errors (if any). Underline each
correction.
def add(j):
if (j >= 4):
j=j*j
return j
else:
j = j*2;
return j
def main():
i=4
a=add(4)
print("The value of a is: %d" %a)
main()
Function Arguments
Parameters are the variables that are defined or used inside parentheses while defining a function,
whereas arguments are the value passed for these parameters while calling a function. Arguments are the
values that are passed to the function at run-time so that the function can do the designated task using
these values.

Function Parameters
Function body
def function_name ( arg1, arg2, …. ):
...
statements-to-be-executed
...
[return <value(s)>]
..........................................
..........................................

function_name ( arg1, arg2, …. ):

Function Arguments
Function argument continues…
Now that you know about Python function arguments and parameters, let’s have a look at a simple
program to highlight more before discussing the types of arguments that can be passed to a function.

# Defining a function to display a message using parameter


def ShowMessage(Msg) : # A function with a parameter
print('Message is:', Msg)

# Calling the function and supplying arguments


ShowMessage("Hello Friends!") # Calling function with an argument "Hello Friends!"
Message is: Hello Friends!

Or
# Defining a function first to return the value of parameter
def ShowMessage(Msg) : # A function with a parameter
return Msg
# Calling the function and supplying arguments
print ("Message is:", ShowMessage("Hello Friends!")) # Calling function with argument "Hello Friends!"
Message is: Hello Friends!
Try this:
Find out the error, if any, in the following program and Rewrite the following code in Python after
write the correct line of code. removing all syntax error(s). Underline each
def sum( arg1, arg2 ): correction done in the code.
total = arg1 + arg2; def Sum(Count) #Method to find sum
print ("Inside the function local total : ", total) S=0
return total; for I in Range(1, Count+1):
def main(): S+=1
n1=int(input("First value is:")) RETURN S
n2=int(input("Second value is :")) print Sum[2] #Function Calls
sum(n1); print Sum[5]
print ("The sum is:", total)
main()
Write the output of the following program: Rewrite the following Python program after
def func(x, y = 10): removing all the syntactical errors (if any),
if ( x % y == 0): underlining each correction:
x=x+1 def checkval:
return x x = input("Enter a number")
else: if x % 2 = 0 :
y=y–1 print (x,"is even")
return y else if x<0 :
def main(): print (x,"should be positive")
p, q = 20, 23 else ;
q = func (p, q) print (x,"is odd“)
print("%d \t %d" % (p, q))
p = func(q);
print("%d \t %d" % (p, q))
q = func(p);
print("%d \t %d" % (p, q))
main()
Programming example : Fibonacci numbers

Write a program to create a module called Fibonacci.py with two function definitions to find the
Fibonacci series up to n. The two function definitions are:
 def fibnos1(n) to write Fibonacci series up to n
 def fibnos2(n) which return Fibonacci series up to n
Note. n is the parameter whose Fibonacci series will be generated.
In Python interactive mode, find the Fibonacci series for 100 implementing two function definitions.

# Fibonacci.py
# Two Fibonacci numbers module
def fibnos1(n): # write Fibonacci series up to n
a, b = 0, 1
while b < n:
print(b, end=' ') # prints each number
a, b = b, a+b
print()
def fibnos2(n): # return Fibonacci series up to n
series = [] # a list
Output:
a, b = 0, 1
while b < n: >>> import Fibonacci as F
>>> F.fibnos1(100)
series.append(b) # Nos. are appended into a list
1 1 2 3 5 8 13 21 34 55 89
a, b = b, a+b >>> F.fibnos2(100)
return series [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
Programming example : Convert Celsius temperature to Fahrenheit.

Write a program to convert Celsius temperature to Fahrenheit. The function should pass the Celsius
value as required argument.

Hints: def rectangle(length, breadth):


# Calculate the requirements
......................
......................
return Area, Perimeter
# Areaperimeter.py
l = int(input("Enter length of rectangle: "))
b = int(input("Enter breadth of rectangle: "))
rectangle(l) # Intentionally one argument is missing

What will happen if you execute the above code?


Programming example : Area and Perimeter of a rectangle.

Write a program to find the area and perimeter of a rectangle using function def C2F(C) with
required arguments.
F = C * 9/5 + 32

Programming example : Finding the place names which are more than 5 characters.

Write definition of a Method COUNTNOW(PLACES) to find and display those place names, in which
there are more than 5 characters.
For example:
If the list PLACES contains
["DELHI","LONDON","PARIS","NEW YORK","DUBAI"]
The following should get displayed
LONDON
NEW YORK
Try this:
Rewrite the following code after removing the syntactical errors (if any). Underline each correction.

def chksum:
x=input("Enter a number")
if (x%2 = 0):
for i range(2*x):
print (i, end = ' ')
loop else:
print ("#", end = ' ')

Das könnte Ihnen auch gefallen