SlideShare une entreprise Scribd logo
1  sur  121
Topic 00
Basic Python Programming – Part 01
Fariz Darari, Ph.D.
Machine Learning Specialization for Geoscientists
In collaboration with FMIPA UI
v04
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
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
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
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
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/
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
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
print("Python" + " is " + "cool!")
9
Top programming languages 2019 by IEEE Spectrum
Let's now explore the Python universe!
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
A more enhanced hello program
12
name = "Dunia" # can be replaced with another value
print("Halo, " + name + "!")
A more and more enhanced hello program
13
print("Halo, " + input() + "!")
Create a program to calculate the area of a circle!
14
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.
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)
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)
Quiz: Create a program to calculate square areas!
18
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)
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)
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()
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.
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
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()
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.
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).
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.
• 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
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
Namespace
Namespace adalah tabel yang mengandung pemetaan antara variable
dan nilai datanya.
30
31
Python Variables and Data Types in Real Life
Operators
32
• Integer
• addition and subtraction: +, -
• multiplication: *
• division: /
• integer division: //
• remainder: %
• Floating point
• add, subtract, multiply, divide: +, -, *, /
Boolean operators
33
Operator Precedence
34
Operator Precedence
35
Logical operators: and, or, not
36
Logical operators: and, or, not
37
38
Conditionals and Loops
39
Conditionals: Simple Form
if condition:
if-code
else:
else-code
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
Conditionals: Usia SIM
age = 20
if age < 17:
print("Belum bisa punya SIM!")
else:
print("OK, sudah bisa punya SIM.")
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.")
43
Conditionals: Grading
grade = int(input("Numeric grade: "))
if grade >= 80:
print("A")
elif grade >= 65:
print("B")
elif grade >= 55:
print("C")
else:
print("E")
• Useful for repeating code!
• Two variants:
44
Loops
while boolean-expression:
code-block
for element in collection:
code-block
45
While Loops
x = 5
while x > 0:
print(x)
x -= 1
print("While loop is over now!")
while boolean-expression:
code-block
46
While Loops
while boolean-expression:
code-block
47
While Loops
while boolean-expression:
code-block
while input("Which is the best subject? ") != "Computer Science":
print("Try again!")
print("Of course it is!")
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)
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
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=" ")
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")
• 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
• 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
54
Functions: Celcius to Fahrenheit
def celsius_to_fahrenheit(celsius):
fahrenheit = celsius * 1.8 + 32.0
return fahrenheit
def function-name(parameters):
code-block
return value
55
Functions: Default and Named Parameters
def hello(name_man="Bro", name_woman="Sis"):
print("Hello, " + name_man + " & " + name_woman + "!")
>>> hello()
Hello, Bro & Sis!
>>> hello(name_woman="Lady")
Hello, Bro & Lady!
>>> hello(name_woman="Mbakyu",name_man="Mas")
Hello, Mas & Mbakyu!
56
Functions: Default and Named Parameters
def hello(name_man="Bro", name_woman="Sis"):
print("Hello, " + name_man + " & " + name_woman + "!")
>>> hello()
Hello, Bro & Sis!
>>> hello(name_woman="Lady")
Hello, Bro & Lady!
>>> hello(name_woman="Mbakyu",name_man="Mas")
Hello, Mas & Mbakyu!
57
Functions: Default and Named Parameters
def hello(name_man="Bro", name_woman="Sis"):
print("Hello, " + name_man + " & " + name_woman + "!")
>>> hello()
Hello, Bro & Sis!
>>> hello(name_woman="Lady")
Hello, Bro & Lady!
>>> hello(name_woman="Mbakyu",name_man="Mas")
Hello, Mas & Mbakyu!
• 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
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
• 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
>>> 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
>>> 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(" ")
>>> 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)
Quiz: Transform the following todo-list
"wake up,turn off alarm,sleep,repeat"
into
"wake up$turn off alarm$sleep$repeat"
64
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)
Topic 00
Basic Python Programming – Part 02
Fariz Darari, Ph.D.
Machine Learning Specialization for Geoscientists
In collaboration with FMIPA UI
v04
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
Factorial
Mathematical definition:
n! = n x (n – 1) x (n – 2) x . . . . . . x 2 x 1
Example:
5! = 5 x 4 x 3 x 2 x 1 = 120
Factorial
Recursive definition:
n! = n x (n – 1)!
Example:
5! = 5 x 4!
Factorial
Recursive definition:
n! = n x (n – 1)!
Example:
5! = 5 x 4!
PS: Where 0! = 1 and 1! = 1
Factorial in Python
def faktorial(num): # function header
Factorial in Python
def faktorial(num): # function header
# 0! or 1! return 1
if (num == 0) or (num == 1):
return 1
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)
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
75
• 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
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
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)]
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]
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]
• 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
82
• 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
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'}
85
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
Dictionary in Real Life
87
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
Quiz: What does this code do?
items = [1, 2, 3, 4, 5]
squared = []
for i in items:
squared.append(i**2)
89
Map
map(function_to_apply, list_of_inputs)
90
Map applies function_to_apply to all the items in list_of_inputs
Using lambda+map, the squared code can be shortened
items = [1, 2, 3, 4, 5]
squared = list(map(lambda x: x**2, items))
91
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
93
• 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
python
is
cool
95
Input
cool.txt
x = open("cool.txt", "r") # read mode
y = x.read() # read the whole content
print(y)
x.close()
python
is
cool
96
Input
cool.txt
x = open("cool.txt", "r")
# read line by line, printing if not containing "py"
for line in x:
if not ("py" in line):
print(line, end="")
x.close()
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
Input and Output in Real Life
98
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.
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
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)
102
print(a)
try:
print(a)
except NameError:
print("Terjadi error!")
VS
Compare
Generic form
103
try:
code block
except a_particular_error:
code block
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)
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()
106
• 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
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
109
Object-oriented programming:
Classes as groups of similar objects
110
Object-oriented programming:
Classes as groups of similar objects
class Cat class Rabbit
class Person:
is_mortal = True
def __init__(self, first, last):
self.firstname = first
self.lastname = last
def describe(self):
return self.firstname + " " + self.lastname
def smiles(self):
return ":-)"
111
Classes: Person
class class-name(base):
attribute-code-block
method-code-block
# code continuation..
guido = Person("Guido","Van Rossum")
print(guido.describe())
print(guido.smiles())
print(guido.is_mortal)
112
Classes: Person & Employee
class class-name(base):
attribute-code-block
method-code-block
# extending code for class Person
class Employee(Person):
def __init__(self, first, last, staffnum):
Person.__init__(self, first, last)
self.staffnum = staffnum
def describe(self):
return self.lastname + ", " + str(self.staffnum)
jg = Employee("James", "Gosling", 5991)
print(jg.describe())
print(jg.smiles())
print(jg.is_mortal)
113
Quiz: What is the output?
class Student:
def __init__(self, name):
self.name = name
self.attend = 0
def says_hi(self):
print(self.name + ": Hi!")
ali = Student("Ali")
ali.says_hi()
ali.attend += 1
print(ali.attend)
bob = Student("Bob")
bob.says_hi()
print(bob.attend)
Class in Real Life
114
What's next: Learning from books
115
https://greenteapress.com/wp/think-python-2e/
What's next: Learning from community
116https://stackoverflow.com/questions/tagged/python
What's next: Learning from community
117https://www.hackerearth.com/practice/
What's next: Learning from academics
118https://www.coursera.org/courses?query=python
What's next: Learning from me :-)
119https://www.slideshare.net/fadirra/recursion-in-python
What's next: Learning from me :-)
120https://twitter.com/mrlogix/status/1204566990075002880
121
Food pack is ready,
enjoy your journey!

