Tuesday, January 2, 2024

Python Basics - Programming Fundamental - Module 3

Ada 5 part pada module 3 ini, yaitu 1)Condition and branching, 2)Loops, 3)Functions, 4)Exception Handling, 5)Objects and classes.


Image 1 - Jembatan Barelang

Part 1: Condition and branching

Comparison operator:
a=6
a==7
6==7 ...> False

i=6
i>5
True

i=5
i>=5
True

i=2
i>=5
False

i=2
i>6
False

i=2
i!=6
True ....> i=2 is not equal to 6

We compare string as well:
"AC/DC"== "Michael Jackson"
False

"AC/DC"!= "Michael Jackson"
True

Branching
If statement
Individual can enter a concert if age 18 or older.
If 17...> False....> can't enter concert
if 19 ...> True ...> enter concert

else ----> to enter other concert or other event

elif condition:

Example:
x = 10

If x>0:
print("x is positive")

else:
print("x is negative or zero")
Output: x is positive.

if condition:
# code to execute if condition is True

else:
# code to execute if condition is False

Logic operators
3 logical operators adalah and, or, not. Tiga logical operators ini dipakai dalam operasi Boolea (True or False).

# Logical AND
x = 5
y = 10
if x > 0 and y > 0:
print("Both x and y are greater than 0")

# Logical OR
x = 5
y = 10
if x > 0 or y < 0:
print("Either x is greater than 0 or y is less than 0")

# Logical NOT
x = True
if not x:
print("x is False")


Image 2 - Pelabuhan ferry, Singapura

Practice quiz:
1) What is the result of the following: 1=2
answer: SyntaxError
note: SyntaxError is error due to code written against grammar rule.

2) What is the output of the following code segment:
i=6
i<5
answer: False

3)What is the result of the following: 5!=5
answer: False

4)What is the output of the following code segment:'a'=='A'
answer: False

5) In the video, if age=18 what would be the result.
answer: Move on
Note: You can't enter

6)In the video what would be the result if we set the variable age as follows: age= -10
answer:go see meat loaf. Move on.

7)What is the result of the following: True or False
answer:True, an or statement is only False if all the Boolean values are False.


Image 3 - Wall at airport in SFO

Part 2: Loops
Loops are used to execute a set of statements repeatedly until a certain condition is met.

Two types of loops: for and while.

for loop:
fruits = ["apple", "banana", "cherry"]
for x in fruits: print(x)
Output:
apple
banana
cherry

while loop:
i = 0
while i < 5: print(i)
i += 1


Image 4 - Ice cream, hanya ilustrasi.

Quiz : Loop

1)What will be the output of the following:
for x in range(0,3):
print(x)
answer:
0
1
2

2) What is the output of the following:
for x in ['A','B','C']:
print(x+'A')
answer:
AA
BA
CA

3)What is the output of the following:
for i,x in enumerate(['A','B','C']):
print(i,x)
answer:
0A
1B
2C

Image 5 - Dua mangga ranum.

Part 3: Functions

A function is a block of code that performs a specific task and can be called multiple times throughout the program.

Functions are defined using the def keyword, followed by the function name and parentheses. 

The code block within the function is indented and can include parameters, which are values passed to the function when it is called. 

Example1:
def print_message():
    print("Hello,world!")
To call this function, you simply need to write its name followed by parentheses: 
print_message()
Output: “Hello, world!”

Example2:
You can also pass arguments to a function by including them in the parentheses when you define the function. Here is an example of a function that takes two arguments and returns their sum:

def add_numbers(x, y):
return x + y
result = add_numbers(3, 5)

print(result) # Output: 8

Example3:
Consider a function named calculate_total that takes two numbers as input (parameters), adds them together, and then produces the sum as the output. Here's how it works:

def calculate_total(a, b): # Parameters: a and b
total = a + b # Task: Addition
return total # Output: Sum of a and b

result = calculate_total(5, 7) # Calling the function with inputs 5 and 7
print(result) # Output: 12


