SlideShare a Scribd company logo
1 of 57
Download to read offline
Pemrograman dengan 
Python untuk Pemula 
oon arfiandwi 
http://oo.or.id/py
Material ini digunakan untuk kelas teknologi pengenalan pemrograman 
dengan bahasa pengantar Python http://oo.or.id/py 
Dipublikasikan dengan lisensi Atribusi-Berbagi Serupa 
Creative Commons (CC BY-SA) oleh oon@oo.or.id
Tools to Install 
Download Python 2.7 from http://python.org/download 
or you can easly use online Python interpreter 
For Google Cloud Platform topic: 
Google App Engine SDK for Python from https: 
//cloud.google.com/appengine/downloads 
Pip Python Package Manager from http://pip.pypa. 
io/en/latest/installing.html
Outline 
Python intro 
Type, Variable, Value 
Functions 
Conditional 
Iteration 
String processing 
Intro to Google Cloud Platform with Python
Reference 
http://www.greenteapress.com/thinkpython/ 
http://www.pythonlearn.com/ 
http://www.diveintopython.net/ 
https://www.python.org/download/ 
http://pythoncentral.org/comparison-of-python-ides- 
development/
Software/Program/App 
compiled or interpreted (or both) 
input-process-output (decide input & output, think about the process) 
syntax and semantic 
>>> 1 + 2 = 3 
>>> panjang = 3 
>>> lebar = 4 
>>> luas = panjang + lebar
Python 
➔ High-level language 
➔ Interactive mode & Scripting mode 
➔ Online interpreter 
◆ http://www.skulpt.org/ 
◆ http://pythontutor.com/ 
➔ case sensitive
Python Brochure | http://getpython.info
Introduction to Python with Jessica McKellar
Hello Python 
>>> print ‘Hello, World!’ 
Hello, World! 
>>> type(‘Hello, World!’) 
<type ‘str’> 
>>> print 1+2 
3 
>>> type(3) 
<type ‘int’> 
>>> type(‘1’)
Type, Variable, Value 
>>> i = 1 
(i adalah variable, dengan type int, memiliki value 1, diberi nilai dengan operator =) 
>>> kata = ‘nilai’ 
(kata adalah variable, dengan type str, memiliki value nilai) 
some of basic data type: 
Integer: int 
String: str 
Boolean: bool
Variable Assignment 
>>> message=’message in the bottle’ 
>>> print message 
>>> type(message) 
>>> x=1 
>>> x=x+2 
>>> x+=3 
>>> y=4 
>>> print x*y
Operator & Operand 
1+2 
(1 adalah operand, + adalah operator, 2 adalah operand) 
x < xx and z > y 
(operand? operator?) 
Order of operations: PEMDAS
Indentation 
4-space indents and no hard tab character
Interactive Mode & Scripting Mode 
give sample of interactive mode on console 
give sample of scripting mode count_down.py
List 
List is a sequence, of elements or items 
[1, 2, 3] 
['ab', 'bc', 'cd', 'de'] 
['ab', 'bc', 1, 2, 1.1, [True, False]]
Array 
array.array is a wrapper of C arrays. can 
handle only homogeneous C array of data. 
so for common use, simply use List 
http://stackoverflow. 
com/questions/176011/python-list-vs-array-when- 
to-use
Tuple 
>>> t = (1, 2, 3) 
>>> type(t) 
<type ‘tuple’> 
>>> print t 
>>> t = (‘hello’) 
>>> print t
String 
String as sequence 
String slice 
String methods (intro OO first) 
String comparison 
in Operator
String 
>>> kata = ‘pemrograman’ 
>>> print kata[4] 
>>> lenkata = len(kata) 
>>> print lenkata 
>>> print kata[lenkata-1] 
>>> for char in kata: 
… print char 
>>> print kata.upper()
String Operations 
Concatenation 
>>> print ‘pemrograman’ + ‘python’
Formatted Printing 
print 'formatting %s %d' % ('text', 7) 
http://forums.udacity. 
com/questions/2019688/python-101-unit-2- 
formatted-printing-and-function-documentation
Conditional 
if 
if .. else .. 
if .. elif .. else ..
Conditional sample 
>>> hari = ‘minggu’ 
>>> if hari == ‘sabtu’ or hari == ‘minggu’: 
… print ‘akhir pekan!’ 
… 
akhir pekan!
boolean, and, or 
x and y 
akan bernilai True, jika keduanya True 
selain itu bernilai False 
x or y 
akan bernilai False, jika keduanya False 
selain itu bernilai True
Conditional samples (2) 
>>> x = 4 
>>> if x%2 == 0: 
… print ‘even’ 
… else: 
… print ‘odd’
assignments 
buat kode program untuk mengecek apakah 
variable x itu positif atau negatif 
>>> x = -1 
buat kode program untuk mengecek apakah 
variable x itu positif, negatif, atau nol 
>>> x = 0
Conditional samples (3) 
>>> x = 7 
>>> if x > 8: 
… print ‘A’ 
… elif x>6 and x<8: 
… print ‘B’ 
… else: 
… print ‘C’
Functions 
Function call 
Add new functions 
Fruitful function, void function 
import 
importing with from
function call and create function 
>>> type(True) 
>>> def apakah_genap(angka): 
… if angka%2 == 0: 
… print ‘benar, genap’ 
… else: 
… print ‘salah, ganjil’ 
>>> apakah_genap(7) 
>>> apakah_genap(100)
function call and create function 
>>> def luas_persegi(panjang, lebar): 
… luas = panjang * lebar 
… return luas 
… 
>>> luasnya = luas_persegi(20, 30) 
>>> print luasnya
import function 
>>> import math 
>>> print math 
>>> akar9 = math.sqrt(9) 
>>> print akar9
assignment 
buat sebuah fungsi luas_lingkaran 
>>> luas_lingkaran(10) 
note: 
pi: math.pi 
input: jari-jari 
process: pi * jari-jari * jari-jari
Iteration with while 
>>> x = 7 
>>> while x>0: 
… print ‘data-%i’ % x 
… x = x -1
assignment 
buat iteration menggunakan while, dalam 
sebuah fungsi, yang akan menampilkan hanya 
angka yang genap saja. 
>>> count_down_genap(4) 
4 
2
Iteration while with break 
>>> while not ketemu: 
... databerikut = cari_data() 
... if databerikut == yangdicari: 
... break 
...
Iteration with for 
>>> for i in range(3) 
… print ‘ulang’ 
>>> for i in range(5,10) 
… print i
comments & docstring 
>>> xxx = 3 # var name xxx 
>>> print xxx
Variable Scope 
local
Google Cloud Platform with Python 
let’s start by making a website using python 
Google Cloud Platform have a free tier of 
Google App Engine 
we’ll develop using Google App Engine SDK for 
Python 
https://developers.google.com/appengine/docs/python/gettingstartedpython27/introduction
Google App Engine SDK for Python 
create 2 files on directory 
app.yaml 
main.py 
dev_appserver.py projectdir 
open http://localhost:8080/
app.yaml 
application: waktusaatini 
version: 1 
runtime: python27 
api_version: 1 
threadsafe: true 
handlers: 
- url: .* 
script: main.application 
libraries: 
- name: webapp2 
version: latest
main.py 
import datetime 
import webapp2 
class MainPage(webapp2.RequestHandler): 
def get(self): 
message = ‘<p>waktu %s</p>’ % datetime.datetime.now() 
self.response.out.write(message); 
application = webapp2.WSGIApplication([(‘/’, MainPage)], debug=True)
Template Engine Jinja2 
install Jinja2 
# pip install jinja2 
3 Files: 
● app.yaml 
● main.py 
● home.html 
Upload to appspot: 
# appcfg.py update kelas-teknologi/ 
Sample: http://kelas-teknologi.appspot.com
app.yaml 
application: kelas-teknologi 
version: 1 
runtime: python27 
api_version: 1 
threadsafe: true 
handlers: 
- url: .* 
script: main.application 
libraries: 
- name: webapp2 
version: latest 
- name: jinja2 
version: latest 
- name: markupsafe 
version: latest
main.py 
import datetime 
import webapp2 
import jinja2 
import os 
from google.appengine.api import users 
template_env = jinja2.Environment( 
loader=jinja2.FileSystemLoader(os.getcwd()))
main.py (cont’d) 
class MainPage(webapp2.RequestHandler): 
def get(self): 
current_time = datetime.datetime.now() 
user = users.get_current_user() 
login_url = users.create_login_url(self.request.path) 
logout_url = users.create_logout_url(self.request.path) 
template = template_env.get_template('home.html') 
context = { 
'current_time': current_time, 
'user': user, 
'login_url': login_url, 
'logout_url': logout_url, 
} 
self.response.out.write(template.render(context)) 
application = webapp2.WSGIApplication([('/', MainPage)], debug=True)
home.html 
<html><head><title>The Time Is...</title></head> 
<body> 
{% if user %} 
<p> 
Welcome, <strong>{{ user.email() }}</strong>! 
You can <a href="{{ logout_url }}">sign out</a>. 
</p> 
{% else %} 
<p> Welcome! 
<a href="{{ login_url }}">Sign in or register</a> to customize. </p> 
{% endif %} 
<p>The time is: {{ current_time }}</p> 
</body></html>
Web Form & Datastore 
5 Files: 
● app.yaml 
● models.py 
● main.py 
● prefs.py 
● home.html 
Upload to appspot: 
# appcfg.py update kelas-teknologi/ 
Sample: http://kelas-teknologi.appspot.com
app.yaml 
application: kelas-teknologi 
version: 1 
runtime: python27 
api_version: 1 
threadsafe: true 
handlers: 
- url: /prefs 
script: prefs.application 
login: required 
- url: .* 
script: main.application 
libraries: 
- name: webapp2 
version: latest 
- name: jinja2 
version: latest 
- name: markupsafe 
version: latest
models.py from google.appengine.api import users 
from google.appengine.ext import db 
class UserPrefs(db.Model): 
tz_offset = db.IntegerProperty(default=0) 
user = db.UserProperty(auto_current_user_add=True) 
def get_userprefs(user_id=None): 
if not user_id: 
user = users.get_current_user() 
if not user: 
return None 
user_id = user.user_id() 
key = db.Key.from_path('UserPrefs', user_id) 
userprefs = db.get(key) 
if not userprefs: 
userprefs = UserPrefs(key_name=user_id) 
return userprefs
main.py ...snip... 
import models 
...snip... 
class MainPage(webapp2.RequestHandler): 
def get(self): 
current_time = datetime.datetime.now() 
user = users.get_current_user() 
userprefs = models.get_userprefs() 
if userprefs: 
current_time += datetime.timedelta(0, 0, 0, 0, 0, userprefs.tz_offset) 
...snip... 
context = { 
'current_time': current_time, 
'user': user, 
'login_url': login_url, 
'logout_url': logout_url, 
'userprefs': userprefs, 
} 
self.response.out.write(template.render(context)) 
application = webapp2.WSGIApplication([('/', MainPage)], debug=True)
home.html <html><head><title>The Time Is...</title></head> 
<body> 
{% if user %} 
<p> 
Welcome, <strong>{{ user.email() }}</strong>! 
You can <a href="{{ logout_url }}">sign out</a>. 
</p> 
{% else %} 
<p> Welcome! 
<a href="{{ login_url }}">Sign in or register</a> to customize. </p> 
{% endif %} 
{% if user %} 
<form action="/prefs" method="post"> 
<label for="tz_offset"> 
Timezone offset from UTC (can be negative): 
</label> 
<input name="tz_offset" id="tz_offset" type="text" 
size="4" value="{{ userprefs.tz_offset }}" /> <input type="submit" value="Set" /> 
</form> 
{% endif %} 
<p>The time is: {{ current_time }}</p> 
</body></html>
prefs.py import webapp2 
import models 
class PrefsPage(webapp2.RequestHandler): 
def post(self): 
userprefs = models.get_userprefs() 
try: 
tz_offset = int(self.request.get('tz_offset')) 
userprefs.tz_offset = tz_offset 
userprefs.put() 
except ValueError: 
# User entered a value that wasn't an integer. Ignore for now. 
pass 
self.redirect('/') 
application = webapp2.WSGIApplication([('/prefs', PrefsPage)], 
debug=True)
OO: Type - Class 
None
Sample with Flask 
None
Oon Arfiandwi 
Co-founder of 7Langit mobile agency 
http://oo.or.id/py 
http://google.com/+oonarfiandwi 
http://twitter.com/oonid 
http://about.me/oon