Contenu connexe

Tendances

Tendances (20)

Introduction to python programming
Introduction to python programmingIntroduction to python programming
Introduction to python programming
 
Python in 30 minutes!
Python in 30 minutes!Python in 30 minutes!
Python in 30 minutes!
 
Python programming
Python  programmingPython  programming
Python programming
 
Python - the basics
Python - the basicsPython - the basics
Python - the basics
 
Regular expressions in Python
Regular expressions in PythonRegular expressions in Python
Regular expressions in Python
 
Introduction to python
Introduction to pythonIntroduction to python
Introduction to python
 
Functions in Python
Functions in PythonFunctions in Python
Functions in Python
 
Python variables and data types.pptx
Python variables and data types.pptxPython variables and data types.pptx
Python variables and data types.pptx
 
Python
PythonPython
Python
 
Python basics
Python basicsPython basics
Python basics
 
Introduction to Python Basics Programming
Introduction to Python Basics ProgrammingIntroduction to Python Basics Programming
Introduction to Python Basics Programming
 
Beginning Python Programming
Beginning Python ProgrammingBeginning Python Programming
Beginning Python Programming
 
Chapter 1 - INTRODUCTION TO PYTHON -MAULIK BORSANIYA
Chapter 1 - INTRODUCTION TO PYTHON -MAULIK BORSANIYAChapter 1 - INTRODUCTION TO PYTHON -MAULIK BORSANIYA
Chapter 1 - INTRODUCTION TO PYTHON -MAULIK BORSANIYA
 
