0% menganggap dokumen ini bermanfaat (0 suara)
880 tayangan

Modul 3

Modul ini membahas beberapa topik sebagai berikut: 1. Operator relasional dan aritmatika 2. Struktur pemilihan if-elif-else dan perulangan while, for 3. Statemen loncat dan operasi logika/bitwise 4. Penggunaan list dan array

Diunggah oleh

syaifulbachri.071
Hak Cipta
© © All Rights Reserved
Format Tersedia
Unduh sebagai PDF, TXT atau baca online di Scribd
0% menganggap dokumen ini bermanfaat (0 suara)
880 tayangan

Modul 3

Modul ini membahas beberapa topik sebagai berikut: 1. Operator relasional dan aritmatika 2. Struktur pemilihan if-elif-else dan perulangan while, for 3. Statemen loncat dan operasi logika/bitwise 4. Penggunaan list dan array

Diunggah oleh

syaifulbachri.071
Hak Cipta
© © All Rights Reserved
Format Tersedia
Unduh sebagai PDF, TXT atau baca online di Scribd
Anda di halaman 1/ 45

Modul 3 http://localhost:8888/nbconvert/html/Desktop/Digital Talent/Modul 3....

Module ini akan menjelaskan beberapa materi sebagai berikut :

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 :

Berikut merupakan mindmap dari operasi 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 :

Statement if untuk satu kasus


Statement if untuk dua kasus
Statement if untuk tiga kasus

1. Statement if untuk satu kasus


Bentuk umum penggunaan perintah if untuk satu kasus dalam Python adalah :

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.

Perhatikan contoh berikut :

In [3]: a = 5
b = 5

if a==b:
print("a dan b bernilai sama")

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....

2. Statement if untuk dua kasus


Untuk pemilihan yang mengandung dua kasus, bentuk umum yang digunakan adalah :

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.

Perhatikan contoh dibawah :

In [9]: a = baca
b = tulis

if a==b:
print("a dan b bernilai sama")
else:
print("a dan b bernilai berbeda")

a dan b bernilai sama

In [ ]: # read two numbers


number1 = int(input("Enter the first number: "))
number2 = int(input("Enter the second number: "))

# choose the larger number


if number1 > number2:
largerNumber = number1
else:
largerNumber = number2

# print the result


print("The larger number is:", largerNumber)

Latihan 1

In [16]: def main():


bilangan = int(input("Masukkan bilangan bulat : "))

if bilangan %2 ==0:
print("%d adalah bilangan genap" %bilangan)
else:
print(" %d adalah bilangan ganjil"%bilangan)
main()

Masukkan bilangan bulat : 8


adalah bilangan genap 8

5 of 45 09/07/2019, 16:54
Modul 3 http://localhost:8888/nbconvert/html/Desktop/Digital Talent/Modul 3....

3. Statement if untuk Tiga kasus atau lebih


Struktur pemilihan jenis ini merupakan bentuk yang paling kompleks jika dibandingkan dengan kedua jenis yang sudah di
bahas diatas. Dalam struktur ini, ada beberapa kondisi yang harus diperiksa oleh program. Bentuk umum penggunaan
perintah if untuk tiga kasus atau lebih adalah :

if kondisi1:
statement1a
statement1b
...
elif kondisi2:
statement2a
statement2b
...
else:
statement_alternatif1
statement_alternatif2
...

Perhatikan contoh dibawah ini :

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

Tuliskan kondisi tersebut dalam bahasa Python.

In [17]: def main():


#input nilai x dan y
print("Memasukkan nilai koordinat")
x = int(input("Masukkan nilai x :"))
y = int(input("Masukkan nilai y :"))

#memeriksa nilai x dan y


if x>0 and y>0 :
print("Koordinat ("+ str(x) + "," + str(y) +") berada pada kuardran " +
"I")
elif x<0 and y>0 :
print("Koordinat ("+ str(x) + "," + str(y) +") berada pada kuardran " +
"II")
elif x<0 and y<0 :
print("Koordinat ("+ str(x) + "," + str(y) +") berada pada kuardran " +
"III")
elif x>0 and y<0 :
print("Koordinat ("+ str(x) + "," + str(y) +") berada pada kuardran " +
"IV")
else :
pass
main()

Memasukkan nilai koordinat


Masukkan nilai x :3
Masukkan nilai y :4
Koordinat (3,4) berada pada kuardran I

