Tutorial Python untuk bukan pengatur cara/Fungsi: Perbezaan antara semakan

Kandungan dihapus Kandungan ditambah
Unexistance (bincang | sumb.)
Unexistance (bincang | sumb.)
Baris 121:
Semasa didalam fungsi, <tt>a_var</tt> = 15 kerana fungsi tersebut dipanggil dengan <tt>a_func(b_var)</tt>. Disebabkan semasa itu <tt>b_var</tt> = 15, maka panggilan kepada fungsi tersebut menjadi <tt>a_func(15)</tt>. Ini menyebabkan <tt>a_var</tt> menjadi 15 semasa ia berada didalam <tt>a_func</tt>
 
Seperti yang dapat dilihat, sebaik sahaja fungsi <tt>a_func</tt> habis dijalankan, pembolehubah setempat <tt>a_var</tt> dan <tt>b_var</tt> akan hilang dan digantikan dengan pembolehubah yang asal. Kenyataan <tt>print "a_var = ", a_var</tt> akan memaparkan nilai <tt>10</tt> (bukan <tt>15</tt>) kerana pembolehubah setempat telah hilang.
As you can see, once the function finishes running, the local variables
<tt>a_var</tt> and <tt>b_var</tt> that had hidden the global variables of the same
name are gone. Then the statement <tt>print "a_var = ", a_var</tt> prints the
value <tt>10</tt> rather than the value <tt>15</tt> since the local variable
that hid the global variable is gone.
 
Perhatikan juga <tt>NameError</tt> yang berlaku. Pembolehubah <tt>d_var</tt> tidak lagi wujud kerana <tt>a_func</tt> telah habis dijalankan. Jika terdapat nilai yang dikehendaki dari sesuatu fungsi, bolehlah menggunakan <tt>return</tt>, contohnya <tt>return a_var</tt>.
Another thing to notice is the <tt>NameError</tt> that happens at the end.
This appears since the variable <tt>d_var</tt> no longer exists since
<tt>a_func</tt> finished. All the local variables are deleted when the function
exits. If you want to get something from a function, then you will have
to use <tt>return something</tt>.
 
Satu perkara lagi, perhatikan nilai <tt>e_var</tt> yang tidak berubah semasa didalam <tt>a_func</tt> kerana ia tidak menjadi parameter dan tiada kenyataan didalam fungsi tersebut yang mengubah nilainya.
One last thing to notice is that the value of <tt>e_var</tt> remains unchanged
inside <tt>a_func</tt> since it is not a parameter and it never appears on the
left of an equals sign inside of the function <tt>a_func</tt>. When a
global variable is accessed inside a function it is the global variable
from the outside.
 
Sesuatu fungsi membenarkan pembolehubah setempat wujud hanya didalam fungsi itu sahaja. Ia juga akan menyorokkan pembolehubah yang mempunyai nama yang sama diluar fungsi tersebut.
Functions allow local variables that exist only inside the function and
can hide other variables that are outside the function.
 
=== Examples ===