Introduction to-python
Introduction to-pythonIntroduction to-python
Introduction to-python
 
Python programming introduction
Python programming introductionPython programming introduction
Python programming introduction
 
Python
PythonPython
Python
 
Basic Concepts in Python
Basic Concepts in PythonBasic Concepts in Python
Basic Concepts in Python
 
Python Basics | Python Tutorial | Edureka
Python Basics | Python Tutorial | EdurekaPython Basics | Python Tutorial | Edureka
Python Basics | Python Tutorial | Edureka
 
Variables & Data Types In Python | Edureka
Variables & Data Types In Python | EdurekaVariables & Data Types In Python | Edureka
Variables & Data Types In Python | Edureka
 
Phython Programming Language
Phython Programming LanguagePhython Programming Language
Phython Programming Language
 

Similaire à Basic Python Programming: Part 01 and Part 02

Python Interview Questions | Python Interview Questions And Answers | Python ...
Python Interview Questions | Python Interview Questions And Answers | Python ...Python Interview Questions | Python Interview Questions And Answers | Python ...
Python Interview Questions | Python Interview Questions And Answers | Python ...
Simplilearn
 
Introduction to Python 01-08-2023.pon by everyone else. . Hence, they must be...
Introduction to Python 01-08-2023.pon by everyone else. . Hence, they must be...Introduction to Python 01-08-2023.pon by everyone else. . Hence, they must be...
Introduction to Python 01-08-2023.pon by everyone else. . Hence, they must be...
DRVaibhavmeshram1
 
ISTA 130 Lab 21 Turtle ReviewHere are all of the turt.docx
ISTA 130 Lab 21 Turtle ReviewHere are all of the turt.docxISTA 130 Lab 21 Turtle ReviewHere are all of the turt.docx
ISTA 130 Lab 21 Turtle ReviewHere are all of the turt.docx
priestmanmable
 

Similaire à Basic Python Programming: Part 01 and Part 02 (20)

Functions, List and String methods
Functions, List and String methodsFunctions, List and String methods
Functions, List and String methods
 
Python basics
Python basicsPython basics
Python basics
 
Python basics
Python basicsPython basics
Python basics
 
Python basics
Python basicsPython basics
Python basics
 
Python basics
Python basicsPython basics
Python basics
 
Python basics
Python basicsPython basics
Python basics
 
Python basics
Python basicsPython basics
Python basics
 
Python basics
Python basicsPython basics
Python basics
 
Learn Python 3 for absolute beginners
Learn Python 3 for absolute beginnersLearn Python 3 for absolute beginners
Learn Python 3 for absolute beginners
 
Python Interview Questions | Python Interview Questions And Answers | Python ...
Python Interview Questions | Python Interview Questions And Answers | Python ...Python Interview Questions | Python Interview Questions And Answers | Python ...
Python Interview Questions | Python Interview Questions And Answers | Python ...
 
Basic concept of Python.pptx includes design tool, identifier, variables.
Basic concept of Python.pptx includes design tool, identifier, variables.Basic concept of Python.pptx includes design tool, identifier, variables.
Basic concept of Python.pptx includes design tool, identifier, variables.
 
Python cheat-sheet
Python cheat-sheetPython cheat-sheet
Python cheat-sheet
 
Pythonppt28 11-18
Pythonppt28 11-18Pythonppt28 11-18
Pythonppt28 11-18
 
FUNDAMENTALS OF PYTHON LANGUAGE
 FUNDAMENTALS OF PYTHON LANGUAGE  FUNDAMENTALS OF PYTHON LANGUAGE