7 of 45 09/07/2019, 16:54
Modul 3 http://localhost:8888/nbconvert/html/Desktop/Digital Talent/Modul 3....

Latihan 3 . Mencari bilangan terbesar

In [11]: # read three numbers


number1 = int(input("Enter the first number: "))
number2 = int(input("Enter the second number: "))
number3 = int(input("Enter the third number: "))

# we temporarily assume that the first number


# is the largest one
# we will verify it soon
largestNumber = number1

# we check if the second number is larger than current largestNumber


# and update largestNumber if needed
if number2 > largestNumber:
largestNumber = number2

# we check if the third number is larger than current largestNumber


# and update largestNumber if needed
if number3 > largestNumber:
largestNumber = number3

# print the result


print("The largest number is:", largestNumber)

Enter the first number: 8


Enter the second number: 9
Enter the third number: 10
The largest number is: 10

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

In [1]: plant = input("Please input a best plant = ")

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

Please input a best plant = Spathiphylum


Spathiphyllum! Not Spathiphylum!

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.

Tugas anda adalah membuat tax calculator.

Harus menerima satu masukan : penghasilan


Berikutnya, print pajak yang telah dihitung, nilai dibulatkan penuh ke thaler (tanpa sen). Fungsi round() akan
membantu anda untuk membulatkan nilai.

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.

income = float(input("Enter the annual income: "))

#
# Put your code here.
#

tax = round(tax, 0)
print("The tax is:", tax, "thalers")

Test your code using the data we've provided.

Sample input: 10000

Expected output: The tax is: 1244.0 thalers

Sample input: 100000

Expected output: The tax is: 19470.0 thalers

Sample input: 1000

Expected output: The tax is: 0.0 thalers

Sample input: -100

Expected output: The tax is: 0.0 thalers

9 of 45 09/07/2019, 16:54
Modul 3 http://localhost:8888/nbconvert/html/Desktop/Digital Talent/Modul 3....

In [27]: income = float(input("Enter the annual income: "))


tax = 0

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

print("The tax is:", tax, "thalers")

Enter the annual income: 1000


The tax is: 0 thalers

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:

if the year number isn't divisible by four, it's a common year;


otherwise, if the year number isn't divisible by 100, it's a leap year;
otherwise, if the year number isn't divisible by 400, it's a common year;
otherwise, it's a leap 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.

year = int(input("Enter a year: "))

#
# 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.

Test your code using the data we've provided.

Sample input: 2000

Expected output: Leap year

Sample input: 2015

Expected output: Common year

Sample input: 1999

Expected output: Common year

Sample input: 1996

Expected output: Leap year

Sample input: 1580

Expected output: Not within the Gregorian calendar period

11 of 45 09/07/2019, 16:54
Modul 3 http://localhost:8888/nbconvert/html/Desktop/Digital Talent/Modul 3....

In [29]: year = int(input("Enter a year: "))

if year < 1582:


print("Not within the Gregorian calender period")
else :
if year % 4 !=0 :
print("common year")
elif year % 100 !=0:
print ("leap year")
elif year % 400 !=0:
print("common year")
else :
print("leap year")

Enter a year: 1580


Not within the Gregorian calender period

Latihan 3

1. Apakah luaran dari syntax berikut :

In [ ]: x = 5
y = 10
z = 8

print(x > y)
print(y > z)

1. Apakah luaran dari syntax berikut :

In [ ]: x, y, z = 5, 10, 8

print(x > z)
print((y - 5) == x)

1. Apakah luaran dari syntax berikut :

In [ ]: x, y, z = 5, 10, 8
x, y, z = z, y, x

print(x > z)
print((y - 5) == x)

1. Apakah luaran dari syntax berikut :

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....

1. Apakah luaran dari syntax berikut :

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

1. Apakah luaran dari syntax berikut :

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:

In [6]: # we will store the current largest number here


largestNumber = -999999999

# input the first value


number = int(input("Enter a number or type -1 to stop: "))

# if the number is not equal to -1, we will continue


while number != -1:
# is number larger than largestNumber?
if number > largestNumber:
# yes, update largestNumber
largestNumber = number
# input the next number
number = int(input("Enter a number or type -1 to stop: "))

# print the largest number


print("The largest number is:", largestNumber)

Enter a number or type -1 to stop: 8


