Python Panduan
Python Panduan
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
- Multi-Line
Contoh:
total = item_one + \
item_two + \
item_three
- 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
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
print counter
print miles
print name
a = b = c = 1
a, b, c = 1, 2, "john"
1. Numbers
Python hanya support 4 tipe data number yaitu: int, long, float,
dan complex.
2. String
#!/usr/bin/python
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.
#!/usr/bin/python
#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
#!/usr/bin/python
#result
#('abcd', 786, 2.23, 'john', 70.200000000000003)
#abcd
#(786, 2.23)
5. Dictionary
#!/usr/bin/python
dict = {}
dict['one'] = "This is one"
dict[2] = "This is two"
#result
#This is one
#This is two
#{'dept': 'sales', 'code': 6734, 'name': 'john'}
#['dept', 'code', 'name']
#['sales', 6734, 'john']
Input
x = input(Masukkan angka :)
x = raw_input(Masukkan Angka :)
Operator
Python mendukung 5 tipe operator yaitu Arithmetic, Comparision,
Logical, Assignment, Conditional.
a = 0011 1100
b = 0000 1101
-----------------
~a = 1100 0011
<< 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.
Arrays Operation
Indexing
Contoh :
greeting = 'Hello'
greeting[0]
Slicing
Contoh:
numbers[3:6]
numbers[0:1]
Jika kita ingin melakukan slicing terhadap isi array yang dihitung
dari belakang, maka dapat digunakan bilangan negatif.
Contoh :
numbers[-3:]
Contoh :
numbers[:3]
numbers[:]
Slicing juga masih memiliki parameter lagi yang mengatur step dari
pengaksesan array.
Contoh :
numbers[0:10:2]
numbers[3:6:3]
Contoh :
[1, 2, 3] + [4, 5, 6]
[1, 2, 3, 4, 5, 6]
Multiplication
'python' * 5
[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
Contoh:
Contoh :
del names[2]
names
name = list('Perl')
name
name[2:] = list('ar')
name
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
Arrays Method
- append
Contoh:
lst = [1, 2, 3]
lst.append(4)
Hasilnya : [1, 2, 3, 4]
- count
Contoh:
Hasilnya: 2
x.count(1)
Hasilnya : 2
x.count([1, 2])
Hasilnya : 1
- extend
Contoh:
a = [1, 2, 3]
b = [4, 5, 6]
a.extend(b)
- index
Contoh :
knights.index('who')
Hasilnya : 4
- insert
Contoh :
numbers = [1, 2, 3, 5, 6, 7]
numbers.insert(3, 'four')
numbers
numbers = [1, 2, 3, 5, 6, 7]
numbers[3:3] = ['four']
numbers
[1, 2, 3, 'four', 5, 6, 7]
- pop
x = [1, 2, 3]
x.pop()
Hasilnya adalah 3
x.pop(0)
Hasilnya adalah 1
- remove
Contoh:
x.remove('be')
- reverse
x = [1, 2, 3]
x.reverse()
- sort
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
Contoh :
Hasilnya adalah 7
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
Contoh:
seq = [1, 2, 3, 4, 5]
sep = '+'
- lower
Contoh:
name = 'Gumby'
- replace
Contoh:
- split
Contoh:
'1+2+3+4+5'.split('+')
'/usr/bin/env'.split('/')
- strip
Contoh:
- upper
if <<condition>> :
elif <<condition>>:
else:
Contoh:
if num > 0:
else:
Looping
Syntax:
While <condition>:
Statement1
Statement 2
Statement2
Contoh:
numbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
print number
Function
Syntax:
Statement1..
Statement2..
Contoh:
def fibs(num):
result = [0, 1]
for i in range(num-2):
result.append(result[-2] + result[-1])
return result
fibs(15)
Hasilnya adalah [0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377]
Files Operation
Open File
Syntax :
Contoh:
f = open(r'C:\text\somefile.txt')
r read mode
w write mode
a append mode
Write File
Contoh:
f = open('somefile.txt', 'w')
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)
f.read()
Setelah kita selesai melakukan operasi pada file, jangan lupa untuk
menutup file tersebut.
Contoh:
try:
finally:
file.close()
#Isi somefile.txt
f = open(r'c:\text\somefile.txt')
f.read(7)
f.read(4)
f.close()
#******
f = open(r'c:\text\somefile.txt')
print f.read()
#Hasilnya adalah :
#*******
f = open(r'c:\text\somefile.txt')
for i in range(3):
#Hasilnya adalah:
f.close()
#*******
import pprint
pprint.pprint(open(r'c:\text\somefile.txt').readlines())
#Hasilnya adalah
#******
#Isi somefile.txt
#this
#is no
#haiku
f = open(r'c:\text\somefile.txt')
lines = f.readlines()
f.close()
f = open(r'c:\text\somefile.txt', 'w')
f.writelines(lines)
f.close()
#Hasilnya
#this
#isn't a
#haiku
Membuat Class
Contoh:
class Person:
self.name = name
def getName(self):
return self.name
def greet(self):
bar = Person()
foo.setName('Luke Skywalker')
bar.setName('Anakin Skywalker')
foo.greet()
bar.greet()
Contoh lain:
class Bird:
song = 'Squaawk!'
def sing(self):
print self.song
bird = Bird()
bird.sing()
Hasilnya : Squaawk!
birdsong = bird.sing
birdsong()
Constructor
Contoh:
class FooBar:
def __init__(self):
self.somevar = 42
f = FooBar()
f.somevar
Hasilnya adalah 42
class FooBar:
self.somevar = value
f.somevar
Inheritance
class Filter:
def init(self):
self.blocked = []
self.blocked = ['SPAM']
issubclass(SPAMFilter, Filter)
Hasilnya True
issubclass(Filter, SPAMFilter)
Hasilnya False
s = SPAMFilter()
isinstance(s, SPAMFilter)
Hasilnya True
isinstance(s, Filter)
Hasilnya True
isinstance(s, str)
Hasilnya False
Multiple Inheritance
class Calculator:
self.value = eval(expression)
class Talker:
def talk(self):
pass
Contoh penggunaan:
tc = TalkingCalculator()
tc.calculate('1+2*3')
tc.talk()
- hasattr(instance, attribute)
Contoh:
hasattr(tc, 'talk')
hasattr(tc, 'fnord')
- getattr(instance,attribut,default_value)
- setattr(instance,artibut,value)
Contoh:
tc.name
'Mr. Gumby'
- callable
Contoh:
True
Contoh:
class Rectangle:
def __init__(self):
self.width = 0
self.height = 0
def getSize(self):
r = Rectangle()
r.width = 10
r.height = 5
r.size
(10, 5)
r.width
class MyClass:
@staticmethod
def smeth():
@classmethod
def cmeth(cls):
MyClass.smeth()
Regular Expression
Match function berguna sebagai flag dari regular expression. Struktur dari
match :
Match Object
Description
Methods
Contoh:
#!/usr/bin/python
import re
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
Contoh:
#!/usr/bin/python
import re
if matchObj:
print "matchObj.group() : ", matchObj.group()
print "matchObj.group(1) : ", matchObj.group(1)
#result
#matchObj.group(): Cats are
#matchObj.group(1) : Cats
#matchObj.group(2) :
Contoh:
#!/usr/bin/python
#result
Phone Num : 2004-959-559
Phone Num : 2004959559
Pattern Description
a| b Matches either a or b.
(?#...) Comment.
\S Matches nonwhitespace.
\D Matches nondigits.
Regular-expression Examples:
Literal characters:
Example Description
Character classes:
Example Description
Repetition Cases:
Example Description
Nongreedy repetition:
Backreferences:
Example Description
Alternatives:
Example Description
Anchors:
Example Description