FUNDAMENTALS OF PYTHON LANGUAGE
 
Introduction to Python 01-08-2023.pon by everyone else. . Hence, they must be...
Introduction to Python 01-08-2023.pon by everyone else. . Hence, they must be...Introduction to Python 01-08-2023.pon by everyone else. . Hence, they must be...
Introduction to Python 01-08-2023.pon by everyone else. . Hence, they must be...
 
ISTA 130 Lab 21 Turtle ReviewHere are all of the turt.docx
ISTA 130 Lab 21 Turtle ReviewHere are all of the turt.docxISTA 130 Lab 21 Turtle ReviewHere are all of the turt.docx
ISTA 130 Lab 21 Turtle ReviewHere are all of the turt.docx
 
lecture 2.pptx
lecture 2.pptxlecture 2.pptx
lecture 2.pptx
 
An Introduction : Python
An Introduction : PythonAn Introduction : Python
An Introduction : Python
 
Basics of Python Programming
Basics of Python ProgrammingBasics of Python Programming
Basics of Python Programming
 
Python Workshop - Learn Python the Hard Way
Python Workshop - Learn Python the Hard WayPython Workshop - Learn Python the Hard Way
Python Workshop - Learn Python the Hard Way
 

Plus de Fariz Darari

Plus de Fariz Darari (20)

Data X Museum - Hari Museum Internasional 2022 - WMID
Data X Museum - Hari Museum Internasional 2022 - WMIDData X Museum - Hari Museum Internasional 2022 - WMID
Data X Museum - Hari Museum Internasional 2022 - WMID
 
[PUBLIC] quiz-01-midterm-solutions.pdf
[PUBLIC] quiz-01-midterm-solutions.pdf[PUBLIC] quiz-01-midterm-solutions.pdf
[PUBLIC] quiz-01-midterm-solutions.pdf
 
Free AI Kit - Game Theory
Free AI Kit - Game TheoryFree AI Kit - Game Theory
Free AI Kit - Game Theory
 
Neural Networks and Deep Learning: An Intro
Neural Networks and Deep Learning: An IntroNeural Networks and Deep Learning: An Intro
Neural Networks and Deep Learning: An Intro
 
NLP guest lecture: How to get text to confess what knowledge it has
NLP guest lecture: How to get text to confess what knowledge it hasNLP guest lecture: How to get text to confess what knowledge it has
NLP guest lecture: How to get text to confess what knowledge it has
 
Supply and Demand - AI Talents
Supply and Demand - AI TalentsSupply and Demand - AI Talents
Supply and Demand - AI Talents
 
AI in education done properly
AI in education done properlyAI in education done properly
AI in education done properly
 
Artificial Neural Networks: Pointers
Artificial Neural Networks: PointersArtificial Neural Networks: Pointers
Artificial Neural Networks: Pointers
 
Open Tridharma at ICACSIS 2019
Open Tridharma at ICACSIS 2019Open Tridharma at ICACSIS 2019
Open Tridharma at ICACSIS 2019
 
Defense Slides of Avicenna Wisesa - PROWD
Defense Slides of Avicenna Wisesa - PROWDDefense Slides of Avicenna Wisesa - PROWD
Defense Slides of Avicenna Wisesa - PROWD
 
Seminar Laporan Aktualisasi - Tridharma Terbuka - Fariz Darari
Seminar Laporan Aktualisasi - Tridharma Terbuka - Fariz DarariSeminar Laporan Aktualisasi - Tridharma Terbuka - Fariz Darari
Seminar Laporan Aktualisasi - Tridharma Terbuka - Fariz Darari
 
Foundations of Programming - Java OOP
Foundations of Programming - Java OOPFoundations of Programming - Java OOP
Foundations of Programming - Java OOP
 
Recursion in Python
Recursion in PythonRecursion in Python
Recursion in Python
 
[ISWC 2013] Completeness statements about RDF data sources and their use for ...
[ISWC 2013] Completeness statements about RDF data sources and their use for ...[ISWC 2013] Completeness statements about RDF data sources and their use for ...
[ISWC 2013] Completeness statements about RDF data sources and their use for ...
 
Testing in Python: doctest and unittest (Updated)
Testing in Python: doctest and unittest (Updated)Testing in Python: doctest and unittest (Updated)
Testing in Python: doctest and unittest (Updated)
 
Testing in Python: doctest and unittest
Testing in Python: doctest and unittestTesting in Python: doctest and unittest
Testing in Python: doctest and unittest
 
Dissertation Defense - Managing and Consuming Completeness Information for RD...
Dissertation Defense - Managing and Consuming Completeness Information for RD...Dissertation Defense - Managing and Consuming Completeness Information for RD...
Dissertation Defense - Managing and Consuming Completeness Information for RD...
 
Research Writing - 2018.07.18
Research Writing - 2018.07.18Research Writing - 2018.07.18
Research Writing - 2018.07.18
 
KOI - Knowledge Of Incidents - SemEval 2018
KOI - Knowledge Of Incidents - SemEval 2018KOI - Knowledge Of Incidents - SemEval 2018
KOI - Knowledge Of Incidents - SemEval 2018
 
Comparing Index Structures for Completeness Reasoning
Comparing Index Structures for Completeness ReasoningComparing Index Structures for Completeness Reasoning
Comparing Index Structures for Completeness Reasoning
 

Dernier

%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
masabamasaba
 
Love witchcraft +27768521739 Binding love spell in Sandy Springs, GA |psychic...
Love witchcraft +27768521739 Binding love spell in Sandy Springs, GA |psychic...Love witchcraft +27768521739 Binding love spell in Sandy Springs, GA |psychic...
Love witchcraft +27768521739 Binding love spell in Sandy Springs, GA |psychic...
chiefasafspells
 
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
masabamasaba
 

Dernier (20)

WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital TransformationWSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
 
WSO2CON 2024 - WSO2's Digital Transformation Journey with Choreo: A Platforml...
WSO2CON 2024 - WSO2's Digital Transformation Journey with Choreo: A Platforml...WSO2CON 2024 - WSO2's Digital Transformation Journey with Choreo: A Platforml...
WSO2CON 2024 - WSO2's Digital Transformation Journey with Choreo: A Platforml...
 
WSO2CON 2024 - Navigating API Complexity: REST, GraphQL, gRPC, Websocket, Web...
WSO2CON 2024 - Navigating API Complexity: REST, GraphQL, gRPC, Websocket, Web...WSO2CON 2024 - Navigating API Complexity: REST, GraphQL, gRPC, Websocket, Web...
WSO2CON 2024 - Navigating API Complexity: REST, GraphQL, gRPC, Websocket, Web...
 
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
 
WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...
WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...
WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...
 
WSO2CON 2024 - Freedom First—Unleashing Developer Potential with Open Source
WSO2CON 2024 - Freedom First—Unleashing Developer Potential with Open SourceWSO2CON 2024 - Freedom First—Unleashing Developer Potential with Open Source
WSO2CON 2024 - Freedom First—Unleashing Developer Potential with Open Source
 
Love witchcraft +27768521739 Binding love spell in Sandy Springs, GA |psychic...
Love witchcraft +27768521739 Binding love spell in Sandy Springs, GA |psychic...Love witchcraft +27768521739 Binding love spell in Sandy Springs, GA |psychic...
Love witchcraft +27768521739 Binding love spell in Sandy Springs, GA |psychic...
 
Artyushina_Guest lecture_YorkU CS May 2024.pptx
Artyushina_Guest lecture_YorkU CS May 2024.pptxArtyushina_Guest lecture_YorkU CS May 2024.pptx
Artyushina_Guest lecture_YorkU CS May 2024.pptx
 
WSO2Con2024 - Enabling Transactional System's Exponential Growth With Simplicity
WSO2Con2024 - Enabling Transactional System's Exponential Growth With SimplicityWSO2Con2024 - Enabling Transactional System's Exponential Growth With Simplicity
WSO2Con2024 - Enabling Transactional System's Exponential Growth With Simplicity
 
%in Benoni+277-882-255-28 abortion pills for sale in Benoni
%in Benoni+277-882-255-28 abortion pills for sale in Benoni%in Benoni+277-882-255-28 abortion pills for sale in Benoni
%in Benoni+277-882-255-28 abortion pills for sale in Benoni
 
