1. Topic 00
Basic Python Programming – Part 01
Fariz Darari, Ph.D.
Machine Learning Specialization for Geoscientists
In collaboration with FMIPA UI
v04
2. print("Python" + " is " + "cool!")
"Python is easy to use, powerful, and versatile, making it a great choice
for beginners and experts alike." – Pluralsight Platform
2
public class Main {
public static void main(String[] args) {
System.out.println("Hello world!");
}
}
print("Hello world!")
Hello world in Java vs. Python
3. print("Python" + " is " + "cool!")
3
Big names using Python
"Python is easy to use, powerful, and versatile, making it a great choice
for beginners and experts alike." – Pluralsight Platform
4. print("Python" + " is " + "cool!")
"Python is easy to use, powerful, and versatile, making it a great choice
for beginners and experts alike." – Pluralsight Platform
4opencv.org
5. print("Python" + " is " + "cool!")
"Python is easy to use, powerful, and versatile, making it a great choice
for beginners and experts alike." – Pluralsight Platform
5pygame.org
6. print("Python" + " is " + "cool!")
"Python is easy to use, powerful, and versatile, making it a great choice
for beginners and experts alike." – Pluralsight Platform
6http://flask.palletsprojects.com/
7. print("Python" + " is " + "cool!")
"Python is easy to use, powerful, and versatile, making it a great choice
for beginners and experts alike." – Pluralsight Platform
7
matplotlib.org
8. print("Python" + " is " + "cool!")
"Python is easy to use, powerful, and versatile, making it a great choice
for beginners and experts alike." – Pluralsight Platform
8
https://github.com/amueller/word_cloud
9. print("Python" + " is " + "cool!")
9
Top programming languages 2019 by IEEE Spectrum
11. How to install Python the Anaconda way
1. Download Anaconda (which includes Python and
relevant libraries): https://www.anaconda.com/distribution/
2. Run the installer and follow the instructions
3. Run the Spyder editor or Jupyter Notebook and create your first Python program "helloworld.py"
11
Python Setup
12. A more enhanced hello program
12
name = "Dunia" # can be replaced with another value
print("Halo, " + name + "!")
13. A more and more enhanced hello program
13
print("Halo, " + input() + "!")
15. Create a program to calculate the area of a circle!
15
Step 1: Minta nilai jari-jari.
Step 2: Hitung sesuai rumus luas lingkaran.
Step 3: Cetak hasil luasnya.
16. Create a program to calculate the area of a circle!
16
# Step 1: Minta nilai jari-jari.
jari2 = input("Jari-jari: ")
jari2_int = int(jari2)
# Step 2: Hitung sesuai rumus luas lingkaran.
luas = 3.14 * (jari2_int ** 2)
# Step 3: Cetak hasil luasnya.
print(luas)
17. Similar program, now with import math
17
import math
# Step 1: Minta nilai jari-jari.
jari2 = input("Jari-jari: ")
jari2_int = int(jari2)
# Step 2: Hitung sesuai rumus luas lingkaran.
luas = math.pi * (math.pow(jari2_int,2))
# Step 3: Cetak hasil luasnya.
print(luas)
19. Quiz: Create a program to calculate square areas!
19
# Step 1: Minta nilai panjang sisi.
# Step 2: Hitung sesuai rumus luas persegi.
# Step 3: Cetak hasil luasnya.
print(luas)
20. Quiz: Create a program to calculate square areas!
20
# Step 1: Minta nilai panjang sisi.
sisi = input("Sisi: ")
sisi_int = int(sisi)
# Step 2: Hitung sesuai rumus luas persegi.
luas = sisi_int * sisi_int
# Step 3: Cetak hasil luasnya.
print(luas)
21. input("some string")
21
It's a function to print "some string" and
simultaneously ask user for some input.
The function returns a string (sequence of characters).
PS: If not wanting to print anything, just type: input()
22. Assignment
22
The = symbol is not for equality,
it is for assignment:
"Nilai di sebelah kanan diasosiasikan dengan
variabel di sebelah kiri"
Contohnya, x = 1.
PS: x = 1 berbeda dengan x == 1. More on this later.
23. Assignment
23
Example:
my_var = 2 + 3 * 5
• evaluate expression (2+3*5): 17
• change the value of my_var to 17
Example (suppose my_int has value 2):
my_int = my_int + 3
• evaluate expression my_int on RHS to: 2
• evaluate expression 2 + 3: 5
• change the value of my_int to 5
24. Type conversion
24
The int() function as we saw before is for converting string to int.
Why? Because we want to do some math operations!
But what if the string value is not converted to int?
Well, try this out: "1" + "1"
Other type conversions: float() , str()
25. print(var, "some string")
25
Well, it prints.
It may take several elements separated by commas:
- If the element is a string, print as is.
- If variable, print the value of the variable.
Note that after printing, we move to a new line.
26. Save program as module
26
Program yang disimpan disebut dengan Python module,
dan menggunakan file extension .py
Jadi, module adalah sekumpulan instruksi Python.
Module dapat dieksekusi, atau diimpor dalam module
lain (ingat module math).
27. Memberi komentar pada program
27
Komentar atau comment adalah cara untuk semakin
memperjelas alur program kita.
Komentar tidak dapat dijadikan excuse untuk kode
program yang berupa spaghetti code (berantakan).
Komentar pada Python dimulai dengan # (hash),
atau diapit dengan petik tiga """ untuk komentar multibaris.
28. • Variables store and give names to data values
• Data values can be of various types:
• int : -5, 0, 1000000
• float : -2.0, 3.14159
• bool : True, False
• str : "Hello world!", "K3WL"
• list : [1, 2, 3, 4], ["Hello", "world!"], [1, 2, "Hello"], [ ]
• And many more!
• In Python, variables do not have types! This is called: Dynamic typing.
• A type defines two things:
• The internal structure of the type
• Operations you can perform on type
(for example, capitalize() is an operation over type string)
28
Variables and Data Types
29. Name convention
• Dimulai dengan huruf atau underscore _
• Ac_123 is OK, but 123_AB is not.
• Dapat mengandung letters, digits, and underscores
• this_is_an_identifier_123
• Panjang bebas
• Upper and lower case letters are different (case sensitive)
• Length_Of_Rope is not the same as length_of_rope
29
40. 40
Conditionals: Generic Form
if boolean-expression-1:
code-block-1
elif boolean-expression-2:
code-block-2
(as many elif's as you want)
else:
code-block-last
41. 41
Conditionals: Usia SIM
age = 20
if age < 17:
print("Belum bisa punya SIM!")
else:
print("OK, sudah bisa punya SIM.")
42. 42
Conditionals: Usia SIM dengan Input
age = int(input("Usia: "))
if age < 17:
print("Belum bisa punya SIM!")
else:
print("OK, sudah bisa punya SIM.")
48. So far, we have seen (briefly) two kinds of collections:
string and list
For loops can be used to visit each collection's element:
48
For Loops
for element in collection:
code-block
for chr in "string":
print(chr)
for elem in [1,3,5]:
print(elem)
49. Range function
49
• range merepresentasikan urutan angka (integer)
• range memiliki 3 arguments:
– the beginning of the range. Assumed to be 0 if not provided.
– the end of the range, but not inclusive (up to but not including
the number). Required.
– the step of the range. Assumed to be 1 if not provided.
• if only one argument is provided, assumed to be the end value
50. Eksplorasi range
50
for i in range(10):
print(i, end=" ")
print()
for i in range(1,7):
print(i, end=" ")
print()
for i in range(0,30,5):
print(i, end=" ")
print()
for i in range(5,-5,-1):
print(i, end=" ")
51. Lirik lagu menggunakan range
51
syg = "sayang"
for i in range(2):
print("satu")
print("aku", syg, "ibu")
print()
for i in range(2):
print("dua")
print("juga", syg, "ayah")
print()
for i in range(2):
print("tiga")
print(syg, "adik", "kakak")
print()
for i in range(1,4):
print(i)
print(syg, "semuanya")
52. • Functions encapsulate (= membungkus) code blocks
• Why functions? Modularization and reuse!
• You actually have seen examples of functions:
• print()
• input()
• Generic form:
52
Functions
def function-name(parameters):
code-block
return value
53. • Functions encapsulate (= membungkus) code blocks
• Why functions? Modularization and reuse!
• You actually have seen examples of functions:
• print()
• input()
• Generic form:
53
Functions
def function-name(parameters):
code-block
return value
58. • Code made by other people shall be reused!
• Two ways of importing modules (= Python files):
• Generic form: import module_name
import math
print(math.sqrt(4))
• Generic form: from module_name import function_name
from math import sqrt
print(sqrt(4))
58
Imports
59. Make your own module
59
def lame_flirt_generator(name):
print("A: Knock-knock!")
print("B: Who's there?")
print("A: Love.")
print("B: Love who?")
print("A: Love you, " + name + " <3")
import mymodule
mymodule.lame_flirt_generator("Fayriza")
mymodule.py
example.py
60. • String is a sequence of characters, like "Python is cool"
• Each character has an index
• Accessing a character: string[index]
x = "Python is cool"
print(x[10])
• Accessing a substring via slicing: string[start:finish]
print(x[2:6])
60
String
P y t h o n i s c o o l
0 1 2 3 4 5 6 7 8 9 10 11 12 13
61. >>> x = "Python is cool"
>>> "cool" in x # membership
>>> len(x) # length of string x
>>> x + "?" # concatenation
>>> x.upper() # to upper case
>>> x.replace("c", "k") # replace characters in a string
61
String Operations
P y t h o n i s c o o l
0 1 2 3 4 5 6 7 8 9 10 11 12 13
62. >>> x = "Python is cool"
>>> x.split(" ") 62
String Operations: Split
P y t h o n i s c o o l
0 1 2 3 4 5 6 7 8 9 10 11 12 13
P y t h o n
0 1 2 3 4 5
i s
0 1
c o o l
0 1 2 3
x.split(" ")
63. >>> x = "Python is cool"
>>> y = x.split(" ")
>>> ",".join(y) 63
String Operations: Join
P y t h o n , i s , c o o l
0 1 2 3 4 5 6 7 8 9 10 11 12 13
P y t h o n
0 1 2 3 4 5
i s
0 1
c o o l
0 1 2 3
",".join(y)
64. Quiz: Transform the following todo-list
"wake up,turn off alarm,sleep,repeat"
into
"wake up$turn off alarm$sleep$repeat"
64
65. Quiz: Transform the following todo-list
"wake up,turn off alarm,sleep,repeat"
into
"wake up$turn off alarm$sleep$repeat"
65
todo_list = "wake up,turn off alarm,sleep,repeat"
todo_list_split = todo_list.split(",")
todo_list_new = "$".join(todo_list_split)
print(todo_list_new)
66. Topic 00
Basic Python Programming – Part 02
Fariz Darari, Ph.D.
Machine Learning Specialization for Geoscientists
In collaboration with FMIPA UI
v04
67. Recursion
WIKIPEDIA
A function where the solution to a problem depends on
solutions to smaller instances of the same problem
THINK PYTHON BOOK
A function that calls itself
72. Factorial in Python
def faktorial(num): # function header
# 0! or 1! return 1
if (num == 0) or (num == 1):
return 1
73. Factorial in Python
def faktorial(num): # function header
# 0! or 1! return 1
if (num == 0) or (num == 1):
return 1
# do recursion for num > 1
return num * faktorial(num-1)
74. Main components of recursion
def faktorial(num):
# BASE CASE
if (num == 0) or (num == 1):
return 1
# RECURSION CASE
return num * faktorial(num-1)
• Base case
Stopping points for recursion
• Recursion case
Recursion points for smaller problems
76. • You've learned that a string is a sequence of characters.
A list is more generic: a sequence of items!
• List is usually enclosed by square brackets [ ]
• As opposed to strings where the object is fixed (= immutable),
we are free to modify lists (= mutable).
76
Lists
x = [1, 2, 3, 4]
x[0] = 4
x.append(5)
print(x) # [4, 2, 3, 4, 5]
77. 77
List Operations
>>> x = [ "Python", "is", "cool" ]
>>> x.sort() # sort elements in x
>>> x = x[0:2] # slicing
>>> len(x) # length of string x
>>> x = x + ["!"] # concatenation
>>> x[1] = "hot" # replace element at index 1 with "hot"
>>> x.remove("Python") # remove the first occurrence of "Python"
>>> x.pop() # remove the last element
78. It is basically a cool way of generating a list
78
List Comprehension
[expression for-clause condition]
Example:
["Aku tidak akan bolos lagi" for i in range(100)]
79. It is basically a cool way of generating a list
79
List Comprehension
[expression for-clause condition]
Example:
["Aku tidak akan bolos lagi" for i in range(100)]
[i*2 for i in [0,1,2,3,4] if i%2 == 0]
80. It is basically a cool way of generating a list
80
List Comprehension
[expression for-clause condition]
Example:
["Aku tidak akan bolos lagi" for i in range(100)]
[i*2 for i in [0,1,2,3,4] if i%2 == 0]
[i.replace("ai", "uy") for i in ["Santai", "kyk", "di", "pantai"] if len(i) > 3]
81. • Like a list, but you cannot modify/mutate it
• Tuple is usually (but not necessarily) enclosed by parentheses ()
• Everything that works with lists, works with tuples,
except functions modifying the content
• Example:
81
Tuples
x = (0,1,2)
y = 0,1,2 # same as x
x[0] = 2 # this gives an error
83. • As opposed to lists, in sets duplicates are removed and
there is no order of elements!
• Set is of the form { e1, e2, e3, ... }
• Operations include: intersection, union, difference.
• Example:
83
Sets
x = [0,1,2,0,0,1,2,2] # list
y = {0,1,2,0,0,1,2,2} # set
print(x)
print(y) # observe difference list vs set
print(y & {1,2,3}) # intersection
print(y | {1,2,3}) # union
print(y - {1,2,3}) # difference
84. 84
Dictionaries
• Dictionaries map from keys to values!
• Content in dictionaries is not ordered.
• Dictionary is of the form { k1:v1, k2:v2, k3:v3, ... }
• Example:
x = {"indonesia":"jakarta", "germany":"berlin","italy":"rome"}
print(x["indonesia"]) # get value from key
x["japan"] = "tokyo" # add a new key-value pair to dictionary
print(x) # {'italy': 'rome', 'indonesia': 'jakarta', 'germany': 'berlin', 'japan': 'tokyo'}
86. Quiz: What is the output?
Hint: https://www.python-course.eu/python3_dictionaries.php
x = {"a":3, "b":4}
y = {"b":5, "c":1}
print(x)
x.update(y)
print(x)
print(x.keys())
print(x.values())
86
88. Lambda expression
Lambda expressions - also known as anonymous functions - allow you
to create and use a function in a single line. They are useful when
you need a short function that you will only use once.
>>> (lambda x: 3*x + 1)(3)
10
88
89. Quiz: What does this code do?
items = [1, 2, 3, 4, 5]
squared = []
for i in items:
squared.append(i**2)
89
91. Using lambda+map, the squared code can be shortened
items = [1, 2, 3, 4, 5]
squared = list(map(lambda x: x**2, items))
91
92. Lambda expression
Sort a list of names based on the last name.
lst = ["Bob Wick", "John Doe", "Louise Bonn"]
lst.sort(key=lambda name:name.split(" ")[-1])
print(lst) # ['Louise Bonn', 'John Doe', 'Bob Wick']
92
94. • Working with data heavily involves reading and writing!
• Data comes in two types:
• Text: Human readable, encoded in ASCII/UTF-8,
example: .txt, .csv
• Binary: Machine readable, application-specific encoding,
example: .mp3, .mp4, .jpg
94
Input/Output
97. 97
Output
# write mode
x = open("carpe-diem.txt", "w")
x.write("carpendiemn")
x.close()
# append mode
x = open("carpe-diem.txt", "a")
x.write("carpendiemn")
x.close()
Write mode overwrites files,
while append mode does not overwrite files but instead appends at the end of the files' content
99. 99
Errors
• Errors dapat muncul pada program:
syntax errors, runtime errors, logic/semantic errors
• Syntax errors: errors where the program does not follow the rules of Python.
For example: we forgot a colon, we did not provide an end parenthesis
• Runtime errors: errors during program execution.
For example: dividing by 0, accessing a character past the end of a string,
a while loop that never ends.
• Semantic/logic errors: errors due to incorrect algorithms.
For example: Program that translates English to Indonesian,
even though the requirement was from English to Javanese.
100. Quiz: What type error is in this is_even function?
100
def is_even(n):
if n % 2 == 0:
return False
else:
return True
101. 101
Error handling in Python
Basic idea:
• keep watch on a particular section of code
• if we get an exception, raise/throw that exception
(let the exception be known)
• look for a catcher that can handle that kind of exception
• if found, handle it, otherwise let Python handle it (which
usually halts the program)
104. Type conversion feat. exception handling
104
var_a = ["satu", 2, "3"]
for x in var_a:
try:
b = int(x)
print("Berhasil memproses", x)
except ValueError:
print("ValueError saat memproses", x)
105. File accessing feat exception handling
105
# opening a file with exception handling
try:
x = open("this-does-not-exist.py")
x.close()
except FileNotFoundError:
print("Berkas tidak ditemukan!")
# vs.
# opening a file without exception handling
x = open("this-does-not-exist.py")
x.close()
107. • While in functions we encapsulate a set of instructions,
in classes we encapsulate objects!
• A class is a blueprint for objects, specifying:
• Attributes for objects
• Methods for objects
• A class can use other classes as a base, thus inheriting the attributes
and methods of the base class
107
Classes
class class-name(base):
attribute-code-block
method-code-block
108. But why?
• Bundle data attributes and methods into packages (= classes),
hence more organized abstraction
• Divide-and-conquer
• Implement and test behavior of each class separately
• Increased modularity reduces complexity
• Classes make it easy to reuse code
• Class inheritance, for example, allows extending the behavior of (base) class
108
Classes
Color Quantization is the process of reducing number of colors in an image. One reason to do so is to reduce the memory. Sometimes, some devices may have limitation such that it can produce only limited number of colors. In those cases also, color quantization is performed. Here we use k-means clustering for color quantization.
https://docs.opencv.org/4.2.0/d1/d5c/tutorial_py_kmeans_opencv.html
http://irfancen.pythonanywhere.com/
Monumental Java by J. F. Scheltema (1912)
http://www.gutenberg.org/ebooks/42405
Dengan definisi fungsi ini, maka sudah dapat handle kasus faktorial(0) dan faktorial(1)
Bagaimana dengan faktorial(num) dimana num > 1?
Coba base casenya dihilangkan!
- Base case, sesuai dengan namanya, tidak ada pemanggilan fungsi ke dirinya sendiri (= tanpa rekursi).
- Recursion case memanggil dirinya sendiri tapi harus melakukan reduksi masalah ke yang lebih simpel dan mengarah ke base case!
unicode hex value
https://unicode.org/cldr/utility/character.jsp?a=0041
is
cool
Carpe Diem = Take the opportunity and do not think too much about tomorrow!
used to urge someone to make the most of the present time and give little thought to the future
ValueError saat memproses satu
Berhasil memproses 2
Berhasil memproses 3
Berkas tidak ditemukan!
Traceback (most recent call last):
File "C:/Users/Fariz/Downloads/temp.py", line 9, in <module>
x = open("this-does-not-exist.py")
FileNotFoundError: [Errno 2] No such file or directory: 'this-does-not-exist.py'
https://commons.wikimedia.org/wiki/File:Blauwdruk-Ronhaar.jpg
1923 blueprint for shophouse with bakery Ronhaar at the Hammerweg in Ommen, demolished in 2007; the almost flat upper part of the mansard roof is found in the central and eastern Netherlands, but is virtually unknown in the river area and in the southern part of the Netherlands.
and other books
https://stackoverflow.com/questions/tagged/python
Code practice
https://www.hackerearth.com/practice/