Friday, April 19, 2024

Python Beginner - Alison 01

 Kita akan kursus python untuk pemula. Kursus ini disediakan secara gratis oleh Alison. Silahkan search di internet.


Image - Python untuk pemula (credit to Google)

Python is "universal language" in the computer program.

Compiled ---> Just execute "true" code
Interpreter ----> Check all codes line by line, then just stop if find wrong codes.

Python is interpreter language.

What do you call a set of instructions that a computer follows to perform a certain task, at a certain time, and in a certain way?
- program

Which of these are the kinds of programs?
- compiler and interpreter programs.

Python has several versions and you have to choose one that matches the operating system of your computer.
- True

=========================

Module 2 - Data Type, Variables and Basic Operations

What term refers to a reserved memory location to store value(s) and serves as a reference or pointer to the value(s) stored in it?
- Variables

Integer --> number: -1, -2, -3...... 2, 34, 36....
Float...> 12.0, 3.14 ........-3.6,
String ..> Characters: "name"...'12'...'''ABC''' ...
Boolean: True False

Which of these are data types available in Python? Choose three.
- Floats
- Strings
- Integers

True or False: To create a variable, you just declare it by assigning a value to it.
- True

Low level language -----> Machine oriented
High level language ------> Python

==================
Terminal ----> New terminal
PS C:\Users\Evi\.vscode\Lesson1> py -3 --version ...> for Window
Python 3.5.2...> Output....> Python I use

PS C:\Users\Evi\.vscode\Lesson1> py
Python 3.5.2 (...............)
Type "help", ...........
>>> 2+2
4
>>> name = 'Atan'
>>> name
'Atan'
>>> quit()
PS C:\Users\Evi\.vscode\Lesson1>
then click x ----> sebelah kanan


Kemudian pergi ke folder Lesson1
tambahkan file: hello.py
greeting = 'Hello Word'
print(greeting)
Hello word!

----------------------------------

What term refers to a reserved memory location to store value(s) and serves as a reference or pointer to the value(s) stored in it? Choose one:
- variable

Module 2, Chapter 5
number = "12"
print(type(number))
number = int(number)
print(type(number))
then, run ..> start debugging
<class 'str'> ..... > String ....> "12"
<class 'int'> ....> Integer ......>
<class 'float'> 12.0 

A representation such as "12" with the quotation marks in Python will be classified under what kind of data? Choose one.
- strings
-----------------------------------

Module 2, Chapter 6.
age = input('enter your age: ')

print('you are ' + str(age) + ' years old')
enter your age: 56
you are 56 years old

True or False: The Input() function is the one used to receive data from users.
- True
----------------------------------------------

Module 2, Chapter 7
in python a % b ----> meaning: calculate the reminder of dividing.
example: 9 % 2 = 4 + 1....> jadi, 9 % 2 = 1

9//2 ...> floor division = 4.5, thus 9//2 = 4

9 ** 2 = 9 pangkat 2 = 81
9 * 2 = 9 kali 2 = 18

print('welcome to super simple calculator')
a = input('enter first number : ')
b = input('enter econd number : ')
print('your answer is', a + b)

welcome to super simple calculator
enter first number : 1
enter second number : 19
your answer is : 119 ....> wrong

then, we change program:
print('welcome to super simple calculator')
a = float(input('enter first number : '))
b = float(input('enter econd number : '))
print('your answer is', a + b)

welcome to super simple calculator
enter first number : 1
enter second number : 19.0
your answer is : 20.0

In Python calculations when a = 5, and b = 2. What value will a//b return? Choose one.
answer: 2 .....> not 2.5
-------------------------------------------------

Module 3, Chapter 1

Booleans ...> True   False
True: 1
False: 0

and 
0   0 ...> 0
0   1 ...> 0
1   0 ...> 0
1   1 ...> 1
examples:
12 and 0 ...> 0
1 and 1 ...> 1
0 and 0 ...> 0
True and False ...> False

or
0   0 ...> 0
0   1 ...> 1
1   0 ...> 1
1   1 ...> 1
examples:
13 or 0 ...> 13
0 or 2 ...> 2
True or False ...> True

