Anda di halaman 1dari 39

CSGE601020 - Dasar-Dasar Pemrograman 1

ngodingceria
Fariz Darari
Outline

Kali ini kita akan live coding untuk


memberi gambaran materi-materi
yang akan kalian dapatkan
selanjutnya.

2
3
Variables; Data Types; Number Systems
Perkalian (Oops!)
a = input()
b = input()
s = a * b
print(s)

4
Variables; Data Types; Number Systems
Perkalian
a = int(input())
b = float(input())
s = a * b
print(s)

5
Variables; Data Types; Number Systems
Baper
teganya = " teganya"
print("sungguh", teganya*10, "dirimu :(")

6
Variables; Data Types; Number Systems
Celcius ke Fahrenheit berdasar Input
# lengkapi

7
Variables; Data Types; Number Systems
Celcius ke Fahrenheit berdasar Input
celcius = float(input("Suhu celcius: "))
fahrenheit = celcius * 9 / 5 + 32 # coba kalian ganti dgn 32 + celcius * 9 / 5
print("Suhu fahrenheit:", fahrenheit)

8
Variables; Data Types; Number Systems
Celcius ke Fahrenheit berdasar Input (Salah!)
celcius = float(input("Suhu celcius: "))
fahrenheit = celcius * 9 // 5 + 32
print("Suhu fahrenheit:", fahrenheit)

9
Variables; Data Types; Number Systems
Diskon Dobel: Buat program yang menerima input harga,
diskon awal, dan diskon tambahan, dan menghasilkan output
harga setelah diskon

Contoh: Apabila harganya 100000, diskon awal 70%, dan diskon


tambahan 20%, maka harga setelah diskon = 24000
kode ""

10
Variables; Data Types; Number Systems
Diskon Dobel
harga = int(input("Harga: "))
diskon1 = int(input("Diskon 1: "))
diskon2 = int(input("Diskon 2: "))
harga_final = harga * ((100-diskon1)/100) * ((100-diskon2)/100)
print("Harga final:", harga_final)

11
Control Mechanisms: Selection & Repetition
Ke Dokter atau Tidak?
suhu_tubuh = float(input("Suhu tubuh (celcius): "))

if suhu_tubuh > 37.5:


print("Ke dokter!")
else:
print("Aman")

12
Control Mechanisms: Selection & Repetition
Dihukum
hukuman = "saya tidak akan lagi malas belajar DDP"
jumlah_pengulangan = 100
while jumlah_pengulangan > 0:
print(jumlah_pengulangan, hukuman)
jumlah_pengulangan = jumlah_pengulangan - 1

13
Control Mechanisms: Selection & Repetition
Dihukum Berlipat
hukuman = "saya tidak akan lagi malas belajar DDP"
jumlah_pengulangan1 = 100
while jumlah_pengulangan1 > 0:
jumlah_pengulangan2 = 100
while jumlah_pengulangan2 > 0:
print(jumlah_pengulangan1, jumlah_pengulangan2, hukuman)
jumlah_pengulangan2 = jumlah_pengulangan2 - 1
jumlah_pengulangan1 = jumlah_pengulangan1 - 1

14
Control Mechanisms: Selection & Repetition
Dihukum Selamanya 
hukuman = "saya tidak akan lagi malas belajar DDP"

while True:
print(hukuman)

15
Strings & Slicing
Ambil Angka dari String (Oops!)
contoh = "h4l0!!!"

for char in contoh:


if char == '0' and char == '1' and char == '2' and char == '3' and char ==
'4' and char == '5' and char == '6' and char == '7' and char == '8' and char ==
'9':
print(char)

16
Strings & Slicing
Ambil Angka dari String
contoh = "h4l0!!!"

for char in contoh:


if char == '0' or char == '1' or char == '2' or char == '3' or char == '4' or
char == '5' or char == '6' or char == '7' or char == '8' or char == '9':
print(char)

17
Strings & Slicing
Memotong "semangka"
semangka = "semangka"

potongan1 = semangka[0:2]
potongan2 = semangka[2:6]
potongan3 = semangka[6:]

print(potongan1)
print(potongan2)
print(potongan3)

18
Text Files and Exceptions
Swabaca.py
this_file = open("Swabaca.py", "r") # nantinya akan ada banyak mode baca file (mis. "w"), tidak hanya "r"
for tiap_line in this_file:
print(tiap_line,end="") # by default, print advances to the next line, but you can override that behavior
this_file.close()

19
Text Files and Exceptions
Filenya mana?
this_file = open("Swabacaca.py", "r") # nantinya akan ada banyak mode baca file (mis. "w"), tidak hanya "r"
for tiap_line in this_file:
print(tiap_line,end="") # by default, print advances to the next line, but you can override that behavior
this_file.close()
print("Program selesai!")

20
Text Files and Exceptions
Filenya mana? + Exception Handler
try:
this_file = open("Swabacaca.py", "r")
for tiap_line in this_file:
print(tiap_line,end="")
this_file.close()
except FileNotFoundError:
print("Filenya tidak ada.")
print("Program selesai!")

21
Functions; Parameter Passing
Celcius ke Fahrenheit sebagai Fungsi
def dariCelciusKeFahrenheit(x): # function definition utk fungsi konversi c ke f
return x * 9 / 5 + 32

celcius = float(input("Suhu celcius: "))


print("Suhu fahrenheit:",dariCelciusKeFahrenheit(celcius))

22
Functions; Parameter Passing
Tanpa Kembalian
def tanpaKembalian(x):
pass

