Download as pdf or txt
Download as pdf or txt
You are on page 1of 20

Modul 4 - Function Tuple Dictionaries and Data Processing http://localhost:8888/nbconvert/html/Desktop/Digital Talent/Modul 4 -...

In this module, you will learn about:

defining and using functions;


different ways of passing arguments;
name scopes;
tuples and dictionaries;
data processing.

In [1]: # Motivasi function adalah perulangan kode

print("Please, Enter a value: ")


a = int(input())
print(a)

print("Please, Enter a value: ")


b = int(input())
print(b)

print("Please, Enter a value: ")


c = int(input())
print(c)

# can we do this: change made once in one place would be propagated to all the p
laces where it's used.

Please, Enter a value:


4
4
Please, Enter a value:
5
5
Please, Enter a value:
8
8

Sintaks Function:

def functionName():
functionBody

1 of 20 17/07/2019, 17:00
Modul 4 - Function Tuple Dictionaries and Data Processing http://localhost:8888/nbconvert/html/Desktop/Digital Talent/Modul 4 -...

In [30]: def message():


print("Please, Enter a value: ")
a = int(input())
print(a)

#print("Dimulai dari sini")


message() #invocation
message()
message()
#print("Berhenti disini")

Dimulai dari sini


Please, Enter a value:
8
8
Please, Enter a value:
9
9
Please, Enter a value:
7
7
Berhenti disini

Parametrized functions

In [18]: def message(m):


print("pesan: ",m.upper())

message("Hello")
message("Hello juga")

pesan: HELLO
pesan: HELLO JUGA

In [21]: def message(what, number, coba):


print("Enter", what, "number", number, "test", coba)

message("telephone",0,"" )
#message("price", 5)
#message("number", "number")

Enter telephone number 0 test

In [14]: def tambahUmur(nama, umur):


umur = umur + 0.5
print(nama, umur)

tambahUmur("Guntur",5.1)

Guntur 5.6

posisi parameter

In [24]: def introduction(firstName, lastName):


print("Hello, my name is", firstName, lastName)

introduction("Tjandra", "Sarie")

Hello, my name is Tjandra Sarie

2 of 20 17/07/2019, 17:00
Modul 4 - Function Tuple Dictionaries and Data Processing http://localhost:8888/nbconvert/html/Desktop/Digital Talent/Modul 4 -...

In [27]: introduction(firstName = "Tjandra", lastName = "Sarie")


introduction(lastName = "Tjandra", firstName = "Sarie")

Hello, my name is Tjandra Sarie


Hello, my name is Sarie Tjandra

In [28]: def jumlah(a, b, c):


print(a, "+", b, "+", c, "=", a + b + c)

# call the sum function here


jumlah(5,6,4)

5 + 6 + 4 = 15

Default parameter
In [2]: #All required parameters must be placed before any default arguments.

def introduction(firstName, lastName="Kurniawan"):


print("Hello, my name is", firstName, lastName)

# call the function here


introduction(firstName="Asep", lastName="Coba")

Hello, my name is Asep Coba

In [32]: def introductionLengkap(firstName, lastName, middleName="Sirojum"):


print("Hello, my name is", firstName, middleName, lastName)

introductionLengkap(firstName = "Ihyak", lastName = "Munir")

Hello, my name is Ihyak Sirojum Munir

In [35]: def boringFunction():


return 345

x = boringFunction()

print("The boringFunction has returned its result. It's:", x)

The boringFunction has returned its result. It's: 345

In [5]: def boringFunction():


print("'Oughh' ON.")
print("'Oughh lg' ON.")
return

print("This lesson is interesting!")


boringFunction()
print("This lesson is boring...")

This lesson is interesting!


'Oughh' ON.
'Oughh lg' ON.
This lesson is boring...

3 of 20 17/07/2019, 17:00
Modul 4 - Function Tuple Dictionaries and Data Processing http://localhost:8888/nbconvert/html/Desktop/Digital Talent/Modul 4 -...

In [9]: def jumlah(a,b):


c = a + b
return c

print(jumlah(6,4))

None

In [68]: value = None


if value == None:
print("Sorry, you don't carry any value")

Sorry, you don't carry any value

In [12]: def strangeFunction(n):


if(n % 2 == 0):
return True

