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