More Related Content

What's hot

proposisi majemuk & Tautologi
 proposisi majemuk & Tautologi proposisi majemuk & Tautologi
proposisi majemuk & TautologiHuzairi Zairi
 
Implementasi queue
Implementasi queueImplementasi queue
Implementasi queueRhe Dwi Yuni
 
LAPORAN TUGAS AKHIR PERANCANGAN APLIKASI KNOWLEDGE BASE SYSTEM UNTUK INSTRUKS...
LAPORAN TUGAS AKHIR PERANCANGAN APLIKASI KNOWLEDGE BASE SYSTEM UNTUK INSTRUKS...LAPORAN TUGAS AKHIR PERANCANGAN APLIKASI KNOWLEDGE BASE SYSTEM UNTUK INSTRUKS...
LAPORAN TUGAS AKHIR PERANCANGAN APLIKASI KNOWLEDGE BASE SYSTEM UNTUK INSTRUKS...Uofa_Unsada
 
[PBO] Pertemuan 11 - GUI Java Desktop
[PBO] Pertemuan 11 - GUI Java Desktop[PBO] Pertemuan 11 - GUI Java Desktop
[PBO] Pertemuan 11 - GUI Java Desktoprizki adam kurniawan
 
MATERI SISTEM KOMPUTER KELAS X
MATERI SISTEM KOMPUTER KELAS XMATERI SISTEM KOMPUTER KELAS X
MATERI SISTEM KOMPUTER KELAS Xndriehs
 
