dosen.stts.edudosen.stts.edu/erick/wp-content/uploads/2015/09/pyth… · web viewdosen.stts.edu
Post on 10-Feb-2018
242 Views
Preview:
TRANSCRIPT
Praktikum Sistem 1
Bab 6PYTHON - Basics
Basic SyntaxMode pemrograman script dari python yaitu invoking
dari interpreter dengan parameter sebuah script yang dimulai dengan eksekusi script dan berlanjut sampai selesai. Ketika script selesai, interpreter tidak lagi aktif. Python file menggunakan ekstensi .py.
Contoh:
#!/usr/bin/python
print "Hello, Python!";
Untuk menjalankan program, ketikan “python namafile.py”.
- Multi-Line
Multi-line pada python dapat menggunakan tanda \
Contoh:
total = item_one + \ item_two + \
item_three
Praktikum Sistem 2
Statement yang berada pada [], {}, or () tidak memerlukan tanda \
Contoh:
days = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday']
- Quotation di Phyton
Python menerima quote single (‘), double (“), dan triple (‘’’ or “””) untuk menunjukan string, dengan syarat jenis awal mula kutipan harus sama dengan jenis akhir kutipan. Quote triple dapat digunakan untuk multipleline.
Contoh:
word = 'word'sentence = "This is a sentence."paragraph = """This is a paragraph. It ismade up of multiple lines and sentences."""
- Comments di Phyton
Untuk memberikan comment pada python menggunakan tada #
- Multiple Statements pada Single Line
Tanda ; digunakan agar dapat memberikan lebih dari 1 perintah pada 1 baris.
- Multiple Statement Groups
Praktikum Sistem 3
Group pernyataan individu yang membentuk sebuah blok kode tunggal disebut dengan suite. Senyawa atau pernyataan kompleks seperti if, while, def, and class, adalah hal yang membutuhkan sebuah header line dan sebuah suite. Header lines dimulai dengan pernyataan (dengan kata kunci) dan diakhiri dengan tanda titik dua (:) dan diikuti oleh satu atau lebih baris yang membentuk suite.
Contoh:
if expression : suiteelif expression : suite else :
suite
Tipe VariableVariable Python tidak harus secara eksplisit
dideklarasi. Deklarasi akan secara otomatis ketika menetapkan nilai ke dalam variable. Tanda sama dengan (=) digunakan untuk memberikan nilai. Contoh:
#!/usr/bin/python
counter = 100 # An integer assignmentmiles = 1000.0 # A floating pointname = "John" # A string
print counterprint milesprint name
Praktikum Sistem 4
Pada python juga dapat memungkinkan untuk memberikan 1 nilai pada beberapa variable secara bersamaan, contoh:
a = b = c = 1a, b, c = 1, 2, "john"
Python memiliki 5 standart tipe data :
1. Numbers
Number object akan terbentuk ketika memberikan nilai pada suatu variable. Dapat juga melakukan penghapusan referensi dari number object menggunakan statement del. Contoh:
del vardel var_a, var_b
Python hanya support 4 tipe data number yaitu: int, long, float, dan complex.
2. String
String python memungkinkan untuk tanda kutip tunggal atau ganda. Pemotongan string dapat menggunakan slice operator ([] dan [:]) dengan indeks mulai dari 0 di awal string dan -1 untuk bekerja dari akhir string.
Tanda + berfungsi untuk penggabungan string, dan tanda * adalah operator pengulangan. Contoh:
#!/usr/bin/python
str = 'Hello World!'
print str # Hello World!print str[0] # H
Praktikum Sistem 5
print str[2:5] # lloprint str[2:] # llo World!print str * 2 # Hello World!Hello World!print str + "TEST" # Hello World!TEST
3. List
Sebuah list items dipisahkan oleh tanda koma dan tertutup dalam tanda kurung siku ([]). Isi dari list dapat diakses dengan menggunakan operator slice ([] dan [:]) dengan index di awal string dimulai dari 0 dan bekerja diakhir string dengan index -1.
Tanda + adalah operator penggabungan, dan tanda * adalah operator pengulangan. Contoh:
#!/usr/bin/python
list = [ 'abcd', 786 , 2.23, 'john', 70.2 ]tinylist = [123, 'john']
print list # Prints complete listprint list[0] # Prints first element of the listprint list[1:3] # Prints elements starting from 2nd till 3rd print list[2:] # Prints elements starting from 3rd elementprint tinylist * 2 # Prints list two timesprint list + tinylist # Prints concatenated lists
#result#['abcd', 786, 2.23, 'john', 70.200000000000003]#abcd#[786, 2.23]#[2.23, 'john', 70.200000000000003]#[123, 'john', 123, 'john']#['abcd', 786, 2.23, 'john', 70.200000000000003, 123, 'john']
4. Tuple
Praktikum Sistem 6
Tuple diapit oleh kurung kurawal ({}) dan nilai-nilai diakses menggunakan kurung siku ([]). Contoh:
#!/usr/bin/python
tuple = ( 'abcd', 786 , 2.23, 'john', 70.2 )tinytuple = (123, 'john')
print tuple # Prints complete listprint tuple[0] # Prints first element of the listprint tuple[1:3] # Prints elements starting from 2nd till 3rd print tuple[2:] # Prints elements starting from 3rd elementprint tinytuple * 2 # Prints list two timesprint tuple + tinytuple # Prints concatenated lists
#result#('abcd', 786, 2.23, 'john', 70.200000000000003)#abcd#(786, 2.23)#(2.23, 'john', 70.200000000000003)#(123, 'john', 123, 'john')#('abcd', 786, 2.23, 'john', 70.200000000000003, 123, 'john')
5. Dictionary
Dictionary diapit oleh kurung kurawal ({}) dan nilai-nilai diakses menggunakan kurung siku ([]). Contoh:
#!/usr/bin/python
dict = {}dict['one'] = "This is one"dict[2] = "This is two"
tinydict = {'name': 'john','code':6734, 'dept': 'sales'}
print dict['one'] # Prints value for 'one' keyprint dict[2] # Prints value for 2 key
Praktikum Sistem 7
print tinydict # Prints complete dictionaryprint tinydict.keys() # Prints all the keysprint tinydict.values() # Prints all the values
#result#This is one#This is two#{'dept': 'sales', 'code': 6734, 'name': 'john'}#['dept', 'code', 'name']#['sales', 6734, 'john']
Inputx = input(“Masukkan angka :”)
perintah di atas meminta inputan dari user dan dimasukkan ke dalam variabel x. perintah input dapat langsung mendeteksi apakah inputan tersebut angka atau bukan.
Ada perintah mendapatkan input lainnya, yaitu raw_input.
x = raw_input(“Masukkan Angka :”)
Maka hasil dari x pasti akan bertipe string.
Operator
Python mendukung 5 tipe operator yaitu Arithmetic, Comparision, Logical, Assignment, Conditional.
Praktikum Sistem 8
Python Arithmetic Operators:
Asumsikan sebuah variable a nerisi 10 dan variable b berisi 20:
Operator Description Example
+ Addition - Adds values on either side of the operator
a + b will give 30
- Subtraction - Subtracts right hand operand from left hand operand
a - b will give -10
* Multiplication - Multiplies values on either side of the operator
a * b will give 200
/ Division - Divides left hand operand by right hand operand
b / a will give 2
% Modulus - Divides left hand operand by right hand operand and returns remainder
b % a will give 0
** Exponent - Performs exponential (power) calculation on operators
a**b will give 10 to the power 20
// Floor Division - The division of operands where the result is the quotient in which the digits after the decimal point are removed.
9//2 is equal to 4 and 9.0//2.0 is equal to 4.0
Python Comparison Operators:
Asumsikan sebuah variable a nerisi 10 dan variable b berisi 20:
Praktikum Sistem 9
Operator Description Example
== Checks if the value of two operands are equal or not, if yes then condition becomes true.
(a == b) is not true.
!= Checks if the value of two operands are equal or not, if values are not equal then condition becomes true.
(a != b) is true.
<> Checks if the value of two operands are equal or not, if values are not equal then condition becomes true.
(a <> b) is true. This is similar to != operator.
> Checks if the value of left operand is greater than the value of right operand, if yes then condition becomes true.
(a > b) is not true.
< Checks if the value of left operand is less than the value of right operand, if yes then condition becomes true.
(a < b) is true.
>= Checks if the value of left operand is greater than or equal to the value of right operand, if yes then condition becomes true.
(a >= b) is not true.
<= Checks if the value of left operand is less than or equal to the value of right operand, if yes then condition becomes true.
(a <= b) is true.
Python Assignment Operators:
Asumsikan sebuah variable a nerisi 10 dan variable b berisi 20:
Praktikum Sistem 10
Operator Description Example
= Simple assignment operator, Assigns values from right side operands to left side operand
c = a + b will assigne value of a + b into c
+= Add AND assignment operator, It adds right operand to the left operand and assign the result to left operand
c += a is equivalent to c = c + a
-= Subtract AND assignment operator, It subtracts right operand from the left operand and assign the result to left operand
c -= a is equivalent to c = c - a
*= Multiply AND assignment operator, It multiplies right operand with the left operand and assign the result to left operand
c *= a is equivalent to c = c * a
/= Divide AND assignment operator, It divides left operand with the right operand and assign the result to left operand
c /= a is equivalent to c = c / a
%= Modulus AND assignment operator, It takes modulus using two operands and assign the result to left operand
c %= a is equivalent to c = c % a
**= Exponent AND assignment operator, Performs exponential (power) calculation on operators and assign value to the left operand
c **= a is equivalent to c = c ** a
//= Floor Dividion and assigns a value, Performs floor division on operators and assign value to the left
c //= a is equivalent to c = c // a
Praktikum Sistem 11
operand
Python Bitwise Operators:
Asumsikan jika a = 60 dan b = 13: berikut merupakan binarynya:
a = 0011 1100
b = 0000 1101
-----------------
a&b = 0000 1100
a|b = 0011 1101
a^b = 0011 0001
~a = 1100 0011
Berikut Bitwise operator yang support:
Operator Description Example
& Binary AND Operator copies a bit to the result if it exists in both operands.
(a & b) will give 12 which is 0000 1100
| Binary OR Operator copies a bit if it exists in eather operand.
(a | b) will give 61 which is 0011 1101
^ Binary XOR Operator copies the bit if it is set in one operand but not both.
(a ^ b) will give 49 which is 0011 0001
Praktikum Sistem 12
~ Binary Ones Complement Operator is unary and has the efect of 'flipping' bits.
(~a ) will give -60 which is 1100 0011
<< Binary Left Shift Operator. The left operands value is moved left by the number of bits specified by the right operand.
a << 2 will give 240 which is 1111 0000
>> Binary Right Shift Operator. The left operands value is moved right by the number of bits specified by the right operand.
a >> 2 will give 15 which is 0000 1111
Python Logical Operators:
Asumsikan sebuah variable a nerisi 10 dan variable b berisi 20:
Operator Description Example
and Called Logical AND operator. If both the operands are true then then condition becomes true.
(a and b) is true.
or Called Logical OR Operator. If any of the two operands are non zero then then condition becomes true.
(a or b) is true.
not Called Logical NOT Operator. Use to reverses the logical state of its operand. If a condition is true then Logical NOT operator will make false.
not(a and b) is false.
Praktikum Sistem 13
Python Membership Operators:
Terdapat 2 operator yang akan dijelaskan:
Operator Description Example
in Evaluates to true if it finds a variable in the specified sequence and false otherwise.
x in y, here in results in a 1 if x is a member of sequence y.
not in Evaluates to true if it does not finds a variable in the specified sequence and false otherwise.
x not in y, here not in results in a 1 if x is a member of sequence y.
Python Identity Operators:
Identity operators membandingkan lokasi memori dari 2 object.
Operator Description Example
is Evaluates to true if the variables on either side of the operator point to the same object and false otherwise.
x is y, here is results in 1 if id(x) equals id(y).
is not Evaluates to false if the variables on either side of the operator point to the same object and true otherwise.
x is not y, here is not results in 1 if id(x) is not equal to id(y).
Python Operators Precedence
Operator Description
** Exponentiation (raise to the power)
Praktikum Sistem 14
~ + - Ccomplement, unary plus and minus (method names for the last two are +@ and -@)
* / % // Multiply, divide, modulo and floor division
+ - Addition and subtraction
>> << Right and left bitwise shift
& Bitwise 'AND'
^ | Bitwise exclusive `OR' and regular `OR'
<= < > >= Comparison operators
<> == != Equality operators
= %= /= //= -= += *= **=
Assignment operators
is is not Identity operators
in not in Membership operators
not or and Logical operators
Array’s Operation Indexing
Cara mengakses isi array sama dengan bahasa pemrograman lain, yaitu dengan menyebutkan index array nya. Untuk diperhatikan, array dimulai dari index ke-0.
Contoh :
greeting = 'Hello'
greeting[0]
Hasilnya adalah 'H'
Praktikum Sistem 15
Slicing
Slicing merupakan cara mengakses isi array dalam range tertentu, tidak hanya 1 nilai saja.
Contoh:
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
numbers[3:6]
Hasilnya adalah [4, 5, 6]
numbers[0:1]
Hasilnya adalah [1]
Parameter yang dibutuhkan ada 2, yang pertama adalah index dari elemen pertama yang ingin dimasukkan, sedangkan parameter yang kedua adalah index dari elemen pertama setelah melakukan proses slicing.
Jika kita ingin melakukan slicing terhadap isi array yang dihitung dari belakang, maka dapat digunakan bilangan negatif.
Contoh :
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
numbers[-3:]
Hasilnya adalah [8, 9, 10]
Cara pengaksesan seperti di atas sebenarnya juga dapat digunakan untuk mengakses isi array dari depan.
Contoh :
Praktikum Sistem 16
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
numbers[:3]
Hasilnya adalah [1, 2, 3]
Untuk mengcopy semua isi array, digunakan cara seperti demikian:
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
numbers[:]
Hasilnya adalah [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Slicing juga masih memiliki parameter lagi yang mengatur step dari pengaksesan array.
Contoh :
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
numbers[0:10:2]
Hasilnya adalah [1, 3, 5, 7, 9]
numbers[3:6:3]
Hasilnya adalah [4]
Menambahkan isi array
Contoh :
[1, 2, 3] + [4, 5, 6]
[1, 2, 3, 4, 5, 6]
Praktikum Sistem 17
Multiplication
'python' * 5
Hasilnya adalah 'pythonpythonpythonpythonpython'
[42] * 10
Hasilnya adalah [42, 42, 42, 42, 42, 42, 42, 42, 42, 42]
Catatan:
isi array bisa diisi dengan None, yaitu reserved word yang menandakan bahwa isi array tersebut diisi dengan nilai null
Membership -> untuk mengecek apakah suatu nilai berada di dalam array. Cara menggunakan dengan keyword ‘in’.
Contoh:
users = ['mlh', 'foo', 'bar']
raw_input('Enter your user name: ') in users
Enter your user name: mlh
Hasilnya adalah True
Ada fungsi bawaan lain yang dapat digunakan untuk membantu operasi array, yaitu len(array) untuk menghitung jumlah elemen array, max(array) untuk menghitung nilai maksimal yang terdapat dalam
Praktikum Sistem 18
suatu array, dan min(array) untuk menghitung nilai minimal yang terdapat dalam suatu array.
Menghapus isi array, dengan menggunakan perintah del.
Contoh :
names = ['Alice', 'Beth', 'Cecil', 'Dee-Dee', 'Earl']
del names[2]
names
['Alice', 'Beth', 'Dee-Dee', 'Earl']
Perhatikan bahwa urutan array akan otomatis diatur oleh python.
Memasukkan slicing ke dalam array.
Seperti yang sudah dibahas di atas, slicing merupakan salah satu cara yang digunakan untuk mengambil isi array. Isi yang diambil tersebut dapat dimodifikasi, termasuk digabungkan ke dalam array lain. Berikut adalah contohnya:
name = list('Perl')
name
['P', 'e', 'r', 'l']
name[2:] = list('ar')
name
Hasilnya : ['P', 'e', 'a', 'r']
Praktikum Sistem 19
Contoh lain:
numbers = [1, 5]
numbers[1:1] = [2, 3, 4]
numbers
Hasilnya : [1, 2, 3, 4, 5]
numbers
[1, 2, 3, 4, 5]
numbers[1:4] = []
numbers
Hasilnya : [1, 5]
Array’s Method- append
digunakan untuk menambah isi array ke urutan paling terakhir.
Contoh:
lst = [1, 2, 3]
lst.append(4)
Hasilnya : [1, 2, 3, 4]
- count
Praktikum Sistem 20
digunakan untuk menghitung isi array yang sesuai dengan parameter.
Contoh:
['to', 'be', 'or', 'not', 'to', 'be'].count('to')
Hasilnya: 2
x = [[1, 2], 1, 1, [2, 1, [1, 2]]]
x.count(1)
Hasilnya : 2
x.count([1, 2])
Hasilnya : 1
- extend
digunakan untuk menambahkan isi array dari array lainnya.
Contoh:
a = [1, 2, 3]
b = [4, 5, 6]
a.extend(b)
Hasil dari a adalah :[1, 2, 3, 4, 5, 6]
- index
Praktikum Sistem 21
digunakan untuk mencari index dari kemunculan pertama suatu elemen dalam array.
Contoh :
knights = ['We', 'are', 'the', 'knights', 'who', 'say', 'ni']
knights.index('who')
Hasilnya : 4
- insert
digunakan untuk menginsertkan object ke dalam array, namun tidak harus di paling belakang.
Contoh :
numbers = [1, 2, 3, 5, 6, 7]
numbers.insert(3, 'four')
numbers
[1, 2, 3, 'four', 5, 6, 7]
numbers = [1, 2, 3, 5, 6, 7]
numbers[3:3] = ['four']
numbers
[1, 2, 3, 'four', 5, 6, 7]
- pop
Praktikum Sistem 22
digunakan untuk mengambil elemen terakhir dari array.
x = [1, 2, 3]
x.pop()
Hasilnya adalah 3
Isi x sekarang : [1, 2]
x.pop(0)
Hasilnya adalah 1
Isi x sekarang : [2]
- remove
remove digunakan untuk menghapus elemen yang dicari, yang pertama ditemukan.
Contoh:
x = ['to', 'be', 'or', 'not', 'to', 'be']
x.remove('be')
Isi x sekarang adalah ['to', 'or', 'not', 'to', 'be']
- reverse
digunakan untuk membalik isi array
x = [1, 2, 3]
x.reverse()
Praktikum Sistem 23
Isi x sekarang : [3, 2, 1]
- sort
digunakan untuk mengurutkan isi elemen array
Contoh :
x = [4, 6, 2, 1, 7, 9]
x.sort()
x
[1, 2, 4, 6, 7, 9]
String’s OperationMethod yang dapat dijalankan pada variable string
adalah:
- find
digunakan untuk menemukan posisi suatu substring pada string lain yang lebih panjang. Jika substring tidak ditemukan, maka akan mengembalikan nilai -1.
Contoh :
'With a moo-moo here, and a moo-moo there'.find('moo')
Hasilnya adalah 7
title = "Monty Python's Flying Circus"
Praktikum Sistem 24
title.find('Monty')
Hasilnya adalah 0
title.find('Python')
Hasilnya adalah 6
title.find('Flying')
Hasilnya adalah 15
title.find('Zirquss')
Hasilnya adalah -1
- join
perintah join digunakan untuk menggabungkan dua string. Namun harus diperhatikan bahwa yang digabungkan harus bertipe STRING. Perhatikan juga cara python melakukan join seperti pada contoh di bawah.
Contoh:
seq = [1, 2, 3, 4, 5]
sep = '+'
Perintah di atas akan menghasilkan error, karena isi seq adalah integer, bukan string.
seq = ['1', '2', '3', '4', '5']
sep.join(seq) # Joining a list of strings
Praktikum Sistem 25
Hasilnya adalah '1+2+3+4+5'
- lower
digunakan untuk mengembalikan nilai lowercase dari suatu string.
Contoh:
'Trondheim Hammer Dance'.lower()
Hasilnya adalah 'trondheim hammer dance'
name = 'Gumby'
names = ['gumby', 'smith', 'jones']
if name.lower() in names: print 'Found it!'
….
- replace
digunakan untuk mereplace suatu substring dengan substring lainnya.
Contoh:
'This is a test'.replace('is', 'eez')
Hasilnya adalah 'Theez eez a test'
- split
Praktikum Sistem 26
digunakan untuk memecah string berdasarkan delimiter yang sudah ditentukan. Jika parameter delimiter tidak diisi, maka default nya adalah spasi.
Contoh:
'1+2+3+4+5'.split('+')
['1', '2', '3', '4', '5']
'/usr/bin/env'.split('/')
['', 'usr', 'bin', 'env']
'Using the default'.split()
['Using', 'the', 'default']
- strip
digunakan untuk menghilangkan karakter yang dimasukkan sebagai parameter dari kiri dan kanan suatu string (seperti trim). Jika parameter tidak diisi, maka defaultnya adalah spasi.
Contoh:
' internal whitespace is kept '.strip()
Hasilnya adalah 'internal whitespace is kept'
'*** SPAM * for * everyone!!! ***'.strip(' *!')
Hasilnya adalah 'SPAM * for * everyone'
- upper
Praktikum Sistem 27
digunakan untuk menguppercase-kan suatu string. Merupakan kebalikan dari lower.
DecisionSyntax:
if <<condition>> :
elif <<condition>>:
else:
Contoh:
num = input('Enter a number: ')
if num > 0:
print 'The number is positive'
elif num < 0:
print 'The number is negative'
else:
print 'The number is zero'
LoopingSyntax:
While <condition>:
Praktikum Sistem 28
Statement1
Statement 2
For <variable> in <list>
Statement1
Statement2
Contoh:
numbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
for number in numbers:
print number
FunctionSyntax:
Def <<nama functions>>(parameters):
Statement1..
Statement2..
Parameter dipisahkan dengan koma jika lebih dari 1.
Contoh:
def fibs(num):
result = [0, 1]
for i in range(num-2):
Praktikum Sistem 29
result.append(result[-2] + result[-1])
return result
maka ketika dipanggil,
fibs(10)
Hasilnya adalah [0, 1, 1, 2, 3, 5, 8, 13, 21, 34]
fibs(15)
Hasilnya adalah [0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377]
File’s OperationOpen File
Syntax :
open(name[, mode[, buffering]])
Contoh:
f = open(r'C:\text\somefile.txt')
Mode File yang tersedia
‘r’ read mode
‘w’ write mode
‘a’ append mode
‘b’ binary mode (untuk ditambahkan ke mode lainnya)
Praktikum Sistem 30
‘+’ read/write mode (untuk ditambahkan ke mode lainnya)
Write File
Contoh:
f = open('somefile.txt', 'w')
f.write('Hello, ')
f.write('World!')
f.close()
Read file
Contoh: (isi somefile.txt dari operasi penulisan file dari contoh di atas)
f = open('somefile.txt', 'r')
f.read(4)
Hasilnya adalah 'Hell'
f.read()
Hasilnya adalah 'o, World!'
Selain perintah read, ada juga readline (yang gunanya untuk membaca 1 baris sekaligus) dan readlines (untuk membaca semua baris dalam file dan menyimpan ke dalam suatu list).
Setelah kita selesai melakukan operasi pada file, jangan lupa untuk menutup file tersebut.
Praktikum Sistem 31
Contoh:
# Open your file here
try:
# Write data to your file
finally:
file.close()
#Contoh Penggunaan Operasi File
#Isi somefile.txt
#Welcome to this file
#There is nothing here except
#This stupid haiku
f = open(r'c:\text\somefile.txt')
f.read(7)
#Hasilnya adalah 'Welcome'
f.read(4)
#Hasilnya adalah ' to '
f.close()
Praktikum Sistem 32
#******
f = open(r'c:\text\somefile.txt')
print f.read()
#Hasilnya adalah :
#Welcome to this file
#There is nothing here except
#This stupid haiku
f.close()
#*******
f = open(r'c:\text\somefile.txt')
for i in range(3):
print str(i) + ': ' + f.readline(),
#Hasilnya adalah:
#0: Welcome to this file
#1: There is nothing here except
#2: This stupid haiku
Praktikum Sistem 33
f.close()
#*******
import pprint
pprint.pprint(open(r'c:\text\somefile.txt').readlines())
#Hasilnya adalah
#['Welcome to this file\n',
#'There is nothing here except\n',
#'This stupid haiku']
#******
#Isi somefile.txt#this
#is no
#haiku
f = open(r'c:\text\somefile.txt')
lines = f.readlines()
f.close()
lines[1] = "isn't a\n"
f = open(r'c:\text\somefile.txt', 'w')
Praktikum Sistem 34
f.writelines(lines)
f.close()
#Hasilnya
#this
#isn't a
#haiku
Notes
Praktikum Sistem 35
Bab 7PYTHON - Advanced
OOPPython merupakan bahasa pemrograman yang
mendukung Object Oriented Programming, dengan encapsulation, inheritance, dan polymorphism sebagai dasarnya.
Membuat Class
Contoh:
__metaclass__ = type # Make sure we get new style classes
class Person:
def setName(self, name):
self.name = name
def getName(self):
return self.name
def greet(self):
print "Hello, world! I'm %s." % self.name
Praktikum Sistem 36
Jika dari class di atas dibuat instance nya,
foo = Person()
bar = Person()
foo.setName('Luke Skywalker')
bar.setName('Anakin Skywalker')
foo.greet()
Hasilnya : Hello, world! I'm Luke Skywalker.
bar.greet()
Hasilnya : Hello, world! I'm Anakin Skywalker.
Contoh lain:
class Bird:
song = 'Squaawk!'
def sing(self):
print self.song
bird = Bird()
bird.sing()
Praktikum Sistem 37
Hasilnya : Squaawk!
birdsong = bird.sing
birdsong()
Haislnya : Squaawk!
Constructor
Constructor merupakan method yang dipanggil pertama kali ketika suatu instance dibuat dan memiliki nama method yang sama persis dengan nama object lainnya.
Contoh:
class FooBar:
def __init__(self):
self.somevar = 42
f = FooBar()
f.somevar
Hasilnya adalah 42
class FooBar:
def __init__(self, value=42):
Praktikum Sistem 38
self.somevar = value
f = FooBar('This is a constructor argument')
f.somevar
Hasilnya adalah : 'This is a constructor argument'
Inheritance
class Filter:
def init(self):
self.blocked = []
def filter(self, sequence):
return [x for x in sequence if x not in self.blocked]
class SPAMFilter(Filter): # SPAMFilter is a subclass of Filter
def init(self): # Overrides init method from Filter superclass
self.blocked = ['SPAM']
Filter merupakan class induk. Class SPAMFilter merupakan turunan dari class Filter dan mengoverride method init dari Filter.
Kita bisa mengecek inheritance tersebut, dengan cara :
Praktikum Sistem 39
issubclass(SPAMFilter, Filter)
Hasilnya True
issubclass(Filter, SPAMFilter)
Hasilnya False
Kita juga bisa mengecek apakah suatu instance turunan dari class tertentu.
s = SPAMFilter()
isinstance(s, SPAMFilter)
Hasilnya True
isinstance(s, Filter)
Hasilnya True
isinstance(s, str)
Hasilnya False
Multiple Inheritance
Python mengijinkan multiple inheritance seperti contoh di bawah ini.
class Calculator:
def calculate(self, expression):
Praktikum Sistem 40
self.value = eval(expression)
class Talker:
def talk(self):
print 'Hi, my value is', self.value
class TalkingCalculator(Calculator, Talker):
pass
Class TalkingCalculator merupakan turunan dari class Calculator dan Talker.
Contoh penggunaan:
tc = TalkingCalculator()
tc.calculate('1+2*3')
tc.talk()
Hasilnya : Hi, my value is 7
Fungsi-fungsi lain yang berhubungan dengan penggunaan OOP:
- hasattr(instance, attribute)
Praktikum Sistem 41
perintah di atas digunakan untuk memeriksa apakah suatu instance memiliki attribute tertentu atau tidak. Hasilnya berupa boolean.
Contoh:
hasattr(tc, 'talk')
Hasilnya adalah True
hasattr(tc, 'fnord')
Hasilnya adalah False
- getattr(instance,attribut,default_value)
perintah di atas digunakan untuk mendapatkan value dari suatu attribute yang dimiliki oleh instance tersebut. Jika attribut tersebut tidak ditemukan, maka yang dikembalikan adalah nilai yang diisikan pada bagian default_value.
Contoh:
getattr(tc, 'fnord', None)
Hasilnya adalah None (karena tc tidak memiliki atribut fnord)
- setattr(instance,artibut,value)
perintah ini merupakan kebalikan dari getattr, yaitu untuk mengisikan value tertentu ke dalam suatu atribut yang dimiliki oleh instance.
Praktikum Sistem 42
Contoh:
setattr(tc, 'name', 'Mr. Gumby')
tc.name
'Mr. Gumby'
- callable
perintah di atas digunakan untuk mengetahui apakah suatu atribut dari instance bisa dipanggil atau tidak.
Contoh:
callable(getattr(tc, 'talk', None))
True
Properties pada Object
Menurut teori OOP, variable harus bersifat encapsulated, yaitu tidak bisa langsung diakses dari luar object. Maka dari itu, dibutuhkan suatu method aksesor dan mutator. Python menyediakan property untuk menangani hal tersebut, di mana property merupakan cara yang disediakan python untuk mengambil value dari attribut yang dimiliki object maupun mengubah value tersebut. Dengan kata lain, property merupakan gabungan dari aksesor dan mutator.
Contoh:
class Rectangle:
Praktikum Sistem 43
def __init__(self):
self.width = 0
self.height = 0
def setSize(self, size):
self.width, self.height = size
def getSize(self):
return self.width, self.height
size = property(getSize, setSize)
r = Rectangle()
r.width = 10
r.height = 5
r.size
(10, 5)
r.size = 150, 100
r.width
Hasilnya adalah 150
Static Methods
class MyClass:
@staticmethod
Praktikum Sistem 44
def smeth():
print 'This is a static method'
@classmethod
def cmeth(cls):
print 'This is a class method of', cls
MyClass.smeth()
Hasilnya adalah This is a static method
Regular ExpressionMatch function berguna sebagai flag dari regular expression. Struktur dari match :re.match(pattern, string, flags=0)
Group(num) atau group() fanction berguna untuk mengambil ekspresi yang sama.
Match Object Methods Description
group(num=0) This methods returns entire match (or specific subgroup num)
groups() This method return all matching subgroups in a tuple (empty if there weren't any)
Contoh:
Praktikum Sistem 45
#!/usr/bin/pythonimport re
line = "Cats are smarter than dogs";
matchObj = re.match( r'(.*) are(\.*)', line, re.M|re.I)
if matchObj: print "matchObj.group() : ", matchObj.group() print "matchObj.group(1) : ", matchObj.group(1) print "matchObj.group(2) : ", matchObj.group(2)else: print "No match!!"
#result
#matchObj.group(): Cats are#matchObj.group(1) : Cats#matchObj.group(2) :
Search function berguna untuk mencari pattern dalam string. Struktur:re.search(pattern, string, flags=0)
Contoh:#!/usr/bin/pythonimport re
line = "Cats are smarter than dogs";
matchObj = re.search( r'(.*) are(\.*)', line, re.M|re.I)
if matchObj: print "matchObj.group() : ", matchObj.group() print "matchObj.group(1) : ", matchObj.group(1) print "matchObj.group(2) : ", matchObj.group(2)else: print "No match!!"
#result
Praktikum Sistem 46
#matchObj.group(): Cats are#matchObj.group(1) : Cats#matchObj.group(2) :
Terdapat juga fungsi search dan replace menggunakan sub. Struktur:re.sub(pattern, repl, string, max=0)
Contoh:#!/usr/bin/python
phone = "2004-959-559 #This is Phone Number"
# Delete Python-style commentsnum = re.sub(r'#.*$', "", phone)print "Phone Num : ", num
# Remove anything other than digitsnum = re.sub(r'\D', "", phone) print "Phone Num : ", num
#resultPhone Num : 2004-959-559Phone Num : 2004959559
Berikut table regular expression pada python:
Pattern Description
^ Matches beginning of line.
$ Matches end of line.
. Matches any single character except newline. Using m option allows it to match newline as well.
[...] Matches any single character in brackets.
[^...] Matches any single character not in brackets
re* Matches 0 or more occurrences of preceding expression.
Praktikum Sistem 47
re+ Matches 1 or more occurrence of preceding expression.
re? Matches 0 or 1 occurrence of preceding expression.
re{ n} Matches exactly n number of occurrences of preceding expression.
re{ n,} Matches n or more occurrences of preceding expression.
re{ n, m} Matches at least n and at most m occurrences of preceding expression.
a| b Matches either a or b.
(re) Groups regular expressions and remembers matched text.
(?imx) Temporarily toggles on i, m, or x options within a regular expression. If in parentheses, only that area is affected.
(?-imx) Temporarily toggles off i, m, or x options within a regular expression. If in parentheses, only that area is affected.
(?: re) Groups regular expressions without remembering matched text.
(?imx: re) Temporarily toggles on i, m, or x options within parentheses.
(?-imx: re) Temporarily toggles off i, m, or x options within parentheses.
(?#...) Comment.
(?= re) Specifies position using a pattern. Doesn't have a range.
(?! re) Specifies position using pattern negation. Doesn't have a range.
(?> re) Matches independent pattern without backtracking.
\w Matches word characters.
\W Matches nonword characters.
\s Matches whitespace. Equivalent to [\t\n\r\f].
\S Matches nonwhitespace.
\d Matches digits. Equivalent to [0-9].
\D Matches nondigits.
\A Matches beginning of string.
Praktikum Sistem 48
\Z Matches end of string. If a newline exists, it matches just before newline.
\z Matches end of string.
\G Matches point where last match finished.
\b Matches word boundaries when outside brackets. Matches backspace (0x08) when inside brackets.
\B Matches nonword boundaries.
\n, \t, etc. Matches newlines, carriage returns, tabs, etc.
\1...\9 Matches nth grouped subexpression.
\10 Matches nth grouped subexpression if it matched already. Otherwise refers to the octal representation of a character code.
Regular-expression Examples:Literal characters:
Example Description
python Match "python".
Character classes:
Example Description
[Pp]ython Match "Python" or "python"
rub[ye] Match "ruby" or "rube"
[aeiou] Match any one lowercase vowel
[0-9] Match any digit; same as [0123456789]
[a-z] Match any lowercase ASCII letter
[A-Z] Match any uppercase ASCII letter
[a-zA-Z0-9] Match any of the above
Praktikum Sistem 49
[^aeiou] Match anything other than a lowercase vowel
[^0-9] Match anything other than a digit
Special Character Classes:
Example Description
. Match any character except newline
\d Match a digit: [0-9]
\D Match a nondigit: [^0-9]
\s Match a whitespace character: [ \t\r\n\f]
\S Match nonwhitespace: [^ \t\r\n\f]
\w Match a single word character: [A-Za-z0-9_]
\W Match a nonword character: [^A-Za-z0-9_]
Repetition Cases:
Example Description
ruby? Match "rub" or "ruby": the y is optional
ruby* Match "rub" plus 0 or more ys
ruby+ Match "rub" plus 1 or more ys
\d{3} Match exactly 3 digits
\d{3,} Match 3 or more digits
\d{3,5} Match 3, 4, or 5 digits
Nongreedy repetition:
This matches the smallest number of repetitions:
Example Description
<.*> Greedy repetition: matches "<python>perl>"
Praktikum Sistem 50
<.*?> Nongreedy: matches "<python>" in "<python>perl>"
Grouping with parentheses:
Example Description
\D\d+ No group: + repeats \d
(\D\d)+ Grouped: + repeats \D\d pair
([Pp]ython(, )?)+ Match "Python", "Python, python, python", etc.
Backreferences:
This matches a previously matched group again:
Example Description
([Pp])ython&\1ails Match python&rails or Python&Rails
(['"])[^\1]*\1 Single or double-quoted string. \1 matches whatever the 1st group matched . \2 matches whatever the 2nd group matched, etc.
Alternatives:
Example Description
python|perl Match "python" or "perl"
rub(y|le)) Match "ruby" or "ruble"
Python(!+|\?) "Python" followed by one or more ! or one ?
Anchors:
This need to specify match position
Example Description
^Python Match "Python" at the start of a string or internal line
Python$ Match "Python" at the end of a string or line
Praktikum Sistem 51
\APython Match "Python" at the start of a string
Python\Z Match "Python" at the end of a string
\bPython\b Match "Python" at a word boundary
\brub\B \B is nonword boundary: match "rub" in "rube" and "ruby" but not alone
Python(?=!) Match "Python", if followed by an exclamation point
Python(?!!) Match "Python", if not followed by an exclamation point
Special syntax with parentheses:
Example Description
R(?#comment) Matches "R". All the rest is a comment
R(?i)uby Case-insensitive while matching "uby"
R(?i:uby) Same as above
rub(?:y|le)) Group only without creating \1 backreference
top related