Lesson 18

Objects

Objects

In this lesson: you will keep facts about one thing in one object, each under its own name.

The whole lesson on one page

Objects

In this lesson: you will keep facts about one thing in one object, each under its own name.

What is an object?

A list keeps values under numbers (indexes). An object keeps them under names:

1тағ хонанда = {
2 ном: "Зарина",
3 синф: 7,
4 аълочӣ: дуруст,
5};
6чоп(хонанда);
7чоп(хонанда.ном);
8чоп("Синф:", хонанда.синф);
  • An object is written in curly brackets { }: name: value, separated by commas.
  • Each name: value is a property (хосият). You read it with a dot: хонанда.ном.

Change and add a property

1тағ китоб = { ном: "Шоҳнома", саҳифаҳо: 500 };
2китоб.саҳифаҳо = 520;
3китоб.муаллиф = "Фирдавсӣ";
4чоп(китоб);

A list of objects

1тағ хонандагон = [
2 { ном: "Алӣ", хол: 78 },
3 { ном: "Зарина", хол: 95 },
4 { ном: "Фарҳод", хол: 88 },
5];
6тағ беҳтарин = хонандагон[0];
7барои (тағ х аз хонандагон) {
8 агар (х.хол > беҳтарин.хол) {
9 беҳтарин = х;
10 }
11}
12чоп("Беҳтарин:", беҳтарин.ном, беҳтарин.хол);

Common mistakes

  • Reading a property that does not exist: хонанда.суроға gives беқимат.
  • Do not give properties the names of the language's methods, such as дарозӣ or илова: they have a special meaning.

Task: The student

Read the name and the three marks of a student. Create the object { ном, холҳо } ("name", "marks") and print name: average, where the average is the average of the three marks.

Input: Four lines: the name, then three marks.

Output: name: average

Task: Shopping

Read the number of items н, then a name and a price for each item. Keep the items as objects in a list. Print the total cost and the name of the most expensive item.

Input: н, then two lines for each item: the name and the price.

Output: Ҳамагӣ: … ("Total") and Гаронтарин: … ("Most expensive")

Task: The best

Read the number of students н, then a name and a score for each of them. Print the name and the score of the best student (if there are several, the first of them).

Input: н, then two lines for each student: the name and the score.

Output: name score