SlideShare a Scribd company logo
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 (20)

PPTX
Slide minggu 6 (citra digital)
Setia Juli Irzal Ismail
 
PPTX
Kelompok 8 - Implementasi Role & Privilege pada database Oracle & my SQL
Dejiko Chaem
 
PPTX
Kecerdasan bisnis
HehePangibulan2
 
PDF
Data Array
Simon Patabang
 
PDF
Teknik Enkripsi dan Dekripsi Playfair Cipher
Rivalri Kristianto Hondro
 
PPT
Pertemuan 2-pemecahan-masalah-ai
willyhayon
 
DOCX
Use skenario
Septyy Wulandary
 
PDF
Bab 11 citra biner
Syafrizal
 
PPT
Struktur Data Tree
Siti Khotijah
 
DOCX
Laporan Praktikum Basis Data Modul IV-Membuat Database Pada PHPMYADMIN
Shofura Kamal
 
DOC
Materi Kuliah : Dasar pemrograman 1
Braga Rezpect
 
PDF
pemetaan erd
ryzky_aka_babon
 
PDF
PowerPoint entity relationship diagram
uun setiawati
 
PDF
Contoh peyelesaian logika fuzzy
Zaenal Khayat
 
DOCX
Proposal pembuatan aplikasi
HIMATIF UIN SGD
 
PPTX
Jenis dan proses interupsi
laurensius08
 
PPT
Algoritma penjadwalan proses
Rakhmi Khalida, M.M.S.I
 
PPT
Struktur direktori
Anggi DHARMA
 
PPTX
Sistem basis data 4
Fendi Hidayat
 
PPTX
Model data relasional (3)
Fariszal Nova
 
Slide minggu 6 (citra digital)
Setia Juli Irzal Ismail
 
Kelompok 8 - Implementasi Role & Privilege pada database Oracle & my SQL
Dejiko Chaem
 
Kecerdasan bisnis
HehePangibulan2
 
Data Array
Simon Patabang
 
Teknik Enkripsi dan Dekripsi Playfair Cipher
Rivalri Kristianto Hondro
 
Pertemuan 2-pemecahan-masalah-ai
willyhayon
 
Use skenario
Septyy Wulandary
 
Bab 11 citra biner
Syafrizal
 
Struktur Data Tree
Siti Khotijah
 
Laporan Praktikum Basis Data Modul IV-Membuat Database Pada PHPMYADMIN
Shofura Kamal
 
Materi Kuliah : Dasar pemrograman 1
Braga Rezpect
 
pemetaan erd
ryzky_aka_babon
 
PowerPoint entity relationship diagram
uun setiawati
 
Contoh peyelesaian logika fuzzy
Zaenal Khayat
 
Proposal pembuatan aplikasi
HIMATIF UIN SGD
 
Jenis dan proses interupsi
laurensius08
 
Algoritma penjadwalan proses
Rakhmi Khalida, M.M.S.I
 
Struktur direktori
Anggi DHARMA
 
Sistem basis data 4
Fendi Hidayat
 
Model data relasional (3)
Fariszal Nova
 

Viewers also liked (8)

DOCX
My sql dari pemula hingga mahir
Denny Yahya
 
PDF
Hendri python
Char Lie
 
PPTX
Oracle SQL Developer Tips & Tricks
Jeff Smith
 
PDF
Tutorial Migrasi Database dari Microsoft SQL Server ke Oracle Database
Hari Kurnia
 
PPTX
Dimensional modeling in oracle sql developer
Jeff Smith
 
PDF
Belajar netbeans java pemula dari 0 sampai mahir
harisonmtd
 
ODP
ORACLE Di Virtual Box : Ringkasan Penggunaan
Agus SA
 
DOCX
Laporan praktikum modul 6 pemrogrman database dengan jdbc
Devi Apriansyah
 
My sql dari pemula hingga mahir
Denny Yahya
 
Hendri python
Char Lie
 
Oracle SQL Developer Tips & Tricks
Jeff Smith
 
Tutorial Migrasi Database dari Microsoft SQL Server ke Oracle Database
Hari Kurnia
 
Dimensional modeling in oracle sql developer
Jeff Smith
 
Belajar netbeans java pemula dari 0 sampai mahir
harisonmtd
 
ORACLE Di Virtual Box : Ringkasan Penggunaan
Agus SA
 
Laporan praktikum modul 6 pemrogrman database dengan jdbc
Devi Apriansyah
 
Ad

Similar to Pemrograman Python untuk Pemula (20)

PPTX
Basic Python Programming: Part 01 and Part 02
Fariz Darari
 
PPTX
4. Tools Proyek Data Science DTS-TA v.3.pptx
irvaimuhammad
 
KEY
Gae icc fall2011
Juan Gomez
 
PDF
Google app-engine-with-python
Deepak Garg
 
PPTX
IoT-Week1-Day1-Lab.pptx
afsheenfaiq2
 
PDF
Pythonintro
Hardik Malhotra
 
PPTX
#Code2Create: Python Basics
GDGKuwaitGoogleDevel
 
PPTX
Python chapter presentation details.pptx
linatalole2001
 
PPTX
Dr.C S Prasanth-Physics ppt.pptx computer
kavitamittal18
 
PDF
Class 2: Welcome part 2
Marc Gouw
 
PPTX
Learning python
Hoang Nguyen
 
PPTX
Learning python
Harry Potter
 
PPTX
Learning python
Tony Nguyen
 
PPTX
Learning python
Luis Goldster
 
PPTX
Learning python
James Wong
 
PPTX
Learning python
Young Alista
 
PPTX
Learning python
Fraboni Ec
 
PDF
Python于Web 2.0网站的应用 - QCon Beijing 2010
Qiangning Hong
 
PPTX
PYTHON PROGRAMMING
indupps
 
PDF
Python From Scratch (1).pdf
NeerajChauhan697157
 
Basic Python Programming: Part 01 and Part 02
Fariz Darari
 
4. Tools Proyek Data Science DTS-TA v.3.pptx
irvaimuhammad
 
Gae icc fall2011
Juan Gomez
 
Google app-engine-with-python
Deepak Garg
 
IoT-Week1-Day1-Lab.pptx
afsheenfaiq2
 
Pythonintro
Hardik Malhotra
 
#Code2Create: Python Basics
GDGKuwaitGoogleDevel
 
Python chapter presentation details.pptx
linatalole2001
 
Dr.C S Prasanth-Physics ppt.pptx computer
kavitamittal18
 
Class 2: Welcome part 2
Marc Gouw
 
Learning python
Hoang Nguyen
 
Learning python
Harry Potter
 
Learning python
Tony Nguyen
 
Learning python
Luis Goldster
 
Learning python
James Wong
 
Learning python
Young Alista
 
Learning python
Fraboni Ec
 
Python于Web 2.0网站的应用 - QCon Beijing 2010
Qiangning Hong
 
PYTHON PROGRAMMING
indupps
 
Python From Scratch (1).pdf
NeerajChauhan697157
 
Ad

More from Oon Arfiandwi (6)

PDF
Create HTML5 Mobile Apps for WordPress Site
Oon Arfiandwi
 
PDF
Mobile Apps Business
Oon Arfiandwi
 
PDF
Google+ API (2012)
Oon Arfiandwi
 
PPTX
Android App Development using HTML5 Technology
Oon Arfiandwi
 
KEY
7Langit present Marketing and Monetizing on BlackBerry Platform
Oon Arfiandwi
 
PDF
7Langit present Mobile Ad on BlackBerry
Oon Arfiandwi
 
Create HTML5 Mobile Apps for WordPress Site
Oon Arfiandwi
 
Mobile Apps Business
Oon Arfiandwi
 
Google+ API (2012)
Oon Arfiandwi
 
Android App Development using HTML5 Technology
Oon Arfiandwi
 
7Langit present Marketing and Monetizing on BlackBerry Platform
Oon Arfiandwi
 
7Langit present Mobile Ad on BlackBerry
Oon Arfiandwi
 

Recently uploaded (20)

PDF
Wondershare PDFelement Pro Crack for MacOS New Version Latest 2025
bashirkhan333g
 
