Friday, May 24, 2024

Diploma Python Programming - Module 02 - Alison 03

KIta sekarang masuk ke Python programing untuk Module 2. Dimana di Module ini kita akan bicara tentang "Displaying Text)"


Image - Python programming.

Diploma Python programming, module 02: Displaying Text - Online Course | Alison


Di sini, kita akan melihat tampilan text.

' ' ...> single quote
"  " ...> double quote

print('apa kabar')
print("apa kabar")
output: apa kabar ...> hasilnya sama saja.

pemakaian \n ...> to force new line.
print("Hickory Dock\nThe mouse run up")
Run Python file:
Hickory Dock
The mouse run up


The key points from this module are:
Your text inside prints brackets must be enclosed with quotes, Python accepts both single ‘ and double “ quotes.

For printing on multiple lines you could use multiple print statements or you can use \n which declares a new line for the text that follows it.

You can you triple quotes for the text to display, as you have typed it into the editor this is not a recommended method as most other programming languages don’t support it.

You will make mistakes when programming all programmers make mistakes from typing mistakes to logic mistakes, it is not something to stress over.

Recommend solutions to fixing mistakes you can’t find or having trouble with:- Walk away and come back to it,- Have another coder look at it;- Step though your code with your debugger.

Challege: 
Write following program:

There one was a movie icon.
Who preferred to sleep with the light on.
He learned how to code
A device that sure glowed

Next Lesson: Module 3

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

Dave Gray (10/24)


Kita mulai dengan recursion

angka 1 sampai 9
def add_one(num):

    if (num >= 9):
        return num + 1
   
    total = num + 1
    print(total)

    return add_one(total)

add_one(0)
Run Python File:
1
2
3
4
5
6
7
8
9

sekarang, dari angka 1 sampai 10
def add_one(num):

    if (num >= 9):
        return num + 1
   
    total = num + 1
    print(total)

    return add_one(total)

mynewtotal = add_one(0)
print(mynewtotal)
Run Python File:
1
2
3
4
5
6
7
8
9
10

Coding sederhana dan sedikit enhance untuk Scissor games bisa di lihat Module 10 

Pelajaran lanjutan (11/24) : Python Scope tutorial for Beginners - YouTube

JJJJJJJJJJJJJJJJJJJJ


JJJJJJJJJJJJJJJJJJJJ

Thursday, May 23, 2024

7 Fungsi List yang Harus Dikuasai Python Programmers

Ada 7 fungsi (function) yang penting untuk dikuasai oleh seorang "Python Programmers). Apa itu?

Image - Python functions (credit to Google).

"A list is an ordered collection of items, and it’s one of the fundamental data types in Python."

ini 7 functions penting Python programming. dikutip dari sumber: 7 List Functions Every Python Programmer Should Know (msn.com)

1) The len() Function
Use the len() function to get the number of items inside a list. Here's an example:
my_list = [1, 2, 3, "hello", "rice", "code", 1.2]
list_length = len(my_list)
print(list_length) # returns 7

Tanpa fungsi len(), maka coding akan lebih panjang: 

my_list = [1, 2, 3, "hello", "rice", "code", 1.2]

count = 0

for i in my_list:

    count += 1

print(count) # returns 7

2)  The append() Function

The append() function adds a new item to the end of your list. A good use of this is to add an item to your list after your code fulfills a certain condition. Here's a simple example:

my_list = [1, 2, 3, "hello", "rice", "code", 1.2]

question = input("Do you love Python?: ").lower()

if question == "yes":

    my_list.append("Python is the best!!") # use of the append() function

else:

    my_list.append("You should try Python") # use of the append() function

print(my_list)

This example uses an if statement to add a certain sentence to the initial list based on the user's input.

The append() function can add only one item at a time to your list. Instead of the append function, you can use an operator instead:

my_list = [1, 2, 3, "hello", "rice", "code", 1.2]

my_list += ["Python is the best!!"]