%in Midrand+277-882-255-28 abortion pills for sale in midrand
%in Midrand+277-882-255-28 abortion pills for sale in midrand%in Midrand+277-882-255-28 abortion pills for sale in midrand
%in Midrand+277-882-255-28 abortion pills for sale in midrand
 
%in kempton park+277-882-255-28 abortion pills for sale in kempton park
%in kempton park+277-882-255-28 abortion pills for sale in kempton park %in kempton park+277-882-255-28 abortion pills for sale in kempton park
%in kempton park+277-882-255-28 abortion pills for sale in kempton park
 
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
 
%in Rustenburg+277-882-255-28 abortion pills for sale in Rustenburg
%in Rustenburg+277-882-255-28 abortion pills for sale in Rustenburg%in Rustenburg+277-882-255-28 abortion pills for sale in Rustenburg
%in Rustenburg+277-882-255-28 abortion pills for sale in Rustenburg
 
tonesoftg
tonesoftgtonesoftg
tonesoftg
 
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
 
WSO2CON 2024 - Does Open Source Still Matter?
WSO2CON 2024 - Does Open Source Still Matter?WSO2CON 2024 - Does Open Source Still Matter?
WSO2CON 2024 - Does Open Source Still Matter?
 
Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...
Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...
Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...
 
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
 
VTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learnVTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learn
 

Basic Python Programming: Part 01 and Part 02

  • 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
  • 10. Let's now explore the Python universe!
  • 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() + "!")
  • 14. Create a program to calculate the area of a circle! 14
  • 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)
  • 18. Quiz: Create a program to calculate square areas! 18
  • 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
  • 30. Namespace Namespace adalah tabel yang mengandung pemetaan antara variable dan nilai datanya. 30
  • 31. 31 Python Variables and Data Types in Real Life
  • 32. Operators 32 • Integer • addition and subtraction: +, - • multiplication: * • division: / • integer division: // • remainder: % • Floating point • add, subtract, multiply, divide: +, -, *, /
  • 39. 39 Conditionals: Simple Form if condition: if-code else: else-code
  • 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.")
  • 43. 43 Conditionals: Grading grade = int(input("Numeric grade: ")) if grade >= 80: print("A") elif grade >= 65: print("B") elif grade >= 55: print("C") else: print("E")
  • 44. • Useful for repeating code! • Two variants: 44 Loops while boolean-expression: code-block for element in collection: code-block
  • 45. 45 While Loops x = 5 while x > 0: print(x) x -= 1 print("While loop is over now!") while boolean-expression: code-block
  • 47. 47 While Loops while boolean-expression: code-block while input("Which is the best subject? ") != "Computer Science": print("Try again!") print("Of course it is!")
  • 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
  • 54. 54 Functions: Celcius to Fahrenheit def celsius_to_fahrenheit(celsius): fahrenheit = celsius * 1.8 + 32.0 return fahrenheit def function-name(parameters): code-block return value
  • 55. 55 Functions: Default and Named Parameters def hello(name_man="Bro", name_woman="Sis"): print("Hello, " + name_man + " & " + name_woman + "!") >>> hello() Hello, Bro & Sis! >>> hello(name_woman="Lady") Hello, Bro & Lady! >>> hello(name_woman="Mbakyu",name_man="Mas") Hello, Mas & Mbakyu!
  • 56. 56 Functions: Default and Named Parameters def hello(name_man="Bro", name_woman="Sis"): print("Hello, " + name_man + " & " + name_woman + "!") >>> hello() Hello, Bro & Sis! >>> hello(name_woman="Lady") Hello, Bro & Lady! >>> hello(name_woman="Mbakyu",name_man="Mas") Hello, Mas & Mbakyu!
  • 57. 57 Functions: Default and Named Parameters def hello(name_man="Bro", name_woman="Sis"): print("Hello, " + name_man + " & " + name_woman + "!") >>> hello() Hello, Bro & Sis! >>> hello(name_woman="Lady") Hello, Bro & Lady! >>> hello(name_woman="Mbakyu",name_man="Mas") Hello, Mas & Mbakyu!
  • 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
  • 68. Factorial Mathematical definition: n! = n x (n – 1) x (n – 2) x . . . . . . x 2 x 1 Example: 5! = 5 x 4 x 3 x 2 x 1 = 120
  • 69. Factorial Recursive definition: n! = n x (n – 1)! Example: 5! = 5 x 4!
  • 70. Factorial Recursive definition: n! = n x (n – 1)! Example: 5! = 5 x 4! PS: Where 0! = 1 and 1! = 1
  • 71. Factorial in Python def faktorial(num): # function header
  • 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
  • 75. 75
  • 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
  • 82. 82
  • 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'}
  • 85. 85
  • 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
  • 90. Map map(function_to_apply, list_of_inputs) 90 Map applies function_to_apply to all the items in list_of_inputs
  • 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
  • 93. 93
  • 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
  • 95. python is cool 95 Input cool.txt x = open("cool.txt", "r") # read mode y = x.read() # read the whole content print(y) x.close()
  • 96. python is cool 96 Input cool.txt x = open("cool.txt", "r") # read line by line, printing if not containing "py" for line in x: if not ("py" in line): print(line, end="") x.close()
  • 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
  • 98. Input and Output in Real Life 98
  • 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)
  • 103. Generic form 103 try: code block except a_particular_error: code block
  • 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()
  • 106. 106
  • 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
  • 109. 109 Object-oriented programming: Classes as groups of similar objects
  • 110. 110 Object-oriented programming: Classes as groups of similar objects class Cat class Rabbit
  • 111. class Person: is_mortal = True def __init__(self, first, last): self.firstname = first self.lastname = last def describe(self): return self.firstname + " " + self.lastname def smiles(self): return ":-)" 111 Classes: Person class class-name(base): attribute-code-block method-code-block # code continuation.. guido = Person("Guido","Van Rossum") print(guido.describe()) print(guido.smiles()) print(guido.is_mortal)
  • 112. 112 Classes: Person & Employee class class-name(base): attribute-code-block method-code-block # extending code for class Person class Employee(Person): def __init__(self, first, last, staffnum): Person.__init__(self, first, last) self.staffnum = staffnum def describe(self): return self.lastname + ", " + str(self.staffnum) jg = Employee("James", "Gosling", 5991) print(jg.describe()) print(jg.smiles()) print(jg.is_mortal)
  • 113. 113 Quiz: What is the output? class Student: def __init__(self, name): self.name = name self.attend = 0 def says_hi(self): print(self.name + ": Hi!") ali = Student("Ali") ali.says_hi() ali.attend += 1 print(ali.attend) bob = Student("Bob") bob.says_hi() print(bob.attend)
  • 114. Class in Real Life 114
  • 115. What's next: Learning from books 115 https://greenteapress.com/wp/think-python-2e/
  • 116. What's next: Learning from community 116https://stackoverflow.com/questions/tagged/python
  • 117. What's next: Learning from community 117https://www.hackerearth.com/practice/
  • 118. What's next: Learning from academics 118https://www.coursera.org/courses?query=python
  • 119. What's next: Learning from me :-) 119https://www.slideshare.net/fadirra/recursion-in-python
  • 120. What's next: Learning from me :-) 120https://twitter.com/mrlogix/status/1204566990075002880
  • 121. 121 Food pack is ready, enjoy your journey!

