0% found this document useful (0 votes)
7 views114 pages

Python Basics: Lists, Tuples, and Conditionals

This document serves as a comprehensive guide to the basics of Python programming, covering topics such as f-string formatting, list operations, tuples, conditional statements, loops, and dictionaries. It provides practical examples and tips for effective coding, including error handling and code readability. Additionally, it introduces simple applications like a calculator and a to-do list, emphasizing the importance of data persistence.

Uploaded by

fajarbesari1004
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views114 pages

Python Basics: Lists, Tuples, and Conditionals

This document serves as a comprehensive guide to the basics of Python programming, covering topics such as f-string formatting, list operations, tuples, conditional statements, loops, and dictionaries. It provides practical examples and tips for effective coding, including error handling and code readability. Additionally, it introduces simple applications like a calculator and a to-do list, emphasizing the importance of data persistence.

Uploaded by

fajarbesari1004
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Catatan Python Learning

PART I : BASIC OF PYTHON

Catatan Python Learning


f-string formatting = calling values from variables
f"{var1} {var2}" = better than using + and " "
Use underscores to group digit numbers—the interpreter will ignore them.
Constants are useful for variables that remain unchanged throughout the program,
like pi numbers etc.
Comments help with teamwork by letting you note down your previous coding
steps—use Ctrl + / to add them.
Lists [] are powerful tools for storing multiple user data items.
Use positive index order (from 0) or negative index (from -1) to access the last
element.
There are 2 ways to add elements to a list: append() adds to the end, while insert()
adds at a specific position.
There are 3 ways to remove list elements: del statement (del variable[index])
removes permanently, [Link](index) removes and returns the element, and
remove(value) deletes the element but keeps it accessible like moving it to a new
variable.
Lists can be arranged alphabetically or reverse-alphabetically.
Use sort() method for permanent alphabetical ordering, sort(reverse=True) for
reverse order, and sorted(var) function for temporary ordering—reverse=True
works here too.
NOTE: The difference between methods and functions is that methods are
features attached to variables (like my_soul.brave() makes the variable braver),
while functions work independently (like len()).
TIPS: To handle list index out of range errors, try accessing last items with index
-1, or use len() function first to check the number of items.

Catatan Python Learning 1


Use for-in statements to efficiently loop through repeated actions. You need a
temporary variable to access list items. Example: for temporary_var in list_var.
TIPS: Use plural names for lists and singular for temporary variables. Example:
cat/cats, food/foods, etc.
TIPS: Indentation errors usually happen when people forget to use proper spacing
or miss required indents. Also, for-loop statements need a colon in the first line.
The range() function creates a sequence of numbers.
Parameters are (start, end, step) with step defaulting to 1.
range() helps create number sequences for lists in for-loop statements.
3 ways to use range():

1. Use list() function to convert range to a list


Example: list = list(range(start,end))

2. Use append method to add numbers generated by range


Example: squares = []
for value in range(start,end)
square = value** # ** is for exponent
squares = [Link](square)

3. Use list comprehension for an efficient single-line approach


squares = [value** for value in range(start,end)]

slice in list use colon to rule, just like range. has parameter start,end and gap
seperated by colon (:), ex. var = var[1:3]

if there is start and end parameter [2:4] then the output is index start is element 2
end up with index end - 1 is element number 3

if there is no end parameter [2:] then the output is index start is element number 2
and end up with the last element
if there is no start parameter [:3] then the ouput is index end is elemet number 3
and end up with the first element

if there is no start and end parameter [:] the mean the output is all entire element,
this usualy beneficial for copy a list data to new variable

Catatan Python Learning 2


NOTE : the output in same orderline not reverse and works with negative index
too. and the output of last index as -1 then inputed parameter.
slice usefull for makes top 3 on high score games u build

tuple is the only method to assiign a value/items we wont change it, just like a list
but tuple using a paranthese () to define while list use a square bracket. tuple only
has 2 methood are count() to serching how many the items in tupples existed and
index() to finding a element existed in where index number if has 2 or more items
in same it will return the where first items existed.

tuple cant compromise with changing items tuples[0]=90, it will error return. tuple
only want a changing all entire with variable define to reassign new items. ex. x =
(12,15) use x = (45,67) to reasign items not with indexed method x[0] = 45 x[1] =
67 it will error.

styling for better code readblity justt learn PEP 8

conditional if is a powerfull tool to check a circumstance of code. the condition of


true and false, each condition has a exceute program itself.
if true condition will execute true program and false condition will execute false
program. this code use name operator perbandingan ==,≥,≤,≠ to checking
boolean value before execute.

equality operation example. a variable name list have a items


[’asu’,’babi’,’puki’,’cukimai’]

use for loop to checking


for lis in list:
if lis ==’asu’