Using built in functions in Python:
len(): Calculates the length of a sequence or collection
  1. string="Hello Hello"
  2. string_length = len(string)
  3. print(string_length) # Output: 11

  1. string="Hello, Hello"
  2. string_length = len(string)
  3. print(string_length) # Output: 12

  1. string="Hello, Hello??"
  2. string_length = len(string)
  3. print(string_length) # Output: 14

  1. list_length = len([1, 2, 3, 4, 5])
  2. print(list_length) # Output: 5

sum(): Adds up the elements in an iterable (list, tuple, and so on)
total = sum([10, 20, 30, 40, 50])
print(total) # Output: 150


max(): Returns the maximum value in an iterable
highest = max([5, 12, 8, 23, 16])
print(highest) # Output: 23

Function Parameters:
  • Parameters are like inputs for functions
  • They go inside parentheses when defining the function
  • Functions can have multiple parameters
Example:
def greet(name):
print("Hello, " + name)

result = greet("Alice")
print(result) # Output: Hello, Alice


Image 6 - Dekorasi Halloween

Practice Quiz: Functions
1)What does the following function return: len(['A','B',1]) ?
answer:3

2)What does the following function return: len([sum([0,0,1])]) ?
answer:1

3)What is the value of list L after the following code segment is run?
L=[1,3,2]
sorted(L)
answer: L:[1,3,2] .....> doesn't change the list L
Note: if we use the following code:
L = [1, 3, 2]
L.sort()
print(L)
This will output: [1, 2, 3]


4)From the video what is the value of c after the following?
c=add1(2)
c=add1(10)
answer:11


5)What is the output of the following lines of code?
def Print(A):
for a in A:
print(a+'1')
Print(['a','b','c'])
answer:
a1
b1
c1


Image 7 - Bangunan unik, Singapura

Part 4: Exception Handling
Exception adalah "alert" bila sesuatu "unexpected" terjadi ketika menjalankan program.

what is the difference between errors and exceptions?

"Well, errors are usually big problems that come from the computer or the system. They often make the program stop working completely." 

"On the other hand, exceptions are more like issues we can control. They happen because of something we did in our code and can usually be fixed, so the program keeps going.""

ZeroDivisionError: This error arises when an attempt is made to divide a number by zero.
a= 10

b= 0
print(a/b).....> error


To correct the error:
a= 10
b= 0
try:
result = 0
print(result)
output: 0


Image 8 - Aneka bunga, Illustration only

Practice Quiz: Exception Handling

1)Why do we use exception handlers?
answer:Catch errors within a program

2)What is the purpose of a try…except statement?
answer:Catch and handle exceptions when an error occurs


Image 9 - Bunga poinsettia, di samping rumah

Part 5: Objects and classes.

Python adalah objec-oriented program. Object itu sendiri punya properties dan methods.

Class seperti blueprint untuk menghasilkan objects. 
class MyClass:
x= 5 To create an object of the class, you can use the following code:
p1 = MyClass()
Now the object p1 has an attribute x with a value of 5. You can access this attribute using dot notation:
print(p1.x)
This will output 5.

Then, kita juga bisa menggunakan method "init()" dalam class untuk menginisiasi attribute object:
class Person:
def __init__(self, name, age):
self.name = name
self.age = age 
Now you can create a Person object with a name and age
p1 = Person("John", 36)

You can access the object’s attributes using dot notation:
print(p1.name)
print(p1.age)

This will output:
John
36


Image 10 - Cuaca tidak cerah

Practice Quiz: Objects and classes.

1) What is the type of the following?
["a"]
answer: list
note: the "a" is surrounded by brackets so it is a list.

2)What does a method do to an object?
answer:Changes or interacts with the object.

3)We create the object:
Circle(3,'blue')
What is the color attribute set to?
answer: blue

4)What is the radius attribute after the following code block is run?
RedCircle=Circle(10,'red')
RedCircle.radius=1
answer:the line of code RedCircle.radius=1 will change the radius.
Note: circle is a class has two attributes: radius and color.

5)What is the radius attribute after the following code block is run?
BlueCircle=Circle(10,'blue')
BlueCircle.add_radius(20)

answer:30
Note:The add_radius method of the Circle class adds the value of the parameter to the radius attribute of the object. Therefore, the radius attribute of the BlueCircle object will be 30.

No comments:

Post a Comment