0% menganggap dokumen ini bermanfaat (0 suara)
130 tayangan

Python Panduan

pyton

Diunggah oleh

Ratih Dinata
Hak Cipta
© © All Rights Reserved
Format Tersedia
Unduh sebagai DOCX, PDF, TXT atau baca online di Scribd
0% menganggap dokumen ini bermanfaat (0 suara)
130 tayangan

Python Panduan

pyton

Diunggah oleh

Ratih Dinata
Hak Cipta
© © All Rights Reserved
Format Tersedia
Unduh sebagai DOCX, PDF, TXT atau baca online di Scribd
Anda di halaman 1/ 48

Bab 6

PYTHON - Basics
Basic Syntax
Mode 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

Statement yang berada pada [], {}, or () tidak memerlukan tanda \

Praktikum Sistem Operasi 1


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 is
made 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

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.

Praktikum Sistem Operasi 2


Contoh:

if expression :
suite
elif expression :
suite
else :

suite

Tipe Variable
Variable 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 assignment


miles = 1000.0 # A floating point
name = "John" # A string

print counter
print miles
print name

Pada python juga dapat memungkinkan untuk memberikan 1 nilai pada


beberapa variable secara bersamaan, contoh:

a = b = c = 1
a, 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:

Praktikum Sistem Operasi 3


del var
del 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
print str[2:5] # llo
print 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 ]

Praktikum Sistem Operasi 4


tinylist = [123, 'john']

print list # Prints complete list


print list[0] # Prints first element of the list
print list[1:3] # Prints elements starting from
2nd till 3rd
print list[2:] # Prints elements starting from
3rd element
print tinylist * 2 # Prints list two times
print 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

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 list


print tuple[0] # Prints first element of the
list
print tuple[1:3] # Prints elements starting from
2nd till 3rd
print tuple[2:] # Prints elements starting from
3rd element
print tinytuple * 2 # Prints list two times
print tuple + tinytuple # Prints concatenated lists

#result
#('abcd', 786, 2.23, 'john', 70.200000000000003)
#abcd
#(786, 2.23)

Praktikum Sistem Operasi 5


#(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' key


print dict[2] # Prints value for 2 key
print tinydict # Prints complete dictionary
print tinydict.keys() # Prints all the keys
print 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']

Input
x = 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.

Praktikum Sistem Operasi 6


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.

Python Arithmetic Operators:


Asumsikan sebuah variable a nerisi 10 dan variable b berisi 20:

Operator Description Example

+ Addition - Adds values on a + b will give 30


either side of the operator

- Subtraction - Subtracts right a - b will give -10


hand operand from left hand
operand

* Multiplication - Multiplies a * b will give 200


values on either side of the
operator

/ Division - Divides left hand b / a will give 2


operand by right hand operand

% Modulus - Divides left hand b % a will give 0


operand by right hand operand
and returns remainder

** Exponent - Performs a**b will give 10 to the power


exponential (power) calculation 20
on operators

// Floor Division - The division of 9//2 is equal to 4 and 9.0//2.0

Praktikum Sistem Operasi 7


operands where the result is is equal to 4.0
the quotient in which the digits
after the decimal point are
removed.

Python Comparison Operators:


Asumsikan sebuah variable a nerisi 10 dan variable b berisi 20:

Operator Description Example

== Checks if the value of two (a == b) is not true.


operands are equal or not, if
yes then condition becomes
true.

!= Checks if the value of two (a != b) is true.


operands are equal or not, if
values are not equal then
condition becomes true.

<> Checks if the value of two (a <> b) is true. This is similar


operands are equal or not, if to != operator.
values are not equal then
condition becomes true.

> Checks if the value of left (a > b) is not true.


operand is greater than the
value of right operand, if yes
then condition becomes true.

< Checks if the value of left (a < b) is true.


operand is less than the value
of right operand, if yes then
condition becomes true.

>= Checks if the value of left (a >= b) is not true.


operand is greater than or
equal to the value of right
operand, if yes then condition
becomes true.

<= Checks if the value of left (a <= b) is true.

Praktikum Sistem Operasi 8


operand is less than or equal to
the value of right operand, if
yes then condition becomes
true.

Python Assignment Operators:


Asumsikan sebuah variable a nerisi 10 dan variable b berisi 20:

Operator Description Example

