0% found this document useful (0 votes)
3 views

Chapter 03 - Functions

The document is a lecture on functions in computer science, covering topics such as abstraction, function definitions, calling functions, and variable scope. It explains the importance of functions in modular programming, how to implement them, and the use of built-in library functions. Additionally, it discusses local and global variables, return values, and the structure of function calls.

Uploaded by

r975kumar
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

Chapter 03 - Functions

The document is a lecture on functions in computer science, covering topics such as abstraction, function definitions, calling functions, and variable scope. It explains the importance of functions in modular programming, how to implement them, and the use of built-in library functions. Additionally, it discusses local and global variables, return values, and the structure of function calls.

Uploaded by

r975kumar
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 25

COL100

Introduction to Computer Science


Chapter 3 – Function

Aadi & Viresh Semester II


CSE@IITD 2024-2025
Agenda
• Abstraction

• Print Function

• Defining Function

• Calling Function

• Variable Scope

Disclaimer: The contents of these slides are taken from various publicly available resources such as books, talks
and lectures. They are being used for the purpose of classroom teaching and academic dissemination only. The
sources are acknowledged wherever possible.

COL100: Introduction to Computer Science (Semester II, 2024-2025) 2


Recall Computational Model
• Primitive operations which are the simplest calculations that can made

• Combination methods which specify how the primitive operations can be combined with
one another to obtain a compound operation

• Abstraction methods which specify how compound operations can be utilized as


individual units

COL100: Introduction to Computer Science (Semester II, 2024-2025) 3


Abstraction
• Specifying the solution crisply and concisely in terms of problems known to be solvable

• Separating logical sub-problems

• Avoiding repetitions of copies of similar solutions

COL100: Introduction to Computer Science (Semester II, 2024-2025) 4


How to Implement Abstraction
• One of the ways is to use functions.

• What is a function?

• A large program is divided into basic building blocks called functions.

• A function contains set of statements which perform specific operation in a program.

• In essence, a program can be considered to be a collection of these functions.

COL100: Introduction to Computer Science (Semester II, 2024-2025) 5


Why Functions?
• Allows one to develop a program in a modular fashion
• Divide-and-conquer approach
• Construct a program from small pieces or components

• Use existing functions as building blocks for new programs

• Abstraction: hide internal details (library functions)

COL100: Introduction to Computer Science (Semester II, 2024-2025) 6


Function Terminology
• Function Definition
• This contains all the statements to be executed.

• Function Call
• This calls the actual function.

COL100: Introduction to Computer Science (Semester II, 2024-2025) 7


Print Function
• Performs output to the standard output a = 5
device (typically the screen). b = 10
avg = (a+b)/2
• Syntax print("Average of", a, "and", b,
• print(arg1, arg2, …, argn) "is", avg);

• Arguments arg1, arg2, …, argn


represent list of arguments whose
values are to be printed.

COL100: Introduction to Computer Science (Semester II, 2024-2025) 8


Extend Print Functionality
• We can use a function to extend the def my_print(name):
functionality of the default print print(name)
function.
print(“Faculty Member”)
print(“IITD”)

my_print(“Vireshwar”)
my_print(“Amit”)
my_print(“Shashank”)

COL100: Introduction to Computer Science (Semester II, 2024-2025) 9


Function Argument
• Arguments can be of any type, even def func_a():
functions. print("inside func_a")
def func_b(y):
• Python returns the value None, if no print("inside func_b")
return statement is given. return y
def func_c(z):
print ("inside func_c")
return z()
print(func_a())
print(func_b(2))
print(func_c(func_a))

COL100: Introduction to Computer Science (Semester II, 2024-2025) 10


Input Function
• It prints whatever is in the quotes. text = input(“Type anything...
”)
print(text)
• The user types something and hits enter.

