Professional Documents
Culture Documents
In [43]:
numerals = {'I':1, 'V':5, 'X':10, 'L':50, 'C':100, 'D':500, 'M':1000}
Enter a word: V
In [19]:
points = {'A':1, 'B':3, 'C':3, 'D':2, 'E':1, 'F':4, 'G':2,
Enter a key :B
In [21]:
deck = [{'value':i, 'suit':c}
for i in range(2,15)]
print (deck)
'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:
else:
print('Not in dictionary')
Not in dictionary
In [24]:
for key in d:
print(key)
dog
cat
mouse
In [25]:
for key in d:
print(d[key])
says meow
chased by cats
In [31]:
d = {'A':100, 'B':200, 'C':100}
list (d.items())
#Untuk menemukan semua kunci dalam kamus d yang sesuai dengan nilai yang telah diten
In [32]:
d = dict([('A',100),('B',300)])
list (d.items())
#Untuk membuat kamus berguna jika program Anda perlu membuat kamus saat sedang berja
EXERCISES
In [49]:
dic = { }
while True :
break
else :
while True :
name = input("enter the name of product those you are entered (enter q for quit
break
else :
else :
#Menulis sebuah program yang berulang kali meminta pengguna untuk memasukkan nama da
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
lst.sort()
print( lst )
for i in month :
if month [ i ] == 31 :
print( i )
print("feb")
for i in month :
if month [ i ] == 30 :
print(i)
for i in month :
if month [ i ] == 31 :
print( i )
['april', 'aug', 'dec', 'feb', 'jan', 'july', 'june', 'march', 'may', 'nov', 'oct',
'sept']
jan
march
may
july
aug
oct
dec
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",
'indonesia' : "1945",
'iven' : "2003",
'zahra' : "2001",
'sisca' : "2003",
'romeesa' : "2001" }
if username in dic :
if dic[username] == password :
else :
else :
#Menulis program yang menggunakan kamus yang berisi sepuluh nama pengguna dan kata s
Invalid password.
In [65]:
dic ={}
lstwin = []
lstrec = []
while True :
break
else :
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)
#Menuliskan berulang kali lalu meminta pengguna untuk memasukkan nama tim dan berapa
In [66]:
from random import randint
n = 5
print(grid)
In [67]:
# game.py
import random
def create_deck(shuffle=False):
if shuffle:
random.shuffle(deck)
return deck
def deal_hands(deck):
def play():
deck = create_deck(shuffle=True)
print(f"{name}: {card_str}")
if __name__ == "__main__":
play()
P1: ♠Q ♠3 ♣2 ♢A ♣9 ♢7 ♡5 ♠6 ♡Q ♡7 ♢5 ♢8 ♡9
P3: ♡A ♡4 ♣Q ♢9 ♡3 ♢6 ♣3 ♣K ♢2 ♠K ♣5 ♠A ♠J
In [68]:
class Card:
self.suit = suit
self.rank = rank
def __str__(self):
"""
Queen of Hearts
"""
Card.SUITS[self.suit])
if __name__ == '__main__':
import doctest
doctest.testmod()
**********************************************************************
Failed example:
print(Card(2, 11))
Expected:
Queen of Hearts
Got:
Jack of Hearts
**********************************************************************
1 of 1 in __main__.Card.__str__
In [69]:
from collections import namedtuple
class Deck:
suits = '♦♥♠♣'
ranks = '23456789JQKA'
def __init__(self):
flush = False
count = 0
deck = Deck()
stop = False
hand = deck.deal(5)
continue
flush = True
break
if flush:
break
else:
count +=1
print(f'Count is {count}')
Count is 0
print("Original dictionary:")
print(d)
print(type(d))
import json
with open('dictionary') as f:
data = json.load(f)
print(data)
Original dictionary:
<class 'list'>
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))
print("utcmoment: {0}".format(utcmoment))
for tz in timezones:
localDatetime = utcmoment.astimezone(pytz.timezone(tz))
print(localDatetime.strftime(localFormat))
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
def value(r):
if (r == 'I'):
return 1
if (r == 'V'):
return 5
if (r == 'X'):
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
s1 = value(str[i])
if (i + 1 < len(str)):
s2 = value(str[i + 1])
res = res + s1
i = i + 1
else:
res = res + s2 - s1
i = i + 2
else:
res = res + s1
i = i + 1
return res
# Driver code
print(romanToDecimal("MCMIV"))
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
In [11]:
s = 'Hello.\nThis is a text file.\nBye!'
print(s)
#berguna untuk membaca file teks yang memuat seluruh file ke dalam string
Hello.
Bye!
In [12]:
f = open('writefile.txt', 'w')
f.close()
print(f)
In [13]:
file1 = open('ftemps.txt', 'w')
temperatures = ['fahrenheit']
for t in temperatures:
print('t*9/5+32, file=file1')
file1.close()
print(t)
t*9/5+32, file=file1
fahrenheit
In [14]:
questions = ['apakah kamu suka tidur?']
print(questions)
print(answer)
In [15]:
lines = ['12/03/2009', ' SalemInternational', '35', ' Marshall', '119']
biggest_diff = 0
for g in games:
diff = abs(8-2)
if diff>biggest_diff:
biggest_diff = diff
game_info = g
print(game_info)
['12/03/2009']
EXERCISE
CHAPTER 13
In [1]:
def print_hello():
print('Hello!')
print_hello()
print('1234567')
print_hello()
#berguna untuk membuat fungsi sederhana yang hanya digunakan untuk mencetak sesuatu
Hello!
1234567
Hello!
In [2]:
def draw_square():
print('*' * 15)
print('*' * 15)
In [3]:
def print_hello(n):
print('Hello ' * n)
print()
print_hello(3)
print_hello(5)
times = 2
print_hello(times)
Hello Hello
In [16]:
def multiple_print(string, n):
print(string * n)
print()
multiple_print('Hello', 5)
multiple_print('A', 10)
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)
73.0
In [18]:
from math import pi, sin
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]
In [19]:
def multiple_print(string, n, bad_words):
if string in bad_words:
return
print(string * n)
print()
multiple_print
In [20]:
def multiple_print(string, n=1):
print(string * n)
print()
multiple_print('Hello', 5)
multiple_print('Hello')
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
In [22]:
def fancy_print(text='Hi', color='yellow', background='black',style='bold', justify=
print()
fancy_print
In [23]:
fancy_print(text='Hi', style='bold', justify='left',
background='black', color='yellow')
fancy_print
#merupakan urutan argumen tidak menjadi masalah saat Anda menggunakan argumen kata k
In [24]:
def fancy_print(text, color='black', background='white',
style='normal', justify='left'):
fancy_print('Hi', style='bold')
fancy_print('Hi')
fancy_print
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
print(print_time())
#berguna untuk membuat variabel global yaitu variabel yang sama tersedia untuk beber
30
None
EXERCISE
In [6]:
def rectangle (m,n):
print ('*'*n)
rectangle (2,4)
****
****
In [7]:
def add_excitement (string,n):
print (string,n)
Agnes !
In [8]:
def sum_digits (n):
sum_digits (45)
sum_digits (560)
11
In [9]:
def sum_digits(n):
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
print (sol)
number (4)
3874
if n%i==0:
number_of_factors(8)
In [13]:
def numbers(n):
L=[1, 3, 5, 6, 10]
largest=0
for num in x:
if num==x:
x==num
print (num)
numbers (8)
In [14]:
def diff_position (string1, string2):
if len(a)<len(b):
length=len(a)
else:
length=len(b)
count=0
if a[i]!=b[i]:
count=count+1
print (length-count)
string1='Pyhton'
string2='Path'
diff_position(string1, string2)
In [16]:
def findall(n):
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)
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
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)
not prime
prime
not prime
prime
In [22]:
def base20(num):
if num<=20:
return a[str(num)]
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))
In [23]:
def verbose(num):
if (num<20):
return d[num]
if (num<100):
if num % 10==0:
return d[num]
else:
if (num<10**3):
if num % 100==0:
return d[num//100]+'hundred'
else:
if (num<10**6):
if num % 10**3==0:
return int_to_en(num//10**3)+'thousand'
else:
if (num<10**9):
if (num % m)==0:
return verbose(num//10**6)+'million'
else:
if (num<10**12):
if (num % b)==0:
return verbose(num//10**9)+'billion'
else:
if (num % 10**12==0):
return verbose(num//10**12)+'trillion'
else:
print (verbose(549055))
print (verbose(584085))
print (verbose(950343))
fivehundred andfortyninethousandfiftyfive
fivehundred andeightyfourthousandeightyfive
a=string1+string2
print(sorted(a))
merge('hello','pyhton')
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
if alist[midpoint] == item:
found = True
else:
last = midpoint-1
else:
first = midpoint+1
return found
print(binarySearch(testlist, 3))
print(binarySearch(testlist, 13))
False
True
CHAPTER 14
In [27]:
class Example:
self.a = a
self.b = b
def add(self):
e = Example(8, 6)
print(e.add())
14
In [9]:
from string import punctuation
class Analyzer:
for c in punctuation:
s = s.replace(c,'')
s = s.lower()
self.words = s.split()
def number_of_words(self):
return len(self.words)
analyzer = Analyzer(s)
print(analyzer.words)
#program analyzer yang melakukan beberapa analisis sederhana pada sebuah string.
Number of words: 7
In [10]:
class Parent:
self.a = a
def method1(self):
print(self.a*2)
def method2(self):
print(self.a+'!!!')
class Child(Parent):
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()
hihi
hi!!!
hihihihihihihi
hi!!!
hibye
self.a = a
def print_var(self):
print(self.a)
class Child(Parent):
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()
#jika kelas anak hanya ingin menambahkan ke salah satu metode induk.
hi
hi
bye
In [31]:
x_copy = 'agnes'
print(x_copy)
agnes
In [32]:
from copy import copy
x_copy = copy('agnes')
print(x_copy)
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):
(a._str_())
In [2]:
class Product:
def __init__(self,name,amount,price):
self.name=n
self.amount=a
self.price=p
def get_price(self):
def make_purchase(self):
if self.amount<10:
if self.amount>100:
n=input('Product Name:')
p=eval(input('price of pdt:'))
c=Product(n,a,p)
print(c.get_price())
print(c.make_purchase())
Product Name:Case Hp
price of pdt:2015
In [3]:
class Password_manager:
def __init__(self):
self.old_passwords = []
def get_password(self):
return self.old_passwords[-1]
self.old_passwords.append(password)
# check if the given password is the current password and return an appropri
return password == self.get_password()
manager = Password_manager()
manager.set_password('Monty')
# check password
print(manager.is_correct('baz'))
print(manager.is_correct('Monty'))
False
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):
#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']
s='s'
print(verification.words_with_lenght(lenght))
print(verification.starts_with_s(s))
print(verification.ends_with_s(s))
print(verification.palindromes())
abba
sandro
sandro
abba
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.
print(self.a*100,'cm')
print(self.a/100,'m')
# If b=feet and c= centimetre then it multiply 'a' with 30.48 and vice versa.
print(self.a*30.48,'cm')
print(self.a/30.48,'feet')
# If b=inch and c= feet then it multiply 'a' with 0.083 and vice versa.
print(self.a*0.083,'feet')
print(self.a/0.083)
# If b=metre and c= feet then it multiply 'a' with 3.28 and vice versa.
print(self.a*3.28)
print(self.a/3.28)
# If b=km and c=metre then it multiply 'a' with 1000 and vice versa.
print(self.a*1000,'m')
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')
print(self.a/10000)
# If b=miles and c= kilometre then it multiply 'a' with 1.60 and vice versa.
print(self.a*1.60,'km')
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)
count=0
count1=0
count2=0
for i in range(numberofround):
yourchoice.lower()
x=sample(gamesample,1)
y=''.join(x)
if yourchoice==y:
count=count+1
if count>=1:
print('match tie')
if count1>=1:
print('you lose')
if count2>=1:
print('you won')
d=Rock(gamesample=[])
d.Game()
you won
match tie
you won
Number of match tie: 1 Number of match you lose: 0 Number of match you won: 2
CHAPTER 15
In [ ]:
#1
def calculate():
temp = int(entry.get())
temp = 9/5*temp+32
entry.delete(0,END)
root = Tk()
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)
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
def callback():
label.configure(text='Button clicked')
root = Tk()
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
alphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
def callback(x):
label.configure(text='Button {} clicked'.format(alphabet[x]))
root = Tk()
label = Label()
for i in range(26):
buttons[i] = Button(text=alphabet[i],
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
def callback():
global num_clicks
num_clicks = num_clicks + 1
label.configure(text='Clicked {} times.'.format(num_clicks))
num_clicks = 0
root = Tk()
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
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].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
root = Tk()
alphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
buttons = [0]*26
for i in range(26):
buttons[i] = Button(text=alphabet[i])
buttons[i].grid(row=0, column=i)
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
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
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
def mouse_motion_event(event):
def wheel_event(event):
if event.delta>0:
diff = 1
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:
canvas.itemconfigure(rect, fill=color)
def b1_motion_event(event):
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.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.
CHAPTER 17
In [ ]:
#1
def quitter_function():
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
def update_timer():
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
def open_callback():
filename = askopenfilename()
def saveas_callback():
filename = asksaveasfilename()
root = Tk()
menu = Menu()
root.config(menu=menu)
file_menu.add_command(label='Open', command=open_callback)
file_menu.add_separator()
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
def callback():
global count
count +=1
root = Tk()
count = 0
s = StringVar()
s.set('Hello')
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 [ ]: