Dasar-Dasar Fungsi dalam Python: Memahami Konsep Fundamental
Fungsi merupakan salah satu elemen penting dalam pemrograman Python (dan banyak bahasa pemrograman lainnya). Fungsi memungkinkan kita untuk mengatur dan menggunakan ulang kode dengan cara yang lebih efisien. Dengan membagi tugas menjadi bagian-bagian kecil yang dapat digunakan kembali, fungsi membantu kita menulis kode yang bersih, modular, dan mudah dipelihara. Dalam artikel ini, kita akan membahas apa itu fungsi, bagaimana cara kerjanya, serta cara membuat fungsi dari awal.
Apa Itu Fungsi?
Secara sederhana, fungsi adalah blok kode yang dirancang untuk melakukan tugas tertentu. Setiap fungsi biasanya memiliki tiga langkah utama:
- Menerima Input (Argumen): Fungsi menerima data sebagai input yang disebut "argumen". Data ini diproses oleh fungsi untuk mencapai hasil tertentu.
- Melakukan Sesuatu pada Input: Di dalam fungsi, data yang diterima diproses. Ini bisa berupa penghitungan, perubahan, atau operasi lainnya.
- Mengembalikan Output: Setelah fungsi selesai melakukan tugasnya, ia mengembalikan hasilnya sebagai output.
Mari kita lihat contoh fungsi sederhana, len(), yang digunakan untuk menghitung panjang sebuah daftar (list) dalam Python:
python
list_1 = [1, 2, 3, 4, 5]
print(len(list_1))
Dalam contoh di atas, fungsi len():
- Menerima
list_1sebagai input. - Menghitung jumlah elemen dalam daftar tersebut.
- Mengembalikan nilai
5sebagai output, karena ada lima elemen di dalamlist_1.
Mengapa Menggunakan Fungsi?
Fungsi membantu kita menghindari pengulangan kode. Bayangkan jika setiap kali kita ingin menghitung sesuatu atau melakukan operasi yang sama, kita harus menulis ulang logika tersebut. Dengan fungsi, kita hanya perlu menulisnya sekali dan dapat menggunakannya berulang kali dengan argumen yang berbeda.
Berikut beberapa manfaat utama menggunakan fungsi:
- Mengurangi Pengulangan Kode: Alih-alih menulis kode yang sama berkali-kali, Anda dapat memanggil fungsi yang sudah ada.
- Mempermudah Pemeliharaan Kode: Jika ada perubahan dalam logika, Anda hanya perlu mengubahnya di satu tempat (fungsi), bukan di seluruh program.
- Memperjelas Struktur Program: Kode yang dibagi ke dalam fungsi lebih mudah dipahami dan diikuti alurnya.
Membuat Fungsi Sendiri
Di Python, Anda dapat membuat fungsi sendiri menggunakan kata kunci def. Berikut adalah contoh fungsi sederhana yang menerima dua angka sebagai argumen dan mengembalikan hasil penjumlahannya:
python
def tambah(angka1, angka2):
return angka1 + angka2
Dalam contoh ini:
defdigunakan untuk mendefinisikan fungsi dengan namatambah.- Fungsi ini menerima dua parameter:
angka1danangka2. - Fungsi mengembalikan hasil penjumlahan dari kedua angka tersebut menggunakan kata kunci
return.
Kita bisa menggunakan fungsi tersebut seperti ini:
python
hasil = tambah(5, 10)
print(hasil) # Output: 15
Contoh Fungsi Sederhana
Misalnya, kita ingin menulis fungsi yang menghitung jumlah semua elemen dalam sebuah daftar tanpa menggunakan fungsi bawaan sum(). Kita bisa menulisnya seperti ini:
python
def jumlah_daftar(daftar_angka):
total = 0
for angka in daftar_angka:
total += angka
return total
Fungsi jumlah_daftar() menerima sebuah daftar sebagai input, kemudian menambahkan setiap elemen dalam daftar tersebut ke variabel total. Setelah semua elemen dijumlahkan, fungsi akan mengembalikan hasilnya.
Mari kita coba:
python
a_list = [1, 2, 3, 4, 5]
print(jumlah_daftar(a_list)) # Output: 15
Fungsi jumlah_daftar() bekerja sama seperti fungsi bawaan sum(), namun kita membuatnya sendiri untuk pemahaman yang lebih baik.
Fungsi Built-in vs Fungsi Buatan
Python sudah menyediakan banyak fungsi built-in yang bisa langsung digunakan seperti print(), len(), sum(), min(), dan max(). Fungsi-fungsi ini membantu menyelesaikan tugas umum dengan cepat dan mudah. Namun, ketika kita membutuhkan operasi yang lebih spesifik, kita bisa membuat fungsi buatan sendiri.
Tugas
1- Functions
Instructions
Compute the sum of a_list (already defined in the code editor) without using sum().
Initialize a variable named sum_manual with a value of 0.
Loop through a_list, and for each iteration add the current number to sum_manual.
Print sum_manual and sum(a_list) to check whether the values are the same.
2- Built-in Function
Instructions
Generate a frequency table for the ratings list, which is already initialized in the code editor.
Start by creating an empty dictionary named content_ratings.
Loop through the ratings list. For each iteration:
If the rating is already in content_ratings, then increment the frequency of that rating by 1.
Else, initialize the rating with a value of 1 inside the content_ratings dictionary.
Print content_ratings.
3- Creating our own Functions
Instructions
Recreate the square() function above and compute the square for numbers 10 and 16.
Assign the square of 10 to a variable named squared_10.
Assign the square of 16 to a variable named squared_16.
4- The Structure of Function
instructions
Create a function named add_10() that:
Takes a number as the input (name the input variable as you wish).
Adds the integer 10 to that number.
Returns the result of the addition.
Use the add_10() function to:
Add 10 to the number 30. Assign the result to a variable named add_30.
Add 10 to the number 90. Assign the result to a variable named add_90.
5- Parameters & Arguments
Instructions
Recreate the square() function by omitting the variable assignment step inside the function's body.
Without typing out the name of the parameter, use the new square() function to compute the square of the numbers 6 and 11.
Assign the square of 6 to a variable named squared_6.
Assign the square of 11 to a variable named squared_11.
6- Extract Values from any Column
Instructions
Write a function named extract() that can extract any column you want from the apps_data data set.
The function should take in the index number of a column as input (name the parameter as you want).
Inside the function's definition:
Create an empty list.
Loop through the apps_data data set (excluding the header). Extract only the value you want by using the parameter (which is expected to be an index number).
Append that value to the empty list.
Return the list containing the values of the column.
Use the extract() function to extract the values in the prime_genre column. Store them in a variable named genres. The index number of this column is 11.
7- Creating Frequency Tables
Instructions
Write a function named freq_table() that generates a frequency table for any list.
The function should take in a list as input.
Inside the function's body, write code that generates a frequency table for that list and stores the table in a dictionary.
Return the frequency table as a dictionary.
Use the freq_table() function on the genres list (already defined from the previous screen) to generate the frequency table for the prime_genre column. Store the frequency table to a variable named genres_ft.
Feel free to experiment with the extract() and freq_table() functions to easily create frequency tables for any column you want.
8- Writing a Single Function
Instructions
Write a function named freq_table() that generates a frequency table for any column in our iOS apps data set.
The function should take the index number of a column in as an input (name the parameter as you want).
Inside the function's body:
Loop through the apps_data data set (don't include the header row) and extract the value you want by using the parameter (which is expected to be an index number).
Build the frequency table as a dictionary.
The function should return the frequency table as a dictionary.
Use the freq_table() function to generate a frequency table for the user_rating column (the index number of this column is 7).
Store the table in a variable named ratings_ft.
9- Reusability & Multiple Parameters
Instructions
Update the current freq_table() function to make it more reusable.
The function should take in two inputs this time: a data set and the index of a column (name the parameters as you want).
Inside the function's body:
Loop through the data set using that parameter which is expected to be a data set (a list of lists). For each iteration, select the value you want by using the parameter which is expected to be an index number.
Build the frequency table as a dictionary.
The function should return the frequency table as a dictionary.
Use the updated freq_table() function to generate a frequency table for the user_rating column (the index number of this column is 7). Store the table in a variable named ratings_ft.
10- Keyword & Positional Arguments
Instructions
Use the freq_table() function to generate frequency tables for the cont_rating, user_rating, and prime_genre columns.
Use positional arguments when you generate the table for the cont_rating column (index number 10). Assign the table to a variable named content_ratings_ft.
Use keyword arguments for the user_rating column (index number 7) following the order (data_set, index). Assign the table to a variable named ratings_ft.
Use keyword arguments for the prime_genre column (index number 11) following the order (index, data_set). Assign the table to a variable named genres_ft.
11- Combining Functions
Instructions
Write a function named mean() that computes the mean for any column we want from a data set.
The function should take in two inputs: a data set and an index value.
Inside the body of the mean() function, use the extract() function to extract the values of a column into a separate list, and then compute the mean of the values in that list using find_sum() and find_length().
The function should return the mean of the column.
Use the mean() function to compute the mean of the price column (index number 4). Assign the result to a variable named avg_price.
12- Debugging Functions
Instructions¶
The code we provided in the code editor has several bugs (errors). Run the code, and then use the information provided in the tracebacks to debug the code.
Select all lines of code and press ctrl + / (PC) or ⌘ + / (Mac) to uncomment it so you can modify it.
For a demo of how this keyboard shortcut works, see this help article.
To understand what the bug is, read the general description of the error.
To understand where the bug is, follow the red arrows.
You'll see the arrows are represented as ---> or ^.
Note that there's more than one bug in the code we wrote. Once you debug an error, you'll get another error. This doesn't mean you're not making progress, on the contrary — you're closer to debugging the code completely.
Kesimpulan
Fungsi adalah alat penting dalam pemrograman yang memungkinkan kita untuk menulis kode yang lebih efisien, mudah dibaca, dan dapat digunakan kembali. Dengan memahami konsep dasar fungsi, kita bisa menyederhanakan program yang kita tulis, membuatnya lebih terstruktur, dan lebih mudah dipelihara. Selanjutnya, cobalah untuk membuat beberapa fungsi sendiri, dan lihat bagaimana fungsionalitas ini dapat membantu dalam proyek pemrograman Anda.
Komentar
Posting Komentar