In Python programming, functions are the key to building large programs. Building a complex program without them feels close to impossible. That is why understanding the concept of functions matters, and not only in Python.
This time you'll look at functions in Python along with a case example. Let's go..
In programming terms, a function is a block of code you use to solve a specific problem.
Form of a Function Block in Python
One function block in Python is marked by the def keyword, which signals a function definition. It is followed by the identifier, or the function name, and an optional part: the parameters.
In general, the format of a function in Python looks like this:
def <nama_fungsi>([param_1], [param_2], [param_n]):
<tubuh_fungsi>
nama_fungsi: the identifier used to call the function you createdparam_1,param_2, etc: the parameters or input given to the function (optional)tubuh_fungsi: the series of code that will run when the function is called
Remember! Indentation matters a lot in Python
An example of a correct function π
def print_hello():
print("Hello World!")
An example of a wrong function π
def print_hello():
print("Hello World!")
So don't forget the indentation, because you can end up with an error π«
Calling a Function in Python
A function in Python can't stand on its own. To use one, declaring it is not enough, because you have to call it as well.
To call a function, you write the identifier of that function followed by opening and closing parentheses. If the function takes parameters, you have to fill those in too.
The format looks like this:
<nama_fungsi>([param_1], [param_2], [param_n])
nama_fungsi: the identifier of the function being calledparam: the parameter given to the function for it to process (optional, depending on what the function needs)
You have probably seen this code beforeβ¦
print("Hello World")
print()
print("Belajar python bareng Inva")
Output:
Hello World
Belajar python bareng Inva
Whether you notice it or not, this print statement has already been calling a function. The print function takes an optional argument in the form of a string. You can fill it with 1 value or many values at once, or leave it empty.
A Case Example for Using Functions
Now that the format for creating and calling a function is clear, you'll try building one of your own.
Say a case asks you to print student data made up of name, age, class, and final score. That is simple enough, since it only needs the print command.
nama = "Inva"
umur = 18
kelas = "12 MIPA"
nilai = 94
print("Nama :", nama)
print("Umur :", umur, "tahun")
print("Kelas :", kelas)
print("Nilai :", nilai)
Output:
Nama : Inva
Umur : 18 tahun
Kelas : 12 MIPA
Nilai : 94
So far so good, with no trouble at all. Now another problem shows up: what about the other students? If that class has 30 students, imagine how many lines you would have to write to repeat that code 30 times.
To get around this problem you can use a function, so that giving arguments is enough for the student data to print.
The function you'll build this time is named cetak_data, with 4 arguments: nama, umur, kelas, and nilai. No need to write anything from scratch, since the earlier code only needs a small change:
def cetak_data(nama, umur, kelas, nilai): # declare the `cetak_data` function
print("Nama :", nama)
print("Umur :", umur, "tahun")
print("Kelas :", kelas)
print("Nilai :", nilai)
print() # add an empty line
cetak_data("Inva", 18, "12 MIPA", 94) # call the `cetak_data` function
cetak_data("Adi", 17, "11 IPS", 80)
cetak_data("Dita", 17, "10 BHS", 100)
Output:
Nama : Inva
Umur : 18 tahun
Kelas : 12 MIPA
Nilai : 94
Nama : Adi
Umur : 17 tahun
Kelas : 11 IPS
Nilai : 80
Nama : Dita
Umur : 17 tahun
Kelas : 10 BHS
Nilai : 100
Now that's shorter, since you don't call print over and over. The code you write is also easier to read. But what is actually happening?
def cetak_data(nama, umur, kelas, nilai): # declare the `cetak_data` function
print("Nama :", nama)
print("Umur :", umur, "tahun")
print("Kelas :", kelas)
print("Nilai :", nilai)
print() # add an empty line
...
First you declare a function named cetak_data and give it 4 parameter variables. These parameters work like variables in general, and only the way they are filled is different. A parameter variable can only be filled, and must be filled, when the function is called.
Inside the body of cetak_data you write the logic that matches the original goal, which is printing student data. The student data that gets printed (name, age, class, and score) comes from the parameter variables you provided earlier.
...
cetak_data("Inva", 18, "12 MIPA", 94) # call the `cetak_data` function
cetak_data("Adi", 17, "11 IPS", 80)
cetak_data("Dita", 17, "10 BHS", 100)
Next comes the call. Here you call the cetak_data function and fill in every parameter it has. What matters here is the order you fill them in. Because the declaration listed the parameters as nama, umur, kelas, nilai, you have to fill them in that order too. The number of arguments also can't be more or less than what you declared.
When the function is called, the parameters fill up and the function body runs according to its logic and the data you passed. At that point the function has finished running.
What Can You Do with a Function?
You aren't limited to the print command. Inside a function body you can put any Python code, as long as it's valid and fits the logic. Declaring variables, loops, branching, ternary, list comprehension all work in there. That is also why a function is often called a sub program, because every function can work like a program of its own.
Just as a demonstration, let's add a bit of branching to the code you already built.
def cetak_data(nama, umur, kelas, nilai): # declare the `cetak_data` function
predikat = "" # build the score predikat variable
if nilai > 94:
predikat = "A"
elif nilai > 82:
predikat = "B"
elif nilai > 72:
predikat = "C"
else:
predikat = "D"
print("Nama :", nama)
print("Umur :", umur, "tahun")
print("Kelas :", kelas)
print("Nilai :", nilai)
print("Predikat :", predikat)
print() # add an empty line
cetak_data("Inva", 18, "12 MIPA", 94) # call the `cetak_data` function
cetak_data("Adi", 17, "11 IPS", 80)
cetak_data("Dita", 17, "10 BHS", 100)
cetak_data("Budi", 18, "12 MIPA", 68)
Curious about the output? Try running it yourself π
Besides holding all of your Python code, a function body also has special statements and keywords you can only use inside function scope. A few of them are return and pass, which you'll cover next time.
What's Next?
After getting to know functions, next time you'll look at one of the special keywords inside them: the return statement in Python 3.
That's all for this one, and I hope it's useful. See ya π