Metode pencarian heuristik
Metode pencarian heuristikMetode pencarian heuristik
Metode pencarian heuristikBaguss Chandrass
 
1. pengenalan python
1. pengenalan python1. pengenalan python
1. pengenalan pythonirwansyah122
 
Ragam Dialog :: Interaksi Manusia dan Komputer
Ragam Dialog :: Interaksi Manusia dan KomputerRagam Dialog :: Interaksi Manusia dan Komputer
Ragam Dialog :: Interaksi Manusia dan KomputerAuliaa Oktarianii
 
Makalah sistem-operasi
Makalah sistem-operasiMakalah sistem-operasi
Makalah sistem-operasiIKHSAN MAHRURI
 
Proposisi Logika Informatika
Proposisi Logika InformatikaProposisi Logika Informatika
Proposisi Logika InformatikaDeviGayatri
 
DASAR-DASAR DESAIN GRAFIS - dewifitriyani__
DASAR-DASAR DESAIN GRAFIS - dewifitriyani__DASAR-DASAR DESAIN GRAFIS - dewifitriyani__
DASAR-DASAR DESAIN GRAFIS - dewifitriyani__Dewi Fitriyani
 
Materi Kuliah : Dasar pemrograman 1
Materi Kuliah : Dasar pemrograman 1Materi Kuliah : Dasar pemrograman 1
Materi Kuliah : Dasar pemrograman 1Braga Rezpect
 
Java (Netbeans) - Looping - Object Oriented Programming
Java (Netbeans) - Looping - Object Oriented ProgrammingJava (Netbeans) - Looping - Object Oriented Programming
Java (Netbeans) - Looping - Object Oriented ProgrammingMelina Krisnawati
 
Pertemuan 9 Representasi Pengetahuan
Pertemuan 9 Representasi PengetahuanPertemuan 9 Representasi Pengetahuan
Pertemuan 9 Representasi PengetahuanEndang Retnoningsih
 

What's hot (20)

proposisi majemuk & Tautologi
 proposisi majemuk & Tautologi proposisi majemuk & Tautologi
proposisi majemuk & Tautologi
 
Implementasi queue
Implementasi queueImplementasi queue
Implementasi queue
 
LAPORAN TUGAS AKHIR PERANCANGAN APLIKASI KNOWLEDGE BASE SYSTEM UNTUK INSTRUKS...
LAPORAN TUGAS AKHIR PERANCANGAN APLIKASI KNOWLEDGE BASE SYSTEM UNTUK INSTRUKS...LAPORAN TUGAS AKHIR PERANCANGAN APLIKASI KNOWLEDGE BASE SYSTEM UNTUK INSTRUKS...
LAPORAN TUGAS AKHIR PERANCANGAN APLIKASI KNOWLEDGE BASE SYSTEM UNTUK INSTRUKS...
 
[PBO] Pertemuan 11 - GUI Java Desktop
[PBO] Pertemuan 11 - GUI Java Desktop[PBO] Pertemuan 11 - GUI Java Desktop
[PBO] Pertemuan 11 - GUI Java Desktop
 
MATERI SISTEM KOMPUTER KELAS X
MATERI SISTEM KOMPUTER KELAS XMATERI SISTEM KOMPUTER KELAS X
MATERI SISTEM KOMPUTER KELAS X
 
Algoritma penjadwalan proses
Algoritma penjadwalan prosesAlgoritma penjadwalan proses
Algoritma penjadwalan proses
 
Metode pencarian heuristik
Metode pencarian heuristikMetode pencarian heuristik
Metode pencarian heuristik
 
1. pengenalan python
1. pengenalan python1. pengenalan python
1. pengenalan python
 
