FUNCTIONS
Introduction to Functions
• Function: group of statements within a program that perform as specific
task
• Usually one task of a large program
• Functions can be executed in order to perform overall program task
• Known as divide and conquer approach
• Modularized program: program wherein each task within the program is in
its own function
Benefits of Modularizing a Program with Functions
• The benefits of using functions include:
• Simpler code
• Code reuse
• write the code once and call it multiple times
• Better testing and debugging
• Can test and debug each function individually
• Faster development
• Easier facilitation of teamwork
• Different team members can write different functions
Void Functions and Value-Returning Functions
• A void function:
• Simply executes the statements it contains and then terminates.
• A value-returning function:
• Executes the statements it contains, and then it returns a value back to
the statement that called it.
• The input, int, and float functions are examples of value-returning
functions.
Python Functions
There are two kinds of functions in Python.
- Built-in functions that are provided as part of Python - print(),
input(), type(), float(), int() ...
- Functions that we define ourselves and then use
• We treat function names as “new” reserved words
(i.e., we avoid them as variable names)
Function Definition
• In Python a function is some reusable code that takes arguments(s)
as input, does some computation, and then returns a result or
results
• We define a function using the def reserved word
• We call/invoke the function by using the function name,
parentheses, and arguments in an expression
Syntax:
def function_name(parameters):
statements
return value
Defining and Calling a Function
• Functions are given names
• Function naming rules:
• Cannot use key words as a function name
• Cannot contain spaces
• First character must be a letter or underscore
• All other characters must be a letter, number or underscore
• Uppercase and lowercase characters are distinct
• Function name should be descriptive of the task carried out by the function
• Often includes a verb
Defining and Calling a Function (cont’d.)
• Function definition: specifies what function does
def function_name():
statement
statement
• Function header: first line of function
–Includes keyword def and function name, followed by parentheses
and colon
• Block: set of statements that belong together as a group
–Example: the statements included in a function
• Call a function to execute it
• When a function is called:
• Interpreter jumps to the function and executes statements in the block
• Interpreter jumps back to part of program that called the function
• Known as function return
Local Variables
• Local variable: variable that is assigned a value inside a function
• Belongs to the function in which it was created
• Only statements inside that function can access it, error will occur if
another function tries to access the variable
• Scope: the part of a program in which a variable may be accessed
• For local variable: function in which created
• Local variable cannot be accessed by statements inside its function which
precede its creation
• Different functions may have local variables with the same name
• Each function does not see the other function’s local variables, so no confusion
Passing Arguments to Functions
• Argument: piece of data that is sent into a function
• Function can use argument in calculations
• When calling the function, the argument is placed in parentheses following the
function name
Simple Function Example
def greet():
print("Hello, Welcome to Python")
greet() Function with Return Value
Function with Parameters def square(n):
return n * n
def add(a, b):
print(a + b)
result = square(5)
print(result)
add(10, 20)
def student(name, marks):
print("Name:", name)
print("Marks:", marks)
student("Rahul", 85)
Default Arguments
def greet(name="Student"):
print("Hello", name)
greet()
greet("Anita")
Arguments passed using parameter names
def details(name, age):
print(name, age)
details(age=20, name="Ravi")
Variable Length Arguments (*args)
def total(*numbers):
s=0
for n in numbers:
s += n
print(s)
total(10, 20, 30)
Lambda (Anonymous) Functions
• Small, one-line functions
• No function name
square = lambda x: x * x
print(square(6))
Scope of Variables x = 10
def show():
• Local Variable – declared inside function x=5
• Global Variable – declared outside function print(x)
show()
print(x)
Modifying Global Variables Inside a Function
• By default, one cannot modify a global variable inside a function without declaring
it as global.
• If you try, Python will raise an error because it treats variable as local.
• To modify a global variable use the global keyword.
Without global (causes error) With global (works correctly)
s = "Python is great!"
def fun(): def fun():
s += ' University’ global s
print(s) s += 'Easy'
print(s)
s = "I love Silicon" s = "Python Programing"
fun() print(s)
fun()
print(s)
Recursive Function
• Function calling itself
def factorial(n):
if n == 1:
return 1
return n * factorial(n-1)
print(factorial(5))
Returning Multiple Values in Python
• In Python, a function can return more than one value at a time using commas.
• These values are usually returned as a tuple.
• This is useful when a function needs to give back several related results
together.
def fun():
return "Silicon", 20
s, x = fun()
print(s)
print(x)
Silicon
20