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

Kandungan dihapus Kandungan ditambah
Algazel (bincang | sumb.)
kembang
Algazel (bincang | sumb.)
→‎Contoh: terjemah contoh
Baris 159:
 
=== Contoh ===
'''factorialfaktorial.py'''
<source lang="python">
# mentakrif fungsi yang mengira faktorial
#defines a function that calculates the factorial
 
def factorialfaktorial(n):
if n <= 1:
return 1
return n * factorialfaktorial(n - 1)
 
print "2! =", factorialfaktorial(2)
print "3! =", factorialfaktorial(3)
print "4! =", factorialfaktorial(4)
print "5! =", factorialfaktorial(5)
</source>
 
Baris 181:
5! = 120
 
'''countdownkira_detik.py'''
<source lang="python">
def count_downkira_detik(n):
print n
if n > 0:
return count_downkira_detik(n-1)
 
count_downkira_detik(5)
</source>
 
Baris 199:
0
 
Ulasan fungsi_menarik.py
Commented function_interesting.py
<source lang="python">
# Ulasan di bawah diberi nombor tingkat agar
# The comments below have been numbered as steps, to make explanation
# penjelasan kod lebih terang. Sila baca mengikut tingakatan.
# of the code easier. Please read according to those steps.
# (step numbertingkat 1, for examplecontohnya, is atada thedi bottombawah)
 
 
def mult(a, b): # (2.) ThisFungsi functionini willakan keepberulang repeatingkerana itself, because....
if b == 0:
return 0
restbaki = mult(a, b - 1) # (3.) ....Once itApabila reachessampai THISke SINI, thejujukan sequencebermula startskembali overdari againatas! and goes back to the top!
value = a + restbaki
return value # (4.) thereforejusteru, "return value" willtidak notakan happen until the program gets past step 3 aboveberlaku
# sehingga tingkat 3 dilewati program.
 
print "3 * 2 = ", mult(3, 2) # (1.) TheFungsi "mult" functionberasal willdi first initiate heresini
 
# ThePeristiwa "return value" eventdi atpenghujung thehanya endboleh can therefore only happenberlaku
# sebaik sahaja b sama dengan sifar (b mengurang dengan bilangan 1 setiap kali tingkat 3 berlaku).
# once b equals zero (b decreases by 1 everytime step 3 happens).
# Dan hanya pada masa itu baharu perintah "print" dipaparkan.
# And only then can the print command at the bottom be displayed.
 
# Lihatnya sebagai kesan "lompatan". Amnya apa yang anda perlu faham
# See it as kind of a "jump-around" effect. Basically, all you
# adalah fungsi dimulakan semual
# should really understand is that the function is reinitiated
# WITHINDALAM ITSELFDIRINYA atpada steptingkat 3. ThereforeJusteru, the sequencejujukan "jumpsmelompat" back
# toke the topatas.
</source>