tanpaKembalian(99000)

23
Functions; Parameter Passing
Tanpa Kembalian (Sebenarnya Ada Yakni None*)
def tanpaKembalian(x):
pass

print(tanpaKembalian(99000))

* Special value di Python, tidak sama dengan string "None" 


24
Lists, Tuples & Mutability
Ambil Angka dari String (Versi List)
list_angka = ['0','1','2','3','4','5','6','7','8','9']

contoh = "h4l0!!!"

for char in contoh:


if char in list_angka:
print(char)

25
Lists, Tuples & Mutability
List vs. Tuple
ini_list = [1,2,3]
ini_tuple = (1,2,3)

ini_list[0] = 8
print(ini_list)

ini_tuple[0] = 8
print(ini_tuple)

26
Lists, Tuples & Mutability
List vs. String
ini_list = ["a","b","c"]
ini_str = "abc"

ini_list[0] = "z"
print(ini_list)

ini_str[0] = "z"
print(ini_str)

27
Sets; Dictionaries
Jangan Menyimpan Uang Pakai Set
dompet = {1000, 10000, 20000, 20000, 20000, 20000, 20000}

print("Uang di dompet:",dompet)

28
Sets; Dictionaries
Ibukota
dict_ibukota = {'indonesia':'jakarta', 'italia':'roma', 'jerman':'berlin'}

for nama_negara in dict_ibukota:


print("ibukota dari", nama_negara, "adalah",dict_ibukota[nama_negara])

29
Sets; Dictionaries
Tebak Angka 1-9
import random

to_guess = random.randint(1,9) # get a random number between 1 and 9

is_right_guess = False # by default the guess is false


while not is_right_guess:
input_number = int(input("Guess a number from 1 to 9: "))

if input_number == to_guess: # if the guess is correct


print("Nice!")
is_right_guess = True
elif input_number < to_guess: # if too low
print("Too low!")
else: # if too high
print("Too high!")

30
Classes
Tebak Tipe
print(type(1))
print(type(1.0))
print(type("1.0"))
print(type(True))

31
Classes
MahasiswaDDP
class MahasiswaDDP:

matkul = "DDP" # class attribute

def __init__(self, name): # __init__ adalah special method untuk instantiation


self.name = name # name di sini adalah instance attribute

def menyapa(self): # self merefer ke instance yang memanggil method


print(self.name,": \"Hallo!\"")

fariz = MahasiswaDDP('Fariz')
cenna = MahasiswaDDP('Cenna')

print(fariz.matkul)
print(cenna.matkul)
print(fariz.name)
print(cenna.name)
fariz.menyapa()
cenna.menyapa()
32
Classes
MahasiswaDDPGalak
# copas definisi class MahasiswaDDP di atas sini...
class MahasiswaDDPGalak(MahasiswaDDP): # MahasiswaDDP adalah superclassnya

def menyapa(self):
print(self.name,": \"Gukk!\"")

fariz = MahasiswaDDP('Fariz')
cenna = MahasiswaDDP('Cenna')
budi = MahasiswaDDPGalak('Budi')

print(fariz.matkul)
print(cenna.matkul)
print(budi.matkul)
print(fariz.name)
print(cenna.name)
print(budi.name)
fariz.menyapa()
cenna.menyapa()
budi.menyapa()
33
GUI
yukngoding GUI
from tkinter import *

class ProcessButtonEvent:
def __init__(self):
window = Tk()
label = Label(window, text = "yukngoding")
btYUK = Button(window, text = 'yuk', fg = 'red')
btYUKAH = Button(window, text = 'yuk ah', fg = 'green')
label.pack()
btYUK.pack()
btYUKAH.pack()
window.mainloop()

ob = ProcessButtonEvent()

34
GUI with Event Handlers
yukngoding GUI v2
from tkinter import *

class ProcessButtonEvent:
def __init__(self):
window = Tk()
label = Label(window, text = "yukngoding")
btYUK = Button(window, text = 'yuk', fg = 'red', command = self.processYUK)
btYUKAH = Button(window, text = 'yuk ah', fg = 'green', command =
window.destroy)
label.pack()
btYUK.pack()
btYUKAH.pack()
window.mainloop()

def processYUK(self):
print("yuk clicked")

ob = ProcessButtonEvent()

35
Recursion
Factorial
def factorial(n):
if n < 1: # base case
return 1
else:
return n * factorial(n-1)

print(factorial(0))
print(factorial(1))
print(factorial(2))
print(factorial(3))
print(factorial(4))

36
Pada materi selanjutnya,
kalian akan belajar seluk-beluk semua kode tadi.
Ingat,
"The devil is in the details"
Saat ujian nanti, soalnya akan menuntut
pemahaman yang dalam tentang DDP 

Foto kalian ketika badai tugas Python ;-)

37
Bonus
Misteri
size = int(input("Berapa ukurannya? "))

i = 0
while(i < size):
sp = size - (i + 1)
st = 2 * i + 1
print(" "*sp + "*"*st)
i += 1

38
Bonus
Satu-Satu Aku Sayang Ibu
for i in [0,1]:
print("satu")

print("aku sayang ibu")


print()

for i in [10,11]:
print("dua")

print("juga sayang ayah")


print()

for i in ["0","1"]:
print("tiga")

print("sayang adik kakak")


print()

for i in range(1,4): # this range generates a sequence of numbers starting from 1 to 3


print(i)

print("sayang semuanya")
39

Anda mungkin juga menyukai