Python basics: print, variable, f-string, list and loop
Python runs code from top to bottom, line by line. To show a result on the screen you use print(); text (a string) is written in quotation marks.
print("Salom, dunyo!")OutputSalom, dunyo!A variable is a name attached to a value: the = sign attaches the value to the name. An f-string (an f before the quotation marks) puts the value of a variable into the text through {}. This is how request texts for a model are prepared later.
model = "Mini"
versiya = 2
print(f"Men {model} v{versiya} bilan ishlayapman.")OutputMen Mini v2 bilan ishlayapman.A list holds several values in square brackets; items are numbered from 0. A for loop repeats the same action for every item in the list. The lines inside a loop are indented by 4 spaces: in Python this matters.
mavzular = ["token", "prompt", "agent"]
print(mavzular[0])
for mavzu in mavzular:
print(f"Mavzu: {mavzu}")Outputtoken
Mavzu: token
Mavzu: prompt
Mavzu: agentRemember
print()shows a result on the screen.- f-string:
f"... {variable} ...". - List:
[...]; loop:for x in items:with 4 spaces inside.
Exercise
If ism = "Ali", what does print(f"Salom, {ism}") print?
Answer and explanation
- Salom, {ism}in an f-string the name in curly braces is replaced by its value.
- Salom, Ali (correct answer)the f-string puts the variable’s value in place of
{ism}. - ismthat is the variable’s name, not its value.
Code exercises
- Print the word
salom(Uzbek for “hello”) on the screen.
Hint: Write the text in quotation marks insideprint(...). - Put “Ali” into the variable
ismand, using an f-string, printSalom, Ali!.
Hint: Writefbefore the quotation marks and put the variable in curly braces:{ism}. - Print every word in the list
sozlarin capital letters, each on its own line.
Hint: Afterfor soz in sozlar:write the print command indented by 4 spaces. A string has the.upper()method for capital letters.
Do the exercise in the app.
Practical task
Put 3 words you like into a list and, using a loop, print each one inside a sentence with an f-string. Try the code in the exercise editor.
- I made a list
- I wrote a loop
- I looked at the result and understood it
Glossary
Interactive mode: search, progress and Python exercises.