PDF
MiniTool Partition Wizard Free Crack + Full Free Download 2025
bashirkhan333g
 
PPTX
Why Businesses Are Switching to Open Source Alternatives to Crystal Reports.pptx
Varsha Nayak
 
PDF
SAP Firmaya İade ABAB Kodları - ABAB ile yazılmıl hazır kod örneği
Salih Küçük
 
PPTX
Tally_Basic_Operations_Presentation.pptx
AditiBansal54083
 
PDF
[Solution] Why Choose the VeryPDF DRM Protector Custom-Built Solution for You...
Lingwen1998
 
PPTX
AEM User Group: India Chapter Kickoff Meeting
jennaf3
 
PDF
Automate Cybersecurity Tasks with Python
VICTOR MAESTRE RAMIREZ
 
PDF
TheFutureIsDynamic-BoxLang witch Luis Majano.pdf
Ortus Solutions, Corp
 
PDF
Download Canva Pro 2025 PC Crack Full Latest Version
bashirkhan333g
 
PPTX
Agentic Automation: Build & Deploy Your First UiPath Agent
klpathrudu
 
PDF
Build It, Buy It, or Already Got It? Make Smarter Martech Decisions
bbedford2
 
PPTX
Agentic Automation Journey Session 1/5: Context Grounding and Autopilot for E...
klpathrudu
 
PDF
Generic or Specific? Making sensible software design decisions
Bert Jan Schrijver
 
PDF
iTop VPN With Crack Lifetime Activation Key-CODE
utfefguu
 
PDF
Empower Your Tech Vision- Why Businesses Prefer to Hire Remote Developers fro...
logixshapers59
 
PDF
vMix Pro 28.0.0.42 Download vMix Registration key Bundle
kulindacore
 
PDF
4K Video Downloader Plus Pro Crack for MacOS New Download 2025
bashirkhan333g
 
PPTX
ChiSquare Procedure in IBM SPSS Statistics Version 31.pptx
Version 1 Analytics
 
PDF
Why Businesses Are Switching to Open Source Alternatives to Crystal Reports.pdf
Varsha Nayak
 
Wondershare PDFelement Pro Crack for MacOS New Version Latest 2025
bashirkhan333g
 
MiniTool Partition Wizard Free Crack + Full Free Download 2025
bashirkhan333g
 
Why Businesses Are Switching to Open Source Alternatives to Crystal Reports.pptx
Varsha Nayak
 
SAP Firmaya İade ABAB Kodları - ABAB ile yazılmıl hazır kod örneği
Salih Küçük
 
Tally_Basic_Operations_Presentation.pptx
AditiBansal54083
 
[Solution] Why Choose the VeryPDF DRM Protector Custom-Built Solution for You...
Lingwen1998
 
AEM User Group: India Chapter Kickoff Meeting
jennaf3
 
Automate Cybersecurity Tasks with Python
VICTOR MAESTRE RAMIREZ
 
TheFutureIsDynamic-BoxLang witch Luis Majano.pdf
Ortus Solutions, Corp
 
Download Canva Pro 2025 PC Crack Full Latest Version
bashirkhan333g
 
Agentic Automation: Build & Deploy Your First UiPath Agent
klpathrudu
 
Build It, Buy It, or Already Got It? Make Smarter Martech Decisions
bbedford2
 
Agentic Automation Journey Session 1/5: Context Grounding and Autopilot for E...
klpathrudu
 
Generic or Specific? Making sensible software design decisions
Bert Jan Schrijver
 
iTop VPN With Crack Lifetime Activation Key-CODE
utfefguu
 
Empower Your Tech Vision- Why Businesses Prefer to Hire Remote Developers fro...
logixshapers59
 
vMix Pro 28.0.0.42 Download vMix Registration key Bundle
kulindacore
 
4K Video Downloader Plus Pro Crack for MacOS New Download 2025
bashirkhan333g
 
ChiSquare Procedure in IBM SPSS Statistics Version 31.pptx
Version 1 Analytics
 
Why Businesses Are Switching to Open Source Alternatives to Crystal Reports.pdf
Varsha Nayak
 

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 [email protected]
  • 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