Python function, module, and library#
Setelah membaca ini, pembaca diharapkan dapat memahami sintaks dasar Python (function, module, and library).
Function#
Sebuah reusable kode blok yang digunakan untuk menjalankan tugas tertentu.
# Defining a Function
def greet():
print("Hello, World!")
# calling a function
greet() # Output: Hello, World!
Hello, World!
# Fungsi dengan argument
def greet(name):
print(f"Hello, {name}!")
greet("Kang Mas Haryo Sinuwun") # Output: Hello, Kang Mas Haryo Sinuwun!
Hello, Kang Mas Haryo Sinuwun!
# keyword arguments
def describe_pet(animal_type, pet_name):
print(f"I have a {animal_type} named {pet_name}.")
describe_pet(pet_name="Willie", animal_type="dog")
# Output: I have a dog named Willie.
I have a dog named Willie.
Class#
Class adalah cetakan atau blueprint untuk membuat objek. Class memungkinkan kita mengelompokkan data (disebut atribut) dan fungsi (disebut method) ke dalam satu struktur. Bayangkan class seperti resep kue. Resepnya menjelaskan cara membuat kue, dan setiap objek dari class itu adalah kue nyata yang bisa dibuat dari resep tadi.
# Define the class
class Person:
def __init__(self, name, age):
self.name = name # instance variable
self.age = age # instance variable
def say_hello(self):
print(f"Hello, my name is {self.name} and I am {self.age} years old.")
# Create objects (instances) of the class
person1 = Person("Alice", 30)
person2 = Person("Bob", 25)
# Call method on objects
person1.say_hello() # Output: Hello, my name is Alice and I am 30 years old.
person2.say_hello() # Output: Hello, my name is Bob and I am 25 years old.
Hello, my name is Alice and I am 30 years old.
Hello, my name is Bob and I am 25 years old.
Module#
Modul adalah file yang berisi kode Python, yang dapat mencakup fungsi, kelas, dan variabel. Modul membantu mengatur kode ke dalam beberapa bagian yang mudah dikelola.
# mymodule.py
def greet(name):
return f"Hello, {name}!"
import mymodule
mymodule.greet("Kang Mas")
Output: Hello, Kang Mas
Example of Python standard module
## Modul standart python, misalnya math
import math
# Calculate the square root of 2
sqrt2 = math.sqrt(9)
print("Square root of 9:", sqrt2)
# Calculate the value of pi
pi = math.pi
print("Value of pi:", pi)
Square root of 9: 3.0
Value of pi: 3.141592653589793
Library#
Library atau package adalah suatu kumpulan module dalam satu direktori yang berisi file spesial bernama init.py.
mypackage/
__init__.py
module1.py
module2.py
Using package
# main.py
from mypackage import module1, module2
print(module1.func1()) # Output: Function 1 from Module 1
print(module2.func2()) # Output: Function 2 from Module 2
Example of Python standard library
The Python Standard Library contains a wide range of modules that provide access to system functionality.
import os
# Get current working directory
print(os.getcwd())
# List files in a directory
print(os.listdir())
# Create a directory
os.mkdir("new_directory")
/home/tyo/marinemet-training/1_
['1_0_intro.ipynb', '1_1_1_understanding_python_conda.ipynb', '1_1_2_jupyterlab.ipynb', '1_1_3_python_basic_syntax.ipynb', '1_1_4_python_function_mod_lib.ipynb', '1_2_python_libraries.ipynb', '1_3_data_manipulation.ipynb', 'Test.csv', '.ipynb_checkpoints', 'output.txt', 'new_directory', '1_4_data_visualization.ipynb']
---------------------------------------------------------------------------
FileExistsError Traceback (most recent call last)
Cell In[6], line 10
7 print(os.listdir())
9 # Create a directory
---> 10 os.mkdir("new_directory")
FileExistsError: [Errno 17] File exists: 'new_directory'