XOR: Exclusive or ....> sign: ^
0   0 ...> 0
0   1 ...> 1
1   0 ...> 1
1   1 ...> 0
Examples:
11 ^ 11 ...> 0
11 ^ 0 .....> 11

True or False: Boolean variable values can only be either true or false.
- True
--------------------------------

Module 3, Chapter 2
a == b ----> equal
a != b ...> not equal
a >= b ...> a greater than equal to b
a <= b ....> a less than equal to b

Examples:
a = 10
b = 3
c = 10
a == b ...> False
a == "10" ...> False
a != b ...> True
a >= b ...> True


minMarks = 30
studentMarks = float(input('enter your mark: '))
 
if studentMarks > minMarks:
    print("you are eligible")
else:
  print("you are not eligible")

enter your mark: 32
you are eligible

enter your mark: 29
you are not eligible

Which of these are conditional operators in Python? Choose three.
- equal to
- less or equal to
- greater than
--------------------------------------

Module 3, Chapter 3

Loops:
1) Iteration: for
2) Condition: while

# Iteration / for loop
for i in range(1, 51):
    print(i)
Run Start Debugging:
1
2
3
.
.
.
7
8
.
.
49
50

# Iteration / for loop
for i in range(1, 51, 5):
    print(i)
Run Start Debugging:
1
6
11
.
.
.
36
41
46

# Iteration / for loop
for i in 'string':
    print(i)
Run Start Debugging:
s
t
r
i
n
g


# conditional / while loop
i = 1
while i <= 50:
    print(i)
Run Start Debugging:
1
1
1
1
.
.

Then, we modify the program:
# conditional / while loop
i = 1
while i <= 50:
    print(i)
    i += 1 # i = i + 1
Run Start Debugging:
1
2
3
.
.
.
48
49
50

Which of these is used to denote a list in Python? Choose one.
- answer: [ ]
-------------------------------------------------

Module 3, Chapter 4

Lists ...> sign: [ ]
mylist = [1,2,3,4,5,6,7,8,'9']
print(mylist)
Run Start Debugging:
[1,2,3,4,5,6,7,8,'9']

fruits = [
    'apple',
    'banana',
    'pear',
    'strawberies',
]

print(fruits)
Run Start Debugging:
['apple', 'banana', 'pear', 'strawberies']

Now, we modify the program:
fruits = [
    'apple', # 0
    'banana', # 1
    'pear', # 2
    'strawberries', # 3
]

print(fruits[1])
Run Start Debugging:
banana

Now, I want to print all fruits:
fruits = [
    'apple', # 0
    'banana', # 1
    'pear', # 2
    'strawberries', # 3
]

print(fruits[:4])
Run Start Debugging:
['apple', 'banana', 'pear', 'strawberries']

-------------------------------------------------

Module 3, Chapter 5
characters = ['a', 'b', 'd', 'd']
print(characters)
characters [2] = 'c'
print(characters)
Run Start Debugging:
['a', 'b', 'd', 'd']

Then, 'd' changed to 'c'
['a', 'b', 'c', 'd']


>>> characters = ['a', 'b', 'd', 'd']
>>> len(characters)
4

>>> characters.append('e')
>>> characters
['a', 'b', 'd', 'd', 'e']

>>> characters.remove('e')
>>> characters
['a', 'b', 'd', 'd']

>>> characters.pop(3)
'd'
>>> characters
['a', 'b', 'd']

>>> 'a' in characters
True
>>> 't' in characters
False 

>>> characters.append('c')
>>> characters
['a', 'b', 'd', 'c']

>>> characters.sort()
>>> characters
['a', 'b', 'c', 'd']

>>> characters.reverse()
>>> characters
['d', 'c', 'b', 'a']

Which of these is not one of the list operations in Python? Drag the correct answer into the space provided.
- characters.inssert()
----------------------------------------------------------------------

Module 3, Chapter 6

Bubble Sort
"Bubble Sort is a straightforward sorting algorithm that repeatedly compares adjacent elements in an array and swaps them if they are in the wrong order."

list = [8,3,1,4]
print(list)

length = len(list)
for i in range(length):
    for j in range(0, length-i-1):
        if list[j] > list[j+1]:
            list[j], list[j+1] = list[j+1], list[j]

print(list)
Run Start Debugging:
[8,3,1,4]

