Alpro Odd 2021 - Week 6A - Function
Alpro Odd 2021 - Week 6A - Function
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")
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
x = lambda a : a + 10
print(x(5))
15
x = lambda a, b : a * b
print(x(5, 6))
30
(lambda a:a**2)(3)
Example:
def myfunc(n):
return lambda a : a * n
mydoubler = myfunc(2)
mytripler = myfunc(3)
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 :
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
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 !