Interupsi
InterupsiInterupsi
Interupsi
 
Ragam Dialog :: Interaksi Manusia dan Komputer
Ragam Dialog :: Interaksi Manusia dan KomputerRagam Dialog :: Interaksi Manusia dan Komputer
Ragam Dialog :: Interaksi Manusia dan Komputer
 
Ragam dialog
Ragam dialogRagam dialog
Ragam dialog
 
Makalah sistem-operasi
Makalah sistem-operasiMakalah sistem-operasi
Makalah sistem-operasi
 
Proposisi Logika Informatika
Proposisi Logika InformatikaProposisi Logika Informatika
Proposisi Logika Informatika
 
DASAR-DASAR DESAIN GRAFIS - dewifitriyani__
DASAR-DASAR DESAIN GRAFIS - dewifitriyani__DASAR-DASAR DESAIN GRAFIS - dewifitriyani__
DASAR-DASAR DESAIN GRAFIS - dewifitriyani__
 
Materi Kuliah : Dasar pemrograman 1
Materi Kuliah : Dasar pemrograman 1Materi Kuliah : Dasar pemrograman 1
Materi Kuliah : Dasar pemrograman 1
 
Java (Netbeans) - Looping - Object Oriented Programming
Java (Netbeans) - Looping - Object Oriented ProgrammingJava (Netbeans) - Looping - Object Oriented Programming
Java (Netbeans) - Looping - Object Oriented Programming
 
Python File Handling
Python File HandlingPython File Handling
Python File Handling
 
Prinsip User Interface Design
Prinsip User Interface DesignPrinsip User Interface Design
Prinsip User Interface Design
 
Pertemuan 9 Representasi Pengetahuan
Pertemuan 9 Representasi PengetahuanPertemuan 9 Representasi Pengetahuan
Pertemuan 9 Representasi Pengetahuan
 
Imk 1 pendahuluan
Imk 1   pendahuluanImk 1   pendahuluan
Imk 1 pendahuluan
 

Viewers also liked

My sql dari pemula hingga mahir
My sql dari pemula hingga mahirMy sql dari pemula hingga mahir
My sql dari pemula hingga mahirDenny Yahya
 
Hendri python
Hendri pythonHendri python
Hendri pythonChar Lie
 
Oracle SQL Developer Tips & Tricks
Oracle SQL Developer Tips & TricksOracle SQL Developer Tips & Tricks
Oracle SQL Developer Tips & TricksJeff Smith
 
Tutorial Migrasi Database dari Microsoft SQL Server ke Oracle Database
Tutorial Migrasi Database dari Microsoft SQL Server ke Oracle DatabaseTutorial Migrasi Database dari Microsoft SQL Server ke Oracle Database
Tutorial Migrasi Database dari Microsoft SQL Server ke Oracle DatabaseHari Kurnia
 
Dimensional modeling in oracle sql developer
Dimensional modeling in oracle sql developerDimensional modeling in oracle sql developer
Dimensional modeling in oracle sql developerJeff Smith
 
Belajar netbeans java pemula dari 0 sampai mahir
Belajar netbeans java pemula dari 0 sampai mahirBelajar netbeans java pemula dari 0 sampai mahir
Belajar netbeans java pemula dari 0 sampai mahirharisonmtd
 
ORACLE Di Virtual Box : Ringkasan Penggunaan
ORACLE Di Virtual Box : Ringkasan PenggunaanORACLE Di Virtual Box : Ringkasan Penggunaan
ORACLE Di Virtual Box : Ringkasan PenggunaanAgus SA
 
Laporan praktikum modul 6 pemrogrman database dengan jdbc
Laporan praktikum modul 6 pemrogrman database dengan jdbcLaporan praktikum modul 6 pemrogrman database dengan jdbc
Laporan praktikum modul 6 pemrogrman database dengan jdbcDevi Apriansyah
 

Viewers also liked (8)

My sql dari pemula hingga mahir
My sql dari pemula hingga mahirMy sql dari pemula hingga mahir
My sql dari pemula hingga mahir
 
Hendri python
Hendri pythonHendri python
Hendri python
 
Oracle SQL Developer Tips & Tricks
Oracle SQL Developer Tips & TricksOracle SQL Developer Tips & Tricks
Oracle SQL Developer Tips & Tricks
 
Tutorial Migrasi Database dari Microsoft SQL Server ke Oracle Database
Tutorial Migrasi Database dari Microsoft SQL Server ke Oracle DatabaseTutorial Migrasi Database dari Microsoft SQL Server ke Oracle Database
Tutorial Migrasi Database dari Microsoft SQL Server ke Oracle Database
 
Dimensional modeling in oracle sql developer
Dimensional modeling in oracle sql developerDimensional modeling in oracle sql developer
Dimensional modeling in oracle sql developer
 
Belajar netbeans java pemula dari 0 sampai mahir
Belajar netbeans java pemula dari 0 sampai mahirBelajar netbeans java pemula dari 0 sampai mahir
Belajar netbeans java pemula dari 0 sampai mahir
 
ORACLE Di Virtual Box : Ringkasan Penggunaan
ORACLE Di Virtual Box : Ringkasan PenggunaanORACLE Di Virtual Box : Ringkasan Penggunaan
ORACLE Di Virtual Box : Ringkasan Penggunaan
 
Laporan praktikum modul 6 pemrogrman database dengan jdbc
Laporan praktikum modul 6 pemrogrman database dengan jdbcLaporan praktikum modul 6 pemrogrman database dengan jdbc
Laporan praktikum modul 6 pemrogrman database dengan jdbc
 

Similar to Pemrograman Python untuk Pemula

Python Functions Tutorial | Working With Functions In Python | Python Trainin...
Python Functions Tutorial | Working With Functions In Python | Python Trainin...Python Functions Tutorial | Working With Functions In Python | Python Trainin...
Python Functions Tutorial | Working With Functions In Python | Python Trainin...Edureka!
 