Enter a number or type -1 to stop: 1
Enter a number or type -1 to stop: 2
Enter a number or type -1 to stop: -2
Enter a number or type -1 to stop: -9
Enter a number or type -1 to stop: -1
The largest number is: 8

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....

In [ ]: # program that reads a sequence of numbers


# and counts how many numbers are even and how many are odd
# program terminates when zero is entered

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:

will ask the user to enter an integer number;


will use a while loop;
will check whether the number entered by the user is the same as the number picked by the magician. If the number
chosen by the user is different than the magician's secret number, the user should see the message "Ha ha!
You're stuck in my loop!" and be prompted to enter a number again. If the number entered by the user
matches the number picked by the magician, the number should be printed to the screen, and the magician should
say the following words: "Well done, muggle! You are free now."

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? |
+================================+
""")

The magician is counting on you! Don't disappoint him.

15 of 45 09/07/2019, 16:54
Modul 3 http://localhost:8888/nbconvert/html/Desktop/Digital Talent/Modul 3....

In [33]: 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? |
+================================+
""")

guessNumber = 0

while guessNumber != secretNumber:


guessNumber = int(input("So, what is the secret number? "))
if guessNumber != secretNumber:
print("Ha ha! You're stuck in my loop!")

print("Well done, muggle! You are free now.")

+================================+
| Welcome to my game, muggle! |
| Enter an integer number |
| and guess what number I've |
| picked for you. |
| So, what is the secret number? |
+================================+

So, what is the secret number? 80


Ha ha! You're stuck in my loop!
So, what is the secret number? 90
Ha ha! You're stuck in my loop!
So, what is the secret number? 88
Ha ha! You're stuck in my loop!
So, what is the secret number? 100
Ha ha! You're stuck in my loop!
So, what is the secret number? 777
Well done, muggle! You are free now.

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.

Bentuk perintah for dapat dituliskan sebagai berikut :

1. Statement for untuk perintah koleksi

for indeks tipe koleksi:


statement1
statement2
...

2. Statement for untuk rentang nilai tertentu

for indeks in range (nilai_awal, nilai_akhir, step):


statement1
statement2
...

Perhatikan contoh-contoh dibawah ini :

In [34]: for i in range(10):


print("The value of i is currently", i)

The value of i is currently 0


The value of i is currently 1
The value of i is currently 2
The value of i is currently 3
The value of i is currently 4
The value of i is currently 5
The value of i is currently 6
The value of i is currently 7
The value of i is currently 8
The value of i is currently 9

In [35]: for i in range(2, 8):


print("The value of i is currently", i)

The value of i is currently 2


The value of i is currently 3
The value of i is currently 4
The value of i is currently 5
The value of i is currently 6
The value of i is currently 7

In [36]: for i in range(2, 8, 3):


print("The value of i is currently", i)

The value of i is currently 2


The value of i is currently 5

For - else

17 of 45 09/07/2019, 16:54
Modul 3 http://localhost:8888/nbconvert/html/Desktop/Digital Talent/Modul 3....

In [9]: for i in range(5):


print(i)
else:
print("else:", i)

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

Use the skeleton we've provided in the editor.

import time

# Write a for loop that counts to five.


# Body of the loop - print the loop iteration number and the word "Mississipp
i".
# Body of the loop - use: time.sleep(1)

# Write a print function with the final message.

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....

In [11]: import time

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 :

In [13]: for i in range (11):


print (i,end=' ')
if i ==7:
break

0 1 2 3 4 5 6 7

In [1]: # break - example

print("The break instruction:")


for i in range(1, 6):
if i == 5:
break
print("Inside the loop.", i)
print("Outside the loop.")

The break instruction:


Inside the loop. 1
Inside the loop. 2
Inside the loop. 3
Inside the loop. 4
Outside the loop.

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)

In [4]: import time


for i in range (1,11):
if i % 2 ==0:
time.sleep(0.5)
continue
print(i, end='\t')
time.sleep(0.5)

1 3 5 7 9

In [7]: # continue - example


import time
print("\nThe continue instruction:")
for i in range(1, 6):
if i == 3:
time.sleep(1)
continue
print("Inside the loop.", i)
time.sleep(1)
print("Outside the loop.")
time.sleep(1)

The continue instruction:


Inside the loop. 1
Inside the loop. 2
Inside the loop. 4
Inside the loop. 5
Outside the loop.

20 of 45 09/07/2019, 16:54
Modul 3 http://localhost:8888/nbconvert/html/Desktop/Digital Talent/Modul 3....

