Skip to content
Educora
Beginner16 min5 / 14

Conditions, loops, procedures and functions

Make decisions with `Если … ИначеЕсли … КонецЕсли`, repeat work with three kinds of loops, split code into procedures and functions with parameters, and understand `Знач` and `Экспорт`.

Check yourself
In this lesson you will learn
  • Write multi-branch conditions and the ?() expression
  • Pick the right loop for a task and use Прервать and Продолжить
  • Write procedures and functions and explain how parameters are passed

A shop gives a 5% discount on purchases over 200 manat and 10% over 500 manat. An invoice has a hundred rows, and each row's amount must be calculated. For such tasks a program has to make decisions (conditions), repeat work (loops) and split code into parts (procedures and functions).

Conditions

1C
СуммаПокупки = 250;

Если СуммаПокупки >= 500 Тогда
    Скидка = 10;
ИначеЕсли СуммаПокупки >= 200 Тогда
    Скидка = 5;
Иначе
    Скидка = 0;
КонецЕсли;

Сообщить("Скидка: " + Скидка + "%");

Остаток = 0;
Статус = ?(Остаток > 0, "В наличии", "Нет в наличии");
Сообщить(Статус);
Expected output
Скидка: 5%
Нет в наличии
English syntax equivalents: Если = If, Тогда = Then, ИначеЕсли = ElsIf, Иначе = Else, КонецЕсли = EndIf.

Branches are checked from top to bottom and the first true condition runs — that is why 250 got 5%. ?(Condition, A, B) is the short form: it returns A if the condition is true, otherwise B. Complex conditions are built with И, ИЛИ, НЕ and parentheses: Если (Сумма > 100 И НЕ Оплачено) ИЛИ Срочно Тогда.

Three kinds of loops

LoopEnglish syntaxWhen to use
Для Н = 1 По 10 Цикл … КонецЦиклаFor … To … Do … EndDothe number of repetitions is known
Для Каждого Эл Из Коллекция ЦиклFor Each … In … Dogoing through every element of a collection
Пока Условие Цикл … КонецЦиклаWhile … Do … EndDorepeating while a condition is true
1C
Для Н = 1 По 10 Цикл
    Если Н % 2 = 1 Тогда
        Продолжить;   // нечётные пропускаем
    КонецЕсли;
    Если Н > 8 Тогда
        Прервать;     // выходим из цикла
    КонецЕсли;
    Сообщить(Н);
КонецЦикла;

Города = СтрРазделить("Bakı,Gəncə,Şəki", ",");
Для Каждого Город Из Города Цикл
    Сообщить(Город);
КонецЦикла;
Expected output
2
4
6
8
Bakı
Gəncə
Şəki
Продолжить (Continue) jumps to the next iteration, Прервать (Break) ends the loop at once.
When will a deposit double?

A deposit of 1000 manat grows by 10% every year. After how many years will it first reach or exceed 2000 manat? Solve it with a Пока (While) loop.

Show solution
Вклад = 1000; Лет = 0;
Пока Вклад < 2000 Цикл Вклад = Вклад * 1.1; Лет = Лет + 1; КонецЦикла;
After 7 years: 1000 · 1.1⁷ ≈ 1948.7 < 2000.
After 8 years: 1000 · 1.1⁸ ≈ 2143.6 ≥ 2000.
Answer: 8 years. The number of repetitions is not known in advance, so Пока is the right loop here.

Procedures and functions

A procedure (Процедура … КонецПроцедуры) performs an action, and a function (Функция … КонецФункции) returns a value with Возврат (Return). Parameters can have default values. The word Экспорт (Export) makes a procedure callable from other modules, for example РаботаСЦенами.СуммаСоСкидкой(200, 5).

1C
Функция СуммаСоСкидкой(Сумма, ПроцентСкидки = 0) Экспорт
    Возврат Сумма - Сумма * ПроцентСкидки / 100;
КонецФункции

Процедура Удвоить(Значение)
    Значение = Значение * 2;
КонецПроцедуры

Процедура УдвоитьКопию(Знач Значение)
    Значение = Значение * 2;
КонецПроцедуры

Процедура Тест()
    Сообщить(СуммаСоСкидкой(200, 5));
    Сообщить(СуммаСоСкидкой(80));
    А = 5;
    Удвоить(А);
    Б = 5;
    УдвоитьКопию(Б);
    Сообщить(А);
    Сообщить(Б);
КонецПроцедуры
Expected output
190
80
10
5
By default parameters are passed by reference (А changed); Знач (Val) passes a copy (Б did not change).

Procedures and functions always live in some module. The module type decides when and where the code is called, so before writing a new procedure choose the right “home” for it:

  • Common module (Общие модули) — code shared by the whole configuration; called as ИмяМодуля.Процедура().
  • Object module — events of a particular catalog item or document (writing, posting).
  • Manager module — functions for the whole type: Документы.РасходТовара.ПечатнаяФорма().
  • Form module — a form's events and commands; we study it in detail in the next module.
  • Application and session modules — the program start and session parameters.

Key points

  • Если … ИначеЕсли … Иначе … КонецЕсли: the first true branch runs; ?(C, A, B) is the short form.
  • Loops: Для … По, Для Каждого … Из, Пока; all end with КонецЦикла.
  • Прервать exits the loop, Продолжить moves to the next iteration.
  • A function returns a value with Возврат; a procedure does not.
  • Parameters are passed by reference; Знач passes a copy, Экспорт opens the procedure to other modules.

Check yourself

10 questions. Every correct answer earns XP.

1 / 10
What does ?(3 > 5, "A", "B") return?