Sabtu, 24 September 2016

Kursus Python 5 hari lp2maray


Hari1:

  • instalasi+cara penggunaan
  • Tipe Data, Modifier, Operator dan Variabel pada Python
  • Membuat kalkulator matematika pada Pytho (Fungsi abs(x), Fungsi ceil(x),Fungsi exp(x),Fungsi fabs(x),Fungsi floor(x),Fungsi log(x),Fungsi log10(x),Fungsi max(x1, x2, x3, ...), Fungsi min (x1, x2, x3, ...), Fungsi modf(x),Fungsi pow(x,y), Fungsi round(x[,n]), Fungsi sqrt(x), Trigonometri, Radian dll)
  • penerapan logika Loop kontrol, Decision Making, if, switch, while, for, do



Hari2-Hari3:
  • Membuat kalkulator string pada Python
  • Creating Strings
  • String Length
  • Concatenating Strings
  • Format Strings
  • String Method, meliputi 
char charAt(int index)
Returns the character at the specified index.

int compareTo(String anotherString)
Compares two strings lexicographically.

int compareToIgnoreCase(String str)
Compares two strings lexicographically, ignoring case differences.

String concat(String str)
Concatenates the specified string to the end of this string.

boolean endsWith(String suffix)
Tests if this string ends with the specified suffix.

boolean equals(Object anObject)
Compares this string to the specified object.

boolean equalsIgnoreCase(String anotherString)
Compares this String to another String, ignoring case considerations.

int indexOf(int ch)
Returns the index within this string of the first occurrence of the specified character.

int indexOf(int ch, int fromIndex)
Returns the index within this string of the first occurrence of the specified character, starting the search at the specified index.

int lastIndexOf(String str, int fromIndex)
Returns the index within this string of the last occurrence of the specified substring, searching backward starting at the specified index.

int length()
Returns the length of this string.

String replace(char oldChar, char newChar)
Returns a new string resulting from replacing all occurrences of oldChar in this string with newChar.