In [9]: largestNumber = -99999999


counter = 0

number = int(input("Enter a number or type -1 to end program: "))

while number != -1:


if number == -1:
continue
counter += 1

if number > largestNumber:


largestNumber = number
number = int(input("Enter a number or type -1 to end program: "))

if counter:
print("The largest number is", largestNumber)
else:
print("You haven't entered any number.")

Enter a number or type -1 to end program: 2


Enter a number or type -1 to end program: 4
Enter a number or type -1 to end program: 5
Enter a number or type -1 to end program: 6
Enter a number or type -1 to end program: 7
Enter a number or type -1 to end program:

---------------------------------------------------------------------------
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:

ValueError: invalid literal for int() with base 10: ''

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.

In [5]: while True :


word = input("Masukkan Sebuah Kata untuk keluar dari perulangan = ")
if(word=="chupacabra"):
break

print("You've successfully left the loop")

Masukkan Sebuah Kata untuk keluar dari perulangan = chupacabra


You've successfully left the loop

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.

It can be used with both the while and for loops.

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.

Your program must:

ask the user to enter a word;


use userWord = userWord.upper() to convert the word entered by the user to upper case; we'll talk about the
so-called string methods and the upper() method very soon - don't worry;
use conditional execution and the continue statement to "eat" the following vowels A, E, I, O, U from the inputted
word;
print the uneaten letters to the screen, each one of them on a separate line.

# Prompt the user to enter a word


# and assign it to the userWord variable.

for letter in userWord:


# Complete the body of the for loop.

Test your program with the data we've provided for you.

Test data

Sample input: Gregory

Expected output:

G
R
G
R
Y

Sample input: abstemious

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....

In [3]: # Prompt the user to enter a word


# and assign it to the userWord variable.
userWord = input("Masukkan sebuah kata = ")

for letter in userWord:


if letter.upper() in ['A','I','U','E','O']:
continue

print(letter.upper())

Masukkan sebuah kata = HAYO BARU APA


H
Y

B
R

In [5]: wordWithoutVovels = ""

# Prompt the user to enter a word


# and assign it to the userWord variable.
userWord = input("Masukkan sebuah kata = ")

for letter in userWord:


if letter.upper() in ['A','I','U','E','O']:
continue

wordWithoutVovels += letter.upper()

print(wordWithoutVovels)

Masukkan sebuah kata = kamu adalah pahlawan bertopeng


KM DLH PHLWN BRTPNG

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.

The figure illustrates the rule used by the builders:

=== 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.

Test your code using the data we've provided.

Sample input: 6

Expected output: The height of the pyramid: 3

Sample input: 20

Expected output: The height of the pyramid: 5

Sample input: 1000

Expected output: The height of the pyramid: 44

Sample input: 2

Expected output: The height of the pyramid: 1

In [18]: blocks = int(input("Enter the number of blocks: "))


current_block = 0
height = 0
i= 0
while i<blocks:
height += 1
current_block += height
#print(height,i,current_block)
if current_block> blocks:
break

height -= 1

print("The height of the pyramid:", height)

Enter the number of blocks: 6


The height of the pyramid: 3

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

What is the output of the following code?

Exercise 7

What is the output of the following code?

1. Apakah output dari kode berikut?

In [ ]: n = 3

while n > 0:
print(n + 1)
n -= 1
else:
print(n)

1. Apakah output dari kode berikut?

In [ ]: n = range(4)

for num in n:
print(num - 1)
else:
print(num)

1. Apakah output dari kode berikut?

In [ ]: for i in range(0, 6, 3):


print(i)

JAWABAN

In [20]: for i in range(1, 11):


if i % 2 !=0:
print(i,end=' ')

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

In [6]: for ch in "[email protected]":


if ch == "@":
break
print(ch,end=' ')

r a t n a . l e s t a r i

In [11]: for digit in "0165031806510":


if digit == "0":
print ("x")
continue
print(digit)

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 and

Argument A Argument B A and B

False False False

False True False

True False False

True True True

Operasi Logika or

Argument A Argument B A or B

False False False

False True True

True False True

True True True

Operasi Logika not

Argument not Argument

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.

Perhatikan contoh dibawah ini :

In [34]: x = 1
y = 0

z = (x == y)# and (x == y)) #or not(x == y)


print(not(z))

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....

List dan Array