SymfonyCon Berlin 2016 - Symfony Plugin for PhpStorm - 3 years later
SymfonyCon Berlin 2016 - Symfony Plugin for PhpStorm - 3 years laterSymfonyCon Berlin 2016 - Symfony Plugin for PhpStorm - 3 years later
SymfonyCon Berlin 2016 - Symfony Plugin for PhpStorm - 3 years laterHaehnchen
 
An Overview Of Python With Functional Programming
An Overview Of Python With Functional ProgrammingAn Overview Of Python With Functional Programming
An Overview Of Python With Functional ProgrammingAdam Getchell
 
Pres_python_talakhoury_26_09_2023.pdf
Pres_python_talakhoury_26_09_2023.pdfPres_python_talakhoury_26_09_2023.pdf
Pres_python_talakhoury_26_09_2023.pdfRamziFeghali
 
Incredible Machine with Pipelines and Generators
Incredible Machine with Pipelines and GeneratorsIncredible Machine with Pipelines and Generators
Incredible Machine with Pipelines and Generatorsdantleech
 
Performance and Scalability Testing with Python and Multi-Mechanize
Performance and Scalability Testing with Python and Multi-MechanizePerformance and Scalability Testing with Python and Multi-Mechanize
Performance and Scalability Testing with Python and Multi-Mechanizecoreygoldberg
 
Software Project Management
Software Project ManagementSoftware Project Management
Software Project ManagementWidoyo PH
 
Scaling python webapps from 0 to 50 million users - A top-down approach
Scaling python webapps from 0 to 50 million users - A top-down approachScaling python webapps from 0 to 50 million users - A top-down approach
Scaling python webapps from 0 to 50 million users - A top-down approachJinal Jhaveri
 
Web2py Code Lab
Web2py Code LabWeb2py Code Lab
Web2py Code LabColin Su
 
Easy Web Project Development & Management with Django & Mercurial
Easy Web Project Development & Management with Django & MercurialEasy Web Project Development & Management with Django & Mercurial
Easy Web Project Development & Management with Django & MercurialWidoyo PH
 
Effective testing with pytest
Effective testing with pytestEffective testing with pytest
Effective testing with pytestHector Canto
 
What's new in Python 3.11
What's new in Python 3.11What's new in Python 3.11
What's new in Python 3.11Henry Schreiner
 
Question 1 briefly respond to all the following questions. make
Question 1 briefly respond to all the following questions. make Question 1 briefly respond to all the following questions. make
Question 1 briefly respond to all the following questions. make YASHU40
 
Python Programming - II. The Basics
Python Programming - II. The BasicsPython Programming - II. The Basics
Python Programming - II. The BasicsRanel Padon
 
Functions_in_Python.pptx
Functions_in_Python.pptxFunctions_in_Python.pptx
Functions_in_Python.pptxkrushnaraj1
 
Python Programming Essentials - M35 - Iterators & Generators
Python Programming Essentials - M35 - Iterators & GeneratorsPython Programming Essentials - M35 - Iterators & Generators
Python Programming Essentials - M35 - Iterators & GeneratorsP3 InfoTech Solutions Pvt. Ltd.
 
服务框架: Thrift & PasteScript
服务框架: Thrift & PasteScript服务框架: Thrift & PasteScript
服务框架: Thrift & PasteScriptQiangning Hong
 

Similar to Pemrograman Python untuk Pemula (20)

Python Functions Tutorial | Working With Functions In Python | Python Trainin...
Python Functions Tutorial | Working With Functions In Python | Python Trainin...Python Functions Tutorial | Working With Functions In Python | Python Trainin...
Python Functions Tutorial | Working With Functions In Python | Python Trainin...
 
SymfonyCon Berlin 2016 - Symfony Plugin for PhpStorm - 3 years later
SymfonyCon Berlin 2016 - Symfony Plugin for PhpStorm - 3 years laterSymfonyCon Berlin 2016 - Symfony Plugin for PhpStorm - 3 years later
SymfonyCon Berlin 2016 - Symfony Plugin for PhpStorm - 3 years later
 
An Overview Of Python With Functional Programming
An Overview Of Python With Functional ProgrammingAn Overview Of Python With Functional Programming
An Overview Of Python With Functional Programming
 
Pres_python_talakhoury_26_09_2023.pdf
Pres_python_talakhoury_26_09_2023.pdfPres_python_talakhoury_26_09_2023.pdf
Pres_python_talakhoury_26_09_2023.pdf
 
Incredible Machine with Pipelines and Generators
Incredible Machine with Pipelines and GeneratorsIncredible Machine with Pipelines and Generators
Incredible Machine with Pipelines and Generators
 
Performance and Scalability Testing with Python and Multi-Mechanize
Performance and Scalability Testing with Python and Multi-MechanizePerformance and Scalability Testing with Python and Multi-Mechanize
Performance and Scalability Testing with Python and Multi-Mechanize
 
Os lab final
Os lab finalOs lab final
Os lab final
 
Software Project Management
Software Project ManagementSoftware Project Management
Software Project Management
 
Scaling python webapps from 0 to 50 million users - A top-down approach
Scaling python webapps from 0 to 50 million users - A top-down approachScaling python webapps from 0 to 50 million users - A top-down approach
Scaling python webapps from 0 to 50 million users - A top-down approach
 
Web2py Code Lab
Web2py Code LabWeb2py Code Lab
Web2py Code Lab
 
Easy Web Project Development & Management with Django & Mercurial
Easy Web Project Development & Management with Django & MercurialEasy Web Project Development & Management with Django & Mercurial
Easy Web Project Development & Management with Django & Mercurial
 
Effective testing with pytest
Effective testing with pytestEffective testing with pytest
Effective testing with pytest
 
What's new in Python 3.11
What's new in Python 3.11What's new in Python 3.11
What's new in Python 3.11
 
