Python Basics: Lists, Tuples, and Conditionals
Python Basics: Lists, Tuples, and Conditionals
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
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.
print(”already existed”
the code will checking the list items if true will execute print metode, if false will
not execute nothing.
the code will checking the list items, cause kontlo hasnt assigned in list data. it will
true valuable and the expresion will execute.
if 1 condional valued true and other is false then the expresion will executed
if 1 conditional valued true and other is false the expresion will 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
if statement:
expresion
elif statement:
exprresion
else:
expresion
this is 3 blok if statement, if first block passed, next blok will missed
simple if statement
if conditional_test :
do something
if conditional_test :
do something
if conditional_test :
do something
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
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:
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}")
------------------------------------------------------------
colors = ['red','blue'] #value is true
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 .
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
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())
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())
dictionary
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.
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
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')
to add new key-value call this pairing. like same with accesing but with new key
and the value
#pairing 2 key-value
dict['nama'] = 'maxwell'
dict['age'] = 87
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
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.
if alien_0['speed'] == 'slow':
x_increment = 1
elif alien_0['speed'] == 'medium':
x_increment = 2
elif alien_0['speed'] == 'fast':
x_increment = 3
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',
}
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().
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
# 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
Hi, albert
Albert bahasa favoritnya : C
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
NOTE : keys method isnt just to looping purposes. can use for a simple expresion
like above
favorites_animals = {
'einstein' : 'rakun',
'newton' : 'trenggiling',
'mozart' : 'babi',
'nieze' : 'anjng',
}
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.
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',
}
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',
}
}
a list in dictionary
rocks = {
'granite' : ['kuarsa', 'feldspar', 'mikas', 'amfibol'],
'andesite' : ['plagioklas feldspar', 'piroksen', 'hornblende', 'olivin'],
'peridotit' : ['olivin','piroksen', 'klinopiroksen', 'ortopiroksen', 'hornblende', 'mik
}
dicationary in a list
granite = ['kuarsa','mikas','feldspar']
numbers = 0
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
initial_numbers = 0
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.
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 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
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
increment = 0
counter = 0
active = True
while active:
numbers = input()
increment += 1
if numbers == '':
print(counter + increment)
elif numbers == 'quit':
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
5. then if true inside if statement, then a break statmenet will executed. mean
that the program will be quit imediatelly.
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
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
active = True
while active:
print('1st executed block')
print('2nd executed block')
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.
import time
# unverified users list
unverified = ['nata','jeni','silvi','puput','septi']
verified = []
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
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
import time
# initial variable
response = {}
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())
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
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
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
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.
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.
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.
# 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))
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.
# 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()
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
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)
# 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
# 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.
# 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.
def custom_hair(*models):
print(models)
# calling function
custom_hair('babi haircut','highwaycut')
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 :")
we should focused in calling function that has story that important to know:
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
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
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.
Writing good docstrings is essential for creating readable and maintainable code
Here are some tips for writing effective docstrings:
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
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.
Arbitrary arguments can also use double asterisks (**) to create kwargs
def make_person(**user_info):
print(f"{user_info}") # displaying user_info parameter as variable holding a d
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,
# 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
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.
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)
my_car = make_car('toyota','pajero',color='blue',tow_package=True)
print(my_car)
import cars as cr
my_car = cr.make_car('toyota','pajero',color='blue',tow_package=True)
print(my_car)
my_car = mc('toyota','pajero',color='blue',tow_package=True)
print(my_car)
styling function
1. a function should have a descriptive name, mean that a function has benefit
what to do represent as the name.
def function_name(
parameter_0, parameter_1, parameter_2,
parameter_3, parameter_4, parameter_5):
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
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
# the output
His Name Is Einstein
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
NOTE :
3. All parameter inside of parethesse of init method are called instance attribute
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.
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 instance
her_car = Car('daihatsu','ayla',2012)
# output
this car already drove 6 miles
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 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
# replace attribute value of oddometer through a method with new parameter tha
my_car.update_oddometer(15)
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
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)
class PrimalHuman(Human):
--- snip ---
# adding new attribute
[Link] = 'bows'
print([Link])
beast.carry_weapon()
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.
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.
def describe_weapon(self):
print(f"this human has {[Link]} 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.
# create instance
my_human = Human('albert',23,57,170)
# Create instance
my_human = Human('newton',26,55,180)
# 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 human
my_human = [Link]('nize',24,67,189)
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
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.
while active:
y = randint(1,10)
print(y)
[Link](2)
if y == 5:
active = False
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.
example implement random module to build dice app simple using randint class
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())
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
7. one blank line to separating between import statement and entire code inside
a modules
9. instance is a creating object that has attribute assign from initialized by body
form / class
3.1415926535
8979323846
2643383279
whitespace here
whitespace here
# define path
path = Path('phi_digits.txt') # relative path
# path = Path('C:\phi_digits.txt') # absoule path
# display content
print(contents)
contents = path.read_text()
# handling for avoid whitespace of contents
contents = [Link]()
print(contents)
# ouput
3.1415926535
8979323846
2643383279
contents = path.read_text().rsplit()
but always understand the first method writeen, the first it will executed
# 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
NOTE :
print(pi_string)
# output
3.141592653589793238462643383279
Once you’ve read from a file, you can analyze its contents in just about any way
you can imagine.
# 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
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)
file = dir('C:/Users/sustainability/Desktop/Python/python/learning_python.txt')
contents = file.read_text()
for line in [Link]():
print([Link]('python','javascript'))
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)
2. os Module: Useful for checking file existence and working with paths.
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.
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.
try:
print(3/0)
except ZeroDivisionError:
print(f"you cannot fill a zero as divider!!".title())
# output
You Cannot Fill A Zero As Divider!!
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
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 :
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.
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.
# we already has a book txt files and use relative path as directory location
# storing a books to the list
paths = ['[Link]','[Link]','[Link]']
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
file = Path('[Link]')
try:
contents = file.read_text(encoding='utf-8')
except FileNotFoundError:
pass
else:
print('file existed')
file = Path('[Link]')
try:
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.
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 )
# the output
[1, 5, 7, 4, 6, 8, 4, 3, 9]
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
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
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.
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 : ')
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.
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}")
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()
# filename formatted_name.py
def get_formatted_name(f_name,l_name):
formatted_name = f"{f_name} {l_name}"
return formatted_name.title()
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
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
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 ___
____________________________________________
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
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.
3. write the code depend summary report and fix it one by one
4. testing code
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.
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
class AnonymousSurvey:
def __init__(self,question):
[Link] = question
[Link] = []
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
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
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-
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
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
variable = []
for item in iterable:
if conditional
expression
[Link](item)
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
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.
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.
squares = [1,4,9,16,25)
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.
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.
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.
numbers = range(1,1000)
cubes = [number*number*number for number in numbers]
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.
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.
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
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.
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.
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
import requests
# 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
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.
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.
name : free-programming-books
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]