Tipe list dalam python sebenernya mirip dengan array normal pada bahasa pemrograman lain. List juga dapat
menampung beberapa tipe data sekaligus.

Bentuk umum untuk membuat list dalam python adalah :

nama_list = [nilai1, nilai2, nilai3,...]

Perhatikan contoh dibawah ini :

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]

In [28]: #bisa menampung berbagai tipe data


var = ["Digital", 90 , 1000.50 , "Talent"]
print(var)

['Digital', 90, 1000.5, 'Talent']

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 :

In [35]: numbers = [10, 5, 7, 2, 1]


print(numbers)
print(numbers[2])
print(numbers[0])

[10, 5, 7, 2, 1]
7
10

In [36]: numbers = [10, 5, 7, 2, 1]


print("Original list content:", numbers) # printing original list content

numbers[0] = 111
print("\nPrevious list content:", numbers) # printing previous list content

numbers[1] = numbers[4] # copying value of the fifth element to the second


print("Previous list content:", numbers) # printing previous list content

print("\nList length:", len(numbers)) # printing the list's length

Original list content: [10, 5, 7, 2, 1]

Previous list content: [111, 5, 7, 2, 1]


Previous list content: [111, 1, 7, 2, 1]

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 :

In [11]: lst = [100,200,300,400,500]


print(lst[-1])
print(lst[-2])
print(lst[-5])

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]

In [7]: myList = [8, 10, 6, 2, 4] # list to sort


swapped = True # it's a little fake - we need it to enter the while loop

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)

myList= [8, 10, 6, 2, 4] i= 0


myList[i]= 8
myList= [10, 8, 6, 2, 4] i= 1
myList= [10, 8, 6, 2, 4] i= 2
myList= [10, 8, 6, 2, 4] i= 3
myList[i]= 2
myList= [10, 8, 6, 4, 2] i= 0
myList= [10, 8, 6, 4, 2] i= 1
myList= [10, 8, 6, 4, 2] i= 2
myList= [10, 8, 6, 4, 2] i= 3
[10, 8, 6, 4, 2]

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)

How many elements do you want to sort: 5


Enter a list element: 9
Enter a list element: 12
Enter a list element: 2
Enter a list element: 0
Enter a list element: 7

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.

Your task is to:

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?

In [19]: hatList = [1, 2, 3, 4, 5] # This is an existing list of numbers hidden in the h


at.

# Step 1: write a line of code that prompts the user


# to replace the middle number with an integer number entered by the user.

# 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]

1. Menambah Elemen ke dalam list


Terdapat tiga cara untuk menambahkan elemen baru kedalam sebuah list yaitu :

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....

In [13]: buah = ["durian", "mangga", "apel"]


buah.append("jeruk","pisang")
print (buah)

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

TypeError: append() takes exactly one argument (2 given)

In [10]: myList = [] # creating an empty list

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 :

In [11]: buah = ["durian", "mangga", "apel"]


buah.insert(2,"kiwi")
print (buah)

['durian', 'mangga', 'kiwi', 'apel']

Menggunakan metode extend(). Metode ini digunakan untuk menyambung atau menggabungkan suatu list dengan
list yang lain. Perhatikan contoh berikut :

In [12]: buah = ["durian", "mangga", "apel"]


buah.extend(["jeruk","melon","nanas"])
print(buah)

['durian', 'mangga', 'apel', 'jeruk', 'melon', 'nanas']

Perhatikan juga contoh dibawah ini :

33 of 45 09/07/2019, 16:54
Modul 3 http://localhost:8888/nbconvert/html/Desktop/Digital Talent/Modul 3....

In [20]: numbers = [111, 7, 2, 1]


print(len(numbers))
print(numbers)

###

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]

2. Menghapus Elemen kedalam list


Menghapus elemen dapat dilakukan dengan :

nama_list.remove(nilai)

atau dengan memberikan indeksnya menggunakan instruksi delete :

del nama_list[indeks]

In [1]: numbers = [5,4,3,2,1]

del numbers[1] # removing the second element from the list


print("New list's length:", len(numbers)) # printing new list length
print("\nNew list content:", numbers) # printing current list content

New list's length: 4

New list content: [5, 3, 2, 1]

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 1: create an empty list named beatles ;


step 2: use the append() method to add the following members of the band to the list: John Lennon , Paul
McCartney , and George Harrison ;
step 3: use the for loop and the append() method to prompt the user to add the following members of the band
to the list: Stu Sutcliffe , and Pete Best ;
step 4: use the del instruction to remove Stu Sutcliffe and Pete Best from the list;
step 5: use the insert() method to add Ringo Starr to the beginning of the list. By the way, are you a Beatles
fan?

In [9]: beatles = ""


# step 1
print("Step 1:", beatles)

# step 2
print("Step 2:", beatles)

# step 3
print("Step 3:", beatles)

# step 4
print("Step 4:", beatles)

# step 5
print("Step 5:", beatles)

# testing list legth


print("The Fab", len(beatles))

Step 1:
Step 2:
Step 3:
Step 4:
Step 5:
The Fab 0

3. List Method (Advance)


xxxxxxx

Perhatikan contoh berikut :

35 of 45 09/07/2019, 16:54
Modul 3 http://localhost:8888/nbconvert/html/Desktop/Digital Talent/Modul 3....

In [22]: myList = [10, 1, 8, 3, 5]


total = 0

for i in range(len(myList)):
total += myList[i]

print(total)

27

In [2]: squares = [x ** 2 for x in range(10)]


print (squares)

[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]

In [3]: twos = [2 ** i for i in range(8)]


print(twos)

[1, 2, 4, 8, 16, 32, 64, 128]

In [4]: odds = [x for x in squares if x % 2 != 0 ]


print (odds)

[1, 9, 25, 49, 81]

1. List Dua Dimensi (Array)

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.

Perhatikan kode berikut :

In [11]: EMPTY = "-"


board = []

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 :

In [13]: EMPTY = "-"


ROOK = "ROOK"
KNIGHT = "KNIGHT"
PAWN = "PAWN"
board = []

for i in range(8):
row = [EMPTY for i in range(8)]
board.append(row)

#isi dengan ROOK


board[0][0] = ROOK
board[0][7] = ROOK
board[7][0] = ROOK
board[7][7] = ROOK

#isi dengan KNIGHT


board[4][2] = KNIGHT

#isi dengan PAWN


board[3][4] = PAWN

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....

2. List Multidimensi (Array)

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

In [4]: temps = [[0.5 for h in range(24)] for d in range(31)]


print (temps)

File "<ipython-input-4-d8ff1f0c4481>", line 1


temps = [[0.5 for h in range(24)] for 0.3 in range(31)]
^
SyntaxError: can't assign to literal

Kemudian, berikan pengaturan sebagai berikut :

In [2]: temps = [[0.0 for h in range(24)] for d in range(31)]

# 1. the monthly average noon temperature


sum = 0.0

for day in temps:


sum += day[11]

average = sum / 31

print("Average temperature at noon:", average)

# 2. the highest temperature during the whole month


highest = -100.0

for day in temps:


for temp in day:
if temp > highest:
highest = temp

print("The highest temperature was:", highest)

# 3.count the days when the temperature at noon was at least 20 ℃


hotDays = 0

for day in temps:


if day[11] > 20.0:
hotDays += 1

print(hotDays, "days were hot.")

Average temperature at noon: 0.0


The highest temperature was: 0.0
0 days were hot.

38 of 45 09/07/2019, 16:54
Modul 3 http://localhost:8888/nbconvert/html/Desktop/Digital Talent/Modul 3....

3. Array tiga dimensi

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.

Kode dibawah akan menghasilkan array :

39 of 45 09/07/2019, 16:54
Modul 3 http://localhost:8888/nbconvert/html/Desktop/Digital Talent/Modul 3....

In [17]: rooms = [[[False for r in range(20)] for f in range(15)] for t in range(3)]


print (rooms)

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....

Coba berikan input untuk kondisi bibawah ini :

1. Pesan satu kamar pada gedung 2, lantai 10, kamar 14


2. Kosongkan satu kamar pada gedung 1, lantai 5, kamar 2
3. Periksa apakah ada kamar kosong di lantai 15

42 of 45 09/07/2019, 16:54
Modul 3 http://localhost:8888/nbconvert/html/Desktop/Digital Talent/Modul 3....

In [18]: rooms = [[[False for r in range(20)] for f in range(15)] for t in range(3)]

rooms[1][9][13] = True
rooms[0][4][1] = False

print(rooms)

vacancy = 0

for roomNumber in range(20):


if not rooms[2][14][roomNumber]:
vacancy += 1

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

Anda mungkin juga menyukai