= Simple assignment c = a + b will assigne value of a +


operator, Assigns values b into c
from right side operands to
left side operand

+= Add AND assignment c += a is equivalent to c = c + a


operator, It adds right
operand to the left operand
and assign the result to left
operand

-= Subtract AND assignment c -= a is equivalent to c = c - a


operator, It subtracts right
operand from the left
operand and assign the
result to left operand

*= Multiply AND assignment c *= a is equivalent to c = c * a


operator, It multiplies right
operand with the left
operand and assign the
result to left operand

/= Divide AND assignment c /= a is equivalent to c = c / a


operator, It divides left
operand with the right
operand and assign the
result to left operand

%= Modulus AND assignment c %= a is equivalent to c = c % a


operator, It takes modulus
using two operands and

Praktikum Sistem Operasi 9


assign the result to left
operand

**= Exponent AND assignment c **= a is equivalent to c = c ** a


operator, Performs
exponential (power)
calculation on operators
and assign value to the left
operand

//= Floor Dividion and assigns c //= a is equivalent to c = c // a


a value, Performs floor
division on operators and
assign value to the left
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

Praktikum Sistem Operasi 10


& Binary AND Operator copies a (a & b) will give 12 which is
bit to the result if it exists in 0000 1100
both operands.

| Binary OR Operator copies a bit (a | b) will give 61 which is


if it exists in eather operand. 0011 1101

^ Binary XOR Operator copies (a ^ b) will give 49 which is


the bit if it is set in one 0011 0001
operand but not both.

~ Binary Ones Complement (~a ) will give -60 which is


Operator is unary and has the 1100 0011
efect of 'flipping' bits.

<< Binary Left Shift Operator. The a << 2 will give 240 which is
left operands value is moved 1111 0000
left by the number of bits
specified by the right operand.

>> Binary Right Shift Operator. a >> 2 will give 15 which is


The left operands value is 0000 1111
moved right by the number of
bits specified by the right
operand.

Python Logical Operators:


Asumsikan sebuah variable a nerisi 10 dan variable b berisi 20:

Operator Description Example

and Called Logical AND operator. If (a and b) is true.


both the operands are true
then then condition becomes
true.

or Called Logical OR Operator. If (a or b) is true.


any of the two operands are
non zero then then condition
becomes true.

not Called Logical NOT Operator. not(a and b) is false.

Praktikum Sistem Operasi 11


Use to reverses the logical
state of its operand. If a
condition is true then Logical
NOT operator will make false.

Python Membership Operators:


Terdapat 2 operator yang akan dijelaskan:

Operator Description Example

in Evaluates to true if it finds a x in y, here in results in a 1 if


variable in the specified x is a member of sequence y.
sequence and false otherwise.

not in Evaluates to true if it does not x not in y, here not in results


finds a variable in the specified in a 1 if x is a member of
sequence and false otherwise. sequence y.

Python Identity Operators:


Identity operators membandingkan lokasi memori dari 2 object.

Operator Description Example

is Evaluates to true if the x is y, here is results in 1 if


variables on either side of the id(x) equals id(y).
operator point to the same
object and false otherwise.

is not Evaluates to false if the x is not y, here is not results


variables on either side of the in 1 if id(x) is not equal to
operator point to the same id(y).
object and true otherwise.

Python Operators Precedence

Praktikum Sistem Operasi 12


Operator Description

** Exponentiation (raise to the power)

~+- 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

Arrays 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]

Praktikum Sistem Operasi 13


Hasilnya adalah 'H'

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 Operasi 14


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]

Multiplication

'python' * 5

Praktikum Sistem Operasi 15


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 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

Praktikum Sistem Operasi 16


['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']

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

Praktikum Sistem Operasi 17


Hasilnya : [1, 5]

Arrays 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

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

Praktikum Sistem Operasi 18


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

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

Praktikum Sistem Operasi 19


