You are on page 1of 30

4/7/2021 AGNES MEILIANA_1A11_P27838020003_TUGAS 4

NAMA : AGNES MEILIANA


NIM : P27838020003
KELAS : 1A11
CHAPTER 11
In [41]:
d = {'dog' : 'has a tail and goes woof!',

'cat' : 'says meow',

'mouse' : 'chased by cats'}

word = input('Enter a word: ')

print('The definition is:', d[word])

#Untuk menggunakan kamus sebagai kamus definisi yang sebenarnya

Enter a word: cat

The definition is: says meow

In [43]:
numerals = {'I':1, 'V':5, 'X':10, 'L':50, 'C':100, 'D':500, 'M':1000}

word = input('Enter a word: ')

print('The roman numerals is:', numerals[word])

#program yang bekerja dengan angka Romawi.

Enter a word: V

The roman numerals is: 5

In [19]:
points = {'A':1, 'B':3, 'C':3, 'D':2, 'E':1, 'F':4, 'G':2,

'H':4, 'I':1, 'J':8, 'K':5, 'L':1, 'M':3, 'N':1,

'O':1, 'P':3, 'Q':10, 'R':1, 'S':1, 'T':1, 'U':1,

'V':4, 'W':4, 'X':8, 'Y':4, 'Z':10}

key = input ('Enter a key :')

print('The points is:', points [key])

#Cell ini berisikan tentang permainan Scrabble

Enter a key :B

The points is: 3

In [21]:
deck = [{'value':i, 'suit':c}

for c in ['spades', 'clubs', 'hearts', 'diamonds']

for i in range(2,15)]

print (deck)