Using the addition operator will ultimately be less efficient because it doesn't modify your initial list. Instead, it creates a new list in memory and adds a new item to it. The append() function modifies your initial list directly.


3)  The extend() Function

The extend() function is a built-in function that adds several items to an existing list at once. It takes in the new items as an argument and modifies your existing list with the argument. Here's how to use the extend() function:

my_list = [1, 2, 3, "hello", "rice", "code", 1.2]

my_list.extend(["item", "muo", 350])

print(my_list)

# prints [1, 2, 3, 'hello', 'rice', 'code', 1.2, 'item', 'muo', 350]

The extend() function can only take one argument, so you should add all your items to a list like the code above.


4. The reverse() Function

The reverse function simply rewrites your list in the reverse order. Here's an example of the reverse function in use:

my_list = [1, 2, 3, "hello", "rice", "code"]

my_list.reverse()

print(my_list) # prints ['code', 'rice', 'hello', 3, 2, 1]

To reverse a list without using the reverse() function, you would need to slice your list. Here's an example:

my_list = [1, 2, 3, "hello", "rice", "code"]

reversed_list = my_list[::-1]

print(reversed_list) # prints ['code', 'rice', 'hello', 3, 2, 1]

In the above example, my_list[::-1] creates a reversed copy of the original list. This means you'll have two lists in memory, which is not the best approach if you simply want to reverse the original list.


JJJJJ


JJJJJJJ

Wednesday, May 22, 2024

Python Beginner - Module 6 - Dave & Alison 01

Sampai juga kita di module ke 6 dan video ke 9 dari Dave Gray, pelajaran Python for beginner. 


Image Python for beginner (credit to Google)

Module 6, Chapter 1

Kita akan bicara tentang data.txt dan cara membukanya.

data.txt
hello
abc
123

kemudian data.txt dibuka file.read
with open('files/data.txt', 'r') as file:
    data = file.read()
    print(data)
Run Python File:
hello
abc
123
----------------------------------------------------

Module 6, Chapter 2
userInput = input('Enter your message : ')

with open('files/data.txt', 'w') as file:
    file.write(userInput)
Run Python File:
Enter your message : apa kabar

data.txt....> berubah:
apa kabar

w menjadi a
userInput = input('Enter your message : ')

with open('files/data.txt', 'a') as file:
    file.write(userInput + '\n')
Run Python File:
Enter your message : test

data.txt....> berubah:
apa kabartest

Run sekali lagi, berubah:
apa kabartest
 test2


Which of the following are file opening modes? Choose three.
- a+
- w+
- rb
-------------------------------------------------


Binary File:
- difficult to access
- not use python directly, but Pickle
- use dictionary : { }
- load ...> to read (r)
- dump ...> to write (w)

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

Classes


Module 6, Chapter .
subclass

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

Module 6, Chapter 5, 6, 7, 8

Di sini kita tentang variable & Methods

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
-------------------------------------------

KIta akan membuat


The followings are the key points from this module:
The following are the file opening modes mentioned in the module:
 w, a, r, w+,a+, r+. -- These are used for text files.
WHILE:
 rb, wb. -- These are used for binary files. 
The pascal case is written as thus -- ThisIsPascalCase.
The following are the variable types mentioned earlier in the module: 
  • Instance variable.
  • Static variable. 
Polymorphism is the ability to accept multiple forms of objects into a specific class.
Every method you construct in an object-oriented approach take "self" as an argument. 







JJJJJJJJJJJJJJJJJJJJJJ

Wednesday, May 15, 2024

Diploma Python Programming - Module 01 - Alison 03

KIta lanjutkan summary dari kursus Alison, dimana topik kali ini adalah programming dengan memakai bahasa Python. Kita juga memakai bahan kursus dari freeCodeCamp.org - YouTube dan berbagai sumber.


Image - Python Programming (credit to Google)

Module 1:
Introduction to Python programming: Python an Introduction - Online Course | Alison




Lesson Summary: 


