0% found this document useful (0 votes)
75 views37 pages

Alpro Odd 2021 - Week 6A - Function

The document discusses Python functions including: 1) What functions are and how they are defined and called in Python using the def and () syntax. 2) How functions can accept arguments and return values. 3) Lambda or anonymous functions defined using the lambda keyword. 4) How functions can call themselves recursively to loop through and process data. Examples of recursion that count down and calculate sums are provided.

Uploaded by

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

Alpro Odd 2021 - Week 6A - Function

The document discusses Python functions including: 1) What functions are and how they are defined and called in Python using the def and () syntax. 2) How functions can accept arguments and return values. 3) Lambda or anonymous functions defined using the lambda keyword. 4) How functions can call themselves recursively to loop through and process data. Examples of recursion that count down and calculate sums are provided.

Uploaded by

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

1604C011 – ALGORITHM & PROGRAMMING

Function
Week 6A
Program Studi Teknik Informatika
Fakultas Teknik – Universitas Surabaya
01 PYTHON FUNCTIONS
What is a function ?
• 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.
Creating a function
• In Python a function is defined using the def keyword.

Example:

def my_function():
  print("Hello from a function")
Calling a function
• To call a function, use the function name followed by
parenthesis ()

Example:

def my_function():
  print("Hello from a function")

my_function()
Arguments
• Information can be passed into functions as arguments.
• Arguments are specified after the function name, inside the parentheses. You can add as many
arguments as you want, just separate them with a comma.
• When the function is called, we pass along a first name, which is used inside the function to print
the full name.
Example:
A function with one argument : fname
def my_function(fname):
  print(fname + " Refsnes")

my_function("Emil")
my_function("Tobias")
my_function("Linus")

Emil Refsnes
Tobias Refsnes
Linus Refsnes
Arguments
• A parameter is the variable listed inside the parentheses in the function definition.
• An argument is the value that is sent to the function when it is called.
• By default, a function must be called with the correct number of arguments, meaning that if your
function expects 2 arguments, you have to call the function with 2 arguments, not more, and not
less.

Example:
A function with two arguments
def my_function(fname, lname):
  print(fname + " " + lname)

my_function("Emil", "Refsnes")

Emil Refsnes

Note : If you try to call the function with 1 or 3 arguments, you will get an error.
Arbitrary Arguments
• 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:
If the number of arguments is unknown,
def my_function(*kids): add a * before the parameter name
  print("The youngest child is " + kids[2])

my_function("Emil", "Tobias", "Linus")

The youngest child is Linus


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")

I am from Sweden
I am from India
I am from Norway
I am from Brazil
Any data types of 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.
• 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)

apple
banana
cherry
Return Values
• To let a function return a value, use the return statement:

Example:

def my_function(x):
  return 5 * x

print(my_function(3))
print(my_function(5))
print(my_function(9))

15
25
45
02 LAMBDA FUNCTION
Lambda Function
• A lambda function is a small anonymous function.
• A lambda function can take any number of arguments, but can only have one expression.
• The expression is executed and the result is returned.

Syntax :
lambda arguments : expression

• While normal functions are defined using the def keyword in Python,


but anonymous functions are defined using the lambda keyword.
Lambda Function – Example #1
Example:

x = lambda a : a + 10

print(x(5))

15

Add 10 to argument a, and return the result


Lambda Function – Example #2
• Lambda functions can take any number of arguments
Example:

x = lambda a, b : a * b

print(x(5, 6))

30

Multiply argument a with argument b,


and return the result
Lambda Function – Example #3
Anonymous function or lambda function Using normal function
Example: Example:

square = lambda a:a**2 def square(a):


return a**2
square(3)
square(3)
9
9
Example:

(lambda a:a**2)(3)

The expression is evaluated and returned. Lambda functions


can be used wherever function objects are required.
Lambda Function – Example #4
• The power of lambda is better shown when you use them as an anonymous function
inside another function.

Example:

def myfunc(n):
  return lambda a : a * n

mydoubler = myfunc(2)
mytripler = myfunc(3)

print(mydoubler(11)) Say you have a function definition


print(mytripler(11))
that takes one argument, and that
22 argument will be multiplied with an
33 unknown number
Lambda Function – Example #5
Example:

larger=lambda a,b : a if a>b else b

print(larger(3,4))

4
03 RECURSION
FUNCTION
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.
Recursion – Example #1
• 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).
• To a new developer it can take some time to work out how exactly this works, best way to
find out is by testing and modifying it.
Example:

def tri_recursion(k):
  if(k > 0):
    result = k + tri_recursion(k - 1)
    print(result) Recursion Example Results
  else: 1
    result = 0 3
  return result 6
10
print(“Recursion Example Results") 15
tri_recursion(6) 21
Recursion – Example #2
• You are asked to create a recursive function that has
one argument as a number.
• The function will display the inputted numbers, and
are arranged downwards with a value that always
decreases by one to 0

Example:

def show_down(n):
print(n)
4
if n>0: 3
show_down(n-1) 2
1
Show_down(4) 0
Recursion – Example #3
• You are asked to create a recursive Example:
function that has one argument.
• The function will display the inputted def showAndSum(n):
number, and it is arranged sideways with if n>0:
a value that always decreases by one to
if n>1:
0. Then the total number is displayed print(n,end="+")
else:
print(n,end=“")

return n+showAndSum(n-1)
else:
return 0

showAndSum(4)

4+3+2+1
10
Recursion – Example #4
• You are asked to create a recursive
function that has one argument. Example:
• The function will output as follows !
def show(n):
666666 for i in range(n):
55555 print(n,end='')
4444 if n>0:
666666
55555
333 print("")
4444
show(n-1)
22 333
22
1 show(6)
1
if the function is called with code :
show(6)
Recursion – Example #5
• You are asked to create a recursive
function that has two arguments. Example:
• The function will output as follows !
def show(n,p):
666666 for i in range(p-n):
#55555 print('#',end='')
for i in range(n):
##4444 print(n,end='') 666666
###333 #55555
##4444
####22 if n>0: ###333
#####1 print("") ####22
show(n-1,p) #####1
###### ######
if the function is called with code : show(6,6)
show(6,6)
04 EXERCISES
EXERCISE 1
• Create a program using a function to determine the
distance between two points (x1, y1) and (x2, y2) with :

distance = abs(x1-x2) + abs(y1-y2)

Position x1, y1, x2, y2 based on input data.

Example output:
The distance between A(3, 8) and B(7, 2) is 10
EXERCISE 2
• Write a program to create an options Menu and perform area
calculations for two shapes (rectangle, circle).
• Make some functions: menu, calculate the area of ​a rectangle,
calculate the area of ​a circle
• The output of the program is as follows:
EXERCISE 2 Welcome, program to calculate area
====================
Options Menu:
1. Rectangle
2. Circle
Output program, like this: 3. Exit
====================
Enter option: 1
===== Calculate the area of ​a rectangle =====
Input length :2
Input width:5
Area of ​rectangle = 10
====================
Options Menu:
1. Rectangle
2. Circle
3. Exit
====================
Enter option : 2
===== Calculate the area of ​a circle =====
Input radius :10
Area of ​circle = 314.0
====================
Options Menu:
1. Rectangle
2. Circle
3. Exit
====================
Enter option : 3
EXERCISE 3
• Write a program to calculate the factorial of a certain number !

Input :
n=4

Output :
4*3*2*1
Result = 24
EXERCISE 4
• Factorial concept
factorial(N) = N! = 1 * 2 * 3 … *N

• In programming
factorial(N) = N! = N * (N-1) * (N-2) … * 3 * 2 * 1

• Write a program to calculate the factorial of a certain number !


(a) using function
(b) using recursion function
Enter number = 6
0!=1
1!=1
2!=2
Output program, like this: 3!=6
4 ! = 24
5 ! = 120
6 ! = 720
EXERCISE 5
• Write a program to convert x seconds (x=input in seconds) into
minutes if x>= 60 seconds, into hours if x>=3600 seconds and
remains unchanged in seconds if x<60 !

• For example to convert the length of time:

50 seconds is 50 seconds
500 seconds is 8.33 minutes
5000 seconds is 1.39 hours
50000 seconds is 13.89 hours
EXERCISE 6
• There is a quadratic equation ax²+bx+c=0. Find the roots of the
equation using the formula abc. The program uses a function
with input arguments: a,b,c and the function will return the
solution result

• For example :
a= 1
b=-5
c= 6
The solution are:
x1 = 2
x2 = 3
EXERCISE 7
• Write a program that uses a recursive function
to display the following series of numbers !

Input N=10
10
8
6
4
2
EXERCISE 8
• Write a program that uses a recursive function
to display the following series of numbers !

Input N=25
25
20
15
10
5
Total= 75
EXERCISE 9
• Create a lambda function that has three
arguments, where the function will return the
sum of the numbers !
EXERCISE 10
• Create a lambda function that has one
argument, where the function will return 0 if
the argument is less than 1 and return 1 if the
argument is more than 1 !

You might also like