0% menganggap dokumen ini bermanfaat (0 suara)
82 tayangan14 halaman

Handout 2 PDF

1. Python memiliki banyak modul yang dapat diimpor untuk memperluas kemampuan bahasa tersebut. 2. Beberapa modul penting untuk pemrograman saintifik meliputi NumPy, SciPy, Matplotlib, dan Pandas. 3. Modul dapat diimpor secara keseluruhan atau sebagian untuk mengakses fungsi tertentu.

Diunggah oleh

mutia
Hak Cipta
© © All Rights Reserved
Kami menangani hak cipta konten dengan serius. Jika Anda merasa konten ini milik Anda, ajukan klaim di sini.
Format Tersedia
Unduh sebagai PDF, TXT atau baca online di Scribd
0% menganggap dokumen ini bermanfaat (0 suara)
82 tayangan14 halaman

Handout 2 PDF

1. Python memiliki banyak modul yang dapat diimpor untuk memperluas kemampuan bahasa tersebut. 2. Beberapa modul penting untuk pemrograman saintifik meliputi NumPy, SciPy, Matplotlib, dan Pandas. 3. Modul dapat diimpor secara keseluruhan atau sebagian untuk mengakses fungsi tertentu.

Diunggah oleh

mutia
Hak Cipta
© © All Rights Reserved
Kami menangani hak cipta konten dengan serius. Jika Anda merasa konten ini milik Anda, ajukan klaim di sini.
Format Tersedia
Unduh sebagai PDF, TXT atau baca online di Scribd
Anda di halaman 1/ 14

handout_1

January 30, 2020

1 Python sebagai Kalkulator


[2]: 3*15

[2]: 45

[3]: 6+21/3

[3]: 13.0

[4]: (6+21)/3

[4]: 9.0

1.1 pertanyaan:
1. Apakah urutan pengoperasian dalam Python, misal jika operasi - + / dan * muncul
bersamaan?
2. Bagaimana cara mengatur urutan operasi aritmetik agar sesuai dengan keinginan kita?

1.2 Operasi Aritmetik di Python

1
[6]: ## Contoh: --> ini adalah komentar, walaupun diketik di jenis code, tapi tidak␣
,→akan dijalankan oleh Python

12/7

[6]: 1.7142857142857142

[7]: 12//7 # bilangan bulat hasil bagi tanpa desimalnya

[7]: 1

[15]: 12%7 # sisa dari pembagian

[15]: 5

[9]: 12**7

[9]: 35831808

1.3 Latihan 1: tanpa menggunakan Python, tebak output dari operasi berikut:
1. 100 * 3 + 2 =
2. 5 + 100 / 20 =
3. 7 + 130 % 10 =
4. 100 // 9 * 2 =
5. 2 ** 3 - 5 =
6. (24 + 2) / (3 * 0) =
7. (3 * 0) / (2.5 * 0) =

2 Jenis bilangan
1. Integer: bilangan bulat. dapat berupa bilangan positif, negatif, atau bilangan yang sangat
panjang. contoh: 23, -142, 2324324598876
2. floating point: bilangan rasional (memiliki desimal). bilangan float dapat bernilai antara +-
210^(-308) hingga +- 210^(308). contoh: 36.0, 3.452423156564, 4.0, 1.877e+26
3. bilangan kompleks: gabungan dari bagian real dan imajinernya. contoh: bilangan kompleks
3 - 2i ditulis sebagai 3 - 2j pada Python, dimana j = akar(-1). contoh: (2+3j)*(-4+9j)

2.1 Latihan 2: tanpa menggunakan Python, tebaklah jenis bilangan yang men-
jadi output dari operasi berikut ini:
1. 3 + 6 / 2 ->
2. 23 / 5 ->
3. 27 // 8 ->
4. 2 ** 0.3 ->
5. 12.0 // 3. ->

2
6. 29.0 % 5. ->
7. -2.5 - 2j ** 2 ->
8. 1 + 5j // 2 ->