[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

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')

Praktikum Sistem Operasi 20


Isi x sekarang adalah ['to', 'or', 'not', 'to', 'be']

- reverse

digunakan untuk membalik isi array

x = [1, 2, 3]

x.reverse()

Isi x sekarang : [3, 2, 1]

- sort

digunakan untuk mengurutkan isi elemen array

Contoh :

x = [4, 6, 2, 1, 7, 9]

x.sort()

[1, 2, 4, 6, 7, 9]

Strings Operation
Method 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 :

Praktikum Sistem Operasi 21


'With a moo-moo here, and a moo-moo there'.find('moo')

Hasilnya adalah 7

title = "Monty Python's Flying Circus"

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.

Praktikum Sistem Operasi 22


seq = ['1', '2', '3', '4', '5']

sep.join(seq) # Joining a list of strings

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 Operasi 23


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

digunakan untuk menguppercase-kan suatu string. Merupakan


kebalikan dari lower.

Praktikum Sistem Operasi 24


Decision
Syntax:

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'

Looping
Syntax:

While <condition>:

Statement1

Statement 2

For <variable> in <list>

Praktikum Sistem Operasi 25


Statement1

Statement2

Contoh:

numbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

for number in numbers:

print number

Function
Syntax:

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):

result.append(result[-2] + result[-1])

return result

maka ketika dipanggil,

Praktikum Sistem Operasi 26


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]

Files Operation
Open 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)

+ read/write mode (untuk ditambahkan ke mode lainnya)

Write File

Contoh:

f = open('somefile.txt', 'w')

Praktikum Sistem Operasi 27


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.

Contoh:

# Open your file here

try:

# Write data to your file

finally:

file.close()

Praktikum Sistem Operasi 28


#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()

#******

f = open(r'c:\text\somefile.txt')

print f.read()

#Hasilnya adalah :

#Welcome to this file

#There is nothing here except

#This stupid haiku

Praktikum Sistem Operasi 29


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

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',

Praktikum Sistem Operasi 30


#'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')

f.writelines(lines)

f.close()

#Hasilnya

#this

#isn't a

#haiku

Praktikum Sistem Operasi 31


Notes

Praktikum Sistem Operasi 32


Bab 7
PYTHON - Advanced
OOP
Python 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

Jika dari class di atas dibuat instance nya,

Praktikum Sistem Operasi 33


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()

Hasilnya : Squaawk!

birdsong = bird.sing

birdsong()

Praktikum Sistem Operasi 34


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):

self.somevar = value

f = FooBar('This is a constructor argument')

f.somevar

Praktikum Sistem Operasi 35


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 :

issubclass(SPAMFilter, Filter)

Hasilnya True

issubclass(Filter, SPAMFilter)

Hasilnya False

Praktikum Sistem Operasi 36


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):

self.value = eval(expression)

class Talker:

def talk(self):

print 'Hi, my value is', self.value

class TalkingCalculator(Calculator, Talker):

pass

Praktikum Sistem Operasi 37


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)

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.

Praktikum Sistem Operasi 38


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.

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

Praktikum Sistem Operasi 39


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:

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

Praktikum Sistem Operasi 40


Static Methods

class MyClass:

@staticmethod

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 Expression
Match 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
Description
Methods

group(num=0) This methods returns entire match (or specific


subgroup num)

groups() This method return all matching subgroups in a tuple

Praktikum Sistem Operasi 41


(empty if there weren't any)

Contoh:

#!/usr/bin/python
import 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/python
import 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)

Praktikum Sistem Operasi 42


print "matchObj.group(2) : ", matchObj.group(2)
else:
print "No match!!"

#result
#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 comments


num = re.sub(r'#.*$', "", phone)
print "Phone Num : ", num

# Remove anything other than digits


num = re.sub(r'\D', "", phone)
print "Phone Num : ", num

#result
Phone Num : 2004-959-559
Phone 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.

Praktikum Sistem Operasi 43


[^...] Matches any single character not in brackets

re* Matches 0 or more occurrences of preceding expression.

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.

Praktikum Sistem Operasi 44


\d Matches digits. Equivalent to [0-9].

\D Matches nondigits.

\A Matches beginning of string.

\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]

Praktikum Sistem Operasi 45


[a-z] Match any lowercase ASCII letter

[A-Z] Match any uppercase ASCII letter

[a-zA-Z0-9] Match any of the above

[^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:

Praktikum Sistem Operasi 46


Example Description

<.*> Greedy repetition: matches "<python>perl>"

<.*?> 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

Praktikum Sistem Operasi 47


^Python Match "Python" at the start of a string or internal
line

Python$ Match "Python" at the end of a string or line

\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

Praktikum Sistem Operasi 48

Anda mungkin juga menyukai