[{'value': 2, 'suit': 'spades'}, {'value': 3, 'suit': 'spades'}, {'value': 4, 'sui


t': 'spades'}, {'value': 5, 'suit': 'spades'}, {'value': 6, 'suit': 'spades'}, {'val
ue': 7, 'suit': 'spades'}, {'value': 8, 'suit': 'spades'}, {'value': 9, 'suit': 'spa
des'}, {'value': 10, 'suit': 'spades'}, {'value': 11, 'suit': 'spades'}, {'value': 1
2, 'suit': 'spades'}, {'value': 13, 'suit': 'spades'}, {'value': 14, 'suit': 'spade
s'}, {'value': 2, 'suit': 'clubs'}, {'value': 3, 'suit': 'clubs'}, {'value': 4, 'sui
t': 'clubs'}, {'value': 5, 'suit': 'clubs'}, {'value': 6, 'suit': 'clubs'}, {'valu
e': 7, 'suit': 'clubs'}, {'value': 8, 'suit': 'clubs'}, {'value': 9, 'suit': 'club
s'}, {'value': 10, 'suit': 'clubs'}, {'value': 11, 'suit': 'clubs'}, {'value': 12,
'suit': 'clubs'}, {'value': 13, 'suit': 'clubs'}, {'value': 14, 'suit': 'clubs'},
{'value': 2, 'suit': 'hearts'}, {'value': 3, 'suit': 'hearts'}, {'value': 4, 'suit':
'hearts'}, {'value': 5, 'suit': 'hearts'}, {'value': 6, 'suit': 'hearts'}, {'value':
7, 'suit': 'hearts'}, {'value': 8, 'suit': 'hearts'}, {'value': 9, 'suit': 'heart
s'}, {'value': 10, 'suit': 'hearts'}, {'value': 11, 'suit': 'hearts'}, {'value': 12,
localhost:8888/nbconvert/html/AGNES MEILIANA_1A11_P27838020003_TUGAS 4.ipynb?download=false 1/30
4/7/2021 AGNES MEILIANA_1A11_P27838020003_TUGAS 4

'suit': 'hearts'}, {'value': 13, 'suit': 'hearts'}, {'value': 14, 'suit': 'hearts'},
{'value': 2, 'suit': 'diamonds'}, {'value': 3, 'suit': 'diamonds'}, {'value': 4, 'su
it': 'diamonds'}, {'value': 5, 'suit': 'diamonds'}, {'value': 6, 'suit': 'diamond
s'}, {'value': 7, 'suit': 'diamonds'}, {'value': 8, 'suit': 'diamonds'}, {'value':
9, 'suit': 'diamonds'}, {'value': 10, 'suit': 'diamonds'}, {'value': 11, 'suit': 'di
amonds'}, {'value': 12, 'suit': 'diamonds'}, {'value': 13, 'suit': 'diamonds'}, {'va
lue': 14, 'suit': 'diamonds'}]

In [23]:
letter = input('Enter a letter: ')

if letter in d:

print('The value is', d[letter])

else:

print('Not in dictionary')

#Memeriksa kunci apakah ada di dalam kamus

Enter a letter: Semangat kawan

Not in dictionary

In [24]:
for key in d:

print(key)

#Mencetak kunci dalam kamus

dog

cat

mouse

In [25]:
for key in d:

print(d[key])

#Untuk mencetak nilai

has a tail and goes woof!

says meow

chased by cats

In [31]:
d = {'A':100, 'B':200, 'C':100}

L = [x[0] for x in d.items() if x[1]==100]

list (d.items())

#Untuk menemukan semua kunci dalam kamus d yang sesuai dengan nilai yang telah diten

Out[31]: [('A', 100), ('B', 200), ('C', 100)]

In [32]:
d = dict([('A',100),('B',300)])

list (d.items())

#Untuk membuat kamus berguna jika program Anda perlu membuat kamus saat sedang berja

Out[32]: [('A', 100), ('B', 300)]

EXERCISES
In [49]:
dic = { }

while True :

product = input("enter the name of product (enter q for quit )= ")

if product == "q" or product == "Q" :

break

localhost:8888/nbconvert/html/AGNES MEILIANA_1A11_P27838020003_TUGAS 4.ipynb?download=false 2/30


4/7/2021 AGNES MEILIANA_1A11_P27838020003_TUGAS 4

else :

price = int(input("enter the price of product = "))

dic [ product ] = price

while True :

name = input("enter the name of product those you are entered (enter q for quit

if name == "q" or name == "Q" :

break

else :

if name not in dic :

print("name of product is invaild")

else :

print("price of product = ",dic[name])

#Menulis sebuah program yang berulang kali meminta pengguna untuk memasukkan nama da

enter the name of product (enter q for quit )= Gado Gado

enter the price of product = 10000


enter the name of product (enter q for quit )= Es Cao

enter the price of product = 3000

enter the name of product (enter q for quit )= Rujak CIngur

enter the price of product = 15000


enter the name of product (enter q for quit )= Es Degan

enter the price of product = 6000

enter the name of product (enter q for quit )= Bakso

enter the price of product = 7000

enter the name of product (enter q for quit )= Es Jeruk

enter the price of product = 2000

enter the name of product (enter q for quit )= Mie Ayam

enter the price of product = 9000

enter the name of product (enter q for quit )= Es Teh

enter the price of product = 3000

enter the name of product (enter q for quit )= Nasi Bebek

enter the price of product = 18000


enter the name of product (enter q for quit )= Jus Alpukat

enter the price of product = 12000


enter the name of product (enter q for quit )= Nasi Pecel

enter the price of product = 14000


enter the name of product (enter q for quit )= Jus Jambu

enter the price of product = 11000


enter the name of product (enter q for quit )= Q

enter the name of product those you are entered (enter q for quit )= q

In [50]:
word = 'teknik elektromedik surabaya'

d = dict()

for c in word:

if c not in d:

d[c] = 1

else:

d[c] = d[c] + 1

print(d)

{'t': 2, 'e': 4, 'k': 4, 'n': 1, 'i': 2, ' ': 2, 'l': 1, 'r': 2, 'o': 1, 'm': 1,
'd': 1, 's': 1, 'u': 1, 'a': 3, 'b': 1, 'y': 1}

In [60]:
month = { "jan" : 31 , "feb" : 28 , "march" : 31 , "april" : 30 , "may" : 31 , "june

localhost:8888/nbconvert/html/AGNES MEILIANA_1A11_P27838020003_TUGAS 4.ipynb?download=false 3/30


4/7/2021 AGNES MEILIANA_1A11_P27838020003_TUGAS 4

mon = input("enter the mounth name in short form = ")

print("number of days in ",mon,"=",month [ mon ])

lst = list ( month . keys() )

lst.sort()

print( lst )

print( "month which have 31 days --- ")

for i in month :

if month [ i ] == 31 :

print( i )

print("month according to number of days ---")

print("feb")

for i in month :

if month [ i ] == 30 :

print(i)

for i in month :

if month [ i ] == 31 :

print( i )

#berguna untuk mengetahui nama bulan dan nilainya

enter the mounth name in short form = jan

number of days in jan = 31

['april', 'aug', 'dec', 'feb', 'jan', 'july', 'june', 'march', 'may', 'nov', 'oct',
'sept']

month which have 31 days ---

jan

march

may

july

aug

oct

dec

month according to number of days ---

feb

april

june

sept

nov

jan

march

may

july

aug

oct

dec

In [62]:
dic = {'agnes' : "2002",

'poltekkes' : "2004",

'surabaya' : "1293",

'aleya' : "2003",

'gresik' : "1953",

localhost:8888/nbconvert/html/AGNES MEILIANA_1A11_P27838020003_TUGAS 4.ipynb?download=false 4/30


4/7/2021 AGNES MEILIANA_1A11_P27838020003_TUGAS 4

'indonesia' : "1945",

'iven' : "2003",

'zahra' : "2001",

'sisca' : "2003",

'romeesa' : "2001" }

username = input("Enter username :- ")

if username in dic :

password = input("Enter password :- ")

if dic[username] == password :

print ("You are now logged into the system.")

else :

print ("Invalid password.")

else :

print ("You are not valid user.")

#Menulis program yang menggunakan kamus yang berisi sepuluh nama pengguna dan kata s

Enter username :- agnes

Enter password :- Meiliana

Invalid password.

In [65]:
dic ={}

lstwin = []

lstrec = []

while True :

name = input ("Enter the name of team (enter q for quit)=")

if name == "Q" or name == "q" :

break

else :

win = int (input("Enter the no.of win match ="))

loss = int(input("Enter the no.of loss match ="))

dic [ name ] = [ win , loss ]

lstwin += [ win ]

if win > 0 :

lstrec += [ name ]

nam = input ("Enter the name of team those you are entered =")

print ("Winning percentage =",dic [ nam ][0] *100 / (dic [nam ][0] + dic[nam ][1] ))
print("wining list of all team = ",lstwin)

print("team who has winning records are ",lstrec)

#Menuliskan berulang kali lalu meminta pengguna untuk memasukkan nama tim dan berapa

Enter the name of team (enter q for quit)=Agnes

Enter the no.of win match =4

Enter the no.of loss match =2

Enter the name of team (enter q for quit)=Meiliana

Enter the no.of win match =5

Enter the no.of loss match =1

localhost:8888/nbconvert/html/AGNES MEILIANA_1A11_P27838020003_TUGAS 4.ipynb?download=false 5/30


4/7/2021 AGNES MEILIANA_1A11_P27838020003_TUGAS 4

Enter the name of team (enter q for quit)=q

Enter the name of team those you are entered =Agnes

Winning percentage = 66.66666666666667

wining list of all team = [4, 5]

team who has winning records are ['Agnes', 'Meiliana']

In [66]:
from random import randint

n = 5

grid = [[randint(1, 5) for _ in range(n)] for i in range(n)]

print(grid)

[[2, 5, 1, 4, 4], [2, 4, 3, 4, 3], [3, 2, 2, 4, 5], [2, 4, 5, 5, 5], [1, 5, 1, 4,


3]]

In [67]:
# game.py

import random

SUITS = "♠ ♡ ♢ ♣".split()

RANKS = "2 3 4 5 6 7 8 9 10 J Q K A".split()

def create_deck(shuffle=False):

"""Create a new deck of 52 cards"""

deck = [(s, r) for r in RANKS for s in SUITS]

if shuffle:

random.shuffle(deck)

return deck

def deal_hands(deck):

"""Deal the cards in the deck into four hands"""

return (deck[0::4], deck[1::4], deck[2::4], deck[3::4])

def play():

"""Play a 4-player card game"""

deck = create_deck(shuffle=True)

names = "P1 P2 P3 P4".split()

hands = {n: h for n, h in zip(names, deal_hands(deck))}

for name, cards in hands.items():

card_str = " ".join(f"{s}{r}" for (s, r) in cards)

print(f"{name}: {card_str}")

if __name__ == "__main__":

play()

P1: ♠Q ♠3 ♣2 ♢A ♣9 ♢7 ♡5 ♠6 ♡Q ♡7 ♢5 ♢8 ♡9

P2: ♡K ♡J ♠10 ♣10 ♣4 ♡6 ♠7 ♢Q ♠8 ♠4 ♡2 ♣J ♣6

P3: ♡A ♡4 ♣Q ♢9 ♡3 ♢6 ♣3 ♣K ♢2 ♠K ♣5 ♠A ♠J

P4: ♠9 ♣8 ♢K ♣A ♡8 ♢J ♠5 ♠2 ♢3 ♢4 ♢10 ♣7 ♡10

In [68]:
class Card:

SUITS = ('Clubs', 'Diamonds', 'Hearts', 'Spades')

RANKS = ('narf', 'Ace', '2', '3', '4', '5', '6', '7',

'8', '9', '10', 'Jack', 'Queen', 'King')

def __init__(self, suit=0, rank=0):

self.suit = suit

self.rank = rank

def __str__(self):

"""

>>> print(Card(2, 11))

localhost:8888/nbconvert/html/AGNES MEILIANA_1A11_P27838020003_TUGAS 4.ipynb?download=false 6/30


4/7/2021 AGNES MEILIANA_1A11_P27838020003_TUGAS 4

Queen of Hearts

"""

return '{0} of {1}'.format(Card.RANKS[self.rank],

Card.SUITS[self.suit])

if __name__ == '__main__':

import doctest

doctest.testmod()

**********************************************************************

File "__main__", line 12, in __main__.Card.__str__

Failed example:

print(Card(2, 11))

Expected:

Queen of Hearts

Got:

Jack of Hearts

**********************************************************************

1 items had failures:

1 of 1 in __main__.Card.__str__

***Test Failed*** 1 failures.

In [69]:
from collections import namedtuple

from random import shuffle

Card = namedtuple("Card", "suit, rank")

class Deck:

suits = '♦♥♠♣'

ranks = '23456789JQKA'

def __init__(self):

self.cards = [Card(suit, rank) for suit in self.suits for rank in self.ranks


shuffle(self.cards)

def deal(self, amount):

return tuple(self.cards.pop() for _ in range(amount))

flush = False

count = 0

while not flush:

deck = Deck()

stop = False

while len(deck.cards) > 5:

hand = deck.deal(5)

# (Card(suit='♣', rank='7'), Card(suit='♠', rank='2'), Card(suit='♥', rank='


if len(set(card.suit for card in hand)) > 1:

#print(f"No Flush: {hand}")

continue

print(f"Yay, it's a Flush: {hand}")

flush = True

break

if flush:

break

else:

count +=1

print(f'Count is {count}')

Yay, it's a Flush: (Card(suit='♥', rank='A'), Card(suit='♥', rank='9'), Card(suit


='♥', rank='7'), Card(suit='♥', rank='J'), Card(suit='♥', rank='2'))

Count is 0

localhost:8888/nbconvert/html/AGNES MEILIANA_1A11_P27838020003_TUGAS 4.ipynb?download=false 7/30


4/7/2021 AGNES MEILIANA_1A11_P27838020003_TUGAS 4

In [1]: d=[{'name':'Todd', 'phone':'555-1414', 'email':'todd@mail.net'},

{'name':'Helga', 'phone':'555-1618', 'email':'helga@mail.net'},

{'name':'Princess', 'phone':'555-3141', 'email':''},

{'name':'LJ', 'phone':'555-2718', 'email':'lj@mail.net'}]

print("Original dictionary:")

print(d)

print(type(d))

import json

with open("dictionary", "w") as f:

json.dump(d, f, indent = 4, sort_keys = True)

print("\nJson file to dictionary:")

with open('dictionary') as f:

data = json.load(f)

print(data)

Original dictionary:

[{'name': 'Todd', 'phone': '555-1414', 'email': 'todd@mail.net'}, {'name': 'Helga',


'phone': '555-1618', 'email': 'helga@mail.net'}, {'name': 'Princess', 'phone': '555-
3141', 'email': ''}, {'name': 'LJ', 'phone': '555-2718', 'email': 'lj@mail.net'}]

<class 'list'>

Json file to dictionary:

[{'email': 'todd@mail.net', 'name': 'Todd', 'phone': '555-1414'}, {'email': 'helga@m


ail.net', 'name': 'Helga', 'phone': '555-1618'}, {'email': '', 'name': 'Princess',
'phone': '555-3141'}, {'email': 'lj@mail.net', 'name': 'LJ', 'phone': '555-2718'}]

In [2]:
from datetime import datetime

import pytz

utcmoment_naive = datetime.utcnow()

utcmoment = utcmoment_naive.replace(tzinfo=pytz.utc)

# print "utcmoment_naive: {0}".format(utcmoment_naive) # python 2

print("utcmoment_naive: {0}".format(utcmoment_naive))

print("utcmoment: {0}".format(utcmoment))

localFormat = "%Y-%m-%d %H:%M:%S"


timezones = ['America/Los_Angeles', 'Europe/Madrid', 'America/Puerto_Rico']

for tz in timezones:

localDatetime = utcmoment.astimezone(pytz.timezone(tz))

print(localDatetime.strftime(localFormat))

utcmoment_naive: 2021-07-02 00:04:42.399599

utcmoment: 2021-07-02 00:04:42.399599+00:00

2021-07-01 17:04:42

2021-07-02 02:04:42

2021-07-01 20:04:42

In [3]:
# Python program to convert Roman Numerals

# to Numbers

# This function returns value of each Roman symbol

def value(r):

if (r == 'I'):

return 1

if (r == 'V'):

return 5

if (r == 'X'):

localhost:8888/nbconvert/html/AGNES MEILIANA_1A11_P27838020003_TUGAS 4.ipynb?download=false 8/30


4/7/2021 AGNES MEILIANA_1A11_P27838020003_TUGAS 4

return 10

if (r == 'L'):

return 50

if (r == 'C'):

return 100

if (r == 'D'):

return 500

if (r == 'M'):

return 1000

return -1

def romanToDecimal(str):

res = 0

i = 0

while (i < len(str)):

# Getting value of symbol s[i]

s1 = value(str[i])

if (i + 1 < len(str)):

# Getting value of symbol s[i + 1]

s2 = value(str[i + 1])

# Comparing both values

if (s1 >= s2):

# Value of current symbol is greater

# or equal to the next symbol

res = res + s1

i = i + 1

else:

# Value of current symbol is greater

# or equal to the next symbol

res = res + s2 - s1

i = i + 2

else:

res = res + s1

i = i + 1

return res

# Driver code

print("Integer form of Roman Numeral is"),

print(romanToDecimal("MCMIV"))

Integer form of Roman Numeral is

1904

CHAPTER 12
In [10]:
lines = ['Hello.', 'This is a text file.', 'Bye!']

print(lines)

#berguna untuk membaca file teks menggunakan pemahaman daftar yang berguna untuk mem

['Hello.', 'This is a text file.', 'Bye!']

In [11]:
s = 'Hello.\nThis is a text file.\nBye!'

localhost:8888/nbconvert/html/AGNES MEILIANA_1A11_P27838020003_TUGAS 4.ipynb?download=false 9/30


4/7/2021 AGNES MEILIANA_1A11_P27838020003_TUGAS 4

print(s)

#berguna untuk membaca file teks yang memuat seluruh file ke dalam string

Hello.

This is a text file.

Bye!

In [12]:
f = open('writefile.txt', 'w')

print('This is line 1.', file=f)

print('This is line 2.', file=f)

f.close()

print(f)

#berguna untuk menulis ke file

<_io.TextIOWrapper name='writefile.txt' mode='w' encoding='cp1252'>

In [13]:
file1 = open('ftemps.txt', 'w')

temperatures = ['fahrenheit']

for t in temperatures:

print('t*9/5+32, file=file1')

file1.close()

print(t)

#berguna untuk membaca daftar suhu yang ada

t*9/5+32, file=file1

fahrenheit

In [14]:
questions = ['apakah kamu suka tidur?']

print(questions)

answer = ['ya saya sangat suka']

print(answer)

#berguna untuk membuat daftar pertanyaan dan jawaban

['apakah kamu suka tidur?']

['ya saya sangat suka']

In [15]:
lines = ['12/03/2009', ' SalemInternational', '35', ' Marshall', '119']

games = [line.split(',') for line in lines]

biggest_diff = 0

for g in games:

diff = abs(8-2)

if diff>biggest_diff:

biggest_diff = diff

game_info = g

print(game_info)

#game yang berguna untuk mencari margin kemenangan terbesar

['12/03/2009']

EXERCISE
CHAPTER 13
In [1]:
def print_hello():

print('Hello!')

print_hello()

print('1234567')

localhost:8888/nbconvert/html/AGNES MEILIANA_1A11_P27838020003_TUGAS 4.ipynb?download=false 10/30


4/7/2021 AGNES MEILIANA_1A11_P27838020003_TUGAS 4

print_hello()

#berguna untuk membuat fungsi sederhana yang hanya digunakan untuk mencetak sesuatu

Hello!

1234567

Hello!

In [2]:
def draw_square():

print('*' * 15)

print('*', ' '*11, '*')

print('*', ' '*11, '*')

print('*' * 15)

#berguna untuk mencetak sekotak bintang

In [3]:
def print_hello(n):

print('Hello ' * n)

print()

print_hello(3)

print_hello(5)

times = 2

print_hello(times)

#berguna untuk memberikan nilai ke fungsi

Hello Hello Hello

Hello Hello Hello Hello Hello

Hello Hello

In [16]:
def multiple_print(string, n):

print(string * n)

print()

multiple_print('Hello', 5)

multiple_print('A', 10)

#berguna untuk meneruskan lebih dari satu nilai ke suatu fungsi

HelloHelloHelloHelloHello

AAAAAAAAAA

In [5]:
def convert(t):

return t*9/5+32

print(convert(20))

#program memilki fungsi sederhana yaitu mengubah suhu dari Celcius ke Fahrenheit

68.0

In [17]:
def convert(t):

return t*9/5+32

print(convert(20)+5)

#berguna untuk mencetak hasil kedalam fungsi alih-alih

73.0

In [18]:
from math import pi, sin

localhost:8888/nbconvert/html/AGNES MEILIANA_1A11_P27838020003_TUGAS 4.ipynb?download=false 11/30


4/7/2021 AGNES MEILIANA_1A11_P27838020003_TUGAS 4

def deg_sin(x):

return sin(pi*x/180)

print(deg_sin(80))

# merupakan fungsi dari trigonometri, namun mereka hanya bekerja dalam radian

0.984807753012208

In [2]:
def solve(a,b,c,d,e,f):

x = (d*e-b*f)/(a*d-b*c)
y = (a*f-c*e)/(a*d-b*c)
return [x,y]

xsol, ysol = solve(2,3,4,1,2,5)

print('The solution is x = ', xsol, 'and y = ', ysol)

#menggunakan pintasan untuk menetapkan ke daftar yang telah disebutkan di Bagian

The solution is x = 1.3 and y = -0.2

In [19]:
def multiple_print(string, n, bad_words):

if string in bad_words:

return

print(string * n)

print()

multiple_print

#berguna untuk mengakhiri fungsi lebih awal

Out[19]: <function __main__.multiple_print(string, n, bad_words)>

In [20]:
def multiple_print(string, n=1):

print(string * n)

print()

multiple_print('Hello', 5)

multiple_print('Hello')

#berguna untuk menetukan nilai default untuk sebuah argumen

HelloHelloHelloHelloHello

Hello

In [21]:
def fancy_print(text, color, background, style, justify):

print()

fancy_print

#merupakan argumen kata kunci Konsep yang terkait dengan argumen default adalah argu

Out[21]: <function __main__.fancy_print(text, color, background, style, justify)>

In [22]:
def fancy_print(text='Hi', color='yellow', background='black',style='bold', justify=
print()

fancy_print

#berguna untuk memberi nama argumen saat memanggil fungsi

Out[22]: <function __main__.fancy_print(text='Hi', color='yellow', background='black', style


='bold', justify='left')>

In [23]:
fancy_print(text='Hi', style='bold', justify='left',

background='black', color='yellow')

localhost:8888/nbconvert/html/AGNES MEILIANA_1A11_P27838020003_TUGAS 4.ipynb?download=false 12/30


4/7/2021 AGNES MEILIANA_1A11_P27838020003_TUGAS 4

fancy_print

#merupakan urutan argumen tidak menjadi masalah saat Anda menggunakan argumen kata k

Out[23]: <function __main__.fancy_print(text='Hi', color='yellow', background='black', style


='bold', justify='left')>

In [24]:
def fancy_print(text, color='black', background='white',

style='normal', justify='left'):

# function code goes here

fancy_print('Hi', style='bold')

fancy_print('Hi', color='yellow', background='black')

fancy_print('Hi')

fancy_print

#Menggunakan nilai-nilai ini sebagai default

Out[24]: <function __main__.fancy_print(text, color='black', background='white', style='norma


l', justify='left')>

In [25]:
def func1():

for i in range(10):

print(i)

print(func1())

def func2():

i=100

func1()

print(func2())

#berguna mendefinisikan variabelnya sendiri dan tidak memiliki perlu khawatir jika n

None

None

In [26]:
def reset():

global time_left

time_left = 0

def print_time():

print(time_left)

time_left=30

localhost:8888/nbconvert/html/AGNES MEILIANA_1A11_P27838020003_TUGAS 4.ipynb?download=false 13/30


4/7/2021 AGNES MEILIANA_1A11_P27838020003_TUGAS 4

print(print_time())

#berguna untuk membuat variabel global yaitu variabel yang sama tersedia untuk beber

30

None

EXERCISE
In [6]:
def rectangle (m,n):

for i in range (m):

print ('*'*n)

rectangle (2,4)

****

****

In [7]:
def add_excitement (string,n):

print (string,n)

string=input ('Enter your name:')


add_excitement (string,'!')

Enter your name:Agnes

Agnes !

In [8]:
def sum_digits (n):

print (sum(int(n) for n in str(n)))

sum_digits (45)

sum_digits (560)

11

In [9]:
def sum_digits(n):

x=sum (int(n) for n in str (n))

y=sum (int(x) for x in str (x))

z=sum (int(y) for y in str (y))

print (z)

sum_digits (45893)

In [10]:
def binom(n,k):

return (int(n)/int(k*(n-k)))

print (binom(2,4))

-0.25

In [11]:
def number(n):

a=10**int(n-1)

b=10**int(n)-1

from random import randint

sol=randint (int(a), int(b))

print (sol)

number (4)

3874

localhost:8888/nbconvert/html/AGNES MEILIANA_1A11_P27838020003_TUGAS 4.ipynb?download=false 14/30


4/7/2021 AGNES MEILIANA_1A11_P27838020003_TUGAS 4

In [12]: def number_of_factors (n):

for i in range (1,n):

if n%i==0:

print ('The factors are:', i)

number_of_factors(8)

The factors are: 1

The factors are: 2

The factors are: 4

In [13]:
def numbers(n):

L=[1, 3, 5, 6, 10]

x=[b for b in L if n>b]

largest=0

for num in x:

if num==x:

x==num

print (num)

numbers (8)

In [14]:
def diff_position (string1, string2):

a=string1.replace (' ', '')

b=string2.replace (' ', '')

if len(a)<len(b):

length=len(a)

else:

length=len(b)

count=0

for i in range (length):

if a[i]!=b[i]:

count=count+1

print (length-count)

string1='Pyhton'

string2='Path'

diff_position(string1, string2)

In [16]:
def findall(n):

x='Hi My name is Agnes and you learning pyhton now'

y=x.count(n)

z=list(x)

for i in range(y):

a=z.index(n)

z.remove(n)

print(a+int(i))

findall('a')

20

30

In [17]:
def change_case(n):

y=n.swapcase()

print (y)

localhost:8888/nbconvert/html/AGNES MEILIANA_1A11_P27838020003_TUGAS 4.ipynb?download=false 15/30


4/7/2021 AGNES MEILIANA_1A11_P27838020003_TUGAS 4

change_case('Hello World')

hELLO wORLD

In [18]:
def is_sorted (string):

y=list(string)

if y==sorted(string):

print('true')

else:

print('false')

is_sorted('Pyhton')

is_sorted('app')

false

true

In [19]:
def root (n):

return (n**0.5)

print (root(17))

4.123105625617661

In [20]:
def one_away (string1, string2):

count=0

for i in range (len(string1)):

if string1[i]!=string2[i]:

count=count+1

if count==1:

print('true')

else:

print('false')

one_away('hike', 'bike')

one_away('like', 'hello')

true

false

In [21]:
def prime(num):

count=0

for i in range(2,num):

if num%i==0:

count=count+1

if count>1:

print('not prime')

else:

print('prime')

prime(15)

prime(5)

prime(27)

prime(3)

#Untuk menentukan apakah angka tersebut bilangan prima atau bukan

not prime

prime

not prime

prime

In [22]:
def base20(num):

localhost:8888/nbconvert/html/AGNES MEILIANA_1A11_P27838020003_TUGAS 4.ipynb?download=false 16/30


4/7/2021 AGNES MEILIANA_1A11_P27838020003_TUGAS 4

a= {'0':'A', '1':'B', '2':'C', '3':'D', '4':'E', '5':'F', '6':'G', '7':'H', '8':


if num<=20:

return a[str(num)]

elif num>20 and num<400:

return a[str(num//20)],a[str(num%20)]

elif num>=400:

return a[str(num//20//20)],base20(num%100)

print(base20(548))

print(base20(890))

('B', ('C', 'I'))

('C', ('E', 'K'))

In [23]:
def verbose(num):

d = {0:'zero', 1 :'one', 2 :'two', 3 :'three', 4 :'four', 5 :'five', 6 :'six', 7


if (num<20):

return d[num]

if (num<100):

if num % 10==0:

return d[num]

else:

return d[num//10*10]+d[num % 10]

if (num<10**3):

if num % 100==0:

return d[num//100]+'hundred'
else:

return d[num//100]+'hundred and'+verbose(num % 100)

if (num<10**6):

if num % 10**3==0:

return int_to_en(num//10**3)+'thousand'

else:

return verbose(num//10**3)+'thousand'+verbose(num % 10**3)

if (num<10**9):

if (num % m)==0:

return verbose(num//10**6)+'million'

else:

return verbose(num//10**6)+'million'+verbose(num % 10**6)

if (num<10**12):

if (num % b)==0:

return verbose(num//10**9)+'billion'

else:

return verbose(num//10**9)+'billion'+verbose(num % 10**9)

if (num % 10**12==0):

return verbose(num//10**12)+'trillion'

else:

return verbose(num//10**12)+'trillion'+verbose(num % 10**12)

print (verbose(549055))

print (verbose(584085))

print (verbose(950343))

fivehundred andfortyninethousandfiftyfive

fivehundred andeightyfourthousandeightyfive

ninehundred andfiftythousandthreehundred andfortythree

localhost:8888/nbconvert/html/AGNES MEILIANA_1A11_P27838020003_TUGAS 4.ipynb?download=false 17/30


4/7/2021 AGNES MEILIANA_1A11_P27838020003_TUGAS 4

In [24]: def merge (string1, string2):

a=string1+string2

print(sorted(a))

merge('hello','pyhton')

def merge (string1, string2):

a=string1+string2

print (a)

merge('hello','pyhton')

['e', 'h', 'h', 'l', 'l', 'n', 'o', 'o', 'p', 't', 'y']

hellopyhton

In [25]:
def binarySearch(alist, item):

first = 0

last = len(alist)-1

found = False

while first<=last and not found:

midpoint = (first + last)//2

if alist[midpoint] == item:

found = True

else:

if item < alist[midpoint]:

last = midpoint-1
else:

first = midpoint+1

return found

testlist = [0, 1, 2, 8, 13, 17, 19, 32, 42,]

print(binarySearch(testlist, 3))

print(binarySearch(testlist, 13))

False

True

CHAPTER 14
In [27]:
class Example:

def __init__(self, a, b):

self.a = a

self.b = b

def add(self):

return self.a + self.b

e = Example(8, 6)

print(e.add())

#berguna untuk mendemonstrasikan seperti apa rupa sebuah kelas

14

In [9]:
from string import punctuation

class Analyzer:

def __init__(self, s):

for c in punctuation:

s = s.replace(c,'')

localhost:8888/nbconvert/html/AGNES MEILIANA_1A11_P27838020003_TUGAS 4.ipynb?download=false 18/30


4/7/2021 AGNES MEILIANA_1A11_P27838020003_TUGAS 4

s = s.lower()

self.words = s.split()

def number_of_words(self):

return len(self.words)

def starts_with(self, s):

return len([w for w in self.words if w[:len(s)]==s])

def number_with_length(self, n):

return len([w for w in self.words if len(w)==n])

s = 'This is a test of the class.'

analyzer = Analyzer(s)

print(analyzer.words)

print('Number of words:', analyzer.number_of_words())

print('Number of words starting with "t":', analyzer.starts_with('t'))

print('Number of 2-letter words:', analyzer.number_with_length(2))

#program analyzer yang melakukan beberapa analisis sederhana pada sebuah string.

['this', 'is', 'a', 'test', 'of', 'the', 'class']

Number of words: 7

Number of words starting with "t": 3

Number of 2-letter words: 2

In [10]:
class Parent:

def __init__(self, a):

self.a = a

def method1(self):

print(self.a*2)

def method2(self):

print(self.a+'!!!')

class Child(Parent):

def __init__(self, a, b):

self.a = a

self.b = b

def method1(self):

print(self.a*7)

def method3(self):

print(self.a + self.b)

p = Parent('hi')

c = Child('hi', 'bye')

print('Parent method 1: ', p.method1())

print('Parent method 2: ', p.method2())

print()

print('Child method 1: ', c.method1())

print('Child method 2: ', c.method2())

print('Child method 3: ', c.method3())

#berguna untuk membuat kelas yang dibangun dari kelas lain

hihi

Parent method 1: None

hi!!!

Parent method 2: None

hihihihihihihi

Child method 1: None

hi!!!

Child method 2: None

hibye

Child method 3: None

localhost:8888/nbconvert/html/AGNES MEILIANA_1A11_P27838020003_TUGAS 4.ipynb?download=false 19/30


4/7/2021 AGNES MEILIANA_1A11_P27838020003_TUGAS 4

In [30]: class Parent:

def __init__(self, a):

self.a = a

def print_var(self):

print("The value of this class's variables are:")

print(self.a)

class Child(Parent):

def __init__(self, a, b):

Parent.__init__(self, a)

self.b = b

def print_var(self):

Parent.print_var(self)

print(self.b)

p = Parent('hi')

c = Child('hi', 'bye')

print('Parent print_var: ', p.print_var())

print()

print('Child print_var: ', c.print_var())

#jika kelas anak hanya ingin menambahkan ke salah satu metode induk.

The value of this class's variables are:

hi

Parent print_var: None

The value of this class's variables are:

hi

bye

Child print_var: None

In [31]:
x_copy = 'agnes'

print(x_copy)

#berguna untuk mencetak objek (x)

agnes

In [32]:
from copy import copy

x_copy = copy('agnes')

print(x_copy)

#berguna untuk mengcopy dan mencetak (x)

agnes

EXERCISE
In [1]:
class Investment:

def __init__(self,p,i,n):

self.p=p

self.i=i

self.n=n

def value_after(self):

return ((self.p*(1+self.i))**self.n)

def _str_(self):

print('Principal-$:',self.p, 'Interest rate:',self.i,'%','Interest-$:',a.val


a=Investment(1000,5.12,3)

(a._str_())

localhost:8888/nbconvert/html/AGNES MEILIANA_1A11_P27838020003_TUGAS 4.ipynb?download=false 20/30


4/7/2021 AGNES MEILIANA_1A11_P27838020003_TUGAS 4

Principal-$: 1000 Interest rate: 5.12 % Interest-$: 229220928000.0

In [2]:
class Product:

def __init__(self,name,amount,price):

self.name=n

self.amount=a

self.price=p

def get_price(self):

return 'Regular Price:',self.amount*self.price

def make_purchase(self):

if self.amount<10:

return 'Discount Price',a*p

if self.amount>=10 and self.amount<100:

return 'Discount price:',a*p-(int(a*p*10/100))

if self.amount>100:

return 'Discount price:',a*p-(a*p*20/100)

n=input('Product Name:')

a=eval(input('No. of items bought:'))

p=eval(input('price of pdt:'))

c=Product(n,a,p)

print(c.get_price())

print(c.make_purchase())

Product Name:Case Hp

No. of items bought:15

price of pdt:2015

('Regular Price:', 30225)

('Discount price:', 27203)

In [3]:
class Password_manager:

def __init__(self):

# define an empty list for the old passwords

self.old_passwords = []

def get_password(self):

# get the last password from list

return self.old_passwords[-1]

def set_password(self, password):

# does the password already exist?

if password not in self.old_passwords:

# add new password to list of old passwords

self.old_passwords.append(password)

def is_correct(self, password):

# check if the given password is the current password and return an appropri
return password == self.get_password()

# create an instance of the password manager

manager = Password_manager()

# prefill the list of old passwords

manager.old_passwords = ['foo', 'bar', 'baz']

# set a new password

manager.set_password('Monty')

# check password

print(manager.is_correct('baz'))

print(manager.is_correct('Monty'))

False

localhost:8888/nbconvert/html/AGNES MEILIANA_1A11_P27838020003_TUGAS 4.ipynb?download=false 21/30


4/7/2021 AGNES MEILIANA_1A11_P27838020003_TUGAS 4

True

In [4]:
class Time:

def __init__(self,sec):

self.sec=sec

def convert_to_minutes(self):

return '{}:{}minute'.format(self.sec//60,self.sec%60)

def convert_to_hour(self):

return '{:.2f} hours'.format(self.sec/3600)

#In previous line use :.2f , so that answer written upto 2 digit after dot

a=Time(3680)

print(a.convert_to_minutes())

print(a.convert_to_hour())

61:20minute

1.02 hours

In [5]:
class Wordplay:

def __init__(self):

self.words_list=[]

def words_with_lenght(self,lenght):

for i in range(0,len(self.words_list)-1):

if len(self.words_list[i])==lenght:

return self.words_list[i]

def starts_with_s(self,s):

for i in range(0,len(self.words_list)-1):

if s.startswith('s')==True:

return self.words_list[i]

def ends_with_s(self,s):

for i in range(0,len(self.words_list)-1):

if s.endswith('s')==True:

return self.words_list[i]

def palindromes(self):

for i in range(0,len(self.words_list)-1):

normal_word=self.words_list[i]

reversed_word=normal_word[::-1]

if reversed_word==normal_word:

return reversed_word

verification=Wordplay()

verification.words_list=['sandro','abba','luis']

lenght=int(input('Digit size you want to compare\n'))

s='s'

print(verification.words_with_lenght(lenght))

print(verification.starts_with_s(s))

print(verification.ends_with_s(s))

print(verification.palindromes())

Digit size you want to compare

abba

sandro

sandro

abba

localhost:8888/nbconvert/html/AGNES MEILIANA_1A11_P27838020003_TUGAS 4.ipynb?download=false 22/30


4/7/2021 AGNES MEILIANA_1A11_P27838020003_TUGAS 4

In [3]: class Converter:

def __init__(self,a,b,c):

self.a=a

self.b=b

self.c=c

def Convert(self):

# If b= metre and c= centimetre then it multiply 'a' with 100 and vice-versa.

if self.b=='m' and self.c=='cm':

print(self.a*100,'cm')

if self.b=='cm' and self.c=='m':

print(self.a/100,'m')

# If b=feet and c= centimetre then it multiply 'a' with 30.48 and vice versa.

if self.b=='feet' and self.c=='cm':

print(self.a*30.48,'cm')

if self.b=='cm' and self.c=='feet':

print(self.a/30.48,'feet')

# If b=inch and c= feet then it multiply 'a' with 0.083 and vice versa.

if self.b=='inch' and self.c=='feet':

print(self.a*0.083,'feet')

if self.b=='feet' and self.c=='inch':

print(self.a/0.083)

# If b=metre and c= feet then it multiply 'a' with 3.28 and vice versa.

if self.b=='m' and self.c=='feet':

print(self.a*3.28)

if self.b=='feet' and self.c=='m':

print(self.a/3.28)

# If b=km and c=metre then it multiply 'a' with 1000 and vice versa.

if self.b=='km' and self.c=='m':

print(self.a*1000,'m')

if self.b=='m' and self.c=='km':

print(self.a/1000)

# If b=kilometere and c= milliimetre then it multiply 'a' with 10000 and vice versa.
if self.b=='km' and self.c=='mm':

print(self.a*10000,'mm')

if self.b=='mm' and self.c=='km':

print(self.a/10000)

# If b=miles and c= kilometre then it multiply 'a' with 1.60 and vice versa.

if self.b=='miles' and self.c=='km':

print(self.a*1.60,'km')

if self.b=='km' and self.c=='miles':

print(self.a/1.60,'km')

e=Converter(9,'inch','feet')

f=Converter(50,'miles','km')

e.Convert()

f.Convert()

0.747 feet

80.0 km

In [7]:
from random import sample

class Rock:

def __init__(self,gamesample=[]):

self.gamesample=gamesample

def Game(self):

gamesample=[]

for s in ['rock','paper','scissor']:

gamesample.append(s)

numberofround=eval(input('enter number of round you want to play:'))

localhost:8888/nbconvert/html/AGNES MEILIANA_1A11_P27838020003_TUGAS 4.ipynb?download=false 23/30


4/7/2021 AGNES MEILIANA_1A11_P27838020003_TUGAS 4

count=0

count1=0

count2=0

for i in range(numberofround):

print('Number of round is:',i+1)

yourchoice=input('Rock, Paper or Scissor:')

yourchoice.lower()

x=sample(gamesample,1)

y=''.join(x)

print('Computer choice is:',x)

if yourchoice==y:

count=count+1

if count>=1:

print('match tie')

elif yourchoice=='rock' and y=='paper' or yourchoice=='paper'and y=='sci


count1=count1+1

if count1>=1:

print('you lose')

elif yourchoice=='scissor' and y=='paper' or yourchoice=='paper' and y==


count2=count2+1

if count2>=1:

print('you won')

print('Number of match tie:',count,'Number of match you lose:',count1,'Numbe


d=Rock(gamesample=[])

d.Game()

enter number of round you want to play:3

Number of round is: 1

Rock, Paper or Scissor:rock

Computer choice is: ['scissor']

you won

Number of round is: 2

Rock, Paper or Scissor:paper

Computer choice is: ['paper']

match tie

Number of round is: 3

Rock, Paper or Scissor:scissor

Computer choice is: ['paper']

you won

Number of match tie: 1 Number of match you lose: 0 Number of match you won: 2

CHAPTER 15
In [ ]:
#1

from tkinter import *

def calculate():

temp = int(entry.get())

temp = 9/5*temp+32

output_label.configure(text = 'Converted: {:.1f}'.format(temp))

entry.delete(0,END)

root = Tk()

message_label = Label(text='Enter a temperature',

font=('Verdana', 16))

localhost:8888/nbconvert/html/AGNES MEILIANA_1A11_P27838020003_TUGAS 4.ipynb?download=false 24/30


4/7/2021 AGNES MEILIANA_1A11_P27838020003_TUGAS 4

output_label = Label(font=('Verdana', 16))

entry = Entry(font=('Verdana', 16), width=4)

calc_button = Button(text='Ok', font=('Verdana', 16),

command=calculate)

message_label.grid(row=0, column=0)

entry.grid(row=0, column=1)

calc_button.grid(row=0, column=2)

output_label.grid(row=1, column=0, columnspan=3)

mainloop()

Pada cell di atas input adalah "print" dan output adalah hasil dari kata dan angka yang
dimasukkan pada input dengan menggunakan rumus yang terdapat pada input tersebut.

In [ ]:
#2

from tkinter import *

def callback():

label.configure(text='Button clicked')

root = Tk()

label = Label(text='Not clicked')

button = Button(text='Click me', command=callback)

label.grid(row=0, column=0)

button.grid(row=1, column=0)

mainloop()

Pada cell di atas input adalah "print" dan output adalah hasil dari kata dan angka yang
dimasukkan pada input dengan menggunakan rumus yang terdapat pada input tersebut.

In [ ]:
#3

from tkinter import *

alphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'

def callback(x):

label.configure(text='Button {} clicked'.format(alphabet[x]))

root = Tk()

label = Label()

label.grid(row=1, column=0, columnspan=26)

buttons = [0]*26 # create a list to hold 26 buttons

for i in range(26):

buttons[i] = Button(text=alphabet[i],

command = lambda x=i: callback(x))

buttons[i].grid(row=0, column=i)

mainloop()

Pada cell di atas input adalah "print" dan output adalah hasil dari kata dan angka yang
dimasukkan pada input dengan menggunakan rumus yang terdapat pada input tersebut serta
juga sesuai dengan range yang terdapat pada input tersebut juga.

In [ ]:
#4

from tkinter import *

localhost:8888/nbconvert/html/AGNES MEILIANA_1A11_P27838020003_TUGAS 4.ipynb?download=false 25/30


4/7/2021 AGNES MEILIANA_1A11_P27838020003_TUGAS 4

def callback():

global num_clicks

num_clicks = num_clicks + 1

label.configure(text='Clicked {} times.'.format(num_clicks))

num_clicks = 0

root = Tk()

label = Label(text='Not clicked')

button = Button(text='Click me', command=callback)

label.grid(row=0, column=0)

button.grid(row=1, column=0)

mainloop()

Pada cell di atas input adalah "print" dan output adalah hasil dari kata dan angka yang
dimasukkan pada input dengan menggunakan rumus yang terdapat pada input tersebut.

In [ ]:
#5

from tkinter import *

def callback(r,c):

global player

if player == 'X':

b[r][c].configure(text = 'X')

player = 'O'

else:

b[r][c].configure(text = 'O')

player = 'X'

root = Tk()

b = [[0,0,0],

[0,0,0],

[0,0,0]]

for i in range(3):

for j in range(3):

b[i][j] = Button(font=('Verdana', 56), width=3, bg='yellow',

command = lambda r=i,c=j: callback(r,c))

b[i][j].grid(row = i, column = j)

player = 'X'

mainloop()

Pada cell di atas input adalah "print" dan output adalah hasil dari kata dan angka yang
dimasukkan pada input dengan menggunakan rumus yang terdapat pada input tersebut serta
juga sesuai dengan range yang terdapat pada input tersebut juga.

CHAPTER 16
In [ ]:
#1

from tkinter import *

root = Tk()

alphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'

buttons = [0]*26

localhost:8888/nbconvert/html/AGNES MEILIANA_1A11_P27838020003_TUGAS 4.ipynb?download=false 26/30


4/7/2021 AGNES MEILIANA_1A11_P27838020003_TUGAS 4

for i in range(26):

buttons[i] = Button(text=alphabet[i])

buttons[i].grid(row=0, column=i)

ok_button = Button(text='Ok', font=('Verdana', 24))

ok_button.grid(row=1, column=0)

mainloop()

Pada cell di atas input adalah "print" dan output adalah hasil dari kata dan angka yang
dimasukkan pada input dengan menggunakan rumus yang terdapat pada input tersebut serta
juga sesuai dengan range yang terdapat pada input tersebut juga.

In [ ]:
#2

from tkinter import *

def callback(event):

print(event.keysym)

root = Tk()

root.bind('<Key>', callback)

mainloop()

Pada cell di atas input adalah "print" dan output adalah hasil dari kata yang dimasukkan pada
input dengan menggunakan rumus yang terdapat pada input tersebut.

In [ ]:
#4

from tkinter import *

def callback(event):

global move

if event.keysym=='Right':

move += 1

elif event.keysym=='Left':

move -=1

canvas.coords(rect,50+move,50,100+move,100)

root = Tk()

root.bind('<Key>', callback)

canvas = Canvas(width=200,height=200)

canvas.grid(row=0,column=0)

rect = canvas.create_rectangle(50,50,100,100,fill='blue')

move = 0

mainloop()

Pada cell di atas input adalah "print" dan output adalah hasil dari kata dan angka yang
dimasukkan pada input dengan menggunakan rumus yang terdapat pada input tersebut.

In [ ]:
#5

from tkinter import *

def mouse_motion_event(event):

label.configure(text='({}, {})'.format(event.x, event.y))

def wheel_event(event):

global x1, x2, y1, y2

if event.delta>0:

diff = 1

localhost:8888/nbconvert/html/AGNES MEILIANA_1A11_P27838020003_TUGAS 4.ipynb?download=false 27/30


4/7/2021 AGNES MEILIANA_1A11_P27838020003_TUGAS 4

elif event.delta<0:

diff = -1

x1+=diff

x2-=diff

y1+=diff

y2-=diff

canvas.coords(rect,x1,y1,x2,y2)

def b1_event(event):

global color

if not b1_drag:

color = 'Red' if color=='Blue' else 'Blue'

canvas.itemconfigure(rect, fill=color)

def b1_motion_event(event):

global b1_drag, x1, x2, y1, y2, mouse_x, mouse_y

x = event.x

y = event.y

if not b1_drag:

mouse_x = x

mouse_y = y

b1_drag = True

return

x1+=(x-mouse_x)

x2+=(x-mouse_x)

y1+=(y-mouse_y)

y2+=(y-mouse_y)

canvas.coords(rect,x1,y1,x2,y2)

mouse_x = x

mouse_y = y

def b1_release_event(event):

global b1_drag

b1_drag = False

root=Tk()

label = Label()

canvas = Canvas(width=200, height=200)

canvas.bind('<Motion>', mouse_motion_event)

canvas.bind('<ButtonPress-1>', b1_event)

canvas.bind('<B1-Motion>', b1_motion_event)

canvas.bind('<ButtonRelease-1>', b1_release_event)

canvas.bind('<MouseWheel>', wheel_event)

canvas.focus_set()

canvas.grid(row=0, column=0)

label.grid(row=1, column=0)

mouse_x = 0

mouse_y = 0

b1_drag = False

x1 = y1 = 50

x2 = y2 = 100

color = 'blue'

rect = canvas.create_rectangle(x1,y1,x2,y2,fill=color)

mainloop()

Pada cell di atas input adalah "print" dan output adalah hasil dari kata dan angka yang
dimasukkan pada input dengan menggunakan rumus yang terdapat pada input tersebut.

localhost:8888/nbconvert/html/AGNES MEILIANA_1A11_P27838020003_TUGAS 4.ipynb?download=false 28/30


4/7/2021 AGNES MEILIANA_1A11_P27838020003_TUGAS 4

CHAPTER 17
In [ ]:
#1

from tkinter import *

from tkinter.messagebox import askquestion

def quitter_function():

answer = askquestion(title='Quit?', message='Really quit?')

if answer=='yes':

root.destroy()

root = Tk()

root.protocol('WM_DELETE_WINDOW', quitter_function)

mainloop()

Pada cell di atas input adalah "print" dan output adalah hasil dari kata yang dimasukkan pada
input dengan menggunakan rumus yang terdapat pada input tersebut.

In [ ]:
#2

from time import time

from tkinter import *

def update_timer():

time_left = int(90 - (time()-start))

minutes = time_left // 60

seconds = time_left % 60

time_label.configure(text='{}:{:02d}'.format(minutes, seconds))

root.after(100, update_timer)

root = Tk()

time_label = Label()

time_label.grid(row=0, column=0)

start = time()

update_timer()

mainloop()

Pada cell di atas input adalah "print" dan output adalah hasil dari kata dan angka yang
dimasukkan pada input dengan menggunakan rumus yang terdapat pada input tersebut.

In [ ]:
#4

from tkinter import *

from tkinter.filedialog import *

def open_callback():

filename = askopenfilename()

# add code here to do something with filename

def saveas_callback():

filename = asksaveasfilename()

# add code here to do something with filename

root = Tk()

menu = Menu()

root.config(menu=menu)

file_menu = Menu(menu, tearoff=0)

file_menu.add_command(label='Open', command=open_callback)

file_menu.add_command(label='Save as', command=saveas_callback)

file_menu.add_separator()

localhost:8888/nbconvert/html/AGNES MEILIANA_1A11_P27838020003_TUGAS 4.ipynb?download=false 29/30


4/7/2021 AGNES MEILIANA_1A11_P27838020003_TUGAS 4

file_menu.add_command(label='Exit', command=root.destroy)

menu.add_cascade(label='File', menu=file_menu)

mainloop()

Pada cell di atas input adalah "print" dan output adalah hasil dari kata dan angka yang
dimasukkan pada input dengan menggunakan rumus yang terdapat pada input tersebut.

In [ ]:
#5

from tkinter import *

def callback():

global count

s.set('Goodbye' if count%2==0 else 'Hello')

count +=1

root = Tk()

count = 0

s = StringVar()

s.set('Hello')

label1 = Label(textvariable = s, width=10)

label2 = Label(textvariable = s, width=10)

button = Button(text = 'Click me', command = callback)

label1.grid(row=0, column=0)

label2.grid(row=0, column=1)

button.grid(row=1, column=0)

mainloop()

Pada cell di atas input adalah "print" dan output adalah hasil dari kata dan angka yang
dimasukkan pada input dengan menggunakan rumus yang terdapat pada input tersebut.

In [ ]:

localhost:8888/nbconvert/html/AGNES MEILIANA_1A11_P27838020003_TUGAS 4.ipynb?download=false 30/30

You might also like