Functions: code you can reuse
A function is a named piece of code: you write it once and call it many times. It is declared with def, parameters go in parentheses, and return gives back the result. The lines inside a function are indented by 4 spaces.
def kvadrat(son):
return son * son
print(kvadrat(5))
print(kvadrat(12))Output25
144print shows a value on the screen, while return hands it back to the place that called the function: the returned value can be stored in a variable or passed to another function.
Functions are especially handy when working with artificial intelligence: a function builds a request with the same structure (a prompt template) and you pass in only the parts that change.
def prompt_yasa(rol, mavzu):
return f"Sen {rol} sifatida javob ber. Mavzu: {mavzu}."
print(prompt_yasa("ustoz", "kasr"))
print(prompt_yasa("tarjimon", "salomlashish"))OutputSen ustoz sifatida javob ber. Mavzu: kasr.
Sen tarjimon sifatida javob ber. Mavzu: salomlashish.Remember
def name(parameter):declares it,returngives back the result.printshows on the screen,returngives back a value.- If a function builds the prompt template, requests share the same structure.
Exercise
Given def ikki_baravar(x): return x * 2, what does print(ikki_baravar(4)) print?
Answer and explanation
- 4the function multiplies the argument by 2.
- 8 (correct answer)4 * 2 = 8:
returngives back this value andprintshows it. - ikki_baravarthat is the function’s name; it was called, so the result comes back.
Code exercises
- Write the function
salom_ber: it should return text in the formSalom, <ism>!.
Hint: Write an f-string afterreturn. - The function
prompt_yasa(rol, vazifa)should return two lines of text:Rol: ...on the first andVazifa: ...on the second.
Hint: To separate the two lines, put\n(the newline character) inside the text.
Do the exercise in the app.
Practical task
Write a prompt-template function that takes a role and a maximum answer length, and call it with 2 different values.
- I wrote the function
- I called it with 2 different values
Glossary
Interactive mode: search, progress and Python exercises.