3 Variabel
variabel adalah nama yang digunakan untuk menyimpan data misal,
a = 23 p, q = 35, 2**0.5
[16]: a = 23

[17]: p, q = 35, 2**0.5

[19]: q

[19]: 1.4142135623730951

[20]: a + q

[20]: 24.414213562373096

[21]: q * p

[21]: 49.49747468305833

penamaan variabel bekerja dari kanan ke kiri, yaitu menyimpan nilai yang ada di sebelah kanan
ke nama variabel di sebelah kiri. contoh:
[25]: a = a + 2
a

[25]: 31

[26]: a = a + 2
a

[26]: 33

[28]: a += 2
a

[28]: 37

3.1 Latihan 3: Lakukan operasi berikut ini, kemudian analisis arti operatornya
masing-masing! Anda boleh menjalankan operasinya lebih dari satu kali
hingga benar-benar yakin dengan artinya.
gunakan variabel: c, d = 40, 74.4

3
1. c *= 3 c
2. d /= -2 d
3. d -= 5 d
4. c %= 3 c
5. c **= 2 c
6. d //= 4 d

3.2 Pemilihan nama variabel


• nama variabel di Python harus dimulai dengan huruf atau underscore _ (sebaiknya dimulai
dengan huruf saja)
• dapat diikuti karakter alfanumerik sebanyak mungkin, termasuk _
• spasi dan karakter lain yang bukan huruf atau angka tidak diperbolehkan
• case sensitive, sehingga variabel “bola” tidak sama dengan “Bola”
• tidak boleh menggunakan nama-nama yang sudah digunakan oleh Python sebagai nama
variabel

[ ]:

4 Modul-modul pada Python


Bahasa pemrograman Python terdiri dari bahasa “inti” plus banyak sekali kumpulan software tam-
bahan yang tergabung dalam “module” (atau “package”, yang merupakan kumpulan dari beberapa
module).
Banyak modul-modul yang sudah include saat menginstal Python, tapi banyak juga yang bisa
ditambahkan sesuai dengan kebutuhan.
Kita dapat menganalogikan modul sebagai “library”/perpustakaan yang dapat kita pinjam untuk
digunakan sementara waktu.
Untuk mengakses modul, gunakan syntax “import” yang akan dijelaskan di sesi berikutnya.

4
Ada 4 modul yang bukan bagian dari inti Python, namun akan digunakan dalam kuliah ini, sehingga
kita perlu menambahkan ke dalam Python kita:
1. NumPy
• standar package Python untuk pemrograman saintifik
• menyediakan struktur data array
• dapat digunakan untuk membuat dan memanipulasi array
• menyediakan fungsi dasar matematis trigonometri, exponensial, dan logaritme, juga
fungsi-fungsi spesial (misal, fungsi Bessel, dll), fungsi statistik dan generator bilangan
random
2. SciPy menyediakan fungsi matematis dan numerik untuk Python (lebih lengkap dibanding
NumPy)
3. MatplotLib package standar untuk membuat plot 2D dan 3D
4. Panda menyediakan alat untuk menganalisis data. menggunakan struktur data yang mirip
dengan program seperti Excel, dapat digunakan untuk memanipulasi data seperti spreadsheet
untuk menambahkan module-module tersebut ke Python:
!pip install NumPy
!pip install SciPy
!pip install MatplotLib
!pip install Panda

4.1 contoh penggunaan Modul


[2]: import numpy

numpy.sin(0.5)

[2]: 0.479425538604203

[3]: import math

math.sin(0.5)

[3]: 0.479425538604203

[4]: numpy.sin(3+4j)

[4]: (3.853738037919377-27.016813258003932j)

[5]: math.sin(3+4j)


,→---------------------------------------------------------------------------

5
TypeError Traceback (most recent call␣
last)
,→

<ipython-input-5-b48edfeaf02a> in <module>
----> 1 math.sin(3+4j)

TypeError: can't convert complex to float