Then, changed to:
[1,3,4,8]
-------------------------------------

Module 3, Chapter 7
Logical operators
>>> a = 13
>>> if (a > 6) and (a < 20):
...         print(a)
...
13

>>> if (a > 6) or (a < 20):
...         print(a)
...
13


Complement (~)

Binary Basics

Computers store information as a stream of binary digits (bits), which are either 0s or 1s. Whether you’re dealing with text, images, or videos, it all boils down to these fundamental building blocks. Python’s bitwise operators allow you to manipulate individual bits at the most granular level.

 Python provides several bitwise operators:
  1. Bitwise AND (&): Computes the logical AND of corresponding bits in two integers.
  2. Bitwise OR (|): Computes the logical OR of corresponding bits.
  3. Bitwise XOR (^): Computes the logical XOR (exclusive OR) of corresponding bits.
  4. Bitwise NOT (~): Inverts all the bits.
  5. Bitwise Shift Operators (<< and >>): Shift bits left or right.

Q1: cari binary angka 13
- bagi angka 13 dengan 2: 13/2= 6 ...> reminder 1....> first binary.
- then, 6/2 = 3 ...> reminder 0 ...> second binary
- then, 3/2 = 1 ...> reminder 1 ...> third binary
- kemudian, 1/2 = 0 ...> `reminder 1 ...> fourth binary
Untuk mengetahui binary angka 13, dilihat dari bawah (belakang) atau dari langkah ke 4 (fourth binary): 1101

Q2: cari angka berapa dari binary 0b1100 atau 1100?
- mulai dari sebelah kanan, yaitu 0
- decimal equivalent 0 = 0 x 2^0 = 0
-  decimal equivalent 0 = 0 x 2^1 = 0
- decimal equivalent 1 = 1 x 2^2 = 4
- decimal equivalent 1 = 1 x 2^3 = 8
Then, 0 + 0 + 4 + 8 = 12
------------------------------------------------------------------------

Module 4, Chapter 
def betterPrint(string):
    for char in string:
        print(char)

betterPrint('apa kabar')
Run Start Debugging:
a
p
a

k
a
b
a
r


We changed the program:
def betterPrint(string = 'a parameter'):
    for char in string:
        print(char)

betterPrint()
Run Start Debugging:
a

p
a
r
a
m
e
t
e
r

Which of these are the types of functions available in Python? Choose two
- user-defined functions
- pre-defined functions
-------------------------------------------------------------

Module 4, Chapter 2

Global and Local scope:
x = 10
def function():
    x = 20

function()
print(x)

Run Start Debugging:
10 ...> Global scope

Then, we changed program:
x = 10
def function():
    global x
    x = 20

function()
print(x)
Run Start Debugging:
20 ...> Global scope, now, to be 20

True or False: Pre-defined scopes and user-defined scopes are the types of scopes available in Python.
- False
-----------------------------------------

Module 4, Chapter 3

Returning data
def reverse(string):
    print(string[::-1])

reverse('hai')
Run Start Debugging:
iah ...> reverse (kebalikan) dari 'hai'


def reverse(string):
    return string [::-1]

reversedString = reverse('hai')
print('data', reversedString)
Run Start Debugging:
data iah


Which of these refers to the factorial of 5? Choose three.
* 5!
* 5*4!
* 5(4*3!)
-------------------------------------------------------

Module 4, Chapter 4

Factorial
5! = 5x4x3x2x1 = 120

def iterativeFactorial(n):
    result = 1
    for i in range(n, 0, -1):
        result = result * i
    return(result)

print(iterativeFactorial(5))
Run Start Debugging:
120

What do you call it when a function recalls itself several times for a purpose in Python programming? Drag the correct answer into the space provided.
- recursion
--------------------------------------------

Module 4, chapter 5
Tuples ....> Anything can't be changed

tuple1 = (12, 13, 14, 15)
print(tuple1)
Run Start Debugging:
(12, 13, 14, 15)

Tuples in Python are denoted with what symbol? Choose one.
* ()
-------------------------------------------------

Module 4, Chapter 6
Dictionaries
employee = {
    'name' : 'Atan',
    'age' : 34,
    'salary' : '$10,000',
    'designation' : 'manager'
}

for key in employee:
    print(key + " : " + str(employee[key]))
Run Start Debugging:
name : Atan
age : 34
salary : $10,000
designation : manager
-----------------------------------------------------------------------------

Module 5, Chapter 1

in the file string.py
def reverseString(string):
    return string[::-1]

then, we make file main.py to import from string.py
import strings

print(strings.reverseString('hello'))
Run Start Debugging:
olleh

Which of these is used to call a module from another file into your program? Choose one.
- using the import function
-----------------------------------------------------------------

Module 5, Chapter 2
import random

score = 10
randomNumber = random.randint(1,10)

while True:
    userNumberInput = int(input('Guess : '))

    if userNumberInput == randomNumber:
        print("congratulations your guessed right! your score is " + str(score))
    else:
        print('better luck next time')
        score -= 1
Start Debugging:

Guess : 1
better luck next time

Guess : 8
congratulations your guessed right! your score is 5


What keyword is used to close operations in Python exceptions? Choose one.
- Finally keyword

-----------------------------------------------------------------------------

Module 5, Chapter 3

Which of these is not a classification of error in Python?
- function

Classification of errors:
- run time
- compiling
- logical
---------------------------------------

Module 5, chapter 4

True or False: ZeroDivisionError is a type of error in Python.
- True
-------------------------------------

Module 5, chapter 5

>>> string = '29'
>>> string.isdigit()
True
>>> string.replace('2', 'Hello')
'Hello9'

a = 'ABC123DEF456'

def answer(string):
    alphabets = ''
    result = 0
    for char in string:
        if char.isdigit():
            result += int(char)
        else:
            alphabets += char
        return (alphabets, result)
print(answer(a))
Start Debugging:
('A', 0)

Which of these are examples of string operations in Python? Choose three.
- string.swapcase()
- string'isdigit()
- 'e' in string

==============================================
Module 6, chapter 1

data.txt
hello
abc
123

files.py
f = open("data.txt")
print(f.read())
Run python file in dedicated terminal:
hello
abc
123
-----------------------------------------------

Module 6, chapter 2

Which of the following are file opening modes? Choose three:
* rb
* a+
* w+

================================
Python File Handling for beginner, Dave: Python File Handling for Beginners - YouTube

Open and Read File
# r = Read
# a = Append
# w = Write
# x = Create

# Read - error if it doesn't exist

f = open("names.txt")
print(f.read())
Run Python file:
Dave
Jane
Eddie
Jimmie

We just want to see first 4 characters in the file:
# r = Read
# a = Append
# w = Write
# x = Create

# Read - error if it doesn't exist

f = open("names.txt")
# print(f.read())
print(f.read(4))
Run Python file:
Dave

Read First and Second lines of file:
# r = Read
# a = Append
# w = Write
# x = Create

# Read - error if it doesn't exist

f = open("names.txt")
# print(f.read())
# print(f.read(4))

print(f.readline())
print(f.readline())
Run Python file:
Dave
Jane

Close file and open file we don't have
# r = Read
# a = Append
# w = Write
# x = Create

# Read - error if it doesn't exist

f = open("names.txt")
# print(f.read())
# print(f.read(4))

# print(f.readline())
# print(f.readline())

f.close()

try:
    f = open("name_list.txt")
    print(f.read())
except:
    print("the file doen't exist")
finally:
    f.close()
Run Python file:
the file doen't exist


Append - create file
# Append - creates the file if it doesn't exist
f = open("context.txt", "a")
f.write("Neil")
f.close()

f = open("context.txt")
print(f.read())
f.close()
Run Python file:
Dave
Jane
Eddie
JimmieNeil ....> why?


Write (overwrite)
f = open("context.txt", "w")
f.write("I deleted all of the context")
f.close()

f = open("context.txt")
print(f.read())
f.close()
Run Python file:
I deleted all of the context
-----------------------------------------------------

Module 6, Chapter 3
Binary Files

Which of the following file opening modes is used for binary files? Drag the correct answer into the space provided:
- wb

------------------------------------------------

Which of the following is written in the pascal case format? Choose one.
- ThisIsPascalCase

Which of these is a type of variable? Drag the correct answer into the space provided.
- instance variable

True or False: Every class method you construct in an object-oriented approach will always take "self" as an argument.
- True

# Previous postings:

JJJJJJJJJJJJ



With the increasing importance of cybersecurity, becoming a certified penetration tester can lead to lucrative roles. These certifications cover network security, vulnerability assessment, and ethical hacking.

JJJJJJJJJJJJJ

Wednesday, April 17, 2024

Python Tutorial - Polymorphism - 019

 Polymorphism adalah konsep yang fundamental dalam object-oriented programming.  Kata Polymorphism merujuk pada classes yang berbeda yang diperlakukan sebagai class yang sama melalui inheritance.


Image - Polymorphism (credit to CodersArcade)

Syntax Error:
Class Bear:
def sound(self):
print("Groarrr") class Dog:
def sound(self):
print("Woof woof!") def makeSound(animalType):
animalType.sound()

bearObj = Bear()
dogObj = Dog()

makeSound(bearObj)
makeSound(dogObj)


True Correction:
class Bear: def sound(self): print("Groarrr") class Dog: def sound(self): print("Woof woof!") def makeSound(animal): animal.sound() bearObj = Bear() dogObj = Dog() makeSound(bearObj) makeSound(dogObj)

Output:
Groarrr
Woof woof!

In Python, indentation is crucial for defining code blocks. Here's a breakdown of the corrected code:
Classes:
  • We define two classes, Bear and Dog, each having a sound method.
  • The sound method prints the corresponding animal sound ("Groarrr" for bear and "Woof woof!" for dog).
makeSound function:
  • This function takes an animalType argument as input.
  • Inside the function, we call the sound method of the animalType object to produce the sound.
Creating objects and calling functions:
  • We create instances (bearObj and dogObj) of the Bear and Dog classes, respectively.
  • Then, we call the makeSound function twice, passing bearObj and dogObj as arguments. This invokes the corresponding sound methods for each object.

class Bear: def sound(self): print("Groarrr")

class Dog:
def sound(self):
print("Woof woof!")

def makeSound(animalType):
animalType.sound()
    print("Groarrr")

bearObj = Bear()
dogObj = Dog()

makeSound(bearObj)
makeSound(dogObj)

"When creating applications like a document editor, you may not know beforehand the types of documents a user will open, be it PDF or Word. Rather than having separate types for each document format, wouldn’t it be convenient to access them uniformly?"
"By defining an abstract class, we can outline a structure that every derived class must adhere to. Here’s how it works:"
class Document:
def __init__(self, name):
self.name = name
def show(self):
raise NotImplementedError("Subclass must implement this abstract method")
==========================

Dalam Python, Polymorphism diekskusi dengan berbagai cara, termasuk menggunakan functions dan abstract classes.


Function-Based Polymorphism in Python
    Semisal, ada dua classes, yaitu: Bear and Dog. Setiap class ini punya sebuah metode yang menghasilkan bunyi unik. 
    Menggunakan Polymorphism, kita bisa menggunakan metode sound untuk object  class ini melalui function umum.

SyntaxError:  
class Bear(object):
    def sound(self):
        print("Groarrr")

        class Dog(object):
    def sound(self):
        print("Woof woof!")

        def makeSound(animalType):
    animalType.sound()

    bearObj = Bear()
dogObj = Dog()

makeSound(bearObj)
makeSound(dogObj)

Correction program:



Error and true
class Bear(object):
    def sound(self):
        print("Groarrr")
class Bear:
def sound(self):
    print("Groarrr")

 class Dog(object):
    def sound(self):
        print("Woof woof!")

        def makeSound(animalType):
    animalType.sound()

bearObj = Bear()
dogObj = Dog()

makeSound(bearObj)
makeSound(dogObj)
--------------------------------------------

Abstract Class-Based Polymorphism




class Document: def __init__(self, name): self.name = name def show(self): raise NotImplementedError("Subclass must implement this abstract method")

class Pdf(Document): def show(self): return 'Show pdf contents!' class Word(Document): def show(self): return 'Show word contents!' documents = [Pdf('Document1'), Pdf('Document2'), Word('Document3')] for document in documents: print(document.name + ': ' + document.show())

Output:
Document1: Show pdf contents!
Document2: Show pdf contents!
Document3: Show word contents!'
# Posting sebelumnya:
JJJ

Thursday, April 11, 2024

Python Tutorial - Class Inheritance - 018

Python menawarkan paradigma kuat dalam "Object-Oriented Programming," sehingga class bisa "diwariskan" fungsi dari Class lainnya. 


Image - Class Inheritance (credit to Google).

"This enables objects that are created using a class inheriting from a superclass to have access to methods and variables of both the superclass and the derived class. Unlike some other languages, Python even supports multiple inheritance, expanding its utility."

Understand Class name User:
class User:
    name = ""
    
    def __init__(self, name):
        self.name = name

    def printName(self):
    print("Name = " + self.name)

brian = User("brian")
brian.printName()
Note: program error

Yang benar:
class User:
    def __init__(self, name):
        self.name = name

    def printName(self):
        print("Name = " + self.name)

brian = User("brian")
brian.printName()
=============================================
Mari Kita disain class yang lain, yaitu Programmer
class Programmer(User):
    def __init__(self, name):
        self.name = name

    def doPython(self):
        print("Programming Python")


Now, we do comprehensive inheritance 
class User:
    def __init__(self, name):
        self.name = name
    
    def printName(self):
        print("Name = " + self.name)

class Programmer(User):
    def doPython(self):
        print("Programming Python")

brian = User("Brian")
brian.printName()

diana = Programmer("Diana")
diana.printName()
diana.doPython()

Output: 
Name = Brian
Name = Diana
Programming Python

# Posting sebelumnya:

JJJJJJJJJJ
JJJJJ

Wednesday, April 10, 2024

Python Tutorial - Metode Overloading - 017

Ada banyak cara untuk mendifinisikan dan meyebut metode (fnction) dalam bahasa rogram Python.  



Image - Hanya ilustrasi saja, tanda dilarang parkir.

Tergantung pada mendifinisikan function, bisa didefinisikan dengan "zero, one, two or more parameters."

Hal ini disebut dengan istilah "method overloading," tak banyak program bisa melakukan hal ini.


Contoh Metode Overloading
Class dengan satu metode(fungsi) adalah sayHello().
- parameter metode adalah None
- object dikreasi berdasarkan class
class Human:
    def sayHello(self, name=None):
        if name is not None:
            print('Hello' + name)
        else:
            print('Hello')

obj = Human()
obj.sayHello()
obj.sayHello('Guido')

Output (ekskusi dengan main.pay)
Hello
HelloGuido

# Posting sebelumnya:

JJJJJJJJJJJJ

Monday, April 8, 2024

Python Tutorial - Encapsulation - 016

 Encapsulation adalah konsep dasar dalam Object Oriented Programming (OOP).  Encapsulation menyebabkan kita bisa melakuan restriksi. 



Image - Ilustrasi saja, order secara digital.

Restriksi itu dilakukan terhadap metode dan variabel tertentu dalam class.

Apa itu "Object-Oriented Programming?":
- OOP tergantung pada konsep classes dan objects
- Classes mendifinisikan attributes dan metode
- objects dikreasi dari classes
- Untuk contoh, ada class yang disebut car. Attributesnya color, brand dan mode. Kemudian myCar adalah nilai unik dari class.


Memahami Private Method
Kita punya car sebagai class, dimana ada main method, yaitu main method: drive() dan private method: _udateSoftware().
class Car:
    def __init__(self):
        self.__updateSoftware()
    def drive(self):
        print('driving')
    def __updateSoftware(self):
        print('updating software')

redcar = Car()
redcar.drive()

Output:
updating software
driving


Memanfaatkan Private Variabel.
class Car:
    __maxspeed = 0
    __name = ""
    def __init__(self):
        self.__maxspeed = 200
        self.__name = "Supercar"
    def drive(self):
        print('driving. maxspeed ' + str(self.__maxspeed))

redcar = Car()
redcar.drive()
redcar.__maxspeed = 10  # This won't alter the variable as it's private.
redcar.drive()

Output:
driving. maxspeed 200
driving. maxspeed 200


Sekarang kita ingin mengubah private variabel:
class Car:
    __maxspeed = 0
    __name = ""
    def __init__(self):
        self.__maxspeed = 200
        self.__name = "Supercar"
    def drive(self):
        print('driving. maxspeed ' + str(self.__maxspeed))
    def setMaxSpeed(self, speed):
        self.__maxspeed = speed

redcar = Car()
redcar.drive()
redcar.setMaxSpeed(320)
redcar.drive()

Output:
driving. maxspeed 200
driving. maxspeed 320

# Posting sebelumnya:

JJJJJJJJJJJJJJJJ

Sunday, April 7, 2024

Python Tutorial - Classes and object - 015

Dalam memahami Python, kita berhadapan dengan konsep "classes." Mari kita mulai asal mula dari mana asal usul classes.  


Image - Bunga liar, hanya ilustrasi.

Ada hal hal penting untuk memahami classes.
1) Statements
ogrammer hanya menulis perintah atau statements untuk berkomunikasi dengan mesin.

2) Fungsi
Dipakai agar "code" lebih modular dan bisa dibaca. Ini adalah grup statements agar code lebih baik.

3) Classes dan Objects.
Jantung dari Object Oriented Programming (OOP) adalah classes. Dengan classes kita menghasilkan Objects.

Objects di sini memiliki dua hal, yaitu: Fungsi (methods) dan Variables. Contoh:
- String variabel bernama 'book' memiliki metode seperti: book.replace() dan book.lower().
- paradigma program ini adalah model real world objects yang disebut "object-oriented programming"


Memahami Classes Dalam Python
Classes menyebabkan kita bisa membuat virtual objects. Objects itu bisa mengandung baik variables (attributes) dan fungsi (methods). Contoh:
Class User:
    name = " "
    def _init_ (self, nme):
         self.name = name

        def sayHello(self):
             print("Hello, my name is " + self.name)

Dalam hal ini:
- User adalah class dengan atribute (variabel) name dan method (function) sayHello.

Class yang kita buat adalah:
james = User("James")
david = User("David")
eric = User("Eric")
------------------------------------------------------

Contoh yang sudah dieksusi akai "main.py":
class User:
    def __init__(self, name):
        self.name = name

    def sayHello(self):
        print("Hello, my name is " + self.name)

# Example usage:
eric = User("Eric")
eric.sayHello()

Output: Hello, my name is Eric
----------------------------------------------------------------

Contoh lain yang sudah diekskusi pakai "main.py"
class Animal:
    def __init__(self,name):
        self.name = name

    def walk(self):
        print(self.name + ' walks.')

duck = Animal('Duck'
duck.walk()

Output: Duck walks.

# Posting sebelumnya:


JJJJJJJJJJJJ


JJJJJJJJJJJJ

Python Tutorial - Writing File - 014

 Kita sudah tahu tetang "reading file," sekarang kita akan memahami writing file dalam Python. 


Image - Grocery di desa

3 hal penting dalam python berkenaan dengan file:
1) Opening file
- memakai fungsi: open(filename, 'w'). Di sini, filename bisa actual file atau file path 
"A file path is a string that specifies the location of a file or directory within a file system."
"An actual file refers to the physical data stored on disk or other storage media. It represents the content and metadata associated with a file."

2) Writing Data.
Setelah opening, kita bisa menggunakan: .write() untuk melakuan input terhadap content yang kita ingini.

3) Closing file.
Jangan lupa melakukan closing file.


Membuat atau Overwriting File dalam Python
filename = "newfile.txt"
myfile = open(filename, 'w')
myfile.write('written with Python\n')
myfile.close()


Appending untuk file yang sudah exist.
filename = "newfile.txt"
myfile = open(filename, 'a')
myfile.write('Appended with Python\n')
myfile.close()

# Posting sebelumnya:

Friday, April 5, 2024

Python Tutorial - Reading File - 013

Memahami File adalah hal penting untuk seorang programmer Python. Ada beberapa metode untuk membaca File dengan Python.


Image - Hanya ilustrasi

Singkatan penting:
  • Read Only (‘r’)
  • Read and Write (‘r+’)
  • Write Only (‘w’)
  • Write and Read (‘w+’)
  • Append Only (‘a’)
  • Append and Read (‘a+’)

Cara yang umum untuk membaca file (reading file) adalah menggunakan fungsi "open()"


Membaca File dalam String.
f = open("file.txt", "r")
lines = f.readlines()
print(lines)

# Posting sebelumnya: