0% found this document useful (0 votes)
3 views

9- Function - revisi 1 (1) (1)

Uploaded by

Silvia Cipy
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

9- Function - revisi 1 (1) (1)

Uploaded by

Silvia Cipy
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 50

Pemrograman Dasar

Function
Remember our first Hello World program?

print("Hello, world!") # calls print() function

list-social-media-story-template_53876-
114936.jpg
list-social-media-story-template_53876-
114936.jpg
This code relies on functions from module math

from math import *

print(ceil(1.23))
print(pow(5,3))
print(factorial(4))

See more at: https://docs.python.org/3/library/math.html

list-social-media-story-template_53876-
114936.jpg
Programming without functions
# compute factorial of 3
result = 1
for i in range(1,4):
result *= i
print("Factorial of", 3, "is", result)

# compute factorial of 4
result = 1
for i in range(1,5):
result *= i
print("Factorial of", 4, "is", result)
Functions: What and why
A function is a set of instructions you can call to carry out a specific task

Benefits of functions
➜ Avoid repeating code
➜ Improved reliability
➜ Improved modularity
Let's create a factorial function

def my_factorial(n): # function signature


# function body
result = 1
for i in range(1,n+1):
result *= i
return result
Let's create a factorial function

def my_factorial(n): # function signature


# function body
result = 1
for i in range(1,n+1):
result *= i
return result
Let's create a factorial function
def my_factorial(n): # function signature
# function body 3
result = 1 Perform operations in the
for i in range(1,n+1): function
result *= i 2
return result Return result to the calling
function

1 The function call passes


argument 4 to parameter n
DIY: Let's create a currency converter function (assume 1 USD = 15000 IDR)

def usd_to_idr(amount):
amount_in_idr = amount * 15000.0
return amount_in_idr
DIY: Let's create a currency converter function (assume 1 USD = 15000 IDR)

def usd_to_idr(amount):
amount_in_idr = amount * 15000.0
return amount_in_idr
DIY: Let's create a currency converter function (assume 1 USD = 15000 IDR)

def usd_to_idr(amount):
"""Convert from the USD currency to IDR currency.""" docstring
amount_in_idr = amount * 15000.0
return amount_in_idr

help(usd_to_idr)
DIY: Let's create a currency converter function (assume 1 USD = 15000 IDR)

def usd_to_idr(amount):
"""Convert from the USD currency to IDR currency.""" docstring
amount_in_idr = amount * 15000.0
return amount_in_idr

help(usd_to_idr)
A function with no parameters and no return

def hi():
print("Hi!")
What goes wrong?
hi()

def hi():
print("Hi!")
What goes wrong?
def hi():
print("Hi!")

hi("Indonesia")
What goes wrong?
def hi():
print("Hi!")

hi("Indonesia")
Modify this function to say hi to some name!

def hi(name):
print("Hi, " + name + "!")
Modify this function to say hi to some name!

def hi(name):
print("Hi, " + name + "!")

[1] print(hi("Python"))
Modify this function to say hi to some name!

def hi(name):
print("Hi, " + name + "!")

[1] print(hi("Python"))
Quiz time: Distance between two points

Given four real numbers (floats) representing cartesian coordinates


(x1, y1) and (x2, y2), write a function distance(x1, y1, x2, y2)
to compute the distance between the two points!
Quiz time: Distance between two points

import math

def distance(x1, y1, x2, y2):


return math.sqrt((x2 - x1) ** 2 + (y2 - y1) ** 2)

x1 = float(input())
y1 = float(input())
x2 = float(input())
y2 = float(input())
print(distance(x1, y1, x2, y2))
A function can have multiple return statements

def power(a, n):


res = 1
for i in range(abs(n)):
res *= a
if n >= 0:
return res
else:
return 1 / res

print(power(float(input()), int(input())))
Default values

def hi(name = "Stranger"):


print("Hi, " + name + "!")
Default values

def hi(name = "Stranger"):


print("Hi, " + name + "!")
Variable scoping

• Not all variables are accessible from any part of our program!
• Variable scope: The part of a program where a variable
is accessible.
Scope matters

x = "Hello, Python!"
def fun():
x = 5
print(f"Inside 'fun', x has the value {x}")

fun()
print(f"Outside 'fun', x has the value {x}")
Scope matters

x = "Hello, Python!"
def fun():
x = 5
print(f"Inside 'fun', x has the value {x}")

fun()
print(f"Outside 'fun', x has the value {x}")
From main to fun

x = 5
def fun(y):
print(y)

fun(x)
From main to fun

x = 5
def fun(y):
print(y)

fun(x)

main fun

x 5 y
From main to fun
x = 5
def fun(y):
y = 7
print(y)

fun(x)
print(x)
From main to fun
x = 5
def fun(y):
y = 7
print(y)

fun(x)
print(x)

main

x 5
fun

7 y
What's wrong with this code?

def hi_fitri():
name = "Fitri"
print("Hi, " + name + "!")

hi_fitri()
print(name)
What's wrong with this code?

def hi_fitri():
name = "Fitri"
print("Hi, " + name + "!")

hi_fitri()
print(name)
Quiz time: What's the output?
a = 0

if a == 0:
b = 1

def my_function(c):
d = 3
print(c)
print(d)

[1] my_function(7)
[2] print(a)
[3] print(b)
[4] print(c)
[5] print(d)
Quiz time: What's the output?
a = 0

if a == 0:
b = 1

def my_function(c):
d = 3
print(c)
print(d)

[1] my_function(7)
[2] print(a)
[3] print(b)
[4] print(c)
[5] print(d)
Global variables

• A global variable is defined in the main body


• Visible throughout the file and any importing file
• Be careful in using global variables as their scope is very wide
Local variables

• A variable defined in a function is local to the function


• Accessible from the point at which the variable is defined until the end of the
function
• Function parameters behave like local variables
Quiz time: Global vars are really global
def f():
print(s)

s = "Can't wait for pre-midterm quiz!"


f()

main

s "Can't wait ..."


Quiz time: Overriding global vars
def f():
s = "Oh, no :("
print(s)

s = "Can't wait for pre-midterm quiz!"


f()

main

s "Can't wait ..."


f

"Oh, no :(" s
Fungsi Rekursif
Recursion
• it is a function that calls itself
def function():
x = 10
function()

• Komponen pada fungsi rekursif terdiri dari dua bagian yaitu:

• Base case : kondisi untuk menghentikan rekursi

• Recursive case : di mana langkah rekursif dijalankan untuk masalah yang


lebih kecil
def countdown(n):
print(n)
if n == 0: # Base case
return
else:
countdown(n - 1) # Recursive case

countdown(5)

• Base case terjadi ketika n adalah nol, di mana rekursi berhenti.


• Dalam panggilan rekursif, argument di dalamnya dikurang satu dari nilai n saat ini,
sehingga setiap rekursi bergerak mendekati base case.
1. Dekomposisi problem menjadi sub-problem yang lebih sederhana dari problem yang sama (Recursive Case).

2. Sub-problem kemudian dipecah hingga menjadi sangat sederhana sehingga dapat diselesaikan tanpa
pembagian lebih lanjut (Base Case).
def factorial_recursive(n):
# Base case: 1! = 1 or n == 0
if (n == 1) or (n == 0):
return 1

# Recursive case: n! = n * (n-1)!


else:
return n * factorial_recursive(n-1)

factorial_recursive(10)
FIBONACCI SEQUENCE

0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, 1597, 2584, 4181

Apa pola nya?


FIBONACCI SEQUENCE

0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, 1597, 2584, 4181
Apa pola nya?
FIBONACCI SEQUENCE
0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, 1597, 2584, 4181

Kode :
Tugas
Thanks
and keep practicing!

You might also like