Functions
Functions
Functions
• In Python, a function is a named sequence of statements that belong
together. Their primary purpose is to help us organize programs into
chunks that match how we think about the problem.
We can make up any names we want for the functions we create, except that we can’t use
a name that is a Python keyword, and the names must follow the rules for legal identifiers.
There can be any number of statements inside the function, but they have to be indented
from the def. In the we will use the standard indentation of four spaces. Function
definitions are the second of several compound statements we will see, all of which have
the same pattern:
1. A header line which begins with a keyword and ends with a colon.
2. A body consisting of one or more Python statements, each indented the same
amount—the Python style guide recommends 4 spaces— from the header line.
Creating and Calling a Function
• In Python a function is defined using the def keyword.
• To call a function, use the function name followed by
parenthesis.
• Example:
def my_function():
print("Hello from a function")
my_function()
Functions that require arguments:
• Example:
print(abs(-5))
print(pow(2, 3))
print(max(4, 1, 17, 2, 12))
print(min(3 * 11, 5**3, 512 - 9, 1024**0))
• if we want to find the absolute value of a number, we have to indicate what the number is. Python has a
built-in function for computing the absolute value.
• Some functions take more than one argument. For example the built-in function pow takes two arguments,
the base and the exponent. Inside the function, the values that are passed get assigned to variables called
parameters.
Functions that return values
• All the functions in the previous slide return values. Calling each of
these functions generates a value, which we usually assign to a
variable or use as part of an expression.
• Example: biggest = max(3, 7, 2, 5)
• A function that returns a value is called a fruitful function. The opposite of a fruitful function is void function
— one that is not executed for its resulting value, but is executed because it does something useful.
(Languages like Java, C#, C and C++ use the term “void function”, other languages like Pascal call it a
procedure.) Even though void functions are not executed for their resulting value, Python always wants to
return something. So if the programmer doesn’t arrange to return a value, Python will automatically return
the value None.
Example:
def final_amount(p, r, n, t):
a = p * (1 + r/n) ** (n*t)
return a # This is new, and makes the function fruitful.
• This way the function will receive a dictionary of arguments, and can
access the items accordingly.
Example:
def my_function(**kid):
print("His last name is " + kid["lname"])
my_function("Sweden")
my_function("India")
my_function()
my_function("Brazil")
Passing a List as an Argument
• You can send any data types of argument to a function (string,
number, list, dictionary etc.), and it will be treated as the same data
type inside the function.
my_function(fruits)
The pass Statement
• function definitions cannot be empty, but if you for some reason have a
function definition with no content, put in the pass statement to avoid
getting an error.
• Example:
def myfunction():
pass
print("Hi")
myfunction()
Recursion
Recursion
• Python also accepts function recursion, which means a
defined function can call itself.
• Recursion is a common mathematical and programming
concept. It means that a function calls itself. This has the
benefit of meaning that you can loop through data to reach
a result.
• The developer should be very careful with recursion as it
can be quite easy to slip into writing a function which never
terminates, or one that uses excess amounts of memory or
processor power. However, when written correctly recursion
can be a very efficient and mathematically-elegant approach
to programming.
Example:
def tri_recursion(k):
if(k>0):
result = k+tri_recursion(k-1)
print(result)
else:
result = 0
return result
print(factorial(5))
Output:
factorial has been called with n = 5
factorial has been called with n = 4
factorial has been called with n = 3
factorial has been called with n = 2
factorial has been called with n = 1
intermediate result for 2 * factorial( 1 ): 2
intermediate result for 3 * factorial( 2 ): 6
intermediate result for 4 * factorial( 3 ): 24
intermediate result for 5 * factorial( 4 ): 120
120
iterative version of the factorial
function
def iterative_factorial(n):
result = 1
for i in range(2,n+1):
result *= i
return result
Conclusion
• Recursion is a way of programming or coding a problem, in
which a function calls itself one or more times in its body.
Usually, it is returning the return value of this function call.
If a function definition fulfils the condition of recursion, we
call this function a recursive function.
Termination condition:
A recursive function has to terminate to be used in a
program. A recursive function terminates, if with every
recursive call the solution of the problem is downsized and
moves towards a base case. A base case is a case, where
the problem can be solved without further recursion. A
recursion can lead to an infinite loop, if the base case is not
met in the calls.