fungsi sin pada modul math hanya menerima satu bilangan riil sebagai input, sedangkan pada
modul numpy bisa menerima bilangan riil dan kompleks
[6]: ## cara lain untuk menggunakan modul:

import numpy as np

np.exp(5)

[6]: 148.4131591025766

[7]: np.arctan(-3-4j)

[7]: (-1.4483069952314644-0.15899719167999918j)

6
4.2 Beberapa fungsi NumPy

[8]: # contoh penggunaan:

np.log(np.sin(0.5))

[8]: -0.7351666863853142

[9]: np.log(np.sin(0.5)+1)

[9]: 0.3916538628347176

[10]: np.sqrt(345*231/34)

[10]: 48.414569999487696

7
5 Cara-cara mengimport Modul
5.1 Import keseluruhan modul
import math
import numpy as np
sudut = np.sin(78)

5.2 Import sebagian modul


hanya mengimport fungsi yang akan digunakan saja misal:
from numpy import sin
sudut2 = sin(90)
atau:
from numpy import log, sin, cos
sudut3 = sin(log(cos(45)))

5.3 Import keseluruhan modul tanpa harus menggunakan prefix


from numpy import *
kekurangan: jika kita mengimport lebih dari satu modul dengan cara ini, sulit memastikan fungsi
mana yang berasal dari modul mana dengan hanya melihat script, karena bisa jadi dua library
menyediakan fungsi yang sama dengan cara yang beda (seperti kasus fungsi sin pada math dan
numpy) –> tidak direkomendasikan untuk mengimport modul dengan cara ini

6 Tersesat di Python? Gunakah help!


[11]: help(complex)

Help on class complex in module builtins:

class complex(object)
| complex(real=0, imag=0)
|
| Create a complex number from a real part and an optional imaginary part.
|
| This is equivalent to (real + imag*1j) where imag defaults to 0.
|
| Methods defined here:
|
| __abs__(self, /)
| abs(self)
|
| __add__(self, value, /)

8
| Return self+value.
|
| __bool__(self, /)
| self != 0
|
| __divmod__(self, value, /)
| Return divmod(self, value).
|
| __eq__(self, value, /)
| Return self==value.
|
| __float__(self, /)
| float(self)
|
| __floordiv__(self, value, /)
| Return self//value.
|
| __format__(…)
| complex.__format__() -> str
|
| Convert to a string according to format_spec.
|
| __ge__(self, value, /)
| Return self>=value.
|
| __getattribute__(self, name, /)
| Return getattr(self, name).
|
| __getnewargs__(…)
|
| __gt__(self, value, /)
| Return self>value.
|
| __hash__(self, /)
| Return hash(self).
|
| __int__(self, /)
| int(self)
|
| __le__(self, value, /)
| Return self<=value.
|
| __lt__(self, value, /)
| Return self<value.
|
| __mod__(self, value, /)
| Return self%value.
|

9
| __mul__(self, value, /)
| Return self*value.
|
| __ne__(self, value, /)
| Return self!=value.
|
| __neg__(self, /)
| -self
|
| __pos__(self, /)
| +self
|
| __pow__(self, value, mod=None, /)
| Return pow(self, value, mod).
|
| __radd__(self, value, /)
| Return value+self.
|
| __rdivmod__(self, value, /)
| Return divmod(value, self).
|
| __repr__(self, /)
| Return repr(self).
|
| __rfloordiv__(self, value, /)
| Return value//self.
|
| __rmod__(self, value, /)
| Return value%self.
|
| __rmul__(self, value, /)
| Return value*self.
|
| __rpow__(self, value, mod=None, /)
| Return pow(value, self, mod).
|
| __rsub__(self, value, /)
| Return value-self.
|
| __rtruediv__(self, value, /)
| Return value/self.
|
| __str__(self, /)
| Return str(self).
|
| __sub__(self, value, /)
| Return self-value.
|

