Latihan Sebelum UAS

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

Misalkan program di bawah (kolom kiri) dijalankan dan file emails1.

txt
berisi email-email berikut pada baris-baris berbeda (kolom kanan).
Apa yang akan muncul pada emails2.txt?
program file emails1.txt
Misalkan program di bawah (kolom kiri) dijalankan dan file emails1.txt
berisi email-email berikut pada baris-baris berbeda (kolom kanan).
Apa yang akan muncul pada emails2.txt?
program file emails1.txt

file emails2.txt
Terdapat pesan error invalid syntax saat menjalankan baris program berikut ini.
Perbaiki kode agar memberikan hasil yang diinginkan tanpa error.

Expected output:
Terdapat pesan error invalid syntax saat menjalankan baris program berikut ini.
Perbaiki kode agar memberikan hasil yang diinginkan tanpa error.

Expected output:

s = "He said, \"You are the cause of my euphoria\""


print(s)

s = """He said, "You are the cause of my euphoria" """ # perhatikan spasinya
print(s)
Apa yang dicetak?

bonus = 1000
num_users = 10

try:
if num_users > 0:
bonus_per_user = bonus / num_users
print("Bonus per user: " + bonus_per_user)
except ZeroDivisionError:
print("Can't divide by zero")
except NameError:
print("Variable not assigned")
except:
print("Some other error")
print("Program finishes successfully.")
Apa yang dicetak?

bonus = 1000
num_users = 10

try:
if num_users > 0:
bonus_per_user = bonus / num_users # 100.0
print("Bonus per user: " + bonus_per_user)
except ZeroDivisionError:
print("Can't divide by zero")
except NameError:
print("Variable not assigned")
except: # wildcard, catching any exception types
print("Some other error")
print("Program finishes successfully.")
Apa yang terjadi, asumsi file pantun.txt tidak ada (nonexisting)?

try:
fileku = open("pantun.txt", "r")
x = fileku.read(1)
print(x)
raise Exception("Terjadi exception")
except:
print("File tidak ditemukan")
finally:
fileku.close()
print("Selesai")
Apa yang terjadi, asumsi file pantun.txt tidak ada (nonexisting)?

try:
fileku = open("pantun.txt", "r") # error happens before variable assignment
x = fileku.read(1)
print(x)
raise Exception("Terjadi exception")
except:
print("File tidak ditemukan")
finally:
fileku.close()
print("Selesai")
Apa yang dilakukan oleh fungsi berikut, asumsi param x dipastikan bertipe list?

def m(x):
z = []
for y in x:
if y % 2:
z += [y]
return sum(z)
Apa yang dilakukan oleh fungsi berikut, asumsi param x dipastikan bertipe list?

def m(x):
z = []
for y in x:
if y % 2: # either 0 (False) or 1 (True)
z += [y]
return sum(z)

>>> m([1,3,6,6,2,1]) Menghitung sum dari elemen-elemen pada


5 x
>>> m([6,6,2,2]) yang bersifat ganjil.
0
Kode Python berikut dimaksudkan untuk mencari karakter pada suatu string dengan
Unicode code point terbesar. Namun, terdapat bug pada kode Python tersebut, yakni pada
baris ke?
def l4rg3st(s):
if len(s) == 0:
return None
else:
mx = "a"
for c in s:
if c > mx:
mx = c
return mx
Kode Python berikut dimaksudkan untuk mencari karakter pada suatu string dengan
Unicode code point terbesar. Namun, terdapat bug pada kode Python tersebut, yakni pada
baris ke?
def l4rg3st(s):
if len(s) == 0:
return None
else:
mx = "a" # harusnya s[0]
for c in s:
if c > mx:
mx = c
return mx

>>> l4rg3st("abcd")
'd'
>>> l4rg3st("ABCD")
'a'
>>> l4rg3st("0123")
'a'
Apa yang dilakukan oleh fungsi Python di bawah ini apabila parameter lst dipastikan
berupa int list yang tidak kosong?

def f(lst):
sum = None
for i in lst:
for j in lst:
return i
return sum
Apa yang dilakukan oleh fungsi Python di bawah ini apabila parameter lst dipastikan
berupa int list yang tidak kosong?

def f(lst):
sum = None
for i in lst:
for j in lst:
return i
return sum

>>> f([1,2,3]) Mengembalikan elemen index ke-0 pada list lst


1
>>> f([6,10,9])
6
What is the output and why?

a = set("what")
b = set("whatis")
c = set("whatisthe")
d = set("whatistheoutput")

print(len(a-b-c-d))
print(len(d-c-b-a))
print(len(a&b&c&d))
print(len(a|b|c|d))
print(a <= b <= c <= d)
What is the output and why?

a = set("what") # {'h', 'w', 'a', 't'}