print(”already existed”
the code will checking the list items if true will execute print metode, if false will
not execute nothing.

Catatan Python Learning 3


sebaliknya dengan equality operation, a inequality operation has true value if a
value with intial has a inequality

for lis in list


if lis ≠ ‘kontlo’
print(’doesnt existed’

the code will checking the list items, cause kontlo hasnt assigned in list data. it will
true valuable and the expresion will execute.

or u can use in or not in statement to checing a items in a list

check = ‘asu’ in list

print(check) #if true will excecuted

check_2 = ‘babi’ not in list


print(check_2)

mutiple condional can using and dan or statement

and statement ( 2 coonditional must havve true value to executed)


if 2 condicional valued true then the expresion will executeed

if 1 condional valued true and other is false then the expresion will executed

if 2 conditonal valued false then the expresion will noot executed

or statement (one of 2 must have true condition to execute the program)

if 2 condicinal valued true then expresion will executed

if 1 conditional valued true and other is false the expresion will executed

if 2 conditional valued false the xpresrion will not executed

boolean exppresion is just a condicional test to keep your program on traack you
want, if true what you will program run to, and if false will program to where or no

Catatan Python Learning 4


run anymore. always true boolean firts will executed.

NOTE : the condicioonal if structure is if statement will do expression, elif


statement will do expresseion, else expresion. else is a last/closed and no have
statement.

if statement:
expresion

elif statement:

exprresion

else:
expresion

this is 3 blok if statement, if first block passed, next blok will missed

in statement a operator define by comparison operators

simple if statement
if conditional_test :

do something

this this one blok if statament

if true python will excecute in do something program, if false will ignored/doesnt


run

not simple if statement


use chained if elif else to runing one blok. if want more blok u wanna run use
series of independen if simple statement.

if conditional_test :

do something

if conditional_test :

Catatan Python Learning 5


do something
if conditional_test :

do something

this meant a series independent of if statement, all code in do something will


execute when the value in condicional test is true. if false will passed to next
condional

for loop use for CHECKING ITEMS validation OF TWO OR MORE DATAS and TAKE
ALL ACTION IN LOOP can use comparion operant, and or statement, in
statemenet. can be true if emppty data

# a boss want username in case insensitif it is mean JOHN, John, john is a same
# so that types username notrepassing to be used

for new_user in new_users: #menjabarkan items yang ada di new_users di variab


if new_user in current_users: #comparing items di daftar current_users
print(f"{new_user} enter a new username".title()) #jika true maka print items
elif new_user in current_users_copy:
print(f"{new_user} enter a new username".title()) #jika true maka print items
else:
print(f"the username {new_user} is available".title())

everything a statement when has collon end up will has a boolean value or a
circumtances to expres next move while a value is true

datas = ['']

#chekin data
if datas:

Catatan Python Learning 6


for data in datas: #Since the element will always be found in the list, the condit
print(f"data tidak tersedia".title())
else:
print("data tersedia: {data}")

numbers = [1,2,3,4,5,6,7,8,9]
print(bool(numbers)) #output is true

for number in numbers: #will execute cause numbers list is true (there are eleme
if number == 1:
suffix = 'st'
elif number == 2:
suffix = 'nd'
elif number == 3:
suffix = 'rd'
elif number >= 4 and number < 10:
suffix = 'th'
print(f"{number}{suffix}")

IT IS SO IMPORTANT TO KNOW INITIAL OBJECT VALUE OF BOOLEAN


ATURAN BOOLEAN

Non-empty sequences or collections (like lists, tuples, strings, dictionaries,


sets) are considered True .

Empty sequences or collections are considered False .

The number 0 is considered False .

None is considered False .

Any other value is considered True .

colors = [] #value is false

if colors: #value is false cause none


for color in colors: #this code will not executed

Catatan Python Learning 7


print(f"{color}")
else: #cause colors is false the this will true
print(f"the color is empty") #this code will executed

------------------------------------------------------------
colors = ['red','blue'] #value is true

if colors: #value is true cause colors has element


for color in colors: #this code will executed
print(f"{color}")
else: #cause colors is true then this code will false
print(f"the color is empty") #this code will not executed

1.
Direct Comparison with True : The condition if colors == True is checking if the
list colors is exactly equal to the boolean value True . This comparison is not about
the truthiness of the list but about whether the list object itself is the same as the
boolean value True . Since a list object is never the same as the boolean
value True , this condition will always be False .

colors = [] #value is false

if colors == True: #value always false cause isnt be comparisate beetwen object
for color in colors: #this code will not executed
print(f"{color}")
else: #cause colors is false then this will true
print(f"the color is empty") #this code will executed

colors = ['red','blue'] #value is true

if bool(colors) == True: #value is true cause colors has element


for color in colors: #this code will executed
print(f"{color}")
else: #cause colors is true then this code will false

Catatan Python Learning 8


print(f"the color is empty") #this code will not executed

SIMPLE KALKULATOR APP

print(f"simple kalkulator".upper())
#initial value
numb_1,numb_2 = 0,0

#input value
numb_1 = int(input(f"input angka pertama :".title()))
numb_2 = int(input(f"input angka kedua :".title()))

#input operasi
operasis = input(f"masukan operasi + - * / allowed : ".title())

#rumus
addition = numb_1 + numb_2
reduction = numb_1 - numb_2
perkalian = numb_1 * numb_2
pembagian = numb_1 / numb_2

if operasis == '+':
print(f"hasilnya : {addition}")
elif operasis == '-':
print(f"hasilnya : {reduction}")
elif operasis == '*':
print(f"hasilnya : {perkalian}")
elif operasis == '/':
print(f"hasilnya : {pembagian}")
else:
print("kau input operasi apa tolol!!".upper())

Catatan Python Learning 9


You can't use variables for local storage. If you want information to persist across
program runs, you need to store it in a persistent location - typically a disk file or a
database. There are a lot of modules available to make this easier, Pickle (as noted
in klashxx's response) is an excellent one for simple scenarios.

print(f"TO DO LIST APPLICATION")


#even you were input a lot data in here it will call only the last your input
#you need a local disk or database to store a data inputed
#use method open(),write(), and read() we can do this to store data in disk storag

while 1 == 1:
#initial list
to_do = {}

# print(type(to_do))
#pair input priority key-value
to_do['prioritas'] = int(input(f"inputkan prioritas".title()))
#pair input do_list key-value
to_do['do_list'] = input(f"masukkan to do list : ".title())

#display
print(f"dictionary sementara : {to_do['prioritas']}. {to_do['do_list']}")
print(f"press any key to play again".upper())

coarsed_list = open("coarsed_list.txt", "a")


file = input(f"Kata kasar hari ini :".title())

# Write the new input to the file


coarsed_list.write(file + "\n")
coarsed_list.close()

Catatan Python Learning 10


# Open the file in read mode to display its contents
buka = open("coarsed_list.txt", "r")
print([Link]())
[Link]()

dictionary

a powerfull teknic to call a value based on a key paired


same as a list, can be altering/mutable and storing a lot datas

to define dictionary, create name variable and use bracket {} containing key-value
pairs. every data can be stored in dictionary.
user a colon to connecting key-value and use commas to store other key-value
datas.

variables = {'key_1': 'value1', 'key_2' : 76}

einstein = {
'name': 'einstein',
'age': 76,
'carrier': 'scientist',
}

to accesing data with key value use [ ] contain a key to return a value connected,
if a key you want to acces didnt existed, the console will return a error

Catatan Python Learning 11


umur = einstein['age']
print(f"umurnya adalah : {umur}".title())

to accesing data with get() method use parameter key and string ( if a key what u
want to acces didnt existed, the string will appeared. if not be define the striing
parameter, console will return a none

variable_temporary = dict_var.get('key','string')

karir = [Link]('carrier',"key-pairs didnt existed")


print (f"karirnya : seorang {karir}".title())

to add new key-value call this pairing. like same with accesing but with new key
and the value

dict = {} #empty dictionary as initial is empty


print(f"ini adalah dictionary originalnya : {dict}")

#pairing 2 key-value
dict['nama'] = 'maxwell'
dict['age'] = 87

print(f"ini adalah dictinoary setelah penambahan key-value : {dict}".title())

to change value based on key, just like same using square bracket contain a key
that you want to change and asign a value with new one

Catatan Python Learning 12


alien_0 = {'color':'green','point':5 }

print(f"this is a original color : {alien_0['color']}")

alien_0['color'] = 'yellow'
print(f"the color has been changed to {alien_0['color']}")

to remove unused data u can usiing a del statement with just like same above
tectic, use square bracket contain key data u wanna delete.

alien_0 = {'x_potition':0, 'y_potition':25, 'speed':'medium'}


print(f"this is original x potition : {alien_0['x_potition']}")

if alien_0['speed'] == 'slow':
x_increment = 1
elif alien_0['speed'] == 'medium':
x_increment = 2
elif alien_0['speed'] == 'fast':
x_increment = 3

print(f"speed of the allien : {alien_0['speed']}")


print(f"so move x incremant is : {x_increment}")

new_potition = alien_0['x_potition'] + x_increment


print(f"posisi terbarunya adalah {new_potition}".title())
---------------------!!!!!!!!!!!!!----------------------------
#remove unused data
del alien_0['y_potition']
print(f"sisa data : {alien_0}".title())

Catatan Python Learning 13


a dictionary to similar object, use for storing polling data

#a dictionary a similar object


favorite_languages = {
'albert' : 'C',
'faraday' : 'java',
'newton' : 'python',
'babi' : 'nyindir',
}
fav = favorite_languages['albert']

print(f"bahasa favorite albert : {fav}".title())

lopping all key-value pairs in a dictionary,


using for loop, to define that, always using a temporary variable, cause a
dictionary we use 2 temporary variable to accesing a key and value. then we use
method items(), with empty parameter.

ITEMS() METHOD
1ST VARIABLE TEMPORARY IS ALWAYS A KEY
2ND VARIABLE TEMPORARY IS ALWAYS A VALUE

user_0 = {
'username' : 'archimadesu',
'first_name' : 'archi',
'last_name' : 'medes',
}

#use 1 temporary variable to looping all element key:value paired


for k in user_0.items(): #output {'key':value,'key':'value'}

Catatan Python Learning 14


print(k)

#use 2 temporary var to accesing lopping all element


#lopping user_0 and print all key element
for k,v in user_0.items(): #output id all key
print(k)

#use 2 temporary var to accesing lopping all element


#lopping user_0 and print all value element
for k,v in user_0.items(): #output is all value
print(v)

#tempoary value can use whatever even a abbrevations

#works to a dictionary with similar object and with different value


favorite_languages = {
'albert' : 'C',
'faraday' : 'java',
'newton' : 'python',
'babi' : 'nyindir',
}

for name, language in favorite_languages.items():


print(f"{name}'s favorite language is a {language}".title())

looping a dictionary keys only can use keys() method or with default for loop
when use it with a list, using one variable without the method keys().

keys() method useful for who want assign keys only

Catatan Python Learning 15


for name in favorite_languages.keys():
print(f"{name}".title())

for name in favorite_languages:


print(f"{name}".title())

#output will same

You can choose to use the keys() method explicitly if it makes your code
easier to read, or you can omit it if you wish.

favorite_languages = {
'albert' : 'C',
'faraday' : 'java',
'newton' : 'python',
'babi' : 'nyindir',
}

friends = ['albert','babi']
for name in favorite_languages.keys(): #1
print(f"Hi, {name}") #2
if name in friends: #3
language = favorite_languages[name] #4
print(f"{[Link]()} bahasa favoritnya : {language}") #5

# we can read that code mean. looping and pulling a element in favorite_languag
# then assign to temporary var called name cause its not empty data type
# so bolean value is true will executing statement #2 (action loping for print)
# if statement indicating a condition, that if element existed too in friend then
# will execute statement #4 and #5 (action take looping) if condition true

Catatan Python Learning 16


# so there are 2 looping action, first looping no condition and with condition

for name in favorite_languages.keys(): #1


print(f"Hi, {name}") #2
if name in friends: #3
language = favorite_languages[name] #4
print(f"{[Link]()} bahasa favoritnya : {language}") #5

# while above just act one looping only that execute #2 when true
# cause if statement no contained in for looping
# so if statement just execute one only that last element execute
# wherease should be 2 that we want to display cause list contained same 2 valu
# favorite_language

OUTPUT CODE 1 PRINTING SPECIAL GREETING “BAHASA FAVORITE”


CORRECTLY

Hi, albert
Albert bahasa favoritnya : C
Hi, faraday
Hi, newton
Hi, babi
Babi bahasa favoritnya : nyindir

OUTPUT CODE 2 DIDNT PRINTING SPECIAL GRETING CAUSE IF STATEMENT


DIDNT LOOPING
Hi, albert
Hi, faraday
Hi, newton
Hi, babi
Babi bahasa favoritnya : nyindir

can also use the keys() method to end out if a particular person was polled

Catatan Python Learning 17


if 'erin' not in favorite_languages.keys():
print(f"Erin, please take our poll!")

NOTE : keys method isnt just to looping purposes. can use for a simple expresion
like above

looping a dictionary in paticular order using keys method wraped in sorting


method to be ascending order. first step is using a if in statement and define new
temporary variable then write a condition, this case we want to sorting a keys only
and printing all as a statement if the condion is true

favorites_animals = {
'einstein' : 'rakun',
'newton' : 'trenggiling',
'mozart' : 'babi',
'nieze' : 'anjng',
}

for name in favorites_animals.keys():


print(f"{name},terimakasih sudah polling!!") # output print looping all keys in o

for name in sorted(favorites_animals.keys()):


print(f"{name},terimakasih sudah polling!!") #output print looping all keys in pa

as same as keys that can being called by method keys(). also a values that can be
called separated without a keys using value() method. to define just like a code
above same keys() method.

Catatan Python Learning 18


favorites_animals = {
'einstein' : 'rakun',
'newton' : 'trenggiling',
'mozart' : 'babi',
'nieze' : 'anjng',
}
print(f"animals yang sudah ada di list: ")
for animals in favorites_animals.values(): # output print all value in original order
print(animals)

for animals in sorted(favorites_animals.values()): # output print all values in sortin


print(animals)

in other circumstances, sometimes we want to displaying items with no repetitif


way means no duplicated existed. method set() use to do this task to make unique
output with no repetitif.
if u see if a data stored in bracekt with no keys-value pairing. it is must be a sets
data.

in real case set method will beneficial to displaying a data with no duplicated

favorites_animals = {
'einstein' : 'rakun',
'newton' : 'trenggiling',
'mozart' : 'babi',
'nieze' : 'anjng',
'khircoff' : 'babi',
}

for animals in set(favorites_animals.values()):

Catatan Python Learning 19


print(animals) # output printing all values with no repetitif

cats = {'persia', 'anggora', 'local','mandung','oren','persia'}


print(cats) # output printing all cats items in unique way ( no repetitif )

nested datas is a storing a lot in beautiful ways to make more structured. nesting
is a powerfull tecniq ways to store a data when a datas are a lot of information. u
can make nesting a list in list, list in dictioanry, dictioanry in a list, and can also
dictioanry in a dictionary.
u can use for loop to display data fasttly, and accesing with method items(),
keys(), values() to dictionary.

a dictionary in a dictionary

rocks = {
'felsik' : {
'color' : 'light',
'minerals' : 'quartz',
'keterdapatan' : 'upper crust',
},
'intermediete' : {
'color' : 'grey',
'minerals' : 'biotit',
'keterdapatan' : "middle crust",
},
'bassa' : {
'color' : "dark",
'minerals' : 'pyroxcen',
'keterdapatan' : 'deep crust',
}
}

Catatan Python Learning 20


for rock,ciri in [Link]():
print(f"\nciri batuan {rock}")
for k,v in [Link]():
print(f"{k} : {v}".title())

a list in dictionary
rocks = {
'granite' : ['kuarsa', 'feldspar', 'mikas', 'amfibol'],
'andesite' : ['plagioklas feldspar', 'piroksen', 'hornblende', 'olivin'],
'peridotit' : ['olivin','piroksen', 'klinopiroksen', 'ortopiroksen', 'hornblende', 'mik
}

for rock,primary_mineral in [Link]():


print(f"\nmineral utama {rock} :")
for primary in primary_mineral:
print(f"{primary}")

dicationary in a list

kuarsa = {'color' : 'no color','kilap' : 'kaca','hardness':7}


mikas = {'color' : 'dark','kilap' : 'kaca','hardness':4}
feldspar = {'color' : 'yellow','kilap' : 'dull','hardness':6}

granite = ['kuarsa','mikas','feldspar']

print(f"mineral utama granite :")


for granit in granite:
print(f"{granit}")

NESTED TECTIQ IS THE MOST USED ON PROGRAMING SO MAKES IT U ARE


UNDERSTAND!!!

Catatan Python Learning 21


while loop

use to a more interactif programing to user. we example using a input() function.


input() is a function to makes user interactive to ask a value of variable.

program will not end if the input fucntion isnt filled.

numbers = 0

pesan = f"\nMASUKAN ANGKANYA ? "

numbers = int(input(pesan))

print(numbers)

for example code above, a declare int() funcatiuon to make a input is a integer
value, so if user a input string will erorr outputed. will return a numbers what user
input

xception has occurred: ValueError


invalid literal for int() with base 10: 'awsdf'
File "C:\Users\sustainability\Desktop\Python\[Link]", line 1337, in <module>
numbers = int(input(pesan))
^^^^^^^^^^^^^^^^^
ValueError: invalid literal for int() with base 10: 'awsdf'

below is a simple define a while loops

Catatan Python Learning 22


while condition_true:
executed_expresion_looped

is a loop a certainly running always if the condition is true. it is so damn beneficial


for a example games end concept.

while loops use to print looping a series a number

initial_numbers = 0

while initial_numbers < 5:


print('this is will executed as infinity loops')

# cause while always executed if the condition true


# the code above readed as initial_numbers = 0 is lower than the condition = 5 so

a code above explained that in the begining alwayas define a intial value of
variable, intial_number = 0 it has value boolean of False cause 0, then define while
loops statement, while condition intitial_number less than 5. so cause it is true ( 0
< 5 ), while loops will running always then block of expresion will be executed
looping infinity cause hasnt a bounderis to broke the infinity, or caused by we
printed a string that it hasnt a relation with a condition while true.

initial_number = 1 # this is true value

while initial_number < 11: # true so expresion below will be executed


initial_number += 1 # increment mean variable will printed up
print(initial_number) # throught true initial number will print number until the inc

Catatan Python Learning 23


# increment use for broke the infinity in numbers reverse condition??

therefore, in code above has a relation between the condition and the printable
log, a numbers series. the story is initial_number in the begining has intial value as
0 or false, then continue to while statement it has a condition if a intial_number is
less than 11, maka while loop while runing cause the true is intial number 0 less
than 11. then the expresion code will executed as loop. it were a inrement meant
intial_number = intial number + 1. meaning when looping the variable will priinting
until the condition is false.

the diferencies with for loop is, that for loop use to looping a stored data,
wherease while loop statment use to makes a program more interactive

while loops use for a user to quiting a programs

it is useful for a concept example a gameover condition or a condition something


to make a user wanna quit from a program.

#while loop for letting user to quit


promt = 'ketikkan apa saja akan saya ulangi'
promt += 'apa hayo : '

message = "" # intial value

while message != 'quit': # always true if the input user not such a 'quit'
message = input(promt) # cause true this expresion will executed
print(message)

while loops will never stop if the condition message ≠quit is still true. to make it
stop u need to make the condition of while loops to False, in this case we use a if

Catatan Python Learning 24


statment, if message ≠ ‘quit’ is a way to broke the while loops.
the story of code is:

1. initial value of message variable is false

2. then while statement message not equal comparison to ‘quit’ is not true, cause
intial value as false and the condition inside while statement false too, so
makes while stamenet has true value.

3. so block expresion code running looping, message variable has been updated
with input fucntion, became a idle when a user not filled yet

4. in the end if input a ‘quit’, it will makes while condition colapsing became false
value, cause quit is equal to quit, whereares the condition is true if a condition
the variable message not equal to ‘quit’ and initial value of variable is empty

while loops use for a many condition with flag state


this a concept usually to how games over end up with many condiiton, a
programmer
use to a flag them named call. define a variable active as true value, then can be
updated as a false value cause by someting condition.

increment = 0
counter = 0
active = True

while active:
numbers = input()
increment += 1
if numbers == '':
print(counter + increment)
elif numbers == 'quit':

Catatan Python Learning 25


active = False
print('you broke my loop!')

using break statement to broke or falsenave in a while


loops
break statement use to a alternative way to recondition while loops became false,
overide updating a variable inside while loops to false. break statement just a code
to quit immediately of course combination with if statement. break statement also
works to for loops to breaking iterate a list or dictionary.

prompt = "\nPlease enter the name of a city you have visited:"


prompt += "\n(Enter 'quit' when you are finished.) "
while True:
city = input(prompt)
if city == 'quit':
break
else:
print(f"I'd love to go to {[Link]()}!")

the code story is :

1. while loops in this case use frontal condtion is true to make looping running

2. then cause true, block code will be executed, there are 2 block code
highlightly

3. the first is a city as new variable has a input function to ask a value from user

4. then if equality comparison, beetwn inputed user as city variable weather


equal to ‘quit’, if not equal as a false value will executed code block in else
statement, and if true that user input a city as ‘quit’ that is equal to ‘quit’

5. then if true inside if statement, then a break statmenet will executed. mean
that the program will be quit imediatelly.

Catatan Python Learning 26


users = ['einstein','mozart','newton','khircof','maxwell']

for user in users:


print(f"{user}") # khircoff and mawxwell will not be printed cause code block b
if user == 'newton':
print('i found newton')
break

example of break statement in for loops

continue statement to skipping a something in a loops


use for loops too

skipped_number = 3
active = True

while active:
for number in range(1,10):
if number == skipped_number: # a condition skipping number 9
continue # this a statement to skipping a numbers of 9
print(number) # display a value from range with conditional executed
print('end of loops')
active = False # a flag variable to breaking while loops

this a example code of implementing while loops


neested inside for loops
in a conlusion, the while loops is a teknik to control a executed block if the while
loops hold to true value will looping to begining until the condition became false
and stopped while loops imediately. whereas, a for loops is a tecnic to extract a
data or element in a list or distioanry or other data stored variable.

Catatan Python Learning 27


# Initialize variables
active = True
outer_counter = 0
skipped_number = 3

# Outer while loop


while active:
outer_counter += 1
print(f"Outer loop iteration: {outer_counter}")

# Inner for loop


for number in range(1, 6):
if number == skipped_number:
print(f"Skipping number {number} in inner loop")
continue # Skip the rest of the code in this iteration and move to the next

if outer_counter == 3:
print("Breaking out of both loops")
active = False # Set active to False to stop the while loop
break # Break out of the for loop

print(f"Inner loop number: {number}")

print("End of outer loop iteration\n")

print("Both loops have ended")

a simplify of the while loops behaviour

active = True
while active:
print('1st executed block')
print('2nd executed block')

Catatan Python Learning 28


print('3rd executed block')
print('if doesnt breaking rules existed will looping from beginning 1st block to 3
active = False # flag variable as while loops breaking rules

works = True
while works:
print('1st executed block')
print('2nd executed block')
print('3rd executed block')
print('if doesnt breaking rules existed will looping from beginning 1st block to 3
break # break statement as while loops breaking rules

NOTE :
nested loop in begining, must end with nested too, to avoiding multiple iteration
useless. the solution is use a flag variable. example found=True to False in the end
of nested thinngs. simplify if nested, make sure to pay attention the indentation
the shape should be like > mean must be back to original position in differences y
axis.

avoiding infitny loops


in the first experinces, a programmers will always running a inifty loops causeed
by doesnt scrutinezie a code that hasnt at least one code to make the condition of
while loops became false or to break statement.

use a while loops to moving a list to other list


this a concept use to example in website function to verifying a new registered
user were unverified to be verified.

Catatan Python Learning 29


the logic is we need 3 variable, unverified variable of list data store contain a list
of users name, verified variable of list data stored after moved from variable
unverified variable, and one variable temporary for storing or a bridge/api to move
a items in unverified to verified.
the method that we were use to running the logic are pop() to removing a last
items temporary and assign to temporary variable that we call users, after a last
variable was kicked out we will assign a new items in users variable to verified list
variable that things will take care by append() method which is storing items to the
last potition of list. then we will displaying with print() method, displaying a already
verified items.

import time
# unverified users list
unverified = ['nata','jeni','silvi','puput','septi']
verified = []

while unverified: # this is true condition


# remove unverified users and assign to new temporary variable users and add
users = [Link]() # a falseize ways to break infinite loops also remove m
print(f"\nverifying users : {users}")
[Link](5)
[Link](users) # assign a new items to verified variable that carried by
print(f"doneeeee")

else: # executed if while coniditon is false, this case caused by unverified list item
print(f"\nusers already verified : ")
for verif in verified:
print(verif,end=" ") #output septi puput silvi jeni nata

use a while loops for removing all items in list magically way
removing items in a list if there a lot duplicates is so damn will curlying your tumb
cause u need a same code in repetitive. so while loops can be a efisiens ways to

Catatan Python Learning 30


did it. we usee a remove() method in this case. in example code existed a code of
any ways with if in condition also for if statement.

favorite_lesson = ['mathematic','geologi','inggris','perancis','pyloshopy','geologi','

# prefered method
while 'geologi' in favorite_lesson:
favorite_lesson.remove('geologi')
print(favorite_lesson) # # output ['mathematic', 'inggris', 'perancis', 'pyloshopy', '

# comparison method 1
if 'geologi' in favorite_lesson:
favorite_lesson.remove('geologi')
favorite_lesson.remove('geologi')
favorite_lesson.remove('geologi')
print(favorite_lesson) # # output ['mathematic', 'inggris', 'perancis', 'pyloshopy

# comparison method 2
for geo in favorite_lesson:
if geo == 'geologi':
favorite_lesson.remove('geologi')
print(favorite_lesson) # output ['mathematic', 'inggris', 'perancis', 'pyloshopy', 'ch

filling a empty dictionary for polling data beneficial. the logic is we need a empty
dictionary and 2 variable temporary for use to a bridge or courrier then storing or
and paired as keys value to empty dictionary in order to filling that then displaying
the polling when everyone has polling.
the method to add data is like a simple way such a list did. dictionary name
followed by variable of courrier of keys and equal to courier variable of values.

response[name] = mountain

Catatan Python Learning 31


then we need a flag variable to break while loops infinite loops with input method,
if we answer yes, the program will continue, and otherwise.
the end of program particulary in else statement of while loops executed when the
varible flag was changed to false make else statement true whis is makes code
inside executed that displaying a user input with method items() to extract a keys
and value inside of for statement to take action repetitve and pritnting all of user
input.

import time

# initial variable
response = {}

# logic : users input for name, mountain, and yes/no


polling_active = True

while polling_active:
# inital temporary variable as courier for storing data
name = input(f"\nwhat is your name: ".title())
mountain = input(f"what mountain would you climb for: ".title())

# pairing keys and value and storing data to dictionary named response
response[name] = mountain

# message of progress
print(f"\nmengoleksi polling".title())
[Link](3)
print(f"been noted".title())

# logic for breaking while loops rules


ask = input(f"Would you like to let another person respond? (yes/ no)".title())
if ask == 'no':
polling_active = False
#print(response)

Catatan Python Learning 32


else:

# displaying an information has been stored


print(f"\n------------polling completed--------------.".title())
[Link](3)
for name, mountain in [Link]():
print(f"{name} would like to climb {mountain} mountain".title())

so damn to pay attention how the python to


try running the code, every each code is
executed orderly, same code difference
places will outpting difference too

every code block in python are contained


combinated or single of initializing value
variable, variable value assignment,
removing value of variable, moving value to
other variable, and displaying value to
users

simplify the code is contained by an


initializing variable, manipulating value, and
displaying value

all statement and function is use for


universal whereas a method is not, it only

Catatan Python Learning 33


beneficial for a object were built a method it
self

while loops = iterating vertically of block


code

for loops = iterating horizontally of stored


data variable

function
is a cool tools to verbose your code in one single line.
to function is just such a other statement but in fucntion we use a def stetemnt
mean ‘definition’.
followed by parenthes consist of parameters then a collon will end up the
definition. afterthat we should filling body of the fucntion to give a what jobs we
wanna do in that function.
parameter is a temporary variable inside the function to be a stored variable that
filled by argumenmt
argument is a value that filling a parameters to doing jobs inside body function

# define a function
def make_something(parameter1,parameter2):
# body function : a place to execute what wanna do in this function
# can consist of other proses like looping, printing, or other function itself

Catatan Python Learning 34


# calling a function
make_something(argument1,argument2) # to execute code inside body function

function is a powerfull tool to effisienly a code became less text and readeble.
potitional argument must have to be concern, or the output of program will not in
order what we wanna. to be sure, first argument whetere you were inputed is a
name, and the second is the city

def make_things(name,city): # it is always first argument is a name


print(f"{name} from {city}") # body function

make_things('harry','somewhere')

to broke the potitional argument we can use a keyword argument to make program
can running in order what we wanna but this doesnt matter cause python the
output will same but this case will more writing a code. to define the keyword
argument just use = to define the parameter, will working if u input a parameter
diferently within the parameter order function

make_things(city = 'somewhere',name = 'harry') # keyword argument to broke po

default value of parameter


is usefull for a parameter that we know always being filled. default value of
parameter works if a user didnt input a argument as value of parameter, despite
that if user inputed new value as a argument of parameter the python will take a
new value/argument.
NOTE : for further code, should always use default argument to handling/avoiding
error

def do_things(username, works = 'teacher'): # works parameter has a default va


print(f"{username} works as a {works}")

Catatan Python Learning 35


# calling function
do_things('admin') # works parameter didnt inputed so the argument will as 'teac
do_things('dajjal','desk collector') # works parameter has new arguemnt that will

return statemnet
is a statement to return a value, to exit of function, and to returning special value
as None ( false for integer ). return statement tidak bisa digunakan untuk
mengembalikan fungsi, ex print(full_name)

def get_users(first_name,last_name):
full_name = f"{first_name} {last_name}"
return full_name # return a value inside variable full_name

users = get_users('aji','ataitong')
print(users)

maybe this function haha doesnt usefull et all, but if we facing a large amount of
data this function will so much beneficely.

optional value
is a value define to parameter of function inside parathese to make a conditional
case. empty string will checked false, and none spesial value also false ussualy
beneficial for an integer.
example: we wanna build function that have 2 parameter as primarry and 1 as a
optional parameter.

def get_users(first_name, last_name, middle_name = ' '):


if middle_name: # checked true if the paramether filled
full_name = f"{first_name} {middle_name} {last_name}"
else:

Catatan Python Learning 36


full_name = f"{first_name} {last_name}"
return full_name

get_users('monkey','luffy','d') # output is with first condition

make sure to seeing or put the optional value to the end of parameter when
defining the function for understanding or match up a potitional argument
correctly.

returning a function as a dictionary value

a function can storing or returning a value from prossing data inside body of
function. not only a string, intetger, boolean value, it is also can return a complex
data structure like a dictionary and list.

def build_person(first_name, last_name):


person = {'first' : first_name, 'last' : last_name}
return person

extending an optional parameter to dictionary we can use a syntax been we were


learned before.
using a special value None to executed a conditional case

# define function
def build_person(first_name, last_name, age=None):
person = {'first' : first_name, 'last' : last_name}
if age:
person['age'] = age
return person

# calling function
print(build_person('babi','asu',30))

Catatan Python Learning 37


TIPS CREATING A FUNCTION

1. Define the function using the def keyword.


2. Use descriptive names for the function and parameters.
3. Keep the function focused on a single task.
4. Include a docstring to describe the function.
5. Handle edge cases and input validation.
6. Use the return statement to return values.
7. Use optional arguments with default values.
8. Avoid side effects.
9. Test your function to ensure it works correctly.

side effect meaning Functions should ideally avoid side effects, such as modifying
global variables or performing I/O operations. This makes them easier to test and
debug.

using a function to looping with while loops statement


it is a efisiens things to makes working like a robot

# define function
def greeting(f_name,l_name):
"""
returning as a fullname with convert method to capitilze
"""
full_name = f" {f_name} + {l_name} "
return full_name.title()

# calling fucntion with while loops


active = True
while active:
f_name = input(f"your first name : ")
if f_name == 'quit':

Catatan Python Learning 38


active = False
l_name = input(f"your last name : ")
if l_name == 'quit':
active = False
full_name = greeting(f_name,l_name)
print(f" Haloo, {full_name} "

passing a list in a function

if we try to act with a large of data, this case we use a list for example.
we can use a function parameter with all we learned before. string, number, bool,
and also data collection like a list, dictionary, tuple, or set

for example we will printing a username in a list

usernames = ['james','mikel','jack','kevin']

# define function
def greetings(list_datas):
for data in list_datas:
print(f" hallo, {data}!! ".title())

# calling function
greetings(usernames)

modifying a list in a function

is a act to manipulate a list, to create/append, to remove/pop. all happend in body


function that modifying a list will permanently.

Catatan Python Learning 39


example we will manipulated a list of chapter we has learned before and stored to
new list had been completed.

# deifne list of chapter


list_chaper = ['string', 'number','boolean','list','dictioanry','tuple','set']

# define list of completed chapter


completed_chapter = []

# define function
# we need 2 parameter, first is a chapter what we learned and second is a empty
# then we need a courier to move form list of chapter to completed list
def unlearned_chapters(list_chapter,completed_chapter)
# we use while loops to move a list
while list_chapter: # is true cause list_chapter is non-empty data
kurir = list_chapter.pop() # a method to remove a items then asign to
completed_chapter.append(kurir) # a method to receive a new items
print(f" sedang dipelajari : {kurir}") # a method to displaying progress

# deifne fucntion to show completed chapters


def show_completed_chapters(completed_chapter)
for chapter in completed_chapter:
print(f"{chapter}"

# calling function
unlearned_chapters(list_chapter,completed_chapter)
show_completed_chapters(completed_chapter)

this purpose is to make a program code simple and easier to be understood, and
also recomended to split a fucntion based on single task to avoid difficult
maintenacing. and remember that you can a call fucntion from another function.

preventing a funtion to modifying a list

Catatan Python Learning 40


sometimes we wanna saving a original list to backuping or in other circumastanse
we wanna call the original list. but when fucntion did modifying, a perma changed
been a consequencis.
so to handle that we can use split method to the original and we will got a copy of
original list.

def unlearned_chapters(list_chapter[:], completed_chapter)

# list_chapter[:] is new variable that collect of copying data form the original list_
# and list_chapter will not changed and ready to be call again

but to be realised, makes a copy of data will cause increasing a memory and time
of course.

Arbitrary arguments, defined by an asterisk (*) symbol followed by a parameter


in a function

An arbitrary argument is an optional parameter that allows a function to run even


without a value being passed.

It's a useful tool because it's versatile and reusable.


It works by passing arguments through an asterisk parameter, which stores
multiple arguments as a tuple.
A tuple is a data structure that groups related items together.
So *args, as it's commonly called, lets us store any number of arguments as a
tuple.
This works even when passing just a single argument.

def custom_hair(*models):
print(models)

Catatan Python Learning 41


custom_hair('babi haircut','highwaycut')
# output as a tupel
('babi haircut', 'highwaycut')

# define arbitery argument fucntion


def custom_hair(*models)
for model in models: # unpack a tupel items
print(model) # displaying items in model variable

# calling function
custom_hair('babi haircut','highwaycut')

# output printing a items in model variable


babi haircut
highwaycu

NOTE : Always using a function for each task!! for procesing data, gather user
input, and displaying data must be separated each other
mixing potitional argument and arbitery argument *args
we know that what we learned before, a potitional argument is a value passing
through from a parameter what we define in function, and potional argument is a
must be inputed as function parameter. then an arbitary arguemnt is tools for
collecting data no matter how many the items that saved to tuple. this combination
sometings use for the users input a what them wanna input doesnt based on our
program.

in example we will build a function that has 2 parameter for ordered pizza with
many toppings as arbitary argument and size parameter as potitional argument.

# define function
def orders_pizza(size,*toppings):
print(f"ordered pizza size {size} with topping of :")

Catatan Python Learning 42


for topping in toppings:
print(f"- {topping}")
# calling function
orders_pizza('small','cheese','corn','cokelat')

we should focused in calling function that has story that important to know:

after we define the function with 2 paramether, first is potitional argument as


mandatory parameter we called size, and second is arbitary argument as optional
parameter meaning if we didnt input a argumetn the code will still running.
as long as we remembered, arbitary argument in this case is *args that will create
a tuple stored data which is we will call the parameter and unpack the items to
display thems as ordered toppings
after define was done, we calling out the function with argument we want, to
being understood
string ‘small’ is roleplaying as potitional argument that mandatory argument and
might be inputed, then strings after ‘small’ were a toppings tuple collection data no
matter how many strings after ‘small’ that will be inputed as items in toppings
tuple that otherwise even void inputed.
so we can see a * args is use to create a strings data became tuple

the code above example of arbiter arguments changed to tuple data in a function
internally, we can also use tuple data externally, just using *args and folowed by
name of a tuple

topping = 'cheese','corn','cokelat'
orders_pizza('small',*topping)

# orders_pizza(*topping)

NOTE : if we avoid the potitional argument the output will became so funny, cause
the potitional argument has changed to first items of toppings tuple.
so we need a docstring to makes your fucntion expalined well and didnt wrong
inputing a argument

Catatan Python Learning 43


Positional parameters are parameters that are passed to a function in a specific o
Here are some tips for effectively using positional parameters in your functions:

1. Order Matters
The order in which positional parameters are defined in the function signature is
Ensure that the order makes logical sense and is intuitive for users of the function

2. Use Descriptive Names


Choose descriptive names for positional parameters to make the function's purp
This helps users understand what each parameter represents.

3. Limit the Number of Positional Parameters


Too many positional parameters can make a function call confusing and error-pro
If a function requires many parameters, consider using keyword arguments or a d

4. Provide Default Values


For optional parameters, provide default values.
This allows the function to be called with fewer arguments while still providing fle

5. Document Parameters
Clearly document each positional parameter in the function's docstring.
Include the parameter's name, type, and a brief description of its purpose.

6. *Use args for Variable-Length Arguments


If a function needs to accept an arbitrary number of positional arguments, use *a
This allows the function to handle a variable number of arguments.

Writing good docstrings is essential for creating readable and maintainable code
Here are some tips for writing effective docstrings:

1. Use Triple Quotes

Catatan Python Learning 44


Always use triple quotes (""") for docstrings,
even if the docstring fits on one line.
This is the convention in Python and allows for multi-line descriptions if needed.

2. Describe the Purpose


Start with a brief description of what the function, class, or module does.
This should be a concise summary.

3. Mention Parameters
List and describe each parameter, including its type and purpose.
For functions that accept *args and **kwargs, describe what these arguments re

4. Explain Return Values


Describe the return value, including its type and what it represents.
If the function does not return anything, you can mention that it returns None.

5. Include Examples
Provide examples of how to use the function or class.
This can be especially helpful for complex functions.

6. Mention Exceptions
If the function raises any exceptions,
list them and explain the conditions under which they are raised.

7. Follow PEP 257


Follow the conventions outlined in PEP 257,
which provides guidelines for writing docstrings in Python.

NOTE : POSITIONAL ARGUMENT / POSITIONAL PARAMETER IS A RULE


WHEREASE ARBITERY ARGUMENT IS SAME OTHER ARGUMENT BUT USE FOR
COLLECT A DATA AS TUPEL (*ARGS) OR DICTIONARY (** KWARGS / KEYWORD-
ARGUMENT)

Arbitrary arguments can also use double asterisks (**) to create kwargs

Catatan Python Learning 45


Kwargs (short for keyword arguments) are defined using the equals sign (=) in
function parameters
is an arbitrary argument that stores input arguments as dictionary data.
A function doesn't just process and display data—it can also directly
accommodate multiple arguments or values and store them as a dictionary.
In simpler terms, kwargs (like args) is a variable that collects multiple items and
processes them according to how we want to handle the values stored in the
kwargs variable.
it also to avoid a positional parameter more existed, its why args and kwargs
existed.
args and kwargs existed to simpler proses of collectiong data and prosesing data
in one ways

def make_person(**user_info):
print(f"{user_info}") # displaying user_info parameter as variable holding a d

# calling function and using kwargs


# keyword argument as keys of user info dictioanry and value of keyword argume
einstein = make_person(name='eintein',age=32,works='science',city='banyumas

# output as dictioanry that accomodate by user_info variable


{'name': 'eintein', 'age': 32, 'works': 'science', 'city': 'banyumas', 'teori': 'relativity

In this case, user_info is treated like a dictionary inside the function, where each
key corresponds to a keyword argument name, and the value corresponds to the
value passed to the argument. It's incredibly handy for writing flexible, reusable
code!
we can see the differnces betwenn with kwargs and without,

# define function without kwargs


def make_person(name,age,works,city,teori):
person = {'name' : name, 'age' : age, 'works' : works, 'city' : city, 'teori' : teori}
print(person)

Catatan Python Learning 46


einstein = make_person('einstein',34,'scientist','purwokerto','relativity')

# output
{'name': 'einstein', 'age': 34, 'works': 'scientist', 'city': 'purwokerto', 'teori': 'relati

without kwrags will make code more long and break the positional argument
cause too long and diddnt effective.

mixing a positional parameter and keyword parameter is same just like with args,
we need a positonal argument as a mandatory or we just wanna user to take a
additonal information as kwargs.
the example code is below

def make_car(manufacture, model_name,**cars_info):


cars_info['manufacture'] = manufacture
cars_info['model'] = model_name
return cars_info

my_car = make_car('nissan','grand livina',color='grey',tow_package=True)

print(my_car)

cars_info is a variable that hold the information as dictionary that ways return
statement below to itself. wherease manufacture and model_name are a
parameter that took positional paramter in one and second inside make_car
function.
inside body of function is a code to adding as maniputating ways to be part of
cars_info variable as keys-values pair.

storing a function in a modules

Catatan Python Learning 47


module is a file that consist of functions and use to make our programs more clear
so we just calling a function in the modules with import statement, there are
several ways to calling a function to our programs. import statement is a just
copying a module content to our programs in behind proses.

use import statement to import all entire modules content


first step we must have a module file with has .py as its extention and the module
can contains one or many function.
example we has a module named by [Link] and has a function to create car with
2 positional parameter and arbitrary parameter to add new information.

def make_car(manufacture, model_name,**cars_info):


cars_info['manufacture'] = manufacture
cars_info['model'] = model_name
return cars_info

to import entire content of modules [Link] we can simplify use import statement
followed by modules name. and we can free to use a function of the modules. to
using the function we can call a name of modules followed by name of function
and separated by dot.

import cars

my_car = cars.make_car('toyota','pajero',color='blue',tow_package=True)
print(my_car)

# ouput return cars_info as dictionary just like the function wanna do

use from and import statement to import specificly function of modules


we can also import a function of module that what we only needed

Catatan Python Learning 48


and to using a function we didnt necesary to including a modules separated with
dot. we can instanly call them.

from cars import make_car

my_car = make_car('toyota','pajero',color='blue',tow_package=True)
print(my_car)

# ouput will be same as code above

u can also import a few of function in one single line

from module_name import function1, function2, function3

use asterik * to import all function


this is not recomendation approach to accesing modules to our programs cause
this method can be crashing each other between function name by the module
and our program.

from cars import *

use alias statement aka as


usually use for make a code shorter if in the case the modules has a long name,
and use to preventing from crashed code or getting unexpecting output cause by
our program has a variable inside modules content.

import cars as cr

my_car = cr.make_car('toyota','pajero',color='blue',tow_package=True)
print(my_car)

Catatan Python Learning 49


alias statement can also use to a function inside the module

from cars import make_car as mc

my_car = mc('toyota','pajero',color='blue',tow_package=True)
print(my_car)

NOTE : just remembered in mind, if we import a function spesificly we just dont


need dot notatio

styling function

1. a function should have a descriptive name, mean that a function has benefit
what to do represent as the name.

2. descriptive name should use a lower case and underline.

3. every function should have a comment inside docstring to explain whatever in


the function, the beneficial, the parameter and the return value.

4. if a default value will be assign in the parameter, should be no spacing

def spacing(name='fajar besari') # this is no recomended

def no_spacing(name='fajarbesari') # this is recomended

5. PEP 8 recommendation to use only 79 character every lines, if already got


limit, the recomendation is to press ENTER and use new line and then pressing
tab twice for indentation.

def function_name(
parameter_0, parameter_1, parameter_2,
parameter_3, parameter_4, parameter_5):

Catatan Python Learning 50


function_body

6. If your program or module has more than one function, you can separate each
by two blank lines

7. All import statements should be written at the beginning of a le. The only
exception is if you use comments at the beginning of your le to describe the
overall program

classes
class MyClass:
def __init__(self, parameter):
# Modify the value of the parameter during initialization
[Link] = parameter * 2 # Example of modification

# Create an instance of the class


obj = MyClass(5)

# Access the modified value


print([Link]) # Output will be 10

is a statement in python to declare a class of object in basic way or this class will
be a structure of somethings, class usually has init method to initialyze a class
that the object was created.
we can create a class with atribut thats represent of own feature like name or age,
class also allow us to create own method to represent the behaviour like walk, run.
object created from class we call them as instance, and we can create many
instance from the class with different value of atribut, name of instance must be
uniqe from other been created or has occupied spotted in list or dictionary.
to define a class we use class statement followed by name of class in capital first
letter with no parentases, then you need to makes a comment to explain what is it

Catatan Python Learning 51


object with docstring rules. after that we must define init method and a atribut to
define what is your build kind of class. the parameter inside is self this parameter
is a must to be assign in each method inside of class. self itself represent of the
object/class. every atribut must be define to self parameter to working with dot
notation.
after all defined class we can create an instance from the class create particulary
object
example we build class of human with simple atribute that has name and works
and has the behavior as method like walk and run

# define class of human


class Human: # remember to use capital letter for first character of name
# then we define the atribut inside init method
def __init__(self,name,works):
# define a atribute to being value of argument
[Link] = name
[Link] = works
def walking(self):
print(f"now the {[Link]} just walking")
def running(self):
print(f"now the {[Link]} just running")

# create instance of human class


# assign a atribut as argument
einstein = Human('einstein','scientist')
print(f"his name is {[Link]}".title())
print(f"his works is {[Link]}".title())

# calling the method of class


[Link]()
[Link]()

# the output
His Name Is Einstein

Catatan Python Learning 52


His Works Is Scientist
now the einstein) just walking
now the einstein just running

we can infer that class is commonly object that has a feature and behaviour that
we built from the scratch, then a instance is a object that we created in particulary
with true atribute as argument
example using a kwargs ** as dictionary as addional data stored.

class User:
"""A simple object of users that have a first name and last name and several ad
def __init__(self, first_name, last_name, **user_info):
self.user_info = {} # Initialize user_info as a dictionary
self.user_info['first_name'] = first_name
self.user_info['last_name'] = last_name
self.user_info.update(user_info) # Add additional user info

def describe_user(self):
for user, info in self.user_info.items():
print(f"{user} : {info}".title())
return self.user_info

my_profil = User('fajar', 'besari', works='unemployed', age=27, motto='take it eas


my_profil.describe_user()

NOTE :

1. init method is built in method to initialize all attribute owned be object we


wanna create

2. all method in a class is connected to method init, or init method is a head of


others method. see point 4

3. All parameter inside of parethesse of init method are called instance attribute

Catatan Python Learning 53


4. The self parameter is essential for defining instance methods in a class. It
allows methods to access and modify the instance's attributes and other
methods, enabling object-oriented programming in Python. remember this

5. Function with *kwargs : You do not need to initialize *kwargs as a dictionary; it is


automatically done by Python.

6. Class with *kwargs : If you want to store the keyword arguments in an instance
attribute, you need to initialize that attribute as a dictionary and then update it
with the keyword arguments.

modifying a value of instance attribute


instance attribute is a value passed of parameter inside of init method of class
statement
or with no parameter either
there are 3 ways to change the value of attribute

1. doing directly changed to the attribute tied with instance separated by dot
then directly changed with equal operand then input the new value. example
we has a class car that has attribute as parameter there are make /
manufacture, model, years and additional attribute named oddometer with
zero value without defined as parameter

# create new instance from class car


new_car = Car('nissan','leaf',2010)

# assumed we already define self initialize within __init_ method


# modifying value attribute of oddometer which is the origin was 0 zero
new_car.oddometer = 10
print(f"this car was already drove {new_car.oddometer} miles")

2. doing create a method to passing through new value of attribute oddometer.


this approach must be written inside of class. example

Catatan Python Learning 54


# assumed we already initialize an instance attribute inside __init__ method
# create a method to modifying the value of attribute oddometer with new param
def update_oddometer(self,mileage):
[Link] = mileage

# calling a method to modifying value of attribute oddometer


update_oddometer(5)

# assumed we already has a method to read a oddometer


# calling a read_oddometer to display new value of attribute oddometer
read_oddometer()

3. doing create method to makes increment value of attribute oddometer.


increment means that the value of attribute oddometer will being add by initial
value that has been defined before

# assumed we already initialize an instance attribute inside __init__ method


# create a method to increment value as argmument from instace attribute of odd
def increment_oddometer(self,mileage)
[Link] += mileage
# we assumed initial oddometer value is 3 that has been initialize inside __in
print(f"this car already drove {[Link]} miles")

# create instance
her_car = Car('daihatsu','ayla',2012)

# calling out the method to increment a value


her_car.increment_oddometer(3)

# output
this car already drove 6 miles

Catatan Python Learning 55


example full code: has implementation of three approach how to modifying the
value of attribute oddometer and a conditional logic in 2nd approach using update
oddometer method to manage a circumstance if we assign a value less then initial
value, will there is a warning print method that says we cant roll back a
oddometer.

class Car:
""" a simple object ( body form ) of car with basic attribute a make/manufactur
then a method to describe and to passing mileage incremently
"""

def __init__(self, make, model, years):


[Link] = make
[Link] = model
[Link] = years
[Link] = 0 # a attribute without define a parameter should be write

def describe_car(self):
print(f"{[Link]} {[Link]} {[Link]}".title())

def oddometer_reading(self):
print(f"oddometer reading says it has {[Link]} miles")

def update_oddometer(self,mileage):
if mileage >= [Link]: # logic if we assign a number < initial number
[Link] = mileage
else:
print(f"You can't roll back an odometer!")

def increment_oddometer(self,mileages):
[Link] += mileages

my_car = Car('nissan', 'grand livina',2006)

Catatan Python Learning 56


my_car.describe_car()
print(f"beginning value of oddemeter : {my_car.oddometer}")

# change attribute value of oddometer directly


my_car.oddometer = 10
# reading oddometer method to call oddoemeter value is passed to new value as
my_car.oddometer_reading()

# replace attribute value of oddometer through a method with new parameter tha
my_car.update_oddometer(15)
my_car.oddometer_reading()

# increment attribute value of oddometer through a method with new parameter t


my_car.increment_oddometer(3)
my_car.oddometer_reading()

NOTE : You can use methods like this to control how users of your program
update values
such as an odometer reading, but anyone with access to the program can set the
odom
eter reading to any value by accessing the attribute directly. Effective security
takes
extreme attention to detail in addition to basic checks like those shown here

"inheritance" or "passing down" in English. It typically refers to the act of


transferring something—such as property, knowledge, traditions, or even traits—
from one generation to another.

inheritance in python is a technique to inherits a attribute or a methods or maybe


both of class ( parent / superclass ) to makes a new class inherited of itself.
to define inheritance in python is first we need a class that we wanna inherits must
be appeared in above directly of new class we wanna write or we must write code
of new class as child class below out a parent class. then use a paranthesee

Catatan Python Learning 57


contains class that we wanna inherited. we can call a class that inheriting is parent
class or superclass and class that inherited is child class or subclass.

# superclass as parent class


class Human:
""" body class """

# subclass as child class


class PrimalHuman(Human):
""" body class """

we can explain that PrimalHuman is new class that created will inherited entire
attribute and method inside Human class as parent class, and PrimalHuman as
child class.
and the rules of naming based on convention PEP 8 that if we wanna named of
new class with have two word we can using a camelcase upper or other name is
PascalCase like the example above.
after we define the child class, second we wanna inherits attribute and method
anythings existed in Human class as parent class, we use built in function named
super() followed by init method along with all parameters then separated by dot
notation that writen inside init method of child class with same parameter of
parent class (in further learning, we will add a attribute and method in child class)

class PrimalHuman(Human):
""" create a class to define new kind of human """
def __init__(name, height, weight):
super().__init__(name, height, weight)

# create new instance of primal human


beast = PrimalHuman('beast',210,80)

# assumed we already has descriptive method


[Link]()

Catatan Python Learning 58


define new attribute and behaviour / method to child class
it is why inheritance so powerfull cause you can makes your code more readeble
and structured. not only parent class inherits all attribute and method to the child
class, you can also makes attribute and method for spesific child class itself.
example we will adding a new attribute weapon, that mean we can understand
human has itself weapon too but we will adding only to primal human only. to
define new attriubte and method we just write the code like we used to and adding
a new parameter or without ( value directly assign ) also works too. we should
write below of super() function ( assumed allready writen inside snip code )

class PrimalHuman(Human):
--- snip ---
# adding new attribute
[Link] = 'bows'

# adding new method


def carry_weapon(self):
print(f"this kind of primal human wearing a {[Link]} as hunti
ng tool")

# calling attribute and method

print([Link])
beast.carry_weapon()

overriding or changing a method of parent class through child class


as python syntax works out, that we knew that python always execute a last code
if we has a same code. this overriding concepts follow what syntax python does
cause child class will always passing through (init method did) parent class that
has method itself when the child class called out, the same method will overwrite
by child class. and the purpose of this concept is to makes a specific method for
child class that parent itself is commonly form of somethings model. example we
has a method in parent class called hunt_kind that what kind of human hunting, in
the parent class hunting what is kind usually common like a girl but overide

Catatan Python Learning 59


concepts wanna child class has specific kind like in this case, a child class hasnt
hunting anymore but changed to production merhod for eat. for sure, this just to
makes the value is different to spesific wherease the method it same. we can use
a method of parent class through child class with spresific answer.

# define parent class


class Human:
--- snip ---
# initialize attribute with parameter hunt
[Link] = hunt
def hunt_kind(self):
print(f"this {[Link]} hunting a {[Link]}")

# define child class


class PrimalHuman(Human):
--- snip ---
# overring a method of parent class to new spesific value
def hunt_kind(self)
print(f"this {[Link]} isn't hunting anymore !!")

create an instance as attribute


instance is a variable that has a properties ( attributes and method ) from where
class its defined.
as we can simply that class is a body form of object and instance is entities of
class that have properties injected.

wherease the attributes are a one of two represent of the class object we create.
as we can simply that attributes is a part of body form from class we define.
aware that if we programming a object class in real world situation, it will makes a
lot of code and if we try to read, it will makes us so hard, then instance as attribute
use for separating a code become a bulk of class that explain as one object. this
we called as compositions.
if we have an object to be coded.

Catatan Python Learning 60


example, we has human object to be modelling, so human have a lot of
component like below

human_components = ["Head", "Neck", "Chest", "Arms", "Hands", "Abdome


n", "Legs", "Feet"]

if we create code for all component in one class called human, it will makes you
mentally breakdance and i swear will makes you won’t to write a codes anymore.
so separating a class as compositions of human will makes you life easier.
so we can create an instance as attribute. to define as simple as, we assign
attribute to an instance we want to inside of init method. but first we should create
class itself.

this compositions class will working to the child class


once you have create an instance of classes as attribute means to you can call
entire method on the class with define a attribute with self parameter followed by
name of method inside an class you were instancing became attribute and
separated by dot notation

# class a (has-a relationship) instance you wanna attributing initialize


class Arm:
def __init__(self,weapon='empty'):
[Link] = weapon

def describe_weapon(self):
print(f"this human has {[Link]} weapon")

# initialize a instance as attribute to class has a relationship


class Human:
def __init__(self,name,age,height,weight):
[Link] = name
[Link] = age
[Link] = height
[Link] = weight
# initialize class arm as attribute

Catatan Python Learning 61


[Link] = Arm()

# create an instance of human class


ordinary_human = Human('einstein',58,67,170)
# calling method arm through human class
ordinary_human.arm.describe_weapon()
# output
this human has empty weapon

the code story is we knew that inside of init method of human class we already
initialize an intance as attribute.
self is a initialize of instance to arm class that became [Link] is an instance and
Arm() is a attribute
it is truely so fucking confusing in the begining, you will understand further more
you have learn ahead. that to define an attribute is using self parameter, then the
proses of initialize that is an instance itself and equal to an attribute?? nah
matematical cases of comutatif??
NOTE : every method inside of class doing only one task should be

importing a class
to importing class is as same as importing a function
to import entire of file module, a spesific class, multiple class and importing
module to module
importing a class has purposes to makes your code not too long of word so we
just separated it to file called modules. a modules can contains multiple of class.
then we can import entire, spesific, and multiple.
import spesificly class
assumed we has a module named as [Link] that contains class human and
compositon class of it called arm class.
to import human class only we define with from statement followed by name of
modules then import statement followed by name of class you wanna use it.

Catatan Python Learning 62


from human import Human

# create instance
my_human = Human('albert',23,57,170)

import multiple class


to import multiple we just use comma as separated each class, in example we will
import class arm as composition of human class

from human import Human, Arm

# Create instance
my_human = Human('newton',26,55,180)

# use method presence in arm class


my_human.arm.describe_weapon()

# output
this human has empty weapon

in from statement is a module files name called [Link] with lower case and in
import statement is class name called Human with PascalCase rule

import entire module


has different way to define. we need dot notation that separating name modules
and a init method to create an instance

import human

my_human = [Link]('nize',24,67,189)

Catatan Python Learning 63


import all clases of modules
this is not reccomendation approach cause your code will crashing each other
to define this approach using * asterik symbol

from human import *

is a recommendation to use above approach than this way!

import a module into modules

is a way to makes your class in module to larging the code so we can just nesting
a modules then call all the class in the modules separated
Sometimes you’ll want to spread out your classes over several modules to keep
any one le from growing too large and avoid storing unrelated classes in the same
module
example we has human class that has is-a relationship called primalhuman as
child class now has self modules called primal_human.py

from human import Human


from primal_human import PrimalHuman

using alias
we has learned before in function chapter, alias is a way to makes your name of
class became what you want, a step to shorting a name of class.

from primal_human import PrimalHuman as PH

FINDING YOUR OWN WORKFLOW


Try doing everything in one file and moving your classes to separate modules
once every thing is working. If you like how modules and files interact, try storing
your classes in modules when you start a project.

Catatan Python Learning 64


PYTHON STANDART LIBRARY

we have learned a lot before in chapter a function and a class. as a programmers


we will a lot hustle with this stuff, a module stuff and doing import a class or
multiple class inside a modules to our project. in python, has already build module
to exactly has no beneficial for real problem solving but this kind of stuff a lot
having fun. example is a module name random. there is a lot class inside to play
with, such a randint class, a class to find random number between we were assign
2 number of argument and a choice class, a class to find a randomly string we
were provide in tuple or list data collector.
example using module random with randint class

from random import randint


import time
active = True

while active:
y = randint(1,10)
print(y)
[Link](2)
if y == 5:
active = False

example using module random with choice class

from random import choice


import time
# List of Latin names
latin_names = [
"Homo sapiens", # Modern human
"Panthera leo", # Lion
"Canis lupus", # Gray wolf
"Felis catus", # Domestic cat
"Gallus gallus", # Chicken

Catatan Python Learning 65


"Equus caballus", # Horse
"Sus scrofa", # Wild boar
"Bos taurus", # Domestic cattle
"Oryctolagus cuniculus", # European rabbit
"Apis mellifera" # Western honey bee
]
# Tuple of French things
french_things = (
"Eiffel Tower", # Iconic landmark
"Croissant", # Famous pastry
"Louvre Museum", # Renowned art museum
"Château de Versailles", # Historical palace
"Baguette", # Traditional bread
"Mont Saint-Michel", # Stunning island commune
"Champagne", # Celebrated sparkling wine
"Arc de Triomphe", # Monument
"Notre-Dame Cathedral", # Gothic masterpiece
"French Riviera" # Glamorous Mediterranean coastline
)
active = True
while active:
first = choice(latin_names)
print(first)
second = choice(french_things)
print(second)
[Link](2)
if first == 'Gallus gallus' or second == 'Croissant':
active = False
else:
print(f"\none of them founded".upper())

One excellent resource for exploring the Python standard library is a site called
Python Module of the Week. Go to [Link] and look at the table of
contents. Find a module that looks
interesting to you and read about it, perhaps starting with the random module.

Catatan Python Learning 66


there are a lot module externally were writeen by someone. as long as you have
programming, you will dealing with them stuff.

example implement random module to build dice app simple using randint class

from random import randint

class Dice:
def __init__(self,sides=6):
[Link] = sides

def roll_dice(self):
number = randint(1,[Link])
return number

role_dice = Dice()
print("Rolling a 6-sided die 10 times:")
for i in range(1,10):
print(role_dice.roll_dice())

role_dice = Dice(sides=10)
print("\nRolling a 10-sided die 10 times:")
for i in range(1,10):
print(role_dice.roll_dice())

role_dice = Dice(sides=20)
print("\nRolling a 20-sided die 10 times:")
for i in range(1,10):
print(role_dice.roll_dice())

NOTE : it is a recommendation to use return statement to return a values to being


nice programs

example implement of random module to build a lottery simple app

Catatan Python Learning 67


class Lottery:
def __init__(self,*args):
[Link] = args

def spin_lottery(self):
active = True
numbers_and_letters = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10,'A', 'B', 'C', 'D', 'E']
putaran = 0
while active:
putaran += 1
for i in range(0,4):
code1 = choice(numbers_and_letters)
code2 = choice(numbers_and_letters)
code3 = choice(numbers_and_letters)
code4 = choice(numbers_and_letters)
y = (code1,code2,code3,code4)
print(y)
#if [Link][0] == code1 and [Link][1] == code2 and [Link][2] ==
code3 and [Link][3] == code4:
if [Link] == y:
active = False
else:
print(f"\nselamat ticket nomer {[Link]} menang setelah putaran ke-
{putaran}".upper())

my_ticket = Lottery('B','B','B','B')
my_ticket.spin_lottery()

styling classes

1. a class should be writte with CamelCase upper rules or PascalCase

2. an instance and modules name should be writen with snake_case which is a


lowercase each word concate with underscore

Catatan Python Learning 68


3. a class should be write a docstring to explain what is the class do

4. a module should be write a docstring to explain a program you built

5. one blank line to separating between a method

6. 2 blank line to separating between a class inside a modules

7. one blank line to separating between import statement and entire code inside
a modules

8. attribute is a argument initialized by self parameter

9. instance is a creating object that has attribute assign from initialized by body
form / class

chapter 10 file handling and exceptions


is a excelent chapter to know that we can build a application based on user
dataset. it is usefully good to analysis or just only displaying a data. we can do
anything in this tecnique such a read file, write even rewrite and manipulation
things also. and trying to avoid an error throught exceptions.
in this chapter we will practice what we learned before, real practicing a basic
python and how we can solve a problems.
for further understanding programming, we should know that a programs is a
several act to assigns a value, this moment, value doesnt only a number, string,
bool, or similar to type data but also a function, method or class or combination of
them. the one impoertant is a logic programs, we should know every step in
programming is neccesary. assumed the python is dumb, he want the detail of
programs we take care with. example we will raise in below
we will use a python library call pathlib to makes a file can be accesed, and read
the file then displaying to the terminal.
first we will create a file and consist of pi number with 10 digit a row and 3 line as
colums, after created in our main programs we need to define a library/module
with import statement to access the method of reading file. after that we should a
has variable to hold a path of the file, to makes python know where is directory of

Catatan Python Learning 69


file. there are two ways to define a path with pathlib library, first, if your main
programs has same directory with the phi [Link] file you could define as
relative path only use ‘phi_digits.txt’ as value of path variable. second, if you
wanna separated a main programs and your phi_digits.txt you should use absolute
path with long strings caused it will pathing the certain directory and use
backslash as pathway. then we need to storing a content of file to computer
memory with read_text() method and assign to new variable named contents. after
already stored, you can do anything what you want such a formatting string,
replace, rewrite and more thorughut library of pathlib has such a methods. in this
circumstance, a stored numbers is a string type data, if u wanna works with
numerical things u should convert it to numbers uses int() method. and in this
lesson, we simple to display the content of file with print() method.

# contents of file phi_digits.xt

3.1415926535
8979323846
2643383279
whitespace here
whitespace here

# define pathlib library


from pathlib import Path

# define path
path = Path('phi_digits.txt') # relative path
# path = Path('C:\phi_digits.txt') # absoule path

# define content file


contents = path.read_text()

# display content
print(contents)

Catatan Python Learning 70


manipulating a contents of file
When you’re working with a file, you’ll often want to examine each line of the file.
You might be looking for certain information in the file, you might want to modify
the text in the file in some way.

avoid a whitespace below of contents with rsplit() method


the output in the terminal should be same as the file, if maybe has a blank line as
whitespace on below of the digits we can use rsplit() method to makes the output
similar to file contents

contents = path.read_text()
# handling for avoid whitespace of contents
contents = [Link]()
print(contents)

# ouput
3.1415926535
8979323846
2643383279

or we can direclty merge method in only named as chaining method

contents = path.read_text().rsplit()

but always understand the first method writeen, the first it will executed

breaking each lines of contents using splitline() method


You can use the splitlines() method to turn a long string into a set of lines, and
then use a for loop to examine each line from a fille and storing a list type data.

# define library
from pathlib import Path
# define path with absolute path
jalur = Path('C:/Users/sustainability/Desktop/Python/python/pi_digits.txt')
# storing contents to computer memory

Catatan Python Learning 71


isi = jalur.read_text().rstrip()
# break each line to store list data
lines = [Link]()
# display each line
for line in lines:
print(line)
# output
3.1415926535 8979323846 2643383279

NOTE :

1. to more understanding of programming, we should know that every we assign


a value to variable it has means that it has been happened except if
conditional that has required circumstance spesificly to be happend. you
should has a vision to know what the output of codes what you has written.

2. path class in pathlib is a class that has an argument file directory, it is to be


more define / understood well, should be the varibale name is ‘file’ doesnt
‘jalur’ cause it is refers to the file itself.

makes a each line spotted in one row


it is a way to spotting a phi numbers displayed in terminal be one rows string. this
will use lstrip() method to erased any whitespace presence in each line. this is
neccesary to understanding how many letters/numbers consists inside txt file.
further more you expect more functionality about this way

--- snip ---


lines = [Link]()
# initiate new variable to hold a file content in computer memory
pi_string = ''
for line in lines:
pi_string += [Link]()

print(pi_string)
# output
3.141592653589793238462643383279

Catatan Python Learning 72


take care of large ammount data
example above is a way to handle with 3 lines of data, what if we hustled a large
ammount of data, whetere we must to display all the datas? it is nesecary to
understand, python will not forbide how many data you has loaded, througut you
computer memory can handle all the data, the python doesnt bottered. so it is
yours choices, wheter we want to display all datas or just a few of those.
in this example we will try to accesing a few of data with split annotation [:] we
has learned.
first we need has a file consist of million digits of phi numbers, the code is as
same as we wrote above but has additional notation in print() method to cut of a
digits we wanna display it.

--- snip ---


# displaying a first digits of million digits phi
print(pi_string[:50]
# displaying a count of digits to evaluate we were programed corectly
print(len(pi_string[:50]))

looking for a spesific data within


sometime we will do to looking for a spesific data inside of file provide. so first to
know is, before we can manipulate a file contents, we must to move the file
contents to memory this mean to storing a file content to variable as value.
in example above, we already storing to variable pi_string as string value. and
simply experientaly to practice what this subchapter do, we just to find a numbers
that matching with our birthday number, if we find a matching numbers as birthday
numbers will print ‘existed’ otherwase, in this situation we just need an if in
statement.

--- snip ---


pi_string = ''
for line in lines:
pi_string += line

Catatan Python Learning 73


birthday_numbers = input(f'your birthday number please (mmddyy) : ')
if birthday_numbers in pi_string:
print(f"existed")
else:
print(f"doesnt existed")

Once you’ve read from a file, you can analyze its contents in just about any way
you can imagine.

replace specific string within


for what is purposes we were looking for a spesific data within a file? just wanna
to display it? sometimes we wanna replace it wont we? so to replace any spesific
string with in file we can use replace method to do.
in this example we use new file called learning_python.txt that contains of few
lines text written. and we challenge to replace a ‘python’ word to another name
kind of program language

# contents of learning_python.txt
in python i can write syntax python
in python i can define all tipe data such a number,string,boolean
in python i can create a function
in python i can create a method inside class
in python i can create an object with class
in python i can use standart library like a random, pathlib

# define a program to replace 'python' word


from pathlib import Path as Dir

file = Dir('C:/Users/sustainability/Desktop/Python/python/learning_python.tx
t')
contents = file.read_text().splitline()
for content in contents:
content = [Link]('python','javascript').title()
print(content)

Catatan Python Learning 74


# output
In Javascript I Can Write Syntax Javascript
In Javascript I Can Define All Tipe Data Such A Number,String,Boolean
In Javascript I Can Create A Function
In Javascript I Can Create A Method Inside Class
In Javascript I Can Create An Object With Class
In Javascript I Can Use Standart Library Like A Random, Pathlib

# alternative code with avoiding temporary variable in loops code


from pathlib import Path as dir

file = dir('C:/Users/sustainability/Desktop/Python/python/learning_python.txt')
contents = file.read_text()
for line in [Link]():
print([Link]('python','javascript'))

NOTE : to be considered to define your variable name, should be has descriptive


name!!!

write a strings to file txt


programming isnt about displaying things but we also doing create and write. we
know those things as CRUD operation. in this subchapter we will learn how to
create a file and write a strings inside of using library name pathlib also Path
class.
first we do exactly define the library initialize trough import statement then
implementing while loops to looping input method then storing it become a file
that contains everywords the user typing. we also use if conditional as break
statement. the end will displaying what the users inputed.
in this case, we refers to a few method such a write_text and read_text.
write_text method forcing python to create a file if the file that we wanna take
care doesnt existed and if has existed python will overwrite the contents of file to
new strings that we inject pratically

Catatan Python Learning 75


# define the class specificly
from pathlib import Path

# define variable to accessing the file


file = Path('C:/Users/sustainability/Desktop/Python/python/[Link]')

active = True
# variable holding strings from user inputed
guests_books = ''
while active:
guest_name = input(f"your name please : ")
if guest_name != 'q':
# creating a strings in colums based on user input
guests_books += f"{guest_name}\n"
else:
active = False
# write user inputed to file
file.write_text(guests_books)
# accesing contents of file
contents = file.read_text()
# displaying a file contents's
print(contents)

NOTE : assign a value to a variable is depends on what your code wanna do

Here are the different ways to access files in Python:

1. open() : Traditional and flexible.

2. os Module: Useful for checking file existence and working with paths.

3. shutil Module: High-level file operations like copying.

4. pandas : Ideal for structured/tabular data.

5. csv Module: Lightweight for CSV files.

Catatan Python Learning 76


6. io Module: For in-memory file-like objects.

7. glob Module: For pattern-based file matching.

8. pathlib: Modern, object-oriented, and versatile.

Choose the method that best fits your use case! For modern Python
code, pathlib is often the preferred choice due to its simplicity and power.

handling exceptions
exceptions are an object built in that raised caused by an error. so if the
exceptions raise, the code u written was going to crashed and doesnt running.
crashed program you were writen should be write into try-except block to
handling the error and the programs still running, at least doesnt crashed just only
displaying a message of error and understanding what we encounter to got
running properly soon. try-excepts blocks is like another statements in python, if
true i mean if try block doesnt error existed so the programs is going to the end,
and if try block find an error then an exceptions object raised so excepts block
handling the exceptions, in the way changing an exceptions object to become you
wanna display in except block overrding the programs crashed, it will still running.

handling divide by zero


the example is an exception object caused by a number divide with zero number
called ZeroDivisionError

print(3/0)

we know that in pyhton if we divide a number with zero, will arised an exception
and crashing the programs, and poped up a dialog below.

Exception has occurred: ZeroDivisionError


division by zero
File "C:\Users\sustainability\Desktop\Python\python\[Link]", line 2919, in <
module>
print(3/0)

Catatan Python Learning 77


~^~
ZeroDivisionError: division by zero

to handling the exception of ZeroDivisionError we using a try-except block to


forwarding a popped crashed dialog to be more friendly and the program still
running. to define try-except block just like another statement syntax. try followed
by collon, then the block as you think will causing an error then new of except
block followed by an exception object then collon as to end the statement after
that consist of except block should be a code to inform what try code block was
found an error. dont forget an indentations!

try:
print(3/0)
except ZeroDivisionError:
print(f"you cannot fill a zero as divider!!".title())

# output
You Cannot Fill A Zero As Divider!!

an example handling ZeroDivisionError that has user input

print(f"calculate divition".upper())
print(f"type 'q' to quit".title())

active = True
while active:
number_1 = input(f"input first number : ")
if number_1 == 'q':
active = False
break
number_2 = input(f"input second number : ")
if number_2 == 'q':
active = False

Catatan Python Learning 78


break
try:
hasil = int(number_1) / int(number_2)
print(int(hasil))
except ZeroDivisionError:
print(f"you cannot fill a zero as divider!!".title())

use else statement in try-except block


try-except block is a statement that has boolean mechanical like loops stuff, try
block is a presence of a exceptions object might arise, then if occurs the issue of
rising exceptions the except block will trying to send a friendly message that need
going to fixed depends on a kind of exceptions. in the example above,
ZeroDivisionError exceptions commonly occurs caused by user. however, if there
is no exceptions arise? else statement existed to executed if the try-except block
running normally, i mean try block doesn’t rise an exceptions object, so the
program is going to else statement, everything inside it will executed. we will use a
simple example how else statement works out, just send a message that the
program runs normally and we use an exception object called FilleNotFoundError
that usually come in cause fille we work to has different directory or maybe
doesn’t existed et all. in further more we learned, we will got a problematic issues
then else statement will handle it that our program became robust and user
friendly.

from pathlib import Path from pathlib import Path

file = Path('[Link]') # set up try-except to handle exce


contents = file.read_text() ptions occur
print(contents) try:
file = Path('[Link]')
# the program doesnt set up a try- contents = file.read_text()
except handling exceptions except FileNotFoundError:
print("file doesn't existed")

Catatan Python Learning 79


# the program is going to crashed else:
soon as we running print('file existed')

Exception has occurred: FileNotFoundError


[Errno 2] No such file or directory: '[Link]'
File "C:\Users\sustainability\Desktop\Python\python\[Link]", line 3012, in <
module>
contents = file.read_text()
^^^^^^^^^^^^^^^^
FileNotFoundError: [Errno 2] No such file or directory: '[Link]'

the code story is try block looking for an exceptions object inside its block code.
there are two lines block as presence. file variable and contents, file variable is
just a variable to locate the file wherease contents variable is a variable to read a
file content then hold to computer memorise and this might usually rising an
exceptions called FileNotFoundError. and in this circumstance we doesn’t need to
put file variable inside of try block. then if a try block has been checking an
exceptions that rising an error so except block will excecuted, and if doesnt an
error, else statement will excecuted.
NOTE :

1. we remember learn before to makes certain directory or path of file we can


just using absolute path.

2. makes to clear cause the methods has a litle bit same named betwen split
method and strip method. split method use to converting a sentence become
words that whitespace as delimeter. strip method beneficial for removing a
whitespace existed on the left and right of the sentences, also lstrip to remove
whitespace on lefted sentences, and rstrip to remove whitespace on right
sentences.

from pathlib import Path


file = Path('War and Peace by graf Leo [Link]')
# set up try-except to handle exceptions occur
try:

Catatan Python Learning 80


contents = file.read_text(encoding='utf-8')
except FileNotFoundError:
print('file not found')
else:
# need a vaiable to hold words
words = [Link]()
# use len method to counting the words inside list type data words
print(f"the books has {len(words)} words")

the example above, we little bit makes advanced things in else statement. we
handle an exceptions of FileNotFoundError if file we works to doesnt existed and if
existed we will print a word count of contents file. using split method to convert txt
file become list data of words that whitespace as delimiter. then we use len
method to count all element inside of variabale has converted by split method.
encoding argument is writen caused we using a txt file from external resources, if
we write the txt file ourself, we dont need an encoding argument.

works with multiple files


we know that programming is not only about an problem solve but it is more than
it, should be regarding the python zen principle of ‘simple is better than complex’
means we shall program an apllication simple as we could, represent an
effectiveness and effisienness.
the example above, we just facing with only one file. in the facts, we will rumbling
a large amount of files cases for we are an industrial computer employe. sure this
will anoyying if we doing something for repeating what we doing in the last we
living.
we will trying to read a lot of file then the output is like the example above. we
need a function that has path library to accessing our files, then looping mechanic
to easier and making fast our working.
we will write a function called count_words in different directory, then call it the we
py file we usually works to.

# file name count_words.py


# creating a function count_words()

Catatan Python Learning 81


from pathlib import Path

# the paramater as path of files existed


def count_words(path):
file = Path(path)
# use try-except to handling exception rise
try:
# use encoding argument if the files got from external resources like g
utterberg
contents = file.read_text(encoding='utf-8')
except FileNotFoundError:
print(f"the file {path} doesn't existed")
return
# split method convert a txt file become a list of words
words = [Link]()
print(f"the file {path} has about {len(words)} words")

return statement existed is a way should be writeen if we doesnt use else


statement. this ways only used if the program simple code. if dont we should
using else statement.
then we call the function in our python file to see the program running has the
output we expected

# we import the function


from count_words import count_words as cw

# we already has a book txt files and use relative path as directory location
# storing a books to the list

paths = ['[Link]','[Link]','[Link]']

for path in paths:


cw(path)

Catatan Python Learning 82


# the output
the [Link] has about 32583 words
file [Link] doesn't existed
the [Link] has about 25058 words

in this case we have advantageous if we use try-except to handling an error. if the


file doesnt existed that rising an exceptions might be crashed the program running
out, in this case the program continue analysize the txt book files until the last of
list. and the important, the programs being friendly cause users couldnt saw a
traceback error in front that could makes users annoy and abbandon our program.

failing silently
it is means that as we as a human that has a big ideas and we doesnt need to
inform if it were not gonna happend. it is has an example that the users wanna
information they dont to see, so we dont need to inform the whole programs
proses too.
the same this subchapter, means is a exceptions has raised, we dont need to
informs the users of the errors, we just informs what the users wanna see. pass
statement will take on this duty, when you write it inside of except statement it will
passing to next code while the programs still trying to catch exceptions, and the
programs runs normally uncrashed

from pathlib import Path

file = Path('[Link]')
try:
contents = file.read_text(encoding='utf-8')
except FileNotFoundError:
pass
else:
print('file existed')

Catatan Python Learning 83


the example above has a story that inside except block will do nothing caused by
pass statement and passing continued to else block. in this case, the txt file is
doesnt existed means try block will catch an exception filenotfounderror that
forwarded to except to handle it, but inside except block there is nothing output to
users thats why we placeholding pass statement cause a statement shouldnt
empty. then in the end the output will empty or there isnt output in the terminal.
which is else statement executed if only the file is existed.

deciding which errors to report


such a we talking about before this chapter, necesary to know it that informing a
error that users wont to see it will decreased our program usability despite it cross
line of pyton zen principles. python has structured methods to control how much
we want to inform an errors to users, it is depends on your decide how many, but
making sure the errors are informed being a insight to users for future fix when
users use our program. as well-writer programer, the errors sometimes that raised
an exceptions object commonly caused by a program trying to interact with users
through user input, or working with a large amount datas that maybe file not found
or existed in other directory and maybe relationship with internet connections.
the example, we trying to write a text analyses such a an example in previous
chapter. maybe we want to makes an users comfort so we write a program with
path usage an absolute path, in other situations that will be difficultave yourself to
write the program with that using absolute path, overriding comforting the users,
you shall just control the users and makes a program with relative path then
control the users to put the txt files and the program in same directory, that will be
more easier to us, then the try-except block is going to be a guidance for users.

additional : count() method to looking for a numbers of word in a strings

from pathlib import Path

file = Path('[Link]')

try:

Catatan Python Learning 84


# converting a txt contents file to string that holded by contents variable
contents = file.read_text(encoding='utf-8')
except FileNotFoundError:
pass
else:
# lower method converting a strings first before counting
words = [Link]().count('the ')
print(words)

in this example case, we focused on words variable that holding a words from
converting a variable contents has been stored to computer memory became a
strings data. then lower method has duty to formatting a strings to lower case
before holded by words variable, then count method is going to counting a words
we wanna counted. for the example above, we are trying to catch ‘the’ words how
many existed in txt file provided, and the value of the output is an approximation
cause the count method counting all ‘the’ words not only but in ‘there’ or ‘brother’,
i means all words that consist of ‘the’ word will counted, so the tips is we need a
whitespace in the end of ‘the’ words came to ‘the ‘, in this approach we will only
counting ‘the’ word how many existed inside txt file.

json modules
has long named as javascript object notation is a file extention that hold data
structure like strings, numbers, list, also dictionary. commonly use to javascript in
the past but now already usage for almost programming languages such a python,
json provides a usefull and portable files. to define json modules you just write
import json to your programs file.

json dumps and json loads method


in this subchapter we will use the methods to write a list to json file and load it to
the terminal.
considered we know we have pathlib to create a txt file, here we going to use
pathlib to locate json file and parsing to memory computer then write to it use

Catatan Python Learning 85


write_text method then parsed by and read the json file through read_text method
to passing the contents file to json loads method displaying to the terminal.

# initiate the modules


from pathlib import Path
import json

# create a list numbers data to storing it to [Link]


numbers = [1,5,7,4,6,8,4,3,9]

# locate json file assign to file variable


file = Path('[Link]')
# we need a varible to represent content of json file even didn't created yet
contents = [Link](numbers)
# then we write a contents to json file
file.write_text(contents)

this the first program to assign a data to json file through [Link] method and
write_text method. don’t forget to use write_text() method you need a variable that
assigned by path of file, in this program will not have output in the terminal.
the second program we will built is how to read the json file using pathlib modules
and json modules, usually we were practiced in previous, we just need a read_text
method to read txt file, but in this case we need to parsing it using [Link]()
method then you can see the contents of json file as terminal output. the output is
the same as we assigned a list of numbers ( the case example )

--- snip ---


file = Path('[Link]')

# create a variable to assign json content to computer memory as unparsed d


ata
contents = file.read_text()
# create a variable to assign json content to computer memory as parsed data
content = [Link](contents)

Catatan Python Learning 86


# displaying json file contents been parsed
print(content)

# the output
[1, 5, 7, 4, 6, 8, 4, 3, 9]

using path object called exists() method


in facts, there are a lots a method that provides by path object, one of them is this
exists() method.
exists() method same such a try-except block to handling file to catch
FileNotFound exception object. if the file is existed means try block successfuly
executed which is has true value as return, and if doesn’t will return false value
which is structured by else statement.

from pathlib import Path


import json

file = Path('[Link]')

if [Link]():
contents = file.read_text()
usernames = [Link](contents)
print(f"welcome back, {usernames}")
else:
usernames = input("what is your name? ")
contents = [Link](usernames)
file.write_text(contents)
print(f"we'll remember you, {usernames}!")

the code stories are, we jus combine 2 program has written before with advance
case using if statement, first we assign a variable name file as location of file. then
we use if statement to checking a file in the directory we had putted and we use a

Catatan Python Learning 87


exist() method which is if the value is true means file is existed then the block
caused by true value will executed, considered consist of a variable to hold
unparsed ( contents variable ) and parsed data ( usernames variable ) ( this is a
string inside of file [Link] ) and printed a message greetings particulary
to user. if the value is false means file doesnt existed inside else statement will
executed that presence of username variable that has input method to catch and
storing it (a string) to computer memory, contents variable that hold parsed data
by decode [Link]() method and a initialize a write_text() method data to json
file then displaying a message that like we will remember you, sir!.
the flowchart is :
when reading file

1. read file through path object using read_text() method

2. after read the file considered storing content of file to computer memories
(ram)

3. then json modules works here to decode the content of file from json
formatted to unparsed data happened inside computer memories using json
loads() method

4. after decode you can display or manipulated those data

when write a content of json file

1. prepare a data in computer memories this case we need a variable to hold the
data

2. then you need to coded the data to json formatted by using json dumps()
method

3. after successfully coded to formatted json format, u can write it to json file
using write_text() method

4. this whole proses is fact still saved in computer memories (ram) so u can call
the data directly without reading steps.

NOTE : the example just a single data type strings, this moment could be works to
any data type that converted to JSON formatting.

Catatan Python Learning 88


refactoring an code
is a tecnique to arrange the code big and longer to pieces of code through several
functions regardless of how many tasks the program in presences.
so the tasks is somethings what we wanna do inside the programs, usually tasks
mean how the code to read, write, create, delete, display, and more. the common
sign is always has a function or method that we counting as one task.
refactoring needs to be did cause expect of easy to maintenance and larging the
codes easier.
example we wanna do is reafactoring the code in previous way we written, that a
username prompted if exists we will say hello back message and display whole
profile, if doesnt we going to create new profil using a prompt function then stored
it json file.
first we create a code doesnt refactoring, then we analysize how many tasks we
wanna seperate to change become several function as refactor touching.

from pathlib import Path


import json

file = Path('[Link]')

if [Link]():
contents = file.read_text()
dict = [Link](contents)
username = input('your username : ')
if username == dict['username']:
print(f"welcome back commander, {username}")
print(f"\ndata anda sebagai berikut :")
for k,v in [Link]():
print(f"{k} : {v}")
else:
contents = {}
nama = input('masukan username : ')

Catatan Python Learning 89


hobi = input('masukan hobi : ')
fav_place = input('masukan favorite place : ')
contents['username'] = nama
contents['hobi'] = hobi
contents['fav_place'] = fav_place
dict = [Link](contents)
file.write_text(dict)
print('terimakasih data anda sudah tersimpan')

refactoring means you need to know the flowchart of your program written, the
story the code you program is needed to know, that’s why we supposed to write a
comments every single code block to represent the flowchart does and it gonna
be a docstring after touched by refactor.
the code story above is : first we checking the file exist with exists method which
have boolean value, if true mean file existed then the block executed otherwise
else block is execute. exists method in here as an exception try-except catcher, to
catch filenotfounderror. which is the program has 2 tasks, first, to get contents
and display it, second, to get new contents cause the contents doesnt have any
contents. then we need 1 task more to running or combine thoose tasks.

from pathlib import Path


import json

def get_profil(file):
if [Link]():
contents = file.read_text()
dict = [Link](contents)
check_username = input('your username : ')
username = dict['username']
print(f"welcome back commander, {dict['username']}")
if check_username == username:
print(f"data anda sebagai berikut: ")
for k,v in [Link]():
print(f"{k} : {v}")

Catatan Python Learning 90


return username
else:
print(f"{check_username} tersebut belum terdaftar")
print(f"isi pertanyaan berikut untuk membuat profil anda")
return None
else:
return None

def get_new_profil(file):
contents = {}
nama = input('username :')
hobi = input('hobi : ')
fav_place = input('favorite place : ')
contents['username'] = nama
contents['hobi'] = hobi
contents['fav_place'] = fav_place
dict = [Link](contents)
file.write_text(dict)
print(f"terimakasih profil anda sudah dibuat")

def greets():
file = Path('[Link]')
username = get_profil(file)
if username:
pass
else:
get_new_profil(file)

greets()

testing a function and class

Catatan Python Learning 91


testing code has several meaning including automate, edge cases, and thinking
visionary.
testing is an automate means that as programmer we will always checking an
output to have less of errors, it is going to exhausted when checking it manually,
especially when we works with complex program we have written, so testing is
give us an extra time to handle other problems simply can saving our time in
second.
testing is preventing edge cases means that we are always expected the output of
programs we written as software engineer went to robust from unexpected bugs
or any errors. edge cases means that we facing an unexpected input from users
or dataset we works to. this can be understanding for preventing human error also
dataset error.
testing is thinking visionary means as software developer we need to know what
will be the problems to our programs, including human errors, and missing
requirement of program we build.

define testing modules pytest


pystest is one of several module that provide us to running test through terminal,
pytest is an external module that we have to install it to our IDE, so that we can
testing our function and class.
to install pytest, we need to write and run code ‘python -m install pytest’ in
terminal line.
to define a testing code we need a function or classes to be tested and a test
function file that name begin of test_ and consist of a function that has descriptive
name also started with test_ name.
a test function is a function to test a code we wrote before to has expected output
as well we want to. contents of the function are a implementation of the code we
wrote then end up with assert statement as same as return statement but this
assert returning a conditional code that represent of comparison the output
supposed to be has equality with the output we expect to.
example function code we wanna test : this example is a simple code that has
string formatted return with capitalize each words, to get this we need a 2
positional argumen f_name as first name and l_name as last name.

Catatan Python Learning 92


# filename [Link]
active = True
while active:
f_name = input('nama pertamamu : ')
l_name = input('nama keduamu : ')
if f_name == 'q':
active = False
break
if l_name == 'q':
active = False
break
formatted_name = get_formatted_name(f_name,l_name)
print(formatted_name)

# filename formatted_name.py
def get_formatted_name(f_name,l_name):
formatted_name = f"{f_name} {l_name}"
return formatted_name.title()

unit test and test case


unit test is a single test doing trough a function we wrote, wherease test cast is
several test of unit test.

passing test
means that the function we wrote has an expected output and has good
implementation to catch unexpected bugs then the code we wrote became robust.
this example we trying to testing a function inside formatted_name.py file, the first
we do should importing the function

from formatted_name import get_formatted_name

# creating a test function

Catatan Python Learning 93


def test_first_last_name()
formatted_name = get_formatted_name('albert','einstein')
assert formatted_name == 'Albert Einstein'

when the test file created, we just to run the file which supposed to be has the
same directory with the function code we wanna tested. after that we run in
terminal.

PS C:\Users\sustainability\Desktop\Python> pytest
=================================================== test s
ession starts ==============================================
======
platform win32 -- Python 3.12.7, pytest-8.3.5, pluggy-1.5.0
rootdir: C:\Users\sustainability\Desktop\Python
plugins: anyio-4.6.2
collected 2 items

python\test_first_last_name.py ..
[100%]

==================================================== 2 pa
ssed in 0.07s =================

the output on that testing if passed test consists of a the version python, pytest
modules and another requirement of our codes, the directory we running the test
code, collected word means how many we have a unit test that represent by dot
aside ‘python\test_first_last_name.py’ also dots notation means passed test, if a
unit test failed dots notation changed to ‘f’ letter meaning of failure.
percentage indicates monitoring tools means we can see the process throughout
the testing running. and has a times how much testing process took our code.

failing test
if we passed the test maybe we will not fixing the code, and we can be confident
and ready to deploy it. how about we facing failing test? what wanna do? example
error is caused by the users the middle name we should provide to the users? for

Catatan Python Learning 94


sure the testing code will pop failure test so what we should do? of course we will
learn how the code can be error pop up caused which is pytest has already
summary report to bring us an insight what occured with our code.

def get_formatted_named(f_name,m_name,l_name):
formatted_name = f"{f_name} {m_name} {l_name}"
return formatted_name.title()

PS C:\Users\sustainability\Desktop\Python> pytest
=================================================== test s
ession starts ==============================================
======
platform win32 -- Python 3.12.7, pytest-8.3.5, pluggy-1.5.0
rootdir: C:\Users\sustainability\Desktop\Python
plugins: anyio-4.6.2
collected 2 items

python\test_first_last_name.py FF
[100%]

=======================================================
== FAILURES ==============================================
===========
__________________________________________________ test_first_last_named ________
___________________________________________

def test_first_last_named():
> formatted_name = get_formatted_named('albert','einstein')
E TypeError: get_formatted_named() missing 1 required positional argumen
t: 'l_name'

python\test_first_last_name.py:4: TypeError
_______________________________________________ test_first_last_middle_named ___
____________________________________________

Catatan Python Learning 95


def test_first_last_middle_named():
formatted_name = get_formatted_named('monkey','luffy','d')
> assert formatted_name == 'Monkey D Luffy'
E AssertionError: assert 'Monkey Luffy D' == 'Monkey D Luffy'
E
E - Monkey D Luffy
E ? --
E + Monkey Luffy D
E ? ++

python\test_first_last_name.py:9: AssertionError
================================================= short tes
t summary info ============================================
======
FAILED python/test_first_last_name.py::test_first_last_named - TypeError: get_
formatted_named() missing 1 required positional argument: 'l_name'
FAILED python/test_first_last_name.py::test_first_last_middle_named - Asserti
onError: assert 'Monkey Luffy D' == 'Monkey D Luffy'
==================================================== 2 fail
ed in 0.15s =================

the errors story above is we have 2 unit test, first is testing first_last_name and
2nd testing first_last_middle_name that simbolized by ‘f’ letters and has failures
summary. and angle bracket ( > ) means the point where the code rising an errors.
in this case we have 2 problem each unit tests, the first caused by positional
argument and second the comparison of assert statement didint matched each
other beetwen the code output and the expected.

in this moment what we should be do? overriding we fix the unit test function, we
just need to fix the function code and modifying the code to reduce the output
pytest summary errors.
in this moment, to fix our code became passed, we will use previous code of
formatted_name.py then trying to modify an additional parameter ‘m_name’ as
middle name as keyword argument with default value of empty string.
remember except positional argument must be define in end of parameter
paratheses of function

Catatan Python Learning 96


# modified file formatted_name.py
def get_formatted_name(f_name,l_name,m_name='')
# we need if conditonal to facing the users cant input the middle name
if m_name:
formatted_name = f"{f_name} {m_name} {l_name}"
else:
formatted_name = f"{f_name} {l_name}"
return formatted_name.title()

if we running test code, we will passed the test each unit test, first_last_name unit
and first_last_middle_name unit test. this we can say running test case.

TTD ( test-driven development )


is a method to build an application or program begin from testing code first then
the code following depend passed testing unit. there are 3 point to coding, The
inputs it will take, The outputs it should produce, Any edge cases or special
scenarios it should handle.
the order to this methods :

1. write test code

2. testing the test code

3. write the code depend summary report and fix it one by one

4. testing code

5. rewrite the code

6. repeated from number 3

edge cases
means a lot of unit tests we should take testing on it. in previous function
get_formatted_name before we just only testing if the human which using our
code has clever mind, however our code using by crazy people that inputed a lot
of unexpected input, like whitespace, special character, or combination of all ? it is
will ruins our code become crashing the program. so well-programer should be
critical to this edge case to makes our program robust.

Catatan Python Learning 97


example edge case through previous our function code :

def test_empty_string():
formatted_name = get_formatted_named('', '')
assert formatted_name == ''

def test_large_string():
formatted_name = get_formatted_named('a' * 1000, 'b' * 1000)
assert formatted_name == 'A' + 'a' * 999 + ' ' + 'B' + 'b' * 999

in this case, we just need to rewrite the code to facing if edge case raised in our
visionary thought.

testing a classes
classes is an object we use often in our program if we work in front of a real job as
software engineer, class also OOP that python has to modelling a real world
situation, classes represent of a basic form of things such a stuff, or even a task
but in structural as a builder or framework. from a class we can create a instance
represent of a body form of thing with defined or has particulary purposes.
example we write class of anonymous survey this is a body form means we could
create of instance from that class to be more purposely such a survey of a
language we usually used to, language programming survey, or even a survey of
our favorite food. from instance we created, we can use all the method from the
anonymous survey form, such a show a question survey method, storing a
responses to the list or other data structure method, also displaying all responses
has been stored in the list.

testing a classes basicly same what we did to a function, like testing a output we
expected or testing a maybe we forget a positional argument that we should be
wrote to prevent of human offering additional data, or also testing edge cases
maybe raised caused by human input.
testing class just like testing a function, we need a test function with test_ begin
named also a test function itself. which is we already did to implementing the
class, create an instance, a positional parameter as argument as data we should

Catatan Python Learning 98


provide to give the class can running properly, then a cases what should we
assert to return expected output we want.
as long as we knew, assert is a comparison conditional. we learn just only equal
comparison, but in fact assert comparison have lots. this is an example commonly
being used.

assert a == b # Assert that two values are equal.


assert a != b # Assert that two values are not equal.
assert a # Assert that a evaluates to True.
assert not a # Assert that a evaluates to False.
assert element in list # Assert that an element is in a list.
assert element not in list # Assert that an element is not in a list

in this moments, we need a memberships comparison to validating whether or not


our method inside the class form has works properly to storing the responses to
the list data structure.
we will trying to write the class and the testing function

class AnonymousSurvey:
def __init__(self,question):
[Link] = question
[Link] = []

# a method to define what kind of the survey doing as a question


def show_question(self):
print([Link])

# a method to storing the responses


def store_responses(self,new_response)
[Link](new_response)

# a method to display the list of responses


def get_responses(self)
print(f"thanks for respons the survey!".title())

Catatan Python Learning 99


for respon in [Link]:
print(f"\t{respon}")

NOTE : we also can say the class represent for our program, we need this to more
structured
the program we wanna write is a simple program has while looping that capturing
a data language

# first we need create a kind of survey as parameter assign to the positional a


rgument of the class
question = 'what does you speak in language ?'
# then create an instance of the class to being a tools we use it methods
language_survey = AnonymousSurvey(question)
# then we use one of methods provided to show the kind of survey is running
language_survey.show_question()
# we programmed our program of looping break use flag variable when user p
ress 'q' letter
print(f"press 'q' to quit")
active = True

while active:
# create a variable to hold user input as survey respon
respon = input(f"language : ".title())
# we need a conditional if as break looping
if respon == 'q':
active = False
break
else:
# else statement hold the storing respon data
language_survey.store_responses(respon)
# if the survey has done, we use method to display the list
language_survey.get_responses()

then we continue to write a function test that checking a single response and
three responses supposed to be stored in the list

Catatan Python Learning 100


# importing a function what we wanna testing
from file_name.py import AnonymousSurvey

# create a test function, remember use a suffix named such test_


def test_stored_single_respon():
# create a instance and the paramater as implementing the class
question = 'what does you speak in language ?'
language_survey = AnonymousSurvey(question)
language_survey.store_responses('English')
assert 'English' in language_survey.responses

# checking a test function for three responses


def test_stored_three_responses():
question = 'what does you speak in language ?'
language_survey = AnonymousSurvey(question)
responses = ['English','France','Greek']
# we use a for loop to easier the code
for respon in responses:
language_survey.store_responses(respon)
for respon in responses:
assert respon in language_survey.responses

the code story is, first function testing our program whether works or not to got
single response, we first define them usually with test_ prefix named, then we
implemented the class form, create an instance and makes an positional argument
to get the class running properly, continued to using a method store_responses()
and assign a example of argument then we use assert statement which an
argument we assign has stored to the list or not with membership assert type.
the second paragraph is same but in this testing we trying to got 3 responses, we
use a for loop to easier to storing the data and assert each data to checking
membership inside of the list.
Testing three responses is a way to validate basic functionality. In real projects,
testing functions should also cover edge cases, large data sets, and system-

Catatan Python Learning 101


imposed limits to ensure the program is robust, scalable, and behaves as
expected under various conditions.
NOTE : [Link] is form list data or postulate to could used in instance. to
use it, change the self to name of instance you created, so you were accessing
the data list that have been initialize inside init method.

fixture
a feature of pytest library that lazy person like us wont write the code in repetition,
if we use before in previously testing code we should write the code example of
creating an instance and the argument we should passed it, this is very exhausting
when we work into real projects, the example code above should be written to
each definitions of testing functions. but this fixture feature has provided being a
tech-semi to handle this works. we just need separating the same code and
classified to new function which the name of function as same as the name of the
parameter of the test functions we should provided (in previous way, the
parameter of the test function is empty) then declare it with a decorator. the
function of classified code consist of the code that has repetition behaves with
return value. a decorator is a directive placed usually present in above the
classified we coded which usage to define it. using @ ‘mention’ symbol as mark of
decoration itself. in this case we use a fixture decorator so a decorator we write as
documented-library is such ‘@[Link]’ something like that. we will trying to
refactoring previously code with fixture one.

don’t forget to import the function of our program and the pytest package

NOTE : testing is visionary has calling up, we should have a visionary think to write
this code

# importing a function what we wanna testing


from file_name.py import AnonymousSurvey
import pytest

# define the decorator


@[Link]
# create a function to hold the same code as classified code
def language_survey():

Catatan Python Learning 102


# create a instance and the paramater as implementing the class
question = 'what does you speak in language ?'
language_survey = AnonymousSurvey(question)
return language_survey

# assign a function as argument to each test function


# checking a test function for single response
def test_stored_single_respon(language_survey):
language_survey.store_responses('English')
assert 'English' in language_survey.responses

# checking a test function for three responses


def test_stored_three_responses(language_survey):
responses = ['English','France','Greek']
# we use a for loop to easier the code
for respon in responses:
language_survey.store_responses(respon)
for respon in responses:
assert respon in language_survey.responses

we noticed that if the name of the functions of classified codes matches to the
name of parameter of test function, the fixture decorator will run automatically
that we shouldn’t to call the classified coded function.

NOTE : the name of the fixture decorator must be equal to the name of instance
and also equal to the name of return value from the function fixture also must
equal to the name of parameter of each test function as argument.

testing is important to do, to aiming a edge cases/or critical of your program such
a involving within human input, but in simple project you haven’t to do, further
more being a programmer to big project you will rumble it and makes progresive
learning about testing code. it is also makes another respect for your works.

list comprehension

Catatan Python Learning 103


a little bit an explanations about list comprehension.
list comprehension is a concise why to makes a code more readable.

exactly list comprehension is a tecnique to shorthener a list creation based on for


loops and if conditional as optional. usually used to create new list of numbers
data using range

the template of list comprehension is

variable = [expression for item in iterable if conditional]

expression is a transformation or a new item of variable that we will make


item is a members of iterable sequence that we will transform

iterable is a origin sequence that hold data that we will transform


conditional is a condition of data what we will listed in new variable or as filtering
mode
it is looks like a reverse code of standar code we usually write in few of line code

variable = []
for item in iterable:
if conditional
expression
[Link](item)

example to create sequnce of a number that hold even numbers

even_numbers = [number for number in range(1,100) if number % 2 == 0]

output = [2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30, 32, 34, 36, 38, 40,
42, 44, 46, 48, 50, 52, 54, 56, 58, 60, 62, 64, 66, 68, 70, 72, 74, 76, 78, 80, 8
2, 84, 86, 88, 90, 92, 94, 96, 98]

this is approaching more simple than we write a code usually with few of a line of
code

Catatan Python Learning 104


even_numbers = []
for number in range(1,100):
if number % 2 == 0:
even_numbers.append(number)

output = [2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30, 32, 34, 36, 38, 40,
42, 44, 46, 48, 50, 52, 54, 56, 58, 60, 62, 64, 66, 68, 70, 72, 74, 76, 78, 80, 8
2, 84, 86, 88, 90, 92, 94, 96, 98]

the output is same as the first code reveals a list of new variable in this moment is
even_number that created by if conditional.

the different between both approaching is in an expression, in list comprehension


we just need a temporary variable to hold a list of new item wherease if we write
code as we usually wrote, we need an append method to assign new items to new
variable that hold transformed list as requested on expression and conditional if.

NOTE :

1. use comma on number is a fault instead we use a dot. example phi number
written as 3.14 not 3,14

PART II PROJECT
after all we learned the part one that consist of few basic python sintax and data
structures, then we need to go to create our application to makes our
understanding are better than before, we need to practice of what we were
learned before with a real project. real project means we can build an application
to serve a solutions of real problems around us. there are project that we can
choose according to our desire such a games developer, data analysis, and web
developer. in this part we just practice two of those including as data analysis and
web developer.

Catatan Python Learning 105


DATA ANALYSIS
as data analysis we just know that we works with a data set. data set we will work
is a lot of numbers or also can a collections of kind of unnumbers data set. from
those data we can visualize that makes us easier to read and see what we missing
of the data set that we can see of the visualization we have made. as data analysis
we can know that we seeing a pattern and a correlation between those data set
through a visualization we have coded before. the code we will write as become
data analysis usually using a common library that usage by data analysis such a
matplotlib and pyplot.

create a line of graph


to create a line of graph depending the plot data usually we can use plot method
that provided by matplotlib library, but the first time we need to define the
matplotlib with alias name to make shorten. we use plot() that associated with the
subplots that holding the data. then we can show the graph or we can save it as
image file with show() method or savefig() method

import [Link] as plt

squares = [1,4,9,16,25)

fig, chart = [Link]()


[Link](square)
[Link]()

this is a simple code of creating a single plot that using plot() method to generate
a line which is existed inside of fig variable as background of the plot frame that
hold squares data.

squares variable is a data collection consist of value of second power of


sequence 1 until 5, then we create a variable to handle object defined by using
matplotlib library alias plt associated with subplots() method then dot notation as
calling way out tecnique.

then we call the all of the figure of frame with method show() approacing to
matplotlib with dot notation, then new pop up screen will display the visualization.

Catatan Python Learning 106


in this understanding, we know that plot() method have only one an argument
inputed that single data collection of squares as y axis. in this single data python
will put them into y axis and started from 0 number of x axis, are you understand?
maybe not.

squares data of those as single data, each will be plotted suitable to index
position, example first number of square data is 1 as y axis value then the value x
axis will be number 0 causes its positional index is 0 too.

that is an example of we provide single data, we can see that single data
represented to a pattern, trend or a distribution of the data.

create a scatter plot


then, how about we provide more data to correlating them into our visual image to
reveals appealing an information. we can use scatter() method to do with this task.
an example we will create 2 data that hold number and value of third powered. this
example will use loops for to generate a lot of items using range() method and list
comprehension.

Catatan Python Learning 107


import [Link] as plt

numbers = range(1,1000)
cubes = [number*number*number for number in numbers]

fig, chart = [Link]()


[Link](numbers,cubes)
[Link]([0,1000,0,1_000_000_000])
[Link]()

the code story is as usual we need to define the matplotlib library and the object
to create a figure and a frame which this example hold by chart variable, then we
can call scatter method and toe with dot notation to chart variable with 2
argument, the first argument is x-axis and second is y-axis then we limit the
visualization what we wanna display it with axis() method which using list as
argument consist of the value minimum and maximum of each axis. then we can
display it with show() method.

customize the visualization

Catatan Python Learning 108


every element of frame the figure exactly we can doing something interesting to
deal estetic view and easier us to read the data and understanding what gonna
being informed by the dataset.

matplotlib provide all this kind of customize such a adding a title, labels x-axis and
y-axis and change the colour each element and also can use styles. in this
example we gonna try to make a visualization of time-series data how much we
spend our time to learning this python.

import [Link] as plt

days = ['senin','selasa','rabu','kamis','jumat']
spend_time_hours = [10,20,8,6,4]

[Link]('Solarize_Light2')
fig, chart = [Link]()
[Link](days,spend_time_hours,c=spend_time_hours,cmap=[Link]
s,s=10)
chart.set_title('TIME SPENDING OF LEARNING PYTHON',fontsize=15)
chart.set_xlabel('HARI',fontsize=20)
chart.set_ylabel('TIME (Hours)',fontsize=20)
chart.tick_params(labelsize=10)
[Link]()

the code story is in this example we have 2 data including days and
spend_time_hours to informing a pattern when the heavy day occurs and when
the easy day we have learned python.
we use style named ggplot is a built in style of frame to visualize and changed the
default theme, there is a lot of styles you need to try each style to fit in with your
desire.

[Link]
after that usually we define figure and chart as frame to being an instance of
matplotlib object. then we plot the data to scatter plot with method scatter() use a
few of argument such a x-axis, y-axis, c means to color refers to 2nd data

Catatan Python Learning 109


spend_time_hours, cmap to colouring the scatter to define it using module
colourmap (cm) associated with matplotlib and the colour we wanna use, in this
case blues means the colour will darkize when the value is high otherwise, and s
means size of the scatter.
[Link]

then we set a title, x-axis label and y-axis label with method suffix set_ as starter
named with parameter fontsize to control how big the dimension of the text
visualize.
tick_params() with the parameter labelsize is to control the text dimension of both
the dataset.

saving the figure to image file


instead of we can saving file use the button in the screen tab when we visualize it,
also we just can export the image of visualization with savefig() method and put
the argument as the name of file or we can do also using path directory ended
with file name of image if we wanna save the file into another place we want.

Catatan Python Learning 110


-- snip --
[Link]('[Link]')
[Link]('C:\Users\sustainability\Desktop\Python\learn_part_2\[Link]')

well, we know before we learned it when the part 1 beat us about relative path and
absolute path, a relative path will saving or locate the file according to where the
file py we generate the file image meanwhile absolute path guide us to the
location we hope exactly.

WORKS WITH AN API


an api is long pronounces as application programming interface, it show us how to
makes an program or a website communicate each other to serve several
purposes such a getting a dataset, update a new data or just only as a displaying
data for user who uses our program.

an api analogy as we are human being as social entities to get what we want then
we should give what the other desire. sounds likely too much but it is will be
happen. we want something which people have but we don’t, then we need api
such a lobbying, talking, act like a poor, or rude behaviour maybe to get what we
want in return.
an api is an address to call that ourself inside behave and get what we want which
we usually called it of endpoint. an api looks like [Link]
not always others api website sounds like that, in fact we have different address.
an api most of the data we going to catch is object-oriented and uses json
formatted consist of dictionary or list or both as nested data collection.
an api is same like http,https,rtp, and another a communication tools each
website.

in this learn, we will trying to catch a data existed inside github repositories, to
communicate with other site we need request library and get method to create an

Catatan Python Learning 111


instance or object.

import requests

# url of github api


# this we communicate with github uses talking behave
url = "[Link]
url += "?q=language:python+sort:stars+stars:>10000"

# define header response as dictionary


headers = {"Accept": "application/[Link].v3+json"}

# after we communicate, we got responses object that hold by responses vari


able
# we use url and headers as positional argument as absolute required to get r
esponses
responses = [Link](url, headers=headers)

# we can check the response status code through status_code property of th


e object
print(responses.status_code)
# if got number 200 means github allow us to get the endpoint/data

# then we need to transform an object response to json formatted with json()


method
# we create new variable named as repositories
repositories = [Link]()

# then we need to know what is a data structured served, whether nested or r


egular data
print(repositories)

# if we got a dictionary we could see the keys to get what data we expected u
se for loop
# the get a bunch of data that we get from asking to github of the most high st
artgazers repository such a name of repository, ownership, stargazers numbe

Catatan Python Learning 112


r and its url
for repo in repositories['items']:
print(f"\nname : {repo['name']}")
print(f"owner : {repo['owner']['login']}")
print(f"stargazers : {repo['stargazers_count']}")
print(f"url repository : {repo['html_url']}")

the story code is the core we should know that request library serving this jobs to
create an object of responses to package the bunch of information given by
github then we just extract the data through accessing it object uses for loops.

headers parameter is a argument we should give to help the library do its works
which is contains a few line to get exactly the data we expected. to define headers
we usually use branch paranthases as dictionary and separated by comma. in this
context we use above filled to inform the github that we need a data in json
format.

responses = [Link](url, headers=headers)

on top we can see is an example of creating an object with have two argument
include url as github api address or talking behave and headers as what we need
expected data.

then we can understand whater our request is allowed or not using status_code
property, if status code reveals number 200 so we can explore more far the data.

then we should to check the structured of data, it’s not always simple as we can
see, but maybe more complex data that have nested with list collection or can be
nested 3 with dictionary again.
continue, we can extract the data using for loops and for more advance we can
display it to matplotlib to get visualization.

# the output of finished extracting the data of response object


# the output display a repositories that have more that 10_000 startgazers

name : free-programming-books

Catatan Python Learning 113


owner : EbookFoundation
stargazers : 361377
url repository : [Link]

name : public-apis
owner : public-apis
stargazers : 353831
url repository : [Link]

name : system-design-primer
owner : donnemartin
stargazers : 308898
url repository : [Link]

name : awesome-python
owner : vinta
stargazers : 248171
url repository : [Link]

name : Python
owner : TheAlgorithms
stargazers : 202169
url repository : [Link]

--- snip ---

Catatan Python Learning 114

You might also like