Functions
Defining and calling
A function is defined with funksiya, a name, and a list of parameters in brackets. qaytar ends the function and gives a value back to the caller. A function that reaches its end without qaytar returns bo'sh.
funksiya yuza(eni, boyi):
qaytar eni * boyi
funksiya salomlash(ism):
chiqar(f"Salom, {ism}!")
chiqar(yuza(3, 4))
salomlash("Ali")
chiqar(salomlash("Guli"))12 Salom, Ali! Salom, Guli! bo'sh
A function must be defined before the line that calls it is run. Functions may call each other and themselves:
funksiya faktorial(n):
agar n <= 1:
qaytar 1
qaytar n * faktorial(n - 1)
chiqar(faktorial(5), faktorial(20))120 2432902008176640000
Default values
A parameter written as nom=qiymat has a default value and may be left out in a call. Parameters with defaults come after those without.
funksiya salom(ism, tabrik="Salom", belgi="!"):
qaytar f"{tabrik}, {ism}{belgi}"
chiqar(salom("Ali"))
chiqar(salom("Ali", "Xayr"))
chiqar(salom("Ali", belgi="?"))
chiqar(salom(belgi=".", ism="Guli"))
funksiya qosh(x, r=[]):
r.qo'sh(x)
qaytar r
chiqar(qosh(1), qosh(2))Salom, Ali! Xayr, Ali! Salom, Ali? Salom, Guli. [1] [2]
The default is worked out again at every call. That is why qosh(1) and qosh(2) above each get a fresh, empty list. A default may also use the parameters before it, as in funksiya kesim(r, oxiri=uzunlik(r)).
Named arguments
In a call, nom=qiymat gives an argument by the name of its parameter. Named arguments follow the positional ones and may come in any order, which makes calls with many optional parameters easy to read: salom("Ali", belgi="?").
Named arguments work for functions, methods and classes written in Algorizm. Built-in functions take positional arguments only.
Nameless functions
funksiya(parametrlar): ifoda is a function without a name. Its body is a single expression, and the value of that expression is returned. It is handy where a small function is needed only once, for example as the key for sorting.
ikkilantir = funksiya(x): x * 2
chiqar(ikkilantir(21))
chiqar(qo'lla(funksiya(x): x * x, [1, 2, 3]))
chiqar(filtrla(funksiya(x): x % 2 == 0, oraliq(10)))
chiqar(saralangan(["nok", "olma", "uzum"], funksiya(s): s[-1]))42 [1, 4, 9] [0, 2, 4, 6, 8] ["olma", "nok", "uzum"]
For anything longer than one expression, write an ordinary named function.
Functions are values
A function is a value like any other. It can be stored in a variable or a collection, passed to another function, and returned from one.
funksiya ikki_marta(f, x):
qaytar f(f(x))
funksiya uchni_qosh(x):
qaytar x + 3
chiqar(ikki_marta(uchni_qosh, 10))
amallar = {"qo'sh": funksiya(a, b): a + b, "ayir": funksiya(a, b): a - b}
chiqar(amallar["ayir"](9, 4))16 5
Scope: where a name is visible
A name assigned inside a function is local to that function: it exists only while the function runs and does not disturb a variable of the same name outside. Reading a variable from outside needs nothing special.
To assign to a variable that belongs to the module or to an enclosing function, declare it with global first.
hisob = 0
funksiya oshir():
global hisob
hisob += 1
oshir()
oshir()
chiqar(hisob)
funksiya hisoblagich():
son = 0
funksiya keyingisi():
global son
son += 1
qaytar son
qaytar keyingisi
sanoq = hisoblagich()
chiqar(sanoq(), sanoq(), sanoq())2 1 2 3
Closures
A function defined inside another function can use the variables of the outer one, and keeps them even after the outer function has returned. Here every function made by kopaytiruvchi remembers its own n.
funksiya kopaytiruvchi(n):
qaytar funksiya(x): x * n
uch_karra = kopaytiruvchi(3)
chiqar(uch_karra(5), kopaytiruvchi(10)(7))15 70
Generators
A function that contains ber is a generator. Calling it runs nothing yet. Each time a value is asked for, the function runs up to the next ber, hands out that value, and pauses there until the next request. The values are produced one at a time and never stored together, so a generator may describe a very long, even endless, sequence.
funksiya juft_sonlar(chegara):
n = 0
toki n < chegara:
ber n
n += 2
har s ichida juft_sonlar(1000000):
agar s > 6:
to'xta
chiqar(s)
chiqar(yig'indi(juft_sonlar(11)), ro'yxat(juft_sonlar(7)))
t = takrorlagich([10, 20])
chiqar(keyingi(t), keyingi(t), keyingi(t, "tugadi"))0 2 4 6 30 [0, 2, 4, 6] 10 20 tugadi
Generators work with har and with every built-in function that takes a sequence, such as ro'yxat, yig'indi and saralangan. A generator can be gone through only once.
takrorlagich(r) gives the same one-at-a-time access to any sequence, and keyingi(t) takes the next item. At the end keyingi raises an error, unless a second argument gives the value to return instead.
ber cannot be written inside an urin block, and a function defined inside a generator cannot use the generator's variables.Next
Classes shows how to describe your own kinds of object.