Question 1 briefly respond to all the following questions. make
Question 1 briefly respond to all the following questions. make Question 1 briefly respond to all the following questions. make
Question 1 briefly respond to all the following questions. make
 
Python Programming - II. The Basics
Python Programming - II. The BasicsPython Programming - II. The Basics
Python Programming - II. The Basics
 
Functions_in_Python.pptx
Functions_in_Python.pptxFunctions_in_Python.pptx
Functions_in_Python.pptx
 
Python Programming Essentials - M17 - Functions
Python Programming Essentials - M17 - FunctionsPython Programming Essentials - M17 - Functions
Python Programming Essentials - M17 - Functions
 
Python Programming Essentials - M35 - Iterators & Generators
Python Programming Essentials - M35 - Iterators & GeneratorsPython Programming Essentials - M35 - Iterators & Generators
Python Programming Essentials - M35 - Iterators & Generators
 
服务框架: Thrift & PasteScript
服务框架: Thrift & PasteScript服务框架: Thrift & PasteScript
服务框架: Thrift & PasteScript
 
Pythonpresent
PythonpresentPythonpresent
Pythonpresent
 

More from Oon Arfiandwi

Create HTML5 Mobile Apps for WordPress Site
Create HTML5 Mobile Apps for WordPress SiteCreate HTML5 Mobile Apps for WordPress Site
Create HTML5 Mobile Apps for WordPress SiteOon Arfiandwi
 
Mobile Apps Business
Mobile Apps BusinessMobile Apps Business
Mobile Apps BusinessOon Arfiandwi
 
Android App Development using HTML5 Technology
Android App Development using HTML5 TechnologyAndroid App Development using HTML5 Technology
Android App Development using HTML5 TechnologyOon Arfiandwi
 
7Langit present Marketing and Monetizing on BlackBerry Platform
7Langit present Marketing and Monetizing on BlackBerry Platform7Langit present Marketing and Monetizing on BlackBerry Platform
7Langit present Marketing and Monetizing on BlackBerry PlatformOon Arfiandwi
 
7Langit present Mobile Ad on BlackBerry
7Langit present Mobile Ad on BlackBerry7Langit present Mobile Ad on BlackBerry
7Langit present Mobile Ad on BlackBerryOon Arfiandwi
 

More from Oon Arfiandwi (6)

Create HTML5 Mobile Apps for WordPress Site
Create HTML5 Mobile Apps for WordPress SiteCreate HTML5 Mobile Apps for WordPress Site
Create HTML5 Mobile Apps for WordPress Site
 
Mobile Apps Business
Mobile Apps BusinessMobile Apps Business
Mobile Apps Business
 
Google+ API (2012)
Google+ API (2012)Google+ API (2012)
Google+ API (2012)
 
Android App Development using HTML5 Technology
Android App Development using HTML5 TechnologyAndroid App Development using HTML5 Technology
Android App Development using HTML5 Technology
 
7Langit present Marketing and Monetizing on BlackBerry Platform
7Langit present Marketing and Monetizing on BlackBerry Platform7Langit present Marketing and Monetizing on BlackBerry Platform
7Langit present Marketing and Monetizing on BlackBerry Platform
 
7Langit present Mobile Ad on BlackBerry
7Langit present Mobile Ad on BlackBerry7Langit present Mobile Ad on BlackBerry
7Langit present Mobile Ad on BlackBerry
 

Recently uploaded

Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024Andreas Granig
 
CRM Contender Series: HubSpot vs. Salesforce
CRM Contender Series: HubSpot vs. SalesforceCRM Contender Series: HubSpot vs. Salesforce
CRM Contender Series: HubSpot vs. SalesforceBrainSell Technologies
 
Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)OPEN KNOWLEDGE GmbH
 
Intelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalmIntelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalmSujith Sukumaran
 
Introduction Computer Science - Software Design.pdf
Introduction Computer Science - Software Design.pdfIntroduction Computer Science - Software Design.pdf
Introduction Computer Science - Software Design.pdfFerryKemperman
 
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio, Inc.
 
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptxKnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptxTier1 app
 
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...soniya singh
 
英国UN学位证,北安普顿大学毕业证书1:1制作
英国UN学位证,北安普顿大学毕业证书1:1制作英国UN学位证,北安普顿大学毕业证书1:1制作
英国UN学位证,北安普顿大学毕业证书1:1制作qr0udbr0
 
EY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityEY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityNeo4j
 
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样umasea
 
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...Christina Lin
 
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)jennyeacort
 
Unveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML DiagramsUnveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML DiagramsAhmed Mohamed
 
SpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at RuntimeSpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at Runtimeandrehoraa
 
Building Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop SlideBuilding Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop SlideChristina Lin
 
Cloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEECloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEEVICTOR MAESTRE RAMIREZ
 
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024StefanoLambiase
 

Recently uploaded (20)

Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024
 
CRM Contender Series: HubSpot vs. Salesforce
CRM Contender Series: HubSpot vs. SalesforceCRM Contender Series: HubSpot vs. Salesforce
CRM Contender Series: HubSpot vs. Salesforce
 
Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)
 
Intelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalmIntelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalm
 
Introduction Computer Science - Software Design.pdf
Introduction Computer Science - Software Design.pdfIntroduction Computer Science - Software Design.pdf
Introduction Computer Science - Software Design.pdf
 
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
 
2.pdf Ejercicios de programación competitiva
2.pdf Ejercicios de programación competitiva2.pdf Ejercicios de programación competitiva
2.pdf Ejercicios de programación competitiva
 
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptxKnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
 
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
 
Hot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort Service
Hot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort ServiceHot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort Service
Hot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort Service
 
英国UN学位证,北安普顿大学毕业证书1:1制作
英国UN学位证,北安普顿大学毕业证书1:1制作英国UN学位证,北安普顿大学毕业证书1:1制作
英国UN学位证,北安普顿大学毕业证书1:1制作
 