There are plenty tools for Visual Studio Code (VSC).
GeekTrainer: https://aka.ms/intropythoncode
 



The key points from this module are: 
  • The Basic principle of programming is that it is problem solving.
  • Python is one of the easier programming languages to learn, and many of its tools are free to download and use.
  • One you learn how to code in one programming language it will be easier to learn other programming languages, as the principles are the same.
  • There are a lot of different variations of Python, IronPython, Ipython, CPython to name a few. Most of python’s variations only have some syntax differences but not too many.
  • Comments are very useful in your code to help you or someone else understand:- What your program does,- What a particular line or section of code does;- Why you chose to do something a particular way;- Anything that might be helpful to know if you or someone else looking at the code later and trying to understand it.
  • The # is the symbol to indicate using comments in python.

After completing this module, you will be able to:
  • Identify how to use the print() function to display text.
  • Recognize the different methods of using quotes to contain your text in the print function.
  • Identify process of making mistakes in programming and different solutions to help find and resolve mistakes.

Next Lesson : Module 2 Displaying Text: Displaying Text - Online Course | Alison

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

Dave Gray

Sekarang, kita belajar tentang Functions in Python

kabar() ..> Bukan functions
def kabar():
    print("Apa Kabar")

kabar ()
Run Python File:
Apa Kabar

apa kabar_() ..> functions
def kabar_apa():
    print("Apa Kabar")

kabar_apa()
Run Python File:
Apa Kabar ...> hasilnya sama, jika tanpa functions

Integer
def kabar_apa():
    print("Apa Kabar")

kabar_apa()

def sum(num1, num2):
    print(num1 + num2)

sum(2, 3)
sum(1, 7)
sum(100, 3)
Run Python File:
Apa Kabar
5
8
103

Parameters
def sum(num1, num2):
    print(num1 + num2)


Arguments (2,3...) ...> Functions (sum)
sum(2, 3)
sum(1, 7)
sum(100, 3)

None ...> No False, No True, just None



JJJJJJJJJJJJJJJJ
JJJJJJJJJJJJJJJJJJ

Python Beginner - Module 5 - Dave & Alison 01

 Terus berlanjut, kita sampai ke Module 5 dari Alison Course dan pelajaran ke 7 (video ke 7/24) dari Dave Gray.


Image (credit from Google)

Module & Package

Module:
- a module is a file containing Python code. It can define functions, classes, and variables, and may also include runnable code. 
- If you want to create a module, simply create a .py file with your desired code and import it into your program using the import statement.

Module for string
# A module for string operations

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

Import string
import strings

print(strings.reverseString('hello'))
Run Python File:
olleh


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

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


Guessing Game
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))
        break
    else:
        print('better luck next time')
        score -= 1
Run Python File:
Guess : 1
better luck next time
Guess : 2
better luck next time
Guess : 3
congratulations your guessed right! your score is 8

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


Exceptions/Error
3 errors in Python:
1-Logic
2-Run Time
3-Compiling
------------------------------------------


Errors Practices

Coding dengan hasil benar
a = int(input('one : '))
b = int(input('two : '))

print(a + b)
Run Python File:
one : 1 two : 8 9

Sekarang, hasilnya salah, error
a = int(input('one : '))
b = int(input('two : '))

print(a + b)
Run Python File:
one : 1 two : b ...> error
ValueError: invalid literal for int() with base 10: 'b'

Error Correction
try:
    a = int(input('one : '))
    b = int(input('one : '))
    print(a + b)
except ValueError:
    print('Invalid Input')
Run Python File:
one : 1 one : b Invalid Input

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


String Operations
>>> string = 'string'
>>> string.islower()
True

>>> string = 'STRING'
>>> string.islower()
False

>>> string = 'STRING'
>>> string.isupper() 
True

>>> string = '29'
>>> string.isdigit()
True

>>> 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))
Run Python File:
('ABCDEF', 21)

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


The followings are the key points from this module:
A module is a single file consisting of Python code that can be imported into your program.
WHILE:
A package is basically a directory with Python files (i.e modules) and also can be imported into your program as well. 
The Import function is used to import modules from another file into your code. 
The following are the types of exceptions/errors mentioned:
  • Compiling errors -- These are errors thrown when a program is being compiled or interpreted. e.g Extra space, function misspelling, missing colon or parentheses, etc. 
  • Logical errors -- These are errors in your logic. e.g Calculating and getting a wrong answer. 
  • Run-time errors -- This happens when something is done incorrectly on the part of the user. e.g User entering a string value when the application can only receive integers. 

Some possible errors that you can come across in Python include
  • ValueError
  • ZeroDivisionError
  • TypeError. etc.
The following are string operations that one can run on string values in Python:
  • string.islower -- To check if a string in lower case. 
  • string.isupper -- To check if a string in upper case. 
  • string.isdigit -- To check availability of digits in strings. 
  • string.lower -- To change a string from upper to lower case. 
  • string.upper -- To change a string from lower to upper case. 
  • string.swapcase -- To swap the cases of the strings. 
  • 'e' in string -- Searches for the character "e" in strings. 

Having completed this module, you will be able to: 
  • Discuss file handling and how to write to different types of files. 
  • Explain the basis of classes and subclasses. 
  • Identify the different types of variables and methods. 
  • Explain the concept of polymorphism. 





Lanjutkan ke Module 6:




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

Dave Gray

Kita akan belajar dictionaries dan set.

Dictionaries
band = {
    "vocals": "Plant",
    "guitar": "Page"
}

band2 = dict(vocals="Plant", guitar="Page")

print(band)
print(band2)
Run Python File:
{'vocals': 'Plant', 'guitar': 
'Page'}

{'vocals': 'Plant', 'guitar': 
'Page'}

Print(type(band))
Run Python File:
<class 'dict'>


Sets
# sets

nums = {1, 2, 3, 4}

nums2 = set((1,2,3,4))

print(nums)
print(nums2)
print(type(nums))
print(len(nums))
Run Python File:
{1, 2, 3, 4}        
{1, 2, 3, 4}        
<class 'set'>  ...Type data kita adalah 'set'     
4 ....> ada 4 elemen di data kita (1, 2, 3, 4)


Add element to set
nums = {1, 2, 3, 4}

nums2 = set((1,2,3,4))

print(nums)
print(nums2)
print(type(nums))
print(len(nums))

# add element to set
nums.add(5)
print(nums)
Run Python File:
{1, 2, 3, 4, 5} 
-------------------------------------------------------


Loops:
1) while
2) for 

while, value += 1
value = 1
while value < 10:
    print(value)
    value += 1
Run Python File:
1
2
3
4
5
6
7
8
9

If value == 5, then break
value = 1
while value < 10:
    print(value)
    if value == 5:
        break
    value += 1
Run Python File:
1
2
3
4
5

we change position, and use continue and else
value = 1
while value <= 10:
    value += 1
    if value == 5:
        continue
    print(value)
else:
    print("value is now equal to " + str(value))
Run Python File:
2
3
4
6
7
8
9
10
11
value is now equal to 11


for loop
names = ["Dave","Sara","John"]
for x in names:
    print(x)
Run Python File:
Dave
Sara
Johnx

for x in "Florida"
for x in "Florida":
    print(x)
Run Python File:
F
l
o
r
i
d
a

break 
names = ["Dave","Sara","John"]
for x in names:
    if x == "Sara":
        break
    print(x)
Run Python File:
Dave


Continue
names = ["Dave","Sara","John"]
for x in names:
    if x == "Sara":
        continue
    print(x)
Run Python File:
Dave
John


Untuk game (rps.py) bisa dilihat di video 5: Python User Input & Control Flow | Python tutorial - YouTube

Pelajaran selanjutnya (9/24), Python Function: Python Functions for Beginners | Python tutorial - YouTube




JJJJJJJJJJ