b = set("whatis") # {'i', 'h', 't', 'w', 's', 'a'}
c = set("whatisthe") # {'i', 'h', 't', 'w', 'e', 's', 'a'}
d = set("whatistheoutput") # {'i', 'h', 't', 'u', 'o', 'w', 'e', 's', 'a', 'p'}

print(len(a-b-c-d)) # set difference


print(len(d-c-b-a)) # set difference
print(len(a&b&c&d)) # set intersection
print(len(a|b|c|d)) # set union
print(a <= b <= c <= d) # subset
What is the output and why?

dct = dict()
a_int = 1
for x in "p455word4":
try:
dct[int(x)] = a_int
except ValueError:
a_int += 1
print(dct)
What is the output and why?

dct = dict()
a_int = 1
for x in "p455word4":
try:
dct[int(x)] = a_int
except ValueError:
a_int += 1
print(dct)
What is this function about?

def m(dct):
values = set()
for key, value in dct.items():
if value in values:
return True
else:
values.add(value)
return False
What is this function about?

def m(dct):
values = set()
for key, value in dct.items():
if value in values:
return True
else:
values.add(value)
return False
Create a recursive function to return the length of a list
Create a recursive function to return the length of a list

def r(lst):
if not lst: # base case
return 0
else: # recursive case
return 1 + r(lst[1:])

print(r([])) # 0
print(r([1])) # 1
print(r([1,2])) # 2
What's the output and why?
class Gadget(object):

def __init__(self, merek, tipe):


self.merek = merek
self.tipe = tipe

def __str__(self):
return f'Gadget {self.merek} dengan tipe {self.tipe}'

class Handphone(Gadget):

def __init__(self, merek, tipe, os):


super().__init__(merek, tipe)
self.os = os

def __str__(self):
return super().__str__() + f': Handphone {self.merek} dengan OS {self.os}'

class Tablet(Gadget):

def __init__ (self, merek, tipe, ukuran):


super(). __init__(merek, tipe)
self.ukuran = ukuran

def __str__(self):
return f'Tablet berukuran {self.ukuran} inch'

hp = Handphone("CiaoMie", 2, "Doors")
print(hp)
tb = Tablet("Sungsam", 3, 10)
print(tb)
What's the output and why?
class Gadget(object):

def __init__(self, merek, tipe):


self.merek = merek
self.tipe = tipe

def __str__(self):
return f'Gadget {self.merek} dengan tipe {self.tipe}'

class Handphone(Gadget):

def __init__(self, merek, tipe, os):


super().__init__(merek, tipe)
self.os = os

def __str__(self):
return super().__str__() + f': Handphone {self.merek} dengan OS {self.os}'

class Tablet(Gadget):

def __init__ (self, merek, tipe, ukuran):


super(). __init__(merek, tipe)
self.ukuran = ukuran

def __str__(self):
return f'Tablet berukuran {self.ukuran} inch'

hp = Handphone("CiaoMie", 2, "Doors")
print(hp)
tb = Tablet("Sungsam", 3, 10)
print(tb)
How does the GUI look like and how's the GUI interaction?
from tkinter import *

class Voting:

def __init__(self, window):


self.window = window
self.window.geometry("150x50")
self.countA = 0
self.countB = 0
self.label = Label(window, text=self.display_text())
self.label.grid(row=0, column=0, columnspan=2)
self.tombol1 = Button(window, text="A", command=self.button_pressedA)
self.tombol1.grid(row=1, column=0)
self.tombol2 = Button(window, text="B", command=self.button_pressedB)
self.tombol2.grid(row=1, column=1)

def display_text(self):
return "A: " + str(self.countA) + " -- B: " + str(self.countB)

def button_pressedA(self):
self.countA += 1
self.label["text"] = self.display_text()

def button_pressedB(self):
self.countB += 1
self.label["text"] = self.display_text()

window = Tk()
Voting(window)
window.mainloop()
How does the GUI look like and how's the GUI interaction?
from tkinter import *

class Voting:

def __init__(self, window):


self.window = window
self.window.geometry("150x50")
self.countA = 0
self.countB = 0
self.label = Label(window, text=self.display_text())
self.label.grid(row=0, column=0, columnspan=2)
self.tombol1 = Button(window, text="A", command=self.button_pressedA)
self.tombol1.grid(row=1, column=0)
self.tombol2 = Button(window, text="B", command=self.button_pressedB)
self.tombol2.grid(row=1, column=1)

def display_text(self):
return "A: " + str(self.countA) + " -- B: " + str(self.countB)

def button_pressedA(self):
self.countA += 1
self.label["text"] = self.display_text()

def button_pressedB(self):
self.countB += 1
self.label["text"] = self.display_text()

window = Tk()
Voting(window)
window.mainloop()

You might also like