Lesson 3

Variables

Variables

In this lesson: you will keep values in variables and change them.

The whole lesson on one page

Variables

In this lesson: you will keep values in variables and change them.

What is a variable?

A variable is a box with a name that holds a value. You create it with the word тағ:

1тағ ном = "Зарина";
2тағ синну = 13;
3чоп(ном);
4чоп(синну);
5чоп(ном, "-", синну, "сола");
  • тағ ном = "Зарина"; creates (declares) the variable ном ("name") and gives it the value "Зарина".
  • чоп(ном) prints the value of the variable, not the word "ном".

Changing a value

1тағ хол = 10;
2чоп(хол);
3хол = 15;
4чоп(хол);
5хол = хол + 5;
6чоп(хол);
  • хол = 15; gives a new value; you do not need тағ any more.
  • хол = хол + 5; takes the current value, adds 5, and saves the result in хол again.

Changing a value

What value is in х after this program?

1тағ х = 4;
2х = х * 2;
3х = х + 1;
  • 4
  • 8
  • 9
  • 5

Constants

A value that does not change is declared with the word собит:

1собит рӯзҳоиҲафта = 7;
2чоп("Дар як ҳафта", рӯзҳоиҲафта, "рӯз ҳаст");

If you give a собит a new value, the playground shows an error.

The name of a variable

  • A name is made of letters, digits and _, and it starts with a letter: ном, хол2, шумораи_хонандагон, рӯзҳоиҲафта.
  • Choose names that are easy to understand: синну ("age") is better than х.
  • Keywords (тағ, агар, чоп …) cannot be used as names.

Common mistakes

  • Using a variable before it is declared: чоп(х); тағ х = 1;
  • Declaring the same name twice with тағ.
  • Writing чоп("ном") instead of чоп(ном): quotes print the text itself.

Task: My card

Declare a variable ном with the value "Сино" and a variable синну with the value 12. Then use them to print two lines: Ном: Сино and Синну: 12.

Input: None.

Output: Ном: Сино and Синну: 12.

Task: Swap

The program starts with тағ а = 5; and тағ б = 8;. Swap the values of а and б - without writing the numbers 5 and 8 again - and print а = 8 and б = 5. Hint: you will need a third variable.

Input: None.

Output: а = 8 and б = 5.

Task: Next year

Start with тағ синну = 12;. Increase синну by one and print Соли оянда ман 13 сола мешавам.. Do not write the number 13 yourself: take it from синну.

Input: None.

Output: Соли оянда ман 13 сола мешавам.