- 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
СуммаПокупки = 250;
Если СуммаПокупки >= 500 Тогда
Скидка = 10;
ИначеЕсли СуммаПокупки >= 200 Тогда
Скидка = 5;
Иначе
Скидка = 0;
КонецЕсли;
Сообщить("Скидка: " + Скидка + "%");
Остаток = 0;
Статус = ?(Остаток > 0, "В наличии", "Нет в наличии");
Сообщить(Статус);Скидка: 5% Нет в наличии
Если = 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
| Loop | English syntax | When to use |
|---|---|---|
Для Н = 1 По 10 Цикл … КонецЦикла | For … To … Do … EndDo | the number of repetitions is known |
Для Каждого Эл Из Коллекция Цикл | For Each … In … Do | going through every element of a collection |
Пока Условие Цикл … КонецЦикла | While … Do … EndDo | repeating while a condition is true |
Для Н = 1 По 10 Цикл
Если Н % 2 = 1 Тогда
Продолжить; // нечётные пропускаем
КонецЕсли;
Если Н > 8 Тогда
Прервать; // выходим из цикла
КонецЕсли;
Сообщить(Н);
КонецЦикла;
Города = СтрРазделить("Bakı,Gəncə,Şəki", ",");
Для Каждого Город Из Города Цикл
Сообщить(Город);
КонецЦикла;2 4 6 8 Bakı Gəncə Şəki
Продолжить (Continue) jumps to the next iteration, Прервать (Break) ends the loop at once.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 solutionHide 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).
Функция СуммаСоСкидкой(Сумма, ПроцентСкидки = 0) Экспорт
Возврат Сумма - Сумма * ПроцентСкидки / 100;
КонецФункции
Процедура Удвоить(Значение)
Значение = Значение * 2;
КонецПроцедуры
Процедура УдвоитьКопию(Знач Значение)
Значение = Значение * 2;
КонецПроцедуры
Процедура Тест()
Сообщить(СуммаСоСкидкой(200, 5));
Сообщить(СуммаСоСкидкой(80));
А = 5;
Удвоить(А);
Б = 5;
УдвоитьКопию(Б);
Сообщить(А);
Сообщить(Б);
КонецПроцедуры190 80 10 5
А 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.
?(3 > 5, "A", "B") return?