String replaceAll(String regex, String replacement
Replaces each substring of this string that matches the given regular expression with the given replacement.

String[] split(String regex)
Splits this string around matches of the given regular expression.

String[] split(String regex, int limit)
Splits this string around matches of the given regular expression.

boolean startsWith(String prefix)
Tests if this string starts with the specified prefix.

CharSequence subSequence(int beginIndex, int endIndex)
Returns a new character sequence that is a subsequence of this sequence.

char[] toCharArray()
Converts this string to a new character array.

String toLowerCase()
Converts all of the characters in this String to lower case using the rules of the default locale.

String toLowerCase(Locale locale)
Converts all of the characters in this String to lower case using the rules of the given Locale.

String toString()
This object (which is already a string!) is itself returned.

String toUpperCase()
Converts all of the characters in this String to upper case using the rules of the default locale.

String trim()
Returns a copy of the string, with leading and trailing whitespace omitted.

static String valueOf(primitive data type x)
Returns the string representation of the passed data


Hari 4:
  • Instalasi dan Konfigurasi Database Mysql
  • Koneksi ke database mysql
  • Membaca isi tabel/read
  • Mengubah isi tabel/update
  • Menghapus isi tabel/delete
  • mencari isi tabel/search

Hari 5:
  • Membedah Array 1d, 2d, 3d
  • Implementasi Exception
  • Penerapan Method 
  • Penggunaan Files I/O
  • Contoh Date / Time
  • Trouble shooting

Belajar 5 hari @ 3 jam  (Total: 15 jam)
Khusus hanya u Mahasiswa RP. 400.000; include sertifikat






Python CRUD database mysql

hasil mysql pada phpmyadmin

Adapun codenya adalah sbb:
import MySQLdb
from time import gmtime, strftime
from random import randint


tgl=strftime("%Y-%m-%d", gmtime())
jam=strftime("%H:%M:%S", gmtime())
T=randint(25,40)

print 'waktu=',tgl,' jam ', jam
print 'T =',T ,' C'

db = MySQLdb.connect("localhost","root","","pythondb" )

cursor = db.cursor()
#cursor.execute("DROP TABLE IF EXISTS `tb_sensor`")

sql = """CREATE TABLE IF NOT EXISTS `tb_sensor` (
  `id` int(15) NOT NULL AUTO_INCREMENT,
  `tanggal` date NOT NULL,
  `jam` time NOT NULL,
  `sensor` int(15) NOT NULL,
  `status` varchar(15) NOT NULL,
  `note` text NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=3"""
try:
cursor.execute(sql)
except:
print('sukses membentuk tabel')

sql = 'INSERT INTO `tb_sensor` ( `tanggal`, `jam`, `sensor`, `status`, `note`) VALUES ("%s", "%s", "%d", "Y", "Sensor temperatur1")' % (tgl, jam, T)

try:
   cursor.execute(sql)
   db.commit()
except:
   db.rollback()
 
 
cursor.execute("SELECT * FROM tb_sensor")

count = 1
print 'No',' . ','ID',' | ','Tanggal',' | ','Jam',' | ','Sensor',' | ','Status',' | ','Note',' # '
print '=========================================================================# '
for row in cursor.fetchall():
print count,' . ',row[0],' | ',row[1],' | ',row[2],' | ',row[3],' | ',row[4],' | ',row[5],' # '
count = count + 1


db.close()



OK selamat mencoba friends.......

UNTUK UPDATE:
#!/usr/bin/python

import MySQLdb

# Open database connection
db = MySQLdb.connect("localhost","root","","pythondb" )

# prepare a cursor object using cursor() method
cursor = db.cursor()

# Prepare SQL query to UPDATE required records
sql = "UPDATE tb_sensor SET note = 'Sensor Lapangan 1'
                          WHERE id = '%d'" % (1)
try:
   # Execute the SQL command
   cursor.execute(sql)
   # Commit your changes in the database
   db.commit()
except:
   # Rollback in case there is any error
   db.rollback()

# disconnect from server
db.close()
#!/usr/bin/python

import MySQLdb

# Open database connection
db = MySQLdb.connect("localhost","root","","pythondb" )
# prepare a cursor object using cursor() method
cursor = db.cursor()

# Prepare SQL query to DELETE required records
sql = "DELETE FROM tb_sensor WHERE id> '%d'" % (20)
try:
   # Execute the SQL command
   cursor.execute(sql)
   # Commit your changes in the database
   db.commit()
except:
   # Rollback in case there is any error
   db.rollback()

# disconnect from server
db.close()

Koneksi Mysql menggunakan Python

1.setting path python dahulu....




2.download driver mysql-python for windows
https://pypi.python.org/pypi/MySQL-python/1.2.5

lalu install:

3.buat database dan tabel di localhost/phpmyadmin



CREATE TABLE IF NOT EXISTS `tb_sensor` (
  `id` int(15) NOT NULL AUTO_INCREMENT,
  `tanggal` date NOT NULL,
  `jam` time NOT NULL,
  `sensor` int(15) NOT NULL,
  `status` varchar(15) NOT NULL,
  `note` text NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=3 ;

--
-- Dumping data for table `tb_sensor`
--

INSERT INTO `tb_sensor` (`id`, `tanggal`, `jam`, `sensor`, `status`, `note`) VALUES
(1, '2016-09-25', '10:00:00', 35, 'Y', 'Sensor temperatur1'),
(2, '2016-09-25', '10:10:00', 36, 'Y', 'Sensor temperatur1');


4.buat code sbb

import MySQLdb

db = MySQLdb.connect(host="localhost",    # your host, usually localhost
                     user="root",         # your username
                     passwd="",  # your password
                     db="pythondb")        # name of the data base

cur = db.cursor()
cur.execute("SELECT * FROM tb_sensor")

count = 1
print 'No',' . ','ID',' | ','Tanggal',' | ','Jam',' | ','Sensor',' | ','Status',' | ','Note',' # '
print '=========================================================================# '
for row in cur.fetchall():
print count,' . ',row[0],' | ',row[1],' | ',row[2],' | ',row[3],' | ',row[4],' | ',row[5],' # '
count = count + 1
db.close()

Lalu jalankan:

OK Sip.....Selanjutnya tinggal CRUD: Create, Read, Update, Delete




Membuat Fungsi Python


wadah = "lp2m"
panjang = len(wadah)
firstletter=wadah[0]
lastletter=wadah[len(wadah)-1]
print "Panjang         : ",len(wadah)
print "Huruf pertama   : ",firstletter
print "Huruf terakhir  : ",lastletter

print "Susunan letter wadah di-looping : ", "\n"
hit=0
for i in wadah :
   print "Letter ke-",hit," adalah ",i
   hit+=1

#-------------------------------------------------------lat4.py
wadah='lp2maray.com'
index = 0
a=len(fruit)
while index < a:
   letter = wadah[index]
   print letter
   index = index + 1
---------------------------------------------lat5.py


fhand = open('D:\python\latihan\pesan.txt')
count = 0
for line in fhand:
    count = count + 1
print 'Line Count:', count  
#-------------------------------------------------------lat6.py
fhand = open('pesan.txt')
inp = fhand.read()
print len(inp)
print inp[:36]
#-------------------------------------------------------lat7.py
fhand = open('D:\python\latihan\pesan.txt')
inp = fhand.read()
p=len(inp)
print p
print inp[:36]
print('#############################')
print inp[:p]
#-------------------------------------------------------lat7.py


NIM=['1120329','1120330','1120332','1120333','1120335','1120336']
NAMA=['Riadi Marta Dinata','Rini Dyah Anggorowati','Jaka Laksamana','Andhika Indrajaya','Boy Chandra Sasmita',Khanza Humaira Dinata']
NOHP=['1628128283344','2628128281244','36281358281244','4628123456789','562817582812','6628535822322']


f = raw_input("Nama file tanpa extention : ")
fon = f + '.csv'
fo=open(fon,"a")
c=0
while c < 6  :
    print '%s ; %20s ; %13s \n' %(NIM[c],str(NAMA[c]),str(NOHP[c]))
    fo.write(str(NIM[c]) + "; " + str(NAMA[c]) + "; " + str(NOHP[c]) + "\n")
    c+=1
fo.close()

file yang terakhir akan menghasilkan file .xls di path instalasi python



-------------------------------------------------------------

def print_sayhello():
     print "Hallo, apa kabar?"
     print "Saya senang Anda dapat memiliki dan menggunkan buku kami ini."


#memanggil fungsi di sini

print_sayhello ()    

#-------------------------------------------------------
def faktorial (a):
  if a == 1 :
      print a
      return 1
  else :
      print a
      return ( a * faktorial(a-1))

#program utama

m=raw_input ('Masukkan angka : ')
try :
  x=int(m)
  hasil=faktorial(x)
  print "Hasil faktorial ",x," adalah ", hasil
except:
  print "Data yang dimasukan salah, ulangi!"
#-------------------------------------------------------

def hitung_luas_lingkaran():
    print "Menghitung luas lingkaran"
    radius = input("Jari-jari = ")
    luas = 3.14 * radius * radius
    print "Luas=", luas

def hitung_luas_persegipanjang():
    print "Menghitung luas persegi panjang"
    panjang = input("Panjang = ")
    lebar   = input("Lebar   = ")
    luas = panjang * lebar
    print "Luas=", luas


# Program utama
print "Menghitung luas"
print "1. Lingkaran"
print "2. Persegipanjang"

pilihan = input("Pilihan (1 atau 2): ")
if pilihan == 1:
    hitung_luas_lingkaran()
elif pilihan == 2:
    hitung_luas_persegipanjang()
else:
    print "Pilihan salah"
#--------------------------------------------

Instalasi dan Hello World Python on Windows / Linux

Python Download dimari: https://www.python.org/downloads/

Lalu install....disini saya installnya di D:\
OK siap-siap testing....


ketik sbb
print "Selamat Belajar Python"
print "Sukses!"


simpan di d:\python\latihan\lat1.py
lalu jalankan....



ok.........mudah yaaaaaaaaaaaaaaaaaaa.....

next....belajar lg yuk......
copas n jalankan tiap tiap blok:

#-------------------------------------------------------
nilai = input("Nilai ujian (0-100):")

if nilai >= 60:
    print "Lulus"
else:
    print "Tidak lulus"
#-------------------------------------------------------
tinggi = input("Tinggi segitiga: ")

baris = 1
while baris <= tinggi:
    print "*" * baris
    baris = baris + 1
#-------------------------------------------------------
x = 254

print "%d" % x
print "%8d" % x
print "%10d" % x

x = -254
y = 2.4678e-4

print "Format %%i: %i" % x
print "Format %%d: %d" % x
print "Format %%o: %o" % x
print "Format %%x: %x" % x
print "Format %%X: %X" % x
print "Format %%S: %s" % x

print "Format %%e: %e" % y
print "Format %%E: %E" % y
print "Format %%f: %f" % y
print "Format %%G: %G" % y
print "Format %%g: %g" % y
print "Format %%S: %s" % y

#-------------------------------------------------------
import math

kecepatan = input("Kecepatan: ")
sudut     = input("Sudut (derajat): ");

sudut = math.radians(sudut)
jarak = 2 * kecepatan * kecepatan * \
        math.sin(sudut) * math.cos(sudut) / 9.8

print "Jarak = ", jarak
#-------------------------------------------------------
nilai = input("Nilai ujian (0-100): ")

if nilai >= 90:
    print "A"
elif nilai >= 70:
    print "B"
elif nilai >= 60:
    print "C"
elif nilai >= 50:
    print "D"
else:
    print "E"
#-------------------------------------------------------
print "Menjumlah dua buah bilangan"

x = input("bilangan pertama: ")
y = input("bilangan kedua: ")

print "Jumlah = ",  (x+y)
#-------------------------------------------------------
while 1:
    try:
        bil = input("Masukkan bilangan: ")
        break
    except SyntaxError:
        print("Anda salah memasukkan bilangan")
    except KeyboardInterrupt:
        print("\nMaaf jangan menekan tombol Ctrl+C")

print "Anda memasukkan bilangan", bil



#-------------------------------------------------------

while 1:
    try:
        bil = input("Masukkan bilangan: ")
        break
    except SyntaxError:
        print("Anda salah memasukkan bilangan")

print "Anda memasukkan bilangan", bil
#-------------------------------------------------------
import time

bulan = ("Januari", "Pebruari", "Maret","April", "Mei", "Juni",  "Juli", "Agustus", "September", "Oktober", "Nopember", "Desember")
hari = ("Minggu", "Senin", "Selasa", "rabu", "Kamis", "Jumat", "Sabtu")

sekarang = time.time()
infowaktu = time.localtime(sekarang)
print "Saat sekarang :"
print "Tanggal", infowaktu[2], \
      bulan[infowaktu[1]-1], infowaktu[0]

print "Hari", hari[infowaktu[6]]
print "Jam", str(infowaktu[3]) + ":" + \
             str(infowaktu[4]) + ":" + \
             str(infowaktu[5])
#-------------------------------------------------------

daftar = ["1234", 2, "Edi", 1999]
jumlah = 0

for nilai in daftar:
    try:
        bil = int(nilai)
        jumlah = jumlah + 1
    except ValueError:
        pass

print "Jumlah elemen berupa bilangan:", jumlah
#-------------------------------------------------------
kalimat = raw_input("Masukkan suatu kalimat: ")
jumkar = {}
for kar in kalimat:
    jumkar[kar] = jumkar.get(kar,0) + 1

# Tampilkan frekuensi karakter
for kar in jumkar.keys():
    if kar == " ":
        print "Spasi = ",
    else:
        print kar, "=",

    print jumkar[kar]
#-------------------------------------------------------

daftar_nama = [ "Riadi Marta Dinata", "Rini Dyah Anggorowati","Khanza Humaira", "Jaka Laksamana",  "Andhika Indrajaya", "Boy Chandra Sasmita"]

dicari = raw_input("Penggalan nama yang dicari: ")

indeks = 0
ketemu = False

while indeks <= len(daftar_nama):
    if dicari in daftar_nama[indeks]:
        ketemu = True
        break

    indeks = indeks + 1

if ketemu:
    print "Nama yang Anda cari cocok dengan: "
    print daftar_nama[indeks]
else:
    print "Tak ada yang cocok"
#-------------------------------------------------------
inp = raw_input('Enter Fahrenheit Temperature:')
fahr = float(inp)
cel = (fahr - 32.0) * 5.0 / 9.0
print cel
#-------------------------------------------------------
a = False
b = True

print ("a or b = ", a or b)
print ("a and b = ", a and b)
print ("not a = ", not a)
print ("not b = ", not b)
#-------------------------------------------------------
a = 21
b = 10

if ( a == b ):
   print "Baris 1 - a sama dengan b"
else:
   print "Baris 1 - a tidak sama dengan b"

if ( a != b ):
   print "Baris 2 - a tidak sama dengan b"
else:
   print "Baris 2 - a sama dengan b"

if ( a <> b ):
   print "Baris 3 - a tidak sama dengan b"
else:
   print "Baris 3 - a sama dengan b"

if ( a < b ):
   print "Baris 4 - a kurang dari b"
else:
   print "Baris 4 - a tidak kurang dari b"

if ( a > b ):
   print "Baris 5 - a lebih dari b"
else:
   print "Baris 5 - a tidak lebih dari b"

a = 5;
b = 20;
if ( a <= b ):
   print "Baris 6 - a kurang dari atau sama dengan b"
else:
   print "Baris 6 - a tidak kurang dari b"

if ( b >= a ):
   print "Baris 7 - a lebih dari atau sama dengan b"
else:
   print "Baris 7 - a tidak lebih dari b"
#-------------------------------------------------------

a = 15            # 60 = 0011 1100
b = 12            # 13 = 0000 1101
c = 0

c = a & b;        # 12 = 0000 1100
print "Baris 1 - Nilai dari c adalah ", c

c = a | b;        # 61 = 0011 1101
print "Baris 2 - Nilai dari c adalah ", c

c = a ^ b;        # 49 = 0011 0001
print "Baris 3 - Nilai dari c adalah ", c

c = ~a;           # -61 = 1100 0011
print "Baris 4 - Nilai dari c adalah ", c

c = a << 2;       # 240 = 1111 0000
print "Baris 5 - Nilai dari c adalah ", c

c = a >> 2;       # 15 = 0000 1111
print "Baris 6 - Nilai dari c adalah ", c
#-------------------------------------------------------
x = raw_input ('Masukkan nilai x = ')
y = raw_input ('Masukkan nilai y = ')

if x < y:
   print 'x is less than y'
elif x > y:
   print 'x is greater than y'
else:
   print 'x and y are equal'
#-------------------------------------------------------
x = raw_input ('Masukkan nilai x = ')
y = raw_input ('Masukkan nilai y = ')

if x == y:
      print 'x dan y adalah sama'
else:
      if x < y:
            print 'x kurang dari y'
      else:
            print 'x is lebih dari y'

if 0 < x:
   if x < 10:
       print 'x is a positive single-digit number.'
#-------------------------------------------------------
inp = raw_input('Enter Fahrenheit Temperature:')
fahr = float(inp)
cel = (fahr - 32.0) * 5.0 / 9.0
print cel


#dengan try-except
inp = raw_input('Enter Fahrenheit Temperature:')
try:
  fahr = float(inp)
  cel = (fahr - 32.0) * 5.0 / 9.0
  print cel
except:
  print 'Please enter a number'
#-------------------------------------------------------
a = raw_input('Data masukan 1 :')
b = raw_input('Data masukan 2 :')

c=max(a)
d=min(b)

print c
print d
#-------------------------------------------------------

N=raw_input ("jumlah loop N = ")
try :
   m=int(N)
   while m > 0 :
      print m
      m=m-1

   print  "BLASTOFF!"
except :
    print "Salah entry data"
#-------------------------------------------------------
i=1
while 1:
   i +=1
   print i
   if i == 1000:
      i=0
#stop with KeyboardInterrupt: tekan CTRL C di Windwows dan CTRL Z di Raspberry
print 'selesai ...'
#-------------------------------------------------------
i=1
while 1:
   i +=1
   print i
   if i == 1000:
      break
#stop with break
print 'selesai ...'
#-------------------------------------------------------
while 1:
   print 'Ketik "done" untuk keluar dari loop ini'
   line = raw_input('> ')
   if line == 'done':
      break
   else :
      continue
   print line

print 'Done!'
 
#-------------------------------------------------------
temantemin = ['Edi', 'Faisal', 'Fajar']
for teman in temantemin:
   print 'Selamat bekerja kawanku,', teman,' !'

print 'SELESAI!'
 
#-------------------------------------------------------
data = [3, 41, 12, 9, 74, 15]
count = 0
for itervar in data:
      count = count + 1
      print count,itervar

print 'Count: ', count
#-------------------------------------------------------
data = [3, 41, 12, 9, 74, 15]
total = 0
for itervar in data:
      total = total + itervar
      print total
   
print 'Jumlah: ', total
#-------------------------------------------------------
data = [3, 41, 12, 9, 74, 15]
total = 0
for itervar in data:
      total = total + itervar
      print total
   
print 'Jumlah: ', total
#-------------------------------------------------------
data = [3, 41, 12, 9, 74, 15]
terbesar = None
print 'Sebelum: ', terbesar

for itervar in data:
      if terbesar is None or itervar > terbesar :
          terbesar = itervar
      print 'Loop:', itervar, terbesar

print 'Data terbesar : ', terbesar

#####################
NB setelah di jalankan lalu amati hasilnya juga maknai maksudnya OK Bisa yaaaa......