AI Ustoz UZ: learn artificial intelligence in Uzbek

Functions: code you can reuse

Beginner level · lesson 4 · about 12 min

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
144

print 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, return gives back the result.
  • print shows on the screen, return gives 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
  1. 4the function multiplies the argument by 2.
  2. 8 (correct answer)4 * 2 = 8: return gives back this value and print shows it.
  3. ikki_baravarthat is the function’s name; it was called, so the result comes back.

Code exercises

  1. Write the function salom_ber: it should return text in the form Salom, <ism>!.
    Hint: Write an f-string after return.
  2. The function prompt_yasa(rol, vazifa) should return two lines of text: Rol: ... on the first and Vazifa: ... 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.