-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathcontrolflow.po
More file actions
2348 lines (2122 loc) · 107 KB
/
Copy pathcontrolflow.po
File metadata and controls
2348 lines (2122 loc) · 107 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# SOME DESCRIPTIVE TITLE.
# Copyright (C) 2001 Python Software Foundation
# This file is distributed under the same license as the Python package.
# FIRST AUTHOR <EMAIL@ADDRESS>, YEAR.
#
# Translators:
# python-doc bot, 2025
# Dmitry Luschan, 2026
#
#, fuzzy
msgid ""
msgstr ""
"Project-Id-Version: Python 3.15\n"
"Report-Msgid-Bugs-To: \n"
"POT-Creation-Date: 2026-08-11 14:51+0000\n"
"PO-Revision-Date: 2025-09-16 00:02+0000\n"
"Last-Translator: Dmitry Luschan, 2026\n"
"Language-Team: Russian (https://app.transifex.com/python-doc/teams/5390/"
"ru/)\n"
"MIME-Version: 1.0\n"
"Content-Type: text/plain; charset=UTF-8\n"
"Content-Transfer-Encoding: 8bit\n"
"Language: ru\n"
"Plural-Forms: nplurals=4; plural=(n%10==1 && n%100!=11 ? 0 : n%10>=2 && "
"n%10<=4 && (n%100<12 || n%100>14) ? 1 : n%10==0 || (n%10>=5 && n%10<=9) || "
"(n%100>=11 && n%100<=14)? 2 : 3);\n"
msgid "More Control Flow Tools"
msgstr "Больше инструментов управления потоком выполнения программы"
msgid ""
"As well as the :keyword:`while` statement just introduced, Python uses a few "
"more that we will encounter in this chapter."
msgstr ""
"Помимо только что представленной инструкции :keyword:` while `, Python "
"использует ещё несколько, с которыми мы столкнёмся в этой главе."
msgid ":keyword:`!if` Statements"
msgstr "Инструкция :keyword:`!if`"
msgid ""
"Perhaps the most well-known statement type is the :keyword:`if` statement. "
"For example::"
msgstr "Пожалуй, самый известный тип инструкции — это :keyword:`if`. Например:"
msgid ""
">>> x = int(input(\"Please enter an integer: \"))\n"
"Please enter an integer: 42\n"
">>> if x < 0:\n"
"... x = 0\n"
"... print('Negative changed to zero')\n"
"... elif x == 0:\n"
"... print('Zero')\n"
"... elif x == 1:\n"
"... print('Single')\n"
"... else:\n"
"... print('More')\n"
"...\n"
"More"
msgstr ""
">>> x = int(input(\"Пожалуйста, введите целое число: \"))\n"
"Пожалуйста, введите целое число: 42\n"
">>> if x < 0:\n"
"... x = 0\n"
"... print('Отрицательное число заменено нулём')\n"
"... elif x == 0:\n"
"... print('Ноль')\n"
"... elif x == 1:\n"
"... print('Единица')\n"
"... else:\n"
"... print('Больше единицы')\n"
"...\n"
"Больше единицы"
msgid ""
"There can be zero or more :keyword:`elif` parts, and the :keyword:`else` "
"part is optional. The keyword ':keyword:`!elif`' is short for 'else if', "
"and is useful to avoid excessive indentation. An :keyword:`!if` ... :"
"keyword:`!elif` ... :keyword:`!elif` ... sequence is a substitute for the "
"``switch`` or ``case`` statements found in other languages."
msgstr ""
"В условной инструкции может быть несколько ветвей :keyword:`elif` или не "
"быть их. Ветка :keyword:`else` также необязательна. Ключевое слово ':keyword:"
"`!elif`' — сокращение для 'else if' ('иначе если'), оно позволяет избежать "
"большого количества отступов. Последовательность :keyword:`!if` ... :keyword:"
"`!elif` ... :keyword:`!elif` ... заменяет инструкции ``switch`` и ``case`` в "
"других языках."
msgid ""
"If you're comparing the same value to several constants, or checking for "
"specific types or attributes, you may also find the :keyword:`!match` "
"statement useful. For more details see :ref:`tut-match`."
msgstr ""
"Если вы сравниваете одно и то же значение с несколькими константами или "
"проверяете определенные типы или атрибуты, вам также может пригодиться "
"инструкция :keyword:`!match`. Для получения более подробной информации см. :"
"ref:`tut-match`."
msgid ":keyword:`!for` Statements"
msgstr "Инструкция :keyword:`!for`"
msgid ""
"The :keyword:`for` statement in Python differs a bit from what you may be "
"used to in C or Pascal. Rather than always iterating over an arithmetic "
"progression of numbers (like in Pascal), or giving the user the ability to "
"define both the iteration step and halting condition (as C), Python's :"
"keyword:`!for` statement iterates over the items of any sequence (a list or "
"a string), in the order that they appear in the sequence. For example (no "
"pun intended):"
msgstr ""
"В Python инструкция :keyword:`for`немного отличается от :keyword:`for` в C "
"или Pascal. Вместо того, чтобы обходить арифметическую прогрессию чисел (как "
"в Pascal) или давать программисту возможность задавать шаг итерации и "
"условие остановки (как в C), цикл :keyword:`!for` в Python обходит элементы "
"любой последовательности (списка или строки) в том порядке, в котором они в "
"ней встречаются. Например:"
msgid ""
">>> # Measure some strings:\n"
">>> words = ['cat', 'window', 'defenestrate']\n"
">>> for w in words:\n"
"... print(w, len(w))\n"
"...\n"
"cat 3\n"
"window 6\n"
"defenestrate 12"
msgstr ""
">>> # Измеряем несколько строк:\n"
">>> words = ['кот', 'окно', 'выбросить']\n"
">>> for w in words:\n"
"... print(w, len(w))\n"
"...\n"
"кот 3\n"
"окно 4\n"
"выбросить 9"
msgid ""
"Code that modifies a collection while iterating over that same collection "
"can be tricky to get right. Instead, it is usually more straight-forward to "
"loop over a copy of the collection or to create a new collection::"
msgstr ""
"Правильно написать цикл, изменяющий коллекцию во время её обхода, бывает "
"трудно. Обычно гораздо проще пройтись по копии коллекции или создать новую::"
msgid ""
"# Create a sample collection\n"
"users = {'Hans': 'active', 'Éléonore': 'inactive', '景太郎': 'active'}\n"
"\n"
"# Strategy: Iterate over a copy\n"
"for user, status in users.copy().items():\n"
" if status == 'inactive':\n"
" del users[user]\n"
"\n"
"# Strategy: Create a new collection\n"
"active_users = {}\n"
"for user, status in users.items():\n"
" if status == 'active':\n"
" active_users[user] = status"
msgstr ""
"# Создать пример коллекции\n"
"users = {'Hans': 'активен', 'Éléonore': 'неактивна', '景太郎': 'активен'}\n"
"\n"
"# Стратегия: итерироваться по копии\n"
"for user, status in users.copy().items():\n"
" if status == 'неактивна':\n"
" del users[user]\n"
"\n"
"# Стратегия: создать новую коллекцию\n"
"active_users = {}\n"
"for user, status in users.items():\n"
" if status == 'активен':\n"
" active_users[user] = status"
msgid "The :func:`range` Function"
msgstr "Функция :func:`range`"
msgid ""
"If you do need to iterate over a sequence of numbers, the built-in function :"
"func:`range` comes in handy. It generates arithmetic progressions::"
msgstr ""
"Если вам нужно перебрать последовательность чисел, то пригодится встроенная "
"функция :func:`range`. Она генерирует арифметические прогрессии::"
msgid ""
">>> for i in range(5):\n"
"... print(i)\n"
"...\n"
"0\n"
"1\n"
"2\n"
"3\n"
"4"
msgstr ""
">>> for i in range(5):\n"
"... print(i)\n"
"...\n"
"0\n"
"1\n"
"2\n"
"3\n"
"4"
msgid ""
"The given end point is never part of the generated sequence; ``range(10)`` "
"generates 10 values, the legal indices for items of a sequence of length "
"10. It is possible to let the range start at another number, or to specify "
"a different increment (even negative; sometimes this is called the 'step')::"
msgstr ""
"Предоставленная \"конечная точка\" никогда не входит в сгенерированную "
"последовательность; ``range(10)`` сгенерирует 10 значений, индексы элементов "
"последовательности длиной равной 10. Также возможно начать диапазон с "
"другого числа или указать другое приращение (даже отрицательное; иногда это "
"называется \"шагом\")::"
msgid ""
">>> list(range(5, 10))\n"
"[5, 6, 7, 8, 9]\n"
"\n"
">>> list(range(0, 10, 3))\n"
"[0, 3, 6, 9]\n"
"\n"
">>> list(range(-10, -100, -30))\n"
"[-10, -40, -70]"
msgstr ""
">>> list(range(5, 10))\n"
"[5, 6, 7, 8, 9]\n"
"\n"
">>> list(range(0, 10, 3))\n"
"[0, 3, 6, 9]\n"
"\n"
">>> list(range(-10, -100, -30))\n"
"[-10, -40, -70]"
msgid ""
"To iterate over the indices of a sequence, you can combine :func:`range` "
"and :func:`len` as follows::"
msgstr ""
"Чтобы перебрать индексы последовательности, можно соединить функции :func:"
"`range` и :func:`len` следующим образом::"
msgid ""
">>> a = ['Mary', 'had', 'a', 'little', 'lamb']\n"
">>> for i in range(len(a)):\n"
"... print(i, a[i])\n"
"...\n"
"0 Mary\n"
"1 had\n"
"2 a\n"
"3 little\n"
"4 lamb"
msgstr ""
">>> a = ['У', 'Мэри', 'была', 'маленькая', 'овечка']\n"
">>> for i in range(len(a)):\n"
"... print(i, a[i])\n"
"...\n"
"0 У\n"
"1 Мэри\n"
"2 была\n"
"3 маленькая\n"
"4 овечка"
msgid ""
"In most such cases, however, it is convenient to use the :func:`enumerate` "
"function, see :ref:`tut-loopidioms`."
msgstr ""
"В большинстве подобных случаев функция :func:`enumerate` более удобна, см. :"
"ref:`tut-loopidioms`."
msgid "A strange thing happens if you just print a range::"
msgstr "Если вы просто печатаете функцию range, происходит странная вещь::"
msgid ""
">>> range(10)\n"
"range(0, 10)"
msgstr ""
">>> range(10)\n"
"range(0, 10)"
msgid ""
"In many ways the object returned by :func:`range` behaves as if it is a "
"list, but in fact it isn't. It is an object which returns the successive "
"items of the desired sequence when you iterate over it, but it doesn't "
"really make the list, thus saving space."
msgstr ""
"В множестве случаев объект, который возвращается функцией :func:`range`, "
"ведёт себя как список, но в действительности он списком не является. Это "
"объект, который возвращает следующий элемент последовательности, когда он "
"действительно нужен в процессе итерации, таким образом сохраняется память, "
"потому что список на самом деле не составляется."
msgid ""
"We say such an object is :term:`iterable`, that is, suitable as a target for "
"functions and constructs that expect something from which they can obtain "
"successive items until the supply is exhausted. We have seen that the :"
"keyword:`for` statement is such a construct, while an example of a function "
"that takes an iterable is :func:`sum`::"
msgstr ""
"Мы говорим, что такой объект является :term:`iterable`, то есть подходит в "
"качестве цели для функций и конструкций, которые ожидают чего-то, из чего "
"они могут получать последовательные элементы, пока они не закончатся. Мы "
"видели, что такой конструкцией является инструкция :keyword:`for`, а "
"примером функции, принимающей итерируемый объект, является :func:`sum`::"
msgid ""
">>> sum(range(4)) # 0 + 1 + 2 + 3\n"
"6"
msgstr ""
">>> sum(range(4)) # 0 + 1 + 2 + 3\n"
"6"
msgid ""
"Later we will see more functions that return iterables and take iterables as "
"arguments. In chapter :ref:`tut-structures`, we will discuss :func:`list` "
"in more detail."
msgstr ""
"Позже мы увидим больше функций, которые возвращают итерируемые объекты и "
"принимают их в качестве аргументов. В главе :ref:`tut-structures` мы "
"подробнее обсудим :func:`list`."
msgid ":keyword:`!break` and :keyword:`!continue` Statements"
msgstr "Инструкции :keyword:`!break` и :keyword:`!continue`"
msgid ""
"The :keyword:`break` statement breaks out of the innermost enclosing :"
"keyword:`for` or :keyword:`while` loop::"
msgstr ""
"Инструкция :keyword:`break` прерывает выполнение самого внутреннего цикла :"
"keyword:`for` или :keyword:`while`::"
msgid ""
">>> for n in range(2, 10):\n"
"... for x in range(2, n):\n"
"... if n % x == 0:\n"
"... print(f\"{n} equals {x} * {n//x}\")\n"
"... break\n"
"...\n"
"4 equals 2 * 2\n"
"6 equals 2 * 3\n"
"8 equals 2 * 4\n"
"9 equals 3 * 3"
msgstr ""
">>> for n in range(2, 10):\n"
"... for x in range(2, n):\n"
"... if n % x == 0:\n"
"... print(f\"{n} equals {x} * {n//x}\")\n"
"... break\n"
"...\n"
"4 equals 2 * 2\n"
"6 equals 2 * 3\n"
"8 equals 2 * 4\n"
"9 equals 3 * 3"
msgid ""
"The :keyword:`continue` statement continues with the next iteration of the "
"loop::"
msgstr "Инструкция :keyword:`continue` переходит к следующей итерации цикла::"
msgid ""
">>> for num in range(2, 10):\n"
"... if num % 2 == 0:\n"
"... print(f\"Found an even number {num}\")\n"
"... continue\n"
"... print(f\"Found an odd number {num}\")\n"
"...\n"
"Found an even number 2\n"
"Found an odd number 3\n"
"Found an even number 4\n"
"Found an odd number 5\n"
"Found an even number 6\n"
"Found an odd number 7\n"
"Found an even number 8\n"
"Found an odd number 9"
msgstr ""
">>> for num in range(2, 10):\n"
"... if num % 2 == 0:\n"
"... print(f\"Найдено чётное число {num}\")\n"
"... continue\n"
"... print(f\"Найдено нечётное число {num}\")\n"
"...\n"
"Найдено чётное число 2\n"
"Найдено нечётное число 3\n"
"Найдено чётное число 4\n"
"Найдено нечётное число 5\n"
"Найдено чётное число 6\n"
"Найдено нечётное число 7\n"
"Найдено чётное число 8\n"
"Найдено нечётное число 9"
msgid ":keyword:`!else` Clauses on Loops"
msgstr ":keyword:`!else` ветви в циклах"
msgid ""
"In a :keyword:`!for` or :keyword:`!while` loop the :keyword:`!break` "
"statement may be paired with an :keyword:`!else` clause. If the loop "
"finishes without executing the :keyword:`!break`, the :keyword:`!else` "
"clause executes."
msgstr ""
"В цикле :keyword:`!for` или :keyword:`!while` инструкция :keyword:`!break` "
"может сочетаться с ветвью :keyword:`!else`. Если цикл завершается без "
"выполнения :keyword:`!break`, выполняется ветвь :keyword:`!else`."
msgid ""
"In a :keyword:`for` loop, the :keyword:`!else` clause is executed after the "
"loop finishes its final iteration, that is, if no break occurred."
msgstr ""
"В цикле :keyword:`for` ветвь :keyword:`!else` выполняется после последней "
"итерации, то есть, если не произошло прерывания."
msgid ""
"In a :keyword:`while` loop, it's executed after the loop's condition becomes "
"false."
msgstr ""
"В цикле :keyword:`while` она выполняется, когда условие цикла становится "
"ложным."
msgid ""
"In either kind of loop, the :keyword:`!else` clause is **not** executed if "
"the loop was terminated by a :keyword:`break`. Of course, other ways of "
"ending the loop early, such as a :keyword:`return` or a raised exception, "
"will also skip execution of the :keyword:`else` clause."
msgstr ""
"В любом типе цикла ветвь :keyword:`!else` **не** выполняется, если цикл был "
"прерван с помощью :keyword:`break`. Конечно, другие способы досрочного "
"завершения цикла, такие как :keyword:`return` или возбуждение исключения, "
"также пропустят выполнение ветви :keyword:`else`."
msgid ""
"This is exemplified in the following :keyword:`!for` loop, which searches "
"for prime numbers::"
msgstr ""
"Это показано в следующем циклом :keyword:`!for`, который ищет простые числа::"
msgid ""
">>> for n in range(2, 10):\n"
"... for x in range(2, n):\n"
"... if n % x == 0:\n"
"... print(n, 'equals', x, '*', n//x)\n"
"... break\n"
"... else:\n"
"... # loop fell through without finding a factor\n"
"... print(n, 'is a prime number')\n"
"...\n"
"2 is a prime number\n"
"3 is a prime number\n"
"4 equals 2 * 2\n"
"5 is a prime number\n"
"6 equals 2 * 3\n"
"7 is a prime number\n"
"8 equals 2 * 4\n"
"9 equals 3 * 3"
msgstr ""
">>> for n in range(2, 10):\n"
"... for x in range(2, n):\n"
"... if n % x == 0:\n"
"... print(n, 'равно', x, '*', n//x)\n"
"... break\n"
"... else:\n"
"... # цикл завершился, не найдя делителя\n"
"... print(n, ' — простое число')\n"
"...\n"
"2 — простое число\n"
"3 — простое число\n"
"4 равно 2 * 2\n"
"5 — простое число\n"
"6 равно 2 * 3\n"
"7 — простое число\n"
"8 равно 2 * 4\n"
"9 равно 3 * 3"
msgid ""
"(Yes, this is the correct code. Look closely: the ``else`` clause belongs "
"to the ``for`` loop, **not** the ``if`` statement.)"
msgstr ""
"(Да, это правильный код. Посмотрите внимательно: ветвь ``else`` относится к "
"циклу ``for``, а не к инструкции ``if``.)"
msgid ""
"One way to think of the else clause is to imagine it paired with the ``if`` "
"inside the loop. As the loop executes, it will run a sequence like if/if/if/"
"else. The ``if`` is inside the loop, encountered a number of times. If the "
"condition is ever true, a ``break`` will happen. If the condition is never "
"true, the ``else`` clause outside the loop will execute."
msgstr ""
"Один из способов понять ветвь else в цикле — представить её в паре с "
"инструкцией ``if`` внутри цикла. По мере выполнения цикла будет выполняться "
"последовательность действий типа if/if/if/else. ``if`` находится внутри "
"цикла и встречается несколько раз. Если условие когда-либо будет истинным, "
"произойдет прерывание цикла с помощью ``break``. Если условие никогда не "
"будет истинным, то будет выполнена ветвь ``else`` вне цикла."
msgid ""
"When used with a loop, the ``else`` clause has more in common with the "
"``else`` clause of a :keyword:`try` statement than it does with that of "
"``if`` statements: a ``try`` statement's ``else`` clause runs when no "
"exception occurs, and a loop's ``else`` clause runs when no ``break`` "
"occurs. For more on the ``try`` statement and exceptions, see :ref:`tut-"
"handling`."
msgstr ""
"При использовании с циклом ветвь ``else`` имеет больше общего с ветвью "
"``else`` инструкции :keyword:`try`, чем с инструкцией ``if``. Ветвь ``else`` "
"инструкции ``try`` выполняется, когда не возникло исключение, а ветвь "
"``else`` цикла выполняется, когда не произошло ``break``. Дополнительную "
"информацию об инструкции ``try`` и исключениях см. в разделе :ref:`tut-"
"handling`."
msgid ":keyword:`!pass` Statements"
msgstr "Инструкция :keyword:`!pass`"
msgid ""
"The :keyword:`pass` statement does nothing. It can be used when a statement "
"is required syntactically but the program requires no action. For example::"
msgstr ""
"Инструкция :keyword:`pass` ничего не делает. Её можно использовть, когда "
"инструкция требуется в соответствии с синтаксисом, но программа при этом не "
"должна ничего делать. Например::"
msgid ""
">>> while True:\n"
"... pass # Busy-wait for keyboard interrupt (Ctrl+C)\n"
"..."
msgstr ""
">>> while True:\n"
"... pass # Ожидание прерывания с клавиатуры (Ctrl+C)\n"
"..."
msgid "This is commonly used for creating minimal classes::"
msgstr "Обычно :keyword:`pass` используется при создании минимальных классов::"
msgid ""
">>> class MyEmptyClass:\n"
"... pass\n"
"..."
msgstr ""
">>> class MyEmptyClass:\n"
"... pass\n"
"..."
msgid ""
"Another place :keyword:`pass` can be used is as a place-holder for a "
"function or conditional body when you are working on new code, allowing you "
"to keep thinking at a more abstract level. The :keyword:`!pass` is silently "
"ignored::"
msgstr ""
"Другое применение инструкции :keyword:`pass` — заглушка для тела функции или "
"ветки условной инструкции, когда вы работаете над новым кодом. Это позволяет "
"думаю о коде на более высоком, абстрактном уровне. Инструкция :keyword:`!"
"pass` просто игнорируется::"
msgid ""
">>> def initlog(*args):\n"
"... pass # Remember to implement this!\n"
"..."
msgstr ""
">>> def initlog(*args):\n"
"... pass # Не забыть реализовать это!\n"
"..."
msgid ""
"For this last case, many people use the ellipsis literal :code:`...` instead "
"of :code:`pass`. This use has no special meaning to Python, and is not part "
"of the language definition (you could use any constant expression here), "
"but :code:`...` is used conventionally as a placeholder body as well. See :"
"ref:`bltin-ellipsis-object`."
msgstr ""
"В таких случаях многие используют литерал многоточия :code:`...` вместо :"
"code:`pass`. Это использование не имеет особого значения для Python, и не "
"является частью определения языка (здесь можно использовать любое "
"константное выражение), но :code:`...` принято использовать как заглушку "
"вместо реального блока кода. См. :ref:`bltin-ellipsis-object`."
msgid ":keyword:`!match` Statements"
msgstr "Инструкция :keyword:`!match`"
msgid ""
"A :keyword:`match` statement takes an expression and compares its value to "
"successive patterns given as one or more case blocks. This is superficially "
"similar to a switch statement in C, Java or JavaScript (and many other "
"languages), but it's more similar to pattern matching in languages like Rust "
"or Haskell. Only the first pattern that matches gets executed and it can "
"also extract components (sequence elements or object attributes) from the "
"value into variables. If no case matches, none of the branches is executed."
msgstr ""
"Инструкция :keyword:`match` принимает выражение и последовательно сравнивает "
"его значение с шаблонами, заданными в одном или нескольких блоках case. На "
"первый взгляд это похоже на инструкцию switch в C, Java или JavaScript (и "
"многих других языках), но гораздо ближе к сопоставлению с образцом в таких "
"языках, как Rust или Haskell. Выполняется только первая ветвь, чей шаблон "
"подошёл. Шаблон также может извлекать части значения (элементы "
"последовательности или атрибуты объекта) и связывать их с переменными. Если "
"ни один шаблон не подошёл, не выполняется ни одна из ветвей."
msgid ""
"The simplest form compares a subject value against one or more literals::"
msgstr ""
"Самая простая форма сравнивает сопоставляемое значение с одним или "
"несколькими литералами:"
msgid ""
"def http_error(status):\n"
" match status:\n"
" case 400:\n"
" return \"Bad request\"\n"
" case 404:\n"
" return \"Not found\"\n"
" case 418:\n"
" return \"I'm a teapot\"\n"
" case _:\n"
" return \"Something's wrong with the internet\""
msgstr ""
"def http_error(status):\n"
" match status:\n"
" case 400:\n"
" return \"Некорректный запрос\"\n"
" case 404:\n"
" return \"Не найдено\"\n"
" case 418:\n"
" return \"Я — чайник\"\n"
" case _:\n"
" return \"Что-то не так с интернетом\""
msgid ""
"Note the last block: the \"variable name\" ``_`` acts as a *wildcard* and "
"never fails to match."
msgstr ""
"Обрати внимание на последний блок: «имя переменной» ``_`` действует как "
"*подстановочный символ* и всегда проходит сопоставление."
msgid ""
"You can combine several literals in a single pattern using ``|`` (\"or\")::"
msgstr ""
"Можно объединять несколько литералов в одном шаблоне, используя ``|`` "
"(\"или\")::"
msgid ""
"case 401 | 403 | 404:\n"
" return \"Not allowed\""
msgstr ""
"case 401 | 403 | 404:\n"
" return \"Доступ запрещён\""
msgid ""
"Patterns can look like unpacking assignments, and can be used to bind "
"variables::"
msgstr ""
"Шаблоны могут выглядеть как присваивания с распаковкой и использоваться для "
"привязки переменных:"
msgid ""
"# point is an (x, y) tuple\n"
"match point:\n"
" case (0, 0):\n"
" print(\"Origin\")\n"
" case (0, y):\n"
" print(f\"Y={y}\")\n"
" case (x, 0):\n"
" print(f\"X={x}\")\n"
" case (x, y):\n"
" print(f\"X={x}, Y={y}\")\n"
" case _:\n"
" raise ValueError(\"Not a point\")"
msgstr ""
"# point — это кортеж (x, y)\n"
"match point:\n"
" case (0, 0):\n"
" print(\"Начало координат\")\n"
" case (0, y):\n"
" print(f\"Y={y}\")\n"
" case (x, 0):\n"
" print(f\"X={x}\")\n"
" case (x, y):\n"
" print(f\"X={x}, Y={y}\")\n"
" case _:\n"
" raise ValueError(\"Это не точка\")"
msgid ""
"Study that one carefully! The first pattern has two literals, and can be "
"thought of as an extension of the literal pattern shown above. But the next "
"two patterns combine a literal and a variable, and the variable *binds* a "
"value from the subject (``point``). The fourth pattern captures two values, "
"which makes it conceptually similar to the unpacking assignment ``(x, y) = "
"point``."
msgstr ""
"Изучите это внимательно! Первый шаблон имеет два литерала, и его можно "
"рассматривать как расширение шаблона литералов, показанного выше. Но "
"следующие два шаблона объединяют литерал и переменную, а переменная "
"*привязывается* к значению из сопоставляемого объекта (``point``). Четвёртый "
"шаблон захватывает два значения, что делает его концептуально похожим на "
"присваивание с распаковкой ``(x, y) = point``."
msgid ""
"If you are using classes to structure your data you can use the class name "
"followed by an argument list resembling a constructor, but with the ability "
"to capture attributes into variables::"
msgstr ""
"Если вы используете классы для структурирования своих данных, вы можете "
"использовать имя класса, за которым следует список аргументов, напоминающий "
"конструктор, но с возможностью захвата атрибутов в переменные:"
msgid ""
"class Point:\n"
" def __init__(self, x, y):\n"
" self.x = x\n"
" self.y = y\n"
"\n"
"def where_is(point):\n"
" match point:\n"
" case Point(x=0, y=0):\n"
" print(\"Origin\")\n"
" case Point(x=0, y=y):\n"
" print(f\"Y={y}\")\n"
" case Point(x=x, y=0):\n"
" print(f\"X={x}\")\n"
" case Point():\n"
" print(\"Somewhere else\")\n"
" case _:\n"
" print(\"Not a point\")"
msgstr ""
"class Point:\n"
" def __init__(self, x, y):\n"
" self.x = x\n"
" self.y = y\n"
"\n"
"def where_is(point):\n"
" match point:\n"
" case Point(x=0, y=0):\n"
" print(\"Начало координат\")\n"
" case Point(x=0, y=y):\n"
" print(f\"Y={y}\")\n"
" case Point(x=x, y=0):\n"
" print(f\"X={x}\")\n"
" case Point():\n"
" print(\"Где-то в другом месте\")\n"
" case _:\n"
" print(\"Это не точка\")"
msgid ""
"You can use positional parameters with some builtin classes that provide an "
"ordering for their attributes (e.g. dataclasses). You can also define a "
"specific position for attributes in patterns by setting the "
"``__match_args__`` special attribute in your classes. If it's set to (\"x\", "
"\"y\"), the following patterns are all equivalent (and all bind the ``y`` "
"attribute to the ``var`` variable)::"
msgstr ""
"Вы можете использовать позиционные параметры с некоторыми встроенными "
"классами, которые обеспечивают порядок их атрибутов (например, классов "
"данных). Вы также можете явно задать определенное положение атрибутов в "
"шаблонах, установив в своих классах специальный атрибут ``__match_args__``. "
"Если для него установлено значение («x», «y»), все следующие шаблоны "
"эквивалентны (и все они привязывают атрибут ``y`` к переменной ``var``):"
msgid ""
"Point(1, var)\n"
"Point(1, y=var)\n"
"Point(x=1, y=var)\n"
"Point(y=var, x=1)"
msgstr ""
"Point(1, var)\n"
"Point(1, y=var)\n"
"Point(x=1, y=var)\n"
"Point(y=var, x=1)"
msgid ""
"A recommended way to read patterns is to look at them as an extended form of "
"what you would put on the left of an assignment, to understand which "
"variables would be set to what. Only the standalone names (like ``var`` "
"above) are assigned to by a match statement. Dotted names (like ``foo."
"bar``), attribute names (the ``x=`` and ``y=`` above) or class names "
"(recognized by the \"(...)\" next to them like ``Point`` above) are never "
"assigned to."
msgstr ""
"Рекомендуется читать шаблоны так, будто это расширенная форма того, что "
"можно записать слева в присваивании, — чтобы понять, каким переменным какое "
"значение будет присвоено. Только отдельные имена (как ``var`` выше) "
"связываются инструкцией match. Имена в точечной нотации (например, ``foo."
"bar``), имена атрибутов (``x=`` и ``y=`` выше) или имена классов "
"(распознаваемые по скобкам \"(...)\" после них, например ``Point`` выше) "
"никогда не связываются."
msgid ""
"Patterns can be arbitrarily nested. For example, if we have a short list of "
"Points, with ``__match_args__`` added, we could match it like this::"
msgstr ""
"Шаблоны могут быть произвольно вложены. Например, если у нас есть короткий "
"список точек с добавленным ``__match_args__``, мы могли бы сопоставить его "
"следующим образом:"
msgid ""
"class Point:\n"
" __match_args__ = ('x', 'y')\n"
" def __init__(self, x, y):\n"
" self.x = x\n"
" self.y = y\n"
"\n"
"match points:\n"
" case []:\n"
" print(\"No points\")\n"
" case [Point(0, 0)]:\n"
" print(\"The origin\")\n"
" case [Point(x, y)]:\n"
" print(f\"Single point {x}, {y}\")\n"
" case [Point(0, y1), Point(0, y2)]:\n"
" print(f\"Two on the Y axis at {y1}, {y2}\")\n"
" case _:\n"
" print(\"Something else\")"
msgstr ""
"class Point:\n"
" __match_args__ = ('x', 'y')\n"
" def __init__(self, x, y):\n"
" self.x = x\n"
" self.y = y\n"
"\n"
"match points:\n"
" case []:\n"
" print(\"Нет точек\")\n"
" case [Point(0, 0)]:\n"
" print(\"Начало координат\")\n"
" case [Point(x, y)]:\n"
" print(f\"Одна точка {x}, {y}\")\n"
" case [Point(0, y1), Point(0, y2)]:\n"
" print(f\"Две точки на оси Y: {y1}, {y2}\")\n"
" case _:\n"
" print(\"Что-то другое\")"
msgid ""
"We can add an ``if`` clause to a pattern, known as a \"guard\". If the "
"guard is false, ``match`` goes on to try the next case block. Note that "
"value capture happens before the guard is evaluated::"
msgstr ""
"Мы можем добавить в шаблон выражение if, известное как «охранное условие». "
"Если это условие ложно, ``match`` переходит к следующему блоку case. "
"Обратите внимание, что захват значения происходит до проверки охранного "
"условия::"
msgid ""
"match point:\n"
" case Point(x, y) if x == y:\n"
" print(f\"Y=X at {x}\")\n"
" case Point(x, y):\n"
" print(f\"Not on the diagonal\")"
msgstr ""
"match point:\n"
" case Point(x, y) if x == y:\n"
" print(f\"Точка на диагонали: Y = X = {x}\")\n"
" case Point(x, y):\n"
" print(f\"Не на диагонали\")"
msgid "Several other key features of this statement:"
msgstr "Несколько других ключевых особенностей этой инструкции:"
msgid ""
"Like unpacking assignments, tuple and list patterns have exactly the same "
"meaning and actually match arbitrary sequences. An important exception is "
"that they don't match iterators or strings."
msgstr ""
"Как и при распаковке, шаблоны кортежей и списков имеют одинаковую семантику "
"и сопоставляются с любыми последовательностями. Однако строки и итераторы "
"под такие шаблоны не подходят."
msgid ""
"Sequence patterns support extended unpacking: ``[x, y, *rest]`` and ``(x, y, "
"*rest)`` work similar to unpacking assignments. The name after ``*`` may "
"also be ``_``, so ``(x, y, *_)`` matches a sequence of at least two items "
"without binding the remaining items."
msgstr ""
"Шаблоны последовательностей поддерживают расширенную распаковку: ``[x, y, "
"*rest]`` и ``(x, y, *rest)`` работают аналогично присваиванию с распаковкой. "
"Имя после ``*`` также может быть ``_``, поэтому ``(x, y, *_)`` соответствует "
"последовательности, состоящей как минимум из двух элементов, без привязки "
"остальных элементов."
msgid ""
"Mapping patterns: ``{\"bandwidth\": b, \"latency\": l}`` captures the "
"``\"bandwidth\"`` and ``\"latency\"`` values from a dictionary. Unlike "
"sequence patterns, extra keys are ignored. An unpacking like ``**rest`` is "
"also supported. (But ``**_`` would be redundant, so it is not allowed.)"
msgstr ""
"Шаблоны сопоставления: ``{\"bandwidth\": b, \"latency\": l}`` захватывает "
"значения ``\"bandwidth\"`` и ``\"latency\"`` из словаря. В отличие от "
"шаблонов последовательности, дополнительные ключи игнорируются. Также "
"поддерживается распаковка типа ``**rest``. (Но ``**_`` было бы лишним, "
"поэтому запрещено.)"
msgid "Subpatterns may be captured using the ``as`` keyword::"
msgstr "Подшаблоны можно захватывать с помощью ключевого слова ``as``:"
msgid "case (Point(x1, y1), Point(x2, y2) as p2): ..."
msgstr "case (Point(x1, y1), Point(x2, y2) as p2): ..."
msgid ""
"will capture the second element of the input as ``p2`` (as long as the input "
"is a sequence of two points)"
msgstr ""
"захватит второй элемент последовательности как ``p2`` (пока входные данные "
"представляют собой последовательность из двух точек)"
msgid ""
"Most literals are compared by equality, however the singletons ``True``, "
"``False`` and ``None`` are compared by identity."
msgstr ""
"Большинство литералов сравниваются с помощью равенства, однако одиночные "
"элементы ``True``, ``False`` и ``None`` сравниваются на идентичность."
msgid ""
"Patterns may use named constants. These must be dotted names to prevent "
"them from being interpreted as capture variables::"
msgstr ""
"Шаблоны могут использовать именованные константы. Такие имена должны иметь "
"точечную нотацию, чтобы их нельзя было интерпретировать как переменные "
"захвата::"
msgid ""
"from enum import Enum\n"
"class Color(Enum):\n"
" RED = 'red'\n"
" GREEN = 'green'\n"
" BLUE = 'blue'\n"
"\n"
"color = Color(input(\"Enter your choice of 'red', 'blue' or 'green': \"))\n"
"\n"
"match color:\n"
" case Color.RED:\n"
" print(\"I see red!\")\n"
" case Color.GREEN:\n"
" print(\"Grass is green\")\n"
" case Color.BLUE:\n"
" print(\"I'm feeling the blues :(\")"
msgstr ""
"from enum import Enum\n"
"class Color(Enum):\n"
" RED = 'red'\n"
" GREEN = 'green'\n"
" BLUE = 'blue'\n"
"\n"
"color = Color(input(\"Введите ваш выбор of 'red', 'blue' или 'green': \"))\n"
"\n"
"match color:\n"
" case Color.RED:\n"
" print(\"Я вижу красный!\")\n"
" case Color.GREEN:\n"
" print(\"Трава зелёная\")\n"
" case Color.BLUE:\n"
" print(\"Похоже, накрыла голубая хандра :(\")"
msgid ""
"For a more detailed explanation and additional examples, you can look into :"
"pep:`636` which is written in a tutorial format."
msgstr ""
"Более подробное объяснение и дополнительные примеры можно найти в :pep:"
"`636`, написанном в формате учебного пособия."
msgid "Defining Functions"
msgstr "Определение функций"
msgid ""
"We can create a function that writes the Fibonacci series to an arbitrary "
"boundary::"
msgstr ""
"Мы можем создать функцию, которая будет выводить ряд Фибоначчи до "
"произвольной границы:"
msgid ""
">>> def fib(n): # write Fibonacci series less than n\n"
"... \"\"\"Print a Fibonacci series less than n.\"\"\"\n"
"... a, b = 0, 1\n"
"... while a < n:\n"
"... print(a, end=' ')\n"
"... a, b = b, a+b\n"
"... print()\n"
"...\n"
">>> # Now call the function we just defined:\n"
">>> fib(2000)\n"
"0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597"
msgstr ""
">>> def fib(n): # вывести ряд Фибоначчи меньше n\n"
"... \"\"\"Вывести ряд Фибоначчи для чисел, меньших n.\"\"\"\n"
"... a, b = 0, 1\n"
"... while a < n:\n"
"... print(a, end=' ')\n"
"... a, b = b, a+b\n"
"... print()\n"
"...\n"
">>> # Теперь вызовем только что определённую функцию:\n"
">>> fib(2000)\n"
"0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597"
msgid ""
"The keyword :keyword:`def` introduces a function *definition*. It must be "
"followed by the function name and the parenthesized list of formal "
"parameters. The statements that form the body of the function start at the "
"next line, and must be indented."
msgstr ""
"Ключевое слово :keyword:`def` вводит *определение* функции. За ним должны "
"следовать имя функции и заключённый в скобки список формальных параметров. "
"Инструкции, составляющие тело функции, начинаются со следующей строки и "
"должны быть оформлены с отступом."
msgid ""
"The first statement of the function body can optionally be a string literal; "
"this string literal is the function's documentation string, or :dfn:"
"`docstring`. (More about docstrings can be found in the section :ref:`tut-"