Notes de l'éditeur

  1. https://www.pexels.com/photo/close-up-colors-object-pastel-114119/
  2. 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
  3. http://irfancen.pythonanywhere.com/
  4. Monumental Java by J. F. Scheltema (1912) http://www.gutenberg.org/ebooks/42405
  5. web, enterprise/desktop, embedded
  6. Credits: https://docs.microsoft.com/en-us/media/common/i_get-started.svg https://emojiisland.com/products/snake-emoji-icon https://www.pexels.com/photo/sky-space-milky-way-stars-110854/
  7. Ask for input name first
  8. more precise, reuse functions
  9. RHS = Right Hand Side
  10. named parameter end= may alter the new line behavior
  11. http://infohost.nmt.edu/tcc/help/pubs/lang/pytut27/web/namespace-dict.html
  12. https://www.pexels.com/photo/aroma-aromatic-assortment-bottles-531446/
  13. Multiple assignment = first on right is associated to first on left, second on right to second on left, etc
  14. Multiple assignment = first on right is associated to first on left, second on right to second on left, etc
  15. Shapes' meaning: https://support.office.com/en-us/article/create-a-basic-flowchart-e207d975-4a51-4bfa-a356-eeec314bd276 Sumber: https://www.bbc.co.uk/education/guides/z3bq7ty/revision/3
  16. https://www.tutorialspoint.com/python/python_if_else.htm
  17. .lower() for case-insensitive
  18. Collection: Store many elements
  19. 0 1 2 3 4 5 6 7 8 9 1 2 3 4 5 6 0 5 10 15 20 25 5 4 3 2 1 0 -1 -2 -3 -4
  20. Modularization: So that your code can be better managed, unlike one huge program -> small functions, glued into one
  21. Modularization: So that your code can be better managed, unlike one huge program -> small functions, glued into one
  22. Have to be in same folder
  23. start: where we start taking the substring finish: the index one after we end the substring
  24. or with replace: todo_list.replace(',','$')
  25. https://www.pexels.com/photo/close-up-colors-object-pastel-114119/
  26. Some issue, this goes infinitely!
  27. It's defined that 0! = 1
  28. Dengan definisi fungsi ini, maka sudah dapat handle kasus faktorial(0) dan faktorial(1) Bagaimana dengan faktorial(num) dimana num > 1?
  29. 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!
  30. https://blog.kotlin-academy.com/excluded-item-use-tail-recursion-to-achieve-efficient-recurrence-364593eed969
  31. Items can be anything!
  32. Final result: ['hot']
  33. [0, 4, 8] ['Santuy', 'pantuy']
  34. [0, 4, 8] ['Santuy', 'pantuy']
  35. [0, 4, 8] ['Santuy', 'pantuy']
  36. http://www.addletters.com/pictures/bart-simpson-generator/6680520.htm#.Xi0_QGgza00
  37. [0, 1, 2, 0, 0, 1, 2, 2] {0, 1, 2} {1, 2} {0, 1, 2, 3} {0}
  38. https://medium.com/@GalarnykMichael/python-basics-10-dictionaries-and-dictionary-methods-4e9efa70f5b9
  39. {'a': 3, 'b': 4} {'a': 3, 'b': 5, 'c': 1} dict_keys(['a', 'b', 'c']) dict_values([3, 5, 1])
  40. Map from word to (= key) meaning (= value) https://www.pexels.com/photo/blur-book-close-up-data-270233/
  41. https://www.youtube.com/watch?v=25ovCm9jKfA
  42. https://book.pythontips.com/en/latest/map_filter.html
  43. https://book.pythontips.com/en/latest/map_filter.html
  44. https://book.pythontips.com/en/latest/map_filter.html
  45. unicode hex value https://unicode.org/cldr/utility/character.jsp?a=0041
  46. is cool
  47. 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
  48. https://www.pexels.com/photo/fashion-woman-girl-women-34075/
  49. Semantic error
  50. ValueError saat memproses satu Berhasil memproses 2 Berhasil memproses 3
  51. 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'
  52. https://ocw.mit.edu/courses/electrical-engineering-and-computer-science/6-0001-introduction-to-computer-science-and-programming-in-python-fall-2016/lecture-slides-code/MIT6_0001F16_Lec8.pdf
  53. undescribed rabbit: 2 years old, grey https://ocw.mit.edu/courses/electrical-engineering-and-computer-science/6-0001-introduction-to-computer-science-and-programming-in-python-fall-2016/lecture-slides-code/MIT6_0001F16_Lec9.pdf
  54. undescribed rabbit: 2 years old, grey https://ocw.mit.edu/courses/electrical-engineering-and-computer-science/6-0001-introduction-to-computer-science-and-programming-in-python-fall-2016/lecture-slides-code/MIT6_0001F16_Lec9.pdf
  55. Guido Van Rossum :-) True https://www.python-course.eu/python3_inheritance.php
  56. Gosling, 5991 :-) True https://www.python-course.eu/python3_inheritance.php
  57. Ali: Hi! 1 Bob: Hi! 0
  58. 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.
  59. and other books
  60. https://stackoverflow.com/questions/tagged/python
  61. Code practice https://www.hackerearth.com/practice/
  62. https://www.coursera.org/courses?query=python
  63. https://www.slideshare.net/fadirra/recursion-in-python
  64. https://twitter.com/mrlogix/status/1204566990075002880
  65. https://www.pexels.com/photo/baked-basket-blur-bread-350350/