10
| __truediv__(self, value, /)
| Return self/value.
|
| conjugate(…)
| complex.conjugate() -> complex
|
| Return the complex conjugate of its argument. (3-4j).conjugate() ==
3+4j.
|
| ----------------------------------------------------------------------
| Static methods defined here:
|
| __new__(*args, **kwargs) from builtins.type
| Create and return a new object. See help(type) for accurate signature.
|
| ----------------------------------------------------------------------
| Data descriptors defined here:
|
| imag
| the imaginary part of a complex number
|
| real
| the real part of a complex number

[15]: help(np.array)

Help on built-in function array in module numpy:

array(…)
array(object, dtype=None, copy=True, order='K', subok=False, ndmin=0)

Create an array.

Parameters
----------
object : array_like
An array, any object exposing the array interface, an object whose
__array__ method returns an array, or any (nested) sequence.
dtype : data-type, optional
The desired data-type for the array. If not given, then the type will
be determined as the minimum type required to hold the objects in the
sequence. This argument can only be used to 'upcast' the array. For
downcasting, use the .astype(t) method.
copy : bool, optional
If true (default), then the object is copied. Otherwise, a copy will
only be made if __array__ returns a copy, if obj is a nested sequence,
or if a copy is needed to satisfy any of the other requirements

11
(`dtype`, `order`, etc.).
order : {'K', 'A', 'C', 'F'}, optional
Specify the memory layout of the array. If object is not an array, the
newly created array will be in C order (row major) unless 'F' is
specified, in which case it will be in Fortran order (column major).
If object is an array the following holds.

===== ========= ===================================================


order no copy copy=True
===== ========= ===================================================
'K' unchanged F & C order preserved, otherwise most similar order
'A' unchanged F order if input is F and not C, otherwise C order
'C' C order C order
'F' F order F order
===== ========= ===================================================

When ``copy=False`` and a copy is made for other reasons, the result is
the same as if ``copy=True``, with some exceptions for `A`, see the
Notes section. The default order is 'K'.
subok : bool, optional
If True, then sub-classes will be passed-through, otherwise
the returned array will be forced to be a base-class array (default).
ndmin : int, optional
Specifies the minimum number of dimensions that the resulting
array should have. Ones will be pre-pended to the shape as
needed to meet this requirement.

Returns
-------
out : ndarray
An array object satisfying the specified requirements.

See Also
--------
empty_like : Return an empty array with shape and type of input.
ones_like : Return an array of ones with shape and type of input.
zeros_like : Return an array of zeros with shape and type of input.
full_like : Return a new array with shape of input filled with value.
empty : Return a new uninitialized array.
ones : Return a new array setting values to one.
zeros : Return a new array setting values to zero.
full : Return a new array of given shape filled with value.

Notes
-----
When order is 'A' and `object` is an array in neither 'C' nor 'F' order,
and a copy is forced by a change in dtype, then the order of the result is

12
not necessarily 'C' as expected. This is likely a bug.

Examples
--------
>>> np.array([1, 2, 3])
array([1, 2, 3])

Upcasting:

>>> np.array([1, 2, 3.0])


array([ 1., 2., 3.])

More than one dimension:

>>> np.array([[1, 2], [3, 4]])


array([[1, 2],
[3, 4]])

Minimum dimensions 2:

>>> np.array([1, 2, 3], ndmin=2)


array([[1, 2, 3]])

Type provided:

>>> np.array([1, 2, 3], dtype=complex)


array([ 1.+0.j, 2.+0.j, 3.+0.j])

Data-type consisting of more than one element:

>>> x = np.array([(1,2),(3,4)],dtype=[('a','<i4'),('b','<i4')])
>>> x['a']
array([1, 3])

Creating an array from sub-classes:

>>> np.array(np.mat('1 2; 3 4'))


array([[1, 2],
[3, 4]])

>>> np.array(np.mat('1 2; 3 4'), subok=True)


matrix([[1, 2],
[3, 4]])

13
7 TUGAS 1:
buatlah kode Python untuk menyelesaikan soal berikut ini:

[ ]:

14

Anda mungkin juga menyukai