Modul 3
Modul 3
Operator rasional;
Operator aritmatika;
Struktur pemilihan if-elif-else;
Struktur perulangan while dan for;
Statement loncat;
Operasi logika dan bitwise;
Lists dan Array.
Operator relasional adalah operator yang digunakan untuk membandingkan dua buah nilai. Hasil yang akan diperoleh dari
operasi perbandingan ini adalah logika (bertipe bool), yaitu True (benar) atau False (salah).
In [ ]: a = int(input("masukkan a = "))
b = int(input("masukkan b = "))
c = int(input("masukkan c = "))
d = int(input("masukkan d = "))
print("a==b",a==b)
print("a==c",a==c)
print("a!=b",a!=b)
print("a>d",a>d)
print("b<d",b<d)
print("b<=d",b<=d)
print("b<=d",b<=d)
1 of 45 09/07/2019, 16:54
Modul 3 http://localhost:8888/nbconvert/html/Desktop/Digital Talent/Modul 3....
2 of 45 09/07/2019, 16:54
Modul 3 http://localhost:8888/nbconvert/html/Desktop/Digital Talent/Modul 3....
Operator Aritmatika
Operator aritmatika adalah operator yang digunakan untuk melakukan perhitungan terhadap data numerik. Berikut
merupakan operator aritmatika yang digunakan dalam python :
</b> Prioritas operator </b> Setiap operator aritmatika memiliki prioritas yang berbeda. Sebagai contoh :
</b> 3+57 </b> Seperti yang diketahui, operator perkalian () memiliki prioritas yang lebih tinggi dibandingkan dengan
operator penjumlahan (+) sehingga operasi dapat dituliskan sebagai berikut (3+(5*7)).
Untuk lebih jelasnya, tabel berikut memperlihatkan urutan prioritas dari operator aritmatika :
3 of 45 09/07/2019, 16:54
Modul 3 http://localhost:8888/nbconvert/html/Desktop/Digital Talent/Modul 3....
In [13]: x = 10
y = 3
print("x=",x)
print("y=",y)
print("x+y=", (x+y))
print("x-y=", (x-y))
print("x*y=", (x*y))
print("x/y=", (x/y))
print("x//y=", (x//y))
print("x%y=", (x%y))
print("x**y=", (x**y))
x= 10
y= 3
x+y= 13
x-y= 7
x*y= 30
x/y= 3.3333333333333335
x//y= 3
x%y= 1
x**y= 1000
Struktur Pemilihan
Berbeda dengan bahasa pemrograman lainnya, Python hanya memiliki satu statement untuk melakukan proses
pemilihan, yaitu dengan menggunakan if. Untuk mempermudah pembahasan tentang statement if, pembahasan akan
dibagi menjadi tiga kelompok :
if kondisi:
statement1
statement2
...
Pada bentuk diatas, statement1, statement2 dan seterusnya hanya akan dieksekusi jika kondisi yang didefinisikan dalam
perintah If terpenuhi (bernilai True). Jika kondisi bernilai False, statement tersebut akan diabaikan oleh program.
In [3]: a = 5
b = 5
if a==b:
print("a dan b bernilai sama")
4 of 45 09/07/2019, 16:54
Modul 3 http://localhost:8888/nbconvert/html/Desktop/Digital Talent/Modul 3....
if kondisi :
statement1
statement2
...
else
statement_alternatif1
statement_alternatif2
...
Pada bentuk ini, jika kondisi bernilai True makan statement selanjutnya yang akan dieksekusi oleh program adalah
statement1, stetement 2 dan seterusnya. Tapi jika kondisi bernilai False, maka program akan mengeksekusi statement
yang berada pada bagian else, yaitu statement_alternatif1, statement_alternatif2 dan seterusnya.
In [9]: a = baca
b = tulis
if a==b:
print("a dan b bernilai sama")
else:
print("a dan b bernilai berbeda")
Latihan 1
if bilangan %2 ==0:
print("%d adalah bilangan genap" %bilangan)
else:
print(" %d adalah bilangan ganjil"%bilangan)
main()
5 of 45 09/07/2019, 16:54
Modul 3 http://localhost:8888/nbconvert/html/Desktop/Digital Talent/Modul 3....
if kondisi1:
statement1a
statement1b
...
elif kondisi2:
statement2a
statement2b
...
else:
statement_alternatif1
statement_alternatif2
...
In [18]: a = 60
if a > 80:
print("Lulus")
elif a > 60:
print("Mengulang")
else:
print("Tidak Lulus")
Tidak Lulus
In [28]: x = 10
if x > 5: # True
if x == 6: # False
print("nested: x == 6")
elif x == 10: # True
print("nested: x == 10")
else:
print("nested: else")
else:
print("else")
nested: x == 10
6 of 45 09/07/2019, 16:54
Modul 3 http://localhost:8888/nbconvert/html/Desktop/Digital Talent/Modul 3....
Latihan 2
Perhatikan gambar diatas. Penetuan kuadran dari suatu titik dilakukan dengan cara :
Jika x>0 dan y>0 maka titik akan berada pada Kuadran I
Jika x<0 dan y>0 maka titik akan berapa pada Kuadran II
Jika x<0 dan y<0 maka titik akan berada pada Kuadran III
JIka x>0 dan y<0 maka titik akan berada pada Kuadran IV
Jika keepat kondisi ini tidak dapat dipenuhi, maka titik tidak termasuk pada kuadran manapun
7 of 45 09/07/2019, 16:54
Modul 3 http://localhost:8888/nbconvert/html/Desktop/Digital Talent/Modul 3....
Lab 3.1
Spathiphyllum, atau yang sering disebut dengan 'peace lily' atau tanaman 'white sail merupakan tanaman dalam rumah
yang sangat populer yang dapat menjadi filter guna menyaring udara dari racun. Beberapa racun yang dapat di filter
adalah benzena, fomaldehyde, dan amonia.
Bayangkan bahwa program komputer anda sangat menyukai tanaman. Ketika komputer menerima masukan (input) pada
form "Spathiphyllum", maka komputer akan merespon dengan "Spathiphyllum is the best plant ever!".
Tulislah sebuah program dengan Python untuk beberapa kondisi berikut, input adalah sebuah string :
respon komputer : "Yes - Spathiphyllum is the best plant ever!" ketika input berupa
"Spathiphyllum" (upper-case)
respon komputer : "No, I want a big Spathiphyllum!" ketika input berupa "spathiphyllum" (lower-
case)
respon komputer : "Spathiphyllum! Not [input]!" ketika input berupa "input".
if plant=="Spathiphyllum":
print("Yes - Spathiphyllum is the best plant ever!")
elif plant=="spathiphyllum":
print("No, I want a big Spathiphyllum!")
else:
print("Spathiphyllum! Not "+plant+"!")
8 of 45 09/07/2019, 16:54
Modul 3 http://localhost:8888/nbconvert/html/Desktop/Digital Talent/Modul 3....
Lab 3.2
Pada suatu masa terdapat sebuah daratan - daratan dengan susu dan madu, yang dihuni oleh masyarakat yang bahagia
dan sejahtera. Masyarakat tersebut membayar pajak, sehingga kebahagiaan mereka memiliki batas. Pajak yang paling
penting adalah Personal Income Tax atau disebut PIT yang mana harus dibayarkan tiap tahun, dan dievaluasi dengan
peraturan sebagai berikut :
Jika penghasilan tidak lebih besar daripada 85,528 thaler, maka pajak adalah sebesar 18% dari pemasukan dikurangi
556 thaler dan 2 sen (disebut juga tax relief)
Jika penghasilan lebih dari nilai tersebut, maka pajak adalah sebesar 14,839 thaler and 2 cents, ditambah 32% dari
selisih penghasilan dengan 85,528 thalers.
Catatan : Negara yang bahagia ini tidak pernah mengembalikan uang tersebut ke warganya. Jika perhitungan pajak
kurang dari nol, itu berarti warga tidak dikenakan pajak sama sekali (pajak = 0).
Perhatikan syntax dibawah ini, hanya membaca satu input dan output sebagai hasilnya. Lengkapi syntax tersebut dengan
sebuah perhitungan yang cerdas.
#
# Put your code here.
#
tax = round(tax, 0)
print("The tax is:", tax, "thalers")
9 of 45 09/07/2019, 16:54
Modul 3 http://localhost:8888/nbconvert/html/Desktop/Digital Talent/Modul 3....
if income<85528:
tax = 0.18 * income - 556.2
else:
tax = 14839 + 0.2 + 0.32 * (income - 85528)
tax = round(tax, 0)
if tax<0:
tax = 0
10 of 45 09/07/2019, 16:54
Modul 3 http://localhost:8888/nbconvert/html/Desktop/Digital Talent/Modul 3....
Lab 3.3
As you surely know, due to some astronomical reasons, years may be leap or common. The former are 366 days long,
while the latter are 365 days long.
Since the introduction of the Gregorian calendar (in 1582), the following rule is used to determine the kind of year:
Look at the code in the editor - it only reads a year number, and needs to be completed with the instructions implementing
the test we've just described.
#
# Put your code here.
#
The code should output one of two possible messages, which are Leap year or Common year, depending on the value
entered.
It would be good to verify if the entered year falls into the Gregorian era, and output a warning otherwise: Not within the
Gregorian calendar period. Tip: use the != and % operators.
11 of 45 09/07/2019, 16:54
Modul 3 http://localhost:8888/nbconvert/html/Desktop/Digital Talent/Modul 3....
Latihan 3
In [ ]: x = 5
y = 10
z = 8
print(x > y)
print(y > z)
In [ ]: x, y, z = 5, 10, 8
print(x > z)
print((y - 5) == x)
In [ ]: x, y, z = 5, 10, 8
x, y, z = z, y, x
print(x > z)
print((y - 5) == x)
In [ ]: x = 10
if x == 10:
print(x == 10)
if x > 5:
print(x > 5)
if x < 10:
print(x < 10)
else:
print("else")
12 of 45 09/07/2019, 16:54
Modul 3 http://localhost:8888/nbconvert/html/Desktop/Digital Talent/Modul 3....
In [18]: x = "1"
if x == 1:
print("one")
elif x == "1":
if int(x) > 1:
print("two")
elif int(x) < 1:
print("three")
else:
print("four")
if int(x) == 1:
print("five")
else:
print("six")
four
five
In [ ]: x = 1
y = 1.0
z = "1"
if x == y:
print("one")
if y == int(z):
print("two")
elif x == y:
print("three")
else:
print("four")
Struktur perulangan
Python menyediakan dua statement untuk melakukan proses perulangan yaitu for dan while. Diantara kedua statement
ini, secara umum for lebih banyak digunakan daripada while.
1. Statement while
Sama seperti kebanyakan bahasa pemrograman lainnya, Python juga mendukung statement while untuk melakukan
perulangan satu atau sekelompok statement. Bentuk umum dari perulangan while adalah sebagai berikut :
while kondisi:
statement1
statement2
statement1
:
:
statementn
Pada bentuk perulangan diatas, statement1, statement2 dan seterusnya merupakan sekelompok statement yang akan
diulang. Statement tersebut akan terus dieksekusi/ diulang selama kondisi bernilai True. Maka diperlukan sebuah
statement yang akan bernilai False, agar proses dapat berhenti. Perhatikan syntax berikut :
13 of 45 09/07/2019, 16:54
Modul 3 http://localhost:8888/nbconvert/html/Desktop/Digital Talent/Modul 3....
In [3]: i = 1
while i<10:
i = i+1
print(i)
2
3
4
5
6
7
8
9
10
Ketika i bernilai 10, maka proses akan terhenti karena nilai i = 10, maka proses akan berhenti . Perhatikan contoh
dibawah ini:
Perhatikan contoh program untuk menghitung berapa ganjil dan genap dari rangkaian bilangan :
14 of 45 09/07/2019, 16:54
Modul 3 http://localhost:8888/nbconvert/html/Desktop/Digital Talent/Modul 3....
oddNumbers = 0
evenNumbers = 0
# read the first number
number = int(input("Enter a number or type 0 to stop: "))
# 0 terminates execution
while number != 0:
# check if the number is odd
if number % 2 == 1:
# increase the oddNumbers counter
oddNumbers += 1
else:
# increase the evenNumbers counter
evenNumbers += 1
# read the next number
number = int(input("Enter a number or type 0 to stop: "))
# print results
print("Odd numbers count:", oddNumbers)
print("Even numbers count:", evenNumbers)
Lab 3.4
A junior magician has picked a secret number. He has hidden it in a variable named secretNumber . He wants
everyone who run his program to play the Guess the secret number game, and guess what number he has picked for
them. Those who don't guess the number will be stuck in an endless loop forever! Unfortunately, he does not know how to
complete the code.
Your task is to help the magician complete the code in the editor in such a way so that the code:
secretNumber = 777
print(
"""
+================================+
| Welcome to my game, muggle! |
| Enter an integer number |
| and guess what number I've |
| picked for you. |
| So, what is the secret number? |
+================================+
""")
15 of 45 09/07/2019, 16:54
Modul 3 http://localhost:8888/nbconvert/html/Desktop/Digital Talent/Modul 3....
print(
"""
+================================+
| Welcome to my game, muggle! |
| Enter an integer number |
| and guess what number I've |
| picked for you. |
| So, what is the secret number? |
+================================+
""")
guessNumber = 0
+================================+
| Welcome to my game, muggle! |
| Enter an integer number |
| and guess what number I've |
| picked for you. |
| So, what is the secret number? |
+================================+
16 of 45 09/07/2019, 16:54
Modul 3 http://localhost:8888/nbconvert/html/Desktop/Digital Talent/Modul 3....
2. Statement for
Selain menggunakan statement while, kita juga dapat melakukan perulangan dengan statement for. Perintah for biasanya
digunakan untuk mengambil atau menelusuri data (item) yang terdapat pada tipe-tipe koleksi seperti string, list, tuple,
dictionary dan set. Dalam pemrograman, proses penelusuran data dalam sebuah koleksi disebut iterasi. Selain itu, for
juga dapat melakukan perulangan normal (sama seperti while), yaitu dengan menggunakan fungsi range(). Dengan
menggunakan range(), kita akan dapat dengan mudah melakukan perulangan dari indeks awal ke indeks tertentu.
For - else
17 of 45 09/07/2019, 16:54
Modul 3 http://localhost:8888/nbconvert/html/Desktop/Digital Talent/Modul 3....
0
1
2
3
4
else: 4
Lab 3.5
Do you know what Mississippi is? Well, it's the name of one of the states and rivers in the United States. The Mississippi
River is about 2,340 miles long, which makes it the second longest river in the United States (the longest being the
Missouri River). It's so long that a single drop of water needs 90 days to travel its entire length!
The word Mississippi is also used for a slightly different purpose: to count mississippily.
If you're not familiar with the phrase, we're here to explain to you what it means: it's used to count seconds.
The idea behind it is that adding the word Mississippi to a number when counting seconds aloud makes them sound closer
to clock-time, and therefore "one Mississippi, two Mississippi, three Mississippi" will take approximately an actual three
seconds of time! It's often used by children playing hide-and-seek to make sure the seeker does an honest count.
Your task is very simple here: write a program that uses a for loop to "count mississippily" to five. Having counted to five,
the program should print to the screen the final message "Ready or not, here I come!"
import time
EXTRA INFO
Note that the code in the editor contains two elements which may not be fully clear to you at this moment: the import time
statement, and the sleep() method. We're going to talk about them soon.
For the time being, we'd just like you to know that we've imported the time module and used the sleep() method to
suspend the execution of each subsequent print() function inside the for loop for one second, so that the message
outputted to the console resembles an actual counting. Don't worry - you'll soon learn more about modules and methods.
18 of 45 09/07/2019, 16:54
Modul 3 http://localhost:8888/nbconvert/html/Desktop/Digital Talent/Modul 3....
for i in range(9):
print(i," Missisipi")
time.sleep(1)
0 Missisipi
1 Missisipi
2 Missisipi
3 Missisipi
4 Missisipi
5 Missisipi
6 Missisipi
7 Missisipi
8 Missisipi
Statement Loncat
Statement loncat merupakan perintah yang digunakan untuk memindahkan eksekusi program dari satu bagian tertentu ke
bagian lain. Python menyediakan tiga statement yaitu : break, continue dan return.
1. Statement break
Statement break digunakan untuk menghentikan secara paksa proses perulangan, meskipun kondisi perulangan
sebenarnya masih bernilai True. Perhatikan contoh-contoh berikut ini :
0 1 2 3 4 5 6 7
19 of 45 09/07/2019, 16:54
Modul 3 http://localhost:8888/nbconvert/html/Desktop/Digital Talent/Modul 3....
In [ ]: largestNumber = -99999999
counter = 0
while True:
number = int(input("Enter a number or type -1 to end program: "))
if number == -1:
break
counter += 1
if number > largestNumber:
largestNumber = number
if counter != 0:
print("The largest number is", largestNumber)
else:
print("You haven't entered any number.")
2. Statement continue
Statement continue berguna untuk memaksa pengulangan agar memroses indeks selanjutnya meskipun statement
didalam blok pengulangan sebenarna belum semua di eksekusi. Dengan kata lain, statement yang ada dibawah
statement continue akan diabaikan (tidak dieksekusi)
1 3 5 7 9
20 of 45 09/07/2019, 16:54
Modul 3 http://localhost:8888/nbconvert/html/Desktop/Digital Talent/Modul 3....
if counter:
print("The largest number is", largestNumber)
else:
print("You haven't entered any number.")
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-9-467c98fde176> in <module>
11 if number > largestNumber:
12 largestNumber = number
---> 13 number = int(input("Enter a number or type -1 to end program: "))
14
15 if counter:
Lab 3.6
The break statement is used to exit/terminate a loop.
Design a program that uses a while loop and continuously asks the user to enter a word unless the user enters
"chupacabra" as the secret exit word, in which case the message "You've successfully left the loop."
should be printed to the screen, and the loop should terminate.
Don't print any of the words entered by the user. Use the concept of conditional execution and the break statement.
21 of 45 09/07/2019, 16:54
Modul 3 http://localhost:8888/nbconvert/html/Desktop/Digital Talent/Modul 3....
Lab 3.7
The continue statement is used to skip the current block and move ahead to the next iteration, without executing the
statements inside the loop.
Your task here is very special: you must design a vowel eater! Write a program that uses:
a for loop;
the concept of conditional execution (if-elif-else)
the continue statement.
Test your program with the data we've provided for you.
Test data
Expected output:
G
R
G
R
Y
Expected output:
B
S
T
M
S
22 of 45 09/07/2019, 16:54
Modul 3 http://localhost:8888/nbconvert/html/Desktop/Digital Talent/Modul 3....
print(letter.upper())
B
R
wordWithoutVovels += letter.upper()
print(wordWithoutVovels)
23 of 45 09/07/2019, 16:54
Modul 3 http://localhost:8888/nbconvert/html/Desktop/Digital Talent/Modul 3....
Lab 3.8
Listen to this story: a boy and his father, a computer programmer, are playing with wooden blocks. They are building a
pyramid.
Their pyramid is a bit weird, as it is actually a pyramid-shaped wall - it's flat. The pyramid is stacked according to one
simple principle: each lower layer contains one block more than the layer above.
=== blocks : 6 height : 3 Your task is to write a program which reads the number of blocks the builders have, and outputs
the height of the pyramid that can be built using these blocks.
Note: the height is measured by the number of fully completed layers - if the builders don't have a sufficient number of
blocks and cannot complete the next layer, they finish their work immediately.
Sample input: 6
Sample input: 20
Sample input: 2
height -= 1
24 of 45 09/07/2019, 16:54
Modul 3 http://localhost:8888/nbconvert/html/Desktop/Digital Talent/Modul 3....
Latihan
1. Buatlah perulangan dengan menggunakan for yang mulai dari 0 sampai dengan 10, dan cetak nomer ganjil pada
layar.
2. Buatlah perulangan dengan menggunakan while dari 0 sampai dengan 10, dan cetak nomer ganjil pada layar
3. Buatlah sebuah program dengan perulangan for dan statement break. Program harus diiterasi sebanyak jumlah
karakter didalam sebuah alamat email, dan loop akan berhenti jika menemukan simbol '@' dan cetak karakter yang
ditemukan sebelum simbol '@' didalam sebuah line
4. Buatlah sebuah perulangan loop dan statement continue. Program harus diiterasi sebanyak nomer yang ditemukan
dalam string (digit = "0165031806510"), ganti 0 dengan x, lalu cetak string yang telah dimodifikasi.
Exercise 6
Exercise 7
In [ ]: n = 3
while n > 0:
print(n + 1)
n -= 1
else:
print(n)
In [ ]: n = range(4)
for num in n:
print(num - 1)
else:
print(num)
JAWABAN
1 3 5 7 9
25 of 45 09/07/2019, 16:54
Modul 3 http://localhost:8888/nbconvert/html/Desktop/Digital Talent/Modul 3....
In [4]: x=1
while x<11:
if x % 2 !=0:
print(x,end=' ')
x +=1
1 3 5 7 9
r a t n a . l e s t a r i
x
1
6
5
x
3
1
8
x
6
5
1
x
Operasi Logika
26 of 45 09/07/2019, 16:54
Modul 3 http://localhost:8888/nbconvert/html/Desktop/Digital Talent/Modul 3....
Operasi Logika or
Argument A Argument B A or B
False True
True False
If we have some free time, and the weather is good, we will go for a walk
If you are in the mall or I am in the mall, one of us will buy a gift for Mom.
In [34]: x = 1
y = 0
True
27 of 45 09/07/2019, 16:54
Modul 3 http://localhost:8888/nbconvert/html/Desktop/Digital Talent/Modul 3....
28 of 45 09/07/2019, 16:54
Modul 3 http://localhost:8888/nbconvert/html/Desktop/Digital Talent/Modul 3....
Operasi bitwise
Operator bitwise sebenarnya sama saja dengan operator logika. Perbedaannya, dalam operasi bitwise kedua operand-
nya bertipe bilangan bulat (integer) dan operasinya dilakukan bit-demi-bit. Maka dari itu , bilangan integer yang dijadikan
sebagai operand, terlebih dahulu akan dikonversi kedalam biner.
Konsep logika dari operator &, |, dan ~ sama seperti operator and, or, dan not yang terdapat pada operator logika.
Perbedaannya hanya operator bitwise beroperasi pada masing-masing bit.
Operator ^(XOR) hanya akan menghasilkan nilai True jika salah satu operand (bukan keduanya bernilai True, selain
daripada itu adalah False sebagaimana terlihat pada gambar berikut:
Sebagai contoh :
Operator << akan menggeser n bit kearah kiri dari bilangan binernya. Setiap pergeseran 1 bit akan menghasilkan nilai
operand dikali 2. Sebagai contoh :
operand%20geser%20kiri.png (attachment:operand%20geser%20kiri.png)
Operator >> akan menggeser n bit kearah kanan dari bilangan binernya. Setiap pergeseran 1 bit akan menghasilkan nilai
operand dibagi 2. Jika operand bernilai ganjil, maka sisa pembagi akan diabaikan. Sebagai contoh :
29 of 45 09/07/2019, 16:54
Modul 3 http://localhost:8888/nbconvert/html/Desktop/Digital Talent/Modul 3....
In [29]: var1 = 10
var2 = 5
var3 = 7
var4 = 2
var5 = 1
# VERSUS #
var = [10, 5, 7, 2, 1]
print(var)
[10, 5, 7, 2, 1]
Indexing
Dalam list, elemen tidak diindeks berdasarkan key tertentu yang namanya bisa didefinisikan sendiri melainkan
berdasarkan indeks bilangan yang diawali dengan nilai nol(0). Perhatikan contoh berikut :
[10, 5, 7, 2, 1]
7
10
numbers[0] = 111
print("\nPrevious list content:", numbers) # printing previous list content
List length: 5
30 of 45 09/07/2019, 16:54
Modul 3 http://localhost:8888/nbconvert/html/Desktop/Digital Talent/Modul 3....
Indeks dapat juga bernilai negatif yaitu menghitung indeks mulai dari kanan. Perhatikan contoh berikut :
500
400
100
Swap
Nilai elemen didalam list selain dapat diakses juga dapat dimanipulasi dengan swapping. Perhatikan contoh berikut :
In [7]: # swap
numbers = [10, 5, 7, 2, 1]
numbers[0] , numbers[1] , numbers[2] = numbers[2] , numbers[0], numbers[1]
print(numbers)
[7, 10, 5, 2, 1]
while swapped:
swapped = False # no swaps so far
for i in range(len(myList) - 1):
print ("myList=",myList,"i=" ,i)
if myList[i] < myList[i + 1]:
print ("myList[i]=",myList[i])
swapped = True # swap occured!
myList[i], myList[i + 1] = myList[i + 1], myList[i]
print(myList)
31 of 45 09/07/2019, 16:54
Modul 3 http://localhost:8888/nbconvert/html/Desktop/Digital Talent/Modul 3....
In [8]: myList = []
swapped = True
num = int(input("How many elements do you want to sort: "))
for i in range(num):
val = float(input("Enter a list element: "))
myList.append(val)
while swapped:
swapped = False
for i in range(len(myList) - 1):
if myList[i] > myList[i + 1]:
swapped = True
myList[i], myList[i + 1] = myList[i + 1], myList[i]
print("\nSorted:")
print(myList)
Sorted:
[0.0, 2.0, 7.0, 9.0, 12.0]
Lab 3.9
There once was a hat. The hat contained no rabbit, but a list of five numbers: 1, 2, 3, 4, and 5.
write a line of code that prompts the user to replace the middle number in the list with an integer number entered by
the user (step 1)
write a line of code that removes the last element from the list (step 2)
write a line of code that prints the length of the existing list (step 3.) Ready for this challenge?
# Step 2: write a line of code here that removes the last element from the list.
# Step 3: write a line of code here that prints the length of the existing list.
print(hatList)
[1, 2, 3, 4, 5]
Menggunakan metode append() : Metode ini digunakan untuk menambah elemen tunggal dibagian akhir list.
Perhatikan contoh dibawah :
32 of 45 09/07/2019, 16:54
Modul 3 http://localhost:8888/nbconvert/html/Desktop/Digital Talent/Modul 3....
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-13-25ed6dde5ec7> in <module>
1 buah = ["durian", "mangga", "apel"]
----> 2 buah.append("jeruk","pisang")
3 print (buah)
for i in range(5):
myList.append(i + 1)
print(myList)
[1]
[1, 2]
[1, 2, 3]
[1, 2, 3, 4]
[1, 2, 3, 4, 5]
Menggunakan metode insert() : Metode ini digunakan untuk menambah elemen tunggal di indeks / posisi tertentu.
Perhatikan contoh dibawah :
Menggunakan metode extend(). Metode ini digunakan untuk menyambung atau menggabungkan suatu list dengan
list yang lain. Perhatikan contoh berikut :
33 of 45 09/07/2019, 16:54
Modul 3 http://localhost:8888/nbconvert/html/Desktop/Digital Talent/Modul 3....
###
numbers.append(4)
print(len(numbers))
print(numbers)
###
numbers.insert(0, 222)
print(len(numbers))
print(numbers)
4
[111, 7, 2, 1]
5
[111, 7, 2, 1, 4]
6
[222, 111, 7, 2, 1, 4]
nama_list.remove(nilai)
del nama_list[indeks]
34 of 45 09/07/2019, 16:54
Modul 3 http://localhost:8888/nbconvert/html/Desktop/Digital Talent/Modul 3....
Lab 3.10
The Beatles were one of the most popular music group of the 1960s, and the best-selling band in history. Some people
consider them to be the most influential act of the rock era. Indeed, they were included in Time magazine's compilation of
the 20th Century's 100 most influential people.
The band underwent many line-up changes, culminating in 1962 with the line-up of John Lennon, Paul McCartney, George
Harrison, and Richard Starkey (better known as Ringo Starr).
Write a program that reflects these changes and lets you practice with the concept of lists. Your task is to:
# step 2
print("Step 2:", beatles)
# step 3
print("Step 3:", beatles)
# step 4
print("Step 4:", beatles)
# step 5
print("Step 5:", beatles)
Step 1:
Step 2:
Step 3:
Step 4:
Step 5:
The Fab 0
35 of 45 09/07/2019, 16:54
Modul 3 http://localhost:8888/nbconvert/html/Desktop/Digital Talent/Modul 3....
for i in range(len(myList)):
total += myList[i]
print(total)
27
List dapat berisi berbagai tipe data seperti strings, boolean maupun list lainnya. Kita sering sekali menemukan bentuk
array seperti ini dikehidupan kita, salah satu contohnya adalah papan catur. Papan catur terdiri dari baris dan kolom,
terdapat 8 baris dan juga 8 kolom. Setiap kolom ditandai oleh huruf A sampai dengan H, dan setiap baris ditandai oleh 1
sampai dengan 8.
for i in range(8):
row = [EMPTY for i in range(8)] #membuat satu list
board.append(row) #membuat 8 list
print(board)
[['-', '-', '-', '-', '-', '-', '-', '-'], ['-', '-', '-', '-', '-', '-', '-',
'-'], ['-', '-', '-', '-', '-', '-', '-', '-'], ['-', '-', '-', '-', '-', '-',
'-', '-'], ['-', '-', '-', '-', '-', '-', '-', '-'], ['-', '-', '-', '-', '-',
'-', '-', '-'], ['-', '-', '-', '-', '-', '-', '-', '-'], ['-', '-', '-', '-',
'-', '-', '-', '-']]
36 of 45 09/07/2019, 16:54
Modul 3 http://localhost:8888/nbconvert/html/Desktop/Digital Talent/Modul 3....
List diatas menggambarkan list papan catur yang masih kosong sebagaimana gambar ilustrasi dibawah :
Mari kita isi list sersebut dengan sesuatu yang kita inginkan. Perhatikan kode berikut :
for i in range(8):
row = [EMPTY for i in range(8)]
board.append(row)
print(board)
[['ROOK', '-', '-', '-', '-', '-', '-', 'ROOK'], ['-', '-', '-', '-', '-',
'-', '-', '-'], ['-', '-', '-', '-', '-', '-', '-', '-'], ['-', '-', '-', '-',
'PAWN', '-', '-', '-'], ['-', '-', 'KNIGHT', '-', '-', '-', '-', '-'], ['-',
'-', '-', '-', '-', '-', '-', '-'], ['-', '-', '-', '-', '-', '-', '-', '-'],
['ROOK', '-', '-', '-', '-', '-', '-', 'ROOK']]
37 of 45 09/07/2019, 16:54
Modul 3 http://localhost:8888/nbconvert/html/Desktop/Digital Talent/Modul 3....
Untuk mencari sebuah elemen pada list dua dimensi adalah dengan menggunakan dua koordinat yaitu nomer baris dan
juga nomer kolom. Bayangkan ketika anda akan mengembangkan sebuah program untuk perekam cuaca otomatis. Alat
ini akan mampu merekam suhu udara tiap jam sampai dengan satu bulan. Maka total data yang akan direkam adalah 24
jam x 31 hari = 744 data.
Pertama-tama, kita harus memutuskan tipe data yang akan tepat untuk aplikasi ini. Pada kasus ini, tipe float adalah yang
paling sesuai karena suhu biasanya diukur sampai dengan akurasi satu dibelakang koma (0.1). Selanjutnya, kita akan
menentukan bahwa baris akan merepresentasikan jam (sehingga ada 24 baris) dan setiap baris akan direpresentasikan
untuk satu hari (sehingga kita membutuhkan lagi 31 baris).
average = sum / 31
38 of 45 09/07/2019, 16:54
Modul 3 http://localhost:8888/nbconvert/html/Desktop/Digital Talent/Modul 3....
Python tidak memiliki batasan dalam list-in-list. Ini merupakan contoh untuk array tiga dimensi.
Bayangkan sebuah hotel yang besar terdiri dari tiga bangunan, 15 lantai untuk tiap bangunannya. Pada setiap lantai
terdapat 20 kamar.
Langkah pertama adalah tentukan tipe data dari array yang akan dibuat. Dalam kasus ini nilai Boolean yang paling sesuai,
nilai True jika kamar telah di pesan dan nilai False jika kamar kosong. Langkah kedua adalah dengan menganalisa kondisi
yang diberikan.
39 of 45 09/07/2019, 16:54
Modul 3 http://localhost:8888/nbconvert/html/Desktop/Digital Talent/Modul 3....
40 of 45 09/07/2019, 16:54
Modul 3 http://localhost:8888/nbconvert/html/Desktop/Digital Talent/Modul 3....
[[[False, False, False, False, False, False, False, False, False, False, Fals
e, False, False, False, False, False, False, False, False, False], [False, Fal
se, False, False, False, False, False, False, False, False, False, False, Fals
e, False, False, False, False, False, False, False], [False, False, False, Fal
se, False, False, False, False, False, False, False, False, False, False, Fals
e, False, False, False, False, False], [False, False, False, False, False, Fal
se, False, False, False, False, False, False, False, False, False, False, Fals
e, False, False, False], [False, False, False, False, False, False, False, Fal
se, False, False, False, False, False, False, False, False, False, False, Fals
e, False], [False, False, False, False, False, False, False, False, False, Fal
se, False, False, False, False, False, False, False, False, False, False], [Fa
lse, False, False, False, False, False, False, False, False, False, False, Fal
se, False, False, False, False, False, False, False, False], [False, False, Fa
lse, False, False, False, False, False, False, False, False, False, False, Fal
se, False, False, False, False, False, False], [False, False, False, False, Fa
lse, False, False, False, False, False, False, False, False, False, False, Fal
se, False, False, False, False], [False, False, False, False, False, False, Fa
lse, False, False, False, False, False, False, False, False, False, False, Fal
se, False, False], [False, False, False, False, False, False, False, False, Fa
lse, False, False, False, False, False, False, False, False, False, False, Fal
se], [False, False, False, False, False, False, False, False, False, False, Fa
lse, False, False, False, False, False, False, False, False, False], [False, F
alse, False, False, False, False, False, False, False, False, False, False, Fa
lse, False, False, False, False, False, False, False], [False, False, False, F
alse, False, False, False, False, False, False, False, False, False, False, Fa
lse, False, False, False, False, False], [False, False, False, False, False, F
alse, False, False, False, False, False, False, False, False, False, False, Fa
lse, False, False, False]], [[False, False, False, False, False, False, False,
False, False, False, False, False, False, False, False, False, False, False, F
alse, False], [False, False, False, False, False, False, False, False, False,
False, False, False, False, False, False, False, False, False, False, False],
[False, False, False, False, False, False, False, False, False, False, False,
False, False, False, False, False, False, False, False, False], [False, False,
False, False, False, False, False, False, False, False, False, False, False, F
alse, False, False, False, False, False, False], [False, False, False, False,
False, False, False, False, False, False, False, False, False, False, False, F
alse, False, False, False, False], [False, False, False, False, False, False,
False, False, False, False, False, False, False, False, False, False, False, F
alse, False, False], [False, False, False, False, False, False, False, False,
False, False, False, False, False, False, False, False, False, False, False, F
alse], [False, False, False, False, False, False, False, False, False, False,
False, False, False, False, False, False, False, False, False, False], [False,
False, False, False, False, False, False, False, False, False, False, False, F
alse, False, False, False, False, False, False, False], [False, False, False,
False, False, False, False, False, False, False, False, False, False, False, F
alse, False, False, False, False, False], [False, False, False, False, False,
False, False, False, False, False, False, False, False, False, False, False, F
alse, False, False, False], [False, False, False, False, False, False, False,
False, False, False, False, False, False, False, False, False, False, False, F
alse, False], [False, False, False, False, False, False, False, False, False,
False, False, False, False, False, False, False, False, False, False, False],
[False, False, False, False, False, False, False, False, False, False, False,
False, False, False, False, False, False, False, False, False], [False, False,
False, False, False, False, False, False, False, False, False, False, False, F
alse, False, False, False, False, False, False]], [[False, False, False, Fals
e, False, False, False, False, False, False, False, False, False, False, Fals
e, False, False, False, False, False], [False, False, False, False, False, Fal
se, False, False, False, False, False, False, False, False, False, False, Fals
e, False, False, False], [False, False, False, False, False, False, False, Fal
se, False, False, False, False, False, False, False, False, False, False, Fals
e, False], [False, False, False, False, False, False, False, False, False, Fal
se, False, False, False, False, False, False, False, False, False, False], [Fa
lse, False, False, False, False, False, False, False, False, False, False, Fal
se, False, False, False, False, False, False, False, False], [False, False, Fa
lse, False, False, False, False, False, False, False, False, False, False, Fal
se, False, False, False, False, False, False], [False, False, False, False, Fa
lse, False, False, False, False, False, False, False, False, False, False, Fal
se, False, False, False, False], [False, False, False, False, False, False, Fa
lse, False, False, False, False, False, False, False, False, False, False, Fal
41 of 45 09/07/2019, 16:54
Modul 3 http://localhost:8888/nbconvert/html/Desktop/Digital Talent/Modul 3....
42 of 45 09/07/2019, 16:54
Modul 3 http://localhost:8888/nbconvert/html/Desktop/Digital Talent/Modul 3....
rooms[1][9][13] = True
rooms[0][4][1] = False
print(rooms)
vacancy = 0
print(roomNumber)
43 of 45 09/07/2019, 16:54
Modul 3 http://localhost:8888/nbconvert/html/Desktop/Digital Talent/Modul 3....
[[[False, False, False, False, False, False, False, False, False, False, Fals
e, False, False, False, False, False, False, False, False, False], [False, Fal
se, False, False, False, False, False, False, False, False, False, False, Fals
e, False, False, False, False, False, False, False], [False, False, False, Fal
se, False, False, False, False, False, False, False, False, False, False, Fals
e, False, False, False, False, False], [False, False, False, False, False, Fal
se, False, False, False, False, False, False, False, False, False, False, Fals
e, False, False, False], [False, False, False, False, False, False, False, Fal
se, False, False, False, False, False, False, False, False, False, False, Fals
e, False], [False, False, False, False, False, False, False, False, False, Fal
se, False, False, False, False, False, False, False, False, False, False], [Fa
lse, False, False, False, False, False, False, False, False, False, False, Fal
se, False, False, False, False, False, False, False, False], [False, False, Fa
lse, False, False, False, False, False, False, False, False, False, False, Fal
se, False, False, False, False, False, False], [False, False, False, False, Fa
lse, False, False, False, False, False, False, False, False, False, False, Fal
se, False, False, False, False], [False, False, False, False, False, False, Fa
lse, False, False, False, False, False, False, False, False, False, False, Fal
se, False, False], [False, False, False, False, False, False, False, False, Fa
lse, False, False, False, False, False, False, False, False, False, False, Fal
se], [False, False, False, False, False, False, False, False, False, False, Fa
lse, False, False, False, False, False, False, False, False, False], [False, F
alse, False, False, False, False, False, False, False, False, False, False, Fa
lse, False, False, False, False, False, False, False], [False, False, False, F
alse, False, False, False, False, False, False, False, False, False, False, Fa
lse, False, False, False, False, False], [False, False, False, False, False, F
alse, False, False, False, False, False, False, False, False, False, False, Fa
lse, False, False, False]], [[False, False, False, False, False, False, False,
False, False, False, False, False, False, False, False, False, False, False, F
alse, False], [False, False, False, False, False, False, False, False, False,
False, False, False, False, False, False, False, False, False, False, False],
[False, False, False, False, False, False, False, False, False, False, False,
False, False, False, False, False, False, False, False, False], [False, False,
False, False, False, False, False, False, False, False, False, False, False, F
alse, False, False, False, False, False, False], [False, False, False, False,
False, False, False, False, False, False, False, False, False, False, False, F
alse, False, False, False, False], [False, False, False, False, False, False,
False, False, False, False, False, False, False, False, False, False, False, F
alse, False, False], [False, False, False, False, False, False, False, False,
False, False, False, False, False, False, False, False, False, False, False, F
alse], [False, False, False, False, False, False, False, False, False, False,
False, False, False, False, False, False, False, False, False, False], [False,
False, False, False, False, False, False, False, False, False, False, False, F
alse, False, False, False, False, False, False, False], [False, False, False,
False, False, False, False, False, False, False, False, False, False, True, Fa
lse, False, False, False, False, False], [False, False, False, False, False, F
alse, False, False, False, False, False, False, False, False, False, False, Fa
lse, False, False, False], [False, False, False, False, False, False, False, F
alse, False, False, False, False, False, False, False, False, False, False, Fa
lse, False], [False, False, False, False, False, False, False, False, False, F
alse, False, False, False, False, False, False, False, False, False, False],
[False, False, False, False, False, False, False, False, False, False, False,
False, False, False, False, False, False, False, False, False], [False, False,
False, False, False, False, False, False, False, False, False, False, False, F
alse, False, False, False, False, False, False]], [[False, False, False, Fals
e, False, False, False, False, False, False, False, False, False, False, Fals
e, False, False, False, False, False], [False, False, False, False, False, Fal
se, False, False, False, False, False, False, False, False, False, False, Fals
e, False, False, False], [False, False, False, False, False, False, False, Fal
se, False, False, False, False, False, False, False, False, False, False, Fals
e, False], [False, False, False, False, False, False, False, False, False, Fal
se, False, False, False, False, False, False, False, False, False, False], [Fa
lse, False, False, False, False, False, False, False, False, False, False, Fal
se, False, False, False, False, False, False, False, False], [False, False, Fa
lse, False, False, False, False, False, False, False, False, False, False, Fal
se, False, False, False, False, False, False], [False, False, False, False, Fa
lse, False, False, False, False, False, False, False, False, False, False, Fal
se, False, False, False, False], [False, False, False, False, False, False, Fa
lse, False, False, False, False, False, False, False, False, False, False, Fal
44 of 45 09/07/2019, 16:54
Modul 3 http://localhost:8888/nbconvert/html/Desktop/Digital Talent/Modul 3....
In [ ]:
45 of 45 09/07/2019, 16:54