num = int(input("Type a
• The returned value can be assigned to a
number... "))
variable.
print(num+1)

• The returned value is a string which must


be casted to an appropriate type.

COL100: Introduction to Computer Science (Semester II, 2024-2025) 11


Function Definition
• The first line contains the function name, def square(x):
and optionally a set of comma-separated y = x * x
arguments enclosed in parentheses.
return y

• The arguments are called formal


arguments or formal parameters.

• The body of the function is a block of


statements that defines the action to be
taken by the function

COL100: Introduction to Computer Science (Semester II, 2024-2025) 12


Return Value
• A function can return a value using return def square(x):
statement.
y = x * x

• The return value has a type.


return y

• The function being called is said the callee var = 3


function.
var_square = square(var)
print(var_square)
• Place in the program where a callee
function is called from is said the caller
function.

• The return value from a callee function can


be assigned to a variable in the caller
function.

COL100: Introduction to Computer Science (Semester II, 2024-2025) 13


Return Statement
• In a value-returning function (result type def square(x):
is not None), return statement does two y = x * x
distinct things
return y
• specify the value returned by the
execution of the function

• terminate execution of the callee and


transfer control back to the caller.

COL100: Introduction to Computer Science (Semester II, 2024-2025) 14


Return Statement
• A function might contain more than one def square(x):
return statement. y = x * x
return y
• Writing return statement is optional at the print(y)
end of the function body.

• return may also be used to terminate


execution of the function explicitly.

• No statement that needs to be executed


should appear following return.

COL100: Introduction to Computer Science (Semester II, 2024-2025) 15


Returning Control Back to Caller
• If there is no return statement
• execute until the last statement of the function body
• return None

• If there is a return statement


• return expression;

COL100: Introduction to Computer Science (Semester II, 2024-2025) 16


Calling a Function
• Called by specifying the function name def square(x):
and parameters in an instruction in the y = x * x
calling function.
return y

• When a function is called from some


other function, the corresponding def calc_func(x,y):
arguments in the function call are called u = square(x) + square(y)
actual arguments or actual parameters.

z = calc_func(3,5)
• A value-returning function can be called
by including it in an expression.

COL100: Introduction to Computer Science (Semester II, 2024-2025) 17


Calling a Function
• The function call must include a matching def square(x):
actual parameter for each formal
parameter. y = x * x
return y
• Position of an actual parameters in the
parameter list in the call must match the
position of the corresponding formal def calc_func(x,y):
parameter in the function definition.
u = square(x) + square(y)

• The names of formal and actual arguments


may or may not differ. z = calc_func(3,5)

• When the function is executed, the value of


the actual parameter is copied to the formal
parameter.

COL100: Introduction to Computer Science (Semester II, 2024-2025) 18


Tracking Program Control Flow
def square(x):
• The program starts reading the y = x * x
statements from the first line. print("square function: x =", x)
print("square function: y =", y)
return y
• The program execution starts at the first
statement of the main function. def calc_func(x,y):
print("calc_func function: x =", x)
print("calc_func function: y =", y)
u = square(x) + square(y)
return u

# Main program - main function


x = 3
y = 5
print("main function: x =", x)
print("main function: y =", y)
z = calc_func(x,y)
print("main function: z =", z)

COL100: Introduction to Computer Science (Semester II, 2024-2025) 19


Constraints on Function Calls
• The function has to be defined before being called.

• Nested function calls are allowed: A calls B, B calls C, C calls D, etc.

• The function called last will be the first to return.

• A function can also call itself, either directly or in a cycle


• A calls B, B calls C, C calls back A.
• Called recursive call or recursion (more on this in later lectures)

COL100: Introduction to Computer Science (Semester II, 2024-2025) 20


Parameter Scope
• Scope is mapping of names to objects. def increment(x):
x = x + 1
• It is part of the program from which the print('Inside function
value of the variable can be used (seen) increment(x): x =', x)
return x
• A new scope/frame/environment is x = 3
created when a function is executed z = increment(x)
print('In the main function: x
=', x)

COL100: Introduction to Computer Science (Semester II, 2024-2025) 21


Local variables
def increment(x):
• The identifiers used as formal parameters x = x + 1
in a function are “local”.
print('Inside function
• A function can define its own local increment(x): x =', x)
variables.
return x

• The locals have meaning only within the


function. They are not recognized outside x = 3
the function.
z = increment(x)
• Local variables cease to exist when the print('In the main function: x
function returns. =', x)

• Each execution of the function uses a new


set of locals.

COL100: Introduction to Computer Science (Semester II, 2024-2025) 22


Global Variable
• Scope is entire program by default def g(y):
print(x)
• Inside a function, we can use global print(x + 1)
variables, but it is not recommended.

x = 5
g(x)
print(x)

COL100: Introduction to Computer Science (Semester II, 2024-2025) 23


Library Functions
• Set of functions already written for you, and bundled in a “library”

• Example: print, input

COL100: Introduction to Computer Science (Semester II, 2024-2025) 24


Math Library Functions
• Math library functions perform common mathematical calculations.

• To use this library, we must import the math library in the program.

• Example:
• Function sqrt, which returns the square root of its argument, can be utilized after
importing the math library.

COL100: Introduction to Computer Science (Semester II, 2024-2025) 25

You might also like