EY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityEY_Graph Database Powered Sustainability
EY_Graph Database Powered Sustainability
 
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
 
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
 
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)
 
Unveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML DiagramsUnveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML Diagrams
 
SpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at RuntimeSpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at Runtime
 
Building Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop SlideBuilding Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
 
Cloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEECloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEE
 
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
 

Pemrograman Python untuk Pemula

  • 1. Pemrograman dengan Python untuk Pemula oon arfiandwi http://oo.or.id/py
  • 2. Material ini digunakan untuk kelas teknologi pengenalan pemrograman dengan bahasa pengantar Python http://oo.or.id/py Dipublikasikan dengan lisensi Atribusi-Berbagi Serupa Creative Commons (CC BY-SA) oleh oon@oo.or.id
  • 3. Tools to Install Download Python 2.7 from http://python.org/download or you can easly use online Python interpreter For Google Cloud Platform topic: Google App Engine SDK for Python from https: //cloud.google.com/appengine/downloads Pip Python Package Manager from http://pip.pypa. io/en/latest/installing.html
  • 4. Outline Python intro Type, Variable, Value Functions Conditional Iteration String processing Intro to Google Cloud Platform with Python
  • 5. Reference http://www.greenteapress.com/thinkpython/ http://www.pythonlearn.com/ http://www.diveintopython.net/ https://www.python.org/download/ http://pythoncentral.org/comparison-of-python-ides- development/
  • 6. Software/Program/App compiled or interpreted (or both) input-process-output (decide input & output, think about the process) syntax and semantic >>> 1 + 2 = 3 >>> panjang = 3 >>> lebar = 4 >>> luas = panjang + lebar
  • 7. Python ➔ High-level language ➔ Interactive mode & Scripting mode ➔ Online interpreter ◆ http://www.skulpt.org/ ◆ http://pythontutor.com/ ➔ case sensitive
  • 8. Python Brochure | http://getpython.info
  • 9. Introduction to Python with Jessica McKellar
  • 10. Hello Python >>> print ‘Hello, World!’ Hello, World! >>> type(‘Hello, World!’) <type ‘str’> >>> print 1+2 3 >>> type(3) <type ‘int’> >>> type(‘1’)
  • 11. Type, Variable, Value >>> i = 1 (i adalah variable, dengan type int, memiliki value 1, diberi nilai dengan operator =) >>> kata = ‘nilai’ (kata adalah variable, dengan type str, memiliki value nilai) some of basic data type: Integer: int String: str Boolean: bool
  • 12. Variable Assignment >>> message=’message in the bottle’ >>> print message >>> type(message) >>> x=1 >>> x=x+2 >>> x+=3 >>> y=4 >>> print x*y
  • 13. Operator & Operand 1+2 (1 adalah operand, + adalah operator, 2 adalah operand) x < xx and z > y (operand? operator?) Order of operations: PEMDAS
  • 14. Indentation 4-space indents and no hard tab character
  • 15. Interactive Mode & Scripting Mode give sample of interactive mode on console give sample of scripting mode count_down.py
  • 16. List List is a sequence, of elements or items [1, 2, 3] ['ab', 'bc', 'cd', 'de'] ['ab', 'bc', 1, 2, 1.1, [True, False]]
  • 17. Array array.array is a wrapper of C arrays. can handle only homogeneous C array of data. so for common use, simply use List http://stackoverflow. com/questions/176011/python-list-vs-array-when- to-use
  • 18. Tuple >>> t = (1, 2, 3) >>> type(t) <type ‘tuple’> >>> print t >>> t = (‘hello’) >>> print t
  • 19. String String as sequence String slice String methods (intro OO first) String comparison in Operator
  • 20. String >>> kata = ‘pemrograman’ >>> print kata[4] >>> lenkata = len(kata) >>> print lenkata >>> print kata[lenkata-1] >>> for char in kata: … print char >>> print kata.upper()
  • 21. String Operations Concatenation >>> print ‘pemrograman’ + ‘python’
  • 22. Formatted Printing print 'formatting %s %d' % ('text', 7) http://forums.udacity. com/questions/2019688/python-101-unit-2- formatted-printing-and-function-documentation
  • 23. Conditional if if .. else .. if .. elif .. else ..
  • 24. Conditional sample >>> hari = ‘minggu’ >>> if hari == ‘sabtu’ or hari == ‘minggu’: … print ‘akhir pekan!’ … akhir pekan!
  • 25. boolean, and, or x and y akan bernilai True, jika keduanya True selain itu bernilai False x or y akan bernilai False, jika keduanya False selain itu bernilai True
  • 26. Conditional samples (2) >>> x = 4 >>> if x%2 == 0: … print ‘even’ … else: … print ‘odd’
  • 27. assignments buat kode program untuk mengecek apakah variable x itu positif atau negatif >>> x = -1 buat kode program untuk mengecek apakah variable x itu positif, negatif, atau nol >>> x = 0
  • 28. Conditional samples (3) >>> x = 7 >>> if x > 8: … print ‘A’ … elif x>6 and x<8: … print ‘B’ … else: … print ‘C’
  • 29. Functions Function call Add new functions Fruitful function, void function import importing with from
  • 30. function call and create function >>> type(True) >>> def apakah_genap(angka): … if angka%2 == 0: … print ‘benar, genap’ … else: … print ‘salah, ganjil’ >>> apakah_genap(7) >>> apakah_genap(100)
  • 31. function call and create function >>> def luas_persegi(panjang, lebar): … luas = panjang * lebar … return luas … >>> luasnya = luas_persegi(20, 30) >>> print luasnya
  • 32. import function >>> import math >>> print math >>> akar9 = math.sqrt(9) >>> print akar9
  • 33. assignment buat sebuah fungsi luas_lingkaran >>> luas_lingkaran(10) note: pi: math.pi input: jari-jari process: pi * jari-jari * jari-jari
  • 34. Iteration with while >>> x = 7 >>> while x>0: … print ‘data-%i’ % x … x = x -1
  • 35. assignment buat iteration menggunakan while, dalam sebuah fungsi, yang akan menampilkan hanya angka yang genap saja. >>> count_down_genap(4) 4 2
  • 36. Iteration while with break >>> while not ketemu: ... databerikut = cari_data() ... if databerikut == yangdicari: ... break ...
  • 37. Iteration with for >>> for i in range(3) … print ‘ulang’ >>> for i in range(5,10) … print i
  • 38. comments & docstring >>> xxx = 3 # var name xxx >>> print xxx
  • 40. Google Cloud Platform with Python let’s start by making a website using python Google Cloud Platform have a free tier of Google App Engine we’ll develop using Google App Engine SDK for Python https://developers.google.com/appengine/docs/python/gettingstartedpython27/introduction
  • 41. Google App Engine SDK for Python create 2 files on directory app.yaml main.py dev_appserver.py projectdir open http://localhost:8080/
  • 42. app.yaml application: waktusaatini version: 1 runtime: python27 api_version: 1 threadsafe: true handlers: - url: .* script: main.application libraries: - name: webapp2 version: latest
  • 43. main.py import datetime import webapp2 class MainPage(webapp2.RequestHandler): def get(self): message = ‘<p>waktu %s</p>’ % datetime.datetime.now() self.response.out.write(message); application = webapp2.WSGIApplication([(‘/’, MainPage)], debug=True)
  • 44. Template Engine Jinja2 install Jinja2 # pip install jinja2 3 Files: ● app.yaml ● main.py ● home.html Upload to appspot: # appcfg.py update kelas-teknologi/ Sample: http://kelas-teknologi.appspot.com
  • 45. app.yaml application: kelas-teknologi version: 1 runtime: python27 api_version: 1 threadsafe: true handlers: - url: .* script: main.application libraries: - name: webapp2 version: latest - name: jinja2 version: latest - name: markupsafe version: latest
  • 46. main.py import datetime import webapp2 import jinja2 import os from google.appengine.api import users template_env = jinja2.Environment( loader=jinja2.FileSystemLoader(os.getcwd()))
  • 47. main.py (cont’d) class MainPage(webapp2.RequestHandler): def get(self): current_time = datetime.datetime.now() user = users.get_current_user() login_url = users.create_login_url(self.request.path) logout_url = users.create_logout_url(self.request.path) template = template_env.get_template('home.html') context = { 'current_time': current_time, 'user': user, 'login_url': login_url, 'logout_url': logout_url, } self.response.out.write(template.render(context)) application = webapp2.WSGIApplication([('/', MainPage)], debug=True)
  • 48. home.html <html><head><title>The Time Is...</title></head> <body> {% if user %} <p> Welcome, <strong>{{ user.email() }}</strong>! You can <a href="{{ logout_url }}">sign out</a>. </p> {% else %} <p> Welcome! <a href="{{ login_url }}">Sign in or register</a> to customize. </p> {% endif %} <p>The time is: {{ current_time }}</p> </body></html>
  • 49. Web Form & Datastore 5 Files: ● app.yaml ● models.py ● main.py ● prefs.py ● home.html Upload to appspot: # appcfg.py update kelas-teknologi/ Sample: http://kelas-teknologi.appspot.com
  • 50. app.yaml application: kelas-teknologi version: 1 runtime: python27 api_version: 1 threadsafe: true handlers: - url: /prefs script: prefs.application login: required - url: .* script: main.application libraries: - name: webapp2 version: latest - name: jinja2 version: latest - name: markupsafe version: latest
  • 51. models.py from google.appengine.api import users from google.appengine.ext import db class UserPrefs(db.Model): tz_offset = db.IntegerProperty(default=0) user = db.UserProperty(auto_current_user_add=True) def get_userprefs(user_id=None): if not user_id: user = users.get_current_user() if not user: return None user_id = user.user_id() key = db.Key.from_path('UserPrefs', user_id) userprefs = db.get(key) if not userprefs: userprefs = UserPrefs(key_name=user_id) return userprefs
  • 52. main.py ...snip... import models ...snip... class MainPage(webapp2.RequestHandler): def get(self): current_time = datetime.datetime.now() user = users.get_current_user() userprefs = models.get_userprefs() if userprefs: current_time += datetime.timedelta(0, 0, 0, 0, 0, userprefs.tz_offset) ...snip... context = { 'current_time': current_time, 'user': user, 'login_url': login_url, 'logout_url': logout_url, 'userprefs': userprefs, } self.response.out.write(template.render(context)) application = webapp2.WSGIApplication([('/', MainPage)], debug=True)
  • 53. home.html <html><head><title>The Time Is...</title></head> <body> {% if user %} <p> Welcome, <strong>{{ user.email() }}</strong>! You can <a href="{{ logout_url }}">sign out</a>. </p> {% else %} <p> Welcome! <a href="{{ login_url }}">Sign in or register</a> to customize. </p> {% endif %} {% if user %} <form action="/prefs" method="post"> <label for="tz_offset"> Timezone offset from UTC (can be negative): </label> <input name="tz_offset" id="tz_offset" type="text" size="4" value="{{ userprefs.tz_offset }}" /> <input type="submit" value="Set" /> </form> {% endif %} <p>The time is: {{ current_time }}</p> </body></html>
  • 54. prefs.py import webapp2 import models class PrefsPage(webapp2.RequestHandler): def post(self): userprefs = models.get_userprefs() try: tz_offset = int(self.request.get('tz_offset')) userprefs.tz_offset = tz_offset userprefs.put() except ValueError: # User entered a value that wasn't an integer. Ignore for now. pass self.redirect('/') application = webapp2.WSGIApplication([('/prefs', PrefsPage)], debug=True)
  • 55. OO: Type - Class None
  • 57. Oon Arfiandwi Co-founder of 7Langit mobile agency http://oo.or.id/py http://google.com/+oonarfiandwi http://twitter.com/oonid http://about.me/oon