print(strangeFunction(4))
print(strangeFunction(9))

True
None

In [19]: def sumOfList(lst):


sum = 0

for x in lst:
#print (x)
sum += x
return sum

sumOfList([5,2,10,30])

Out[19]: 47

4 of 20 17/07/2019, 17:00
Modul 4 - Function Tuple Dictionaries and Data Processing http://localhost:8888/nbconvert/html/Desktop/Digital Talent/Modul 4 -...

In [35]: def strangeListFunction(n):


strangeList = []

for i in range(0, n):


print("Insert",i)
strangeList.insert(0, i)
print(strangeList)

return strangeList

print("Hasil = ",strangeListFunction(10))

Insert 0
[0]
Insert 1
[1, 0]
Insert 2
[2, 1, 0]
Insert 3
[3, 2, 1, 0]
Insert 4
[4, 3, 2, 1, 0]
Insert 5
[5, 4, 3, 2, 1, 0]
Insert 6
[6, 5, 4, 3, 2, 1, 0]
Insert 7
[7, 6, 5, 4, 3, 2, 1, 0]
Insert 8
[8, 7, 6, 5, 4, 3, 2, 1, 0]
Insert 9
[9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
Hasil = [9, 8, 7, 6, 5, 4, 3, 2, 1, 0]

Lab
Your task is to write and test a function which takes one argument (a year) and returns True if the year is a leap year, or
False otherwise.

The seed of the function is already sown in the skeleton code in the editor.

Note: we've also prepared a short testing code, which you can use to test your function.

The code uses two lists - one with the test data, and the other containing the expected results. The code will tell you if any
of your results are invalid.

def isYearLeap(year):
#
# put your code here
#

testData = [1900, 2000, 2016, 1987]


testResults = [False, True, True, False]
for i in range(len(testData)):
yr = testData[i]
print(yr,"->",end="")
result = isYearLeap(yr)
if result == testResults[i]:
print("OK")
else:
print("Failed")

5 of 20 17/07/2019, 17:00
Modul 4 - Function Tuple Dictionaries and Data Processing http://localhost:8888/nbconvert/html/Desktop/Digital Talent/Modul 4 -...

In [45]: def isYearLeap(year):


if (year % 4) == 0:
if (year % 100) == 0:
if (year % 400) == 0:
return True
else:
return False
else:
return True
else:
return False

testData = [1900, 2000, 2016, 1989]


testResults = [False, True, True, False]
for i in range(len(testData)):
yr = testData[i]
print(yr,"->",end="")
result = isYearLeap(yr)
if result == testResults[i]:
print("OK")
else:
print("Failed")

1900 ->OK
2000 ->OK
2016 ->OK
1989 ->OK

Masih ada Lab Lainnya

In [15]: def scopeTest():


YY = 123

scopeTest()
print(YY)

---------------------------------------------------------------------------
NameError Traceback (most recent call last)
<ipython-input-15-2d7b0c517e9a> in <module>
4
5 scopeTest()
----> 6 print(YY)

NameError: name 'YY' is not defined

In [46]: def myFunction():


print("Do I know that variable?", var)

var = 1
myFunction()
print(var)

# The answer is: a variable existing outside a function


# has a scope inside the functions' bodies.

Do I know that variable? 1


1

6 of 20 17/07/2019, 17:00
Modul 4 - Function Tuple Dictionaries and Data Processing http://localhost:8888/nbconvert/html/Desktop/Digital Talent/Modul 4 -...

In [49]: def myFunction():


global var
var = 2
print("Do I know that variable?", var)

myFunction()
#var = 1
print(var)

# There's a special Python method which can extend a variable's scope


# in a way which includes the functions' bodies
# (even if you want not only to read the values, but also to modify them).

Do I know that variable? 2


1

In [50]: def myFunction(x):


print("I got", x)
x += 1
print("I have", x)
return x

var = 1
myFunction(var)
print(var)

#changing the parameter's value doesn't propagate outside the function

I got 1
I have 2
1

BMI
In [ ]: def bmi(weight, height):
return weight / height ** 2

print(bmi(52.5, 1.65))

In [52]: def bmi(weight, height):


if height < 1.0 or height > 2.5 or \
weight < 20 or weight > 200:
return
return weight / height ** 2
print(bmi(70,0.67))

None

Segitiga

7 of 20 17/07/2019, 17:00
Modul 4 - Function Tuple Dictionaries and Data Processing http://localhost:8888/nbconvert/html/Desktop/Digital Talent/Modul 4 -...

In [51]: def isItATriangle(a, b, c):


if a + b <= c:
return False
if b + c <= a:
return False
if c + a <= b:
return False
return True

print(isItATriangle(1, 1, 1))
print(isItATriangle(1, 1, 3))

True
False

In [ ]: def isItATriangle(a, b, c):


return a + b > c and b + c > a and c + a > b

a = float(input("Enter the first side's length: "))


b = float(input("Enter the second side's length: "))
c = float(input("Enter the third side's length: "))

if isItATriangle(a, b, c):
print("Congratulations - it can be a triangle.")
else:
print("Sorry, it won't be a triangle.")

Faktorial
In [2]: def factorialFun(n):
if n < 0:
return None
if n < 2:
return 1

product = 1
for i in range(2, n + 1):
product *= i
return product

for n in range(1, 6): # testing


print(n, factorialFun(n))

1 1
2 2
3 6
4 24
5 120

Fibonacci

8 of 20 17/07/2019, 17:00
Modul 4 - Function Tuple Dictionaries and Data Processing http://localhost:8888/nbconvert/html/Desktop/Digital Talent/Modul 4 -...

In [3]: def fib(n):


if n < 1:
return None
if n < 3:
return 1

elem1 = elem2 = 1
sum = 0
for i in range(3, n + 1):
sum = elem1 + elem2
elem1, elem2 = elem2, sum
return sum

for n in range(1, 10): # testing


print(n, "->", fib(n))

1 -> 1
2 -> 1
3 -> 2
4 -> 3
5 -> 5
6 -> 8
7 -> 13
8 -> 21
9 -> 34

Recursion
In [38]: def fib(n):
if n < 1:
return None
if n < 3:
return 1
else:
return fib(n - 1) + fib(n - 2)

for n in range(0, 10): # testing


print(n, "->", fib(n))

0 -> None
1 -> 1
2 -> 1
3 -> 2
4 -> 3
5 -> 5
6 -> 8
7 -> 13
8 -> 21
9 -> 34

In [3]: def bmi(weight, height):


if height < 1.0 or height > 2.5 or weight < 20 or weight > 200:
print(weight, height)
return
return weight / height ** 2

a = float(input("berat badan = "))


b = float(input("tinggi = "))

print(bmi(a,b))

berat badan = 86
tinggi = 1.71
29.410758865975858

9 of 20 17/07/2019, 17:00
Modul 4 - Function Tuple Dictionaries and Data Processing http://localhost:8888/nbconvert/html/Desktop/Digital Talent/Modul 4 -...

List datanya bisa dirubah selama eksekusi program, sifatnya bernama mutable Sebaliknya tuple tidak bisa, sifatnya
dinamakan immutable. Persamaannya keduanya sama-sama bisa menyimpan banyak nilai sekaligus dalam satu tipe data
(sequence type)

Tuples
Tuples are ordered and unchangeable (immutable) collections of data. They can be thought of as immutable lists. They
are written in round brackets:

In [53]: myTuple = (1, 2, True, "a string", (3, 4), [5, 6], None)
print(myTuple)
print (myTuple[3])

myList = [1, 2, True, "a string", (3, 4), [5, 6], None]
print(myList)
print (myList[3])

(1, 2, True, 'a string', (3, 4), [5, 6], None)


a string
[1, 2, True, 'a string', (3, 4), [5, 6], None]
a string

In [2]: tuple1 = (1, 2, 4, 8)


tuple2 = 1., .5, .25, .125

print(tuple1)
print(tuple2)
print (type(tuple1),type(tuple2))

(1, 2, 4, 8)
(1, 5, 3, 3)
<class 'tuple'> <class 'tuple'>

In [3]: dt = ()
print(type(dt))

<class 'tuple'>

In [58]: myTuple = (1, 10, 100, 1000)

print(myTuple[0])
print(myTuple[-1])
print(myTuple[1:])
print(myTuple[:2])

for elem in myTuple:


print(elem, end =" ")

1
1000
(10, 100, 1000)
(1, 10)
1 10 100 1000

10 of 20 17/07/2019, 17:00
Modul 4 - Function Tuple Dictionaries and Data Processing http://localhost:8888/nbconvert/html/Desktop/Digital Talent/Modul 4 -...

In [3]: myTuple = (1, 10, 100, 1000)

#myTuple.append(10000)
#del myTuple[0]
myTuple[1] = -10

---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-3-df6110bf2cdd> in <module>
3 #myTuple.append(10000)
4 #del myTuple[0]
----> 5 myTuple[1] = -10

TypeError: 'tuple' object does not support item assignment

In [1]: myTuple = (1, 10, 100)

t1 = myTuple + (1000, 10000)


t2 = myTuple * 3

print(len(t2))
print(t1)
print(t2)
print(10 in myTuple)
print(-10 not in myTuple)

9
(1, 10, 100, 1000, 10000)
(1, 10, 100, 1, 10, 100, 1, 10, 100)
True
True

11 of 20 17/07/2019, 17:00
Modul 4 - Function Tuple Dictionaries and Data Processing http://localhost:8888/nbconvert/html/Desktop/Digital Talent/Modul 4 -...

In [11]: # Example 1
t1 = (1, 2, 3)
for elem in t1:
print(elem)

# Example 2
t2 = (1, 2, 3, 4)
print(5 in t2)
print(5 not in t2)

# Example 3
t3 = (1, 2, 3, 5)
print(len(t3))

# Example 4
t4 = t1 + t2
t5 = t3 * 2
t6 = (t1,t2)

print(t4)
print(t5)
print(t6)

a = float(input("berat badan = "))


b = float(input("tinggi = "))
t = (a,b)
tup = (t)
print (tup)

1
2
3
False
True
4
(1, 2, 3, 1, 2, 3, 4)
(1, 2, 3, 5, 1, 2, 3, 5)
((1, 2, 3), (1, 2, 3, 4))
berat badan = 4
tinggi = 5
(4.0, 5.0)

In Python's world, the word you look for is named a key. The word you get from the dictionary is called a value.

Dictionaries are unordered, changeable (mutable), and indexed collections of data. (In Python 3.6x dictionaries have
become ordered by default.

This means that a dictionary is a set of key-value pairs. Note:

each key must be unique - it's not possible to have more than one key of the same value;
a key may be data of any type: it may be a number (integer or float), or even a string;
a dictionary is not a list - a list contains a set of numbered values, while a dictionary holds pairs of values;
the len() function works for dictionaries, too - it returns the numbers of key-value elements in the dictionary;
a dictionary is a one-way tool - if you have an English-French dictionary, you can look for French equivalents of
English terms, but not vice versa.

12 of 20 17/07/2019, 17:00
Modul 4 - Function Tuple Dictionaries and Data Processing http://localhost:8888/nbconvert/html/Desktop/Digital Talent/Modul 4 -...

In [4]: dict = {"cat" : "chat", "dog" : "chien", "horse" : "cheval"}


phoneNumbers = {'boss' : 5551234567, 'Suzy' : 22657854310}
emptyDictionary = {}

print(dict)
print(phoneNumbers)
print(emptyDictionary)

{'cat': 'chat', 'dog': 'chien', 'horse': 'cheval'}


{'boss': 5551234567, 'Suzy': 22657854310}
{}

In [5]: print(dict['cat'])
print(phoneNumbers['Suzy'])

chat
22657854310

In [13]: dict = {"cat" : "chat", "dog" : "chien", "horse" : "cheval"}


words = ['cat', 'lion', 'horse']

for word in words:


if word in dict:
print(word, "->", dict[word])
else:
print(word, "is not in dictionary")

cat -> chat


lion is not in dictionary
horse -> cheval

In [14]: dict = {"dog" : "chien", "horse" : "cheval","cat" : "chat"}

for key in dict.keys():


print(key, "->", dict[key])

dog -> chien


horse -> cheval
cat -> chat

In [18]: for key in sorted(dict.keys()):


print(key, "->", dict[key])

cat -> chat


dog -> chien
horse -> cheval

items and values

In [13]: dict = {"cat" : "chat", "dog" : "chien", "horse" : "cheval"}

for english, french in dict.items():


print(english, "->", french)

cat -> chat


dog -> chien
horse -> cheval

13 of 20 17/07/2019, 17:00
Modul 4 - Function Tuple Dictionaries and Data Processing http://localhost:8888/nbconvert/html/Desktop/Digital Talent/Modul 4 -...

In [14]: dict = {"cat" : "chat", "dog" : "chien", "horse" : "cheval"}

for french in dict.values():


print(french)

chat
chien
cheval

In [36]: Data_pribadi = {
"nama": "bahar Ipomiarto",
"umur": 19,
"hobi": ["coding", "membaca", "menulis"],
"menikah" : True
}
#print(Data_pribadi)
#for data in Data_pribadi.values():
# print(data)

for datas, data in Data_pribadi.items():


print(datas, "->", data)

hobi = Data_pribadi['hobi']
for x in hobi:
print (x)

print(hobi[2])

nama -> bahar Ipomiarto


umur -> 19
hobi -> ['coding', 'membaca', 'menulis']
menikah -> True
coding
membaca
menulis
menulis

Replace

In [15]: dict = {"cat" : "chat", "dog" : "chien", "horse" : "cheval"}

dict['cat'] = 'minou'
print(dict)

{'cat': 'minou', 'dog': 'chien', 'horse': 'cheval'}

Adding new key

In [16]: dict = {"cat" : "chat", "dog" : "chien", "horse" : "cheval"}

dict['swan'] = 'cygne'
print(dict)

{'cat': 'chat', 'dog': 'chien', 'horse': 'cheval', 'swan': 'cygne'}

Tuples and Dictionaries work Together

14 of 20 17/07/2019, 17:00
Modul 4 - Function Tuple Dictionaries and Data Processing http://localhost:8888/nbconvert/html/Desktop/Digital Talent/Modul 4 -...

line 1: create an empty dictionary for the input data; the student's name is used as a key, while all the associated
scores are stored in a tuple (the tuple may be a dictionary value - that's not a problem at all)
line 3: enter an "infinite" loop (don't worry, it'll break at the right moment)
line 4: read the student's name here;
line 5-6: if the name is exit, leave the loop;
line 8: ask for one of the student's scores (an integer from the range 1-10)
line 10-11: if the student's name is already in the dictionary, lengthen the associated tuple with the new score (note
the += operator)
line 12-13: if this is a new student (unknown to the dictionary), create a new entry - its value is a one-element tuple
containing the entered score;
line 15: iterate through the sorted students' names;
line 16-17: initialize the data needed to evaluate the average (sum and counter)
line 18-20: we iterate through the tuple, taking all the subsequent scores and updating the sum, together with the
counter;
line 21: evaluate and print the student's name and average score.

In [39]: schoolClass = {}
while True:
name = input("Enter the student's name (or type exit to stop): ")
if name == 'exit':
break
score = int(input("Enter the student's score (0-10): "))

if name in schoolClass:
schoolClass[name] += (score,)
#print (score)
else:
schoolClass[name] = (score,)
#print (score)

for name in sorted(schoolClass.keys()):


sum = 0
counter = 0
for score in schoolClass[name]:
sum += score
counter += 1
print(name, ":", sum / counter)

Enter the student's name (or type exit to stop): lukman


Enter the student's score (0-10): 10
10
Enter the student's name (or type exit to stop): lukman
Enter the student's score (0-10): 100
100
Enter the student's name (or type exit to stop): exit
lukman : 55.0

15 of 20 17/07/2019, 17:00
Modul 4 - Function Tuple Dictionaries and Data Processing http://localhost:8888/nbconvert/html/Desktop/Digital Talent/Modul 4 -...

16 of 20 17/07/2019, 17:00
Modul 4 - Function Tuple Dictionaries and Data Processing http://localhost:8888/nbconvert/html/Desktop/Digital Talent/Modul 4 -...

1. Dictionaries are unordered, changeable (mutable), and indexed collections of data. (In Python 3.6x dictionaries have
become ordered by default.

Each dictionary is a set of key : value pairs. You can create it by using the following syntax:

myDictionary = {
key1 : value1,
key2 : value2,
key3 : value3,
}

1. If you want to access a dictionary item, you can do so by making a reference to its key inside a pair of square
brackets (ex. 1) or by using the get() method (ex. 2):

polEngDict = {
"kwiat" : "flower",
"woda" : "water",
"gleba" : "soil"
}

item1 = polEngDict["gleba"] # ex. 1


print(item1) # outputs: soil

item2 = polEngDict.get("woda")
print(item2) # outputs: water

1. If you want to change the value associated with a specific key, you can do so by referring to the item's key name in
the following way:

polEngDict = {
"zamek" : "castle",
"woda" : "water",
"gleba" : "soil"
}

polEngDict["zamek"] = "lock"
item = polEngDict["zamek"] # outputs: lock

1. To add or remove a key (and the associated value), use the following syntax:

myPhonebook = {} # an empty dictionary

myPhonebook["Adam"] = 3456783958 # create/add a key-value pair


print(myPhonebook) # outputs: {'Adam': 3456783958}

del myPhonebook["Adam"]
print(myPhonebook) # outputs: {}

You can also insert an item to a dictionary by using the update() method, and remove the last element by using the
popitem() method, e.g.:

polEngDict = {"kwiat" : "flower"}

polEngDict = update("gleba" : "soil")


print(polEngDict) # outputs: {'kwiat' : 'flower', 'gleba' : 'soil'}

polEngDict.popitem()
print(polEngDict) # outputs: {'kwiat' : 'flower'}

17 of 20 17/07/2019, 17:00
Modul 4 - Function Tuple Dictionaries and Data Processing http://localhost:8888/nbconvert/html/Desktop/Digital Talent/Modul 4 -...

18 of 20 17/07/2019, 17:00
Modul 4 - Function Tuple Dictionaries and Data Processing http://localhost:8888/nbconvert/html/Desktop/Digital Talent/Modul 4 -...

Scenario Your task is to write a simple program which pretends to play tic-tac-toe with the user. To make it all easier for
you, we've decided to simplify the game. Here are our assumptions:

the computer (i.e., your program) should play the game using 'X's;
the user (e.g., you) should play the game using 'O's;
the first move belongs to the computer - it always puts its first 'X' in the middle of the board;
all the squares are numbered row by row starting with 1 (see the example session below for reference)
the user inputs their move by entering the number of the square they choose - the number must be valid, i.e., it must
be an integer, it must be greater than 0 and less than 10, and it cannot point to a field which is already occupied;
the program checks if the game is over - there are four possible verdicts: the game should continue, or the game ends
with a tie, your win, or the computer's win;
the computer responds with its move and the check is repeated;
don't implement any form of artificial intelligence - a random field choice made by the computer is good enough for the
game.
The example session with the program may look as follows:

+-------+-------+-------+
| | | |
| 1 | 2 | 3 |
| | | |
+-------+-------+-------+
| | | |
| 4 | X | 6 |
| | | |
+-------+-------+-------+
| | | |
| 7 | 8 | 9 |
| | | |
+-------+-------+-------+
Enter your move: 1
+-------+-------+-------+
| | | |
| O | 2 | 3 |
| | | |
+-------+-------+-------+
| | | |
| 4 | X | 6 |
| | | |
+-------+-------+-------+
| | | |
| 7 | 8 | 9 |
| | | |
+-------+-------+-------+
+-------+-------+-------+
| | | |
| O | X | 3 |
| | | |
+-------+-------+-------+
| | | |
| 4 | X | 6 |
| | | |
+-------+-------+-------+
| | | |
| 7 | 8 | 9 |
| | | |
+-------+-------+-------+

19 of 20 17/07/2019, 17:00
Modul 4 - Function Tuple Dictionaries and Data Processing http://localhost:8888/nbconvert/html/Desktop/Digital Talent/Modul 4 -...

In [ ]: def DisplayBoard(board):
#
# the function accepts one parameter containing the board's current status
# and prints it out to the console
#

def EnterMove(board):
#
# the function accepts the board current status, asks the user about their move,
# checks the input and updates the board according to the user's decision
#

def MakeListOfFreeFields(board):
#
# the function browses the board and builds a list of all the free squares;
# the list consists of tuples, while each tuple is a pair of row and column numb
ers
#

def VictoryFor(board, sign):


#
# the function analyzes the board status in order to check if
# the player using 'O's or 'X's has won the game
#

def DrawMove(board):
#
# the function draws the computer's move and updates the board
#

In [ ]:

20 of 20 17/07/2019, 17:00

You might also like