[go: up one dir, main page]

0% found this document useful (0 votes)
26 views27 pages

Functions

Uploaded by

qasemb156
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
26 views27 pages

Functions

Uploaded by

qasemb156
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 27

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.

• A function is a block of code which only runs when it is called.


• You can pass data, known as parameters, into a function.
• A function can return data as a result.
syntax
• The syntax for a function definition is:

def <NAME>( <PARAMETERS> ):


<STATEMENTS>

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.

# now that we have the function above, let us call it.


toInvest = float(input("How much do you want to invest?"))
fnl = final_amount(toInvest, 0.08, 12, 5)
print("At the end of the period you'll have", fnl)
Variables and parameters are local
• When we create a local variable inside a function, it only exists inside
the function, and we cannot use it outside.

• From previous example, if we try to use variable a, outside the


function, we’ll get an error.

• The variable a is local to final_amount, and is not visible outside the


function.
• Additionally, a only exists while the function is being executed—we
call this its lifetime. When the execution of the function terminates,
the local variables are destroyed.
• Parameters are also local, and act like local variables. For example, the
lifetimes of p, r, n, t begin when final_amount is called, and the
lifetime ends when the function completes its execution.
• So it is not possible for a function to set some local variable to a
value, complete its execution, and then when it is called again next
time, recover the local variable. Each call of the function creates new
local variables, and their lifetimes expire when the function returns to
the caller.
Arbitrary Arguments, *args
• If you do not know how many arguments that will be passed into your
function, add a * before the parameter name in the function
definition.
• This way the function will receive a tuple of arguments, and can
access the items accordingly.
Example:
def my_function(*kids):
for i in kids:
print("The child name is " + i)

my_function("Ahmad", "Rami", "Ali")


Arbitrary Keyword Arguments, **kwargs
• If you do not know how many keyword arguments that will be passed
into your function, add two asterisk: ** before the parameter name in
the function definition.

• 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(fname = “Rami", lname = “Ali")


Default Parameter Value
• The following example shows how to use a default parameter value.
• If we call the function without argument, it uses the default value:
• Example:
def my_function(country = "Norway"):
print("I am from " + country)

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.

• E.g. if you send a List as an argument, it will still be a List when it


reaches the function.
Example:
def my_function(food):
for x in food:
print(x)

fruits = ["apple", "banana", "cherry"]

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("\n\nRecursion Example Results")


tri_recursion(6)
• In this example, tri_recursion() is a function that we
have defined to call itself ("recurse"). We use
the k variable as the data, which decrements (-1) every
time we recurse. The recursion ends when the condition
is not greater than 0 (i.e. when it is 0).
Example:
• 4! = 4 * 3!
• 3! = 3 * 2!
• 2! = 2 * 1

• Replacing the calculated values gives us the following expression


• 4! = 4 * 3 * 2 * 1
Python code
def factorial(n):
if n == 1:
return 1
else:
return n * factorial(n-1)
How it’s work
def factorial(n):
print("factorial has been called with n = " + str(n))
if n == 1:
return 1
else:
res = n * factorial(n-1)
print("intermediate result for ", n, " * factorial(" ,n-1, "): ",res)
return res

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.

You might also like