Professional Documents
Culture Documents
Lab No. 9
Objective:
• To understand the function concept in Python
• To learn how to define a function and how to call it
Pre-Lab Reading:
Function:
It is a block of code that performs a specific task. It always return single value to the calling
function. Functions are used to minimize the repetition of code. It can be executed from as many
different parts as required. Optionally it returns a value to the calling program. There are some
properties of a function as discussed below.
• Every function has a unique name. This name is used to call function. A function can be
called from within another function.
• A function is independent and it can perform its task without intervention from or interfering
with other parts of the program.
• A function performs a specific task. A task is a distinct job that a program must perform as a
part of its overall operation, such as adding two or more integers, calculating a cube root, etc.
• A function returns a value to the calling program. This is optional and depends upon the task
the function is going to accomplish.
The syntax of a function is given below:
def Function_Name (Argument1, Argument2,……):
Body of this Function
An optional return Statement(s)
Lab Activity:
1. This program adds two numbers using user defined function add and return the output to the
calling function.
Now what happens, when you remove return z from the previous program, record and explain
the output here:
Scoping:
Each function defines a new name space, also called a scope. To keep track of which variables
can be used, it is sometimes useful to store it in a frame, called stack frame. Each function is
represented by a frame. A frame is a box with the name of a function beside it and the
parameters and variables of the function inside it.
Lab activity:
This program explains the use of same variable x, which has two different values according to
its scope within the program and within the function.
3.
Explain the Output in term what happens to the variable x and the parameter x:
Lab Tasks:
1. Write a function named count_down(a) that takes an input integer value, a, as a parameter
and count down until the value of 'a' is greater than 0. When it gets to zero, it displays the
phrase: countdown is stopped.
2. Write a function named is_even(n) that takes an integer as an argument through input and
returns True if the argument is an even and False if the argument is odd. If the returned
value is True, your program will print you entered even number, and if the returned value is
False your program will print you entered an odd number.
3. Write a function named max(x, y) that take two integer values as an argument and return the
maximum value to a second function called cube (z). This cube(z) function will return the
cubic value of the maximum number, to the main body of program and also, print this cubic
value.