From cf21fafa10798c0b116ac4b2ba14bab5e3441761 Mon Sep 17 00:00:00 2001 From: Maksim Litvinov Date: Wed, 27 Dec 2023 14:18:21 +0300 Subject: [PATCH] new structure --- .../10-basics/10-hello-world/en/EXERCISE.md | 9 ++ modules/10-basics/10-hello-world/en/README.md | 27 ++++ modules/10-basics/10-hello-world/en/data.yml | 1 + .../10-basics/10-hello-world/es/EXERCISE.md | 9 ++ modules/10-basics/10-hello-world/es/README.md | 44 ++++++ modules/10-basics/10-hello-world/es/data.yml | 5 + .../10-basics/10-hello-world/ru/EXERCISE.md | 9 ++ modules/10-basics/10-hello-world/ru/README.md | 44 ++++++ modules/10-basics/10-hello-world/ru/data.yml | 5 + modules/10-basics/20-tags/en/EXERCISE.md | 7 + modules/10-basics/20-tags/en/README.md | 3 + modules/10-basics/20-tags/en/data.yml | 7 + modules/10-basics/20-tags/es/EXERCISE.md | 7 + modules/10-basics/20-tags/es/README.md | 5 + modules/10-basics/20-tags/es/data.yml | 9 ++ modules/10-basics/20-tags/ru/EXERCISE.md | 7 + modules/10-basics/20-tags/ru/README.md | 5 + modules/10-basics/20-tags/ru/data.yml | 11 ++ modules/10-basics/30-comments/en/EXERCISE.md | 1 + modules/10-basics/30-comments/en/README.md | 37 +++++ modules/10-basics/30-comments/en/data.yml | 23 +++ modules/10-basics/30-comments/es/EXERCISE.md | 1 + modules/10-basics/30-comments/es/README.md | 27 ++++ modules/10-basics/30-comments/es/data.yml | 23 +++ modules/10-basics/30-comments/ru/EXERCISE.md | 1 + modules/10-basics/30-comments/ru/README.md | 27 ++++ modules/10-basics/30-comments/ru/data.yml | 23 +++ .../10-basics/40-instructions/en/EXERCISE.md | 7 + .../10-basics/40-instructions/en/README.md | 28 ++++ modules/10-basics/40-instructions/en/data.yml | 13 ++ .../10-basics/40-instructions/es/EXERCISE.md | 7 + .../10-basics/40-instructions/es/README.md | 28 ++++ modules/10-basics/40-instructions/es/data.yml | 14 ++ .../10-basics/40-instructions/ru/EXERCISE.md | 7 + .../10-basics/40-instructions/ru/README.md | 28 ++++ modules/10-basics/40-instructions/ru/data.yml | 12 ++ modules/10-basics/45-testing/en/EXERCISE.md | 1 + modules/10-basics/45-testing/en/README.md | 32 ++++ modules/10-basics/45-testing/en/data.yml | 9 ++ modules/10-basics/45-testing/es/EXERCISE.md | 1 + modules/10-basics/45-testing/es/README.md | 32 ++++ modules/10-basics/45-testing/es/data.yml | 9 ++ modules/10-basics/45-testing/ru/EXERCISE.md | 1 + modules/10-basics/45-testing/ru/README.md | 32 ++++ modules/10-basics/45-testing/ru/data.yml | 9 ++ .../10-basics/50-syntax-errors/en/EXERCISE.md | 4 + .../10-basics/50-syntax-errors/en/README.md | 15 ++ .../10-basics/50-syntax-errors/en/data.yml | 9 ++ .../10-basics/50-syntax-errors/es/EXERCISE.md | 4 + .../10-basics/50-syntax-errors/es/README.md | 16 ++ .../10-basics/50-syntax-errors/es/data.yml | 9 ++ .../10-basics/50-syntax-errors/ru/EXERCISE.md | 4 + .../10-basics/50-syntax-errors/ru/README.md | 16 ++ .../10-basics/50-syntax-errors/ru/data.yml | 7 + .../20-arithmetics/20-basic/en/EXERCISE.md | 2 + modules/20-arithmetics/20-basic/en/README.md | 52 +++++++ modules/20-arithmetics/20-basic/en/data.yml | 12 ++ .../20-arithmetics/20-basic/es/EXERCISE.md | 1 + modules/20-arithmetics/20-basic/es/README.md | 35 +++++ modules/20-arithmetics/20-basic/es/data.yml | 13 ++ .../20-arithmetics/20-basic/ru/EXERCISE.md | 1 + modules/20-arithmetics/20-basic/ru/README.md | 35 +++++ modules/20-arithmetics/20-basic/ru/data.yml | 13 ++ .../20-arithmetics/25-operator/en/EXERCISE.md | 1 + .../20-arithmetics/25-operator/en/README.md | 40 +++++ .../20-arithmetics/25-operator/en/data.yml | 13 ++ .../20-arithmetics/25-operator/es/EXERCISE.md | 1 + .../20-arithmetics/25-operator/es/README.md | 43 ++++++ .../20-arithmetics/25-operator/es/data.yml | 13 ++ .../20-arithmetics/25-operator/ru/EXERCISE.md | 1 + .../20-arithmetics/25-operator/ru/README.md | 43 ++++++ .../20-arithmetics/25-operator/ru/data.yml | 13 ++ .../27-commutativity/en/EXERCISE.md | 4 + .../27-commutativity/en/README.md | 7 + .../27-commutativity/en/data.yml | 9 ++ .../27-commutativity/es/EXERCISE.md | 3 + .../27-commutativity/es/README.md | 3 + .../27-commutativity/es/data.yml | 8 + .../27-commutativity/ru/EXERCISE.md | 3 + .../27-commutativity/ru/README.md | 3 + .../27-commutativity/ru/data.yml | 8 + .../30-composition/en/EXERCISE.md | 8 + .../30-composition/en/README.md | 25 ++++ .../20-arithmetics/30-composition/en/data.yml | 1 + .../30-composition/es/EXERCISE.md | 7 + .../30-composition/es/README.md | 17 +++ .../20-arithmetics/30-composition/es/data.yml | 2 + .../30-composition/ru/EXERCISE.md | 7 + .../30-composition/ru/README.md | 17 +++ .../20-arithmetics/30-composition/ru/data.yml | 2 + .../20-arithmetics/40-priority/en/EXERCISE.md | 4 + .../20-arithmetics/40-priority/en/README.md | 38 +++++ .../20-arithmetics/40-priority/en/data.yml | 5 + .../20-arithmetics/40-priority/es/EXERCISE.md | 3 + .../20-arithmetics/40-priority/es/README.md | 26 ++++ .../20-arithmetics/40-priority/es/data.yml | 5 + .../20-arithmetics/40-priority/ru/EXERCISE.md | 3 + .../20-arithmetics/40-priority/ru/README.md | 26 ++++ .../20-arithmetics/40-priority/ru/data.yml | 5 + .../20-arithmetics/45-linting/en/EXERCISE.md | 2 + .../20-arithmetics/45-linting/en/README.md | 37 +++++ modules/20-arithmetics/45-linting/en/data.yml | 1 + .../20-arithmetics/45-linting/es/EXERCISE.md | 1 + .../20-arithmetics/45-linting/es/README.md | 43 ++++++ modules/20-arithmetics/45-linting/es/data.yml | 2 + .../20-arithmetics/45-linting/ru/EXERCISE.md | 1 + .../20-arithmetics/45-linting/ru/README.md | 44 ++++++ modules/20-arithmetics/45-linting/ru/data.yml | 2 + modules/25-strings/10-quotes/en/EXERCISE.md | 12 ++ modules/25-strings/10-quotes/en/README.md | 93 ++++++++++++ modules/25-strings/10-quotes/en/data.yml | 2 + modules/25-strings/10-quotes/es/EXERCISE.md | 11 ++ modules/25-strings/10-quotes/es/README.md | 91 ++++++++++++ modules/25-strings/10-quotes/es/data.yml | 2 + modules/25-strings/10-quotes/ru/EXERCISE.md | 11 ++ modules/25-strings/10-quotes/ru/README.md | 91 ++++++++++++ modules/25-strings/10-quotes/ru/data.yml | 2 + .../15-escape-characters/en/EXERCISE.md | 7 + .../15-escape-characters/en/README.md | 118 +++++++++++++++ .../15-escape-characters/en/data.yml | 12 ++ .../15-escape-characters/es/EXERCISE.md | 5 + .../15-escape-characters/es/README.md | 42 ++++++ .../15-escape-characters/es/data.yml | 13 ++ .../15-escape-characters/ru/EXERCISE.md | 5 + .../15-escape-characters/ru/README.md | 42 ++++++ .../15-escape-characters/ru/data.yml | 13 ++ .../20-strings-concatenation/en/EXERCISE.md | 8 + .../20-strings-concatenation/en/README.md | 64 ++++++++ .../20-strings-concatenation/en/data.yml | 6 + .../20-strings-concatenation/es/EXERCISE.md | 7 + .../20-strings-concatenation/es/README.md | 43 ++++++ .../20-strings-concatenation/es/data.yml | 6 + .../20-strings-concatenation/ru/EXERCISE.md | 7 + .../20-strings-concatenation/ru/README.md | 45 ++++++ .../20-strings-concatenation/ru/data.yml | 6 + modules/25-strings/30-encoding/en/EXERCISE.md | 16 ++ modules/25-strings/30-encoding/en/README.md | 40 +++++ modules/25-strings/30-encoding/en/data.yml | 5 + modules/25-strings/30-encoding/es/EXERCISE.md | 16 ++ modules/25-strings/30-encoding/es/README.md | 39 +++++ modules/25-strings/30-encoding/es/data.yml | 7 + modules/25-strings/30-encoding/ru/EXERCISE.md | 16 ++ modules/25-strings/30-encoding/ru/README.md | 40 +++++ modules/25-strings/30-encoding/ru/data.yml | 7 + .../40-primitive-data-types/en/EXERCISE.md | 1 + .../40-primitive-data-types/en/README.md | 34 +++++ .../40-primitive-data-types/en/data.yml | 9 ++ .../40-primitive-data-types/es/EXERCISE.md | 1 + .../40-primitive-data-types/es/README.md | 38 +++++ .../40-primitive-data-types/es/data.yml | 20 +++ .../40-primitive-data-types/ru/EXERCISE.md | 1 + .../40-primitive-data-types/ru/README.md | 40 +++++ .../40-primitive-data-types/ru/data.yml | 18 +++ .../50-data-types-weak-typing/en/EXERCISE.md | 2 + .../50-data-types-weak-typing/en/README.md | 22 +++ .../50-data-types-weak-typing/en/data.yml | 1 + .../50-data-types-weak-typing/es/EXERCISE.md | 1 + .../50-data-types-weak-typing/es/README.md | 17 +++ .../50-data-types-weak-typing/es/data.yml | 2 + .../50-data-types-weak-typing/ru/EXERCISE.md | 1 + .../50-data-types-weak-typing/ru/README.md | 17 +++ .../50-data-types-weak-typing/ru/data.yml | 2 + .../55-type-conversion/en/EXERCISE.md | 2 + .../55-type-conversion/en/README.md | 41 +++++ .../55-type-conversion/en/data.yml | 1 + .../55-type-conversion/es/EXERCISE.md | 1 + .../55-type-conversion/es/README.md | 27 ++++ .../55-type-conversion/es/data.yml | 3 + .../55-type-conversion/ru/EXERCISE.md | 1 + .../55-type-conversion/ru/README.md | 27 ++++ .../55-type-conversion/ru/data.yml | 3 + .../30-variables/10-definition/en/EXERCISE.md | 2 + .../30-variables/10-definition/en/README.md | 48 ++++++ .../30-variables/10-definition/en/data.yml | 5 + .../30-variables/10-definition/es/EXERCISE.md | 1 + .../30-variables/10-definition/es/README.md | 34 +++++ .../30-variables/10-definition/es/data.yml | 7 + .../30-variables/10-definition/ru/EXERCISE.md | 1 + .../30-variables/10-definition/ru/README.md | 34 +++++ .../30-variables/10-definition/ru/data.yml | 7 + modules/30-variables/12-change/en/EXERCISE.md | 2 + modules/30-variables/12-change/en/README.md | 21 +++ modules/30-variables/12-change/en/data.yml | 7 + modules/30-variables/12-change/es/EXERCISE.md | 1 + modules/30-variables/12-change/es/README.md | 18 +++ modules/30-variables/12-change/es/data.yml | 10 ++ modules/30-variables/12-change/ru/EXERCISE.md | 1 + modules/30-variables/12-change/ru/README.md | 18 +++ modules/30-variables/12-change/ru/data.yml | 10 ++ .../13-variables-naming/en/EXERCISE.md | 2 + .../13-variables-naming/en/README.md | 19 +++ .../13-variables-naming/en/data.yml | 5 + .../13-variables-naming/es/EXERCISE.md | 1 + .../13-variables-naming/es/README.md | 17 +++ .../13-variables-naming/es/data.yml | 8 + .../13-variables-naming/ru/EXERCISE.md | 1 + .../13-variables-naming/ru/README.md | 17 +++ .../13-variables-naming/ru/data.yml | 9 ++ modules/30-variables/14-errors/en/EXERCISE.md | 8 + modules/30-variables/14-errors/en/README.md | 13 ++ modules/30-variables/14-errors/en/data.yml | 1 + modules/30-variables/14-errors/es/EXERCISE.md | 7 + modules/30-variables/14-errors/es/README.md | 13 ++ modules/30-variables/14-errors/es/data.yml | 3 + modules/30-variables/14-errors/ru/EXERCISE.md | 7 + modules/30-variables/14-errors/ru/README.md | 13 ++ modules/30-variables/14-errors/ru/data.yml | 3 + .../15-expressions/en/EXERCISE.md | 13 ++ .../30-variables/15-expressions/en/README.md | 74 +++++++++ .../30-variables/15-expressions/en/data.yml | 5 + .../15-expressions/es/EXERCISE.md | 8 + .../30-variables/15-expressions/es/README.md | 69 +++++++++ .../30-variables/15-expressions/es/data.yml | 5 + .../15-expressions/ru/EXERCISE.md | 12 ++ .../30-variables/15-expressions/ru/README.md | 69 +++++++++ .../30-variables/15-expressions/ru/data.yml | 4 + .../18-concatenation/en/EXERCISE.md | 18 +++ .../18-concatenation/en/README.md | 32 ++++ .../30-variables/18-concatenation/en/data.yml | 8 + .../18-concatenation/es/EXERCISE.md | 18 +++ .../18-concatenation/es/README.md | 32 ++++ .../30-variables/18-concatenation/es/data.yml | 8 + .../18-concatenation/ru/EXERCISE.md | 18 +++ .../18-concatenation/ru/README.md | 32 ++++ .../30-variables/18-concatenation/ru/data.yml | 8 + .../19-naming-style/en/EXERCISE.md | 4 + .../30-variables/19-naming-style/en/README.md | 17 +++ .../30-variables/19-naming-style/en/data.yml | 4 + .../19-naming-style/es/EXERCISE.md | 3 + .../30-variables/19-naming-style/es/README.md | 18 +++ .../30-variables/19-naming-style/es/data.yml | 5 + .../19-naming-style/ru/EXERCISE.md | 3 + .../30-variables/19-naming-style/ru/README.md | 18 +++ .../30-variables/19-naming-style/ru/data.yml | 5 + .../20-magic-numbers/en/EXERCISE.md | 25 ++++ .../20-magic-numbers/en/README.md | 37 +++++ .../30-variables/20-magic-numbers/en/data.yml | 1 + .../20-magic-numbers/es/EXERCISE.md | 25 ++++ .../20-magic-numbers/es/README.md | 37 +++++ .../30-variables/20-magic-numbers/es/data.yml | 2 + .../20-magic-numbers/ru/EXERCISE.md | 25 ++++ .../20-magic-numbers/ru/README.md | 37 +++++ .../30-variables/20-magic-numbers/ru/data.yml | 2 + .../30-variables/23-constants/en/EXERCISE.md | 2 + .../30-variables/23-constants/en/README.md | 19 +++ modules/30-variables/23-constants/en/data.yml | 10 ++ .../30-variables/23-constants/es/EXERCISE.md | 1 + .../30-variables/23-constants/es/README.md | 32 ++++ modules/30-variables/23-constants/es/data.yml | 11 ++ .../30-variables/23-constants/ru/EXERCISE.md | 1 + .../30-variables/23-constants/ru/README.md | 32 ++++ modules/30-variables/23-constants/ru/data.yml | 10 ++ .../24-magic-constants/en/EXERCISE.md | 2 + .../24-magic-constants/en/README.md | 12 ++ .../24-magic-constants/en/data.yml | 10 ++ .../24-magic-constants/es/EXERCISE.md | 2 + .../24-magic-constants/es/README.md | 12 ++ .../24-magic-constants/es/data.yml | 10 ++ .../24-magic-constants/ru/EXERCISE.md | 2 + .../24-magic-constants/ru/README.md | 12 ++ .../24-magic-constants/ru/data.yml | 10 ++ .../25-interpolation/en/EXERCISE.md | 6 + .../25-interpolation/en/README.md | 32 ++++ .../30-variables/25-interpolation/en/data.yml | 7 + .../25-interpolation/es/EXERCISE.md | 5 + .../25-interpolation/es/README.md | 33 +++++ .../30-variables/25-interpolation/es/data.yml | 8 + .../25-interpolation/ru/EXERCISE.md | 5 + .../25-interpolation/ru/README.md | 33 +++++ .../30-variables/25-interpolation/ru/data.yml | 7 + .../30-variables/30-symbols/en/EXERCISE.md | 10 ++ modules/30-variables/30-symbols/en/README.md | 46 ++++++ modules/30-variables/30-symbols/en/data.yml | 1 + .../30-variables/30-symbols/es/EXERCISE.md | 9 ++ modules/30-variables/30-symbols/es/README.md | 49 ++++++ modules/30-variables/30-symbols/es/data.yml | 2 + .../30-variables/30-symbols/ru/EXERCISE.md | 9 ++ modules/30-variables/30-symbols/ru/README.md | 49 ++++++ modules/30-variables/30-symbols/ru/data.yml | 2 + .../30-variables/35-heredoc/en/EXERCISE.md | 5 + modules/30-variables/35-heredoc/en/README.md | 23 +++ modules/30-variables/35-heredoc/en/data.yml | 5 + .../30-variables/35-heredoc/es/EXERCISE.md | 5 + modules/30-variables/35-heredoc/es/README.md | 19 +++ modules/30-variables/35-heredoc/es/data.yml | 5 + .../30-variables/35-heredoc/ru/EXERCISE.md | 5 + modules/30-variables/35-heredoc/ru/README.md | 19 +++ modules/30-variables/35-heredoc/ru/data.yml | 5 + .../100-call/en/EXERCISE.md | 2 + .../100-call/en/README.md | 64 ++++++++ .../35-calling-functions/100-call/en/data.yml | 11 ++ .../100-call/es/EXERCISE.md | 1 + .../100-call/es/README.md | 64 ++++++++ .../35-calling-functions/100-call/es/data.yml | 11 ++ .../100-call/ru/EXERCISE.md | 1 + .../100-call/ru/README.md | 64 ++++++++ .../35-calling-functions/100-call/ru/data.yml | 11 ++ .../120-function-signature/en/EXERCISE.md | 6 + .../120-function-signature/en/README.md | 28 ++++ .../120-function-signature/en/data.yml | 6 + .../120-function-signature/es/EXERCISE.md | 5 + .../120-function-signature/es/README.md | 70 +++++++++ .../120-function-signature/es/data.yml | 7 + .../120-function-signature/ru/EXERCISE.md | 5 + .../120-function-signature/ru/README.md | 70 +++++++++ .../120-function-signature/ru/data.yml | 7 + .../en/EXERCISE.md | 2 + .../en/README.md | 28 ++++ .../en/data.yml | 4 + .../es/EXERCISE.md | 2 + .../es/README.md | 28 ++++ .../es/data.yml | 5 + .../ru/EXERCISE.md | 2 + .../ru/README.md | 28 ++++ .../ru/data.yml | 5 + .../en/EXERCISE.md | 8 + .../en/README.md | 63 ++++++++ .../en/data.yml | 1 + .../es/EXERCISE.md | 8 + .../es/README.md | 58 ++++++++ .../es/data.yml | 1 + .../ru/EXERCISE.md | 8 + .../ru/README.md | 58 ++++++++ .../ru/data.yml | 1 + .../180-variadic-arguments/en/EXERCISE.md | 2 + .../180-variadic-arguments/en/README.md | 22 +++ .../180-variadic-arguments/en/data.yml | 2 + .../180-variadic-arguments/es/EXERCISE.md | 1 + .../180-variadic-arguments/es/README.md | 16 ++ .../180-variadic-arguments/es/data.yml | 2 + .../180-variadic-arguments/ru/EXERCISE.md | 1 + .../180-variadic-arguments/ru/README.md | 16 ++ .../180-variadic-arguments/ru/data.yml | 2 + .../270-deterministic/en/EXERCISE.md | 2 + .../270-deterministic/en/README.md | 20 +++ .../270-deterministic/en/data.yml | 4 + .../270-deterministic/es/EXERCISE.md | 1 + .../270-deterministic/es/README.md | 53 +++++++ .../270-deterministic/es/data.yml | 5 + .../270-deterministic/ru/EXERCISE.md | 1 + .../270-deterministic/ru/README.md | 53 +++++++ .../270-deterministic/ru/data.yml | 5 + .../900-stdlib/en/EXERCISE.md | 4 + .../900-stdlib/en/README.md | 12 ++ .../900-stdlib/en/data.yml | 8 + .../900-stdlib/es/EXERCISE.md | 4 + .../900-stdlib/es/README.md | 15 ++ .../900-stdlib/es/data.yml | 10 ++ .../900-stdlib/ru/EXERCISE.md | 4 + .../900-stdlib/ru/README.md | 15 ++ .../900-stdlib/ru/data.yml | 9 ++ .../100-define/en/EXERCISE.md | 10 ++ .../100-define/en/README.md | 58 ++++++++ .../100-define/en/data.yml | 5 + .../100-define/es/EXERCISE.md | 9 ++ .../100-define/es/README.md | 66 +++++++++ .../100-define/es/data.yml | 4 + .../100-define/ru/EXERCISE.md | 9 ++ .../100-define/ru/README.md | 68 +++++++++ .../100-define/ru/data.yml | 5 + .../200-return/en/EXERCISE.md | 8 + .../200-return/en/README.md | 134 +++++++++++++++++ .../200-return/en/data.yml | 1 + .../200-return/es/EXERCISE.md | 8 + .../200-return/es/README.md | 140 ++++++++++++++++++ .../200-return/es/data.yml | 2 + .../200-return/ru/EXERCISE.md | 8 + .../200-return/ru/README.md | 140 ++++++++++++++++++ .../200-return/ru/data.yml | 2 + .../300-parameters/en/EXERCISE.md | 29 ++++ .../300-parameters/en/README.md | 73 +++++++++ .../300-parameters/en/data.yml | 1 + .../300-parameters/es/EXERCISE.md | 28 ++++ .../300-parameters/es/README.md | 74 +++++++++ .../300-parameters/es/data.yml | 1 + .../300-parameters/ru/EXERCISE.md | 28 ++++ .../300-parameters/ru/README.md | 74 +++++++++ .../300-parameters/ru/data.yml | 1 + .../340-default-parameters/en/EXERCISE.md | 21 +++ .../340-default-parameters/en/README.md | 72 +++++++++ .../340-default-parameters/en/data.yml | 1 + .../340-default-parameters/es/EXERCISE.md | 21 +++ .../340-default-parameters/es/README.md | 74 +++++++++ .../340-default-parameters/es/data.yml | 1 + .../340-default-parameters/ru/EXERCISE.md | 21 +++ .../340-default-parameters/ru/README.md | 74 +++++++++ .../340-default-parameters/ru/data.yml | 1 + .../500-reading-documentation/en/EXERCISE.md | 12 ++ .../500-reading-documentation/en/README.md | 25 ++++ .../500-reading-documentation/en/data.yml | 6 + .../500-reading-documentation/es/EXERCISE.md | 12 ++ .../500-reading-documentation/es/README.md | 28 ++++ .../500-reading-documentation/es/data.yml | 8 + .../500-reading-documentation/ru/EXERCISE.md | 12 ++ .../500-reading-documentation/ru/README.md | 28 ++++ .../500-reading-documentation/ru/data.yml | 8 + modules/45-logic/10-bool-type/en/EXERCISE.md | 11 ++ modules/45-logic/10-bool-type/en/README.md | 71 +++++++++ modules/45-logic/10-bool-type/en/data.yml | 4 + modules/45-logic/10-bool-type/es/EXERCISE.md | 10 ++ modules/45-logic/10-bool-type/es/README.md | 51 +++++++ modules/45-logic/10-bool-type/es/data.yml | 6 + modules/45-logic/10-bool-type/ru/EXERCISE.md | 10 ++ modules/45-logic/10-bool-type/ru/README.md | 51 +++++++ modules/45-logic/10-bool-type/ru/data.yml | 4 + modules/45-logic/15-predicates/en/EXERCISE.md | 9 ++ modules/45-logic/15-predicates/en/README.md | 43 ++++++ modules/45-logic/15-predicates/en/data.yml | 10 ++ modules/45-logic/15-predicates/es/EXERCISE.md | 9 ++ modules/45-logic/15-predicates/es/README.md | 22 +++ modules/45-logic/15-predicates/es/data.yml | 9 ++ modules/45-logic/15-predicates/ru/EXERCISE.md | 9 ++ modules/45-logic/15-predicates/ru/README.md | 22 +++ modules/45-logic/15-predicates/ru/data.yml | 8 + .../en/EXERCISE.md | 9 ++ .../20-logic-combine-expressions/en/README.md | 98 ++++++++++++ .../20-logic-combine-expressions/en/data.yml | 1 + .../es/EXERCISE.md | 9 ++ .../20-logic-combine-expressions/es/README.md | 52 +++++++ .../20-logic-combine-expressions/es/data.yml | 1 + .../ru/EXERCISE.md | 9 ++ .../20-logic-combine-expressions/ru/README.md | 52 +++++++ .../20-logic-combine-expressions/ru/data.yml | 1 + .../25-logical-operators/en/EXERCISE.md | 22 +++ .../25-logical-operators/en/README.md | 107 +++++++++++++ .../45-logic/25-logical-operators/en/data.yml | 13 ++ .../25-logical-operators/es/EXERCISE.md | 22 +++ .../25-logical-operators/es/README.md | 52 +++++++ .../45-logic/25-logical-operators/es/data.yml | 13 ++ .../25-logical-operators/ru/EXERCISE.md | 22 +++ .../25-logical-operators/ru/README.md | 52 +++++++ .../45-logic/25-logical-operators/ru/data.yml | 13 ++ .../28-logical-negation/en/EXERCISE.md | 30 ++++ .../45-logic/28-logical-negation/en/README.md | 28 ++++ .../45-logic/28-logical-negation/en/data.yml | 4 + .../28-logical-negation/es/EXERCISE.md | 30 ++++ .../45-logic/28-logical-negation/es/README.md | 19 +++ .../45-logic/28-logical-negation/es/data.yml | 4 + .../28-logical-negation/ru/EXERCISE.md | 30 ++++ .../45-logic/28-logical-negation/ru/README.md | 19 +++ .../45-logic/28-logical-negation/ru/data.yml | 4 + .../29-logical-operators-2/en/EXERCISE.md | 17 +++ .../29-logical-operators-2/en/README.md | 26 ++++ .../29-logical-operators-2/en/data.yml | 1 + .../29-logical-operators-2/es/EXERCISE.md | 17 +++ .../29-logical-operators-2/es/README.md | 26 ++++ .../29-logical-operators-2/es/data.yml | 1 + .../29-logical-operators-2/ru/EXERCISE.md | 17 +++ .../29-logical-operators-2/ru/README.md | 26 ++++ .../29-logical-operators-2/ru/data.yml | 1 + .../70-logic-weak-typing/en/EXERCISE.md | 11 ++ .../70-logic-weak-typing/en/README.md | 92 ++++++++++++ .../45-logic/70-logic-weak-typing/en/data.yml | 4 + .../70-logic-weak-typing/es/EXERCISE.md | 11 ++ .../70-logic-weak-typing/es/README.md | 54 +++++++ .../45-logic/70-logic-weak-typing/es/data.yml | 4 + .../70-logic-weak-typing/ru/EXERCISE.md | 11 ++ .../70-logic-weak-typing/ru/README.md | 54 +++++++ .../45-logic/70-logic-weak-typing/ru/data.yml | 4 + modules/48-conditionals/30-if/en/EXERCISE.md | 9 ++ modules/48-conditionals/30-if/en/README.md | 49 ++++++ modules/48-conditionals/30-if/en/data.yml | 6 + modules/48-conditionals/30-if/es/EXERCISE.md | 9 ++ modules/48-conditionals/30-if/es/README.md | 25 ++++ modules/48-conditionals/30-if/es/data.yml | 7 + modules/48-conditionals/30-if/ru/EXERCISE.md | 9 ++ modules/48-conditionals/30-if/ru/README.md | 25 ++++ modules/48-conditionals/30-if/ru/data.yml | 7 + .../48-conditionals/40-if-else/en/EXERCISE.md | 20 +++ .../48-conditionals/40-if-else/en/README.md | 45 ++++++ .../48-conditionals/40-if-else/en/data.yml | 6 + .../48-conditionals/40-if-else/es/EXERCISE.md | 20 +++ .../48-conditionals/40-if-else/es/README.md | 44 ++++++ .../48-conditionals/40-if-else/es/data.yml | 7 + .../48-conditionals/40-if-else/ru/EXERCISE.md | 20 +++ .../48-conditionals/40-if-else/ru/README.md | 44 ++++++ .../48-conditionals/40-if-else/ru/data.yml | 7 + .../48-conditionals/50-else-if/en/EXERCISE.md | 21 +++ .../48-conditionals/50-else-if/en/README.md | 61 ++++++++ .../48-conditionals/50-else-if/en/data.yml | 4 + .../48-conditionals/50-else-if/es/EXERCISE.md | 21 +++ .../48-conditionals/50-else-if/es/README.md | 62 ++++++++ .../48-conditionals/50-else-if/es/data.yml | 5 + .../48-conditionals/50-else-if/ru/EXERCISE.md | 21 +++ .../48-conditionals/50-else-if/ru/README.md | 62 ++++++++ .../48-conditionals/50-else-if/ru/data.yml | 5 + .../60-ternary-operator/en/EXERCISE.md | 13 ++ .../60-ternary-operator/en/README.md | 74 +++++++++ .../60-ternary-operator/en/data.yml | 6 + .../60-ternary-operator/es/EXERCISE.md | 13 ++ .../60-ternary-operator/es/README.md | 75 ++++++++++ .../60-ternary-operator/es/data.yml | 7 + .../60-ternary-operator/ru/EXERCISE.md | 13 ++ .../60-ternary-operator/ru/README.md | 75 ++++++++++ .../60-ternary-operator/ru/data.yml | 7 + .../48-conditionals/65-switch/en/EXERCISE.md | 13 ++ .../48-conditionals/65-switch/en/README.md | 105 +++++++++++++ modules/48-conditionals/65-switch/en/data.yml | 4 + .../48-conditionals/65-switch/es/EXERCISE.md | 16 ++ .../48-conditionals/65-switch/es/README.md | 106 +++++++++++++ modules/48-conditionals/65-switch/es/data.yml | 5 + .../48-conditionals/65-switch/ru/EXERCISE.md | 16 ++ .../48-conditionals/65-switch/ru/README.md | 106 +++++++++++++ modules/48-conditionals/65-switch/ru/data.yml | 5 + .../48-conditionals/75-elvis/en/EXERCISE.md | 13 ++ modules/48-conditionals/75-elvis/en/README.md | 55 +++++++ modules/48-conditionals/75-elvis/en/data.yml | 9 ++ .../48-conditionals/75-elvis/es/EXERCISE.md | 13 ++ modules/48-conditionals/75-elvis/es/README.md | 51 +++++++ modules/48-conditionals/75-elvis/es/data.yml | 9 ++ .../48-conditionals/75-elvis/ru/EXERCISE.md | 13 ++ modules/48-conditionals/75-elvis/ru/README.md | 52 +++++++ modules/48-conditionals/75-elvis/ru/data.yml | 9 ++ modules/50-loops/10-while/en/EXERCISE.md | 17 +++ modules/50-loops/10-while/en/README.md | 118 +++++++++++++++ modules/50-loops/10-while/en/data.yml | 9 ++ modules/50-loops/10-while/es/EXERCISE.md | 16 ++ modules/50-loops/10-while/es/README.md | 122 +++++++++++++++ modules/50-loops/10-while/es/data.yml | 9 ++ modules/50-loops/10-while/ru/EXERCISE.md | 16 ++ modules/50-loops/10-while/ru/README.md | 122 +++++++++++++++ modules/50-loops/10-while/ru/data.yml | 7 + .../20-aggregation-numbers/en/EXERCISE.md | 10 ++ .../20-aggregation-numbers/en/README.md | 82 ++++++++++ .../20-aggregation-numbers/en/data.yml | 1 + .../20-aggregation-numbers/es/EXERCISE.md | 9 ++ .../20-aggregation-numbers/es/README.md | 96 ++++++++++++ .../20-aggregation-numbers/es/data.yml | 2 + .../20-aggregation-numbers/ru/EXERCISE.md | 9 ++ .../20-aggregation-numbers/ru/README.md | 96 ++++++++++++ .../20-aggregation-numbers/ru/data.yml | 2 + .../23-aggregation-strings/en/EXERCISE.md | 10 ++ .../23-aggregation-strings/en/README.md | 43 ++++++ .../23-aggregation-strings/en/data.yml | 1 + .../23-aggregation-strings/es/EXERCISE.md | 10 ++ .../23-aggregation-strings/es/README.md | 42 ++++++ .../23-aggregation-strings/es/data.yml | 2 + .../23-aggregation-strings/ru/EXERCISE.md | 10 ++ .../23-aggregation-strings/ru/README.md | 42 ++++++ .../23-aggregation-strings/ru/data.yml | 2 + .../25-iteration-over-string/en/EXERCISE.md | 16 ++ .../25-iteration-over-string/en/README.md | 29 ++++ .../25-iteration-over-string/en/data.yml | 1 + .../25-iteration-over-string/es/EXERCISE.md | 16 ++ .../25-iteration-over-string/es/README.md | 34 +++++ .../25-iteration-over-string/es/data.yml | 2 + .../25-iteration-over-string/ru/EXERCISE.md | 16 ++ .../25-iteration-over-string/ru/README.md | 34 +++++ .../25-iteration-over-string/ru/data.yml | 2 + .../26-conditions-inside-loops/en/EXERCISE.md | 9 ++ .../26-conditions-inside-loops/en/README.md | 43 ++++++ .../26-conditions-inside-loops/en/data.yml | 1 + .../26-conditions-inside-loops/es/EXERCISE.md | 9 ++ .../26-conditions-inside-loops/es/README.md | 43 ++++++ .../26-conditions-inside-loops/es/data.yml | 2 + .../26-conditions-inside-loops/ru/EXERCISE.md | 9 ++ .../26-conditions-inside-loops/ru/README.md | 43 ++++++ .../26-conditions-inside-loops/ru/data.yml | 2 + .../50-loops/28-build-strings/en/EXERCISE.md | 16 ++ .../50-loops/28-build-strings/en/README.md | 43 ++++++ modules/50-loops/28-build-strings/en/data.yml | 1 + .../50-loops/28-build-strings/es/EXERCISE.md | 15 ++ .../50-loops/28-build-strings/es/README.md | 44 ++++++ modules/50-loops/28-build-strings/es/data.yml | 2 + .../50-loops/28-build-strings/ru/EXERCISE.md | 15 ++ .../50-loops/28-build-strings/ru/README.md | 44 ++++++ modules/50-loops/28-build-strings/ru/data.yml | 2 + modules/50-loops/29-edge-cases/en/EXERCISE.md | 31 ++++ modules/50-loops/29-edge-cases/en/README.md | 35 +++++ modules/50-loops/29-edge-cases/en/data.yml | 1 + modules/50-loops/29-edge-cases/es/EXERCISE.md | 30 ++++ modules/50-loops/29-edge-cases/es/README.md | 73 +++++++++ modules/50-loops/29-edge-cases/es/data.yml | 2 + modules/50-loops/29-edge-cases/ru/EXERCISE.md | 30 ++++ modules/50-loops/29-edge-cases/ru/README.md | 73 +++++++++ modules/50-loops/29-edge-cases/ru/data.yml | 2 + .../50-loops/30-syntax-sugar/en/EXERCISE.md | 10 ++ modules/50-loops/30-syntax-sugar/en/README.md | 12 ++ modules/50-loops/30-syntax-sugar/en/data.yml | 1 + .../50-loops/30-syntax-sugar/es/EXERCISE.md | 10 ++ modules/50-loops/30-syntax-sugar/es/README.md | 12 ++ modules/50-loops/30-syntax-sugar/es/data.yml | 2 + .../50-loops/30-syntax-sugar/ru/EXERCISE.md | 10 ++ modules/50-loops/30-syntax-sugar/ru/README.md | 12 ++ modules/50-loops/30-syntax-sugar/ru/data.yml | 2 + modules/50-loops/50-mutators/en/EXERCISE.md | 14 ++ modules/50-loops/50-mutators/en/README.md | 64 ++++++++ modules/50-loops/50-mutators/en/data.yml | 1 + modules/50-loops/50-mutators/es/EXERCISE.md | 13 ++ modules/50-loops/50-mutators/es/README.md | 64 ++++++++ modules/50-loops/50-mutators/es/data.yml | 2 + modules/50-loops/50-mutators/ru/EXERCISE.md | 13 ++ modules/50-loops/50-mutators/ru/README.md | 64 ++++++++ modules/50-loops/50-mutators/ru/data.yml | 2 + .../55-return-from-loop/en/EXERCISE.md | 16 ++ .../50-loops/55-return-from-loop/en/README.md | 41 +++++ .../50-loops/55-return-from-loop/en/data.yml | 3 + .../55-return-from-loop/es/EXERCISE.md | 16 ++ .../50-loops/55-return-from-loop/es/README.md | 41 +++++ .../50-loops/55-return-from-loop/es/data.yml | 3 + .../55-return-from-loop/ru/EXERCISE.md | 16 ++ .../50-loops/55-return-from-loop/ru/README.md | 41 +++++ .../50-loops/55-return-from-loop/ru/data.yml | 3 + modules/50-loops/70-for/en/EXERCISE.md | 20 +++ modules/50-loops/70-for/en/README.md | 30 ++++ modules/50-loops/70-for/en/data.yml | 1 + modules/50-loops/70-for/es/EXERCISE.md | 20 +++ modules/50-loops/70-for/es/README.md | 33 +++++ modules/50-loops/70-for/es/data.yml | 2 + modules/50-loops/70-for/ru/EXERCISE.md | 20 +++ modules/50-loops/70-for/ru/README.md | 33 +++++ modules/50-loops/70-for/ru/data.yml | 2 + .../10-unicode/en/EXERCISE.md | 9 ++ .../10-unicode/en/README.md | 40 +++++ .../10-unicode/en/data.yml | 3 + .../10-unicode/es/EXERCISE.md | 9 ++ .../10-unicode/es/README.md | 71 +++++++++ .../10-unicode/es/data.yml | 5 + .../10-unicode/ru/EXERCISE.md | 9 ++ .../10-unicode/ru/README.md | 71 +++++++++ .../10-unicode/ru/data.yml | 5 + .../30-locales/en/EXERCISE.md | 2 + .../30-locales/en/README.md | 33 +++++ .../30-locales/en/data.yml | 1 + .../30-locales/es/EXERCISE.md | 1 + .../30-locales/es/README.md | 36 +++++ .../30-locales/es/data.yml | 3 + .../30-locales/ru/EXERCISE.md | 1 + .../30-locales/ru/README.md | 36 +++++ .../30-locales/ru/data.yml | 3 + .../40-startwith/en/EXERCISE.md | 9 ++ .../40-startwith/en/README.md | 32 ++++ .../40-startwith/en/data.yml | 1 + .../40-startwith/es/EXERCISE.md | 8 + .../40-startwith/es/README.md | 33 +++++ .../40-startwith/es/data.yml | 3 + .../40-startwith/ru/EXERCISE.md | 8 + .../40-startwith/ru/README.md | 33 +++++ .../40-startwith/ru/data.yml | 3 + modules/70-dates/10-timestamp/en/EXERCISE.md | 13 ++ modules/70-dates/10-timestamp/en/README.md | 14 ++ modules/70-dates/10-timestamp/en/data.yml | 1 + modules/70-dates/10-timestamp/es/EXERCISE.md | 12 ++ modules/70-dates/10-timestamp/es/README.md | 21 +++ modules/70-dates/10-timestamp/es/data.yml | 3 + modules/70-dates/10-timestamp/ru/EXERCISE.md | 12 ++ modules/70-dates/10-timestamp/ru/README.md | 21 +++ modules/70-dates/10-timestamp/ru/data.yml | 3 + modules/70-dates/20-date/en/EXERCISE.md | 12 ++ modules/70-dates/20-date/en/README.md | 25 ++++ modules/70-dates/20-date/en/data.yml | 5 + modules/70-dates/20-date/es/EXERCISE.md | 11 ++ modules/70-dates/20-date/es/README.md | 26 ++++ modules/70-dates/20-date/es/data.yml | 6 + modules/70-dates/20-date/ru/EXERCISE.md | 11 ++ modules/70-dates/20-date/ru/README.md | 26 ++++ modules/70-dates/20-date/ru/data.yml | 5 + modules/70-dates/30-mktime/en/EXERCISE.md | 8 + modules/70-dates/30-mktime/en/README.md | 14 ++ modules/70-dates/30-mktime/en/data.yml | 1 + modules/70-dates/30-mktime/es/EXERCISE.md | 8 + modules/70-dates/30-mktime/es/README.md | 20 +++ modules/70-dates/30-mktime/es/data.yml | 3 + modules/70-dates/30-mktime/ru/EXERCISE.md | 8 + modules/70-dates/30-mktime/ru/README.md | 20 +++ modules/70-dates/30-mktime/ru/data.yml | 3 + modules/70-dates/40-timezone/en/EXERCISE.md | 2 + modules/70-dates/40-timezone/en/README.md | 8 + modules/70-dates/40-timezone/en/data.yml | 5 + modules/70-dates/40-timezone/es/EXERCISE.md | 2 + modules/70-dates/40-timezone/es/README.md | 9 ++ modules/70-dates/40-timezone/es/data.yml | 6 + modules/70-dates/40-timezone/ru/EXERCISE.md | 2 + modules/70-dates/40-timezone/ru/README.md | 9 ++ modules/70-dates/40-timezone/ru/data.yml | 6 + 675 files changed, 12949 insertions(+) create mode 100644 modules/10-basics/10-hello-world/en/EXERCISE.md create mode 100644 modules/10-basics/10-hello-world/en/README.md create mode 100644 modules/10-basics/10-hello-world/en/data.yml create mode 100644 modules/10-basics/10-hello-world/es/EXERCISE.md create mode 100644 modules/10-basics/10-hello-world/es/README.md create mode 100644 modules/10-basics/10-hello-world/es/data.yml create mode 100644 modules/10-basics/10-hello-world/ru/EXERCISE.md create mode 100644 modules/10-basics/10-hello-world/ru/README.md create mode 100644 modules/10-basics/10-hello-world/ru/data.yml create mode 100644 modules/10-basics/20-tags/en/EXERCISE.md create mode 100644 modules/10-basics/20-tags/en/README.md create mode 100644 modules/10-basics/20-tags/en/data.yml create mode 100644 modules/10-basics/20-tags/es/EXERCISE.md create mode 100644 modules/10-basics/20-tags/es/README.md create mode 100644 modules/10-basics/20-tags/es/data.yml create mode 100644 modules/10-basics/20-tags/ru/EXERCISE.md create mode 100644 modules/10-basics/20-tags/ru/README.md create mode 100644 modules/10-basics/20-tags/ru/data.yml create mode 100644 modules/10-basics/30-comments/en/EXERCISE.md create mode 100644 modules/10-basics/30-comments/en/README.md create mode 100644 modules/10-basics/30-comments/en/data.yml create mode 100644 modules/10-basics/30-comments/es/EXERCISE.md create mode 100644 modules/10-basics/30-comments/es/README.md create mode 100644 modules/10-basics/30-comments/es/data.yml create mode 100644 modules/10-basics/30-comments/ru/EXERCISE.md create mode 100644 modules/10-basics/30-comments/ru/README.md create mode 100644 modules/10-basics/30-comments/ru/data.yml create mode 100644 modules/10-basics/40-instructions/en/EXERCISE.md create mode 100644 modules/10-basics/40-instructions/en/README.md create mode 100644 modules/10-basics/40-instructions/en/data.yml create mode 100644 modules/10-basics/40-instructions/es/EXERCISE.md create mode 100644 modules/10-basics/40-instructions/es/README.md create mode 100644 modules/10-basics/40-instructions/es/data.yml create mode 100644 modules/10-basics/40-instructions/ru/EXERCISE.md create mode 100644 modules/10-basics/40-instructions/ru/README.md create mode 100644 modules/10-basics/40-instructions/ru/data.yml create mode 100644 modules/10-basics/45-testing/en/EXERCISE.md create mode 100644 modules/10-basics/45-testing/en/README.md create mode 100644 modules/10-basics/45-testing/en/data.yml create mode 100644 modules/10-basics/45-testing/es/EXERCISE.md create mode 100644 modules/10-basics/45-testing/es/README.md create mode 100644 modules/10-basics/45-testing/es/data.yml create mode 100644 modules/10-basics/45-testing/ru/EXERCISE.md create mode 100644 modules/10-basics/45-testing/ru/README.md create mode 100644 modules/10-basics/45-testing/ru/data.yml create mode 100644 modules/10-basics/50-syntax-errors/en/EXERCISE.md create mode 100644 modules/10-basics/50-syntax-errors/en/README.md create mode 100644 modules/10-basics/50-syntax-errors/en/data.yml create mode 100644 modules/10-basics/50-syntax-errors/es/EXERCISE.md create mode 100644 modules/10-basics/50-syntax-errors/es/README.md create mode 100644 modules/10-basics/50-syntax-errors/es/data.yml create mode 100644 modules/10-basics/50-syntax-errors/ru/EXERCISE.md create mode 100644 modules/10-basics/50-syntax-errors/ru/README.md create mode 100644 modules/10-basics/50-syntax-errors/ru/data.yml create mode 100644 modules/20-arithmetics/20-basic/en/EXERCISE.md create mode 100644 modules/20-arithmetics/20-basic/en/README.md create mode 100644 modules/20-arithmetics/20-basic/en/data.yml create mode 100644 modules/20-arithmetics/20-basic/es/EXERCISE.md create mode 100644 modules/20-arithmetics/20-basic/es/README.md create mode 100644 modules/20-arithmetics/20-basic/es/data.yml create mode 100644 modules/20-arithmetics/20-basic/ru/EXERCISE.md create mode 100644 modules/20-arithmetics/20-basic/ru/README.md create mode 100644 modules/20-arithmetics/20-basic/ru/data.yml create mode 100644 modules/20-arithmetics/25-operator/en/EXERCISE.md create mode 100644 modules/20-arithmetics/25-operator/en/README.md create mode 100644 modules/20-arithmetics/25-operator/en/data.yml create mode 100644 modules/20-arithmetics/25-operator/es/EXERCISE.md create mode 100644 modules/20-arithmetics/25-operator/es/README.md create mode 100644 modules/20-arithmetics/25-operator/es/data.yml create mode 100644 modules/20-arithmetics/25-operator/ru/EXERCISE.md create mode 100644 modules/20-arithmetics/25-operator/ru/README.md create mode 100644 modules/20-arithmetics/25-operator/ru/data.yml create mode 100644 modules/20-arithmetics/27-commutativity/en/EXERCISE.md create mode 100644 modules/20-arithmetics/27-commutativity/en/README.md create mode 100644 modules/20-arithmetics/27-commutativity/en/data.yml create mode 100644 modules/20-arithmetics/27-commutativity/es/EXERCISE.md create mode 100644 modules/20-arithmetics/27-commutativity/es/README.md create mode 100644 modules/20-arithmetics/27-commutativity/es/data.yml create mode 100644 modules/20-arithmetics/27-commutativity/ru/EXERCISE.md create mode 100644 modules/20-arithmetics/27-commutativity/ru/README.md create mode 100644 modules/20-arithmetics/27-commutativity/ru/data.yml create mode 100644 modules/20-arithmetics/30-composition/en/EXERCISE.md create mode 100644 modules/20-arithmetics/30-composition/en/README.md create mode 100644 modules/20-arithmetics/30-composition/en/data.yml create mode 100644 modules/20-arithmetics/30-composition/es/EXERCISE.md create mode 100644 modules/20-arithmetics/30-composition/es/README.md create mode 100644 modules/20-arithmetics/30-composition/es/data.yml create mode 100644 modules/20-arithmetics/30-composition/ru/EXERCISE.md create mode 100644 modules/20-arithmetics/30-composition/ru/README.md create mode 100644 modules/20-arithmetics/30-composition/ru/data.yml create mode 100644 modules/20-arithmetics/40-priority/en/EXERCISE.md create mode 100644 modules/20-arithmetics/40-priority/en/README.md create mode 100644 modules/20-arithmetics/40-priority/en/data.yml create mode 100644 modules/20-arithmetics/40-priority/es/EXERCISE.md create mode 100644 modules/20-arithmetics/40-priority/es/README.md create mode 100644 modules/20-arithmetics/40-priority/es/data.yml create mode 100644 modules/20-arithmetics/40-priority/ru/EXERCISE.md create mode 100644 modules/20-arithmetics/40-priority/ru/README.md create mode 100644 modules/20-arithmetics/40-priority/ru/data.yml create mode 100644 modules/20-arithmetics/45-linting/en/EXERCISE.md create mode 100644 modules/20-arithmetics/45-linting/en/README.md create mode 100644 modules/20-arithmetics/45-linting/en/data.yml create mode 100644 modules/20-arithmetics/45-linting/es/EXERCISE.md create mode 100644 modules/20-arithmetics/45-linting/es/README.md create mode 100644 modules/20-arithmetics/45-linting/es/data.yml create mode 100644 modules/20-arithmetics/45-linting/ru/EXERCISE.md create mode 100644 modules/20-arithmetics/45-linting/ru/README.md create mode 100644 modules/20-arithmetics/45-linting/ru/data.yml create mode 100644 modules/25-strings/10-quotes/en/EXERCISE.md create mode 100644 modules/25-strings/10-quotes/en/README.md create mode 100644 modules/25-strings/10-quotes/en/data.yml create mode 100644 modules/25-strings/10-quotes/es/EXERCISE.md create mode 100644 modules/25-strings/10-quotes/es/README.md create mode 100644 modules/25-strings/10-quotes/es/data.yml create mode 100644 modules/25-strings/10-quotes/ru/EXERCISE.md create mode 100644 modules/25-strings/10-quotes/ru/README.md create mode 100644 modules/25-strings/10-quotes/ru/data.yml create mode 100644 modules/25-strings/15-escape-characters/en/EXERCISE.md create mode 100644 modules/25-strings/15-escape-characters/en/README.md create mode 100644 modules/25-strings/15-escape-characters/en/data.yml create mode 100644 modules/25-strings/15-escape-characters/es/EXERCISE.md create mode 100644 modules/25-strings/15-escape-characters/es/README.md create mode 100644 modules/25-strings/15-escape-characters/es/data.yml create mode 100644 modules/25-strings/15-escape-characters/ru/EXERCISE.md create mode 100644 modules/25-strings/15-escape-characters/ru/README.md create mode 100644 modules/25-strings/15-escape-characters/ru/data.yml create mode 100644 modules/25-strings/20-strings-concatenation/en/EXERCISE.md create mode 100644 modules/25-strings/20-strings-concatenation/en/README.md create mode 100644 modules/25-strings/20-strings-concatenation/en/data.yml create mode 100644 modules/25-strings/20-strings-concatenation/es/EXERCISE.md create mode 100644 modules/25-strings/20-strings-concatenation/es/README.md create mode 100644 modules/25-strings/20-strings-concatenation/es/data.yml create mode 100644 modules/25-strings/20-strings-concatenation/ru/EXERCISE.md create mode 100644 modules/25-strings/20-strings-concatenation/ru/README.md create mode 100644 modules/25-strings/20-strings-concatenation/ru/data.yml create mode 100644 modules/25-strings/30-encoding/en/EXERCISE.md create mode 100644 modules/25-strings/30-encoding/en/README.md create mode 100644 modules/25-strings/30-encoding/en/data.yml create mode 100644 modules/25-strings/30-encoding/es/EXERCISE.md create mode 100644 modules/25-strings/30-encoding/es/README.md create mode 100644 modules/25-strings/30-encoding/es/data.yml create mode 100644 modules/25-strings/30-encoding/ru/EXERCISE.md create mode 100644 modules/25-strings/30-encoding/ru/README.md create mode 100644 modules/25-strings/30-encoding/ru/data.yml create mode 100644 modules/27-data-types/40-primitive-data-types/en/EXERCISE.md create mode 100644 modules/27-data-types/40-primitive-data-types/en/README.md create mode 100644 modules/27-data-types/40-primitive-data-types/en/data.yml create mode 100644 modules/27-data-types/40-primitive-data-types/es/EXERCISE.md create mode 100644 modules/27-data-types/40-primitive-data-types/es/README.md create mode 100644 modules/27-data-types/40-primitive-data-types/es/data.yml create mode 100644 modules/27-data-types/40-primitive-data-types/ru/EXERCISE.md create mode 100644 modules/27-data-types/40-primitive-data-types/ru/README.md create mode 100644 modules/27-data-types/40-primitive-data-types/ru/data.yml create mode 100644 modules/27-data-types/50-data-types-weak-typing/en/EXERCISE.md create mode 100644 modules/27-data-types/50-data-types-weak-typing/en/README.md create mode 100644 modules/27-data-types/50-data-types-weak-typing/en/data.yml create mode 100644 modules/27-data-types/50-data-types-weak-typing/es/EXERCISE.md create mode 100644 modules/27-data-types/50-data-types-weak-typing/es/README.md create mode 100644 modules/27-data-types/50-data-types-weak-typing/es/data.yml create mode 100644 modules/27-data-types/50-data-types-weak-typing/ru/EXERCISE.md create mode 100644 modules/27-data-types/50-data-types-weak-typing/ru/README.md create mode 100644 modules/27-data-types/50-data-types-weak-typing/ru/data.yml create mode 100644 modules/27-data-types/55-type-conversion/en/EXERCISE.md create mode 100644 modules/27-data-types/55-type-conversion/en/README.md create mode 100644 modules/27-data-types/55-type-conversion/en/data.yml create mode 100644 modules/27-data-types/55-type-conversion/es/EXERCISE.md create mode 100644 modules/27-data-types/55-type-conversion/es/README.md create mode 100644 modules/27-data-types/55-type-conversion/es/data.yml create mode 100644 modules/27-data-types/55-type-conversion/ru/EXERCISE.md create mode 100644 modules/27-data-types/55-type-conversion/ru/README.md create mode 100644 modules/27-data-types/55-type-conversion/ru/data.yml create mode 100644 modules/30-variables/10-definition/en/EXERCISE.md create mode 100644 modules/30-variables/10-definition/en/README.md create mode 100644 modules/30-variables/10-definition/en/data.yml create mode 100644 modules/30-variables/10-definition/es/EXERCISE.md create mode 100644 modules/30-variables/10-definition/es/README.md create mode 100644 modules/30-variables/10-definition/es/data.yml create mode 100644 modules/30-variables/10-definition/ru/EXERCISE.md create mode 100644 modules/30-variables/10-definition/ru/README.md create mode 100644 modules/30-variables/10-definition/ru/data.yml create mode 100644 modules/30-variables/12-change/en/EXERCISE.md create mode 100644 modules/30-variables/12-change/en/README.md create mode 100644 modules/30-variables/12-change/en/data.yml create mode 100644 modules/30-variables/12-change/es/EXERCISE.md create mode 100644 modules/30-variables/12-change/es/README.md create mode 100644 modules/30-variables/12-change/es/data.yml create mode 100644 modules/30-variables/12-change/ru/EXERCISE.md create mode 100644 modules/30-variables/12-change/ru/README.md create mode 100644 modules/30-variables/12-change/ru/data.yml create mode 100644 modules/30-variables/13-variables-naming/en/EXERCISE.md create mode 100644 modules/30-variables/13-variables-naming/en/README.md create mode 100644 modules/30-variables/13-variables-naming/en/data.yml create mode 100644 modules/30-variables/13-variables-naming/es/EXERCISE.md create mode 100644 modules/30-variables/13-variables-naming/es/README.md create mode 100644 modules/30-variables/13-variables-naming/es/data.yml create mode 100644 modules/30-variables/13-variables-naming/ru/EXERCISE.md create mode 100644 modules/30-variables/13-variables-naming/ru/README.md create mode 100644 modules/30-variables/13-variables-naming/ru/data.yml create mode 100644 modules/30-variables/14-errors/en/EXERCISE.md create mode 100644 modules/30-variables/14-errors/en/README.md create mode 100644 modules/30-variables/14-errors/en/data.yml create mode 100644 modules/30-variables/14-errors/es/EXERCISE.md create mode 100644 modules/30-variables/14-errors/es/README.md create mode 100644 modules/30-variables/14-errors/es/data.yml create mode 100644 modules/30-variables/14-errors/ru/EXERCISE.md create mode 100644 modules/30-variables/14-errors/ru/README.md create mode 100644 modules/30-variables/14-errors/ru/data.yml create mode 100644 modules/30-variables/15-expressions/en/EXERCISE.md create mode 100644 modules/30-variables/15-expressions/en/README.md create mode 100644 modules/30-variables/15-expressions/en/data.yml create mode 100644 modules/30-variables/15-expressions/es/EXERCISE.md create mode 100644 modules/30-variables/15-expressions/es/README.md create mode 100644 modules/30-variables/15-expressions/es/data.yml create mode 100644 modules/30-variables/15-expressions/ru/EXERCISE.md create mode 100644 modules/30-variables/15-expressions/ru/README.md create mode 100644 modules/30-variables/15-expressions/ru/data.yml create mode 100644 modules/30-variables/18-concatenation/en/EXERCISE.md create mode 100644 modules/30-variables/18-concatenation/en/README.md create mode 100644 modules/30-variables/18-concatenation/en/data.yml create mode 100644 modules/30-variables/18-concatenation/es/EXERCISE.md create mode 100644 modules/30-variables/18-concatenation/es/README.md create mode 100644 modules/30-variables/18-concatenation/es/data.yml create mode 100644 modules/30-variables/18-concatenation/ru/EXERCISE.md create mode 100644 modules/30-variables/18-concatenation/ru/README.md create mode 100644 modules/30-variables/18-concatenation/ru/data.yml create mode 100644 modules/30-variables/19-naming-style/en/EXERCISE.md create mode 100644 modules/30-variables/19-naming-style/en/README.md create mode 100644 modules/30-variables/19-naming-style/en/data.yml create mode 100644 modules/30-variables/19-naming-style/es/EXERCISE.md create mode 100644 modules/30-variables/19-naming-style/es/README.md create mode 100644 modules/30-variables/19-naming-style/es/data.yml create mode 100644 modules/30-variables/19-naming-style/ru/EXERCISE.md create mode 100644 modules/30-variables/19-naming-style/ru/README.md create mode 100644 modules/30-variables/19-naming-style/ru/data.yml create mode 100644 modules/30-variables/20-magic-numbers/en/EXERCISE.md create mode 100644 modules/30-variables/20-magic-numbers/en/README.md create mode 100644 modules/30-variables/20-magic-numbers/en/data.yml create mode 100644 modules/30-variables/20-magic-numbers/es/EXERCISE.md create mode 100644 modules/30-variables/20-magic-numbers/es/README.md create mode 100644 modules/30-variables/20-magic-numbers/es/data.yml create mode 100644 modules/30-variables/20-magic-numbers/ru/EXERCISE.md create mode 100644 modules/30-variables/20-magic-numbers/ru/README.md create mode 100644 modules/30-variables/20-magic-numbers/ru/data.yml create mode 100644 modules/30-variables/23-constants/en/EXERCISE.md create mode 100644 modules/30-variables/23-constants/en/README.md create mode 100644 modules/30-variables/23-constants/en/data.yml create mode 100644 modules/30-variables/23-constants/es/EXERCISE.md create mode 100644 modules/30-variables/23-constants/es/README.md create mode 100644 modules/30-variables/23-constants/es/data.yml create mode 100644 modules/30-variables/23-constants/ru/EXERCISE.md create mode 100644 modules/30-variables/23-constants/ru/README.md create mode 100644 modules/30-variables/23-constants/ru/data.yml create mode 100644 modules/30-variables/24-magic-constants/en/EXERCISE.md create mode 100644 modules/30-variables/24-magic-constants/en/README.md create mode 100644 modules/30-variables/24-magic-constants/en/data.yml create mode 100644 modules/30-variables/24-magic-constants/es/EXERCISE.md create mode 100644 modules/30-variables/24-magic-constants/es/README.md create mode 100644 modules/30-variables/24-magic-constants/es/data.yml create mode 100644 modules/30-variables/24-magic-constants/ru/EXERCISE.md create mode 100644 modules/30-variables/24-magic-constants/ru/README.md create mode 100644 modules/30-variables/24-magic-constants/ru/data.yml create mode 100644 modules/30-variables/25-interpolation/en/EXERCISE.md create mode 100644 modules/30-variables/25-interpolation/en/README.md create mode 100644 modules/30-variables/25-interpolation/en/data.yml create mode 100644 modules/30-variables/25-interpolation/es/EXERCISE.md create mode 100644 modules/30-variables/25-interpolation/es/README.md create mode 100644 modules/30-variables/25-interpolation/es/data.yml create mode 100644 modules/30-variables/25-interpolation/ru/EXERCISE.md create mode 100644 modules/30-variables/25-interpolation/ru/README.md create mode 100644 modules/30-variables/25-interpolation/ru/data.yml create mode 100644 modules/30-variables/30-symbols/en/EXERCISE.md create mode 100644 modules/30-variables/30-symbols/en/README.md create mode 100644 modules/30-variables/30-symbols/en/data.yml create mode 100644 modules/30-variables/30-symbols/es/EXERCISE.md create mode 100644 modules/30-variables/30-symbols/es/README.md create mode 100644 modules/30-variables/30-symbols/es/data.yml create mode 100644 modules/30-variables/30-symbols/ru/EXERCISE.md create mode 100644 modules/30-variables/30-symbols/ru/README.md create mode 100644 modules/30-variables/30-symbols/ru/data.yml create mode 100644 modules/30-variables/35-heredoc/en/EXERCISE.md create mode 100644 modules/30-variables/35-heredoc/en/README.md create mode 100644 modules/30-variables/35-heredoc/en/data.yml create mode 100644 modules/30-variables/35-heredoc/es/EXERCISE.md create mode 100644 modules/30-variables/35-heredoc/es/README.md create mode 100644 modules/30-variables/35-heredoc/es/data.yml create mode 100644 modules/30-variables/35-heredoc/ru/EXERCISE.md create mode 100644 modules/30-variables/35-heredoc/ru/README.md create mode 100644 modules/30-variables/35-heredoc/ru/data.yml create mode 100644 modules/35-calling-functions/100-call/en/EXERCISE.md create mode 100644 modules/35-calling-functions/100-call/en/README.md create mode 100644 modules/35-calling-functions/100-call/en/data.yml create mode 100644 modules/35-calling-functions/100-call/es/EXERCISE.md create mode 100644 modules/35-calling-functions/100-call/es/README.md create mode 100644 modules/35-calling-functions/100-call/es/data.yml create mode 100644 modules/35-calling-functions/100-call/ru/EXERCISE.md create mode 100644 modules/35-calling-functions/100-call/ru/README.md create mode 100644 modules/35-calling-functions/100-call/ru/data.yml create mode 100644 modules/35-calling-functions/120-function-signature/en/EXERCISE.md create mode 100644 modules/35-calling-functions/120-function-signature/en/README.md create mode 100644 modules/35-calling-functions/120-function-signature/en/data.yml create mode 100644 modules/35-calling-functions/120-function-signature/es/EXERCISE.md create mode 100644 modules/35-calling-functions/120-function-signature/es/README.md create mode 100644 modules/35-calling-functions/120-function-signature/es/data.yml create mode 100644 modules/35-calling-functions/120-function-signature/ru/EXERCISE.md create mode 100644 modules/35-calling-functions/120-function-signature/ru/README.md create mode 100644 modules/35-calling-functions/120-function-signature/ru/data.yml create mode 100644 modules/35-calling-functions/135-calling-functions-default-arguments/en/EXERCISE.md create mode 100644 modules/35-calling-functions/135-calling-functions-default-arguments/en/README.md create mode 100644 modules/35-calling-functions/135-calling-functions-default-arguments/en/data.yml create mode 100644 modules/35-calling-functions/135-calling-functions-default-arguments/es/EXERCISE.md create mode 100644 modules/35-calling-functions/135-calling-functions-default-arguments/es/README.md create mode 100644 modules/35-calling-functions/135-calling-functions-default-arguments/es/data.yml create mode 100644 modules/35-calling-functions/135-calling-functions-default-arguments/ru/EXERCISE.md create mode 100644 modules/35-calling-functions/135-calling-functions-default-arguments/ru/README.md create mode 100644 modules/35-calling-functions/135-calling-functions-default-arguments/ru/data.yml create mode 100644 modules/35-calling-functions/150-calling-functions-expression/en/EXERCISE.md create mode 100644 modules/35-calling-functions/150-calling-functions-expression/en/README.md create mode 100644 modules/35-calling-functions/150-calling-functions-expression/en/data.yml create mode 100644 modules/35-calling-functions/150-calling-functions-expression/es/EXERCISE.md create mode 100644 modules/35-calling-functions/150-calling-functions-expression/es/README.md create mode 100644 modules/35-calling-functions/150-calling-functions-expression/es/data.yml create mode 100644 modules/35-calling-functions/150-calling-functions-expression/ru/EXERCISE.md create mode 100644 modules/35-calling-functions/150-calling-functions-expression/ru/README.md create mode 100644 modules/35-calling-functions/150-calling-functions-expression/ru/data.yml create mode 100644 modules/35-calling-functions/180-variadic-arguments/en/EXERCISE.md create mode 100644 modules/35-calling-functions/180-variadic-arguments/en/README.md create mode 100644 modules/35-calling-functions/180-variadic-arguments/en/data.yml create mode 100644 modules/35-calling-functions/180-variadic-arguments/es/EXERCISE.md create mode 100644 modules/35-calling-functions/180-variadic-arguments/es/README.md create mode 100644 modules/35-calling-functions/180-variadic-arguments/es/data.yml create mode 100644 modules/35-calling-functions/180-variadic-arguments/ru/EXERCISE.md create mode 100644 modules/35-calling-functions/180-variadic-arguments/ru/README.md create mode 100644 modules/35-calling-functions/180-variadic-arguments/ru/data.yml create mode 100644 modules/35-calling-functions/270-deterministic/en/EXERCISE.md create mode 100644 modules/35-calling-functions/270-deterministic/en/README.md create mode 100644 modules/35-calling-functions/270-deterministic/en/data.yml create mode 100644 modules/35-calling-functions/270-deterministic/es/EXERCISE.md create mode 100644 modules/35-calling-functions/270-deterministic/es/README.md create mode 100644 modules/35-calling-functions/270-deterministic/es/data.yml create mode 100644 modules/35-calling-functions/270-deterministic/ru/EXERCISE.md create mode 100644 modules/35-calling-functions/270-deterministic/ru/README.md create mode 100644 modules/35-calling-functions/270-deterministic/ru/data.yml create mode 100644 modules/35-calling-functions/900-stdlib/en/EXERCISE.md create mode 100644 modules/35-calling-functions/900-stdlib/en/README.md create mode 100644 modules/35-calling-functions/900-stdlib/en/data.yml create mode 100644 modules/35-calling-functions/900-stdlib/es/EXERCISE.md create mode 100644 modules/35-calling-functions/900-stdlib/es/README.md create mode 100644 modules/35-calling-functions/900-stdlib/es/data.yml create mode 100644 modules/35-calling-functions/900-stdlib/ru/EXERCISE.md create mode 100644 modules/35-calling-functions/900-stdlib/ru/README.md create mode 100644 modules/35-calling-functions/900-stdlib/ru/data.yml create mode 100644 modules/40-define-functions/100-define/en/EXERCISE.md create mode 100644 modules/40-define-functions/100-define/en/README.md create mode 100644 modules/40-define-functions/100-define/en/data.yml create mode 100644 modules/40-define-functions/100-define/es/EXERCISE.md create mode 100644 modules/40-define-functions/100-define/es/README.md create mode 100644 modules/40-define-functions/100-define/es/data.yml create mode 100644 modules/40-define-functions/100-define/ru/EXERCISE.md create mode 100644 modules/40-define-functions/100-define/ru/README.md create mode 100644 modules/40-define-functions/100-define/ru/data.yml create mode 100644 modules/40-define-functions/200-return/en/EXERCISE.md create mode 100644 modules/40-define-functions/200-return/en/README.md create mode 100644 modules/40-define-functions/200-return/en/data.yml create mode 100644 modules/40-define-functions/200-return/es/EXERCISE.md create mode 100644 modules/40-define-functions/200-return/es/README.md create mode 100644 modules/40-define-functions/200-return/es/data.yml create mode 100644 modules/40-define-functions/200-return/ru/EXERCISE.md create mode 100644 modules/40-define-functions/200-return/ru/README.md create mode 100644 modules/40-define-functions/200-return/ru/data.yml create mode 100644 modules/40-define-functions/300-parameters/en/EXERCISE.md create mode 100644 modules/40-define-functions/300-parameters/en/README.md create mode 100644 modules/40-define-functions/300-parameters/en/data.yml create mode 100644 modules/40-define-functions/300-parameters/es/EXERCISE.md create mode 100644 modules/40-define-functions/300-parameters/es/README.md create mode 100644 modules/40-define-functions/300-parameters/es/data.yml create mode 100644 modules/40-define-functions/300-parameters/ru/EXERCISE.md create mode 100644 modules/40-define-functions/300-parameters/ru/README.md create mode 100644 modules/40-define-functions/300-parameters/ru/data.yml create mode 100644 modules/40-define-functions/340-default-parameters/en/EXERCISE.md create mode 100644 modules/40-define-functions/340-default-parameters/en/README.md create mode 100644 modules/40-define-functions/340-default-parameters/en/data.yml create mode 100644 modules/40-define-functions/340-default-parameters/es/EXERCISE.md create mode 100644 modules/40-define-functions/340-default-parameters/es/README.md create mode 100644 modules/40-define-functions/340-default-parameters/es/data.yml create mode 100644 modules/40-define-functions/340-default-parameters/ru/EXERCISE.md create mode 100644 modules/40-define-functions/340-default-parameters/ru/README.md create mode 100644 modules/40-define-functions/340-default-parameters/ru/data.yml create mode 100644 modules/40-define-functions/500-reading-documentation/en/EXERCISE.md create mode 100644 modules/40-define-functions/500-reading-documentation/en/README.md create mode 100644 modules/40-define-functions/500-reading-documentation/en/data.yml create mode 100644 modules/40-define-functions/500-reading-documentation/es/EXERCISE.md create mode 100644 modules/40-define-functions/500-reading-documentation/es/README.md create mode 100644 modules/40-define-functions/500-reading-documentation/es/data.yml create mode 100644 modules/40-define-functions/500-reading-documentation/ru/EXERCISE.md create mode 100644 modules/40-define-functions/500-reading-documentation/ru/README.md create mode 100644 modules/40-define-functions/500-reading-documentation/ru/data.yml create mode 100644 modules/45-logic/10-bool-type/en/EXERCISE.md create mode 100644 modules/45-logic/10-bool-type/en/README.md create mode 100644 modules/45-logic/10-bool-type/en/data.yml create mode 100644 modules/45-logic/10-bool-type/es/EXERCISE.md create mode 100644 modules/45-logic/10-bool-type/es/README.md create mode 100644 modules/45-logic/10-bool-type/es/data.yml create mode 100644 modules/45-logic/10-bool-type/ru/EXERCISE.md create mode 100644 modules/45-logic/10-bool-type/ru/README.md create mode 100644 modules/45-logic/10-bool-type/ru/data.yml create mode 100644 modules/45-logic/15-predicates/en/EXERCISE.md create mode 100644 modules/45-logic/15-predicates/en/README.md create mode 100644 modules/45-logic/15-predicates/en/data.yml create mode 100644 modules/45-logic/15-predicates/es/EXERCISE.md create mode 100644 modules/45-logic/15-predicates/es/README.md create mode 100644 modules/45-logic/15-predicates/es/data.yml create mode 100644 modules/45-logic/15-predicates/ru/EXERCISE.md create mode 100644 modules/45-logic/15-predicates/ru/README.md create mode 100644 modules/45-logic/15-predicates/ru/data.yml create mode 100644 modules/45-logic/20-logic-combine-expressions/en/EXERCISE.md create mode 100644 modules/45-logic/20-logic-combine-expressions/en/README.md create mode 100644 modules/45-logic/20-logic-combine-expressions/en/data.yml create mode 100644 modules/45-logic/20-logic-combine-expressions/es/EXERCISE.md create mode 100644 modules/45-logic/20-logic-combine-expressions/es/README.md create mode 100644 modules/45-logic/20-logic-combine-expressions/es/data.yml create mode 100644 modules/45-logic/20-logic-combine-expressions/ru/EXERCISE.md create mode 100644 modules/45-logic/20-logic-combine-expressions/ru/README.md create mode 100644 modules/45-logic/20-logic-combine-expressions/ru/data.yml create mode 100644 modules/45-logic/25-logical-operators/en/EXERCISE.md create mode 100644 modules/45-logic/25-logical-operators/en/README.md create mode 100644 modules/45-logic/25-logical-operators/en/data.yml create mode 100644 modules/45-logic/25-logical-operators/es/EXERCISE.md create mode 100644 modules/45-logic/25-logical-operators/es/README.md create mode 100644 modules/45-logic/25-logical-operators/es/data.yml create mode 100644 modules/45-logic/25-logical-operators/ru/EXERCISE.md create mode 100644 modules/45-logic/25-logical-operators/ru/README.md create mode 100644 modules/45-logic/25-logical-operators/ru/data.yml create mode 100644 modules/45-logic/28-logical-negation/en/EXERCISE.md create mode 100644 modules/45-logic/28-logical-negation/en/README.md create mode 100644 modules/45-logic/28-logical-negation/en/data.yml create mode 100644 modules/45-logic/28-logical-negation/es/EXERCISE.md create mode 100644 modules/45-logic/28-logical-negation/es/README.md create mode 100644 modules/45-logic/28-logical-negation/es/data.yml create mode 100644 modules/45-logic/28-logical-negation/ru/EXERCISE.md create mode 100644 modules/45-logic/28-logical-negation/ru/README.md create mode 100644 modules/45-logic/28-logical-negation/ru/data.yml create mode 100644 modules/45-logic/29-logical-operators-2/en/EXERCISE.md create mode 100644 modules/45-logic/29-logical-operators-2/en/README.md create mode 100644 modules/45-logic/29-logical-operators-2/en/data.yml create mode 100644 modules/45-logic/29-logical-operators-2/es/EXERCISE.md create mode 100644 modules/45-logic/29-logical-operators-2/es/README.md create mode 100644 modules/45-logic/29-logical-operators-2/es/data.yml create mode 100644 modules/45-logic/29-logical-operators-2/ru/EXERCISE.md create mode 100644 modules/45-logic/29-logical-operators-2/ru/README.md create mode 100644 modules/45-logic/29-logical-operators-2/ru/data.yml create mode 100644 modules/45-logic/70-logic-weak-typing/en/EXERCISE.md create mode 100644 modules/45-logic/70-logic-weak-typing/en/README.md create mode 100644 modules/45-logic/70-logic-weak-typing/en/data.yml create mode 100644 modules/45-logic/70-logic-weak-typing/es/EXERCISE.md create mode 100644 modules/45-logic/70-logic-weak-typing/es/README.md create mode 100644 modules/45-logic/70-logic-weak-typing/es/data.yml create mode 100644 modules/45-logic/70-logic-weak-typing/ru/EXERCISE.md create mode 100644 modules/45-logic/70-logic-weak-typing/ru/README.md create mode 100644 modules/45-logic/70-logic-weak-typing/ru/data.yml create mode 100644 modules/48-conditionals/30-if/en/EXERCISE.md create mode 100644 modules/48-conditionals/30-if/en/README.md create mode 100644 modules/48-conditionals/30-if/en/data.yml create mode 100644 modules/48-conditionals/30-if/es/EXERCISE.md create mode 100644 modules/48-conditionals/30-if/es/README.md create mode 100644 modules/48-conditionals/30-if/es/data.yml create mode 100644 modules/48-conditionals/30-if/ru/EXERCISE.md create mode 100644 modules/48-conditionals/30-if/ru/README.md create mode 100644 modules/48-conditionals/30-if/ru/data.yml create mode 100644 modules/48-conditionals/40-if-else/en/EXERCISE.md create mode 100644 modules/48-conditionals/40-if-else/en/README.md create mode 100644 modules/48-conditionals/40-if-else/en/data.yml create mode 100644 modules/48-conditionals/40-if-else/es/EXERCISE.md create mode 100644 modules/48-conditionals/40-if-else/es/README.md create mode 100644 modules/48-conditionals/40-if-else/es/data.yml create mode 100644 modules/48-conditionals/40-if-else/ru/EXERCISE.md create mode 100644 modules/48-conditionals/40-if-else/ru/README.md create mode 100644 modules/48-conditionals/40-if-else/ru/data.yml create mode 100644 modules/48-conditionals/50-else-if/en/EXERCISE.md create mode 100644 modules/48-conditionals/50-else-if/en/README.md create mode 100644 modules/48-conditionals/50-else-if/en/data.yml create mode 100644 modules/48-conditionals/50-else-if/es/EXERCISE.md create mode 100644 modules/48-conditionals/50-else-if/es/README.md create mode 100644 modules/48-conditionals/50-else-if/es/data.yml create mode 100644 modules/48-conditionals/50-else-if/ru/EXERCISE.md create mode 100644 modules/48-conditionals/50-else-if/ru/README.md create mode 100644 modules/48-conditionals/50-else-if/ru/data.yml create mode 100644 modules/48-conditionals/60-ternary-operator/en/EXERCISE.md create mode 100644 modules/48-conditionals/60-ternary-operator/en/README.md create mode 100644 modules/48-conditionals/60-ternary-operator/en/data.yml create mode 100644 modules/48-conditionals/60-ternary-operator/es/EXERCISE.md create mode 100644 modules/48-conditionals/60-ternary-operator/es/README.md create mode 100644 modules/48-conditionals/60-ternary-operator/es/data.yml create mode 100644 modules/48-conditionals/60-ternary-operator/ru/EXERCISE.md create mode 100644 modules/48-conditionals/60-ternary-operator/ru/README.md create mode 100644 modules/48-conditionals/60-ternary-operator/ru/data.yml create mode 100644 modules/48-conditionals/65-switch/en/EXERCISE.md create mode 100644 modules/48-conditionals/65-switch/en/README.md create mode 100644 modules/48-conditionals/65-switch/en/data.yml create mode 100644 modules/48-conditionals/65-switch/es/EXERCISE.md create mode 100644 modules/48-conditionals/65-switch/es/README.md create mode 100644 modules/48-conditionals/65-switch/es/data.yml create mode 100644 modules/48-conditionals/65-switch/ru/EXERCISE.md create mode 100644 modules/48-conditionals/65-switch/ru/README.md create mode 100644 modules/48-conditionals/65-switch/ru/data.yml create mode 100644 modules/48-conditionals/75-elvis/en/EXERCISE.md create mode 100644 modules/48-conditionals/75-elvis/en/README.md create mode 100644 modules/48-conditionals/75-elvis/en/data.yml create mode 100644 modules/48-conditionals/75-elvis/es/EXERCISE.md create mode 100644 modules/48-conditionals/75-elvis/es/README.md create mode 100644 modules/48-conditionals/75-elvis/es/data.yml create mode 100644 modules/48-conditionals/75-elvis/ru/EXERCISE.md create mode 100644 modules/48-conditionals/75-elvis/ru/README.md create mode 100644 modules/48-conditionals/75-elvis/ru/data.yml create mode 100644 modules/50-loops/10-while/en/EXERCISE.md create mode 100644 modules/50-loops/10-while/en/README.md create mode 100644 modules/50-loops/10-while/en/data.yml create mode 100644 modules/50-loops/10-while/es/EXERCISE.md create mode 100644 modules/50-loops/10-while/es/README.md create mode 100644 modules/50-loops/10-while/es/data.yml create mode 100644 modules/50-loops/10-while/ru/EXERCISE.md create mode 100644 modules/50-loops/10-while/ru/README.md create mode 100644 modules/50-loops/10-while/ru/data.yml create mode 100644 modules/50-loops/20-aggregation-numbers/en/EXERCISE.md create mode 100644 modules/50-loops/20-aggregation-numbers/en/README.md create mode 100644 modules/50-loops/20-aggregation-numbers/en/data.yml create mode 100644 modules/50-loops/20-aggregation-numbers/es/EXERCISE.md create mode 100644 modules/50-loops/20-aggregation-numbers/es/README.md create mode 100644 modules/50-loops/20-aggregation-numbers/es/data.yml create mode 100644 modules/50-loops/20-aggregation-numbers/ru/EXERCISE.md create mode 100644 modules/50-loops/20-aggregation-numbers/ru/README.md create mode 100644 modules/50-loops/20-aggregation-numbers/ru/data.yml create mode 100644 modules/50-loops/23-aggregation-strings/en/EXERCISE.md create mode 100644 modules/50-loops/23-aggregation-strings/en/README.md create mode 100644 modules/50-loops/23-aggregation-strings/en/data.yml create mode 100644 modules/50-loops/23-aggregation-strings/es/EXERCISE.md create mode 100644 modules/50-loops/23-aggregation-strings/es/README.md create mode 100644 modules/50-loops/23-aggregation-strings/es/data.yml create mode 100644 modules/50-loops/23-aggregation-strings/ru/EXERCISE.md create mode 100644 modules/50-loops/23-aggregation-strings/ru/README.md create mode 100644 modules/50-loops/23-aggregation-strings/ru/data.yml create mode 100644 modules/50-loops/25-iteration-over-string/en/EXERCISE.md create mode 100644 modules/50-loops/25-iteration-over-string/en/README.md create mode 100644 modules/50-loops/25-iteration-over-string/en/data.yml create mode 100644 modules/50-loops/25-iteration-over-string/es/EXERCISE.md create mode 100644 modules/50-loops/25-iteration-over-string/es/README.md create mode 100644 modules/50-loops/25-iteration-over-string/es/data.yml create mode 100644 modules/50-loops/25-iteration-over-string/ru/EXERCISE.md create mode 100644 modules/50-loops/25-iteration-over-string/ru/README.md create mode 100644 modules/50-loops/25-iteration-over-string/ru/data.yml create mode 100644 modules/50-loops/26-conditions-inside-loops/en/EXERCISE.md create mode 100644 modules/50-loops/26-conditions-inside-loops/en/README.md create mode 100644 modules/50-loops/26-conditions-inside-loops/en/data.yml create mode 100644 modules/50-loops/26-conditions-inside-loops/es/EXERCISE.md create mode 100644 modules/50-loops/26-conditions-inside-loops/es/README.md create mode 100644 modules/50-loops/26-conditions-inside-loops/es/data.yml create mode 100644 modules/50-loops/26-conditions-inside-loops/ru/EXERCISE.md create mode 100644 modules/50-loops/26-conditions-inside-loops/ru/README.md create mode 100644 modules/50-loops/26-conditions-inside-loops/ru/data.yml create mode 100644 modules/50-loops/28-build-strings/en/EXERCISE.md create mode 100644 modules/50-loops/28-build-strings/en/README.md create mode 100644 modules/50-loops/28-build-strings/en/data.yml create mode 100644 modules/50-loops/28-build-strings/es/EXERCISE.md create mode 100644 modules/50-loops/28-build-strings/es/README.md create mode 100644 modules/50-loops/28-build-strings/es/data.yml create mode 100644 modules/50-loops/28-build-strings/ru/EXERCISE.md create mode 100644 modules/50-loops/28-build-strings/ru/README.md create mode 100644 modules/50-loops/28-build-strings/ru/data.yml create mode 100644 modules/50-loops/29-edge-cases/en/EXERCISE.md create mode 100644 modules/50-loops/29-edge-cases/en/README.md create mode 100644 modules/50-loops/29-edge-cases/en/data.yml create mode 100644 modules/50-loops/29-edge-cases/es/EXERCISE.md create mode 100644 modules/50-loops/29-edge-cases/es/README.md create mode 100644 modules/50-loops/29-edge-cases/es/data.yml create mode 100644 modules/50-loops/29-edge-cases/ru/EXERCISE.md create mode 100644 modules/50-loops/29-edge-cases/ru/README.md create mode 100644 modules/50-loops/29-edge-cases/ru/data.yml create mode 100644 modules/50-loops/30-syntax-sugar/en/EXERCISE.md create mode 100644 modules/50-loops/30-syntax-sugar/en/README.md create mode 100644 modules/50-loops/30-syntax-sugar/en/data.yml create mode 100644 modules/50-loops/30-syntax-sugar/es/EXERCISE.md create mode 100644 modules/50-loops/30-syntax-sugar/es/README.md create mode 100644 modules/50-loops/30-syntax-sugar/es/data.yml create mode 100644 modules/50-loops/30-syntax-sugar/ru/EXERCISE.md create mode 100644 modules/50-loops/30-syntax-sugar/ru/README.md create mode 100644 modules/50-loops/30-syntax-sugar/ru/data.yml create mode 100644 modules/50-loops/50-mutators/en/EXERCISE.md create mode 100644 modules/50-loops/50-mutators/en/README.md create mode 100644 modules/50-loops/50-mutators/en/data.yml create mode 100644 modules/50-loops/50-mutators/es/EXERCISE.md create mode 100644 modules/50-loops/50-mutators/es/README.md create mode 100644 modules/50-loops/50-mutators/es/data.yml create mode 100644 modules/50-loops/50-mutators/ru/EXERCISE.md create mode 100644 modules/50-loops/50-mutators/ru/README.md create mode 100644 modules/50-loops/50-mutators/ru/data.yml create mode 100644 modules/50-loops/55-return-from-loop/en/EXERCISE.md create mode 100644 modules/50-loops/55-return-from-loop/en/README.md create mode 100644 modules/50-loops/55-return-from-loop/en/data.yml create mode 100644 modules/50-loops/55-return-from-loop/es/EXERCISE.md create mode 100644 modules/50-loops/55-return-from-loop/es/README.md create mode 100644 modules/50-loops/55-return-from-loop/es/data.yml create mode 100644 modules/50-loops/55-return-from-loop/ru/EXERCISE.md create mode 100644 modules/50-loops/55-return-from-loop/ru/README.md create mode 100644 modules/50-loops/55-return-from-loop/ru/data.yml create mode 100644 modules/50-loops/70-for/en/EXERCISE.md create mode 100644 modules/50-loops/70-for/en/README.md create mode 100644 modules/50-loops/70-for/en/data.yml create mode 100644 modules/50-loops/70-for/es/EXERCISE.md create mode 100644 modules/50-loops/70-for/es/README.md create mode 100644 modules/50-loops/70-for/es/data.yml create mode 100644 modules/50-loops/70-for/ru/EXERCISE.md create mode 100644 modules/50-loops/70-for/ru/README.md create mode 100644 modules/50-loops/70-for/ru/data.yml create mode 100644 modules/60-deep-into-strings/10-unicode/en/EXERCISE.md create mode 100644 modules/60-deep-into-strings/10-unicode/en/README.md create mode 100644 modules/60-deep-into-strings/10-unicode/en/data.yml create mode 100644 modules/60-deep-into-strings/10-unicode/es/EXERCISE.md create mode 100644 modules/60-deep-into-strings/10-unicode/es/README.md create mode 100644 modules/60-deep-into-strings/10-unicode/es/data.yml create mode 100644 modules/60-deep-into-strings/10-unicode/ru/EXERCISE.md create mode 100644 modules/60-deep-into-strings/10-unicode/ru/README.md create mode 100644 modules/60-deep-into-strings/10-unicode/ru/data.yml create mode 100644 modules/60-deep-into-strings/30-locales/en/EXERCISE.md create mode 100644 modules/60-deep-into-strings/30-locales/en/README.md create mode 100644 modules/60-deep-into-strings/30-locales/en/data.yml create mode 100644 modules/60-deep-into-strings/30-locales/es/EXERCISE.md create mode 100644 modules/60-deep-into-strings/30-locales/es/README.md create mode 100644 modules/60-deep-into-strings/30-locales/es/data.yml create mode 100644 modules/60-deep-into-strings/30-locales/ru/EXERCISE.md create mode 100644 modules/60-deep-into-strings/30-locales/ru/README.md create mode 100644 modules/60-deep-into-strings/30-locales/ru/data.yml create mode 100644 modules/60-deep-into-strings/40-startwith/en/EXERCISE.md create mode 100644 modules/60-deep-into-strings/40-startwith/en/README.md create mode 100644 modules/60-deep-into-strings/40-startwith/en/data.yml create mode 100644 modules/60-deep-into-strings/40-startwith/es/EXERCISE.md create mode 100644 modules/60-deep-into-strings/40-startwith/es/README.md create mode 100644 modules/60-deep-into-strings/40-startwith/es/data.yml create mode 100644 modules/60-deep-into-strings/40-startwith/ru/EXERCISE.md create mode 100644 modules/60-deep-into-strings/40-startwith/ru/README.md create mode 100644 modules/60-deep-into-strings/40-startwith/ru/data.yml create mode 100644 modules/70-dates/10-timestamp/en/EXERCISE.md create mode 100644 modules/70-dates/10-timestamp/en/README.md create mode 100644 modules/70-dates/10-timestamp/en/data.yml create mode 100644 modules/70-dates/10-timestamp/es/EXERCISE.md create mode 100644 modules/70-dates/10-timestamp/es/README.md create mode 100644 modules/70-dates/10-timestamp/es/data.yml create mode 100644 modules/70-dates/10-timestamp/ru/EXERCISE.md create mode 100644 modules/70-dates/10-timestamp/ru/README.md create mode 100644 modules/70-dates/10-timestamp/ru/data.yml create mode 100644 modules/70-dates/20-date/en/EXERCISE.md create mode 100644 modules/70-dates/20-date/en/README.md create mode 100644 modules/70-dates/20-date/en/data.yml create mode 100644 modules/70-dates/20-date/es/EXERCISE.md create mode 100644 modules/70-dates/20-date/es/README.md create mode 100644 modules/70-dates/20-date/es/data.yml create mode 100644 modules/70-dates/20-date/ru/EXERCISE.md create mode 100644 modules/70-dates/20-date/ru/README.md create mode 100644 modules/70-dates/20-date/ru/data.yml create mode 100644 modules/70-dates/30-mktime/en/EXERCISE.md create mode 100644 modules/70-dates/30-mktime/en/README.md create mode 100644 modules/70-dates/30-mktime/en/data.yml create mode 100644 modules/70-dates/30-mktime/es/EXERCISE.md create mode 100644 modules/70-dates/30-mktime/es/README.md create mode 100644 modules/70-dates/30-mktime/es/data.yml create mode 100644 modules/70-dates/30-mktime/ru/EXERCISE.md create mode 100644 modules/70-dates/30-mktime/ru/README.md create mode 100644 modules/70-dates/30-mktime/ru/data.yml create mode 100644 modules/70-dates/40-timezone/en/EXERCISE.md create mode 100644 modules/70-dates/40-timezone/en/README.md create mode 100644 modules/70-dates/40-timezone/en/data.yml create mode 100644 modules/70-dates/40-timezone/es/EXERCISE.md create mode 100644 modules/70-dates/40-timezone/es/README.md create mode 100644 modules/70-dates/40-timezone/es/data.yml create mode 100644 modules/70-dates/40-timezone/ru/EXERCISE.md create mode 100644 modules/70-dates/40-timezone/ru/README.md create mode 100644 modules/70-dates/40-timezone/ru/data.yml diff --git a/modules/10-basics/10-hello-world/en/EXERCISE.md b/modules/10-basics/10-hello-world/en/EXERCISE.md new file mode 100644 index 00000000..d688c2c8 --- /dev/null +++ b/modules/10-basics/10-hello-world/en/EXERCISE.md @@ -0,0 +1,9 @@ +Copy the exact code from the instructions into the editor and run it by clicking «Run». + +```php + +Hello, World! + + +Output to the screen is done with a special command `echo`, followed by a single or double-quoted string to be output. Be sure to put a semicolon at the end. + +```php + Hello, World! +``` + +https://replit.com/@hexlet/php-basics-hello-world-echo + +There are other ways to display a string on the screen. For example, you can use the function (a concept we will get to know later) `print_r()`. In this case, the string is entered in parentheses immediately after the function name. You also need to put `;` at the end. + +```php + ¡Hola, Mundo! +``` + +https://replit.com/@hexlet/php-basics-hello-world-echo + +La salida en la pantalla se realiza utilizando el comando especial `echo`. Después de él, se especifica la cadena a mostrar entre comillas simples. Al final, es importante colocar un punto y coma. + +Para mayor comodidad, mostraremos el resultado de la ejecución del código de esta manera: `=> RESULTADO`. + +### Escribir un programa usando `print_r()` + +Otra forma de mostrar una cadena en la pantalla es utilizando la función `print_r()`: + +```php + ¡Hola, Mundo! +``` + +https://replit.com/@hexlet/php-basics-hello-world-printr + +En este caso, la cadena se especifica entre paréntesis justo después del nombre de la función. Al final, también es necesario colocar un punto y coma. + +En situaciones simples, no hay diferencia entre estas dos construcciones. Puedes usar cualquier método. Sin embargo, cuando necesitas mostrar en la pantalla algo más que números o cadenas, por ejemplo, matrices, `echo` no podrá hacerlo, pero `print_r()` sí. diff --git a/modules/10-basics/10-hello-world/es/data.yml b/modules/10-basics/10-hello-world/es/data.yml new file mode 100644 index 00000000..745da738 --- /dev/null +++ b/modules/10-basics/10-hello-world/es/data.yml @@ -0,0 +1,5 @@ +name: ¡Hola, Mundo! +tips: + - > + [Un poco sobre 'Hello, + World!'](https://codica.la/blog/mi-gente-me-entiende-la-historia-de-la-frase-hello-world-y-sus-analogos) diff --git a/modules/10-basics/10-hello-world/ru/EXERCISE.md b/modules/10-basics/10-hello-world/ru/EXERCISE.md new file mode 100644 index 00000000..419c1c95 --- /dev/null +++ b/modules/10-basics/10-hello-world/ru/EXERCISE.md @@ -0,0 +1,9 @@ +Наберите в редакторе код из задания символ в символ и нажмите «Проверить». + +```php + Hello, World! +``` + +https://replit.com/@hexlet/php-basics-hello-world-echo + +Вывод на экран выполняется с помощью специальной команды `echo`. После нее в одиночных кавычках указывается строка для вывода. В конце обязательно ставим точку с запятой. + +Для удобства мы будем показывать результат запуска строк кода так: `=> РЕЗУЛЬТАТ`. + +### Пишем программу через `print_r()` + +Другой способ вывести строку на экран — функция `print_r()`: + +```php + Hello, World! +``` + +https://replit.com/@hexlet/php-basics-hello-world-printr + +В этом случае строка указывается в скобках сразу после имени функции. В конце также нужно ставить `;`. + +В простых ситуациях между этими конструкциями нет разницы. Можно использовать любой способ. А там, где на экран нужно выводить не просто числа или строки, а, например, массивы, `echo` не сможет этого сделать, а `print_r()` все выведет. diff --git a/modules/10-basics/10-hello-world/ru/data.yml b/modules/10-basics/10-hello-world/ru/data.yml new file mode 100644 index 00000000..1a060c77 --- /dev/null +++ b/modules/10-basics/10-hello-world/ru/data.yml @@ -0,0 +1,5 @@ +name: Привет, Мир! +tips: + - > + [Немного о 'Hello, + World!'](https://ru.hexlet.io/blog/posts/moy-chelovek-menya-ponimaet-istoriya-frazy-hello-world-i-ee-analogov) diff --git a/modules/10-basics/20-tags/en/EXERCISE.md b/modules/10-basics/20-tags/en/EXERCISE.md new file mode 100644 index 00000000..68adf558 --- /dev/null +++ b/modules/10-basics/20-tags/en/EXERCISE.md @@ -0,0 +1,7 @@ +Type the code from the example, and put the `` construct. + +`` is the closing tag. PHP allows you to omit the closing part `?>`. And the PSR-12 code manual doesn't let you include it at all. diff --git a/modules/10-basics/20-tags/en/data.yml b/modules/10-basics/20-tags/en/data.yml new file mode 100644 index 00000000..163e66ae --- /dev/null +++ b/modules/10-basics/20-tags/en/data.yml @@ -0,0 +1,7 @@ +name: Tags +tips: + - '[Basic Code Writing Standard (PSR-1)](https://www.php-fig.org/psr/psr-1/)' + - '[Code Design Guide (PSR-12)](https://www.php-fig.org/psr/psr-12/)' +definitions: + - name: Interpreter + description: a program that executes code written in a programming language. diff --git a/modules/10-basics/20-tags/es/EXERCISE.md b/modules/10-basics/20-tags/es/EXERCISE.md new file mode 100644 index 00000000..054fa8a6 --- /dev/null +++ b/modules/10-basics/20-tags/es/EXERCISE.md @@ -0,0 +1,7 @@ +Escriba el código del ejemplo y coloque la etiqueta ``. Esta es una característica de este lenguaje de programación. + +`` es la etiqueta de cierre. PHP permite no especificar la parte de cierre `?>`. Y la guía de estilo de código PSR-12 prohíbe su especificación. diff --git a/modules/10-basics/20-tags/es/data.yml b/modules/10-basics/20-tags/es/data.yml new file mode 100644 index 00000000..e27d4084 --- /dev/null +++ b/modules/10-basics/20-tags/es/data.yml @@ -0,0 +1,9 @@ +name: Etiquetas +tips: + - '[PSR-1: Estándar básico de codificación](https://www.php-fig.org/psr/psr-1/)' + - >- + [PSR-12: Guía de estilo de + codificación](https://www.php-fig.org/psr/psr-12/) +definitions: + - name: Intérprete + description: programa que ejecuta el código escrito en un lenguaje de programación. diff --git a/modules/10-basics/20-tags/ru/EXERCISE.md b/modules/10-basics/20-tags/ru/EXERCISE.md new file mode 100644 index 00000000..ba04c733 --- /dev/null +++ b/modules/10-basics/20-tags/ru/EXERCISE.md @@ -0,0 +1,7 @@ +Наберите код из примера, поставьте в начале тег ``. Это особенность данного языка программирования. + +`` — закрывающий тег. PHP позволяет не указывать закрывающую часть `?>`. А руководство по оформлению кода PSR-12 запрещает ее указывать. diff --git a/modules/10-basics/20-tags/ru/data.yml b/modules/10-basics/20-tags/ru/data.yml new file mode 100644 index 00000000..8a260a16 --- /dev/null +++ b/modules/10-basics/20-tags/ru/data.yml @@ -0,0 +1,11 @@ +name: Теги +tips: + - >- + [Базовый стандарт написания кода + (PSR-1)](https://www.php-fig.org/psr/psr-1/) + - >- + [Руководство по оформлению кода + (PSR-12)](https://www.php-fig.org/psr/psr-12/) +definitions: + - name: Интерпретатор + description: программа, выполняющая код, написанный на языке программирования. diff --git a/modules/10-basics/30-comments/en/EXERCISE.md b/modules/10-basics/30-comments/en/EXERCISE.md new file mode 100644 index 00000000..cedf3a85 --- /dev/null +++ b/modules/10-basics/30-comments/en/EXERCISE.md @@ -0,0 +1 @@ +Create a one-line comment with the text: `You know nothing, Jon Snow!`. diff --git a/modules/10-basics/30-comments/en/README.md b/modules/10-basics/30-comments/en/README.md new file mode 100644 index 00000000..79c4a859 --- /dev/null +++ b/modules/10-basics/30-comments/en/README.md @@ -0,0 +1,37 @@ + +Almost every programming language allows you to add comments to your code. This is text that isn't part of the program and is needed for programmers to make notes. They help explain how the code works, what errors need to be corrected, or what not to forget to add later. + +Comments in PHP come in two flavors: + +## Single line comments + +_Single line comments start with `//`. Any text can go after these characters, the whole line will be left alone when the program is run. + +A comment can take up a whole line. Or you can create several comments if one line isn't enough: + +```php + + text in program code that doesn't affect functionality, and is added by + programmers for themselves and their colleagues. + + + `// single-line comment` + + + ``` + + /* + + * multiline comment + + * multiline comment + + */ + + ``` diff --git a/modules/10-basics/30-comments/es/EXERCISE.md b/modules/10-basics/30-comments/es/EXERCISE.md new file mode 100644 index 00000000..f58809aa --- /dev/null +++ b/modules/10-basics/30-comments/es/EXERCISE.md @@ -0,0 +1 @@ +Crea un comentario de una línea con el texto: `¡No sabes nada, Jon Snow!`. diff --git a/modules/10-basics/30-comments/es/README.md b/modules/10-basics/30-comments/es/README.md new file mode 100644 index 00000000..4ebd238c --- /dev/null +++ b/modules/10-basics/30-comments/es/README.md @@ -0,0 +1,27 @@ +## ¿Para qué sirven los comentarios? + +Además del código en los archivos de código fuente, puede haber comentarios. Este texto no es parte del programa. Es útil para los programadores como notas. Con ellos se agregan explicaciones, por ejemplo, cómo funciona el código, qué errores corregir o qué agregar más tarde. + +Los comentarios en PHP pueden ser de dos tipos: + +* **Comentarios de una línea** - comienzan con `//`. Después de estos caracteres puede seguir cualquier texto, toda la línea no se analizará ni se ejecutará: + + ```php + + texto en el código del programa que no afecta la funcionalidad y se agrega + por los programadores para ellos mismos y sus colegas. + + + `// comentario de una línea` + + + ``` + + /* + + * comentario de varias líneas + + * comentario de varias líneas + + */ + + ``` diff --git a/modules/10-basics/30-comments/ru/EXERCISE.md b/modules/10-basics/30-comments/ru/EXERCISE.md new file mode 100644 index 00000000..b326c804 --- /dev/null +++ b/modules/10-basics/30-comments/ru/EXERCISE.md @@ -0,0 +1 @@ +Создайте однострочный комментарий с текстом: `You know nothing, Jon Snow!`. diff --git a/modules/10-basics/30-comments/ru/README.md b/modules/10-basics/30-comments/ru/README.md new file mode 100644 index 00000000..05703678 --- /dev/null +++ b/modules/10-basics/30-comments/ru/README.md @@ -0,0 +1,27 @@ +## Зачем нужны комментарии + +Кроме кода в файлах с исходным кодом могут находиться комментарии. Этот текст не является частью программы. Он нужен программистам для пометок. С их помощью добавляют пояснения, например, как работает код, какие ошибки нужно поправить или не забыть что-то позже добавить. + +Комментарии в PHP бывают двух видов: + +* **Однострочные комментарии** — начинаются с `//`. После этих символов может следовать любой текст, вся строка не будет анализироваться и исполняться: + + ```php + + текст в коде программы, который не влияет на функциональность, и + добавляется программистами для себя и своих коллег. + + + `// однострочный комментарий` + + + ``` + + /* + + * многострочный комментарий + + * многострочный комментарий + + */ + + ``` diff --git a/modules/10-basics/40-instructions/en/EXERCISE.md b/modules/10-basics/40-instructions/en/EXERCISE.md new file mode 100644 index 00000000..c642d12e --- /dev/null +++ b/modules/10-basics/40-instructions/en/EXERCISE.md @@ -0,0 +1,7 @@ +Print these three names, one after the other: _Robert_, _Stannis_, _Renly_. As a result, the editor should print: + +
+RobertStannisRenly
+
+ +Use a `print_r()` call for each name. diff --git a/modules/10-basics/40-instructions/en/README.md b/modules/10-basics/40-instructions/en/README.md new file mode 100644 index 00000000..c9a76f6d --- /dev/null +++ b/modules/10-basics/40-instructions/en/README.md @@ -0,0 +1,28 @@ +A statement is a command given to a computer to do something. Code in PHP is a collection of instructions, usually separated from each other by a `;`. + +Here's an example of some code with two statements. + +```php + +Mother of Dragons. Dracarys! + + +Theoretically, the instructions can be written one after the other without moving them to a new line: + +```php + + [A little about + interpreters](https://en.wikipedia.org/wiki/Interpreter_(computing)) +definitions: + - name: The interpreter + description: | + is a program that runs the code in PHP. + - name: An instruction (statement) + description: > + is a command for a computer written in a programming language. PHP code is + a set of instructions separated (most often) by a `;`. diff --git a/modules/10-basics/40-instructions/es/EXERCISE.md b/modules/10-basics/40-instructions/es/EXERCISE.md new file mode 100644 index 00000000..4d0b6025 --- /dev/null +++ b/modules/10-basics/40-instructions/es/EXERCISE.md @@ -0,0 +1,7 @@ +Muestra en pantalla consecutivamente tres nombres: _Robert_, _Stannis_, _Renly_. El resultado en pantalla debe ser: + +
+RobertStannisRenly
+
+ +Utiliza una llamada `print_r()` para cada nombre. diff --git a/modules/10-basics/40-instructions/es/README.md b/modules/10-basics/40-instructions/es/README.md new file mode 100644 index 00000000..ee750eb7 --- /dev/null +++ b/modules/10-basics/40-instructions/es/README.md @@ -0,0 +1,28 @@ +## ¿Qué es una instrucción? + +Una **instrucción** es un comando que el intérprete de PHP ejecuta. Está escrita en un lenguaje de programación. Se puede comparar con una instrucción o receta para cocinar un plato: + +El código en PHP es un conjunto de instrucciones separadas por el símbolo `;`. + +Aquí tienes un ejemplo de código con dos instrucciones: + +```php + Madre de Dragones. ¡Dracarys! +``` + +Al ejecutar este código, se mostrarán en pantalla dos frases consecutivas: `Madre de Dragones. ¡Dracarys!`. + +Las instrucciones se pueden escribir una tras otra sin saltar de línea: + +```php + Madre de Dragones. ¡Dracarys! +``` + +El resultado en pantalla será el mismo. Sin embargo, este código es difícil de leer, por lo que las instrucciones se colocan una debajo de la otra. diff --git a/modules/10-basics/40-instructions/es/data.yml b/modules/10-basics/40-instructions/es/data.yml new file mode 100644 index 00000000..b10187ee --- /dev/null +++ b/modules/10-basics/40-instructions/es/data.yml @@ -0,0 +1,14 @@ +name: Instrucciones +tips: + - > + [Un poco sobre los + intérpretes](https://es.wikipedia.org/wiki/Int%C3%A9rprete) +definitions: + - name: Intérprete + description: | + un programa que ejecuta código en PHP. + - name: Instrucción + description: > + un comando para la computadora escrito en un lenguaje de programación. El + código en PHP es un conjunto de instrucciones separadas (generalmente) por + el símbolo `;`. diff --git a/modules/10-basics/40-instructions/ru/EXERCISE.md b/modules/10-basics/40-instructions/ru/EXERCISE.md new file mode 100644 index 00000000..53a3073a --- /dev/null +++ b/modules/10-basics/40-instructions/ru/EXERCISE.md @@ -0,0 +1,7 @@ +Выведите на экран друг за другом три имени: _Robert_, _Stannis_, _Renly_. В результате на экране должно отобразиться: + +
+RobertStannisRenly
+
+ +Для каждого имени используйте свой собственный вызов `print_r()`. diff --git a/modules/10-basics/40-instructions/ru/README.md b/modules/10-basics/40-instructions/ru/README.md new file mode 100644 index 00000000..9a4641be --- /dev/null +++ b/modules/10-basics/40-instructions/ru/README.md @@ -0,0 +1,28 @@ +## Что такое инструкция + +**Инструкция** — это команда, которую исполняет интерпретатор PHP. Она написана на языке программирования. Ее можно сравнить с инструкцией или рецептом по приготовлению блюда: + +Код на PHP — это набор инструкций, которые отделяются друг от друга символом `;`. + +Вот пример кода с двумя инструкциями: + +```php + Mother of Dragons. Dracarys! +``` + +При запуске этого кода на экран последовательно выводятся два предложения: `Mother of Dragons. Dracarys!`. + +Инструкции можно написать последовательно друг за другом без переноса на новую строчку: + +```php + Mother of Dragons. Dracarys! +``` + +Результат на экране будет таким же. Но такой код неудобно читать, поэтому инструкции располагают друг под другом. diff --git a/modules/10-basics/40-instructions/ru/data.yml b/modules/10-basics/40-instructions/ru/data.yml new file mode 100644 index 00000000..d2aad354 --- /dev/null +++ b/modules/10-basics/40-instructions/ru/data.yml @@ -0,0 +1,12 @@ +name: Инструкции (Statements) +tips: + - | + [Немного об интерпретаторах](https://ru.wikipedia.org/wiki/Интерпретатор) +definitions: + - name: Интерпретатор + description: | + программа, выполняющая код на PHP. + - name: Инструкция (statement) + description: > + команда для компьютера, написанная на языке программирования. Код на PHP — + это набор инструкций, разделенных (чаще всего) символом `;`. diff --git a/modules/10-basics/45-testing/en/EXERCISE.md b/modules/10-basics/45-testing/en/EXERCISE.md new file mode 100644 index 00000000..6770f271 --- /dev/null +++ b/modules/10-basics/45-testing/en/EXERCISE.md @@ -0,0 +1 @@ +Display `9780262531962`. diff --git a/modules/10-basics/45-testing/en/README.md b/modules/10-basics/45-testing/en/README.md new file mode 100644 index 00000000..803063d6 --- /dev/null +++ b/modules/10-basics/45-testing/en/README.md @@ -0,0 +1,32 @@ + +Our site automatically checks your solutions. You may be wondering how it works. + +In the simplest case, the system just runs the code and looks at what's displayed on the screen. Then it compares the actual output against the expected one. + +In the future, more complicated lessons, you will write functions - mini-programs that take information from the external world and perform operations on it. Verifying solutions gets a little more complicated in this case. The system runs your code and passes data to it. The system knows what result a correctly written function would give with the data the system provides it with, and this result is what the system expects. + +Let's assume your task is to program a function that adds two numbers together. The checking system will give it several combinations of numbers and compare your function's answers with the correct answers. If all actual values match the expected ones, your solution will be considered valid. + +This is testing. It's used extensively in the real, day-to-day development process. Developers usually write the tests first, and only after that do they actually proceed to write the program itself. During that process, they run tests multiple times to check how close they are to the desired solution. + +That is why our website says, “Tests passed” once you've done the exercise correctly. + +Here's a simple example, say you want to print the string `Hello, World!`. Now imagine you make a small mistake and the function displays a different value. In that case, the system will give you the following message: + +
+  -'Hello, World!'
+  +'ello, World!'
+
+  FAILURES!
+  Tests: 1, Assertions: 1, Failures: 1.
+
+ +A hint appears on the screen. The `+` sign on it indicates what your code printed. The `-` sign is what was expected. By comparing the two values, you can see the error. In the example above, you can see that the letter _H_ is missing from the output. + +In addition to our tests, it'll also be extremely useful to experiment with code. To do this, you can use [repl.it](https://repl.it/languages/php). Ideally, you should execute all the code in the lessons yourself. + +--- + +Sometimes, it'll seem that you've done everything correctly, but the system seems to be fickle and won't make a decision. It's nigh on impossible for the system to just decide that it's wrong. Failed tests simply won't get as far as the site, they're automatically run after each change. In the vast majority of cases (all our projects have been run millions of times in total over many years) the error is in the solution code. It can be very imperceptible, maybe you used the wrong punctuation, or you used upper case instead of lower case, or you missed a comma. Other cases are more complicated. Maybe your solution works for one set of inputs, but not for another. So always read the instructions and test your output carefully. There will almost certainly be a sign of an error. + +However, if you're sure there's an error or find some kind of inaccuracy, you can always point it out. At the end of each theory section, there's a link to the contents of the lesson on Github (this project is completely open-source!). You can write about an issue, look through the tests (you can see how your code is called there), and even send a pull request. If this still feels like a dark forest for you, then join our community, we'll always be there to help in the _#hexlet-feedback_ channel. diff --git a/modules/10-basics/45-testing/en/data.yml b/modules/10-basics/45-testing/en/data.yml new file mode 100644 index 00000000..afbc8565 --- /dev/null +++ b/modules/10-basics/45-testing/en/data.yml @@ -0,0 +1,9 @@ +name: How we test your solutions +definitions: + - name: Tests + description: > + are special code that checks the programs have been made correctly by + checking the correct result against the actual one. +tips: + - | + [TDD](https://en.wikipedia.org/wiki/Test-driven_development) diff --git a/modules/10-basics/45-testing/es/EXERCISE.md b/modules/10-basics/45-testing/es/EXERCISE.md new file mode 100644 index 00000000..b3685eb3 --- /dev/null +++ b/modules/10-basics/45-testing/es/EXERCISE.md @@ -0,0 +1 @@ +Imprime en la pantalla `9780262531962`. diff --git a/modules/10-basics/45-testing/es/README.md b/modules/10-basics/45-testing/es/README.md new file mode 100644 index 00000000..a25a9e62 --- /dev/null +++ b/modules/10-basics/45-testing/es/README.md @@ -0,0 +1,32 @@ + +Nuestro sitio web verifica automáticamente tus soluciones. ¿Cómo funciona? + +En el caso más simple, el sistema simplemente ejecuta el código y verifica lo que se muestra en la pantalla. Luego lo compara con lo que "esperábamos" según la tarea. + +En las lecciones más avanzadas, escribirás funciones, que son mini programas que toman información del mundo exterior y realizan operaciones. La verificación de tus soluciones en estos casos es un poco más complicada: el sistema ejecuta tu solución y le pasa cierta información. El sistema también sabe qué respuesta debería dar la función correcta con esos datos de entrada. + +Por ejemplo, si tu tarea es escribir una función que sume dos números, el sistema de verificación le pasará diferentes combinaciones de números y comparará la respuesta de tu función con las sumas reales. Si las respuestas coinciden en todos los casos, se considera que la solución es correcta. + +Este enfoque se llama pruebas y se utiliza en el desarrollo diario real. Por lo general, el programador primero escribe una prueba, que es un programa de verificación, y luego escribe el programa que quería escribir. Durante el proceso, se ejecutan las pruebas constantemente y se verifica si se está acercando a la solución. + +Es por eso que nuestro sitio web muestra "Pruebas superadas" cuando resuelves correctamente una tarea. + +Aquí tienes un ejemplo sencillo: imprimir la cadena `Hello, World!`. Supongamos que cometiste un pequeño error y la función muestra otro valor en la pantalla. El sistema responderá algo así: + +
+  -'Hello, World!'
+  +'ello, World!'
+
+  ¡FALLOS!
+  Pruebas: 1, Afirmaciones: 1, Fallos: 1.
+
+ +En la pantalla aparece una pista. El signo `+` indica lo que imprimió tu código. El signo `-` indica lo que se esperaba. Al comparar estos dos valores, puedes ver el error. En el ejemplo anterior, se puede ver que falta la letra _H_ en la salida. + +Además de nuestras pruebas, es muy útil experimentar con el código. Para ello, puedes utilizar el servicio [repl.it](https://repl.it/languages/php). Sería ideal si ejecutas todo el código presente en las lecciones por tu cuenta. + +--- + +A veces, durante la resolución de una tarea, puede parecer que has hecho todo correctamente, pero el sistema no acepta la solución. Este comportamiento es prácticamente inexistente. Las pruebas no funcionales simplemente no pueden llegar al sitio web, se ejecutan automáticamente después de cada cambio. En la gran mayoría de estos casos (y todos nuestros proyectos en conjunto han realizado millones de verificaciones a lo largo de muchos años), el error se encuentra en el código de la solución. Puede ser muy sutil, como haber ingresado accidentalmente una letra rusa en lugar de una letra en inglés, haber utilizado minúsculas en lugar de mayúsculas o haber olvidado imprimir una coma. Otros casos son más complicados. Es posible que tu solución funcione para un conjunto de datos de entrada, pero no funcione para otro. Por lo tanto, siempre lee atentamente la descripción de la tarea y la salida de las pruebas. Casi seguro que habrá una indicación del error. + +Sin embargo, si estás seguro de que hay un error o has encontrado alguna imprecisión, siempre puedes señalarlo. Al final de cada teoría hay un enlace al contenido de la lección en GitHub (¡este proyecto es completamente abierto!). Al ir allí, puedes escribir un issue, ver el contenido de las pruebas (donde se muestra cómo se llama tu código) e incluso enviar un pull request. Si esto aún te resulta confuso, únete a nuestra comunidad en [Telegram Hexlet](https://t.me/hexletcommunity/12), allí en el canal de Voluntarios siempre estaremos dispuestos a ayudar. diff --git a/modules/10-basics/45-testing/es/data.yml b/modules/10-basics/45-testing/es/data.yml new file mode 100644 index 00000000..3d67a446 --- /dev/null +++ b/modules/10-basics/45-testing/es/data.yml @@ -0,0 +1,9 @@ +name: Cómo verificamos tus soluciones +definitions: + - name: Pruebas + description: > + código especial que verifica la corrección de los programas, comparando el + resultado correcto con el resultado real. +tips: + - | + [TDD](https://es.wikipedia.org/wiki/Desarrollo_guiado_por_pruebas) diff --git a/modules/10-basics/45-testing/ru/EXERCISE.md b/modules/10-basics/45-testing/ru/EXERCISE.md new file mode 100644 index 00000000..f2b2063b --- /dev/null +++ b/modules/10-basics/45-testing/ru/EXERCISE.md @@ -0,0 +1 @@ +Выведите на экран `9780262531962`. diff --git a/modules/10-basics/45-testing/ru/README.md b/modules/10-basics/45-testing/ru/README.md new file mode 100644 index 00000000..fbedfcae --- /dev/null +++ b/modules/10-basics/45-testing/ru/README.md @@ -0,0 +1,32 @@ + +Наш сайт автоматически проверяет ваши решения. Как это работает? + +В самом простом случае, система просто запускает код и смотрит на то, что вывелось на экран. А потом сверяет с тем, что мы «ожидали» по заданию. + +В следующих, более сложных уроках, вы будете писать функции — мини-программы, принимающие информацию из внешнего мира и производящие какие-то операции. Проверка ваших решений в таких случаях выглядит немного сложнее: система запускает ваше решение и передаёт какую-то информацию. Система также знает — «ожидает» — какой именно ответ должна дать правильная функция при таких входных данных. + +Например, если ваша задача — написать функцию сложения двух чисел, то проверочная система будет передавать ей разные комбинации чисел и сверять ответ вашей функции с реальными суммами. Если во всех случаях ответы совпадут, то решение считается верным. + +Такой подход называется тестированием, и он используется в реальной повседневной разработке. Обычно программист сначала пишет тест — проверочную программу, а потом уже ту программу, которую хотел написать. В процессе он постоянно запускает тесты и смотрит, приблизился ли он к решению. + +Именно поэтому наш сайт говорит «Тесты пройдены», когда вы правильно решили задачу. + +Вот простой пример: необходимо распечатать строку `Hello, World!`. Предположим, вы допустили небольшую ошибку, и функция вывела на экран другое значение. Система ответит примерно так: + +
+  -'Hello, World!'
+  +'ello, World!'
+
+  FAILURES!
+  Tests: 1, Assertions: 1, Failures: 1.
+
+ +На экране появляется подсказка. На ней знаком `+` обозначено то, что распечатал ваш код. Знаком `-` – то, что ожидалось. Сравнивая эти два значения, можно увидеть ошибку. В примере выше видно, что в выводе пропущена буква _H_. + +Кроме наших тестов, будет крайне полезно экспериментировать с кодом. Для этого можно использовать сервис [repl.it](https://repl.it/languages/php). Идеально, если вы выполните самостоятельно весь код, который присутствует в уроках. + +--- + +Иногда в процессе решения будет казаться, что вы сделали все правильно, но система «капризничает» и не принимает решение. Подобное поведение практически исключено. Нерабочие тесты просто не могут попасть на сайт, они автоматически запускаются после каждого изменения. В подавляющем большинстве таких случаев, (а все наши проекты в сумме провели миллионы проверок за много лет), ошибка содержится в коде решения. Она может быть очень незаметной, вместо английской буквы случайно ввели русскую, вместо верхнего регистра использовали нижний или забыли вывести запятую. Другие случаи сложнее. Возможно ваше решение работает для одного набора входных данных, но не работает для другого. Поэтому всегда внимательно читайте условие задачи и вывод тестов. Там почти наверняка есть указание на ошибку. + +Однако, если вы уверены в ошибке или нашли какую-то неточность, то вы всегда можете указать на неё. В конце каждой теории есть ссылка на содержимое урока на гитхабе (этот проект полностью открытый!). Перейдя туда, вы можете написать issue, посмотреть содержимое тестов (там видно, как вызывается ваш код) и даже отправить pullrequest. Если для вас это пока тёмный лес, то подключитесь в наше сообщество [Telegram Hexlet](https://t.me/hexletcommunity/12), там в канале Волонтеры мы всегда поможем. diff --git a/modules/10-basics/45-testing/ru/data.yml b/modules/10-basics/45-testing/ru/data.yml new file mode 100644 index 00000000..9245d42b --- /dev/null +++ b/modules/10-basics/45-testing/ru/data.yml @@ -0,0 +1,9 @@ +name: Как мы проверяем ваши решения +definitions: + - name: Тесты + description: > + специальный код, проверяющий программы на корректность, сверяя правильный + результат с реальным. +tips: + - | + [TDD](https://ru.wikipedia.org/wiki/Разработка_через_тестирование) diff --git a/modules/10-basics/50-syntax-errors/en/EXERCISE.md b/modules/10-basics/50-syntax-errors/en/EXERCISE.md new file mode 100644 index 00000000..f762e285 --- /dev/null +++ b/modules/10-basics/50-syntax-errors/en/EXERCISE.md @@ -0,0 +1,4 @@ + +This task isn't directly related to the lesson, but it would be useful to practice with printing anyway. + +Print `What Is Dead May Never Die`. diff --git a/modules/10-basics/50-syntax-errors/en/README.md b/modules/10-basics/50-syntax-errors/en/README.md new file mode 100644 index 00000000..0970f250 --- /dev/null +++ b/modules/10-basics/50-syntax-errors/en/README.md @@ -0,0 +1,15 @@ +If a PHP program is written syntactically incorrectly, the interpreter will display a corresponding message on the screen, along with a pointer to the file and line where it thinks the error occurred. _Syntax errors_ occur when the code has grammatical mistakes. Grammar is essential to human language, but a text with grammar mistakes can still be read and understood. However, when it comes to programming, things are much more strict. Any tiny violation and the program won't even start. Maybe you've mixed up your brackets, or there's a `;`, that you forgot to add — these are just some examples of such mistakes. + +Here is an example of some code with a syntax error: + +```php +- + is a type of PHP error that occurs when there are syntax errors in the + code. diff --git a/modules/10-basics/50-syntax-errors/es/EXERCISE.md b/modules/10-basics/50-syntax-errors/es/EXERCISE.md new file mode 100644 index 00000000..7b33e509 --- /dev/null +++ b/modules/10-basics/50-syntax-errors/es/EXERCISE.md @@ -0,0 +1,4 @@ + +Esta tarea no está directamente relacionada con la lección. Pero será útil practicar la salida en la pantalla. + +Muestra en la pantalla `What Is Dead May Never Die`. diff --git a/modules/10-basics/50-syntax-errors/es/README.md b/modules/10-basics/50-syntax-errors/es/README.md new file mode 100644 index 00000000..82a93fbd --- /dev/null +++ b/modules/10-basics/50-syntax-errors/es/README.md @@ -0,0 +1,16 @@ + +Si un programa escrito en PHP tiene errores de sintaxis, el intérprete mostrará un mensaje correspondiente en la pantalla, junto con la indicación del archivo y la línea donde, según su opinión, se produjo el error. Un _error de sintaxis_ ocurre cuando el código se ha escrito con violación de las reglas gramaticales. En los lenguajes humanos, la gramática es importante, pero generalmente se puede entender y leer el texto con errores. En la programación, todo es estricto. Cualquier violación mínima y el programa ni siquiera se ejecutará. Un ejemplo puede ser un punto y coma olvidado, paréntesis mal colocados y otros detalles. + +Aquí hay un ejemplo de código con un error de sintaxis: + +```php +- + tipo de errores en PHP que ocurren cuando hay errores de sintaxis en el + código. diff --git a/modules/10-basics/50-syntax-errors/ru/EXERCISE.md b/modules/10-basics/50-syntax-errors/ru/EXERCISE.md new file mode 100644 index 00000000..a7b008f0 --- /dev/null +++ b/modules/10-basics/50-syntax-errors/ru/EXERCISE.md @@ -0,0 +1,4 @@ + +Это задание не связано с уроком напрямую. Но будет полезным потренироваться с выводом на экран. + +Выведите на экран `What Is Dead May Never Die`. diff --git a/modules/10-basics/50-syntax-errors/ru/README.md b/modules/10-basics/50-syntax-errors/ru/README.md new file mode 100644 index 00000000..d1bdaa9e --- /dev/null +++ b/modules/10-basics/50-syntax-errors/ru/README.md @@ -0,0 +1,16 @@ + +Если программа на PHP написана синтаксически некорректно, то интерпретатор выводит на экран соответствующее сообщение, а также указание на файл и строчку в нём, где по его мнению произошла ошибка. _Синтаксическая ошибка_ возникает в том случае, когда код был записан с нарушением грамматических правил. В человеческих языках грамматика важна, но текст с ошибками чаще всего можно понять и прочитать. В программировании всё строго. Любое мельчайшее нарушение — и программа даже не запустится. Примером может быть забытая `;`, неправильно расставленные скобки и другие детали. + +Вот пример кода с синтаксической ошибкой: + +```php + +7 + + +Besides addition, we can also use the following operations: + +* `*` — multiplication +* `/` — division +* `-` — subtraction +* `%` — [remainder](https://en.wikipedia.org/wiki/Euclidean_division) +* `**` — exponentiation + +Now let’s print the result of a division, and then the result of an exponentiation: + +```php + 4 +print_r(3 ** 2); // => 9 +``` + +Sometimes, for convenience, we'll show the result of running lines of code in the comments like this: `=> RESULT`. For example, `// => 4`. + +The first statement will print `4` (since 8 / 2 is 4), and the second statement will print 9 (since 32 is 9). diff --git a/modules/20-arithmetics/20-basic/en/data.yml b/modules/20-arithmetics/20-basic/en/data.yml new file mode 100644 index 00000000..a698198e --- /dev/null +++ b/modules/20-arithmetics/20-basic/en/data.yml @@ -0,0 +1,12 @@ +name: Arithmetic Operations +tips: + - > + Always indent arithmetic operators with spaces between the numbers + (operands). It's good form when programming. Therefore, in our examples, we + have `print_r(3 + 4)` rather than `print_r(3+4)`. + - > + Dividing by zero causes, unsurprisingly, a `Division by zero` error. To + avoid it, you need to know about conditional constructs (you'll learn about + them in future + - | + Type your code between the`// BEGIN` and `// END` lines in the editor. diff --git a/modules/20-arithmetics/20-basic/es/EXERCISE.md b/modules/20-arithmetics/20-basic/es/EXERCISE.md new file mode 100644 index 00000000..9bc55cb5 --- /dev/null +++ b/modules/20-arithmetics/20-basic/es/EXERCISE.md @@ -0,0 +1 @@ +Muestra en pantalla el resultado de dividir el número `81` entre `9`. diff --git a/modules/20-arithmetics/20-basic/es/README.md b/modules/20-arithmetics/20-basic/es/README.md new file mode 100644 index 00000000..8fa6a3c7 --- /dev/null +++ b/modules/20-arithmetics/20-basic/es/README.md @@ -0,0 +1,35 @@ +A nivel básico, las computadoras operan solo con números. Para sumar dos números en matemáticas, escribimos, por ejemplo, `3 + 4`. En programación, es lo mismo. En esta lección, aprenderemos cómo realizar operaciones aritméticas en el código. + +## Aritmética en programación + +Veamos un ejemplo de un programa que suma dos números: + +```php + 7 +``` + +Además de la suma, están disponibles las siguientes operaciones: + +* `*` — multiplicación +* `/` — división +* `-` — resta +* `%` — [resto de la división](https://es.wikipedia.org/wiki/Resto_(matem%C3%A1tica)) +* `**` — potenciación + +Estos símbolos de operación se llaman operadores. diff --git a/modules/20-arithmetics/20-basic/es/data.yml b/modules/20-arithmetics/20-basic/es/data.yml new file mode 100644 index 00000000..2b87bfdf --- /dev/null +++ b/modules/20-arithmetics/20-basic/es/data.yml @@ -0,0 +1,13 @@ +name: Operaciones aritméticas +tips: + - > + Siempre deja espacios entre los operadores aritméticos y los números + (operandos) - esto es una buena práctica de programación. Por lo tanto, en + nuestros ejemplos es `print_r(3 + 4)`, no `print_r(3+4)`. + - > + La división por cero resulta en un error `Division by zero`. Para evitarlo, + debes conocer las estructuras condicionales (las aprenderás en las próximas + lecciones). + - > + Si en el editor hay una línea que dice `// BEGIN` y `// END`, el código debe + escribirse entre esas líneas. diff --git a/modules/20-arithmetics/20-basic/ru/EXERCISE.md b/modules/20-arithmetics/20-basic/ru/EXERCISE.md new file mode 100644 index 00000000..5dfef630 --- /dev/null +++ b/modules/20-arithmetics/20-basic/ru/EXERCISE.md @@ -0,0 +1 @@ +Выведите на экран результат деления числа `81` на `9`. diff --git a/modules/20-arithmetics/20-basic/ru/README.md b/modules/20-arithmetics/20-basic/ru/README.md new file mode 100644 index 00000000..046cd027 --- /dev/null +++ b/modules/20-arithmetics/20-basic/ru/README.md @@ -0,0 +1,35 @@ +На базовом уровне компьютеры оперируют только числами. Для сложения двух чисел в математике мы пишем, например, `3 + 4`. В программировании — то же самое. В этом уроке разберем, как проводить арифметические операции в коде. + +## Арифметика в программировании + +Рассмотрим пример программы, которая складывает два числа: + +```php + 7 +``` + +Кроме сложения доступны следующие операции: + +* `*` — умножение +* `/` — деление +* `-` — вычитание +* `%` — [остаток от деления](https://ru.wikipedia.org/wiki/Деление_с_остатком) +* `**` — возведение в степень + +Эти знаки операций называют операторами. diff --git a/modules/20-arithmetics/20-basic/ru/data.yml b/modules/20-arithmetics/20-basic/ru/data.yml new file mode 100644 index 00000000..e77a18ba --- /dev/null +++ b/modules/20-arithmetics/20-basic/ru/data.yml @@ -0,0 +1,13 @@ +name: Арифметические операции +tips: + - > + Всегда отбивайте арифметические операторы пробелами от самих чисел + (операндов) – это хороший стиль программирования. Поэтому в наших примерах + `print_r(3 + 4)`, а не `print_r(3+4)`. + - > + Деление на ноль приводит к ошибке `Division by zero`. Чтобы его не + допустить, нужно знать про условные конструкции (о них вы узнаете в + следующих уроках). + - > + Если в редакторе есть запись `// BEGIN` и `// END`, то код нужно писать + между этими строчками. diff --git a/modules/20-arithmetics/25-operator/en/EXERCISE.md b/modules/20-arithmetics/25-operator/en/EXERCISE.md new file mode 100644 index 00000000..01196ea7 --- /dev/null +++ b/modules/20-arithmetics/25-operator/en/EXERCISE.md @@ -0,0 +1 @@ +Write a program that calculates the difference between the numbers `6` and `-81` and displays the answer on the screen. diff --git a/modules/20-arithmetics/25-operator/en/README.md b/modules/20-arithmetics/25-operator/en/README.md new file mode 100644 index 00000000..b514a237 --- /dev/null +++ b/modules/20-arithmetics/25-operator/en/README.md @@ -0,0 +1,40 @@ + +Before we move on, let's take a look at the basic terminology. An operation sign, such as `+`, is called an **operator**. Operators perform operations on certain values, which are called **operands**. The operators themselves are usually represented by one or more characters,, and occasionally by a word. Most of the operators are identical to those you'll have seen in math class. + +```php + -3 +``` + +Above is an example of applying a unary operation to the number `3`. The minus operator before the three tells the interpreter to take the number `3` and find the opposite, which is `-3`. + +This can be a bit confusing because `-3` is both a number in itself and an operator with an operand, but this is just how programming languages are structured. + +```php + 1 +``` + +The same goes for the plus sign: + +```php + 3 +print_r(1 + +3); // => 4 +``` diff --git a/modules/20-arithmetics/25-operator/en/data.yml b/modules/20-arithmetics/25-operator/en/data.yml new file mode 100644 index 00000000..4d82fa82 --- /dev/null +++ b/modules/20-arithmetics/25-operator/en/data.yml @@ -0,0 +1,13 @@ +name: Operators +tips: + - | + [Operators in PHP](https://www.php.net/manual/en/language.operators.php) +definitions: + - name: Arithmetic operations + description: include addition, subtraction, multiplication and division. + - name: A unary operation + description: >- + is an operation with one operand. For example, `-3` is a unary operation + to get the opposite of three. + - name: A binary operation + description: is an operation with two operands. For example, `3 + 9`. diff --git a/modules/20-arithmetics/25-operator/es/EXERCISE.md b/modules/20-arithmetics/25-operator/es/EXERCISE.md new file mode 100644 index 00000000..ab2820b3 --- /dev/null +++ b/modules/20-arithmetics/25-operator/es/EXERCISE.md @@ -0,0 +1 @@ +Escribe un programa que calcule la diferencia entre los números `6` y `-81` y muestre la respuesta en la pantalla. diff --git a/modules/20-arithmetics/25-operator/es/README.md b/modules/20-arithmetics/25-operator/es/README.md new file mode 100644 index 00000000..7fabc95e --- /dev/null +++ b/modules/20-arithmetics/25-operator/es/README.md @@ -0,0 +1,43 @@ +Un **operador** es un símbolo de operación, como `+`. Los operadores suelen estar representados por uno o varios caracteres, a veces por una palabra. Por lo general, corresponden a operaciones matemáticas. + +Los operadores realizan operaciones en valores específicos, llamados **operandos**. + +Veamos un ejemplo: + +```php + -3 +``` + +En el ejemplo anterior, se aplica una operación unaria al número `3`. El operador `-` antes del tres le indica al intérprete que tome el número `3` y encuentre su opuesto, es decir, `-3`. Esto puede ser confuso, ya que `-3` es tanto un número como un operador con un operando. Pero en los lenguajes de programación, esta es la estructura: + +```php + 1 +``` + +Lo mismo ocurre con el signo más: + +```php + 3 +print_r(1 + +3); // => 4 +``` diff --git a/modules/20-arithmetics/25-operator/es/data.yml b/modules/20-arithmetics/25-operator/es/data.yml new file mode 100644 index 00000000..f2395a67 --- /dev/null +++ b/modules/20-arithmetics/25-operator/es/data.yml @@ -0,0 +1,13 @@ +name: Operadores +tips: + - | + [Operadores en PHP](https://www.php.net/manual/es/language.operators.php) +definitions: + - name: Operación aritmética + description: suma, resta, multiplicación y división. + - name: Operación unaria + description: >- + operación con un solo operando. Por ejemplo, `-3` es una operación unaria + para obtener el número opuesto al número tres. + - name: Operación binaria + description: operación con dos operandos. Por ejemplo, `3 + 9`. diff --git a/modules/20-arithmetics/25-operator/ru/EXERCISE.md b/modules/20-arithmetics/25-operator/ru/EXERCISE.md new file mode 100644 index 00000000..003cfc9c --- /dev/null +++ b/modules/20-arithmetics/25-operator/ru/EXERCISE.md @@ -0,0 +1 @@ +Напишите программу, которая посчитает разность между числами `6` и `-81` и выведет ответ на экран. diff --git a/modules/20-arithmetics/25-operator/ru/README.md b/modules/20-arithmetics/25-operator/ru/README.md new file mode 100644 index 00000000..b7b41c59 --- /dev/null +++ b/modules/20-arithmetics/25-operator/ru/README.md @@ -0,0 +1,43 @@ +Знак операции, например, `+`, называют **оператором**. Операторы обычно представлены одним или несколькими символами, реже — словом. Обычно они соответствуют математическим операциям. + +Операторы выполняют операции над определенными значениями, которые называются **операндами**. + +Рассмотрим пример: + +```php + -3 +``` + +Выше пример применения унарной операции к числу `3`. Оператор `-` перед тройкой говорит интерпретатору взять число `3` и найти противоположное, то есть `-3`. Это может сбить с толку, потому что `-3` — это одновременно и число, и оператор с операндом. Но у языков программирования такая структура: + +```php + 1 +``` + +То же самое касается и плюса: + +```php + 3 +print_r(1 + +3); // => 4 +``` diff --git a/modules/20-arithmetics/25-operator/ru/data.yml b/modules/20-arithmetics/25-operator/ru/data.yml new file mode 100644 index 00000000..b353e864 --- /dev/null +++ b/modules/20-arithmetics/25-operator/ru/data.yml @@ -0,0 +1,13 @@ +name: Операторы +tips: + - | + [Операторы в PHP](https://www.php.net/manual/ru/language.operators.php) +definitions: + - name: Арифметическая операция + description: сложение, вычитание, умножение и деление. + - name: Унарная операция + description: >- + операция с одним операндом. Например, `-3` — унарная операция для + получения числа, противоположного числу три. + - name: Бинарная операция + description: операция с двумя операндами. Например, `3 + 9`. diff --git a/modules/20-arithmetics/27-commutativity/en/EXERCISE.md b/modules/20-arithmetics/27-commutativity/en/EXERCISE.md new file mode 100644 index 00000000..094cff65 --- /dev/null +++ b/modules/20-arithmetics/27-commutativity/en/EXERCISE.md @@ -0,0 +1,4 @@ + +Write a program that counts and sequentially displays the values of the following mathematical expressions: "3 to the power of 5" and "-8 divided by -4". + +Note that the results will appear stuck together, on one line, and without any spaces. We'll learn how to deal with this problem in future lessons. diff --git a/modules/20-arithmetics/27-commutativity/en/README.md b/modules/20-arithmetics/27-commutativity/en/README.md new file mode 100644 index 00000000..a47a75b8 --- /dev/null +++ b/modules/20-arithmetics/27-commutativity/en/README.md @@ -0,0 +1,7 @@ +Do you remember the basic rule of arithmetic that changing the order of the numbers we're adding doesn't change the sum? It's one of the most basic and intuitive rules of arithmetics, it's called the **commutative law**. + +A binary operation is considered commutative if you get the same result after swapping operands. Obviously, addition is a commutative operation: _3 + 2 = 2 + 3_. + +But is subtraction a commutative operation? Of course not: _2 - 3 ≠ 3 - 2_. In programming, this law applies in the same way as in arithmetic. + +Moreover, most of the operations we face in real life aren't commutative. In conclusion, you should always pay attention to the order of things you're working with. diff --git a/modules/20-arithmetics/27-commutativity/en/data.yml b/modules/20-arithmetics/27-commutativity/en/data.yml new file mode 100644 index 00000000..2b152f67 --- /dev/null +++ b/modules/20-arithmetics/27-commutativity/en/data.yml @@ -0,0 +1,9 @@ +name: Commutative operation +tips: [] +definitions: + - name: Commutativity + description: > + is the property of an operation wherein changing the order of operands + doesn't affect the result. For example, addition is a commutative + operation; changing the order of the numbers we're adding doesn't change + the result. diff --git a/modules/20-arithmetics/27-commutativity/es/EXERCISE.md b/modules/20-arithmetics/27-commutativity/es/EXERCISE.md new file mode 100644 index 00000000..4a977b61 --- /dev/null +++ b/modules/20-arithmetics/27-commutativity/es/EXERCISE.md @@ -0,0 +1,3 @@ +Escriba un programa que calcule y muestre en pantalla de forma secuencial los valores de las siguientes expresiones matemáticas: "3 elevado a la 5" y "-8 dividido por -4". + +Tenga en cuenta que los resultados se mostrarán "pegados" en una sola línea sin espacios. Aprenderemos a solucionar este problema en futuras lecciones. diff --git a/modules/20-arithmetics/27-commutativity/es/README.md b/modules/20-arithmetics/27-commutativity/es/README.md new file mode 100644 index 00000000..b28b967a --- /dev/null +++ b/modules/20-arithmetics/27-commutativity/es/README.md @@ -0,0 +1,3 @@ +En programación se utiliza la ley básica de la aritmética: el orden de los sumandos no afecta a la suma. Esto se conoce como la **ley conmutativa**. Si intercambiamos los operandos en una operación binaria y obtenemos el mismo resultado, esa operación es conmutativa. Por lo tanto, la suma es una operación conmutativa: `3 + 2 = 2 + 3`. + +La resta no es una operación conmutativa: `2 - 3 ≠ 3 - 2`. En programación, esta ley también se aplica. La mayoría de las operaciones con las que nos encontramos en la vida real no son conmutativas. Por lo tanto, siempre debemos prestar atención al orden en el que trabajamos. diff --git a/modules/20-arithmetics/27-commutativity/es/data.yml b/modules/20-arithmetics/27-commutativity/es/data.yml new file mode 100644 index 00000000..2443694a --- /dev/null +++ b/modules/20-arithmetics/27-commutativity/es/data.yml @@ -0,0 +1,8 @@ +name: Operación conmutativa +tips: [] +definitions: + - name: Conmutatividad + description: > + propiedad de una operación en la que el cambio de orden de los operandos + no afecta al resultado. Por ejemplo, la suma es una operación conmutativa: + el orden de los sumandos no afecta a la suma. diff --git a/modules/20-arithmetics/27-commutativity/ru/EXERCISE.md b/modules/20-arithmetics/27-commutativity/ru/EXERCISE.md new file mode 100644 index 00000000..59f7db4b --- /dev/null +++ b/modules/20-arithmetics/27-commutativity/ru/EXERCISE.md @@ -0,0 +1,3 @@ +Напишите программу, которая считает и последовательно выводит на экран значения следующих математических выражений: «3 в степени 5» и «-8 разделить на -4». + +Обратите внимание, что результаты выведутся «слепленными» в одну строчку без пробела. Мы научимся решать эту проблему в будущих уроках. diff --git a/modules/20-arithmetics/27-commutativity/ru/README.md b/modules/20-arithmetics/27-commutativity/ru/README.md new file mode 100644 index 00000000..bbb5b91c --- /dev/null +++ b/modules/20-arithmetics/27-commutativity/ru/README.md @@ -0,0 +1,3 @@ +В программировании используется базовый закон арифметики: от перемены мест слагаемых сумма не меняется. Он называется **коммутативным законом**. Если поменять местами операнды в бинарной операции, и получится тот же результат, такая операция будет коммутативной. Получается, что сложение — коммутативная операция: `3 + 2 = 2 + 3`. + +Вычитание не будет являться коммутативной операцией: `2 - 3 ≠ 3 - 2`. В программировании этот закон тоже работает. Большинство операций, с которыми мы будем сталкиваться в реальной жизни, не являются коммутативными. Поэтому всегда нужно обращать внимание на порядок того, с чем работаем. diff --git a/modules/20-arithmetics/27-commutativity/ru/data.yml b/modules/20-arithmetics/27-commutativity/ru/data.yml new file mode 100644 index 00000000..d6004c26 --- /dev/null +++ b/modules/20-arithmetics/27-commutativity/ru/data.yml @@ -0,0 +1,8 @@ +name: Коммутативная операция +tips: [] +definitions: + - name: Коммутативность + description: > + свойство операции, когда изменение порядка операндов не влияет на + результат. Например, сложение — коммутативная операция: от перемены мест + слагаемых сумма не меняется. diff --git a/modules/20-arithmetics/30-composition/en/EXERCISE.md b/modules/20-arithmetics/30-composition/en/EXERCISE.md new file mode 100644 index 00000000..be1ff967 --- /dev/null +++ b/modules/20-arithmetics/30-composition/en/EXERCISE.md @@ -0,0 +1,8 @@ + +Write a program that calculates and prints the value of this expression: + +``` +8 / 2 + 5 - -3 / 2 +``` + +Don't calculate anything manually, your program should do all the calculations on its own. diff --git a/modules/20-arithmetics/30-composition/en/README.md b/modules/20-arithmetics/30-composition/en/README.md new file mode 100644 index 00000000..3379fb81 --- /dev/null +++ b/modules/20-arithmetics/30-composition/en/README.md @@ -0,0 +1,25 @@ +Suppose we want to calculate an expression like `3 * 5 - 2`? This is how we'd write it down: + +```php + 13 +``` + +Note that the interpreter performs arithmetic operations in the right order: first division and multiplication, then addition and subtraction. Sometimes we want to change the order of operations. We'll dig into this topic in the next lesson. + +Or another example: + +```php + 400 +``` + +We can combine operations, which allows us to calculate even more complex compound expressions. This property of operations is called composition. The composition of arithmetic operations in programming is similar to how it's done in school. As you'll later learn, the composition of operations applies to all operations in general, not just arithmetic operations. + +To visualize how calculations are done inside the interpreter, let's look at an example: `2 * 4 * 5 * 10`. + +1. First we calculate `2 * 4` and get `8 * 5 * 10`. +1. Then `8 * 5`. The result is `40 * 10`. +3. Finally, we do the last multiplication, and the result is `400`. diff --git a/modules/20-arithmetics/30-composition/en/data.yml b/modules/20-arithmetics/30-composition/en/data.yml new file mode 100644 index 00000000..54ecc5cb --- /dev/null +++ b/modules/20-arithmetics/30-composition/en/data.yml @@ -0,0 +1 @@ +name: Composition of operations diff --git a/modules/20-arithmetics/30-composition/es/EXERCISE.md b/modules/20-arithmetics/30-composition/es/EXERCISE.md new file mode 100644 index 00000000..f2bf8e89 --- /dev/null +++ b/modules/20-arithmetics/30-composition/es/EXERCISE.md @@ -0,0 +1,7 @@ +Implementa un programa que calcule y muestre en pantalla el valor de la expresión: + +``` +8 / 2 + 5 - -3 / 2 +``` + +No calcules nada por tu cuenta, tu programa debe realizar todos los cálculos por sí mismo. diff --git a/modules/20-arithmetics/30-composition/es/README.md b/modules/20-arithmetics/30-composition/es/README.md new file mode 100644 index 00000000..3b96d2d6 --- /dev/null +++ b/modules/20-arithmetics/30-composition/es/README.md @@ -0,0 +1,17 @@ +Veamos un ejemplo de composición de operaciones: + +```php + 400 +``` + +Las operaciones se pueden combinar entre sí. Esto permite calcular expresiones compuestas más complejas. Esta propiedad de las operaciones se llama **composición**. + +La composición de operaciones aritméticas en programación es similar a la composición en el programa escolar. Se aplica a todas las operaciones, no solo a las aritméticas. + +Para comprender cómo se realizan los cálculos dentro del intérprete, veamos el ejemplo: `2 * 4 * 5 * 10`. + +1. Primero se calcula `2 * 4` y se obtiene la expresión `8 * 5 * 10` +2. Luego se calcula `8 * 5`. Al final, tenemos `40 * 10` +3. Por último, se realiza la última multiplicación y se obtiene el resultado `400` diff --git a/modules/20-arithmetics/30-composition/es/data.yml b/modules/20-arithmetics/30-composition/es/data.yml new file mode 100644 index 00000000..ee2fdfce --- /dev/null +++ b/modules/20-arithmetics/30-composition/es/data.yml @@ -0,0 +1,2 @@ +name: Composición de operaciones +tips: [] diff --git a/modules/20-arithmetics/30-composition/ru/EXERCISE.md b/modules/20-arithmetics/30-composition/ru/EXERCISE.md new file mode 100644 index 00000000..83f7ab12 --- /dev/null +++ b/modules/20-arithmetics/30-composition/ru/EXERCISE.md @@ -0,0 +1,7 @@ +Реализуйте программу, которая вычисляет и выводит на экран значение выражения: + +``` +8 / 2 + 5 - -3 / 2 +``` + +Не вычисляйте ничего самостоятельно, ваша программа должна производить все вычисления сама. diff --git a/modules/20-arithmetics/30-composition/ru/README.md b/modules/20-arithmetics/30-composition/ru/README.md new file mode 100644 index 00000000..1acddea3 --- /dev/null +++ b/modules/20-arithmetics/30-composition/ru/README.md @@ -0,0 +1,17 @@ +Разберем пример композиции операций: + +```php + 400 +``` + +Операции можно соединять друг с другом. Это дает возможность вычислять более сложные составные выражения. Такое свойство операций называется **композицией**. + +Композиция арифметических операций в программировании аналогична композиции из школьной программы. Она распространяется на все операции, а не только на арифметические. + +Чтобы представить, как происходят вычисления внутри интерпретатора, разберем пример: `2 * 4 * 5 * 10`. + +1. Сначала вычисляется `2 * 4` и получается выражение `8 * 5 * 10` +2. Затем `8 * 5`. В итоге имеем `40 * 10` +3. В конце происходит последнее умножение, и получается результат `400` diff --git a/modules/20-arithmetics/30-composition/ru/data.yml b/modules/20-arithmetics/30-composition/ru/data.yml new file mode 100644 index 00000000..da230c59 --- /dev/null +++ b/modules/20-arithmetics/30-composition/ru/data.yml @@ -0,0 +1,2 @@ +name: Композиция операций +tips: [] diff --git a/modules/20-arithmetics/40-priority/en/EXERCISE.md b/modules/20-arithmetics/40-priority/en/EXERCISE.md new file mode 100644 index 00000000..57687a7a --- /dev/null +++ b/modules/20-arithmetics/40-priority/en/EXERCISE.md @@ -0,0 +1,4 @@ + +Here's a calculation: `70 * 3 + 4 / 8 + 2`. + +Place parentheses so that both additions, (`3 + 4`) and (`8 + 2`) will be calculated first. Print the result on the screen. diff --git a/modules/20-arithmetics/40-priority/en/README.md b/modules/20-arithmetics/40-priority/en/README.md new file mode 100644 index 00000000..25ede4a3 --- /dev/null +++ b/modules/20-arithmetics/40-priority/en/README.md @@ -0,0 +1,38 @@ +Look closely at the expression `2 + 2 * 2` and try and work out the answer. + +The correct answer is `6`. + +If you got `8`, then this lesson is for you. You'll have studied the order of operations in high school math. This concept defines the order in which operations are to be performed. For example, multiplication and division have a higher precedence than addition and subtraction, and exponentiation comes before all other arithmetic operations, e.g., `2 ** 3 * 2` gives us `16`. + +But sometimes, we have to perform calculations in a non-standard order. In complex cases, precedence can (and must) be set with parentheses, just like we did in high school, e.g, `(2 + 2) * 2`. + +Parentheses fit with any operation. They can be nested into each other as many times as you need. Here are a couple of examples: + + ```php + 9 + print_r(7 * 3 + (4 / 2) - (8 + (2 - 1))); // => 14 + ``` + +The main thing is to make sure to close the parentheses in the correct order. This often causes errors not just for beginners but also for experienced programmers. For convenience's sake, do the opening and closing parentheses first, and then write the inside part. The editor on our site (and most other code editors) does this automatically: you write `(`, and the editor immediately adds `)`. This also applies to other paired characters, such as quotation marks. We'll talk about them in future lessons. + +Sometimes, an expression can be visually cumbersome. In such cases, parentheses can come in handy without affecting the order of operations. For example, the task from the previous lesson gets clearer if you have parentheses. + +Before: + +```php + 10.5 +``` + +After: + +```php + 10.5 +``` + +Note: code is written for humans, since they'll be the ones to read it, the machine just executes it. For the machine, code is either valid or invalid, it doesn't recognize "more" or "less" valid code. Explicit prioritization makes it easier for other developers to read your code. diff --git a/modules/20-arithmetics/40-priority/en/data.yml b/modules/20-arithmetics/40-priority/en/data.yml new file mode 100644 index 00000000..7267426e --- /dev/null +++ b/modules/20-arithmetics/40-priority/en/data.yml @@ -0,0 +1,5 @@ +name: Priority of operations +tips: + - > + [Priority of + operators](https://www.php.net/manual/en/language.operators.precedence.php) diff --git a/modules/20-arithmetics/40-priority/es/EXERCISE.md b/modules/20-arithmetics/40-priority/es/EXERCISE.md new file mode 100644 index 00000000..414965ca --- /dev/null +++ b/modules/20-arithmetics/40-priority/es/EXERCISE.md @@ -0,0 +1,3 @@ +Dada la expresión `70 * 3 + 4 / 8 + 2`. + +Coloca los paréntesis de manera que ambas sumas (`3 + 4`) y (`8 + 2`) se calculen primero. Imprime el resultado en pantalla. diff --git a/modules/20-arithmetics/40-priority/es/README.md b/modules/20-arithmetics/40-priority/es/README.md new file mode 100644 index 00000000..e4657e57 --- /dev/null +++ b/modules/20-arithmetics/40-priority/es/README.md @@ -0,0 +1,26 @@ +En matemáticas escolares, existe el concepto de "prioridad de la operación". La prioridad determina en qué secuencia deben realizarse las operaciones. + +Supongamos que queremos calcular la siguiente expresión: `2 + 2 * 2`: + +```php + 6 +``` + +El intérprete realiza los cálculos aritméticos en el orden correcto: primero la multiplicación y la división, luego la suma y la resta, y la potenciación tiene una prioridad más alta que todas las demás operaciones aritméticas: `2 ** 3 * 2` se calculará como `16`. + +A veces, los cálculos deben realizarse en un orden diferente. En este caso, se utilizan paréntesis para establecer la prioridad, por ejemplo: `(2 + 2) * 2`. Los paréntesis se pueden colocar alrededor de cualquier operación y se pueden anidar tantas veces como sea necesario. Aquí hay algunos ejemplos: + +```php + 9 +print_r(7 * 3 + (4 / 2) - (8 + (2 - 1))); // => 14 +``` + +En este caso, es importante cerrar los paréntesis en el orden correcto. Esto a menudo es la causa de errores no solo para principiantes, sino también para programadores experimentados. Para mayor comodidad, se pueden colocar los paréntesis de apertura y cierre de inmediato, y luego escribir la parte interna. + +La mayoría de los editores de código hacen esto automáticamente. Por ejemplo, colocamos un paréntesis de apertura y automáticamente se coloca el de cierre. Esto también se aplica a otros caracteres emparejados, como comillas. Hablaremos de ellos en futuras lecciones. + +A veces, una expresión puede ser difícil de entender visualmente. En ese caso, se pueden colocar paréntesis sin afectar la prioridad. El código se escribe para las personas, y las máquinas solo lo ejecutarán. Para las máquinas, el código es correcto o incorrecto. No hay código "más" o "menos" comprensible para ellas. La colocación explícita de prioridades facilita la lectura del código para otros desarrolladores. diff --git a/modules/20-arithmetics/40-priority/es/data.yml b/modules/20-arithmetics/40-priority/es/data.yml new file mode 100644 index 00000000..c4ccc1a8 --- /dev/null +++ b/modules/20-arithmetics/40-priority/es/data.yml @@ -0,0 +1,5 @@ +name: Prioridad de las operaciones +tips: + - > + [Prioridad de los + operadores](https://www.php.net/manual/es/language.operators.precedence.php) diff --git a/modules/20-arithmetics/40-priority/ru/EXERCISE.md b/modules/20-arithmetics/40-priority/ru/EXERCISE.md new file mode 100644 index 00000000..615f07de --- /dev/null +++ b/modules/20-arithmetics/40-priority/ru/EXERCISE.md @@ -0,0 +1,3 @@ +Дано вычисление `70 * 3 + 4 / 8 + 2`. + +Расставьте скобки так, чтобы оба сложения (`3 + 4`) и (`8 + 2`) высчитывались в первую очередь. Выведите на экран результат. diff --git a/modules/20-arithmetics/40-priority/ru/README.md b/modules/20-arithmetics/40-priority/ru/README.md new file mode 100644 index 00000000..97a74bd4 --- /dev/null +++ b/modules/20-arithmetics/40-priority/ru/README.md @@ -0,0 +1,26 @@ +В школьной математике есть понятие «приоритет операции». Приоритет определяет, в какой последовательности должны выполняться операции. + +Допустим, нам нужно вычислить такое выражение: `2 + 2 * 2`: + +```php + 6 +``` + +Интерпретатор производит арифметические вычисления в правильном порядке: сначала деление и умножение, потом сложение и вычитание, а приоритет возведения в степень выше всех остальных арифметических операций: `2 ** 3 * 2` вычислится в `16`. + +Иногда вычисления должны происходить в другом порядке. В этом случае приоритет задают круглыми скобками, например: `(2 + 2) * 2`. Скобки можно ставить вокруг любой операции. Они могут вкладываться друг в друга сколько угодно раз. Вот пара примеров: + +```php + 9 +print_r(7 * 3 + (4 / 2) - (8 + (2 - 1))); // => 14 +``` + +В этом случае главное закрывать скобки в правильном порядке. Это часто становится причиной ошибок не только у новичков, но и у опытных программистов. Для удобства можно сразу ставить открывающую и закрывающую скобки, а потом писать внутреннюю часть. + +Сейчас большинство редакторов кода делают это автоматически. Например, мы ставим открывающую скобку, а он автоматически ставит закрывающую. Это касается и других парных символов, например, кавычек. О них — в будущих уроках. + +Иногда выражение сложно воспринимать визуально. Тогда можно расставить скобки, не повлияв на приоритет. Код пишется для людей, а машины будут только исполнять его. Для машин код — или корректный, или не корректный. Для них нет «более» понятного или «менее» понятного кода. Явная расстановка приоритетов упрощает чтение кода другими разработчиками. diff --git a/modules/20-arithmetics/40-priority/ru/data.yml b/modules/20-arithmetics/40-priority/ru/data.yml new file mode 100644 index 00000000..df7a9915 --- /dev/null +++ b/modules/20-arithmetics/40-priority/ru/data.yml @@ -0,0 +1,5 @@ +name: Приоритет операций +tips: + - > + [Приоритет + операторов](https://www.php.net/manual/ru/language.operators.precedence.php) diff --git a/modules/20-arithmetics/45-linting/en/EXERCISE.md b/modules/20-arithmetics/45-linting/en/EXERCISE.md new file mode 100644 index 00000000..a8bd27b5 --- /dev/null +++ b/modules/20-arithmetics/45-linting/en/EXERCISE.md @@ -0,0 +1,2 @@ + +Print the result of the difference between five squared and the product of three and seven. Write the code so that each operator is separated from the operands with spaces. diff --git a/modules/20-arithmetics/45-linting/en/README.md b/modules/20-arithmetics/45-linting/en/README.md new file mode 100644 index 00000000..2fc313f9 --- /dev/null +++ b/modules/20-arithmetics/45-linting/en/README.md @@ -0,0 +1,37 @@ +Since we've learned to write simple programs, let's talk about the very process of writing. + +Code must be designed in a certain way so that it's clear and easy to maintain. Special sets of rules - standards - describe different aspects of code writing. Specifically in PHP, the most common standards are the **PSR** standards (PHP Standards Recommendations) from [PHP-FIG](https://www.php-fig.org/psr/). A recommendation is a set of rules designed to facilitate a particular aspect of development (or to solve a particular problem). Currently there are several approved recommendations, each labeled with a number: PSR-1, PSR-2, PSR-3 and [so on](https://en.wikipedia.org/wiki/PHP_Standard_Recommendation). You'll gradually become familiar with all of these recommendations as you learn and work. Now let's focus on the two main ones: + +* PSR-1: [Basic Coding Standard](https://www.php-fig.org/psr/psr-1/). This is a set of rules defining how to write PHP code, including how to write PHP tags, and what rules to use for naming classes, methods and class constants. It also touches on encoding, autoloading, namespaces, and sharing responsibility between files. These are basic rules; the PSR-12 standard expands on them. +* PSR-12: [Extended Coding Style](https://www.php-fig.org/psr/psr-12/). replaces and supplements the obsolete PSR-2. The first thing to mention is that this standard requires compliance with PSR-1 rules. Secondly, it adds many new requirements, for indentations, files, strings, keywords, classes, control structures, scope and other elements. + +In any programming language, there are special tools, called **linters**, which check the code for compliance with standards. One commonly used linter in PHP is the [PHP_CodeSniffer](https://github.com/squizlabs/PHP_CodeSniffer). + +Suppose we have a file with this PHP code: + +```php + +``` + +When you check the file, the linter will find the following errors: + +* `Spaces must be used to indent lines; tabs are not allowed` — PSR-12 recommends indenting four spaces, and the example above uses tabs +* `A closing tag is not permitted at the end of a PHP file` — the standard requires the closing tag `?>` +* `Space before opening parenthesis of function call prohibited` — when calling a function, there should be no whitespace between the function name and parentheses, and in the code being checked there is one space after `print_r` name + +Fix the code by removing the closing tag, indentation, and space after the function name: + +```php + 10.5 +``` + +This code doesn't violate the rules, and the linter will "say nothing", as it were. + +Don't be frightened by the abundance of recommendations and rules. Most of the rules are simple and straightforward. You'll most likely intuitively stick to them in the code anyway. Time, experience, and a linter will help you with the rest ;) diff --git a/modules/20-arithmetics/45-linting/en/data.yml b/modules/20-arithmetics/45-linting/en/data.yml new file mode 100644 index 00000000..5dcbe414 --- /dev/null +++ b/modules/20-arithmetics/45-linting/en/data.yml @@ -0,0 +1 @@ +name: Linter diff --git a/modules/20-arithmetics/45-linting/es/EXERCISE.md b/modules/20-arithmetics/45-linting/es/EXERCISE.md new file mode 100644 index 00000000..bbf7f920 --- /dev/null +++ b/modules/20-arithmetics/45-linting/es/EXERCISE.md @@ -0,0 +1 @@ +Muestra en pantalla el resultado de la siguiente operación: "la diferencia entre el cuadrado de cinco y el producto de tres y siete". Escribe el código de manera que cada operador esté separado de los operandos por espacios. diff --git a/modules/20-arithmetics/45-linting/es/README.md b/modules/20-arithmetics/45-linting/es/README.md new file mode 100644 index 00000000..a4a9af14 --- /dev/null +++ b/modules/20-arithmetics/45-linting/es/README.md @@ -0,0 +1,43 @@ +En esta lección aprenderemos qué son los estándares de codificación. Facilitan el desarrollo y hacen que el código sea más comprensible. Vamos a analizar en detalle dos recomendaciones principales para PHP que contienen reglas de codificación. + +## Estándares de codificación en PHP + +El código debe estar formateado de manera que sea comprensible y fácil de mantener. Para ello existen conjuntos de reglas especiales llamados **estándares**. Estos describen varios aspectos de la escritura de código. + +En PHP, los estándares más comunes son los **PSR** - PHP Standards Recommendations o Recomendaciones de Estándares PHP de [PHP-FIG](https://www.php-fig.org/psr/). Son un conjunto de reglas que facilitan el desarrollo y resuelven problemas específicos. + +Actualmente existen varias recomendaciones aprobadas, cada una de ellas se identifica con un número: PSR-1, PSR-2, PSR-3 y [otros](https://en.wikipedia.org/wiki/PHP_Standard_Recommendation). Conocerás todas estas recomendaciones durante el aprendizaje y el trabajo. En esta lección, vamos a analizar en detalle las siguientes: + +* PSR-1. [Basic Coding Standard](https://www.php-fig.org/psr/psr-1/) - estándar básico de codificación. Es un conjunto de reglas que definen cómo formatear el código: cómo escribir etiquetas PHP, cómo nombrar clases, métodos y constantes de clases. También aborda cuestiones de codificación, autoloading, namespaces y separación de responsabilidades entre archivos. +* PSR-12. [Extended Coding Style](https://www.php-fig.org/psr/psr-12/) - estándar de estilo de codificación extendido, reemplaza y amplía el obsoleto PSR-2. Este estándar requiere el cumplimiento de las reglas de PSR-1. También agrega muchas nuevas reglas: sangrías, archivos, líneas, palabras clave, clases, estructuras de control, ámbitos y otros elementos. + +## Linters en PHP + +En cualquier lenguaje de programación existen herramientas especiales llamadas **linters**. Verifican el código en busca de cumplimiento de los estándares. El linter ampliamente utilizado en PHP es [PHP_CodeSniffer](https://github.com/squizlabs/PHP_CodeSniffer). + +Supongamos que tenemos un archivo con el siguiente código PHP: + +```php + +``` + +Al verificar el archivo, el linter encontrará los siguientes errores: + +* `Spaces must be used to indent lines; tabs are not allowed` - PSR-12 recomienda usar una sangría de cuatro espacios, pero en el ejemplo se utiliza una tabulación. +* `A closing tag is not permitted at the end of a PHP file` - el estándar requiere omitir la etiqueta de cierre `?>`. +* `Space before opening parenthesis of function call prohibited` - al llamar a una función, no debe haber espacios entre el nombre de la función y los paréntesis. Sin embargo, en el código verificado hay un espacio después del nombre `print_r`. + +Vamos a corregir el código: eliminaremos la etiqueta de cierre, las sangrías y el espacio después del nombre de la función: + +```php + 10.5 +``` + +Esta versión ya cumple con las reglas y el linter no mostrará ningún mensaje de error. diff --git a/modules/20-arithmetics/45-linting/es/data.yml b/modules/20-arithmetics/45-linting/es/data.yml new file mode 100644 index 00000000..d14182b1 --- /dev/null +++ b/modules/20-arithmetics/45-linting/es/data.yml @@ -0,0 +1,2 @@ +name: Linter +tips: [] diff --git a/modules/20-arithmetics/45-linting/ru/EXERCISE.md b/modules/20-arithmetics/45-linting/ru/EXERCISE.md new file mode 100644 index 00000000..953edd5c --- /dev/null +++ b/modules/20-arithmetics/45-linting/ru/EXERCISE.md @@ -0,0 +1 @@ +Выведите на экран результат следующего вычисления: «разница между пятью в квадрате и произведением трёх и семи». Напишите код так, чтобы каждый оператор отделялся от операндов пробелами. diff --git a/modules/20-arithmetics/45-linting/ru/README.md b/modules/20-arithmetics/45-linting/ru/README.md new file mode 100644 index 00000000..31983925 --- /dev/null +++ b/modules/20-arithmetics/45-linting/ru/README.md @@ -0,0 +1,44 @@ +В этом уроке мы узнаем, что такое стандарты по написанию кода. Они облегчают разработку и делают код более понятным. Мы подробнее разберем две основные рекомендации по PHP, которые содержат правила по написанию кода. + +## Стандарты по написанию кода в PHP + +Код нужно оформлять так, чтобы он был понятным и простым в поддержке. Для этого существуют специальные наборы правил — **стандарты**. Они описывают различные аспекты написания кода. + +В PHP самыми распространенными являются стандарты **PSR** — PHP Standards Recommendations или стандартные рекомендации PHP от [PHP-FIG](https://www.php-fig.org/psr/). Это набор правил, которые облегчают разработку и решают определенную проблему. + +На текущий момент существует несколько утвержденных рекомендаций, каждая из них обозначена цифрой: PSR-1, PSR-2, PSR-3 и [другие](https://en.wikipedia.org/wiki/PHP_Standard_Recommendation). Со всеми рекомендациями вы познакомитесь во время обучения и работы. +В этом уроке разберем подробнее следующие: + +* PSR-1. [Basic Coding Standard](https://www.php-fig.org/psr/psr-1/) — базовый стандарт написания кода. Это набор правил, которые определяют, как следует оформлять программный код: как писать теги PHP, по каким правилам именовать классы, методы и константы классов. Он также затрагивает вопросы кодировки, автозагрузки, пространства имен и разделения ответственности между файлами +* PSR-12. [Extended Coding Style](https://www.php-fig.org/psr/psr-12/) — расширенный стандарт стиля кодирования, заменяет и дополняет устаревший PSR-2. Этот стандарт требует выполнения правил PSR-1. Также он добавляет множество новых требований: к отступам, файлам, строкам, ключевым словам, классам, управляющим конструкциям, области видимости и другим элементам + +## Линтеры в PHP + +В любом языке программирования существуют специальные инструменты — **линтеры**. Они проверяют код на соответствие стандартам. Повсеместно используемым линтером в PHP является [PHP_CodeSniffer](https://github.com/squizlabs/PHP_CodeSniffer). + +Допустим, у нас есть файл с таким PHP-кодом: + +```php + +``` + +При проверке файла линтер найдет следующие ошибки: + +* `Spaces must be used to indent lines; tabs are not allowed` — PSR-12 рекомендует делать отступ размером в четыре пробела, а в примере выше использована табуляция +* `A closing tag is not permitted at the end of a PHP file` — стандарт содержит требование опускать завершающий тег `?>` +* `Space before opening parenthesis of function call prohibited` — при вызове функции между именем функции и круглыми скобками не должно быть пробельных символов, а в проверяемом коде после имени `print_r` стоит один пробел + +Исправим код — уберем закрывающий тег, отступы и пробел после имени функции: + +```php + 10.5 +``` + +Этот вариант уже не нарушает правил, и линтер будет «молчать». diff --git a/modules/20-arithmetics/45-linting/ru/data.yml b/modules/20-arithmetics/45-linting/ru/data.yml new file mode 100644 index 00000000..d3e5043c --- /dev/null +++ b/modules/20-arithmetics/45-linting/ru/data.yml @@ -0,0 +1,2 @@ +name: Линтер +tips: [] diff --git a/modules/25-strings/10-quotes/en/EXERCISE.md b/modules/25-strings/10-quotes/en/EXERCISE.md new file mode 100644 index 00000000..425e1904 --- /dev/null +++ b/modules/25-strings/10-quotes/en/EXERCISE.md @@ -0,0 +1,12 @@ + +Write a program that prints: + +``` +"Khal Drogo's favorite word is "athjahakar"" +``` + +The program should display this exact phrase on the screen. Note the quotes at the beginning and the end of the phrase: + +
+"Khal Drogo's favorite word is "athjahakar""
+
diff --git a/modules/25-strings/10-quotes/en/README.md b/modules/25-strings/10-quotes/en/README.md new file mode 100644 index 00000000..d5e48dc1 --- /dev/null +++ b/modules/25-strings/10-quotes/en/README.md @@ -0,0 +1,93 @@ + +```php +'Hello' +'Goodbye' + +'G' +' ' +'' +``` + +Which of these five items are strings? + +With the first two, everything is clear, they're strings, we've already worked with similar constructions and said that strings are sets of characters. + +Any single character between parentheses is a string. `''`, is also a string (albeit empty). So everything inside the quotation marks can be considered a string, even if it's a space, one character, or no characters at all. + +In previous lessons, we enclosed strings in single quotes. You can also use double quotes: + +```php + Dragon's mother said "No" +``` + +Look closely: we had to use `\` for double quotes to escape them, and not for the single quote (apostrophe) because the string is written in double quotes. If the string were written in single quotes, the escape character would be used before the apostrophe, not before the double quotes. + +```php + Death is \so terribly final +``` + +But what if you want to print the backslash? Just like any other special symbol, it escapes using a backslash too. + +```php + \ +``` + +Self-test: what will be printed? + +```php + +"Khal Drogo's favorite word is "athjahakar"" + diff --git a/modules/25-strings/10-quotes/es/README.md b/modules/25-strings/10-quotes/es/README.md new file mode 100644 index 00000000..3caee5e6 --- /dev/null +++ b/modules/25-strings/10-quotes/es/README.md @@ -0,0 +1,91 @@ +En esta lección vamos a hablar sobre las cadenas de texto y por qué necesitamos comillas simples y dobles. También aprenderemos sobre las secuencias de escape y la concatenación. + +## ¿Qué es una cadena de texto? + +Cualquier carácter individual entre comillas es una **cadena de texto**. Por ejemplo: + +```php +'Hola' +'Adiós' +'G' +' ' +'' +``` + +Una cadena de texto vacía `''` también es una cadena de texto. Es decir, consideramos como cadena de texto todo lo que está dentro de las comillas, incluso si es un espacio, un solo carácter o la ausencia total de caracteres. + +Anteriormente, en las lecciones, hemos escrito cadenas de texto entre comillas simples, pero también se pueden usar comillas dobles: + +```php + La madre del dragón dijo "No" +``` + +Tuvimos que agregar `\` para las comillas dobles, pero no para el apóstrofe, porque la cadena misma se creó con comillas dobles. Si la cadena se hubiera creado con comillas simples, entonces se necesitaría un carácter de escape antes del apóstrofe, pero no antes de las comillas dobles. + +```php + La muerte es \tan terriblemente final +``` + +También puede ser necesario imprimir la barra invertida en sí: + +```php + \ +``` + +Esto también se puede hacer escapando la barra invertida. diff --git a/modules/25-strings/10-quotes/es/data.yml b/modules/25-strings/10-quotes/es/data.yml new file mode 100644 index 00000000..1ceacd43 --- /dev/null +++ b/modules/25-strings/10-quotes/es/data.yml @@ -0,0 +1,2 @@ +name: Comillas +tips: [] diff --git a/modules/25-strings/10-quotes/ru/EXERCISE.md b/modules/25-strings/10-quotes/ru/EXERCISE.md new file mode 100644 index 00000000..10fbe5b5 --- /dev/null +++ b/modules/25-strings/10-quotes/ru/EXERCISE.md @@ -0,0 +1,11 @@ +Напишите программу, которая выведет на экран: + +``` +"Khal Drogo's favorite word is "athjahakar"" +``` + +Программа должна вывести на экран эту фразу в точности. Обратите внимание на кавычки в начале и в конце фразы: + +
+"Khal Drogo's favorite word is "athjahakar""
+
diff --git a/modules/25-strings/10-quotes/ru/README.md b/modules/25-strings/10-quotes/ru/README.md new file mode 100644 index 00000000..864c6e76 --- /dev/null +++ b/modules/25-strings/10-quotes/ru/README.md @@ -0,0 +1,91 @@ +В этом уроке мы разберем, что такое строки, зачем для них нужны одинарные и двойные кавычки. Также узнаем, что такое экранирующие последовательности и конкатенация. + +## Что такое строка + +Любой одиночный символ в кавычках — это **строка**. Например: + +```php +'Hello' +'Goodbye' +'G' +' ' +'' +``` + +Пустая строка `''` — это тоже строка. То есть строкой мы считаем все, что находится внутри кавычек, даже если это пробел, один символ или вообще отсутствие символов. + +Ранее в уроках мы записывали строки в одинарных кавычках, но можно использовать и двойные: + +```php + Dragon's mother said "No" +``` + +Нам нужно было добавить `\` для двойных кавычек, но не для апострофа, потому что сама строка создана с двойными кавычками. Если бы строка создавалась с одинарными кавычками, то символ экранирования нужен был бы перед апострофом, но не перед двойными кавычками. + +```php + Death is \so terribly final +``` + +Также нам может понадобиться вывести сам обратный слеш: + +```php + \ +``` + +Это тоже можно сделать через экранирование, но уже самого себя. diff --git a/modules/25-strings/10-quotes/ru/data.yml b/modules/25-strings/10-quotes/ru/data.yml new file mode 100644 index 00000000..e583d868 --- /dev/null +++ b/modules/25-strings/10-quotes/ru/data.yml @@ -0,0 +1,2 @@ +name: Кавычки +tips: [] diff --git a/modules/25-strings/15-escape-characters/en/EXERCISE.md b/modules/25-strings/15-escape-characters/en/EXERCISE.md new file mode 100644 index 00000000..23577c5a --- /dev/null +++ b/modules/25-strings/15-escape-characters/en/EXERCISE.md @@ -0,0 +1,7 @@ + +Write a program that prints this to the screen: + + - Did Joffrey agree? + - He did. He also said "I love using \n". + +This program uses only one `print_r()`, but the result on the screen should look exactly like the one shown above. diff --git a/modules/25-strings/15-escape-characters/en/README.md b/modules/25-strings/15-escape-characters/en/README.md new file mode 100644 index 00000000..9204cfdd --- /dev/null +++ b/modules/25-strings/15-escape-characters/en/README.md @@ -0,0 +1,118 @@ + +We want to show a dialogue between the Mother of Dragons and her child: + +``` +- Are you hungry? +- Aaaarrrgh! +``` + +If you display a line with this text on the screen: + +```php + +- Hey!¶ +- Oh, hey!¶ +- How's it going? + + +The device that outputs the corresponding text takes this character into account. For example, the printer pulls the paper up one line when it encounters the LF, and the text editor pulls all subsequent text below, also by one line. + +`\n` is an example of an **escape sequence**. They're also called control constructs. Although there are more than a dozen such characters, there are often only a few such characters in programming. In addition to line feeds, these can include tabs (the break you get when you press the Tab button) and carriage returns (only in Windows). We programmers often need to use line feed `\n` for proper text formatting. + +```php + +Gregor Clegane +Dunsen +Polliver +Chiswyck + + +Note the following points: + +1. It does not matter what comes before or after `\n`: a character or an empty string. The line feed will be spotted and executed in any case. + +2. Remember that a string can contain a single character or zero characters. Also, a string can only contain `\n`. Analyze the following example: + + ```php + + Gregor Clegane + Dunsen + + +3. If we need to output `\n` as text (two separate printable characters), we can use the escape method we already know, adding another `\` at the beginning. I.e., the sequence `\\n` will appear as the characters `\` and `n` following each other. + +```php + +Joffrey loves using \n + + +A small but important note about Windows. Windows uses `\r\n`. to do line feeds by default. This combination works well only in Windows, but creates problems when migrating to other systems (for example, when the development team has both Windows and Linux users). The point is that the sequence `\r\n` has a different interpretation depending on the chosen encoding (discussed later). For this reason, it's common among developers to always use `\n` without `\r`, since LF is always treated the same and works fine on any system. Remember to configure your editor to use `\n`. diff --git a/modules/25-strings/15-escape-characters/en/data.yml b/modules/25-strings/15-escape-characters/en/data.yml new file mode 100644 index 00000000..9cef26b4 --- /dev/null +++ b/modules/25-strings/15-escape-characters/en/data.yml @@ -0,0 +1,12 @@ +name: Escape equences +definitions: + - name: An escape sequence + description: > + is a special combination of characters in text. For example, `\n` means + line feed. +tips: + - > + Be sure to experiment with the output of different lines on the site + [https://repl.it/languages/php](https://repl.it/languages/php) + - | + [History of Line Translation](https://en.wikipedia.org/wiki/Newline) diff --git a/modules/25-strings/15-escape-characters/es/EXERCISE.md b/modules/25-strings/15-escape-characters/es/EXERCISE.md new file mode 100644 index 00000000..8062755d --- /dev/null +++ b/modules/25-strings/15-escape-characters/es/EXERCISE.md @@ -0,0 +1,5 @@ +Escribe un programa que muestre en la pantalla: + + - Did Joffrey agree? + - He did. He also said "I love using \n". +El programa debe usar solo un `print_r()`, pero el resultado en la pantalla debe verse exactamente como se muestra arriba. diff --git a/modules/25-strings/15-escape-characters/es/README.md b/modules/25-strings/15-escape-characters/es/README.md new file mode 100644 index 00000000..4a4cece2 --- /dev/null +++ b/modules/25-strings/15-escape-characters/es/README.md @@ -0,0 +1,42 @@ +A veces necesitamos colocar varias líneas una tras otra. Para hacer esto, debemos decirle al intérprete "presiona Enter" - hacer un salto de línea después del signo de interrogación. Esto se puede hacer con el carácter de salto de línea - `\n`: + +```php + + una combinación especial de caracteres en un texto. Por ejemplo, `\n` es + un salto de línea. +tips: + - > + Asegúrate de experimentar con la impresión de diferentes cadenas en el sitio + [https://repl.it/languages/php](https://repl.it/languages/php) + - > + [Historia del salto de + línea](https://es.wikipedia.org/wiki/Salto_de_l%C3%ADnea#Historia) diff --git a/modules/25-strings/15-escape-characters/ru/EXERCISE.md b/modules/25-strings/15-escape-characters/ru/EXERCISE.md new file mode 100644 index 00000000..04d13cf4 --- /dev/null +++ b/modules/25-strings/15-escape-characters/ru/EXERCISE.md @@ -0,0 +1,5 @@ +Напишите программу, которая выводит на экран: + + - Did Joffrey agree? + - He did. He also said "I love using \n". +При этом программа использует только один `print_r()`, но результат на экране должен выглядеть в точности как показано выше. diff --git a/modules/25-strings/15-escape-characters/ru/README.md b/modules/25-strings/15-escape-characters/ru/README.md new file mode 100644 index 00000000..8977c103 --- /dev/null +++ b/modules/25-strings/15-escape-characters/ru/README.md @@ -0,0 +1,42 @@ +Иногда нам необходимо расположить несколько строк друг за другом. Для этого нужно сказать интерпретатору «нажать на энтер» — сделать перевод строки после вопросительного знака. Это можно сделать с помощью символа перевода строки — `\n`: + +```php + + специальная комбинация символов в тексте. Например, `\n` - это перевод + строки. +tips: + - > + Обязательно поэкспериментируйте с выводом разных строк на сайте + [https://repl.it/languages/php](https://repl.it/languages/php) + - > + [История перевода + строки](https://ru.wikipedia.org/wiki/Перевод_строки#История) diff --git a/modules/25-strings/20-strings-concatenation/en/EXERCISE.md b/modules/25-strings/20-strings-concatenation/en/EXERCISE.md new file mode 100644 index 00000000..1d27823e --- /dev/null +++ b/modules/25-strings/20-strings-concatenation/en/EXERCISE.md @@ -0,0 +1,8 @@ + +Print + +``` +Winter came for the House of Frey. +``` + +using concatenation diff --git a/modules/25-strings/20-strings-concatenation/en/README.md b/modules/25-strings/20-strings-concatenation/en/README.md new file mode 100644 index 00000000..8f431ab8 --- /dev/null +++ b/modules/25-strings/20-strings-concatenation/en/README.md @@ -0,0 +1,64 @@ + +In web development, programs use strings all the time. Everything we see on websites, in one way or another, is presented as text. This text is most often dynamic, it's made up of different connected pieces. The operation of joining strings in programming is called concatenation. + +We already know about addition in mathematics. This sort of program: + +```php + Kingswood + +print_r('Kings' . 'road'); // => Kingsroad + +print_r("King's" . 'Landing'); // => King'sLanding +``` + +As you can see, strings can be concatenated even if they're written in different quotes. + +In the last example, the name of the city has been misspelled: *King's Landing* should be spelled with a space! But there were no spaces in our initial lines, and the spaces in the code itself to the left and right of the `.` character don't matter, because they're not part of the strings. + +There are two ways to fix this: + +```php + King's Landing + +// Put a space at the start of the right part +print_r("King's" . ' Landing'); // => King's Landing +``` + +Space is a character like any other, so however many spaces you put in the string is how many you'll get: + +```php + King's Landing + +print_r("King's " . ' Landing'); // => King's Landing +``` diff --git a/modules/25-strings/20-strings-concatenation/en/data.yml b/modules/25-strings/20-strings-concatenation/en/data.yml new file mode 100644 index 00000000..52b51769 --- /dev/null +++ b/modules/25-strings/20-strings-concatenation/en/data.yml @@ -0,0 +1,6 @@ +name: Concatenation +definitions: + - name: Concatenation + description: > + is the operation of joining two strings. For example, `print_r("King's " . + ' Landing');` diff --git a/modules/25-strings/20-strings-concatenation/es/EXERCISE.md b/modules/25-strings/20-strings-concatenation/es/EXERCISE.md new file mode 100644 index 00000000..7979494e --- /dev/null +++ b/modules/25-strings/20-strings-concatenation/es/EXERCISE.md @@ -0,0 +1,7 @@ +Muestra en pantalla + +``` +Winter came for the House of Frey. +``` + +utilizando la concatenación de palabras. diff --git a/modules/25-strings/20-strings-concatenation/es/README.md b/modules/25-strings/20-strings-concatenation/es/README.md new file mode 100644 index 00000000..7d2d680f --- /dev/null +++ b/modules/25-strings/20-strings-concatenation/es/README.md @@ -0,0 +1,43 @@ +En el desarrollo web, los programas operan constantemente con cadenas de texto. Todo lo que vemos en los sitios web está representado de alguna manera como texto. Este texto suele ser dinámico, obtenido de diferentes partes que se unen entre sí. La operación de unir cadenas en programación se llama **concatenación**. + +Ya conocemos la operación matemática de suma: + +```php + 8 +``` + +Este programa mostrará `8` en la pantalla, que es el resultado de la operación binaria `+` con los operandos `5` y `3`. + +También podemos "sumar" dos cadenas. Este programa mostrará `Dragonstone`, que es el resultado de la operación binaria `.` con los operandos 'Dragon' y 'stone': + +```php + Dragonstone +``` + +La concatenación de cadenas siempre ocurre en el mismo orden en el que se escriben los operandos. El operando izquierdo se convierte en la parte izquierda de la cadena, y el operando derecho en la parte derecha. Aquí hay algunos ejemplos más: + +```php + Kingswood +print_r('Kings' . 'road'); // => Kingsroad +print_r("King's" . 'Landing'); // => King'sLanding +``` + +Las cadenas se pueden concatenar incluso si están escritas con diferentes tipos de comillas. + +Un espacio en blanco es un carácter igual que los demás, por lo que la cantidad de espacios en blanco que se coloque en una cadena será la misma en la cadena resultante: + +```php + King's Landing + +// Colocamos un espacio en blanco en la parte derecha +print_r("King's" . ' Landing'); // => King's Landing +``` diff --git a/modules/25-strings/20-strings-concatenation/es/data.yml b/modules/25-strings/20-strings-concatenation/es/data.yml new file mode 100644 index 00000000..ae3349df --- /dev/null +++ b/modules/25-strings/20-strings-concatenation/es/data.yml @@ -0,0 +1,6 @@ +name: Concatenación +definitions: + - name: Concatenación + description: > + operación que une dos cadenas. Por ejemplo, `print_r("King's " . ' + Landing');` diff --git a/modules/25-strings/20-strings-concatenation/ru/EXERCISE.md b/modules/25-strings/20-strings-concatenation/ru/EXERCISE.md new file mode 100644 index 00000000..a3c3cc1c --- /dev/null +++ b/modules/25-strings/20-strings-concatenation/ru/EXERCISE.md @@ -0,0 +1,7 @@ +Выведите на экран + +``` +Winter came for the House of Frey. +``` + +используя конкатенацию слов. diff --git a/modules/25-strings/20-strings-concatenation/ru/README.md b/modules/25-strings/20-strings-concatenation/ru/README.md new file mode 100644 index 00000000..af5a03b9 --- /dev/null +++ b/modules/25-strings/20-strings-concatenation/ru/README.md @@ -0,0 +1,45 @@ +В веб-разработке программы постоянно оперируют строками. Все, что мы видим на сайтах, так или иначе представлено в виде текста. Этот текст чаще всего динамический — полученный из разных частей, которые соединяются вместе. Операция соединения строк в программировании называется **конкатенацией**. + +Мы уже знаем о математической операции сложения: + +```php + 8 +``` + +Такая программа выведет на экран `8` — результат работы бинарного оператора `+` с операндами `5` и `3`. + +Можно также «сложить» две строки. Такая программа выведет на экран `Dragonstone` — результат работы бинарного оператора `.` с операндами 'Dragon' и 'stone': + +```php + Dragonstone +``` + +https://replit.com/@hexlet/php-basics-strings-concatenation + +Склеивание строк всегда происходит в том же порядке, в котором записаны операнды. Левый операнд становится левой частью строки, а правый — правой. Вот еще несколько примеров: + +```php + Kingswood +print_r('Kings' . 'road'); // => Kingsroad +print_r("King's" . 'Landing'); // => King'sLanding +``` + +Строки можно склеивать, даже если они записаны с разными кавычками. + +Пробел — такой же символ, как и другие, поэтому сколько пробелов поставить в строке — столько и получится в итоговой строке: + +```php + King's Landing + +// Ставим пробел в правой части +print_r("King's" . ' Landing'); // => King's Landing +``` diff --git a/modules/25-strings/20-strings-concatenation/ru/data.yml b/modules/25-strings/20-strings-concatenation/ru/data.yml new file mode 100644 index 00000000..1761d6e3 --- /dev/null +++ b/modules/25-strings/20-strings-concatenation/ru/data.yml @@ -0,0 +1,6 @@ +name: Конкатенация +definitions: + - name: Конкатенация + description: > + операция соединения двух строк. Например, `print_r("King's " . ' + Landing');` diff --git a/modules/25-strings/30-encoding/en/EXERCISE.md b/modules/25-strings/30-encoding/en/EXERCISE.md new file mode 100644 index 00000000..69275dc3 --- /dev/null +++ b/modules/25-strings/30-encoding/en/EXERCISE.md @@ -0,0 +1,16 @@ + +In PHP you can "request" and display any ASCII character. For instance: + +```php +- + conjunto de caracteres codificados con números para representar texto en + formato electrónico. diff --git a/modules/25-strings/30-encoding/ru/EXERCISE.md b/modules/25-strings/30-encoding/ru/EXERCISE.md new file mode 100644 index 00000000..518dd4c4 --- /dev/null +++ b/modules/25-strings/30-encoding/ru/EXERCISE.md @@ -0,0 +1,16 @@ + +В PHP можно «запросить» и вывести на экран любой символ из кодировки ASCII. Например: + +```php +- + набор символов, закодированных с помощью чисел для представления текста в + электронном виде. diff --git a/modules/27-data-types/40-primitive-data-types/en/EXERCISE.md b/modules/27-data-types/40-primitive-data-types/en/EXERCISE.md new file mode 100644 index 00000000..2762f5e6 --- /dev/null +++ b/modules/27-data-types/40-primitive-data-types/en/EXERCISE.md @@ -0,0 +1 @@ +Print the number `-0.304`. diff --git a/modules/27-data-types/40-primitive-data-types/en/README.md b/modules/27-data-types/40-primitive-data-types/en/README.md new file mode 100644 index 00000000..c5d03caf --- /dev/null +++ b/modules/27-data-types/40-primitive-data-types/en/README.md @@ -0,0 +1,34 @@ + +There are different ways to represent data in programs. + +There are **strings** — sets of characters in quote marks, like `"Hello, World!"`. There are **integers** — for example, `7`, `-198`, `0`. These are two different categories of information — two different **types of data**. + +The multiplication operation makes sense for integers, but it makes no sense for strings; why would you want to multiply the word "mom" by the word "notepad"? + +**The data type defines what can be done with the elements from a particular set of elements** + +PHP recognizes types. Therefore, it won't allow us to multiply a string by a string ("text by text"). But it will allow you to multiply an integer by another integer. The existence of types and these restrictions in the language protects programs from accidental errors. + +Unlike strings, numbers don't need to be wrapped in quotes. To print the number 5, all you have to do is write: + +```php +- + Primitive data types are simple types built into the programming language + itself. diff --git a/modules/27-data-types/40-primitive-data-types/es/EXERCISE.md b/modules/27-data-types/40-primitive-data-types/es/EXERCISE.md new file mode 100644 index 00000000..50494b22 --- /dev/null +++ b/modules/27-data-types/40-primitive-data-types/es/EXERCISE.md @@ -0,0 +1 @@ +Imprime en pantalla el número `-0.304`. diff --git a/modules/27-data-types/40-primitive-data-types/es/README.md b/modules/27-data-types/40-primitive-data-types/es/README.md new file mode 100644 index 00000000..bf011a1c --- /dev/null +++ b/modules/27-data-types/40-primitive-data-types/es/README.md @@ -0,0 +1,38 @@ +## Tipos de datos disponibles + +Hay diferentes formas de representar datos en los programas: + +* **Cadenas de texto** - conjuntos de caracteres entre comillas, como `"Hola, Mundo!"` +* **Números enteros** - por ejemplo, `7`, `-198`, `0` + +Estas son dos categorías diferentes de información, dos **tipos de datos** diferentes. + +La operación de multiplicación tiene sentido para los números enteros, pero no tiene sentido para las cadenas de texto. Multiplicar la palabra "mamá" por la palabra "cuaderno" no tiene sentido. El tipo de dato determina qué se puede hacer con los elementos de un conjunto específico. + +El lenguaje de programación reconoce los tipos. Por lo tanto, PHP no nos permitirá multiplicar texto por texto, pero sí permitirá multiplicar un número entero por otro número entero. La presencia de tipos y de tales restricciones en el lenguaje protege a los programas de errores accidentales. + +A diferencia de las cadenas de texto, los números enteros no necesitan estar entre comillas. Para imprimir el número 5, simplemente escriba: + +```php + + [Artículo sobre números + decimales](https://es.wikipedia.org/wiki/N%C3%BAmero_decimal) +definitions: + - name: Tipo de dato + description: >- + conjunto de datos en el código (tipo de información). El tipo determina + qué se puede hacer con los elementos de un conjunto específico. Por + ejemplo, los números enteros, los números racionales, las cadenas de texto + son diferentes tipos de datos. + - name: Tipos de datos primitivos + description: tipos simples incorporados en el propio lenguaje de programación. + - name: Cadena de texto (string) + description: > + tipo de dato que describe un conjunto de caracteres (es decir, texto); por + ejemplo, `'texto'` o `"texto"`. diff --git a/modules/27-data-types/40-primitive-data-types/ru/EXERCISE.md b/modules/27-data-types/40-primitive-data-types/ru/EXERCISE.md new file mode 100644 index 00000000..f795f618 --- /dev/null +++ b/modules/27-data-types/40-primitive-data-types/ru/EXERCISE.md @@ -0,0 +1 @@ +Выведите на экран число `-0.304`. diff --git a/modules/27-data-types/40-primitive-data-types/ru/README.md b/modules/27-data-types/40-primitive-data-types/ru/README.md new file mode 100644 index 00000000..22682b01 --- /dev/null +++ b/modules/27-data-types/40-primitive-data-types/ru/README.md @@ -0,0 +1,40 @@ +## Какие бывают типы данных + +Существуют разные способы представлять данные в программах: + +* **Строки** — наборы символов в кавычках, вроде `"Hello, World!"` +* **Целые числа** — например, `7`, `-198`, `0` + +Это две разные категории информации — два разных **типа данных**. + +Операция умножения имеет смысл для целых чисел, но не имеет смысла для строк. Умножать слово «мама» на слово «блокнот» — бессмыслица. Тип данных определяет, что можно делать с элементами конкретного множества элементов. + +Язык программирования распознает типы. Поэтому PHP не позволит нам умножать текст на текст. Но позволит умножать целое число на другое целое число. Наличие типов и таких ограничений в языке защищает программы от случайных ошибок. + +В отличие от строк, числа оборачивать в кавычки не нужно. Чтобы напечатать число 5, достаточно написать: + +```php + + [Литерал](https://ru.wikipedia.org/wiki/%D0%9B%D0%B8%D1%82%D0%B5%D1%80%D0%B0%D0%BB_(%D0%B8%D0%BD%D1%84%D0%BE%D1%80%D0%BC%D0%B0%D1%82%D0%B8%D0%BA%D0%B0)) + - | + [Статья о дробных числах](https://habrahabr.ru/post/112953/) +definitions: + - name: Тип данных + description: >- + множество данных в коде (разновидность информации). Тип определяет, что + можно делать с элементами конкретного множества. Например, целые числа, + рациональные числа, строки — это разные типы данных. + - name: Примитивные типы данных + description: простые типы, встроенные в сам язык программирования. + - name: Строка (string) + description: > + тип данных, описывающий набор символов (иными словами — текст); например, + `'text'` или `"text"`. diff --git a/modules/27-data-types/50-data-types-weak-typing/en/EXERCISE.md b/modules/27-data-types/50-data-types-weak-typing/en/EXERCISE.md new file mode 100644 index 00000000..dd171e4c --- /dev/null +++ b/modules/27-data-types/50-data-types-weak-typing/en/EXERCISE.md @@ -0,0 +1,2 @@ + +Print the result of the expression: `7 - (-8 - -2)`. Try making 7 a string instead of a number. Experiment with other numbers too. diff --git a/modules/27-data-types/50-data-types-weak-typing/en/README.md b/modules/27-data-types/50-data-types-weak-typing/en/README.md new file mode 100644 index 00000000..f3d8dabb --- /dev/null +++ b/modules/27-data-types/50-data-types-weak-typing/en/README.md @@ -0,0 +1,22 @@ + +We know two different data types: numbers and strings. We could, for example, add numbers, because the addition operation is an operation for the "number" type. + +But what if you add a number to a string? + +```php +print_r(1 + '7'); // => 8 +``` + +Although though `'7'` is a string and not a number, the PHP interpreter gave the answer `8`, as if we were adding two numbers. When PHP sees a type mismatch, it tries to convert the information itself. In this case, it converted the string `'7'` to the number `7`, and then happily added `1` and `7`. + +Not all languages can do this. PHP is a language with **weak typing**. It recognizes different data types (numbers, strings, etc.), but doesn't use them too strictly, trying to convert data when it seems reasonable. + +In **strongly typed** languages, adding a number to a string won't work. + +PHP was created for the internet, and on the internet, all information is strings. Even when you type a phone number or a birth year on a website, that information goes to the server as a string, not as a number. So the designers of the language decided that automatic type conversion was the best option. + +This tacit automatic type conversion is indeed convenient. But in practice, this feature causes a lot of errors, which are difficult to find. The code may work or fail, depending on whether you're lucky enough for the automatic conversion to have been done correctly A programmer may not notice this immediately. + +You'll encounter these cases more than once in future tasks. You'll often ask, "Why doesn't my code work the way I expect?". + +Weak typing is a red thread running through all PHP development. diff --git a/modules/27-data-types/50-data-types-weak-typing/en/data.yml b/modules/27-data-types/50-data-types-weak-typing/en/data.yml new file mode 100644 index 00000000..88298722 --- /dev/null +++ b/modules/27-data-types/50-data-types-weak-typing/en/data.yml @@ -0,0 +1 @@ +name: Weak typing diff --git a/modules/27-data-types/50-data-types-weak-typing/es/EXERCISE.md b/modules/27-data-types/50-data-types-weak-typing/es/EXERCISE.md new file mode 100644 index 00000000..eebb413d --- /dev/null +++ b/modules/27-data-types/50-data-types-weak-typing/es/EXERCISE.md @@ -0,0 +1 @@ +Muestra en pantalla el resultado de la expresión: `7 - (-8 - -2)`. Intenta hacer que el número 7 sea una cadena en lugar de un número. Experimenta también con otros números. diff --git a/modules/27-data-types/50-data-types-weak-typing/es/README.md b/modules/27-data-types/50-data-types-weak-typing/es/README.md new file mode 100644 index 00000000..7ba014ce --- /dev/null +++ b/modules/27-data-types/50-data-types-weak-typing/es/README.md @@ -0,0 +1,17 @@ +Podíamos sumar números porque la operación de suma es una operación para el tipo "número". Y si aplicamos esta operación a un número y una cadena: + +```php +print_r(1 + '7'); // => 8 +``` + +`'7'` es una cadena, no un número, pero el intérprete de PHP devuelve `8`, como si estuviéramos sumando dos números. Cuando PHP encuentra una incompatibilidad de tipos, intenta convertir la información por sí mismo. En este caso, convirtió la cadena `'7'` en el número `7` y luego sumó `1` y `7`. + +No todos los lenguajes hacen esto. PHP es un lenguaje con **tipado débil**. Conoce la existencia de diferentes tipos, pero no los trata de manera estricta. Intenta convertir la información cuando parece razonable. + +En los lenguajes con **tipado fuerte**, no se puede sumar un número y una cadena. + +PHP fue creado para Internet, y en Internet toda la información es una cadena. Incluso cuando ingresamos un número de teléfono o una fecha de nacimiento en un sitio web, esa información llega al servidor como una cadena, no como un número. Por eso, los autores del lenguaje decidieron que convertir automáticamente los tipos es correcto y conveniente. + +Esta conversión automática e implícita de tipos es realmente conveniente. Pero en la práctica, esta característica del lenguaje crea muchos errores y problemas difíciles de encontrar. El código puede funcionar a veces y otras veces no. Esto depende de si la conversión automática tuvo "suerte" en un caso particular. El programador no se dará cuenta de esto de inmediato. + +En futuras tareas nos encontraremos con este comportamiento más de una vez. A menudo surgirá la pregunta "¿por qué mi código no funciona como espero?". diff --git a/modules/27-data-types/50-data-types-weak-typing/es/data.yml b/modules/27-data-types/50-data-types-weak-typing/es/data.yml new file mode 100644 index 00000000..31b43d9f --- /dev/null +++ b/modules/27-data-types/50-data-types-weak-typing/es/data.yml @@ -0,0 +1,2 @@ +name: Tipado débil +tips: [] diff --git a/modules/27-data-types/50-data-types-weak-typing/ru/EXERCISE.md b/modules/27-data-types/50-data-types-weak-typing/ru/EXERCISE.md new file mode 100644 index 00000000..d6cb0377 --- /dev/null +++ b/modules/27-data-types/50-data-types-weak-typing/ru/EXERCISE.md @@ -0,0 +1 @@ +Выведите на экран результат выражения: `7 - (-8 - -2)`. Попробуйте сделать число 7 не числом, а строкой. Поэкспериментируйте с другими числами тоже. diff --git a/modules/27-data-types/50-data-types-weak-typing/ru/README.md b/modules/27-data-types/50-data-types-weak-typing/ru/README.md new file mode 100644 index 00000000..2a6ceb3b --- /dev/null +++ b/modules/27-data-types/50-data-types-weak-typing/ru/README.md @@ -0,0 +1,17 @@ +Мы могли складывать числа, потому что операция сложения — это операция для типа «числа». А если применить эту операцию к числу и строке: + +```php +print_r(1 + '7'); // => 8 +``` + +`'7'` — это строка, а не число, при этом интерпретатор PHP выдал ответ `8`, как если бы мы складывали два числа. Когда PHP видит несоответствие типов, он сам пытается преобразовать информацию. В данном случае он преобразовал строку `'7'` в число `7`, а потом сложил `1` и `7`. + +Не все языки так делают. PHP — это язык со **слабой типизацией**. Он знает о существовании разных типов, но относится к их использованию не строго. Он пытается преобразовывать информацию, когда это кажется разумным. + +В языках со **строгой типизацией** сложить число со строкой не получится. + +PHP был создан для интернета, а в интернете вся информация — это строки. Даже когда мы вводим на сайте номер телефона или год рождения, на сервер эта информация поступает не как числа, а как строки. Поэтому авторы языка решили, что автоматически преобразовывать типы — правильно и удобно. + +Такое автоматическое неявное преобразование типов с одной стороны и правда удобно. Но на практике это свойство языка создает множество ошибок и проблем, которые трудно найти. Код может иногда работать, а иногда не работать. Это зависит от того, «повезло» ли в конкретном случае с автоматическим преобразованием. Программист это заметит не сразу. + +В дальнейших заданиях мы будем встречаться с таким поведением не раз. Часто будет возникать вопрос «почему мой код работает не так, как я ожидаю?». diff --git a/modules/27-data-types/50-data-types-weak-typing/ru/data.yml b/modules/27-data-types/50-data-types-weak-typing/ru/data.yml new file mode 100644 index 00000000..923d4c50 --- /dev/null +++ b/modules/27-data-types/50-data-types-weak-typing/ru/data.yml @@ -0,0 +1,2 @@ +name: Слабая типизация +tips: [] diff --git a/modules/27-data-types/55-type-conversion/en/EXERCISE.md b/modules/27-data-types/55-type-conversion/en/EXERCISE.md new file mode 100644 index 00000000..c87e3fdb --- /dev/null +++ b/modules/27-data-types/55-type-conversion/en/EXERCISE.md @@ -0,0 +1,2 @@ + +Output the string 2 times from the number 2.9 and the string `times` using type conversion and concatenation. This requires two conversions: first, to an integer and then to a string diff --git a/modules/27-data-types/55-type-conversion/en/README.md b/modules/27-data-types/55-type-conversion/en/README.md new file mode 100644 index 00000000..ae95fbd3 --- /dev/null +++ b/modules/27-data-types/55-type-conversion/en/README.md @@ -0,0 +1,41 @@ + +Type conversion is a fairly common operation in web development. On the one hand, you can rely on weak typing to perform it, on the other hand, in many situations it's better to do the conversion explicitly, using special syntax. This code is clearer and more predictable. + +```php + 5 +``` + +Type conversion can be used within compound expressions: + +```php + + Это 5 + + +In more complex situations (when using functions that are passed later) multiple conversions are encountered: `(string) (5 + ((int) '4'))`. The procedure for calculating this expression is as follows: + +```php + 'Esto es 5' +``` + +La conversión explícita de tipos funciona de la siguiente manera: se especifica el tipo deseado antes del valor entre paréntesis. Como resultado, el valor a la derecha se convierte en un valor de otro tipo, especificado a la izquierda entre paréntesis. Hasta ahora, solo estamos familiarizados con dos tipos, pero la conversión funciona para cualquier tipo. + +En situaciones más complejas, al utilizar funciones que veremos más adelante, se encuentran conversiones múltiples: `(string) (5 + ((int) '4'))`. El orden de evaluación de esta expresión es el siguiente: + +```php + 'Это 5' +``` + +Явное преобразование типа работает так: перед значением в скобках указывается желаемый тип. В результате значение справа преобразуется в значение другого типа, указанного слева в скобках. На текущий момент мы знакомы только с двумя типами, но преобразование работает для любого типа. + +В более сложных ситуациях при использовании функций, которые будем проходить позже, встречаются множественные преобразования: `(string) (5 + ((int) '4'))`. Порядок вычисления этого выражения следующий: + +```php + + Father! + Father! + + +Any set of valid characters can be used for a variable name, which includes letters of the English alphabet, numbers, and the `_`. Note that you can't place a digit at the beginning of a name. Variable names are case-sensitive, which means that `hello` and `heLLo` are two different names and thus two distinct variables. Case is important in PHP, never forget it. + +The number of variables you can create isn't limited in any way, large programs contain tens and hundreds of thousands of variable names: + +```php + ¡Padre! +// => ¡Padre! +``` + +En la línea `$greeting = '¡Padre!'`, el valor `'¡Padre!'` se asigna a la variable con el nombre `$greeting`. En PHP, los nombres de las variables comienzan con el símbolo *$*. Como resultado, la variable apunta a los datos que se han almacenado en ella. + +Una vez que se ha creado la variable, podemos comenzar a usarla. + +## Uso de una variable + +La variable se inserta en los lugares donde solíamos tener nuestra palabra. Durante la ejecución, el intérprete llega a la línea `print_r($greeting);` y reemplaza la variable por su contenido, y luego ejecuta el código. + +Para el nombre de la variable, se puede utilizar cualquier conjunto de caracteres válidos, que incluyen letras del alfabeto inglés, números y el carácter `_`. Sin embargo, no se puede colocar un número al principio. Los nombres de las variables en PHP distinguen entre mayúsculas y minúsculas, es decir, `hello` y `heLLo` son dos nombres diferentes, lo que significa que son dos variables diferentes. La distinción entre mayúsculas y minúsculas es importante en PHP, así que no olvides tenerlo en cuenta. + +No hay límite en la cantidad de variables que se pueden crear. Los programas grandes contienen decenas o incluso cientos de miles de nombres de variables. Para facilitar el análisis del programa, es conveniente crear las variables lo más cerca posible del lugar donde se utilizan. diff --git a/modules/30-variables/10-definition/es/data.yml b/modules/30-variables/10-definition/es/data.yml new file mode 100644 index 00000000..8d15d493 --- /dev/null +++ b/modules/30-variables/10-definition/es/data.yml @@ -0,0 +1,7 @@ +name: ¿Qué es una variable? +tips: [] +definitions: + - name: Variable + description: >- + una forma de almacenar información y darle un nombre para su uso posterior + en el código. diff --git a/modules/30-variables/10-definition/ru/EXERCISE.md b/modules/30-variables/10-definition/ru/EXERCISE.md new file mode 100644 index 00000000..1b7393ae --- /dev/null +++ b/modules/30-variables/10-definition/ru/EXERCISE.md @@ -0,0 +1 @@ +Создайте переменную с именем `$motto` и содержимым `What Is Dead May Never Die!`. Распечатайте содержимое переменной. diff --git a/modules/30-variables/10-definition/ru/README.md b/modules/30-variables/10-definition/ru/README.md new file mode 100644 index 00000000..981b89d3 --- /dev/null +++ b/modules/30-variables/10-definition/ru/README.md @@ -0,0 +1,34 @@ +Допустим, нам нужно напечатать на экран слово «Father!» два раза или даже пять раз. Эту задачу можно решить так: + +```php + Father! +// => Father! +``` + +В строчке `$greeting = 'Father!'` значение `'Father!'` присваивается переменной с именем `$greeting`. В PHP имена переменных начинаются со знака *$*. В итоге переменная указывает на данные, которые были в нее записаны. + +Когда переменная создана, можно начать ее использовать. + +## Использование переменной + +Переменная подставляется в те места, где раньше стояло наше слово. Во время выполнения интерпретатор доходит до строчки `print_r($greeting);` и подставляет вместо переменной ее содержимое, а затем выполняет код. + +Для имени переменной используется любой набор допустимых символов, к которым относятся буквы английского алфавита, цифры, знак `_`. При этом цифру нельзя ставить в начале. Имена переменных регистрозависимы, то есть имя `hello` и имя `heLLo` — это два разных имени, значит, это две переменные. Регистр в PHP имеет важное значение, не стоит забывать про него. + +Количество создаваемых переменных не ограничено, большие программы содержат десятки и сотни тысяч имен переменных. Для удобства анализа программы переменные принято создавать как можно ближе к тому месту, где они используются. diff --git a/modules/30-variables/10-definition/ru/data.yml b/modules/30-variables/10-definition/ru/data.yml new file mode 100644 index 00000000..be88755a --- /dev/null +++ b/modules/30-variables/10-definition/ru/data.yml @@ -0,0 +1,7 @@ +name: Что такое переменная +tips: [] +definitions: + - name: Переменная + description: >- + способ сохранить информацию и дать ей имя для последующего использования в + коде. diff --git a/modules/30-variables/12-change/en/EXERCISE.md b/modules/30-variables/12-change/en/EXERCISE.md new file mode 100644 index 00000000..8f0cdd2d --- /dev/null +++ b/modules/30-variables/12-change/en/EXERCISE.md @@ -0,0 +1,2 @@ + +In this exercise, a variable has been defined with a string inside it. Override the value of this variable and assign it a string in which the characters of the original string are arranged in reverse order. diff --git a/modules/30-variables/12-change/en/README.md b/modules/30-variables/12-change/en/README.md new file mode 100644 index 00000000..36c77a13 --- /dev/null +++ b/modules/30-variables/12-change/en/README.md @@ -0,0 +1,21 @@ + +The word "variable" itself indicates that it can be changed. Indeed, the value of a variable can change throughout your code. + +```php + ¡Padre! + +$greeting = '¡Madre!'; +print_r($greeting); // => ¡Madre! +``` + +El nombre se mantiene igual, pero los datos internos cambian. Las variables en PHP no requieren una declaración especial. En su lugar, la variable se declara cuando se utiliza por primera vez en el programa. + +Nunca se puede estar seguro de lo que está almacenado dentro de una variable. Para estar tranquilo, es necesario analizar el código que se encuentra antes de la variable. Esto es lo que hacen los desarrolladores durante la depuración, cuando intentan entender por qué el programa no funciona o no funciona como se esperaba. + +Las variables no cambian con frecuencia. Por lo general, se utilizan para almacenar información. diff --git a/modules/30-variables/12-change/es/data.yml b/modules/30-variables/12-change/es/data.yml new file mode 100644 index 00000000..99420c3f --- /dev/null +++ b/modules/30-variables/12-change/es/data.yml @@ -0,0 +1,10 @@ +name: Cambio de variable +tips: + - > + Si hay una línea `// BEGIN` y `// END` en el editor, el código debe + escribirse entre estas líneas. +definitions: + - name: Variable + description: >- + una forma de almacenar información y darle un nombre para su uso posterior + en el código. diff --git a/modules/30-variables/12-change/ru/EXERCISE.md b/modules/30-variables/12-change/ru/EXERCISE.md new file mode 100644 index 00000000..b503e50d --- /dev/null +++ b/modules/30-variables/12-change/ru/EXERCISE.md @@ -0,0 +1 @@ +В упражнении определена переменная, внутри которой строка. Переопределите значение этой переменной и присвойте ей строку, в которой расположите символы первоначальной строки в обратном порядке. diff --git a/modules/30-variables/12-change/ru/README.md b/modules/30-variables/12-change/ru/README.md new file mode 100644 index 00000000..50bbb1fb --- /dev/null +++ b/modules/30-variables/12-change/ru/README.md @@ -0,0 +1,18 @@ +Со временем внутри программы значения переменных могут изменяться: + +```php + Father! + +$greeting = 'Mother!'; +print_r($greeting); // => Mother! +``` + +Имя осталось тем же, но внутри другие данные. Переменные в PHP не требуют специального объявления. Вместо этого переменная объявляется при первом ее использовании в программе. + +Никогда нельзя быть точно уверенным, что записано внутри переменной. Чтобы быть спокойным, нужно проанализировать код, который находится перед переменной. Этим занимаются разработчики во время отладки, когда пытаются разобраться, почему программа не работает или работает не так, как задумано. + +Переменные меняются нечасто. Обычно их используют, чтобы хранить. diff --git a/modules/30-variables/12-change/ru/data.yml b/modules/30-variables/12-change/ru/data.yml new file mode 100644 index 00000000..259c4339 --- /dev/null +++ b/modules/30-variables/12-change/ru/data.yml @@ -0,0 +1,10 @@ +name: Изменение переменной +tips: + - > + Если в редакторе есть запись `// BEGIN` и `// END`, то код нужно писать + между этими строчками. +definitions: + - name: Переменная + description: >- + способ сохранить информацию и дать ей имя для последующего использования в + коде. diff --git a/modules/30-variables/13-variables-naming/en/EXERCISE.md b/modules/30-variables/13-variables-naming/en/EXERCISE.md new file mode 100644 index 00000000..8207003a --- /dev/null +++ b/modules/30-variables/13-variables-naming/en/EXERCISE.md @@ -0,0 +1,2 @@ + +Create a variable describing the number of my brothers and assign it the value *2*. Print its contents. Then compare your name with the name used in the teacher's solution. diff --git a/modules/30-variables/13-variables-naming/en/README.md b/modules/30-variables/13-variables-naming/en/README.md new file mode 100644 index 00000000..b8cacbb6 --- /dev/null +++ b/modules/30-variables/13-variables-naming/en/README.md @@ -0,0 +1,19 @@ + + +Let's imagine that the program from the last lesson looks like this: + +```php + + [Code Complete: Naming in + Programming](https://hexlet.io/blog/posts/code-complete-naming-in-programming) diff --git a/modules/30-variables/13-variables-naming/es/EXERCISE.md b/modules/30-variables/13-variables-naming/es/EXERCISE.md new file mode 100644 index 00000000..cfdf691e --- /dev/null +++ b/modules/30-variables/13-variables-naming/es/EXERCISE.md @@ -0,0 +1 @@ +Crea una variable que describa la cantidad de mis hermanos y asígnele el valor *2*. Imprime el contenido de la variable. Luego, compara tu nombre con el nombre utilizado en la solución del profesor. diff --git a/modules/30-variables/13-variables-naming/es/README.md b/modules/30-variables/13-variables-naming/es/README.md new file mode 100644 index 00000000..f93d51bf --- /dev/null +++ b/modules/30-variables/13-variables-naming/es/README.md @@ -0,0 +1,17 @@ +En esta lección hablaremos sobre la nomenclatura. Comenzaremos estudiando un ejemplo. Veamos el siguiente programa: + +```php + + [Errores en la nomenclatura de + variables](https://codica.la/blog/naming-errors-1) +definitions: [] diff --git a/modules/30-variables/13-variables-naming/ru/EXERCISE.md b/modules/30-variables/13-variables-naming/ru/EXERCISE.md new file mode 100644 index 00000000..1b055a6d --- /dev/null +++ b/modules/30-variables/13-variables-naming/ru/EXERCISE.md @@ -0,0 +1 @@ +Создайте переменную, описывающую количество моих братьев, и присвойте ей значение *2*. Распечатайте содержимое переменной. Затем сравните своё имя с именем, которое используется в учительском решении. diff --git a/modules/30-variables/13-variables-naming/ru/README.md b/modules/30-variables/13-variables-naming/ru/README.md new file mode 100644 index 00000000..21792a4c --- /dev/null +++ b/modules/30-variables/13-variables-naming/ru/README.md @@ -0,0 +1,17 @@ +В этом уроке мы поговорим об именовании. Изучать эту тему мы начнем с примера. Посмотрим на такую программу: + +```php + + [Именование в + программировании](https://ru.hexlet.io/blog/posts/naming-in-programming) + - > + [Ошибки в именовании + переменных](https://ru.hexlet.io/blog/posts/naming-errors-1) +definitions: [] diff --git a/modules/30-variables/14-errors/en/EXERCISE.md b/modules/30-variables/14-errors/en/EXERCISE.md new file mode 100644 index 00000000..3325fbfd --- /dev/null +++ b/modules/30-variables/14-errors/en/EXERCISE.md @@ -0,0 +1,8 @@ + +Find an undeclared variable in the program and declare it by assigning the value `'Dragon'` to it. + +After running the program, the result on the screen should look like this: + +
+Targaryen and Dragon
+
diff --git a/modules/30-variables/14-errors/en/README.md b/modules/30-variables/14-errors/en/README.md new file mode 100644 index 00000000..c24131df --- /dev/null +++ b/modules/30-variables/14-errors/en/README.md @@ -0,0 +1,13 @@ + +The main rule is that a variable must be declared before it can be used. If you do it later, the program simply won't work. + +```php + +Targaryen and Dragon + diff --git a/modules/30-variables/14-errors/es/README.md b/modules/30-variables/14-errors/es/README.md new file mode 100644 index 00000000..1a98d9ab --- /dev/null +++ b/modules/30-variables/14-errors/es/README.md @@ -0,0 +1,13 @@ +Es necesario declarar una variable antes de utilizarla. Si se hace después, el programa no funcionará: + +```php + +Targaryen and Dragon + diff --git a/modules/30-variables/14-errors/ru/README.md b/modules/30-variables/14-errors/ru/README.md new file mode 100644 index 00000000..ee476413 --- /dev/null +++ b/modules/30-variables/14-errors/ru/README.md @@ -0,0 +1,13 @@ +Переменную нужно объявить до ее использования. Если сделать это позже, то программа не заработает: + +```php + +The price is 431.875 yuans + + +Any variable can be part of any expression. At the moment of calculation, its value is substituted for the variable name. + +The interpreter calculates the value of `$dollarsCount` before this variable is used in other expressions. When it comes time to use a variable, PHP "knows" the value because it's already computed it. diff --git a/modules/30-variables/15-expressions/en/data.yml b/modules/30-variables/15-expressions/en/data.yml new file mode 100644 index 00000000..2e1b8645 --- /dev/null +++ b/modules/30-variables/15-expressions/en/data.yml @@ -0,0 +1,5 @@ +name: Expressions in definitions +tips: + - > + You can use `\n` between the withdrawal of dollars and yuans to go to a new + line. diff --git a/modules/30-variables/15-expressions/es/EXERCISE.md b/modules/30-variables/15-expressions/es/EXERCISE.md new file mode 100644 index 00000000..3b21b448 --- /dev/null +++ b/modules/30-variables/15-expressions/es/EXERCISE.md @@ -0,0 +1,8 @@ +Escribe un programa que tome la cantidad inicial de euros de la variable `$cantidadEuros`, convierta los euros a dólares y muestre el valor en pantalla. Luego, el programa debe convertir el valor obtenido a yuanes y mostrar el resultado en una nueva línea. + +Ejemplo de salida para 100 euros: + +``` +125 +863.75 +``` diff --git a/modules/30-variables/15-expressions/es/README.md b/modules/30-variables/15-expressions/es/README.md new file mode 100644 index 00000000..f13e9494 --- /dev/null +++ b/modules/30-variables/15-expressions/es/README.md @@ -0,0 +1,69 @@ +Las variables son útiles no solo para almacenar y reutilizar información. También son necesarias para simplificar cálculos complejos. En esta lección aprenderemos a hacerlo. + +## Usando una expresión + +Supongamos que necesitamos convertir euros a yuanes a través de dólares. Estas conversiones a través de una moneda intermedia son comunes en los bancos al realizar compras en el extranjero. + +Primero, convertiremos 50 euros a dólares. Supongamos que un euro equivale a 1.25 dólares: + +```php + "Kingsroad" + +// Concatenamos una cadena de texto y una variable que contiene una cadena de texto +$primera = "Kings"; +$que = $primera . "road"; +print_r($que); // => "Kingsroad" + +// Concatenamos dos variables que contienen cadenas de texto +$ultima = 'road'; +$que = $primera . $ultima; +print_r($que); // => "Kingsroad" +``` diff --git a/modules/30-variables/15-expressions/es/data.yml b/modules/30-variables/15-expressions/es/data.yml new file mode 100644 index 00000000..5d569242 --- /dev/null +++ b/modules/30-variables/15-expressions/es/data.yml @@ -0,0 +1,5 @@ +name: Expresiones en definiciones +tips: + - > + Para hacer un salto de línea, puedes usar `\n` entre la impresión de los + dólares y los yuanes. diff --git a/modules/30-variables/15-expressions/ru/EXERCISE.md b/modules/30-variables/15-expressions/ru/EXERCISE.md new file mode 100644 index 00000000..203cc69c --- /dev/null +++ b/modules/30-variables/15-expressions/ru/EXERCISE.md @@ -0,0 +1,12 @@ +Напишите программу, которая берёт исходное количество евро из переменной `$eurosCount`, переводит евро в доллары и выводит значение на экран. Затем программа полученное значение переводит в юани и выводит результат на новой строчке. + +Пример вывода для 100 евро: + +``` +125 +863.75 +``` + +Считаем, что: +- 1 евро = 1.25 долларов +- 1 доллар = 6.91 юаней diff --git a/modules/30-variables/15-expressions/ru/README.md b/modules/30-variables/15-expressions/ru/README.md new file mode 100644 index 00000000..87d34d00 --- /dev/null +++ b/modules/30-variables/15-expressions/ru/README.md @@ -0,0 +1,69 @@ +Переменные полезны не только для хранения и переиспользования информации. Также они нужны, чтобы упрощать сложные вычисления. В этом уроке мы научимся делать это. + +## Используем выражение + +Допустим, нам нужно перевести евро в юани через доллары. Подобные конвертации через промежуточную валюту часто делают банки при покупках за рубежом. + +Для начала переведем 50 евро в доллары. Допустим, один евро равен 1.25 доллара: + +```php + "Kingsroad" + +// Конкатенируем строку и переменную, в которой записана строка +$first = "Kings"; +$what = $first . "road"; +print_r($what); // => "Kingsroad" + +// Конкатенируем две переменные, в которых записаны строки +$last = 'road'; +$what = $first . $last; +print_r($what); // => "Kingsroad" +``` diff --git a/modules/30-variables/15-expressions/ru/data.yml b/modules/30-variables/15-expressions/ru/data.yml new file mode 100644 index 00000000..4a0bb2e1 --- /dev/null +++ b/modules/30-variables/15-expressions/ru/data.yml @@ -0,0 +1,4 @@ +name: Выражения в определениях +tips: + - | + Для перевода строчки можно использовать `\n` между выводом долларов и юаней. diff --git a/modules/30-variables/18-concatenation/en/EXERCISE.md b/modules/30-variables/18-concatenation/en/EXERCISE.md new file mode 100644 index 00000000..9f398d11 --- /dev/null +++ b/modules/30-variables/18-concatenation/en/EXERCISE.md @@ -0,0 +1,18 @@ + +Websites are constantly sending emails to their users. One common task is to automatically send a personalized email with the user's name in the header. If you store a person's name as a string somewhere in a website database, the task of generating the header boils down to concatenation. For instance, you have to concatenate the string `Hello` with a string containing their name. + +Write a program that'll create a header and a body of the email using ready-made variables and print the resulting strings. + +For the header, use the `$firstName` and `$greeting` variables for the, and a comma and exclamation point. Print it in the correct order. + +Use the variables `$info` and `$intro` for the body of the email, with the second sentence on a new line. + +The result should look like this: + +
+Hello, Joffrey!
+Here is important information about your account security.
+We couldn't verify you mother's maiden name.
+
+ +Try and do it using just two `print_r()` statements. diff --git a/modules/30-variables/18-concatenation/en/README.md b/modules/30-variables/18-concatenation/en/README.md new file mode 100644 index 00000000..6b805419 --- /dev/null +++ b/modules/30-variables/18-concatenation/en/README.md @@ -0,0 +1,32 @@ + +Let's try concatenating variables so that we can reinforce the previous topic a little. The syntax is still the same, we know how to concatenate (combine) two strings: + +```php + "Kingsroad" +``` + +… which means we can concatenate the string and the variable that the string has been written to: + +```php + "Kingsroad" +``` + +… and even concatenate two variables with strings in them: + +```php + "Kingsroad" +``` diff --git a/modules/30-variables/18-concatenation/en/data.yml b/modules/30-variables/18-concatenation/en/data.yml new file mode 100644 index 00000000..4abbe438 --- /dev/null +++ b/modules/30-variables/18-concatenation/en/data.yml @@ -0,0 +1,8 @@ +name: Variables and concatenation +tips: + - > + Consider how you should concatenate the variables (Which string? What + order?) to get the two-line output of the email body. + - > + Remember that you can create a string containing only the escape sequence + `\n`. diff --git a/modules/30-variables/18-concatenation/es/EXERCISE.md b/modules/30-variables/18-concatenation/es/EXERCISE.md new file mode 100644 index 00000000..5e5989e1 --- /dev/null +++ b/modules/30-variables/18-concatenation/es/EXERCISE.md @@ -0,0 +1,18 @@ + +Los sitios web constantemente envían correos electrónicos a sus usuarios. Una tarea típica es enviar automáticamente un correo electrónico personalizado, donde el nombre de usuario estará en el asunto. Si el nombre del usuario se encuentra en algún lugar de la base de datos del sitio web como una cadena, la tarea de generar el asunto se reduce a la concatenación: por ejemplo, necesitas unir la cadena `Hello` con la cadena que contiene el nombre. + +Escribe un programa que genere el asunto y el cuerpo del correo electrónico, utilizando las variables proporcionadas, y muestre las cadenas resultantes en la pantalla. + +Para el asunto, utiliza las variables `$firstName` y `$greeting`, seguido de una coma y un signo de exclamación. Muestra esto en la pantalla en el orden correcto. + +Para el cuerpo del correo electrónico, utiliza las variables `$info` e `$intro`, con la segunda oración en una nueva línea. + +El resultado en la pantalla debería lucir así: + +
+Hello, Joffrey!
+Here is important information about your account security.
+We couldn't verify you mother's maiden name.
+
+ +Completa la tarea utilizando solamente dos `print_r()`. diff --git a/modules/30-variables/18-concatenation/es/README.md b/modules/30-variables/18-concatenation/es/README.md new file mode 100644 index 00000000..5d95a658 --- /dev/null +++ b/modules/30-variables/18-concatenation/es/README.md @@ -0,0 +1,32 @@ + +Para reforzar el tema anterior, intentemos usar variables con concatenación. Sintácticamente, nada cambia: sabemos cómo concatenar (unir) dos cadenas: + +```php + "CaminodeReyes" +``` + +... y por lo tanto, podemos concatenar una cadena y una variable que contiene una cadena: + +```php + "CaminodeReyes" +``` + +... e incluso concatenar dos variables que contienen cadenas: + +```php + "CaminodeReyes" +``` diff --git a/modules/30-variables/18-concatenation/es/data.yml b/modules/30-variables/18-concatenation/es/data.yml new file mode 100644 index 00000000..f702d672 --- /dev/null +++ b/modules/30-variables/18-concatenation/es/data.yml @@ -0,0 +1,8 @@ +name: Variables y Concatenación +tips: + - > + Piensa en qué cadena y en qué orden debes concatenar las variables para + obtener una salida de dos líneas para el cuerpo del correo electrónico. + - > + Recuerda que puedes crear una cadena que contenga solo la secuencia de + control `\n`. diff --git a/modules/30-variables/18-concatenation/ru/EXERCISE.md b/modules/30-variables/18-concatenation/ru/EXERCISE.md new file mode 100644 index 00000000..1041084c --- /dev/null +++ b/modules/30-variables/18-concatenation/ru/EXERCISE.md @@ -0,0 +1,18 @@ + +Сайты постоянно посылают письма своим пользователям. Типичная задача — сделать автоматическую отправку персонального письма, где в заголовке будет имя пользователя. Если где-то в базе сайта хранится имя человека в виде строки, то задача генерации заголовка сводится к конкатенации: например, нужно склеить строку `Здравствуйте` со строкой, где записано имя. + +Напишите программу, которая будет генерировать заголовок и тело письма, используя уже готовые переменные, и выводить получившиеся строки на экран. + +Для заголовка используйте переменные `$firstName` и `$greeting`, запятую и восклицательный знак. Выведите это на экран в правильном порядке. + +Для тела письма используйте переменные `$info` и `$intro`, при этом второе предложение должно быть на новой строке. + +Результат на экране будет выглядеть так: + +
+Hello, Joffrey!
+Here is important information about your account security.
+We couldn't verify you mother's maiden name.
+
+ +Выполните задание, используя только два `print_r()`. diff --git a/modules/30-variables/18-concatenation/ru/README.md b/modules/30-variables/18-concatenation/ru/README.md new file mode 100644 index 00000000..43250d3c --- /dev/null +++ b/modules/30-variables/18-concatenation/ru/README.md @@ -0,0 +1,32 @@ + +Для закрепления предыдущей темы попробуем использовать переменные с конкатенацией. Синтаксически ничего не меняется: мы умеем конкатенировать (склеивать) две строки: + +```php + "Kingsroad" +``` + +… а значит сумеем конкатенировать строку и одну переменную, в которой записана строка: + +```php + "Kingsroad" +``` + +… и даже конкатенировать две переменные, в которых записаны строки: + +```php + "Kingsroad" +``` diff --git a/modules/30-variables/18-concatenation/ru/data.yml b/modules/30-variables/18-concatenation/ru/data.yml new file mode 100644 index 00000000..5bfc0b79 --- /dev/null +++ b/modules/30-variables/18-concatenation/ru/data.yml @@ -0,0 +1,8 @@ +name: Переменные и конкатенация +tips: + - > + Подумайте, с какой строкой и в каком порядке нужно склеивать переменные, + чтобы получить такой двухстрочный вывод тела письма. + - > + Помните, что можно создать строку, которая содержит только управляющую + последовательность `\n`. diff --git a/modules/30-variables/19-naming-style/en/EXERCISE.md b/modules/30-variables/19-naming-style/en/EXERCISE.md new file mode 100644 index 00000000..8f46657a --- /dev/null +++ b/modules/30-variables/19-naming-style/en/EXERCISE.md @@ -0,0 +1,4 @@ + +Create two variables named "first number" and "second number" using lowerCamelCase. Write the number `1.10`, to the first variable and `-100` to the second. Print the product of the numbers written to the resulting variables. + +The code will work with any name, and we only check the printed result, so the task is up to you. diff --git a/modules/30-variables/19-naming-style/en/README.md b/modules/30-variables/19-naming-style/en/README.md new file mode 100644 index 00000000..8ad27fed --- /dev/null +++ b/modules/30-variables/19-naming-style/en/README.md @@ -0,0 +1,17 @@ + +`$greeting` is an example of a simple name, but not all names are that simple. Often, they're a combination of several words. For example, "user password". Different languages have different naming styles for variables. + +There are three main variable naming conventions, which are sometimes combined. These conventions apply to variable names consisting of several words: + +* kebab-case — a hyphen separates the parts of the name. For example, `my-super-var`. +* snake_case — an underscore is used as a separator. For example, `my_super_var`. +* CamelCase — each word in the name is capitalized. For example, `MySuperVar`. +* lowerCamelCase — each word is capitalized except the first. For example, `mySuperVar`. + +PHP uses CamelCase and its variation lowerCamelCase, where the first letter of the first word is lowercase. We use lowerCamelCase for variables. This means that names are joined together, with all but the first word capitalized: `$userName`. With three words, it looks like this: `$mySuperVariable`. + +Over time, by digging through other people's code, you'll develop the right concepts for naming. + +Names should not only convey meaning, but also correspond to syntactic rules, which aren't usually checked by the language, but are still needed during development. Program writing in today's world is a team effort, and for better teamwork, code should be written in a unified style. Every language has its own rules. PHP has been in chaos for a long time. And the language itself is riddled with contradictions, and not only with names. You will encounter this in the following lessons and in real work. A [coding standard](https://www.php-fig.org/psr/psr-1/), for PHP only appeared relatively recently, and everyone is striving to meet it one way or another. Standards describe multiple aspects. We recommend making a habit of looking at the standard and writing code according to it from the very beginning. + +Fortunately, nowadays, you don't need to remember all the rules from the standard, because there are special programs that check the code automatically and report violations. These programs are called **linters**, and you'll start using them later when you have a little more experience. diff --git a/modules/30-variables/19-naming-style/en/data.yml b/modules/30-variables/19-naming-style/en/data.yml new file mode 100644 index 00000000..69e09706 --- /dev/null +++ b/modules/30-variables/19-naming-style/en/data.yml @@ -0,0 +1,4 @@ +name: Variable naming +definitions: + - name: A coding standard + description: is a set of syntactic and stylistic rules for writing code. diff --git a/modules/30-variables/19-naming-style/es/EXERCISE.md b/modules/30-variables/19-naming-style/es/EXERCISE.md new file mode 100644 index 00000000..d5e6bef6 --- /dev/null +++ b/modules/30-variables/19-naming-style/es/EXERCISE.md @@ -0,0 +1,3 @@ +Crea dos variables con los nombres "primer número" y "segundo número" en inglés, utilizando lowerCamelCase. Asigna el número `1.10` a la primera variable y `-100` a la segunda. Imprime en pantalla el producto de los números almacenados en las variables resultantes. + +El código funcionará con cualquier nombre, y nuestro sistema siempre verifica solo el resultado en pantalla, por lo que la ejecución de esta tarea es responsabilidad tuya. diff --git a/modules/30-variables/19-naming-style/es/README.md b/modules/30-variables/19-naming-style/es/README.md new file mode 100644 index 00000000..42e37fd3 --- /dev/null +++ b/modules/30-variables/19-naming-style/es/README.md @@ -0,0 +1,18 @@ +Algunos nombres son bastante simples, como `$greeting`. Pero a menudo no es tan obvio. Muchas veces los nombres son compuestos, es decir, incluyen varias palabras. Por ejemplo, "nombre de usuario". En diferentes lenguajes se utilizan diferentes estilos de codificación, por lo que el nombre de la variable será diferente. + +En la nomenclatura de variables se pueden distinguir cuatro enfoques principales, que a veces se combinan entre sí. Todos estos enfoques se aplican cuando el nombre de la variable consta de varias palabras: + +* kebab-case: las partes compuestas de la variable se separan con guiones (`my-super-var`) +* snake_case: se utiliza un guion bajo para separar (`my_super_var`) +* CamelCase: cada palabra en la variable se escribe con mayúscula inicial (`MySuperVar`) +* lowerCamelCase: cada palabra en la variable se escribe con mayúscula inicial, excepto la primera (`mySuperVar`) + +En PHP se utiliza CamelCase y su variante lowerCamelCase, donde la primera letra de la primera palabra es minúscula. Es precisamente lowerCamelCase el que se utiliza para las variables. Esto significa que los nombres se unen entre sí, y todas las palabras excepto la primera se escriben con mayúscula inicial: `$userName`. Con tres palabras se vería así: `$mySuperVariable`. + +Otra regla generalmente aceptada es no utilizar transliteraciones para los nombres, solo inglés. Si tienes dificultades con el inglés, utiliza un traductor. Con el tiempo, al investigar en el código de otras personas, adquirirás una comprensión adecuada de la nomenclatura. + +Los nombres no solo deben transmitir significado, sino también cumplir con las reglas sintácticas que generalmente no se verifican en el nivel del lenguaje, pero son necesarias durante el desarrollo. El proceso de escribir programas en el mundo moderno es un trabajo en equipo, y para una mejor interacción en el equipo, el código se escribe en un estilo uniforme, como si fuera realizado por una sola persona. + +Cada lenguaje tiene sus propias reglas. Recientemente, en PHP se ha establecido un [estándar de codificación](https://www.php-fig.org/psr/psr-1/) ampliamente aceptado, al que todos aspiran de una forma u otra. Estos estándares describen muchos aspectos. Recomendamos que desde el principio te acostumbres a consultar el estándar y escribir código de acuerdo con él. + +Afortunadamente, hoy en día no es necesario recordar todas las reglas del estándar, porque existen programas especiales que verifican automáticamente el código y señalan las violaciones. Estos programas se llaman **linter**, y comenzarás a usarlos un poco más adelante, cuando tengas un poco más de experiencia. diff --git a/modules/30-variables/19-naming-style/es/data.yml b/modules/30-variables/19-naming-style/es/data.yml new file mode 100644 index 00000000..0fb184c5 --- /dev/null +++ b/modules/30-variables/19-naming-style/es/data.yml @@ -0,0 +1,5 @@ +name: Nomenclatura de variables +tips: [] +definitions: + - name: Estándar de codificación + description: conjunto de reglas sintácticas y estilísticas para escribir código. diff --git a/modules/30-variables/19-naming-style/ru/EXERCISE.md b/modules/30-variables/19-naming-style/ru/EXERCISE.md new file mode 100644 index 00000000..0e87dcaa --- /dev/null +++ b/modules/30-variables/19-naming-style/ru/EXERCISE.md @@ -0,0 +1,3 @@ +Создайте две переменные с именами «первое число» и «второе число» на английском языке, используя lowerCamelCase. Запишите в первую переменную число `1.10`, во вторую — `-100`. Выведите на экран произведение чисел, записанных в получившиеся переменные. + +Код будет работать с любыми названиями, а наша система всегда проверяет только результат на экране, поэтому выполнение этого задания — под вашу ответственность. diff --git a/modules/30-variables/19-naming-style/ru/README.md b/modules/30-variables/19-naming-style/ru/README.md new file mode 100644 index 00000000..892af728 --- /dev/null +++ b/modules/30-variables/19-naming-style/ru/README.md @@ -0,0 +1,18 @@ +Некоторые имена довольно просты — например, `$greeting`. Но часто все не так очевидно. Довольно часто имена составные, то есть включают в себя несколько слов. Например, «имя пользователя». В разных языках применяются разные стили кодирования, и имя переменной будет отличаться. + +В именовании переменных можно выделить четыре основных подхода, которые иногда комбинируют друг с другом. Все эти подходы проявляют себя, когда имя переменной состоит из нескольких слов: + +* kebab-case — составные части переменной разделяются дефисом (`my-super-var`) +* snake_case — для разделения используется подчеркивание (`my_super_var`) +* CamelCase — каждое слово в переменной пишется с заглавной буквы (`MySuperVar`) +* lowerCamelCase — каждое слово в переменной пишется с заглавной буквы, кроме первого (`mySuperVar`) + +В PHP используется CamelCase и его вариация lowerCamelCase, при котором первая буква первого слова — строчная. Именно lowerCamelCase применяется для переменных. Это значит, что имена соединяются друг с другом, при этом все имена кроме первого становятся с заглавной буквы: `$userName`. С тремя словами это выглядит так: `$mySuperVariable`. + +Другое общепринятое правило гласит — не используйте транслит для имен, только английский язык. Если вы испытываете сложности с английским, то пользуйтесь переводчиком. Со временем, копаясь в чужом коде, вы сформируете правильные представления об именовании. + +Названия должны не только передавать смысл, но и соответствовать синтаксическим правилам, которые обычно никак не проверяются на уровне языка, но нужны во время разработки. Процесс написания программ в современном мире — коллективная работа, и для лучшего взаимодействия в команде код пишется в едином стиле, как если бы над ним работал один человек. + +В каждом языке свои правила. Относительно недавно в PHP появился общепринятый [стандарт кодирования](https://www.php-fig.org/psr/psr-1/), к которому все так или иначе стремятся. Подобные стандарты описывают множество аспектов. Советуем с самого начала завести привычку заглядывать в стандарт и писать код в соответствие с ним. + +К счастью, сегодня не нужно помнить все правила из стандарта, потому что существуют специальные программы, которые проверяют код автоматически и сообщают о нарушениях. Такие программы называются **линтерами**, и вы начнете их использовать немного позже, когда у вас появится чуть больше опыта. diff --git a/modules/30-variables/19-naming-style/ru/data.yml b/modules/30-variables/19-naming-style/ru/data.yml new file mode 100644 index 00000000..0a0d6ea9 --- /dev/null +++ b/modules/30-variables/19-naming-style/ru/data.yml @@ -0,0 +1,5 @@ +name: Именование переменных +tips: [] +definitions: + - name: Стандарт кодирования + description: набор синтаксических и стилистических правил написания кода. diff --git a/modules/30-variables/20-magic-numbers/en/EXERCISE.md b/modules/30-variables/20-magic-numbers/en/EXERCISE.md new file mode 100644 index 00000000..090e2ce1 --- /dev/null +++ b/modules/30-variables/20-magic-numbers/en/EXERCISE.md @@ -0,0 +1,25 @@ + +You've come across this code, which prints the total number of rooms owned by the present king: + +```php + +King Balon the 6th has 102 rooms. + + +Variable names should convey the meaning of numbers, but should remain short and succinct enough to be easily read. + +Note: The code will work with any name, and we only check the printed result, so the task is up to you. diff --git a/modules/30-variables/20-magic-numbers/en/README.md b/modules/30-variables/20-magic-numbers/en/README.md new file mode 100644 index 00000000..e64b57a6 --- /dev/null +++ b/modules/30-variables/20-magic-numbers/en/README.md @@ -0,0 +1,37 @@ + +Let's remember one of the previous lessons: + +```php + +King Balon the 6th has 102 rooms. + + +Los nombres de las variables deben transmitir el significado de los números, pero al mismo tiempo deben ser lo suficientemente cortos y concisos para una lectura cómoda. + +Recuerda: el código funcionará con cualquier nombre, y nuestro sistema siempre verifica solo el resultado en pantalla, por lo que completar esta tarea es tu responsabilidad. diff --git a/modules/30-variables/20-magic-numbers/es/README.md b/modules/30-variables/20-magic-numbers/es/README.md new file mode 100644 index 00000000..312747f6 --- /dev/null +++ b/modules/30-variables/20-magic-numbers/es/README.md @@ -0,0 +1,37 @@ + +Recordemos una de las lecciones anteriores: + +```php + +King Balon the 6th has 102 rooms. + + +Названия переменных должны передавать смысл чисел, но при этом должны оставаться достаточно короткими и ёмкими для комфортного чтения. + +Помните: код будет работать с любыми названиями, а наша система всегда проверяет только результат на экране, поэтому выполнение этого задания — под вашу ответственность. diff --git a/modules/30-variables/20-magic-numbers/ru/README.md b/modules/30-variables/20-magic-numbers/ru/README.md new file mode 100644 index 00000000..ff99ff7b --- /dev/null +++ b/modules/30-variables/20-magic-numbers/ru/README.md @@ -0,0 +1,37 @@ + +Вспомним один из прошлых уроков: + +```php + 3.14 + ``` + +Creating a constant is different from creating a variable. It starts with the keyword const followed by the constant name. We don't need the dollar sign. Then we assign it the desired value. Constants are usually named with uppercase letters, with `_` as a separator. A constant, like a variable, can be used in any expression. The only limitation is that the constant can't be changed, which sounds pretty logical. + +PHP has a lot of built-in constants that can be used anywhere in the program. Some of them are: + +* `PHP_VERSION` — the current version of PHP +* `PHP_MAXPATHLEN` — maximum file name length +* `PHP_INT_MAX` — the maximum possible value of integers diff --git a/modules/30-variables/23-constants/en/data.yml b/modules/30-variables/23-constants/en/data.yml new file mode 100644 index 00000000..e25c101d --- /dev/null +++ b/modules/30-variables/23-constants/en/data.yml @@ -0,0 +1,10 @@ +name: Constants +tips: + - > + [List of built-in PHP + constants](https://www.php.net/manual/en/reserved.constants.php) +definitions: + - name: A constant + description: >- + is a way of storing information and naming it for later use in code; + constants cannot be changed, unlike variables. diff --git a/modules/30-variables/23-constants/es/EXERCISE.md b/modules/30-variables/23-constants/es/EXERCISE.md new file mode 100644 index 00000000..4c7e484c --- /dev/null +++ b/modules/30-variables/23-constants/es/EXERCISE.md @@ -0,0 +1 @@ +Crea la constante `DRAGONS_BORN_COUNT` y asígnale el valor 3, que es la cantidad de dragones nacidos de Daenerys. diff --git a/modules/30-variables/23-constants/es/README.md b/modules/30-variables/23-constants/es/README.md new file mode 100644 index 00000000..2c304c32 --- /dev/null +++ b/modules/30-variables/23-constants/es/README.md @@ -0,0 +1,32 @@ +Los desarrolladores a menudo trabajan con datos que nunca cambian. Por ejemplo, el número π, que siempre es igual a `3.14` y no puede cambiar. + +En PHP, se utilizan constantes para acceder a este tipo de datos: + +```php + 3.14 +``` + +La creación de una constante es diferente a la creación de una variable. Comienza con la palabra clave `const` seguida del nombre de la constante. No se necesita el signo de dólar. Luego se le asigna el valor deseado. + +Las constantes suelen nombrarse en mayúsculas con `_` como separador. Una constante también se puede utilizar en cualquier expresión. La única restricción es que no se puede modificar. + +PHP tiene muchas constantes integradas que se pueden utilizar en cualquier parte del programa. Aquí hay algunas de ellas: + +* `PHP_VERSION` — versión actual de PHP +* `PHP_MAXPATHLEN` — longitud máxima permitida para el nombre de archivo +* `PHP_INT_MAX` — valor máximo posible para números enteros (integer) + +Además de las constantes normales en PHP, existe un grupo separado llamado **constantes mágicas**. Sus diferencias son las siguientes: + +* No se pueden definir constantes mágicas por uno mismo, solo se pueden utilizar las existentes +* Las constantes mágicas comienzan y terminan con los caracteres `__` (dos guiones bajos) +* La magia radica en que estas constantes tienen el mismo valor solo dentro de una parte específica del programa + +El último punto significa que existen constantes que no son muy constantes, pero sus cambios están regulados y no suelen causar problemas en la práctica. Algunas de estas constantes son: + +* `__LINE__` — contiene el número de línea actual del archivo en el que se utiliza +* `__FILE__` — ruta al archivo actual +* `__DIR__` — ruta al directorio en el que se encuentra el archivo actual diff --git a/modules/30-variables/23-constants/es/data.yml b/modules/30-variables/23-constants/es/data.yml new file mode 100644 index 00000000..ecaabe5f --- /dev/null +++ b/modules/30-variables/23-constants/es/data.yml @@ -0,0 +1,11 @@ +name: Constantes +tips: + - > + [Lista de constantes integradas en + PHP](https://php.net/manual/es/reserved.constants.php) +definitions: + - name: Constante + description: >- + una forma de almacenar información y darle un nombre para su uso posterior + en el código; las constantes no se pueden modificar, a diferencia de las + variables. diff --git a/modules/30-variables/23-constants/ru/EXERCISE.md b/modules/30-variables/23-constants/ru/EXERCISE.md new file mode 100644 index 00000000..4768f44c --- /dev/null +++ b/modules/30-variables/23-constants/ru/EXERCISE.md @@ -0,0 +1 @@ +Создайте константу `DRAGONS_BORN_COUNT` и запишите в неё число 3 — это количество драконов, родившихся у Дайенерис. diff --git a/modules/30-variables/23-constants/ru/README.md b/modules/30-variables/23-constants/ru/README.md new file mode 100644 index 00000000..71ec3030 --- /dev/null +++ b/modules/30-variables/23-constants/ru/README.md @@ -0,0 +1,32 @@ +Разработчики часто работают с данными, которые никогда не меняются. Например, число π, которое всегда равно `3.14` и не может измениться. + +Для обращения к подобным данным в PHP принято использовать константы: + +```php + 3.14 +``` + +Создание константы отличается от создания переменной. Оно начинается с ключевого слова `const` и последующего имени константы. При этом знак доллара не нужен. Далее ей присваивается нужное значение. + +Константы принято именовать буквами в верхнем регистре с `_` в качестве разделителя. Константа тоже может использоваться в любом выражении. Единственное ограничение — константу нельзя изменить. + +В PHP много встроенных констант, которые можно использовать в любом месте программы. Вот некоторые из них: + +* `PHP_VERSION` — текущая версия PHP +* `PHP_MAXPATHLEN` — максимальная разрешенная длина имени файла +* `PHP_INT_MAX` — максимальное возможное значение целых чисел (integer) + +Кроме обычных констант в PHP существует отдельная группа — **магические константы**. Их отличия заключаются в следующем: + +* Магические константы невозможно определить самому, можно пользоваться только существующими +* Магические константы начинаются и заканчиваются символами `__` (два подчеркивания) +* Магия заключается в том, что такие константы имеют одно и то же значение только в пределах определенной части программы + +Последний пункт говорит о том, что существуют не очень постоянные константы, но их изменения регламентированы и на практике не вызывают проблем. К подобным константам относятся: + +* `__LINE__` — содержит текущую строку файла, в котором она используется +* `__FILE__` — путь до текущего файла +* `__DIR__` — путь до директории, в которой находится текущий файл diff --git a/modules/30-variables/23-constants/ru/data.yml b/modules/30-variables/23-constants/ru/data.yml new file mode 100644 index 00000000..9465cf76 --- /dev/null +++ b/modules/30-variables/23-constants/ru/data.yml @@ -0,0 +1,10 @@ +name: Константы +tips: + - > + [Список встроенных в PHP + констант](https://php.net/manual/ru/reserved.constants.php) +definitions: + - name: Константа + description: >- + способ сохранить информацию и дать ей имя для последующего использования в + коде; константы нельзя изменять, в отличие от переменных. diff --git a/modules/30-variables/24-magic-constants/en/EXERCISE.md b/modules/30-variables/24-magic-constants/en/EXERCISE.md new file mode 100644 index 00000000..82b21470 --- /dev/null +++ b/modules/30-variables/24-magic-constants/en/EXERCISE.md @@ -0,0 +1,2 @@ + +Output the path to the current directory using a magic constant. diff --git a/modules/30-variables/24-magic-constants/en/README.md b/modules/30-variables/24-magic-constants/en/README.md new file mode 100644 index 00000000..6e68dd1d --- /dev/null +++ b/modules/30-variables/24-magic-constants/en/README.md @@ -0,0 +1,12 @@ + +In addition to the usual constants, PHP has a separate group of **magic constants**. The differences are as follows: + +* You can't define magic constants yourself, you can only use existing ones. +* Magic constants begin and end with `__` (two underscores). +* The magic is that the constants have the same value only within a certain part of the program. + +This last point may seem strange. What kind of constants are they if their value changes? To put it bluntly, they're not very constant, but their changes are clearly regulated and in practice don't cause problems. Such constants include, for example, the following: + +* `__LINE__` — contains the current line of the file it's used in +* `__FILE__` — path to the current file +* `__DIR__` — the path to the directory where the current file is located diff --git a/modules/30-variables/24-magic-constants/en/data.yml b/modules/30-variables/24-magic-constants/en/data.yml new file mode 100644 index 00000000..acf077fa --- /dev/null +++ b/modules/30-variables/24-magic-constants/en/data.yml @@ -0,0 +1,10 @@ +name: Magic constants +tips: + - > + [Magic + constants](https://www.php.net/manual/en/language.constants.predefined.php) +definitions: + - name: A magic constant + description: >- + is a special constant available in PHP; it contains different values in + different contexts. diff --git a/modules/30-variables/24-magic-constants/es/EXERCISE.md b/modules/30-variables/24-magic-constants/es/EXERCISE.md new file mode 100644 index 00000000..ec09bb2c --- /dev/null +++ b/modules/30-variables/24-magic-constants/es/EXERCISE.md @@ -0,0 +1,2 @@ + +Muestra en pantalla la ruta al directorio actual utilizando una constante mágica. diff --git a/modules/30-variables/24-magic-constants/es/README.md b/modules/30-variables/24-magic-constants/es/README.md new file mode 100644 index 00000000..57e77e65 --- /dev/null +++ b/modules/30-variables/24-magic-constants/es/README.md @@ -0,0 +1,12 @@ + +Además de las constantes normales, en PHP existe un grupo separado llamado **constantes mágicas**. Sus diferencias son las siguientes: + +* No se pueden definir constantes mágicas por uno mismo, solo se pueden utilizar las existentes. +* Las constantes mágicas comienzan y terminan con los caracteres `__` (dos guiones bajos). +* La magia radica en que estas constantes tienen el mismo valor solo dentro de una parte específica del programa. + +El último punto puede parecer extraño. ¿Cómo pueden ser constantes si su valor cambia? Para ser honestos, no son muy constantes, pero sus cambios están claramente regulados y en la práctica no causan problemas. Algunos ejemplos de estas constantes son: + +* `__LINE__` - contiene la línea actual del archivo en el que se utiliza +* `__FILE__` - la ruta al archivo actual +* `__DIR__` - la ruta al directorio en el que se encuentra el archivo actual diff --git a/modules/30-variables/24-magic-constants/es/data.yml b/modules/30-variables/24-magic-constants/es/data.yml new file mode 100644 index 00000000..563d7efa --- /dev/null +++ b/modules/30-variables/24-magic-constants/es/data.yml @@ -0,0 +1,10 @@ +name: Constantes mágicas +tips: + - > + [Constantes + mágicas](https://php.net/manual/es/language.constants.predefined.php) +definitions: + - name: Constante mágica + description: >- + una constante especial disponible en PHP; tiene diferentes valores en + diferentes contextos. diff --git a/modules/30-variables/24-magic-constants/ru/EXERCISE.md b/modules/30-variables/24-magic-constants/ru/EXERCISE.md new file mode 100644 index 00000000..20f4c4e2 --- /dev/null +++ b/modules/30-variables/24-magic-constants/ru/EXERCISE.md @@ -0,0 +1,2 @@ + +Выведите на экран путь до текущей директории, используя магическую константу. diff --git a/modules/30-variables/24-magic-constants/ru/README.md b/modules/30-variables/24-magic-constants/ru/README.md new file mode 100644 index 00000000..6bfd7030 --- /dev/null +++ b/modules/30-variables/24-magic-constants/ru/README.md @@ -0,0 +1,12 @@ + +Кроме обычных констант, в PHP существует отдельная группа — **магические константы**. Их отличия заключаются в следующем: + +* Магические константы невозможно определить самому, можно пользоваться только существующими. +* Магические константы начинаются и заканчиваются символами `__` (два подчёркивания). +* Магия заключается в том, что такие константы имеют одно и то же значение только в пределах определенной части программы. + +Последний пункт может показаться странным. Какие же они константы, если их значение меняется? Прямо скажем, они не очень постоянные, но их изменения четко регламентированы и на практике не вызывают проблем. К подобным константам относятся, например, такие: + +* `__LINE__` — содержит текущую строку файла, в котором она используется +* `__FILE__` — путь до текущего файла +* `__DIR__` — путь до директории, в которой находится текущий файл diff --git a/modules/30-variables/24-magic-constants/ru/data.yml b/modules/30-variables/24-magic-constants/ru/data.yml new file mode 100644 index 00000000..99f6d48b --- /dev/null +++ b/modules/30-variables/24-magic-constants/ru/data.yml @@ -0,0 +1,10 @@ +name: Магические константы +tips: + - > + [Магические + константы](https://php.net/manual/ru/language.constants.predefined.php) +definitions: + - name: Магическая константа + description: >- + специальная константа, доступная в PHP; содержит разное значение в разных + контекстах. diff --git a/modules/30-variables/25-interpolation/en/EXERCISE.md b/modules/30-variables/25-interpolation/en/EXERCISE.md new file mode 100644 index 00000000..3d2a3284 --- /dev/null +++ b/modules/30-variables/25-interpolation/en/EXERCISE.md @@ -0,0 +1,6 @@ + +Display the line Do you want to eat, ?`. And the variable `$stark` should be used instead of ``. The output should look like this: + +
+Do you want to eat, Arya?
+
diff --git a/modules/30-variables/25-interpolation/en/README.md b/modules/30-variables/25-interpolation/en/README.md new file mode 100644 index 00000000..353bd2f3 --- /dev/null +++ b/modules/30-variables/25-interpolation/en/README.md @@ -0,0 +1,32 @@ + +In the lesson on concatenation, we had the task of creating a letter header out of two variables and punctuation marks. You most likely did it this way: + +```php + Hello, Joffrey! +``` + +https://replit.com/@hexlet/php-basics-interpolation + +We just created one line and inserted variables into it in the right places using curly brackets (`{}`). It's like we have a blank form where we can enter the desired values. And we no longer have to worry about separate strings for punctuation marks and spaces, all of these characters already exist in our template string. + +You can make as many bracketed blocks as you want on one line. + +**Interpolation only works with double-quoted strings.** + +Nearly all languages favor interpolation over concatenation for combining strings. It glues a string together, and spaces and other characters look good in it. diff --git a/modules/30-variables/25-interpolation/en/data.yml b/modules/30-variables/25-interpolation/en/data.yml new file mode 100644 index 00000000..4906649b --- /dev/null +++ b/modules/30-variables/25-interpolation/en/data.yml @@ -0,0 +1,7 @@ +name: Interpolation +tips: [] +definitions: + - name: Interpolation + description: >- + is a way to join strings by inserting variable values into a string + template using curly brackets. For example, `\"Hi, {$name}!\"`. diff --git a/modules/30-variables/25-interpolation/es/EXERCISE.md b/modules/30-variables/25-interpolation/es/EXERCISE.md new file mode 100644 index 00000000..3585b2c4 --- /dev/null +++ b/modules/30-variables/25-interpolation/es/EXERCISE.md @@ -0,0 +1,5 @@ +Imprime en pantalla la cadena `Do you want to eat, ?`, donde en lugar de `` se debe utilizar la variable `$stark`. La salida debe ser la siguiente: + +
+Do you want to eat, Arya?
+
diff --git a/modules/30-variables/25-interpolation/es/README.md b/modules/30-variables/25-interpolation/es/README.md new file mode 100644 index 00000000..15f0490d --- /dev/null +++ b/modules/30-variables/25-interpolation/es/README.md @@ -0,0 +1,33 @@ +Imaginemos que necesitamos crear un encabezado de correo electrónico a partir de dos variables y signos de puntuación. Podemos resolver esta tarea de la siguiente manera: + +```php + 'Hola, Joffrey!' +``` + +Este es un caso simple, pero incluso aquí se requiere un esfuerzo para ver qué cadena se obtendrá al final. Hay que prestar atención a las comillas y los espacios, y a primera vista es difícil entender qué y dónde comienza y termina. + +Existe otra forma más conveniente: la **interpolación**. Así es como se ve: + +```php +$firstName = 'Joffrey'; +$greeting = 'Hola'; + +// Ten en cuenta que los delimitadores de la cadena son comillas dobles +// La interpolación no funciona con comillas simples +print_r("{$greeting}, {$firstName}!"); // => Hola, Joffrey! +``` + +https://replit.com/@hexlet/php-basics-interpolation + +En este ejemplo, creamos una sola cadena e insertamos las variables en el orden deseado utilizando llaves (`{}`). Creamos una plantilla donde se insertan los valores necesarios. + +Ahora no tenemos que preocuparnos por las cadenas separadas para los signos de puntuación y los espacios. Estos caracteres están escritos en la cadena de la plantilla. + +En una sola cadena se pueden hacer tantos bloques con llaves como se desee. La interpolación solo funciona con cadenas entre comillas dobles. + +En casi todos los lenguajes, la interpolación es preferible a la concatenación para unir cadenas. La cadena resultante está concatenada y dentro de ella se pueden ver claramente los espacios y otros caracteres. diff --git a/modules/30-variables/25-interpolation/es/data.yml b/modules/30-variables/25-interpolation/es/data.yml new file mode 100644 index 00000000..9d2a1a62 --- /dev/null +++ b/modules/30-variables/25-interpolation/es/data.yml @@ -0,0 +1,8 @@ +name: Interpolación +tips: [] +definitions: + - name: Interpolación + description: >- + método de concatenación de cadenas mediante la inserción de valores de + variables en una cadena de plantilla utilizando llaves. Por ejemplo, + `\"¡Hola, {$name}!\"`. diff --git a/modules/30-variables/25-interpolation/ru/EXERCISE.md b/modules/30-variables/25-interpolation/ru/EXERCISE.md new file mode 100644 index 00000000..8f8e01d7 --- /dev/null +++ b/modules/30-variables/25-interpolation/ru/EXERCISE.md @@ -0,0 +1,5 @@ +Выведите на экран строку `Do you want to eat, ?`. Где вместо `` должна использоваться переменная `$stark`. Вывод должен получиться таким: + +
+Do you want to eat, Arya?
+
diff --git a/modules/30-variables/25-interpolation/ru/README.md b/modules/30-variables/25-interpolation/ru/README.md new file mode 100644 index 00000000..da84ee79 --- /dev/null +++ b/modules/30-variables/25-interpolation/ru/README.md @@ -0,0 +1,33 @@ +Представим, что нам нужно создать заголовок письма из двух переменных и знаков препинания. Эту задачу можно решить так: + +```php + 'Hello, Joffrey!' +``` + +Это простой случай, но даже здесь нужно приложить усилия, чтобы увидеть, какая в итоге получится строка. Нужно следить за несколькими кавычками и пробелами, и с первого взгляда сложно понять, что и где начинается и заканчивается. + +Есть другой более удобный способ — **интерполяция**. Так это выглядит: + +```php +$firstName = 'Joffrey'; +$greeting = 'Hello'; + +// Обратите внимание на ограничители строки — это двойные кавычки +// Интерполяция не работает с одинарными кавычками +print_r("{$greeting}, {$firstName}!"); // => Hello, Joffrey! +``` + +https://replit.com/@hexlet/php-basics-interpolation + +В этом примере мы создали одну строку и в нужном нам порядке вставили в нее переменные с помощью фигурных скобок (`{}`). Получился шаблон, куда внесены нужные значения. + +Теперь нам не нужно заботиться об отдельных строках для знаков препинания и пробелов. Эти символы записаны в строке-шаблоне. + +В одной строке можно делать сколько угодно блоков с фигурными скобками. Также интерполяция работает только со строками в двойных кавычках. + +Почти во всех языках интерполяция предпочтительнее конкатенации для объединения строк. Строка при этом получается склеенная, и внутри нее хорошо просматриваются пробелы и другие символы. diff --git a/modules/30-variables/25-interpolation/ru/data.yml b/modules/30-variables/25-interpolation/ru/data.yml new file mode 100644 index 00000000..686c753f --- /dev/null +++ b/modules/30-variables/25-interpolation/ru/data.yml @@ -0,0 +1,7 @@ +name: Интерполяция +tips: [] +definitions: + - name: Интерполяция + description: >- + способ соединения строк через вставку значений переменных в строку-шаблон + с помощью фигурных скобок. Например, `\"Hi, {$name}!\"`. diff --git a/modules/30-variables/30-symbols/en/EXERCISE.md b/modules/30-variables/30-symbols/en/EXERCISE.md new file mode 100644 index 00000000..b5280fc0 --- /dev/null +++ b/modules/30-variables/30-symbols/en/EXERCISE.md @@ -0,0 +1,10 @@ + +You've been given three variables with the names of different people. Put together and print a word out from the characters in this order: + +1. The third character from the first line. +2. The second character from the second line. +3. The fourth character from the third line. +4. The fifth character from the second line. +5. The third character from the second line. + +Try using interpolation: you can put individual characters (called via square brackets), as well as variables, inside curly brackets. diff --git a/modules/30-variables/30-symbols/en/README.md b/modules/30-variables/30-symbols/en/README.md new file mode 100644 index 00000000..4024599a --- /dev/null +++ b/modules/30-variables/30-symbols/en/README.md @@ -0,0 +1,46 @@ + +Sometimes, you need to get a single character from a string. For example, if a website knows the user's first name and surname, and at some point, it needs to output it as`J. Smith`, you need to take the initial letter from the first name. + +```php + A +``` + +Square brackets with a number are a special string extraction operator. This number is called an **index** — the position of the character inside the string. Indexes start with 0 in almost all programming languages, so to get the first character, you must specify index `0`. The index of the last element is equal to the length of the string minus one: + +```php + r + +// Self-check. What will this code print? +$magic = '\nyou'; +print_r($magic[1]); // => ? +``` + +You're allowed to use negative indices. In this case there's a reference to characters starting from the end of the string. `-1` is the index of the last character, `-2` of the penultimate, and so on. Unlike direct indexing, reverse indexing counts down from `-1`: + +```php + r +``` + +You can use variables as well as numbers as an index. Here's an example that will have the same result of displaying the character `A`, but the index inside the square brackets is written as a variable instead of a number: + +```php + A +``` diff --git a/modules/30-variables/30-symbols/en/data.yml b/modules/30-variables/30-symbols/en/data.yml new file mode 100644 index 00000000..29389f54 --- /dev/null +++ b/modules/30-variables/30-symbols/en/data.yml @@ -0,0 +1 @@ +name: Extracting characters from string diff --git a/modules/30-variables/30-symbols/es/EXERCISE.md b/modules/30-variables/30-symbols/es/EXERCISE.md new file mode 100644 index 00000000..96695749 --- /dev/null +++ b/modules/30-variables/30-symbols/es/EXERCISE.md @@ -0,0 +1,9 @@ +Se te han dado tres variables con los apellidos de diferentes personas. Crea y muestra en pantalla una palabra con los caracteres en el siguiente orden: + +1. El tercer carácter de la primera cadena. +2. El segundo carácter de la segunda cadena. +3. El cuarto carácter de la tercera cadena. +4. El quinto carácter de la segunda cadena. +5. El tercer carácter de la segunda cadena. + +Intenta utilizar interpolación: dentro de las llaves, puedes colocar no solo variables enteras, sino también caracteres individuales utilizando corchetes. diff --git a/modules/30-variables/30-symbols/es/README.md b/modules/30-variables/30-symbols/es/README.md new file mode 100644 index 00000000..9655b8e7 --- /dev/null +++ b/modules/30-variables/30-symbols/es/README.md @@ -0,0 +1,49 @@ +En esta lección aprenderemos a obtener un carácter específico de una cadena. Por ejemplo, si un sitio web conoce el nombre y apellido del usuario, y en algún momento se requiere mostrar esta información en el formato `A. Ivanov`. En este caso, debemos tomar el primer carácter del nombre: + +```php + A +``` + +Los corchetes con un número son un operador especial para extraer una cadena. Este número se llama **índice** y representa la posición del carácter dentro de la cadena. + +Los índices comienzan desde cero en casi todos los lenguajes de programación. Para obtener el primer carácter, debemos especificar el índice `0`. El índice del último elemento es igual a la longitud de la cadena menos uno: + +```php + r + +// Pregunta de autoevaluación. ¿Qué imprimirá este código? +$magic = '\nyou'; +print_r($magic[1]); // => ? +``` + +También es posible utilizar índices negativos. En este caso, se accede a los caracteres desde el final de la cadena. `-1` es el índice del último carácter, `-2` es el índice del penúltimo carácter, y así sucesivamente. A diferencia de la indexación directa, el conteo inverso comienza desde `-1`: + +```php + r +``` + +El índice puede ser no solo un número específico, sino también el valor de una variable. Aquí hay un ejemplo que dará el mismo resultado, mostrando el carácter `A` en la pantalla: + +```php + A +``` + +Aquí, el índice dentro de los corchetes no está escrito como un número, sino como una variable. diff --git a/modules/30-variables/30-symbols/es/data.yml b/modules/30-variables/30-symbols/es/data.yml new file mode 100644 index 00000000..c9c9224b --- /dev/null +++ b/modules/30-variables/30-symbols/es/data.yml @@ -0,0 +1,2 @@ +name: Extracción de caracteres de una cadena +tips: [] diff --git a/modules/30-variables/30-symbols/ru/EXERCISE.md b/modules/30-variables/30-symbols/ru/EXERCISE.md new file mode 100644 index 00000000..58ea64b3 --- /dev/null +++ b/modules/30-variables/30-symbols/ru/EXERCISE.md @@ -0,0 +1,9 @@ +Вам даны три переменные с фамилиями разных людей. Составьте и выведите на экран слово из символов в таком порядке: + +1. Третий символ из первой строки. +2. Второй символ из второй строки. +3. Четвертый символ из третьей строки. +4. Пятый символ из второй строки. +5. Третий символ из второй строки. + +Попробуйте использовать интерполяцию: внутри фигурных скобок можно помещать не только целые переменные, но и отдельные символы с помощью квадратных скобок. diff --git a/modules/30-variables/30-symbols/ru/README.md b/modules/30-variables/30-symbols/ru/README.md new file mode 100644 index 00000000..cbe8ac7d --- /dev/null +++ b/modules/30-variables/30-symbols/ru/README.md @@ -0,0 +1,49 @@ +В этом уроке мы научимся получать из строки конкретный символ. Например, если сайт знает имя и фамилию пользователя, и в какой-то момент требуется вывести эту информацию в формате `A. Ivanov`. В этом случае нужно взять первый символ из имени: + +```php + A +``` + +Квадратные скобки с цифрой — это специальный оператор извлечения строки. Эта цифра называется **индексом** — позицией символа внутри строки. + +Индексы начинаются с нуля почти во всех языках программирования. Чтобы получить первый символ, нужно указать индекс `0`. Индекс последнего элемента равен длине строки минус единица: + +```php + r + +// Вопрос на самопроверку. Что выведет этот код? +$magic = '\nyou'; +print_r($magic[1]); // => ? +``` + +Также допустимо использовать отрицательные индексы. В этом случае идет обращение к символам с конца строки. `-1` — индекс последнего символа, `-2` — предпоследнего и так далее. В отличие от прямой индексации обратный отсчет идет от `-1`: + +```php + r +``` + +Индексом может быть не только конкретное число, но и значение переменной. Вот пример, который приведет к тому же результату — выводу на экран символа `A`: + +```php + A +``` + +Здесь индекс внутри квадратных скобок записан не числом, а переменной. diff --git a/modules/30-variables/30-symbols/ru/data.yml b/modules/30-variables/30-symbols/ru/data.yml new file mode 100644 index 00000000..2d07240e --- /dev/null +++ b/modules/30-variables/30-symbols/ru/data.yml @@ -0,0 +1,2 @@ +name: Извлечение символов из строки +tips: [] diff --git a/modules/30-variables/35-heredoc/en/EXERCISE.md b/modules/30-variables/35-heredoc/en/EXERCISE.md new file mode 100644 index 00000000..d8d46a98 --- /dev/null +++ b/modules/30-variables/35-heredoc/en/EXERCISE.md @@ -0,0 +1,5 @@ + +Write the text below to the `$str` variable. Use heredoc syntax. + + Lannister, Targaryen, Baratheon, Stark, Tyrell... they're all just spokes on a wheel. + This one's on top, then that one's on top, and on and on it spins, crushing those on the ground. diff --git a/modules/30-variables/35-heredoc/en/README.md b/modules/30-variables/35-heredoc/en/README.md new file mode 100644 index 00000000..b521ed09 --- /dev/null +++ b/modules/30-variables/35-heredoc/en/README.md @@ -0,0 +1,23 @@ + +You can use a special syntax called heredoc to define strings in PHP. After the `<<<` operator, you need to specify an identifier with whatever name you like then a line feed, followed by the string itself. The same identifier is added at the end, closing the insertion. This method is convenient for specifying long strings, containing both line feeds and multi-type quotes. + +```php + +Example of a string, +covering several lines, +using heredoc syntax. +Here we don't need to escape either single ', or double " quotes. + + +Note that the trailing identifier (in this case `EOT`) must not have spaces, otherwise PHP will tell you off for having a syntax error. diff --git a/modules/30-variables/35-heredoc/en/data.yml b/modules/30-variables/35-heredoc/en/data.yml new file mode 100644 index 00000000..ffebd219 --- /dev/null +++ b/modules/30-variables/35-heredoc/en/data.yml @@ -0,0 +1,5 @@ +name: Heredoc +definitions: [] +tips: + - | + [Heredoc](https://www.php.net/manual/en/language.types.string.php) diff --git a/modules/30-variables/35-heredoc/es/EXERCISE.md b/modules/30-variables/35-heredoc/es/EXERCISE.md new file mode 100644 index 00000000..affb8fd6 --- /dev/null +++ b/modules/30-variables/35-heredoc/es/EXERCISE.md @@ -0,0 +1,5 @@ + +Asigne el siguiente texto a la variable `$str` utilizando la sintaxis de heredoc. + + Lannister, Targaryen, Baratheon, Stark, Tyrell... they're all just spokes on a wheel. + This one's on top, then that one's on top, and on and on it spins, crushing those on the ground. diff --git a/modules/30-variables/35-heredoc/es/README.md b/modules/30-variables/35-heredoc/es/README.md new file mode 100644 index 00000000..9c3d35cc --- /dev/null +++ b/modules/30-variables/35-heredoc/es/README.md @@ -0,0 +1,19 @@ +En PHP, se pueden definir cadenas de texto utilizando la sintaxis especial de heredoc. Después del operador `<<<`, se debe especificar un identificador con un nombre arbitrario, seguido de un salto de línea y la cadena de texto en sí. Al final, se agrega el mismo identificador que cierra la inserción. Este método es conveniente para definir cadenas de texto largas que contienen saltos de línea y comillas de diferentes tipos: + +```php + Ejemplo de cadena de texto +// => que abarca varias líneas, +// => utilizando la sintaxis de heredoc. +// => Aquí no es necesario escapar ni las comillas simples ' ni las comillas dobles ". +``` + +Antes del identificador de cierre, en nuestro caso 'EOT', no deben haber espacios en blanco, de lo contrario, PHP mostrará un error de sintaxis. diff --git a/modules/30-variables/35-heredoc/es/data.yml b/modules/30-variables/35-heredoc/es/data.yml new file mode 100644 index 00000000..a86922a8 --- /dev/null +++ b/modules/30-variables/35-heredoc/es/data.yml @@ -0,0 +1,5 @@ +name: Heredoc +definitions: [] +tips: + - > + [Heredoc](https://www.php.net/manual/es/language.types.string.php#language.types.string.syntax.heredoc) diff --git a/modules/30-variables/35-heredoc/ru/EXERCISE.md b/modules/30-variables/35-heredoc/ru/EXERCISE.md new file mode 100644 index 00000000..cf047077 --- /dev/null +++ b/modules/30-variables/35-heredoc/ru/EXERCISE.md @@ -0,0 +1,5 @@ + +Запишите в переменную `$str` текст, который приведен ниже. Используйте heredoc-синтаксис. + + Lannister, Targaryen, Baratheon, Stark, Tyrell... they're all just spokes on a wheel. + This one's on top, then that one's on top, and on and on it spins, crushing those on the ground. diff --git a/modules/30-variables/35-heredoc/ru/README.md b/modules/30-variables/35-heredoc/ru/README.md new file mode 100644 index 00000000..f15bc171 --- /dev/null +++ b/modules/30-variables/35-heredoc/ru/README.md @@ -0,0 +1,19 @@ +Определять строки в PHP можно с помощью специального heredoc-синтаксиса. После оператора `<<<` необходимо указать идентификатор с произвольным именем, затем перевод строки и саму строку. В конце добавляется тот же идентификатор, который закрывает вставку. Такой способ удобен для задания длинных строк, внутри которых встречаются и переводы строк, и разнотипные кавычки: + +```php + Пример строки, +// => охватывающей несколько строк, +// => с использованием heredoc-синтаксиса. +// => Здесь не нужно экранировать ни одинарные ', ни двойные " кавычки. +``` + +Перед закрывающим идентификатором, в нашем случае — `EOT`, не должны стоять пробелы, иначе PHP начнет ругаться на ошибку синтаксиса. diff --git a/modules/30-variables/35-heredoc/ru/data.yml b/modules/30-variables/35-heredoc/ru/data.yml new file mode 100644 index 00000000..406ecae0 --- /dev/null +++ b/modules/30-variables/35-heredoc/ru/data.yml @@ -0,0 +1,5 @@ +name: Heredoc +definitions: [] +tips: + - > + [Heredoc](https://www.php.net/manual/ru/language.types.string.php#language.types.string.syntax.heredoc) diff --git a/modules/35-calling-functions/100-call/en/EXERCISE.md b/modules/35-calling-functions/100-call/en/EXERCISE.md new file mode 100644 index 00000000..94555f33 --- /dev/null +++ b/modules/35-calling-functions/100-call/en/EXERCISE.md @@ -0,0 +1,2 @@ + +There are two variables defined in the program code that contain the names of companies. Calculate their total character length and print it. diff --git a/modules/35-calling-functions/100-call/en/README.md b/modules/35-calling-functions/100-call/en/README.md new file mode 100644 index 00000000..238e8b89 --- /dev/null +++ b/modules/35-calling-functions/100-call/en/README.md @@ -0,0 +1,64 @@ + +Addition, concatenation, and the other operations discussed are all fairly basic features of programming languages. Mathematics isn't limited to arithmetic, but there are many other areas with their own operations, such as geometry. The same goes for strings: you can flip them, change a letter's case, delete extra characters – and that's just the tip of the iceberg. And finally, at a higher level, there's the applied logic of a particular program. Programs withdraw money, calculate taxes, and generate reports. The number of these jobs is endless and different for each program. And they all have to be somehow expressed in code. + +The notion of a *function* expresses any arbitrary operation in programming. Functions can be both built-in and manually written by a programmer. One built-in function we're already familiar with is `print_r()`. + +Functions are fundamental building blocks in programming, and it's impossible to accomplish anything without them. We need to get acquainted with them as soon as possible because future courses will deal almost exclusively with functions. First, we'll learn how to use the functions we've already defined, and we'll also learn to define our own functions. + +We will start with basic functions that handle strings. Below is an example of a call to `strrev()`, that reverses a string: + +```php + '!olleH' +``` + +We created a variable, `$result` and told the interpreter to write the result of the `strrev()` function to it. In this sense, functions are identical to operations; they always return the result of their work. The entry `strrev('Hello!')` means that a function named `strrev` is being called, to which the argument (or parameter) `'Hello!'` has been passed. Arguments are needed for functions to work, just like how operators need operands. The `strrev()` function flips the string passed to it in the arguments. + +Another example is the `strlen()` function, which counts the number of characters in a string + +```php + 6 +``` + +The function being called is always indicated by parentheses `()` following the function name. There can be any number of arguments in brackets, and sometimes none at all. The number depends on the function used, for example, the `pow()` function takes two arguments as input and raises the number passed to the power passed in the second parameter. + +```php + 8 + +// Modern PHP now has a special operator for exponentiation: +$result = 2 ** 3; // 8 +``` + +And here's an example of a function that takes no arguments. The `rand()` function generates and returns a random number: + +```php +- + is an operation capable of accepting data and returning a result; a + function is called like this: `foo()`. + - name: An argument + description: >- + is the information the function receives when it is called. For example, + with `foo(42), we pass the argument `42` to `foo()` diff --git a/modules/35-calling-functions/100-call/es/EXERCISE.md b/modules/35-calling-functions/100-call/es/EXERCISE.md new file mode 100644 index 00000000..f43b4f87 --- /dev/null +++ b/modules/35-calling-functions/100-call/es/EXERCISE.md @@ -0,0 +1 @@ +En el código del programa se han definido dos variables que contienen nombres de empresas. Calcula la longitud total de los nombres en caracteres y muéstrala en pantalla. diff --git a/modules/35-calling-functions/100-call/es/README.md b/modules/35-calling-functions/100-call/es/README.md new file mode 100644 index 00000000..dbe90070 --- /dev/null +++ b/modules/35-calling-functions/100-call/es/README.md @@ -0,0 +1,64 @@ +La suma, la concatenación y otras operaciones que hemos visto son capacidades básicas de los lenguajes de programación. Pero con las cadenas de texto se pueden realizar operaciones más complejas. Se pueden invertir, cambiar el caso de las letras, eliminar caracteres innecesarios. + +A un nivel más alto, existe la lógica aplicada a una aplicación específica. Los programas pueden realizar transacciones monetarias, calcular impuestos, generar informes. La cantidad de operaciones similares es infinita y depende de cada programa en particular. Y todas ellas deben estar expresadas en código. Para eso, las funciones nos ayudan, y en esta lección aprenderemos sobre ellas. + +## Tipos de funciones + +Para expresar cualquier operación arbitraria en programación, existen las **funciones**. Pueden ser funciones incorporadas o agregadas por el programador. Ya estamos familiarizados con una función incorporada: `print_r()`. + +Las **funciones** son una de las construcciones clave en programación, sin ellas no se puede hacer prácticamente nada. Primero aprenderemos a utilizar las funciones ya creadas y luego aprenderemos a crear las nuestras propias. + +## Cómo trabajar con funciones incorporadas + +Comenzaremos con funciones sencillas para trabajar con cadenas de texto. A continuación, se muestra un ejemplo de llamado a la función `strrev()`, que invierte una cadena de texto: + +```php + '!aloH' +``` + +Hemos creado la variable `$resultado` y le hemos indicado al intérprete que guarde en ella el resultado que devuelve el llamado a la función `strrev()`. En este sentido, las funciones son similares a las operaciones, siempre devuelven un resultado. + +La expresión `strrev('¡Hola!')` significa que se está llamando a la función con el nombre `strrev`, a la cual se le ha pasado el argumento o parámetro `'¡Hola!'`. + +Las funciones necesitan argumentos para funcionar, al igual que los operadores necesitan operandos. La función `strrev()` invierte la cadena de texto que se le pasa como argumento. + +El llamado a una función siempre se indica con paréntesis `()`. Estos van justo después del nombre de la función. Entre los paréntesis puede haber cualquier cantidad de argumentos, o incluso ninguno. La cantidad depende de la función que se esté utilizando. Por ejemplo, la función `pow()` recibe dos argumentos y eleva el número pasado como primer parámetro a la potencia indicada como segundo parámetro: + +```php + 8 + +// En PHP moderno, hay un operador especial para elevar a una potencia +$resultado = 2 ** 3; // 8 +``` + +Ahora veamos un ejemplo de una función que no recibe argumentos. La función `rand()` genera y devuelve un número aleatorio: + +```php +- + operación capaz de recibir datos y devolver un resultado; se llama a una + función de esta manera: `foo()`. + - name: Argumento + description: >- + información que una función recibe cuando se llama a ella. Por ejemplo, + `foo(42)` es pasar el argumento `42` a la función `foo()`. diff --git a/modules/35-calling-functions/100-call/ru/EXERCISE.md b/modules/35-calling-functions/100-call/ru/EXERCISE.md new file mode 100644 index 00000000..081bc8d1 --- /dev/null +++ b/modules/35-calling-functions/100-call/ru/EXERCISE.md @@ -0,0 +1 @@ +В коде программы определены две переменные, содержащие имена компаний. Посчитайте их общую длину в символах и выведите ее на экран. diff --git a/modules/35-calling-functions/100-call/ru/README.md b/modules/35-calling-functions/100-call/ru/README.md new file mode 100644 index 00000000..d21727a9 --- /dev/null +++ b/modules/35-calling-functions/100-call/ru/README.md @@ -0,0 +1,64 @@ +Сложение, конкатенация и остальные рассмотренные операции — это базовые возможности языков программирования. Но со строками можно поизводить более сложные операции. Их можно переворачивать, менять регистр букв, удалять лишние символы. + +На более высоком уровне есть прикладная логика конкретного приложения. Программы списывают деньги, считают налоги, формируют отчеты. Количество подобных операций бесконечно и индивидуально для каждой программы. И все они должны быть выражены в коде. В этом помогают функции, с которыми мы познакомимся в этом уроке. + +## Какие бывают функции + +Для выражения любой произвольной операции в программировании существуют **функции**. Они бывают встроенными и добавленными программистом. С одной встроенной функцией мы уже знакомы — это `print_r()`. + +**Функции** — одна из ключевых конструкций в программировании, без них невозможно сделать практически ничего. Сначала мы научимся пользоваться уже созданными функциями, а потом научимся создавать свои. + +## Как работать со встроенными функциями + +Начнем с простых функций для работы над строками. Ниже пример вызова функции `strrev()`, которая переворачивает строку: + +```php + '!olleH' +``` + +Мы создали переменную `$result` и указали интерпретатору записать в нее результат, который вернет вызов функции `strrev()`. В этом смысле функции идентичны операциям — они всегда возвращают результат своей работы. + +Запись `strrev('Hello!')` означает, что вызывается функция с именем `strrev`, в которую был передан аргумент или параметр `'Hello!'`. + +Аргументы нужны функциям для работы так же, как операторам нужны операнды. Функция `strrev()` переворачивает ту строку, которая передается ей в аргументах. + +Вызов функции всегда обозначается скобками `()`. Они идут сразу за именем функции. В скобках может быть любое количество аргументов, а иногда — ни одного. Количество зависит от используемой функции. Например, функция `pow()` принимает на вход два аргумента и возводит число, переданное первым параметром, в степень, переданную вторым параметром: + +```php + 8 + +// В современном PHP появился специальный оператор для возведения в степень +$result = 2 ** 3; // 8 +``` + +Теперь рассмотрим пример функции, которая не принимает аргументов. Функция `rand()` генерирует и возвращает случайное число: + +```php +- + операция, способная принимать данные и возвращать результат; функция + вызывается так: `foo()`. + - name: Аргумент + description: >- + информация, которую функция получает при вызове. Например, `foo(42)` — + передача аргумента `42` функции `foo()` diff --git a/modules/35-calling-functions/120-function-signature/en/EXERCISE.md b/modules/35-calling-functions/120-function-signature/en/EXERCISE.md new file mode 100644 index 00000000..f2ef9574 --- /dev/null +++ b/modules/35-calling-functions/120-function-signature/en/EXERCISE.md @@ -0,0 +1,6 @@ + +Now it's your turn, look at the signature of a function in the documentation and work out how to use it. Now it's your turn to find the function signature in the documentation and figure out how to use it. + +In PHP, there's a function called `ucfirst()`. Study its signature at [https://www.php.net/manual/en/function.ucfirst.php](https://www.php.net/manual/en/function.ucfirst.php). + +Write a program that uses `ucfirst()` with the variable `$text` and displays the result. The value of the `$text` variable is already defined. diff --git a/modules/35-calling-functions/120-function-signature/en/README.md b/modules/35-calling-functions/120-function-signature/en/README.md new file mode 100644 index 00000000..ef281900 --- /dev/null +++ b/modules/35-calling-functions/120-function-signature/en/README.md @@ -0,0 +1,28 @@ + +The `pow()`, function, which raises a number to any power, takes two parameters: **which number to raise** and **to what power to raise it to**. If you call `pow()` without parameters, PHP outputs the following: `PHP Warning: pow() expects exactly 2 parameters, 0 given in php shell code on line 1`. The interpreter has told you that the function expects 2 parameters, and that you called it without parameters. + +Whoever created the `pow()`, function made it a function with two mandatory parameters, so it can't be called with any other number of parameters. + +Moreover, the parameters of `pow()` can only be numbers. Attempting to pass, for example, a string to it will result in the following error: `PHP Warning: A non-numeric value encountered in php shell code on line 1`. The result of this function call will also always be a number. + +Other functions may have different numbers of parameters and different types of parameters. For example, there may be a function that takes three parameters: a number, a string, and another number. + +How do we know how many parameters the `pow` function needs and what sort of result it'll return? We've taken a look at this function's **signature**. The signature defines the input parameters and their types, as well as the output parameter and its type. You can read about the `pow` function in [the official PHP documentation](https://www.php.net/manual/en/function.pow.php). In the "description" section, you can see this this text: + +``` +pow ( number $base , number $exp ) : number + +Returns base raised to the power of exp. +``` + +This is a function signature and a short explanation. + +The information is deciphered as follows: +- the function is called `pow` +- the function takes two parameters: a number (base) and a number (exp) +- the function returns a number (number) +- the function returns base raised to the power of exp + +Parameters can only be passed in the order they're given in the signature. + +Any function will always return only one value. This restriction exists at language level and cannot be broken. diff --git a/modules/35-calling-functions/120-function-signature/en/data.yml b/modules/35-calling-functions/120-function-signature/en/data.yml new file mode 100644 index 00000000..79823db1 --- /dev/null +++ b/modules/35-calling-functions/120-function-signature/en/data.yml @@ -0,0 +1,6 @@ +name: Сигнатура функции +definitions: + - name: A function signature + description: >- + is a formal description of the types of arguments and the type of return + value of a function. diff --git a/modules/35-calling-functions/120-function-signature/es/EXERCISE.md b/modules/35-calling-functions/120-function-signature/es/EXERCISE.md new file mode 100644 index 00000000..9c293162 --- /dev/null +++ b/modules/35-calling-functions/120-function-signature/es/EXERCISE.md @@ -0,0 +1,5 @@ +Ahora es tu turno de mirar la firma de una función en la documentación y entender cómo usarla. Puedes leer la documentación en español, pero un programador debe ser capaz de leer la documentación en inglés. Utiliza diccionarios o traductores si es necesario. Es mejor acostumbrarse y mejorar tus habilidades de lectura en inglés desde el principio, de lo contrario, tendrás dificultades en el futuro. + +En PHP, hay una función llamada `ucfirst()`. Estudia su firma en la página [https://php.net/manual/es/function.ucfirst.php](https://php.net/manual/es/function.ucfirst.php). + +Escribe un programa que utilice la función `ucfirst()` con la variable `$text` y muestre el resultado en pantalla. El valor de la variable `$text` ya está definido. diff --git a/modules/35-calling-functions/120-function-signature/es/README.md b/modules/35-calling-functions/120-function-signature/es/README.md new file mode 100644 index 00000000..ee4d1dde --- /dev/null +++ b/modules/35-calling-functions/120-function-signature/es/README.md @@ -0,0 +1,70 @@ +En esta lección aprenderemos a trabajar con la firma de una función. También aprenderemos cómo una función recibe y devuelve valores. Analizaremos las funciones `abs()` y `round()`. + +## Función abs() + +La función `abs()`, que devuelve el valor absoluto, recibe un parámetro: un número. Si llamamos a `abs()` sin parámetros, PHP mostrará el siguiente mensaje de error: + +``` +TypeError: abs() expects exactly 1 argument, 0 given +``` + +Esto indica que la función espera un parámetro, pero la llamamos sin ninguno. + +Los parámetros de `abs()` solo pueden ser números. Si intentamos pasarle una cadena de texto, obtendremos el siguiente error: + +``` +TypeError: abs(): Argument #1 ($num) must be of type int|float, string given +``` + +El resultado de llamar a esta función siempre es un número. Otra función puede tener un número diferente de parámetros y diferentes tipos de parámetros. Por ejemplo, puede existir una función que reciba tres parámetros: un número, una cadena de texto y otro número. + +¿Cómo sabemos cuántos y qué tipo de parámetros necesita la función `abs()` y qué tipo de valor devuelve? Lo vemos en la **firma** de la función. La firma define los parámetros de entrada y sus tipos, así como el parámetro de salida y su tipo. + +Puedes leer más sobre la función `abs()` en la [documentación oficial de PHP](https://www.php.net/manual/es/function.abs.php). En la sección "Descripción" encontrarás el siguiente texto: + +```txt +abs(int|float $num): int|float + +Devuelve el valor absoluto de num. +``` + +Esta es la firma de la función y una breve explicación en español. + +La información se interpreta de la siguiente manera: + +* El nombre de la función es `abs` +* La función recibe un parámetro: un número (num) +* La función devuelve un número +* La función devuelve el valor absoluto de num + +Si hay más de un parámetro, debemos pasarlos en el mismo orden en que están definidos en la firma. Cualquier función siempre devuelve solo un valor. Esta es una limitación del lenguaje y no puede ser violada. + +## Argumentos por defecto + +Veamos la función `round()`. Esta función redondea un número: + +```php +- + descripción formal de los tipos de argumentos y el tipo de valor devuelto + por una función. diff --git a/modules/35-calling-functions/120-function-signature/ru/EXERCISE.md b/modules/35-calling-functions/120-function-signature/ru/EXERCISE.md new file mode 100644 index 00000000..6830c809 --- /dev/null +++ b/modules/35-calling-functions/120-function-signature/ru/EXERCISE.md @@ -0,0 +1,5 @@ +Теперь ваша очередь посмотреть на сигнатуру функции в документации и разобраться, как её использовать. Можете читать документацию на русском языке, но программист обязан уметь читать документацию на английском. Используйте словари или переводчики при необходимости. Лучше сразу привыкать и подтягивать навыки чтения на английском, иначе будут сложности в будущем. + +В PHP есть функция `ucfirst()`. Изучите её сигнатуру на странице [https://php.net/manual/ru/function.ucfirst.php](https://php.net/manual/ru/function.ucfirst.php). + +Напишите программу, которая использует функцию `ucfirst()` с переменной `$text` и выводит результат на экран. Значение переменной `$text` уже определено. diff --git a/modules/35-calling-functions/120-function-signature/ru/README.md b/modules/35-calling-functions/120-function-signature/ru/README.md new file mode 100644 index 00000000..29af479d --- /dev/null +++ b/modules/35-calling-functions/120-function-signature/ru/README.md @@ -0,0 +1,70 @@ +В этом уроке мы научимся работать с сигнатурой функции. Также мы узнаем, как функция принимает и возвращает значения. Мы разберем функции `abs()` и `round()`. + +## Функция abs() + +Функция `abs()`, которая возвращает абсолютное значение, принимает параметр — число. Если вызывать `abs()` без параметров, то PHP выдаст следующее: + +``` +TypeError: abs() expects exactly 1 argument, 0 given +``` + +Так интерпретатор сообщает, что функция ожидает один параметр, а мы вызвали ее без параметров. + +Параметрами `abs()` могут быть только числа. Если мы попробуем передать в нее строку, это приведет к следующей ошибке: + +``` +TypeError: abs(): Argument #1 ($num) must be of type int|float, string given +``` + +Результат вызова этой функции — тоже всегда число. Другая функция может иметь иное число параметров и другие типы параметров. Например, может существовать функция, которая принимает три параметра: число, строку и еще одно число. + +Откуда мы знаем, сколько и каких параметров нужно функции `abs()` и какого типа будет возврат? Мы посмотрели в **сигнатуру** этой функции. Сигнатура определяет входные параметры и их типы, а также выходной параметр и его тип. + +О функции `abs()` можно почитать в [официальной документации PHP](https://www.php.net/manual/ru/function.abs.php). В разделе «Описание» есть такой текст: + +```txt +abs(int|float $num): int|float + +Возвращает абсолютное значение num. +``` + +Это сигнатура функции и короткое пояснение на русском языке. + +Информация расшифровывается так: + +* Функция называется `abs` +* Функция принимает параметр: число (num) +* Функция возвращает число +* Функция возвращает абсолютное значение num + +Если параметров больше одного, то передавать их можно только в той последовательности, в которой они определены в сигнатуре. Любая функция возвращает всегда только одно значение. Это ограничение существует на уровне языка, и не может нарушаться. + +## Аргументы по умолчанию + +Рассмотрим функцию `round()`. Она округляет переданное число: + +```php +- + формальное описание типов аргументов и типа возвращаемого значения + функции. diff --git a/modules/35-calling-functions/135-calling-functions-default-arguments/en/EXERCISE.md b/modules/35-calling-functions/135-calling-functions-default-arguments/en/EXERCISE.md new file mode 100644 index 00000000..174b1f18 --- /dev/null +++ b/modules/35-calling-functions/135-calling-functions-default-arguments/en/EXERCISE.md @@ -0,0 +1,2 @@ + +Round up the number written in the $number variable to two decimal places and display the result on the screen. diff --git a/modules/35-calling-functions/135-calling-functions-default-arguments/en/README.md b/modules/35-calling-functions/135-calling-functions-default-arguments/en/README.md new file mode 100644 index 00000000..ed576cf0 --- /dev/null +++ b/modules/35-calling-functions/135-calling-functions-default-arguments/en/README.md @@ -0,0 +1,28 @@ + +Let's look at the `round()` function. It rounds up the number passed to it: + +```php + +First: N +Last: t + + +Try to only create one variable you want to assign the text to before you print it. In this lesson, we're practising building a compound expression. diff --git a/modules/35-calling-functions/150-calling-functions-expression/en/README.md b/modules/35-calling-functions/150-calling-functions-expression/en/README.md new file mode 100644 index 00000000..539ba9fe --- /dev/null +++ b/modules/35-calling-functions/150-calling-functions-expression/en/README.md @@ -0,0 +1,63 @@ +In programming, an expression is something that returns a usable output value. We already know a lot about expressions and how they're made. Math operations (addition, subtraction, etc.) and string operations (concatenation) are all expressions: + +```php + 2 +``` + +All of this applies for any function, e.g., string functions: + +```php + 'Last character: p' +``` diff --git a/modules/35-calling-functions/150-calling-functions-expression/en/data.yml b/modules/35-calling-functions/150-calling-functions-expression/en/data.yml new file mode 100644 index 00000000..44c91eb7 --- /dev/null +++ b/modules/35-calling-functions/150-calling-functions-expression/en/data.yml @@ -0,0 +1 @@ +name: Function call - expression diff --git a/modules/35-calling-functions/150-calling-functions-expression/es/EXERCISE.md b/modules/35-calling-functions/150-calling-functions-expression/es/EXERCISE.md new file mode 100644 index 00000000..6b6cfb93 --- /dev/null +++ b/modules/35-calling-functions/150-calling-functions-expression/es/EXERCISE.md @@ -0,0 +1,8 @@ +Muestra en pantalla la primera y la última letra de la oración que se encuentra en la variable `text`, en el siguiente formato: + +
+First: N
+Last: t
+
+ +Intenta crear solo una variable en la que se almacene el texto necesario antes de imprimirlo en pantalla. En esta lección, estamos practicando cómo construir una expresión compuesta. diff --git a/modules/35-calling-functions/150-calling-functions-expression/es/README.md b/modules/35-calling-functions/150-calling-functions-expression/es/README.md new file mode 100644 index 00000000..c0a0cebe --- /dev/null +++ b/modules/35-calling-functions/150-calling-functions-expression/es/README.md @@ -0,0 +1,58 @@ +En programación, una expresión es algo que devuelve un resultado que se puede utilizar. Recordemos que las operaciones matemáticas como la suma y la resta, y las operaciones de cadenas de texto, son expresiones: + +```php + 2 +``` + +Todo esto es válido para cualquier función, por ejemplo, las funciones de cadenas de texto: + +```php + Nombre de usuario: Toto +``` diff --git a/modules/35-calling-functions/150-calling-functions-expression/es/data.yml b/modules/35-calling-functions/150-calling-functions-expression/es/data.yml new file mode 100644 index 00000000..e4509f9f --- /dev/null +++ b/modules/35-calling-functions/150-calling-functions-expression/es/data.yml @@ -0,0 +1 @@ +name: Llamada a una función - expresión diff --git a/modules/35-calling-functions/150-calling-functions-expression/ru/EXERCISE.md b/modules/35-calling-functions/150-calling-functions-expression/ru/EXERCISE.md new file mode 100644 index 00000000..07142bf1 --- /dev/null +++ b/modules/35-calling-functions/150-calling-functions-expression/ru/EXERCISE.md @@ -0,0 +1,8 @@ +Выведите на экран первую и последнюю буквы предложения, записанного в переменную `text`, в следующем формате: + +
+First: N
+Last: t
+
+ +Постарайтесь создать только одну переменную, в которую сразу запишется нужный текст перед печатью на экран. В этом уроке мы отрабатываем умение собирать составное выражение. diff --git a/modules/35-calling-functions/150-calling-functions-expression/ru/README.md b/modules/35-calling-functions/150-calling-functions-expression/ru/README.md new file mode 100644 index 00000000..d3b9fdb9 --- /dev/null +++ b/modules/35-calling-functions/150-calling-functions-expression/ru/README.md @@ -0,0 +1,58 @@ +В программировании выражение – нечто возвращающее результат, который можно использовать. Напомним, что математические операции по типу сложения и вычитания и строковые операции — это выражения: + +```php + 2 +``` + +Все это справедливо для любых функций, например, строковых: + +```php + Имя пользователя: Toto +``` diff --git a/modules/35-calling-functions/150-calling-functions-expression/ru/data.yml b/modules/35-calling-functions/150-calling-functions-expression/ru/data.yml new file mode 100644 index 00000000..b61f18a6 --- /dev/null +++ b/modules/35-calling-functions/150-calling-functions-expression/ru/data.yml @@ -0,0 +1 @@ +name: Вызов функции — выражение diff --git a/modules/35-calling-functions/180-variadic-arguments/en/EXERCISE.md b/modules/35-calling-functions/180-variadic-arguments/en/EXERCISE.md new file mode 100644 index 00000000..069d01c6 --- /dev/null +++ b/modules/35-calling-functions/180-variadic-arguments/en/EXERCISE.md @@ -0,0 +1,2 @@ + +Calculate the minimum number (in PHP) out of 3, 10, 22, -3, 0, and display it. Use the `min()` function, which works in the same way as `max()`. diff --git a/modules/35-calling-functions/180-variadic-arguments/en/README.md b/modules/35-calling-functions/180-variadic-arguments/en/README.md new file mode 100644 index 00000000..ffd27ed5 --- /dev/null +++ b/modules/35-calling-functions/180-variadic-arguments/en/README.md @@ -0,0 +1,22 @@ + +An interesting feature of some functions is that they can accept a varying number of arguments. We're not talking about default values. Check out this example: + +```php + + [Funciones + deterministas](https://es.wikipedia.org/wiki/Funci%C3%B3n_pura#Determinismo_de_la_funci%C3%B3n) diff --git a/modules/35-calling-functions/270-deterministic/ru/EXERCISE.md b/modules/35-calling-functions/270-deterministic/ru/EXERCISE.md new file mode 100644 index 00000000..e73eaa8a --- /dev/null +++ b/modules/35-calling-functions/270-deterministic/ru/EXERCISE.md @@ -0,0 +1 @@ +Выведите на экран случайное число от 1 до 6. Для реализации вам потребуется функция `rand()`, которая может принимать два числа: начальное и конечное diff --git a/modules/35-calling-functions/270-deterministic/ru/README.md b/modules/35-calling-functions/270-deterministic/ru/README.md new file mode 100644 index 00000000..a76431ae --- /dev/null +++ b/modules/35-calling-functions/270-deterministic/ru/README.md @@ -0,0 +1,53 @@ +Независимо от того, какой язык программирования используется, функции внутри него обладают некоторыми фундаментальными свойствами. Если знать эти свойства, легче прогнозировать поведение функций, способы их тестирования и место их использования. В этом уроке мы изучим такие свойства функций и особенности их работы. + +## Что такое детерминированность + +**Детерминированность** — это одно из фундаментальных свойств функций. Функция будет детерминированной, когда для одних и тех же входных аргументов она возвращает один и тот же результат. Например, функция, которая переворачивает строку, — детерминированная: + +```php + + [Детерминированные + функции](https://ru.wikipedia.org/wiki/Чистота_функции#Детерминированность_функции) diff --git a/modules/35-calling-functions/900-stdlib/en/EXERCISE.md b/modules/35-calling-functions/900-stdlib/en/EXERCISE.md new file mode 100644 index 00000000..92e043bd --- /dev/null +++ b/modules/35-calling-functions/900-stdlib/en/EXERCISE.md @@ -0,0 +1,4 @@ + +The `gettype()` function allows you to determine the type of the argument being passed. The name of the type is returned as a string. For example, a call to `gettype(10)` will return the string `"integer"`. + +Print the type of the value of the variable `$motto`. diff --git a/modules/35-calling-functions/900-stdlib/en/README.md b/modules/35-calling-functions/900-stdlib/en/README.md new file mode 100644 index 00000000..09159d8e --- /dev/null +++ b/modules/35-calling-functions/900-stdlib/en/README.md @@ -0,0 +1,12 @@ + +PHP, like any other language, comes with a set of useful features. Altogether, they make up the so-called **standard library**. It usually contains thousands of functions you can't remember, and that you don't have to. It's assumed that any programmer knows where to look for their documentation and has a rough idea of what they want to achieve. And the rest is a matter of technique. Programming without the Internet is extremely difficult. + +To newcomers, it often looks like this: "Go I know not whither and fetch I know not what". In other words, most people have no idea how to learn about these functions when they don't know anything at all. Oddly enough, there's no way to know everything you need to know once and for all. As you grow as a developer, you'll learn all the exciting features that can solve your problems more elegantly, thus expanding your toolbox. + +Here are some tips to learn about new features: + +* Always keep track of what you're working with at the moment (the data type). You'll almost always find the function you need in the corresponding section of the documentation, e.g. you have to study string functions to work with strings. +* Open the standard functions section of the topic you are studying every now and then and just run through them,, learning the signatures and ways to use them. +* Read other people's code more often, especially code from the libraries you're using. It's all available on GitHub. + +Another feature of PHP functions from the Standard Library is that they're *available globally*. In other words, you can call them anywhere in your program (this doesn't work with functions you've written yourself). Most standard library functions are centered around some functionality or some type of data. For example, there's a large block of functions for processing strings, working with numbers, and so on. We'll go over some of them as you continue to study. diff --git a/modules/35-calling-functions/900-stdlib/en/data.yml b/modules/35-calling-functions/900-stdlib/en/data.yml new file mode 100644 index 00000000..0728a2c8 --- /dev/null +++ b/modules/35-calling-functions/900-stdlib/en/data.yml @@ -0,0 +1,8 @@ +name: Standard Library +tips: + - > + [Description of string + functions](https://www.php.net/manual/en/ref.strings.php) +definitions: + - name: Standard Library + description: a set of useful features included with the programming language. diff --git a/modules/35-calling-functions/900-stdlib/es/EXERCISE.md b/modules/35-calling-functions/900-stdlib/es/EXERCISE.md new file mode 100644 index 00000000..b5e6ec4a --- /dev/null +++ b/modules/35-calling-functions/900-stdlib/es/EXERCISE.md @@ -0,0 +1,4 @@ + +La función `gettype()` permite determinar el tipo de argumento pasado. El nombre del tipo se devuelve como una cadena. Por ejemplo, llamar a `gettype(10)` devolverá la cadena `"integer"` (integer - número entero). + +Muestra en pantalla el tipo de valor de la variable `$motto`. diff --git a/modules/35-calling-functions/900-stdlib/es/README.md b/modules/35-calling-functions/900-stdlib/es/README.md new file mode 100644 index 00000000..dd84490c --- /dev/null +++ b/modules/35-calling-functions/900-stdlib/es/README.md @@ -0,0 +1,15 @@ +PHP viene con un conjunto de funciones útiles. Juntas, forman la **biblioteca estándar**. Por lo general, incluye miles de funciones que no se pueden aprender todas, ni es necesario hacerlo. En esta lección, daremos recomendaciones sobre cómo trabajar con nuevas funciones. + +Se supone que cualquier programador sabe dónde buscar la documentación y tiene una idea aproximada de lo que quiere lograr. Por lo tanto, programar sin internet es extremadamente difícil. + +A menudo, los principiantes no saben a dónde ir ni qué buscar. Estos conocimientos y habilidades se adquieren con la experiencia. Durante el aprendizaje y el trabajo, se familiarizan con funciones más interesantes que resuelven sus problemas de una manera más conveniente. Así es como enriquecen su arsenal. + +Aquí hay algunos consejos sobre cómo aprender sobre nuevas funciones: + +* Siempre es necesario tener en cuenta el tipo de datos con el que se está trabajando. Las funciones necesarias se pueden encontrar en la sección correspondiente de la documentación. Por ejemplo, para trabajar con cadenas, es necesario estudiar las funciones de cadenas. +* De vez en cuando, es necesario abrir la sección de funciones estándar relacionadas con el tema que se está estudiando. Es necesario estudiarlas, sus firmas y formas de uso. +* Es necesario leer el código de otras personas con frecuencia, especialmente el código de bibliotecas que utilizamos. Siempre está disponible en GitHub. + +Otra característica de las funciones de PHP de la biblioteca estándar es que están disponibles globalmente. Se pueden llamar en cualquier parte del programa. Sin embargo, esto no se aplica a las funciones escritas por uno mismo. + +La mayoría de las funciones de la biblioteca estándar se centran en funcionalidades o tipos de datos específicos. Por ejemplo, hay un gran conjunto de funciones para el manejo de cadenas, números, etc. Algunas de ellas las veremos durante el proceso de aprendizaje. diff --git a/modules/35-calling-functions/900-stdlib/es/data.yml b/modules/35-calling-functions/900-stdlib/es/data.yml new file mode 100644 index 00000000..5e326774 --- /dev/null +++ b/modules/35-calling-functions/900-stdlib/es/data.yml @@ -0,0 +1,10 @@ +name: Biblioteca estándar +tips: + - > + [Descripción de las funciones de + cadenas](https://www.php.net/manual/es/ref.strings.php) +definitions: + - name: Biblioteca estándar + description: >- + conjunto de funciones útiles que se incluyen en el lenguaje de + programación. diff --git a/modules/35-calling-functions/900-stdlib/ru/EXERCISE.md b/modules/35-calling-functions/900-stdlib/ru/EXERCISE.md new file mode 100644 index 00000000..78912d36 --- /dev/null +++ b/modules/35-calling-functions/900-stdlib/ru/EXERCISE.md @@ -0,0 +1,4 @@ + +Функция `gettype()` позволяет определить тип передаваемого аргумента. Название типа возвращается в виде строки. Например, вызов `gettype(10)` вернёт строку `"integer"` (integer — целое число). + +Выведите на экран тип значения переменной `$motto`. diff --git a/modules/35-calling-functions/900-stdlib/ru/README.md b/modules/35-calling-functions/900-stdlib/ru/README.md new file mode 100644 index 00000000..54a2a642 --- /dev/null +++ b/modules/35-calling-functions/900-stdlib/ru/README.md @@ -0,0 +1,15 @@ +PHP поставляется с набором полезных функций. Вместе они составляют **стандартную библиотеку**. Обычно в нее входят тысячи функций, которые невозможно выучить, что и не нужно делать. В этом уроке мы дадим рекомендации по работе с новыми функциями. + +Подразумевается, что любой программист знает, где искать документацию по ним и примерно представляет себе, чего он хочет достичь. Поэтому программировать без интернета крайне сложно. + +Часто новички не знают, куда нужно идти и что искать. Эти знания и навыки приходят с опытом. Во время обучения и работы они знакомятся с более интересными функциями, которые решают их задачи более удобным способом. Так они и пополняют свой арсенал. + +Вот некоторые советы, как узнавать о новых функциях: + +* Всегда нужно отслеживать, с каким типом данных идет работа. Необходимые функции можно найти в соответствующем разделе документации. Например, для работы со строками нужно изучать строковые функции +* Периодически нужно открывать раздел со стандартными функциями по изучаемой тематике. Нужно изучать их, сигнатуры и способы использования +* Необходимо часто читать чужой код, особенно, код библиотек, которые используются нами. Он всегда доступен на GitHub + +Еще одна особенность функций PHP из стандартной библиотеки в том, что они доступны глобально. Их можно вызывать в любом месте программы. Правда это не работает с функциями, написанными самостоятельно. + +Большинство функций стандартной библиотеки сосредоточено вокруг определенных функциональности или типа данных. Например, есть большой блок функций по обработке строк, с числами и так далее. По некоторым из них мы пройдемся в процессе обучения. diff --git a/modules/35-calling-functions/900-stdlib/ru/data.yml b/modules/35-calling-functions/900-stdlib/ru/data.yml new file mode 100644 index 00000000..95e04b15 --- /dev/null +++ b/modules/35-calling-functions/900-stdlib/ru/data.yml @@ -0,0 +1,9 @@ +name: Стандартная библиотека +tips: + - | + [Описание строковых функций](https://www.php.net/manual/ru/ref.strings.php) +definitions: + - name: Стандартная библиотека + description: >- + набор полезных функций, входящий в комплект поставки языка + программирования. diff --git a/modules/40-define-functions/100-define/en/EXERCISE.md b/modules/40-define-functions/100-define/en/EXERCISE.md new file mode 100644 index 00000000..147048a1 --- /dev/null +++ b/modules/40-define-functions/100-define/en/EXERCISE.md @@ -0,0 +1,10 @@ + +Implement a function, `printMotto()`, which prints the phrase *Winter is coming*. + +```php + "Winter is coming" +``` + +In tasks where you have to implement a function, you don't need to call it. Automated tests will call this function to check if it works. The example call above is shown just to give you an idea of how your function will be used. diff --git a/modules/40-define-functions/100-define/en/README.md b/modules/40-define-functions/100-define/en/README.md new file mode 100644 index 00000000..1592c5df --- /dev/null +++ b/modules/40-define-functions/100-define/en/README.md @@ -0,0 +1,58 @@ +Defining your own functions makes it much easier to write and maintain programs. Functions allow you to combine several complex operations into one. For example, sending an email on a website is a complex process that involves interacting with external systems over the Internet. Since you can define functions, you can hide all the complexity behind one simple function: + +```php +Hello, Hexlet! + +```php + 'Hello, Hexlet!' +``` + +Unlike normal data, functions perform actions, so their names almost always have to be verbs: "build something", "draw something", "open something", etc. + +Anything described below the indented function name is called the body of the function. It can contain any code. Consider it a small independent program, a set of whatever statements are needed. The body is executed when the function is called. And each function call executes the body independently of other calls. + +The body of the function can be empty: + +```php + + [Naming in + programming](https://hexlet.io/blog/posts/code-complete-naming-in-programming) diff --git a/modules/40-define-functions/100-define/es/EXERCISE.md b/modules/40-define-functions/100-define/es/EXERCISE.md new file mode 100644 index 00000000..d44b785f --- /dev/null +++ b/modules/40-define-functions/100-define/es/EXERCISE.md @@ -0,0 +1,9 @@ +Implementa una función llamada `printMotto()` que mostrará en la pantalla la frase *Winter is coming*. + +```php + "Winter is coming" +``` + +En los ejercicios en los que se requiere implementar una función, no es necesario llamarla. Esto lo hacen las pruebas automatizadas que verifican el funcionamiento de la función. El ejemplo de llamada se muestra arriba solo para que entiendas cómo se usará la función. diff --git a/modules/40-define-functions/100-define/es/README.md b/modules/40-define-functions/100-define/es/README.md new file mode 100644 index 00000000..0406aa6b --- /dev/null +++ b/modules/40-define-functions/100-define/es/README.md @@ -0,0 +1,66 @@ +Recordemos que las funciones pueden ser incorporadas o agregadas por el programador. Ya nos hemos familiarizado con las primeras. Y en esta lección aprenderemos a crear nuestras propias funciones. + +La definición de funciones propias simplifica significativamente la escritura y el mantenimiento de programas. Las funciones permiten combinar operaciones complejas en una sola. Por ejemplo, enviar un correo electrónico en un sitio web es un proceso bastante complicado. Incluye la interacción con sistemas externos. + +Gracias a la capacidad de definir funciones, toda la complejidad se puede ocultar detrás de una función simple: + +```php + '¡Hola, Hexlet!' +``` + +A diferencia de los datos normales, las funciones realizan acciones, por lo que sus nombres casi siempre deben ser verbos: "construir algo", "dibujar algo", "abrir algo". + +Todo lo que se describe debajo del nombre de la función con sangría se llama cuerpo de la función. Dentro del cuerpo se puede describir cualquier código. Se puede decir que es un pequeño programa independiente, un conjunto de instrucciones arbitrarias. + +El cuerpo se ejecuta cuando se inicia la función. Y cada llamada a la función inicia el cuerpo independientemente de otras llamadas. + +El cuerpo de la función puede estar vacío: + +```php + "Winter is coming" +``` + +В задачах, в которых нужно реализовать функцию, эту функцию вызывать не нужно. Вызывать функцию будут автоматизированные тесты, которые проверяют его работоспособность. Пример с вызовом выше показан только для того, чтобы вы понимали, как ваша функция будет использоваться. diff --git a/modules/40-define-functions/100-define/ru/README.md b/modules/40-define-functions/100-define/ru/README.md new file mode 100644 index 00000000..a7c88f4d --- /dev/null +++ b/modules/40-define-functions/100-define/ru/README.md @@ -0,0 +1,68 @@ +Напомним, что функции бывают встроенными и добавленными программистом. С первыми мы уже познакомились. А в этом уроке научимся создавать собственные. + +Определение собственных функций значительно упрощает написание и поддержку программ. Функции позволяют объединять сложные операции в одну. Например, отправка письма на сайте — это достаточно сложный процесс. Он включает в себя взаимодействие с внешними системами. + +Благодаря возможности определять функции, всю сложность можно скрыть за одной простой функцией: + +```php + 'Hello, Hexlet!' +``` + +В отличие от обычных данных, функции выполняют действия, поэтому их имена практически всегда должны быть глаголами: «построить что-то», «нарисовать что-то», «открыть что-то». + +Все, что описывается ниже имени функции с отступом, называется телом функции. Внутри тела можно описывать любой код. Можно сказать, что это маленькая самостоятельная программа, набор произвольных инструкций. + +Тело выполняется в тот момент, когда запускается функция. Причем каждый вызов функции запускает тело независимо от других вызовов. + +Тело функции может быть пустым: + +```php + + [Именование в + программировании](https://ru.hexlet.io/blog/posts/naming-in-programming) diff --git a/modules/40-define-functions/200-return/en/EXERCISE.md b/modules/40-define-functions/200-return/en/EXERCISE.md new file mode 100644 index 00000000..12dbad6f --- /dev/null +++ b/modules/40-define-functions/200-return/en/EXERCISE.md @@ -0,0 +1,8 @@ + +Implement a function caleed `sayHurrayThreeTimes()`, which returns the string 'hurray! hurray! hurray!'. + +```php +$hurray = sayHurrayThreeTimes(); +print_r($hurray); // => 'hurray! hurray! hurray!' + +You don't need to call your function, just define it. diff --git a/modules/40-define-functions/200-return/en/README.md b/modules/40-define-functions/200-return/en/README.md new file mode 100644 index 00000000..c496db3a --- /dev/null +++ b/modules/40-define-functions/200-return/en/README.md @@ -0,0 +1,134 @@ +The functions we defined in the previous lessons ended up printing some data on the screen: + +```php + NULL +``` + +Let's change the `greeting()` function so that it starts returning data instead of printing it. To do this, we need to return instead of printing to the screen + +``` + 'Hello, Hexlet!' +// And even perform some actions on the result +print_r(strtoupper($message)); // => 'HELLO, HEXLET!' +``` + +Any code after return isn't executed: + +```php + ? +``` diff --git a/modules/40-define-functions/200-return/en/data.yml b/modules/40-define-functions/200-return/en/data.yml new file mode 100644 index 00000000..f7488f6f --- /dev/null +++ b/modules/40-define-functions/200-return/en/data.yml @@ -0,0 +1 @@ +name: Return values diff --git a/modules/40-define-functions/200-return/es/EXERCISE.md b/modules/40-define-functions/200-return/es/EXERCISE.md new file mode 100644 index 00000000..27e7cf2a --- /dev/null +++ b/modules/40-define-functions/200-return/es/EXERCISE.md @@ -0,0 +1,8 @@ + +Implementa una función llamada `sayHurrayThreeTimes()` que retorne la cadena '¡hurray! ¡hurray! ¡hurray!'. + +```php +$hurray = sayHurrayThreeTimes(); +print_r($hurray); // => '¡hurray! ¡hurray! ¡hurray!' + +No es necesario llamar a tu función, solo definirla. diff --git a/modules/40-define-functions/200-return/es/README.md b/modules/40-define-functions/200-return/es/README.md new file mode 100644 index 00000000..ef23be61 --- /dev/null +++ b/modules/40-define-functions/200-return/es/README.md @@ -0,0 +1,140 @@ +Las funciones que definimos en lecciones anteriores terminaban su ejecución imprimiendo algún dato en la pantalla: + +```php + NULL +``` + +Modificaremos la función `saludo()` para que comience a retornar datos en lugar de imprimirlos. Para hacerlo, necesitamos usar la instrucción de retorno en lugar de imprimir en pantalla: + +```php + '¡Hola, Hexlet!' +// También podemos realizar acciones con el resultado +print_r(strtoupper($mensaje)); // => '¡HOLA, HEXLET!' +``` + +Cualquier código después de `return` no se ejecuta: + +```php + ? +``` diff --git a/modules/40-define-functions/200-return/es/data.yml b/modules/40-define-functions/200-return/es/data.yml new file mode 100644 index 00000000..7d838cdd --- /dev/null +++ b/modules/40-define-functions/200-return/es/data.yml @@ -0,0 +1,2 @@ +name: Retorno de Valores +tips: [] diff --git a/modules/40-define-functions/200-return/ru/EXERCISE.md b/modules/40-define-functions/200-return/ru/EXERCISE.md new file mode 100644 index 00000000..5bd06279 --- /dev/null +++ b/modules/40-define-functions/200-return/ru/EXERCISE.md @@ -0,0 +1,8 @@ + +Реализуйте функцию `sayHurrayThreeTimes()`, которая возвращает строку 'hurray! hurray! hurray!'. + +```php +$hurray = sayHurrayThreeTimes(); +print_r($hurray); // => 'hurray! hurray! hurray!' + +Вам не нужно вызывать свою функцию, только определить её. diff --git a/modules/40-define-functions/200-return/ru/README.md b/modules/40-define-functions/200-return/ru/README.md new file mode 100644 index 00000000..b7a0b861 --- /dev/null +++ b/modules/40-define-functions/200-return/ru/README.md @@ -0,0 +1,140 @@ +Функции, которые мы определяли в предыдущих уроках, заканчивали свою работу тем, что печатали на экран какие-то данные: + +```php + NULL +``` + +Изменим функцию `greeting()` так, чтобы она начала возвращать данные вместо их печати. Для этого нам понадобится выполнить возврат вместо печати на экран: + +```php + 'Hello, Hexlet!' +// И даже выполнить какие-то действия над результатом +print_r(strtoupper($message)); // => 'HELLO, HEXLET!' +``` + +Любой код после `return` не выполняется: + +```php + ? +``` diff --git a/modules/40-define-functions/200-return/ru/data.yml b/modules/40-define-functions/200-return/ru/data.yml new file mode 100644 index 00000000..af0ea3fa --- /dev/null +++ b/modules/40-define-functions/200-return/ru/data.yml @@ -0,0 +1,2 @@ +name: Возврат значений +tips: [] diff --git a/modules/40-define-functions/300-parameters/en/EXERCISE.md b/modules/40-define-functions/300-parameters/en/EXERCISE.md new file mode 100644 index 00000000..7f86abea --- /dev/null +++ b/modules/40-define-functions/300-parameters/en/EXERCISE.md @@ -0,0 +1,29 @@ + +Implement a function, `truncate()`, which trims a string passed to the function to a specified number of characters, adds a dash at the end, and returns the resulting string. This kind of logic is often used on websites to display long text in short form. The function takes two parameters: + +1. The string that needs to be trimmed +2. The number of characters to keep. + +```php +// Passing text directly +// Trim the text, leaving 2 characters +truncate('hexlet', 2) // 'he...' + +// Through a variable +$text = 'it works!' +// Trim the text, leaving 4 characters +$result = truncate($text, 4); +print_r($result); // => 'it w...' +``` + +This function can be implemented in different ways, we'll tell you just one of them. To do it this way, you need to take a substring from the string passed as the first parameter to the `truncate()` function. Use the [substr()](https://www.php.net/manual/en/function.substr.php) function to do this. Think, based on the assignment, which index should you extract the substring from, and how long should it be? + + ```php + '¡fun...' +``` + +Puedes implementar esta función de diferentes maneras, solo te daremos una pista. Para resolverlo de esta manera, necesitarás extraer una subcadena de la cadena pasada como primer parámetro a la función `truncate()`. Para hacer esto, utiliza la función [substr()](https://www.php.net/manual/es/function.substr.php). Piensa, en función de la tarea, desde qué índice y con qué longitud debes extraer la subcadena. + + ```php + 'it w...' +``` + +Реализовать эту функцию можно различными способами, подскажем лишь один из них. Для решения этим способом вам понадобится взять подстроку из строки, переданной первым параметром в функцию `truncate()`. Используйте для этого функцию [substr()](https://www.php.net/manual/ru/function.substr.php). Подумайте, исходя из задания, с какого индекса и какой длины вам надо извлечь подстроку? + + ```php + "nothing" +myPrint("Hexlet"); // => "Hexlet" +``` + +There can be any number of default parameters: + +```php + "nothing" +myPrint("Hexlet"); // => "Hexlet" +``` + +Puede haber cualquier cantidad de parámetros con valores predeterminados: + +```php + "nothing" +myPrint("Hexlet"); // => "Hexlet" +``` + +Параметров со значениями по умолчанию может быть сколько угодно: + +```php + 4`. It sounds like a question, "Is 5 greater than 4?" The answer is "yes". In other cases, the answer may be "no" (e.g., for `3 < 1`). + +Comparison operators aren't restricted to numbers. You can put them in almost anything, e.g., strings. Every time we visit a website, it compares the username and password we've entered with those in the database. And they'll let us in if we have them (authentication). + +Programming languages have borrowed all the comparison operators from math virtually unchanged. The only major change concerns the equality and inequality operators. In math, the usual equal sign is `=`, but this is rare in programming. In many languages, the symbol `=` is used to assign values to variables, so you need to use `==` or `===` for comparison. + +List of comparison operations: + +* `<` less than +* `<=` less than or equal to +* `>` more than +* `>=` greater than or equal to +* `===` equal to +* `!==` not equal to + +_A tiny note: for equality and inequality, there's also `==` and `!=`, neither of which we'll use because of the possible risks. We'll discuss it later._ + +A logical operation like `5 > 4` or `$password === $text` is an expression, and its result is a special value, `true` or `false`. This is a new data type for us - bool. It has only these two values. + +```php + 4; +print_r($result); // => true +print_r('one' !== 'one'); // => false +``` + +Along with strings and integers and rational numbers, the boolean type is one of the most primitive data types in PHP. + +--- + +Try writing a primitive function that takes a child's age as input and decides whether they are a baby or not. Babies are defined as children under a year old: + +```php +bool(false) + +Now, perform the check on a child who's six months old: + +```php +bool(true) diff --git a/modules/45-logic/10-bool-type/en/data.yml b/modules/45-logic/10-bool-type/en/data.yml new file mode 100644 index 00000000..682ac11d --- /dev/null +++ b/modules/45-logic/10-bool-type/en/data.yml @@ -0,0 +1,4 @@ +name: Logic Type +definitions: + - name: bool + description: 'is a data type with two possible values: true and false.' diff --git a/modules/45-logic/10-bool-type/es/EXERCISE.md b/modules/45-logic/10-bool-type/es/EXERCISE.md new file mode 100644 index 00000000..16be651f --- /dev/null +++ b/modules/45-logic/10-bool-type/es/EXERCISE.md @@ -0,0 +1,10 @@ +Escriba una función `isPensioner()`, que tome la edad como único argumento y verifique si esa edad es de jubilación. Se considera una edad de jubilación a partir de los 60 años. + +Ejemplos de llamadas: + +```php + 4` o `3 < 1`. También existen en programación. Por ejemplo, cuando ingresamos a un sitio web, se comparan el nombre de usuario y la contraseña ingresados con los que están en la base de datos. Si coinciden, se nos permite ingresar, es decir, se autentica. En esta lección, veremos las operaciones de comparación. + +Los lenguajes de programación han adaptado todas las operaciones de comparación matemáticas sin cambios, excepto los operadores de igualdad y desigualdad. En matemáticas, se utiliza el signo igual `=`, pero en programación esto ocurre raramente. + +En muchos lenguajes, el símbolo `=` se utiliza para asignar valores a variables. Por lo tanto, en Python se compara con `==`. + +Lista de operaciones de comparación: + +* `<` — menor que +* `<=` — menor o igual que +* `>` — mayor que +* `>=` — mayor o igual que +* `==` — igual que +* `!=` — no igual que + + +Estas operaciones se aplican no solo a números. Por ejemplo, con el operador de igualdad se pueden comparar cadenas de texto: `password == text` es una comparación de identidad de cadenas de texto que están almacenadas en diferentes variables. + +## Tipo lógico + +Una operación lógica como `5 > 4` o `password == text` es una expresión. Su resultado es un valor especial `True` (verdadero) o `False` (falso). Este es un nuevo tipo de dato para nosotros, el tipo `bool`: + +```php + 4; +print_r($resultado); // => true +print_r('uno' !== 'uno'); // => false +``` + +Solo contiene estos dos valores. Junto con las cadenas de texto (string) y los números enteros y racionales, el tipo booleano (bool) es uno de los tipos de datos primitivos en PHP. + +## Predicados + +Intentemos escribir una función simple que tome la edad de un niño como entrada y determine si es un bebé. Los bebés se consideran aquellos menores de un año. + +Cualquier operación es una expresión, por lo que en una sola línea de la función escribimos "devolver el valor que resulte de la comparación `edad < 1`". Dependiendo del argumento que se reciba, la comparación será verdadera (`True`) o falsa (`False`), y `return` devolverá ese resultado: + +```php + bool(false) +var_dump(esBebe(0.5)); // => bool(true) + +``` diff --git a/modules/45-logic/10-bool-type/es/data.yml b/modules/45-logic/10-bool-type/es/data.yml new file mode 100644 index 00000000..5b3b8906 --- /dev/null +++ b/modules/45-logic/10-bool-type/es/data.yml @@ -0,0 +1,6 @@ +name: Tipo lógico +definitions: + - name: Tipo lógico (bool) + description: >- + un tipo de dato con dos posibles valores: true (verdadero) y false + (falso). diff --git a/modules/45-logic/10-bool-type/ru/EXERCISE.md b/modules/45-logic/10-bool-type/ru/EXERCISE.md new file mode 100644 index 00000000..5867a6ae --- /dev/null +++ b/modules/45-logic/10-bool-type/ru/EXERCISE.md @@ -0,0 +1,10 @@ +Напишите функцию `isPensioner()`, которая принимает возраст в качестве единственного аргумента и проверяет, является ли этот возраст пенсионным. Пенсионным считается возраст 60 лет и больше. + +Примеры вызова: + +```php + 4` или `3 < 1`. Они есть и в программировании. Допустим, когда мы заходим на сайт, введенные логин и пароль сравниваются с теми, какие есть в базе. Если они есть, нас пускают внутрь — аутентифицируют. В этом уроке разберем операции сравнения. + +Языки программирования адаптировали все математические операции сравнения в неизменном виде, кроме операторов равенства и неравенства. В математике для этого используется обычное равно `=`, но в программировании такое встречается редко. + +Во многих языках символ `=` используется, чтобы присвоить переменным значения. Поэтому в php сравнивают с помощью `==`. + +Список операций сравнения: + +* `<` — меньше +* `<=` — меньше или равно +* `>` — больше +* `>=` — больше или равно +* `==` — равно +* `!=` — не равно + + +Эти операции применяются не только к числам. Например, с помощью оператора равенства можно сравнить строки: `password == text` — это сравнение идентичности строк, которые записаны в разных переменных. + +## Логический тип + +Логическая операция типа `5 > 4` или `password == text` — это выражение. Его результат — специальное значение `True` («истина») или `False` («ложь»). Это новый для нас тип данных — `bool`: + +```php + 4; +print_r($result); // => true +print_r('one' !== 'one'); // => false +``` + +Он содержит всего лишь два этих значения. Наряду со строками (string) и целыми и рациональными числами, булев тип (bool) — это один из примитивных типов данных в PHP. + +## Предикаты + +Попробуем написать простую функцию, которая принимает на вход возраст ребенка и определяет, младенец ли он. Младенцами считаются дети до года. + +Любая операция — это выражение, поэтому единственной строчкой функции пишем «вернуть то значение, которое получится в результате сравнения `age < 1`». В зависимости от того, какой аргумент пришел, сравнение будет истинным (`True`) или ложным (`False`), а `return` вернет этот результат: + +```php + bool(false) +var_dump(isInfant(0.5)); // => bool(true) + +``` diff --git a/modules/45-logic/10-bool-type/ru/data.yml b/modules/45-logic/10-bool-type/ru/data.yml new file mode 100644 index 00000000..06693161 --- /dev/null +++ b/modules/45-logic/10-bool-type/ru/data.yml @@ -0,0 +1,4 @@ +name: Логический тип +definitions: + - name: Логический тип (bool) + description: 'тип данных с двумя возможными значениями: true (истина) и false (ложь).' diff --git a/modules/45-logic/15-predicates/en/EXERCISE.md b/modules/45-logic/15-predicates/en/EXERCISE.md new file mode 100644 index 00000000..e7ee1327 --- /dev/null +++ b/modules/45-logic/15-predicates/en/EXERCISE.md @@ -0,0 +1,9 @@ + +Write the function `isMister()` that takes a string and checks if it's the word `'Mister'`. + +```php +bool(false) + +This kind of function is called a predicate. Predicate functions answer a question and always (without exception!) return either `true` or `false`. + +Predicates usually have handy names in every language so that they're easily analyzed. In PHP, predicates usually begin with, but are not limited to, the prefixes `is`, `has` or `can`. Examples: + + * `isInfant()` — «is an infant?» + * `hasChildren()` — «does they have children?» + * `isEmpty()` — «is it empty?» + * `hasErrors()` — «are there any errors?» + +A function can only be considered a predicate **if** it returns a bool. + +--- + +Let's write one more predicate function. It takes a string and checks if it's the word `'Castle'`: + +```php +bool(false) diff --git a/modules/45-logic/15-predicates/en/data.yml b/modules/45-logic/15-predicates/en/data.yml new file mode 100644 index 00000000..b75220b6 --- /dev/null +++ b/modules/45-logic/15-predicates/en/data.yml @@ -0,0 +1,10 @@ +name: Predicates +tips: + - > + [Naming in + programming](https://hexlet.io/blog/posts/code-complete-naming-in-programming) +definitions: + - name: A predicate + description: >- + is an expression that answers a yes or no question using the bool data + type. diff --git a/modules/45-logic/15-predicates/es/EXERCISE.md b/modules/45-logic/15-predicates/es/EXERCISE.md new file mode 100644 index 00000000..2be62fa3 --- /dev/null +++ b/modules/45-logic/15-predicates/es/EXERCISE.md @@ -0,0 +1,9 @@ + +Escribe una función `isMister()` que tome una cadena de texto y verifique si es la palabra `'Mister'`. + +```php +- + una expresión que responde a una pregunta "sí" o "no" utilizando el tipo + bool. diff --git a/modules/45-logic/15-predicates/ru/EXERCISE.md b/modules/45-logic/15-predicates/ru/EXERCISE.md new file mode 100644 index 00000000..076d692d --- /dev/null +++ b/modules/45-logic/15-predicates/ru/EXERCISE.md @@ -0,0 +1,9 @@ + +Напишите функцию `isMister()`, которая принимает строку и проверяет, является ли она словом `'Mister'`. + +```php + + [Именование в + программировании](https://ru.hexlet.io/blog/posts/naming-in-programming) +definitions: + - name: Предикат + description: выражение, отвечающее на вопрос «да» или «нет» с помощью типа bool. diff --git a/modules/45-logic/20-logic-combine-expressions/en/EXERCISE.md b/modules/45-logic/20-logic-combine-expressions/en/EXERCISE.md new file mode 100644 index 00000000..c15f31f3 --- /dev/null +++ b/modules/45-logic/20-logic-combine-expressions/en/EXERCISE.md @@ -0,0 +1,9 @@ + +Implement the `isInternationalPhone()`, function, which checks the format of the passed phone number. If the number starts with *+*, then it's in the international format. + +```php + "Calcular el residuo de la división del número `$number` por 2 y verificar si el residuo es igual a cero; luego devolver el resultado de la comparación de igualdad"* + +--- + +*Recordemos cómo extraer caracteres de una cadena utilizando corchetes:* + +```php +«Вычислить остаток от деления числа `$number` на 2 и сравнить, равен ли остаток нулю; затем вернуть результат проверки равенства»* + +--- + +*Напомним об извлечении символов из строки с помощью квадратных скобок:* + +```php + 8 && $length < 20; +} + +isCorrectPassword('qwerty'); // false +isCorrectPassword('qwerty1234'); // true +isCorrectPassword('zxcvbnmasdfghjkqwertyui'); // false +``` + +`&&` means «AND» (called 'conjunction' in mathematical logic). The whole expression is true only when every operand, all of which are part of the compound expression, is true. In other words, `&&` means «both». This operator's priority is lower than that of comparison operators, so the expression works correctly without parentheses. Another widespread operator alongside `&&` is `||` — «OR» (disjunction). It means "one or the other, or both". Operators can be combined in any number and any sequence, but when `&&` and `||`, appear together, you should label priority with parentheses. + +Below is an example of an advanced function that validates a password: + +```php + 8 && $length < 20) && hasSpecialChars($password); +} +``` + +Another example. We want to buy an apartment that meets these conditions: an area of 100 square meters or more on any street OR an area of 80 square meters or more, but on `Main Street`. + +We'll write a function that checks the apartment. It takes two arguments, the area (a number) and the street name (a string): + +```php += 100 || ($area >= 80 && $street === 'Main Street'); +} + +var_dump(isGoodApartment(91, 'Queens Street')); // => false +var_dump(isGoodApartment(78, 'Queens Street')); // => false +var_dump(isGoodApartment(70, 'Main Street')); // => false + +var_dump(isGoodApartment(120, 'Queens Street')); // => true +var_dump(isGoodApartment(120, 'Main Street')); // => true +var_dump(isGoodApartment(80, 'Main Street')); // => true +``` + +The area of mathematics dealing with logical operators is called Boolean algebra. The truth tables are shown below, and they can be used to figure out the result of an operator: + +## `&&` + +| A | B | A `&&` B | +| ----- | ----- | -------- | +| TRUE | TRUE | **TRUE** | +| TRUE | FALSE | FALSE | +| FALSE | TRUE | FALSE | +| FALSE | FALSE | FALSE | + +A couple of examples: + +```php + 2 && str_starts_with('wow', 'w'); // true + +// true && false; +'start' === 'start' && 8 < 3; // false +``` + +## OR `||` + +| A | B | A `‖` B | +| ----- | ----- | -------- | +| TRUE | TRUE | **TRUE** | +| TRUE | FALSE | **TRUE** | +| FALSE | TRUE | **TRUE** | +| FALSE | FALSE | FALSE | + +A couple of examples: + +```php + 2 || str_starts_with('wow', 'w'); // true + +// false || false; +'start' === 'Start' || 3 < 3; // false +``` diff --git a/modules/45-logic/25-logical-operators/en/data.yml b/modules/45-logic/25-logical-operators/en/data.yml new file mode 100644 index 00000000..02b39806 --- /dev/null +++ b/modules/45-logic/25-logical-operators/en/data.yml @@ -0,0 +1,13 @@ +name: Logical Operators +tips: + - | + [Boolean algebra](https://en.wikipedia.org/wiki/Boolean_algebra_(structure)) + - | + [Conjunction](https://en.wikipedia.org/wiki/Logical_conjunction) + - | + [Disjunction](https://en.wikipedia.org/wiki/Logical_disjunction) +definitions: + - name: Logical operators + description: >- + the «AND» (&&), OR (||), operators, which allow you to create composite + logical conditions. diff --git a/modules/45-logic/25-logical-operators/es/EXERCISE.md b/modules/45-logic/25-logical-operators/es/EXERCISE.md new file mode 100644 index 00000000..ef6a7299 --- /dev/null +++ b/modules/45-logic/25-logical-operators/es/EXERCISE.md @@ -0,0 +1,22 @@ + +Implementa la función `isLeapYear()`, que determina si un año es bisiesto o no. Un año es bisiesto si es divisible (es decir, no tiene residuo) por 400 o si es divisible por 4 y no es divisible por 100. Como puedes ver, toda la lógica necesaria ya está incluida en la definición, solo falta convertirla en código: + +```php += x <= 20`, donde `x` es la longitud de una contraseña específica. Pero en PHP, este truco no funciona. + +Tendremos que hacer dos expresiones lógicas separadas y combinarlas con el operador especial "Y": + +```php += 8 && $longitud <= 20) && tieneCaracteresEspeciales($contraseña); +} + +esContraseñaCorrecta('qwerty'); // false +esContraseñaCorrecta('qwerty1234'); // true +esContraseñaCorrecta('zxcvbnmasdfghjkqwertyui'); // false +``` + +El operador `&&` significa "Y" - en lógica matemática esto se llama **conjunción**. La expresión completa se considera verdadera solo si cada operando es verdadero, es decir, cada una de las expresiones compuestas. En otras palabras, `&&` significa "y esto, y aquello". La prioridad de este operador es menor que la de los operadores de comparación, por lo que la expresión funciona correctamente sin paréntesis. + +Además de `&&`, se utiliza frecuentemente el operador `||` - "O" (**disyunción**). Significa "o esto, o aquello, o ambos". Los operadores se pueden combinar en cualquier cantidad y en cualquier secuencia, pero cuando se encuentran `&&` y `||` al mismo tiempo, es mejor establecer la prioridad con paréntesis. + +El área de las matemáticas que estudia los operadores lógicos se llama álgebra booleana. A continuación, verás las **tablas de verdad** - a partir de ellas se puede determinar el resultado al aplicar los operadores: + +### Y `&&` + +| A | B | A `&&` B | +| ----- | ----- | -------- | +| TRUE | TRUE | **TRUE** | +| TRUE | FALSE | FALSE | +| FALSE | TRUE | FALSE | +| FALSE | FALSE | FALSE | + +### O `||` + +| A | B | A `‖` B | +| ----- | ----- | -------- | +| TRUE | TRUE | **TRUE** | +| TRUE | FALSE | **TRUE** | +| FALSE | TRUE | **TRUE** | +| FALSE | FALSE | FALSE | diff --git a/modules/45-logic/25-logical-operators/es/data.yml b/modules/45-logic/25-logical-operators/es/data.yml new file mode 100644 index 00000000..6b2d8a19 --- /dev/null +++ b/modules/45-logic/25-logical-operators/es/data.yml @@ -0,0 +1,13 @@ +name: Operadores lógicos +tips: + - | + [Álgebra booleana](https://es.wikipedia.org/wiki/%C3%81lgebra_booleana) + - | + [Conjunción](https://es.wikipedia.org/wiki/Conjunci%C3%B3n) + - | + [Disyunción](https://es.wikipedia.org/wiki/Disyunci%C3%B3n) +definitions: + - name: Operadores lógicos + description: >- + operadores 'Y' (&&), 'O' (||) que permiten crear condiciones lógicas + compuestas. diff --git a/modules/45-logic/25-logical-operators/ru/EXERCISE.md b/modules/45-logic/25-logical-operators/ru/EXERCISE.md new file mode 100644 index 00000000..1689474e --- /dev/null +++ b/modules/45-logic/25-logical-operators/ru/EXERCISE.md @@ -0,0 +1,22 @@ + +Реализуйте функцию `isLeapYear()`, которая определяет, является ли год високосным или нет. Год будет високосным, если он кратен (то есть делится без остатка) 400 или он одновременно кратен 4 и не кратен 100. Как видите, в определении уже заложена вся необходимая логика, осталось только переложить её на код: + +```php += x <= 20`, где `x` — это длина конкретного пароля. Но в PHP такой трюк не пройдет. + +Нам придется сделать два отдельных логических выражения и соединить их специальным оператором «И»: + +```php += 8 && $length <= 20) && hasSpecialChars($password); +} + +isCorrectPassword('qwerty'); // false +isCorrectPassword('qwerty1234'); // true +isCorrectPassword('zxcvbnmasdfghjkqwertyui'); // false +``` + +Оператор `&&` означает «И» — в математической логике это называют **конъюнкцией**. Все выражение считается истинным только в том случае, когда истинен каждый операнд — каждое из составных выражений. Иными словами, `&&` означает «и то, и другое». Приоритет этого оператора ниже, чем приоритет операторов сравнения, поэтому выражение отрабатывает правильно без скобок. + +Кроме `&&`, часто используется оператор `||` — «ИЛИ» (**дизъюнкция**). Он означает «или то, или другое, или оба». Операторы можно комбинировать в любом количестве и любой последовательности, но когда одновременно встречаются `&&` и `||`, то приоритет лучше задавать скобками. + +Область математики, в которой изучаются логические операторы, называется булевой алгеброй. Ниже увидите **таблицы истинности** — по ним можно определить, каким будет результат, если применить оператора: + +### И `&&` + +| A | B | A `&&` B | +| ----- | ----- | -------- | +| TRUE | TRUE | **TRUE** | +| TRUE | FALSE | FALSE | +| FALSE | TRUE | FALSE | +| FALSE | FALSE | FALSE | + +### ИЛИ `||` + +| A | B | A `‖` B | +| ----- | ----- | -------- | +| TRUE | TRUE | **TRUE** | +| TRUE | FALSE | **TRUE** | +| FALSE | TRUE | **TRUE** | +| FALSE | FALSE | FALSE | diff --git a/modules/45-logic/25-logical-operators/ru/data.yml b/modules/45-logic/25-logical-operators/ru/data.yml new file mode 100644 index 00000000..d9954bc0 --- /dev/null +++ b/modules/45-logic/25-logical-operators/ru/data.yml @@ -0,0 +1,13 @@ +name: Логические операторы +tips: + - | + [Булева алгебра](https://ru.wikipedia.org/wiki/Булева_алгебра) + - | + [Конъюнкция](https://ru.wikipedia.org/wiki/Конъюнкция) + - | + [Дизъюнкция](https://ru.wikipedia.org/wiki/Дизъюнкция) +definitions: + - name: Логические операторы + description: >- + операторы «И» (&&), ИЛИ (||), позволяющие создавать составные логические + условия. diff --git a/modules/45-logic/28-logical-negation/en/EXERCISE.md b/modules/45-logic/28-logical-negation/en/EXERCISE.md new file mode 100644 index 00000000..3402ab40 --- /dev/null +++ b/modules/45-logic/28-logical-negation/en/EXERCISE.md @@ -0,0 +1,30 @@ + +In this lesson, you'll need to implement the two functions `isPalindrome()` and `isNotPalindrome()` + +1. The `isPalindrome()` function determines whether a word is a palindrome or not. A palindrome is a word that reads the same backwards as it does forwards. + + ```php + 1 + +```php + + +*(an empty string has been printed)* + +Another example: + +```php +1 + +What happened here: + +The **OR** operator only works with the *bool* type, but it's also given the numbers `1` and `0`. + +1. `0` is converted to `false` and `1` is converted to `true`. +2. The result `false || true` is `true`. +3. Now `print_r()` gets `true`, but it only works with strings (not *bool*). +4. `true` is converted to `1`. +5. And the screen displays `1`. + +--- + +In one of our lessons, we looked at the comparison operators `===` and `!==` and mentioned that PHP also has the operators `==` and `!=`, but we shouldn't use them. The difference lies in type conversion: + +```php + false +var_dump('' == false); // => true +``` + +An empty string and `false` are different values, so the `===` operator says "false! they're not equal! + +But the `==` operator converts types, making an empty string and `false` equivalent from its point of view. This conversion is implicit, so avoid the `==` and `!=` operators whenever possible. + +--- + +Remember the negation operator: + +```php + false +``` + +When you use double negation `!!` the result value is equal to the initial value: + +```php + true +``` + +However, this is where type conversions also take place. Therefore, the result of a double negation will always be a _bool_. This trick is used to change the data type. + +--- + +Different programming languages have different transformation rules. Some languages don't convert types themselves at all. Many features of PHP aren't really the best, but this is the historical legacy of the language. If it were created from scratch today, many of the rules and nuances would probably be quite different. diff --git a/modules/45-logic/70-logic-weak-typing/en/data.yml b/modules/45-logic/70-logic-weak-typing/en/data.yml new file mode 100644 index 00000000..b13f8da3 --- /dev/null +++ b/modules/45-logic/70-logic-weak-typing/en/data.yml @@ -0,0 +1,4 @@ +name: Weak Typing - 2 +tips: + - | + [Booleans](https://www.php.net/manual/en/language.types.boolean.php) diff --git a/modules/45-logic/70-logic-weak-typing/es/EXERCISE.md b/modules/45-logic/70-logic-weak-typing/es/EXERCISE.md new file mode 100644 index 00000000..6b622f37 --- /dev/null +++ b/modules/45-logic/70-logic-weak-typing/es/EXERCISE.md @@ -0,0 +1,11 @@ + +Escribe una función `isFalsy()` que verifique si el valor pasado se interpreta como falso en PHP. Para realizar esta verificación, deberás comparar `false` con el valor pasado utilizando `==`. + +```php + 1 +print_r(false); // => (se muestra una cadena vacía en la pantalla) +print_r(0 || 1); // => 1 +``` + +El operador **OR** solo funciona con el tipo *bool*, pero se le dan los números `1` y `0`: + +1. `0` se convierte en `false` y `1` se convierte en `true` +2. El resultado de `false || true` es `true` +3. Ahora `print_r()` recibe `true`, pero solo funciona con cadenas +4. `true` se convierte en `1` +5. Y se muestra `1` en la pantalla + +Aquí es importante destacar la diferencia entre los operadores `===` y `==`. La diferencia radica en la conversión de tipos. + +La cadena vacía y `false` son valores diferentes, por lo que el operador `===` dice "¡Falso! ¡No son iguales!". + +Pero el operador `==` convierte los tipos. Desde su punto de vista, la cadena vacía y `false` son iguales. Esta conversión es implícita, por lo que se recomienda evitar los operadores `==` y `!=` siempre que sea posible: + +```php + false +var_dump('' == false); // => true +``` + +Recordemos la operación de negación. Con una doble negación `!!`, el valor final es igual al valor inicial: + +```php + false +var_dump(!!$respuesta); // => true +``` + +Aquí también se producen conversiones de tipo adicionales. Por lo tanto, el resultado de una doble negación siempre será de tipo _bool_. Se utiliza este truco para cambiar el tipo de datos. + +En diferentes lenguajes de programación, hay diferentes reglas de conversión. Algunos lenguajes no realizan conversiones de tipos por sí mismos. diff --git a/modules/45-logic/70-logic-weak-typing/es/data.yml b/modules/45-logic/70-logic-weak-typing/es/data.yml new file mode 100644 index 00000000..c4edb2fb --- /dev/null +++ b/modules/45-logic/70-logic-weak-typing/es/data.yml @@ -0,0 +1,4 @@ +name: Tipado débil - 2 +tips: + - | + [Booleanos](https://php.net/manual/es/language.types.boolean.php) diff --git a/modules/45-logic/70-logic-weak-typing/ru/EXERCISE.md b/modules/45-logic/70-logic-weak-typing/ru/EXERCISE.md new file mode 100644 index 00000000..96509082 --- /dev/null +++ b/modules/45-logic/70-logic-weak-typing/ru/EXERCISE.md @@ -0,0 +1,11 @@ + +Напишите функцию `isFalsy()`, которая проверяет, трактуется ли переданное значение как ложное с точки зрения PHP. Для выполнения этой проверки вам понадобится сравнить `false` с переданным значением, используя `==`. + +```php + 1 +print_r(false); // => (на экран выводится пустая строка) +print_r(0 || 1); // => 1 +``` + +Оператор **ИЛИ** работает только с типом *bool*, но ему даны числа `1` и `0`: + +1. `0` преобразуется в `false`, а `1` преобразуется в `true` +2. Результат `false || true` — это `true` +3. Теперь `print_r()` получает `true`, но он работает только со строками +4. `true` преобразуется в `1` +5. И на экран выводится `1` + +Здесь важно отметить также отличие операторов `===` и `==`. Оно как раз заключается в преобразовании типов. + +Пустая строка и `false` — это разные значения, поэтому оператор `===` говорит «Ложь! Они не равны!». + +Но оператор `==` преобразует типы. С его точки зрения, пустая строка и `false` равны. Это преобразование неявное, поэтому по возможности избегайте операторов `==` и `!=`: + +```php + false +var_dump('' == false); // => true +``` + +Вспомним операцию отрицания. При двойном отрицании `!!` итоговое значение равно начальному: + +```php + false +var_dump(!!$answer); // => true +``` + +Здесь также дополнительно происходят преобразования типа. Поэтому результатом двойного отрицания всегда будет _bool_. Этим приемом пользуются, чтобы поменять тип данных. + +В разных языках программирования разные правила преобразований. Некоторые языки вообще не преобразовывают типы сами. diff --git a/modules/45-logic/70-logic-weak-typing/ru/data.yml b/modules/45-logic/70-logic-weak-typing/ru/data.yml new file mode 100644 index 00000000..8c74c5be --- /dev/null +++ b/modules/45-logic/70-logic-weak-typing/ru/data.yml @@ -0,0 +1,4 @@ +name: Слабая типизация - 2 +tips: + - | + [Booleans](https://php.net/manual/ru/language.types.boolean.php) diff --git a/modules/48-conditionals/30-if/en/EXERCISE.md b/modules/48-conditionals/30-if/en/EXERCISE.md new file mode 100644 index 00000000..b7c33908 --- /dev/null +++ b/modules/48-conditionals/30-if/en/EXERCISE.md @@ -0,0 +1,9 @@ + +Implement a function, `guessNumber()`, which takes a number and checks if the number is equal to a given number (let it be 42). If it's equal, the function should return the string `'You win!'`, otherwise, it should return the string `'Try again!'`. + +```php + normal +print_r("\n"); +print_r(getTypeOfSentence('Hodor?')); // => question +``` + +We recommend not doing that and always writing **curly brackets**. That way, you can clearly see where the conditional construction body starts and ends. The code becomes clearer and more readable. diff --git a/modules/48-conditionals/30-if/en/data.yml b/modules/48-conditionals/30-if/en/data.yml new file mode 100644 index 00000000..7fa4722b --- /dev/null +++ b/modules/48-conditionals/30-if/en/data.yml @@ -0,0 +1,6 @@ +name: Conditional constructions (if) +definitions: + - name: A conditional construct + description: >- + is a way to set a condition for code execution. For example `if ($x > 10) + { ... }` diff --git a/modules/48-conditionals/30-if/es/EXERCISE.md b/modules/48-conditionals/30-if/es/EXERCISE.md new file mode 100644 index 00000000..f4a8d4ec --- /dev/null +++ b/modules/48-conditionals/30-if/es/EXERCISE.md @@ -0,0 +1,9 @@ + +Implementa la función `guessNumber()`, que recibe un número y verifica si es igual al número dado (supongamos que es 42). Si es igual, la función debe devolver la cadena `'You win!'`, de lo contrario, debe devolver la cadena `'Try again!'`. + +```php +- + forma de establecer una condición para ejecutar código. Por ejemplo, `if + ($x > 10) { ... }` diff --git a/modules/48-conditionals/30-if/ru/EXERCISE.md b/modules/48-conditionals/30-if/ru/EXERCISE.md new file mode 100644 index 00000000..b3fc91e3 --- /dev/null +++ b/modules/48-conditionals/30-if/ru/EXERCISE.md @@ -0,0 +1,9 @@ + +Реализуйте функцию `guessNumber()`, которая принимает число и проверяет, равно ли число заданному (пусть это будет 42). Если равно, то функция должна вернуть строку `'You win!'`, в противном случае нужно вернуть строку `'Try again!'`. + +```php +- + способ задать условие для выполнения кода. Например, `if ($x > 10) { ... + }` diff --git a/modules/48-conditionals/40-if-else/en/EXERCISE.md b/modules/48-conditionals/40-if-else/en/EXERCISE.md new file mode 100644 index 00000000..8097bc77 --- /dev/null +++ b/modules/48-conditionals/40-if-else/en/EXERCISE.md @@ -0,0 +1,20 @@ + +Write a function, `normalizeUrl()`, that normalizes data passed to it. It takes a site address and returns it with `https://` at the beginning. + +The function accepts addresses as `ADDRESS` or `http://ADDRESS`, but always returns the address as `https://ADDRESS` + +There are two possible solutions: + +1. You can compare the first 7 characters of the argument string with the string `http://`. +2. You can use the [strpos](https://www.php.net/manual/en/function.strpos.php), function to check if the string-argument contains the substring `http://`. + +And then it'll either add or not add `https://` accordingly. + +Call examples: + +```php +- + else is a way to specify the block of code that will be executed if the + `if` condition isn't satisfied diff --git a/modules/48-conditionals/40-if-else/es/EXERCISE.md b/modules/48-conditionals/40-if-else/es/EXERCISE.md new file mode 100644 index 00000000..057a424f --- /dev/null +++ b/modules/48-conditionals/40-if-else/es/EXERCISE.md @@ -0,0 +1,20 @@ + +Implementa la función `normalizeUrl()`, que realiza lo que se conoce como normalización de datos. Recibe una dirección de un sitio web y la devuelve con `https://` al principio. + +La función acepta direcciones en forma de `DIRECCIÓN` o `http://DIRECCIÓN`, pero siempre devuelve la dirección en forma de `https://DIRECCIÓN`. + +Hay dos formas de resolverlo: + +1. Puedes comparar los primeros 7 caracteres de la cadena de argumento con la cadena `http://`. +2. Puedes usar la función [strpos](https://php.net/manual/es/function.strpos.php) para verificar si la subcadena `http://` está presente en la cadena de argumento. + +Luego, en base a esto, agregar o no agregar `https://`. + +Ejemplos de uso: + +```php +- + a way to specify a code block that will be executed if the condition in + `if` is not satisfied diff --git a/modules/48-conditionals/40-if-else/ru/EXERCISE.md b/modules/48-conditionals/40-if-else/ru/EXERCISE.md new file mode 100644 index 00000000..e59a9f51 --- /dev/null +++ b/modules/48-conditionals/40-if-else/ru/EXERCISE.md @@ -0,0 +1,20 @@ + +Реализуйте функцию `normalizeUrl()`, которая выполняет так называемую нормализацию данных. Она принимает адрес сайта и возвращает его с `https://` в начале. + +Функция принимает адреса в виде `АДРЕС` или `http://АДРЕС`, но всегда возвращает адрес в виде `https://АДРЕС` + +Есть два пути решения: + +1. Можно сравнить первые 7 символов строки-аргумента со строкой `http://`. +2. Можно использовать функцию [strpos](https://php.net/manual/ru/function.strpos.php), чтобы проверить, содержится ли в строке-аргументе подстрока `http://`. + +А потом на основе этого добавлять или не добавлять `https://`. + +Примеры вызова: + +```php +- + способ задать блок кода, который будет выполнен, если условие с `if` не + удовлетворено diff --git a/modules/48-conditionals/50-else-if/en/EXERCISE.md b/modules/48-conditionals/50-else-if/en/EXERCISE.md new file mode 100644 index 00000000..6e86c83b --- /dev/null +++ b/modules/48-conditionals/50-else-if/en/EXERCISE.md @@ -0,0 +1,21 @@ + +The digital map of Westeros that Sam has made shows Stark allies in green, enemies in red, and neutral families in gray. + +Write a function called `whoIsThisHouseToStarks()` for Sam that takes the family name as input and returns one of three values: `'friend'`, `'enemy'`, `'neutral'`. + +Rules: + + * Friends (`'friend'`): 'Karstark', 'Tully' + * Enemies (`'enemy'`): 'Lannister', 'Frey' + * Any other families are considered neutral + +Call examples: + +```php += 0) { + return $number; + } + + return -$number; +} + +abs(10); // 10 +abs(-10); // 10 +``` + +Can we write it more concisely? Something like return `return ОТВЕТ В ЗАВИСИМОСТИ ОТ УСЛОВИЯ`? That would require an expression following return, but if is a statement, not an expression. + +In PHP, there's a construct that works like the*if-else* construct, but is an expression. It's called the ternary operator. + +The ternary operator is the only JavaScript operator that takes three operands: + +```php += 0 ? $number : -$number; +} +``` + +It generally looks like this: ` ? : `. + +Let's rewrite the initial version of `getTypeOfSentence()` in the same way: + +Before: + +```php + + is a way to turn a simple conditional instruction into an expression, + e.g., `$number >= 0 ? $number : -$number`. diff --git a/modules/48-conditionals/60-ternary-operator/es/EXERCISE.md b/modules/48-conditionals/60-ternary-operator/es/EXERCISE.md new file mode 100644 index 00000000..044c7496 --- /dev/null +++ b/modules/48-conditionals/60-ternary-operator/es/EXERCISE.md @@ -0,0 +1,13 @@ + +Implementa la función `flipFlop()`, que recibe una cadena de texto y, si esa cadena es igual a `'flip'`, devuelve `'flop'`. De lo contrario, la función debe devolver `'flip'`. + +Ejemplos de uso: + +```php += 0) { + return $number; + } + + return -$number; +} + +abs(10); // 10 +abs(-10); // 10 +``` + +¿Se puede escribir de forma más concisa? Algo como `return RESPUESTA DEPENDIENDO DE LA CONDICIÓN`. Para esto, la expresión a la derecha de `return` debe ser una expresión. Pero hay un problema: `if` es una instrucción, no una expresión. + +En PHP existe una construcción que tiene un efecto similar a la construcción *if-else*, pero es una expresión. Se llama **operador ternario**, y es lo que vamos a estudiar en esta lección. + +El **operador ternario** es el único operador de su tipo que requiere tres operandos: + +```php += 0 ? $number : -$number; +} +``` + +El patrón general se ve así: + +```php + ? : ` +``` + +![Operador ternario](assets/ternary-operator.png) + +Vamos a reescribir la función `getTypeOfSentence()` de la misma manera. Veamos cómo era antes: + + ```php + + una forma de convertir una instrucción condicional simple en una + expresión, por ejemplo, `$number >= 0 ? $number : -$number`. diff --git a/modules/48-conditionals/60-ternary-operator/ru/EXERCISE.md b/modules/48-conditionals/60-ternary-operator/ru/EXERCISE.md new file mode 100644 index 00000000..6a1d8457 --- /dev/null +++ b/modules/48-conditionals/60-ternary-operator/ru/EXERCISE.md @@ -0,0 +1,13 @@ + +Реализуйте функцию `flipFlop()`, которая принимает на вход строку и, если эта строка равна `'flip'`, возвращает строку `'flop'`. В противном случае функция должна вернуть `'flip'`. + +Примеры вызова: + +```php += 0) { + return $number; + } + + return -$number; +} + +abs(10); // 10 +abs(-10); // 10 +``` + +Можно ли записать ее лаконичнее? Что-то вроде `return ОТВЕТ В ЗАВИСИМОСТИ ОТ УСЛОВИЯ`? Для этого справа от `return` должно быть выражение. Но есть проблема: `if` — это инструкция, а не выражение. + +В PHP существует конструкция, которая по своему действию аналогична конструкции *if-else*, но при этом является выражением. Она называется **тернарный оператор**, и именно его мы изучим в этом уроке. + +**Тернарный оператор** — единственный в своем роде оператор, требующий три операнда: + +```php += 0 ? $number : -$number; +} +``` + +Общий паттерн выглядит так: + +```php + ? : ` +``` + +![Тернарный оператор](assets/ternary-operator.png) + +Давайте перепишем начальный вариант `getTypeOfSentence()` аналогично. Посмотрим, как было: + + ```php + + способ превратить простую условную инструкцию в выражение, например, + `$number >= 0 ? $number : -$number`. diff --git a/modules/48-conditionals/65-switch/en/EXERCISE.md b/modules/48-conditionals/65-switch/en/EXERCISE.md new file mode 100644 index 00000000..8e6d0d6d --- /dev/null +++ b/modules/48-conditionals/65-switch/en/EXERCISE.md @@ -0,0 +1,13 @@ + +Write a function, `getNumberExplanation()`, that describes a number passed to it. If there's no explanation available, it returns `null`: + +```php +- + operator is an expression that returns the first operand if it's true, and + the second if it isn't. For example, `$name ?: $nickname;`. +tips: + - | + [elvis](https://www.php.net/manual/en/language.operators.comparison.php) diff --git a/modules/48-conditionals/75-elvis/es/EXERCISE.md b/modules/48-conditionals/75-elvis/es/EXERCISE.md new file mode 100644 index 00000000..6f5bf093 --- /dev/null +++ b/modules/48-conditionals/75-elvis/es/EXERCISE.md @@ -0,0 +1,13 @@ + +Escriba una función `generateAmount()` que tome dos números: la cantidad de productos y el costo de la auditoría. Si la cantidad de productos es 0, la función debe devolver el costo de la auditoría multiplicado por 3. Si la cantidad de productos no es 0, la función debe devolver la cantidad de productos. + +Ejemplos de llamadas: + +```php +- + expresión que devuelve el primer operando si es verdadero, y el segundo en + caso contrario. Por ejemplo, `$name ?: $nickname;`. +tips: + - > + [elvis](https://php.net/manual/es/language.operators.comparison.php#language.operators.comparison.ternary) diff --git a/modules/48-conditionals/75-elvis/ru/EXERCISE.md b/modules/48-conditionals/75-elvis/ru/EXERCISE.md new file mode 100644 index 00000000..0968d797 --- /dev/null +++ b/modules/48-conditionals/75-elvis/ru/EXERCISE.md @@ -0,0 +1,13 @@ + +Напишите функцию `generateAmount()`, которая принимает два числа: количество товаров и стоимость аудита. Если товаров 0, то функция возвращает стоимость аудита, умноженную на 3. Если товаров не 0, то функция возвращает количество товаров. + +Примеры вызова: + +```php +- + выражение, возвращающее первый операнд если он true, и второй в ином + случае. Например, `$name ?: $nickname;`. +tips: + - > + [elvis](https://php.net/manual/ru/language.operators.comparison.php#language.operators.comparison.ternary) diff --git a/modules/50-loops/10-while/en/EXERCISE.md b/modules/50-loops/10-while/en/EXERCISE.md new file mode 100644 index 00000000..58364531 --- /dev/null +++ b/modules/50-loops/10-while/en/EXERCISE.md @@ -0,0 +1,17 @@ + +Edit the `printNumbers()` function so that it prints the numbers in reverse order. To do this, go from the upper bound to the lower bound. Essentially, the counter needs to be initialized with the maximum value, and in the body of the loop, it must be incremented down to the lower limit. + + +```php + +4 +3 +2 +1 +finished! + diff --git a/modules/50-loops/10-while/en/README.md b/modules/50-loops/10-while/en/README.md new file mode 100644 index 00000000..2ad493f4 --- /dev/null +++ b/modules/50-loops/10-while/en/README.md @@ -0,0 +1,118 @@ + +Our code is getting more and more complex and extensive. It's still quite far from real applications, which contain tens or hundreds of thousands (sometimes millions) of lines of code. However, our code is already complex enough to make inexperienced programmers feel a bit nervous. Starting with this lesson, we move on to one of the most difficult of the basic topics in programming: *loops*. + +All applications serve very pragmatic purposes. They help manage employees, finances, and entertain, after all. Despite the differences, all these programs contain and execute similar algorithms. What's an algorithm? An algorithm is a sequence of actions (statements) which lead us to an expected result. This description fits any program in general, but with algorithms, we usually mean something more specific. + +Imagine we have a book, and we want to find a particular phrase within it. We remember the phrase itself, but we don't know what page it is on. How do we find the right page? The easiest (and longest) way is to look through the pages one by one until we find the right one. In the worst case, we'll have to look through all the pages, but we still get the result we want. This very process is called an algorithm. It includes a logical verification (if the phrase is found) and an exhaustive page search. The number of pages you'll have to look through isn't known in advance, but the process itself is repeated again and again in exactly the same way. This is why we need loops to perform repetitive actions. In this case, each repetition is called an iteration. + +Let's say we want to write a function that prints all numbers between 1 and a given number (via arguments): + +```php + 1 +// => 2 +// => 3 +``` + +This function cannot be implemented with the tools we've already learned to use, because the number of outputs on the screen is not known in advance. But with loops this won't be a problem: + +```php + +1 +2 +3 +finished! + + +Here we use a `while` loop in the function. It has three elements: + +* The key word here is `while`. It's not a function call, although it resembles it. +* Predicate. A condition given in parentheses after `while`. This condition is computed at each iteration. +* Loop body. Block of code in curly brackets. + +The construction reads like this: "do what's specified in the body of the loop as long as the condition (predicate) `$i <= $lastNumber`». Let's look at how this code works to `printNumbers(3)`: + +```php +- + is an instruction to repeat the code as long as a certain condition is + met. diff --git a/modules/50-loops/10-while/es/EXERCISE.md b/modules/50-loops/10-while/es/EXERCISE.md new file mode 100644 index 00000000..74cf0fb9 --- /dev/null +++ b/modules/50-loops/10-while/es/EXERCISE.md @@ -0,0 +1,16 @@ +Modifica la función `printNumbers()` para que imprima los números en orden inverso. Para hacer esto, debes ir desde el límite superior hasta el límite inferior. Es decir, el contador debe inicializarse con el valor máximo y, en el cuerpo del ciclo, debe disminuir hasta el límite inferior. + + +```php + +4 +3 +2 +1 +finished! + diff --git a/modules/50-loops/10-while/es/README.md b/modules/50-loops/10-while/es/README.md new file mode 100644 index 00000000..209834ce --- /dev/null +++ b/modules/50-loops/10-while/es/README.md @@ -0,0 +1,122 @@ +Los programas que escribimos se vuelven cada vez más complejos y extensos. Aún están muy lejos de ser programas reales, donde la cantidad de líneas de código se mide en decenas y cientos de miles. La complejidad actual puede ser desafiante incluso para personas sin experiencia. A partir de esta lección, nos adentraremos en uno de los temas básicos más complejos de la programación: los **ciclos**. + +Todos los programas de aplicación tienen objetivos pragmáticos. Ayudan a gestionar empleados y finanzas, y también entretienen. A pesar de las diferencias, todos estos programas ejecutan algoritmos incorporados en ellos, que son similares entre sí. ¿Qué es un algoritmo? Un **algoritmo** es una secuencia de acciones o instrucciones que nos lleva a un resultado esperado. Esta descripción se aplica a cualquier programa, pero los algoritmos suelen ser algo más específicos. + +Imagina que tenemos un libro y queremos encontrar una frase específica en su interior. Recordamos la frase, pero no sabemos en qué página está. ¿Cómo encontramos la página que buscamos? La forma más sencilla y lenta es revisar las páginas secuencialmente hasta encontrar la frase deseada. En el peor de los casos, tendríamos que revisar todas las páginas, pero de todas formas obtendríamos el resultado. Este proceso se llama **algoritmo**. Incluye la búsqueda de páginas y comprobaciones lógicas para determinar si encontramos la frase o no. + +No sabemos de antemano cuántas páginas tendremos que revisar, pero el proceso de revisión se repite de la misma manera una y otra vez. Para realizar acciones repetitivas como esta, necesitamos **ciclos**. Cada repetición se llama **iteración**. + +Supongamos que queremos escribir una función que imprima en pantalla todos los números desde uno hasta un número especificado (a través de argumentos): + +```php + 1 +// => 2 +// => 3 +``` + +No es posible implementar esta función con los conocimientos que ya hemos adquirido, ya que no conocemos de antemano la cantidad de impresiones en pantalla. Pero con los ciclos, esto no es un problema: + +```php + 1 +// => 2 +// => 3 +// => finished! +``` + +https://replit.com/@hexlet/php-basics-while + +En el código de la función se utiliza el ciclo `while`. Está compuesto por tres elementos: + +* La palabra clave `while` - a pesar de su similitud con la llamada a funciones, no es una llamada a función. +* El predicado: una condición que se especifica entre paréntesis después de `while` y se evalúa en cada iteración. +* El cuerpo del ciclo: un bloque de código entre llaves. + +Esta construcción se lee de la siguiente manera: "haz lo que se especifica en el cuerpo del ciclo mientras la condición `$i <= $lastNumber` sea verdadera". + +Veamos cómo funciona este código para la llamada `printNumbers(3)`: + +```php +- + Instrucción para repetir el código mientras se cumple una determinada + condición. diff --git a/modules/50-loops/10-while/ru/EXERCISE.md b/modules/50-loops/10-while/ru/EXERCISE.md new file mode 100644 index 00000000..c8165d4d --- /dev/null +++ b/modules/50-loops/10-while/ru/EXERCISE.md @@ -0,0 +1,16 @@ +Модифицируйте функцию `printNumbers()` так, чтобы она выводила числа в обратном порядке. Для этого нужно идти от верхней границы к нижней. То есть, счетчик должен быть инициализирован максимальным значением, а в теле цикла его нужно уменьшать до нижней границы. + + +```php + +4 +3 +2 +1 +finished! + diff --git a/modules/50-loops/10-while/ru/README.md b/modules/50-loops/10-while/ru/README.md new file mode 100644 index 00000000..f0164350 --- /dev/null +++ b/modules/50-loops/10-while/ru/README.md @@ -0,0 +1,122 @@ +Программы, которые мы пишем, становятся все сложнее и объемнее. Они все еще очень далеки от реальных программ, где количество строк кода измеряется десятками и сотнями тысяч. Текущая сложность уже способна заставить напрячься людей без опыта. Начиная с этого урока, мы переходим к одной из самых сложных базовых тем в программировании – **циклам**. + +Любые прикладные программы служат прагматичным целям. Они помогают управлять сотрудниками и финансами, развлекают, в конце концов. Несмотря на различия, все эти программы выполняют заложенные в них алгоритмы, которые похожи между собой. Что это такое? **Алгоритм** — это последовательность действий или инструкций, которая приводит нас к некоему ожидаемому результату. Это описание подходит под любую программу, но под алгоритмами обычно понимается что-то более специфичное. + +Представьте себе, что у нас есть книга, и мы хотим найти внутри нее какую-то конкретную фразу. Саму фразу мы помним, но не знаем, на какой она странице. Как найти нужную страницу? Самый простой и долгий способ — последовательно просматривать страницы до тех пор, пока мы не найдем нужную фразу. В худшем случае придется просмотреть все страницы, но результат мы все равно получим. Именно этот процесс и называется **алгоритмом**. Он включает в себя перебор страниц и логические проверки, нашли мы фразу или нет. + +Заранее неизвестно количество страниц, которое придется посмотреть, но сам процесс просмотра повторяется из раза в раз совершенно одинаково. Для выполнения таких повторяющихся действий как раз и нужны **циклы**. Каждый такой повтор называется **итерацией**. + +Допустим, мы хотим написать функцию, которая выводит на экран все числа от единицы до указанного (через аргументы): + +```php + 1 +// => 2 +// => 3 +``` + +Эту функцию невозможно реализовать уже изученными средствами, так как количество выводов на экран заранее не известно. А с циклами это не составит никаких проблем: + +```php + 1 +// => 2 +// => 3 +// => finished! +``` + +https://replit.com/@hexlet/php-basics-while + +В коде функции использован цикл `while`. Он состоит из трех элементов: + +* Ключевое слово `while` — несмотря на схожесть с вызовом функций, это не вызов функции +* Предикат — условие, которое указывается в скобках после `while` и вычисляется на каждой итерации +* Тело цикла — блок кода в фигурных скобках + +Конструкция читается так: «делать то, что указано в теле цикла, пока истинно условие `$i <= $lastNumber`». + +Разберем работу этого кода для вызова `printNumbers(3)`: + +```php + 't' +// => 'e' +// => 'l' +// => 'x' +// => 'e' +// => 'H' +``` diff --git a/modules/50-loops/25-iteration-over-string/en/README.md b/modules/50-loops/25-iteration-over-string/en/README.md new file mode 100644 index 00000000..fbe3caee --- /dev/null +++ b/modules/50-loops/25-iteration-over-string/en/README.md @@ -0,0 +1,29 @@ + +You can use loops to process strings as well as numbers. Mainly as a way to retrieve a specific character by its index. Below is some sample code that prints the letters of each word on a different line: + +```php + 'A' +// => 'r' +// => 'y' +// => 'a' +``` + +https://replit.com/@hexlet/php-basics-loops-using-printnamebysymbol + +The main thing in this code is to set the right condition in `while`. This can be done in two ways: `$i < strlen($name)` or `$i <= strlen($name) - 1`. Both lead to the same result. diff --git a/modules/50-loops/25-iteration-over-string/en/data.yml b/modules/50-loops/25-iteration-over-string/en/data.yml new file mode 100644 index 00000000..f4407e1f --- /dev/null +++ b/modules/50-loops/25-iteration-over-string/en/data.yml @@ -0,0 +1 @@ +name: Traversing strings diff --git a/modules/50-loops/25-iteration-over-string/es/EXERCISE.md b/modules/50-loops/25-iteration-over-string/es/EXERCISE.md new file mode 100644 index 00000000..24c3c9db --- /dev/null +++ b/modules/50-loops/25-iteration-over-string/es/EXERCISE.md @@ -0,0 +1,16 @@ + +Implementa la función `printReversedWordBySymbol()`, que imprime la palabra pasada como argumento carácter por carácter, como se muestra en el ejemplo de la teoría, pero en orden inverso. + +```php + 't' +// => 'e' +// => 'l' +// => 'x' +// => 'e' +// => 'H' +``` diff --git a/modules/50-loops/25-iteration-over-string/es/README.md b/modules/50-loops/25-iteration-over-string/es/README.md new file mode 100644 index 00000000..c1821103 --- /dev/null +++ b/modules/50-loops/25-iteration-over-string/es/README.md @@ -0,0 +1,34 @@ +Los bucles no solo son útiles para trabajar con números, sino también para trabajar con cadenas de caracteres, gracias a la posibilidad de acceder a un carácter específico mediante su índice. A continuación se muestra un ejemplo de código que imprime las letras de cada palabra en líneas separadas: + +```php + 'A' +// => 'r' +// => 'y' +// => 'a' +``` + +https://replit.com/@hexlet/php-basics-loops-using-printnamebysymbol + +Lo más importante en este código es establecer la condición correcta en el `while`. Esto se puede hacer de dos formas: + +* `$i < strlen($nombre)` +* `$i <= strlen($nombre) - 1` + +Ambas formas conducen al mismo resultado. diff --git a/modules/50-loops/25-iteration-over-string/es/data.yml b/modules/50-loops/25-iteration-over-string/es/data.yml new file mode 100644 index 00000000..54646028 --- /dev/null +++ b/modules/50-loops/25-iteration-over-string/es/data.yml @@ -0,0 +1,2 @@ +name: Recorriendo una cadena de caracteres +tips: [] diff --git a/modules/50-loops/25-iteration-over-string/ru/EXERCISE.md b/modules/50-loops/25-iteration-over-string/ru/EXERCISE.md new file mode 100644 index 00000000..3bdf7ffd --- /dev/null +++ b/modules/50-loops/25-iteration-over-string/ru/EXERCISE.md @@ -0,0 +1,16 @@ + +Реализуйте функцию `printReversedWordBySymbol()`, которая печатает переданное слово посимвольно, как в примере из теории, но делает это в обратном порядке. + +```php + 't' +// => 'e' +// => 'l' +// => 'x' +// => 'e' +// => 'H' +``` diff --git a/modules/50-loops/25-iteration-over-string/ru/README.md b/modules/50-loops/25-iteration-over-string/ru/README.md new file mode 100644 index 00000000..7bfc7e46 --- /dev/null +++ b/modules/50-loops/25-iteration-over-string/ru/README.md @@ -0,0 +1,34 @@ +Циклы подходят не только для обработки чисел, но и при работе со строками — и это благодаря возможности получить конкретный символ по его индексу. Ниже пример кода, который распечатывает буквы каждого слова на отдельной строке: + +```php + 'A' +// => 'r' +// => 'y' +// => 'a' +``` + +https://replit.com/@hexlet/php-basics-loops-using-printnamebysymbol + +Самое главное в этом коде — поставить правильное условие в `while`. Это можно сделать сразу двумя способами: + +* `$i < strlen($name)` +* `$i <= strlen($name) - 1` + +Оба способа приводят к одному результату. diff --git a/modules/50-loops/25-iteration-over-string/ru/data.yml b/modules/50-loops/25-iteration-over-string/ru/data.yml new file mode 100644 index 00000000..b7b08fce --- /dev/null +++ b/modules/50-loops/25-iteration-over-string/ru/data.yml @@ -0,0 +1,2 @@ +name: Обход строк +tips: [] diff --git a/modules/50-loops/26-conditions-inside-loops/en/EXERCISE.md b/modules/50-loops/26-conditions-inside-loops/en/EXERCISE.md new file mode 100644 index 00000000..df8d909e --- /dev/null +++ b/modules/50-loops/26-conditions-inside-loops/en/EXERCISE.md @@ -0,0 +1,9 @@ + +The function from the theory is case-sensitive. This means that `A` and `a` from its perspective are different characters. Write a version of this function that isn't case-sensitive: + +```php + 6 +echo $x; // => 6 + +echo $x++; // => 6 +echo $x; // => 7 +``` + +What's going on? + +1. We've printed `++$x`. It's a prefix increment, so first the value is increased by 1, and then the result is returned and printed. +2. Since the value has changed, `echo $x` outputs 6. +3. Now display `$x++`. This is a postfix increment, so first the value was returned and displayed, and then the variable was incremented by 1. +4. Since the value has changed, `echo $x` outputs 7. + +Increment and decrement can make code very complex. Things get especially scary when increments are inserted inside other operations: `$x = $i++ - 7 + --$h`. It's impossible to understand such code, and writing it should be considered a serious crime. + +For example, in JavaScript, the linter (the program that checks the code) immediately starts to complain when it sees increment and decrement being used. + +Usage guidelines: + +* Never mix operations/functions that don't have side effects with operations/functions that do have side effects within a single expression. +* Use increment and decrement only if there's no difference between the prefix and postfix version. It should be separate from other expressions and on a separate line of code. diff --git a/modules/50-loops/50-mutators/en/data.yml b/modules/50-loops/50-mutators/en/data.yml new file mode 100644 index 00000000..b3724693 --- /dev/null +++ b/modules/50-loops/50-mutators/en/data.yml @@ -0,0 +1 @@ +name: Increment and decrement diff --git a/modules/50-loops/50-mutators/es/EXERCISE.md b/modules/50-loops/50-mutators/es/EXERCISE.md new file mode 100644 index 00000000..24df00f7 --- /dev/null +++ b/modules/50-loops/50-mutators/es/EXERCISE.md @@ -0,0 +1,13 @@ +El incremento y el decremento no son operaciones muy importantes en PHP y siempre se pueden evitar. La tarea de esta lección no está directamente relacionada con este tema, pero puede utilizar el incremento y el decremento para acostumbrarse a ellos. De lo contrario, este ejercicio es otro entrenamiento para trabajar con bucles, cadenas y condiciones. + +Escriba una función `makeItFunny()` que tome una cadena como entrada y devuelva una copia de la cadena en la que cada elemento n-ésimo esté en mayúsculas. n se especifica como entrada a la función. + +Para determinar cada elemento n-ésimo, se necesita el resto de la división `%`. Piense en cómo se puede utilizar. + +```php + 6 +echo $x; // => 6 + +echo $x++; // => 6 +echo $x; // => 7 +``` + +Discutamos qué sucede paso a paso en el código: + +1. Imprimimos `++$x` - esto es un incremento prefijo, por lo que primero el valor de la variable se incrementa en 1, luego se devuelve el resultado y se imprime en la pantalla. +2. El valor ha cambiado, por lo que `echo $x` imprime 6. +3. Ahora imprimimos `$x++` - esto es un incremento posfijo, por lo que primero se devuelve y se imprime el valor, y luego la variable se incrementa en 1. +4. El valor ha cambiado, por lo que `echo $x` imprime 7. + +El incremento y el decremento pueden complicar significativamente el código. Es especialmente difícil cuando insertamos el incremento dentro de otras operaciones: `$x = $i++ - 7 + --$h`. + +Es imposible entender un código así, por lo que es mejor no utilizar tales construcciones. Por ejemplo, en el lenguaje JavaScript, cuando se verifica el código, el linter comienza a quejarse de inmediato cuando ve el uso de incremento y decremento. + +Recomendamos utilizar estas construcciones de la siguiente manera: + +* Dentro de una expresión, nunca mezcle funciones sin efectos secundarios con funciones con efectos secundarios (lo mismo se aplica a las operaciones). +* Utilice el incremento y el decremento solo donde no haya diferencia entre la forma prefija y la forma posfija: por separado de todo, en su propia línea de código. diff --git a/modules/50-loops/50-mutators/es/data.yml b/modules/50-loops/50-mutators/es/data.yml new file mode 100644 index 00000000..1a71ec56 --- /dev/null +++ b/modules/50-loops/50-mutators/es/data.yml @@ -0,0 +1,2 @@ +name: Incremento y decremento +tips: [] diff --git a/modules/50-loops/50-mutators/ru/EXERCISE.md b/modules/50-loops/50-mutators/ru/EXERCISE.md new file mode 100644 index 00000000..2e13ba71 --- /dev/null +++ b/modules/50-loops/50-mutators/ru/EXERCISE.md @@ -0,0 +1,13 @@ +Инкремент и декремент — не очень важные операции в PHP, и без них всегда можно обойтись. Задание в этом уроке не связано напрямую с этой темой, но вы можете использовать инкремент и декремент, чтобы привыкнуть к ним. В остальном это упражнение — ещё одна тренировка работы с циклами, строками и условиями. + +Напишите функцию `makeItFunny()`, которая принимает на вход строку и возвращает её копию, у которой каждый n-ный элемент переведен в верхний регистр. n – задается на входе в функцию. + +Для определения каждого n-ного элемента понадобится остаток от деления `%`. Подумайте, как его можно использовать. + +```php + 6 +echo $x; // => 6 + +echo $x++; // => 6 +echo $x; // => 7 +``` + +Обсудим, что пошагово происходит в коде: + +1. Вывели на экран `++$x` — это префиксный инкремент, поэтому сначала значение переменной увеличилось на 1, потом результат вернулся и вывелся на экран +2. Значение изменилось, поэтому `echo $x` вывел 6 +3. Теперь выводим на экран `$x++` — это постфиксный инкремент, поэтому сначала значение вернулось и вывелось на экран, а потом переменная увеличилась на 1 +4. Значение изменилось, поэтому `echo $x` вывел 7 + +Инкремент и декремент могут заметно усложнить код. Особенно сложно все становится, когда мы вставляем инкремент внутрь других операций: `$x = $i++ - 7 + --$h`. + +Понять такой код невозможно, поэтому лучше не использовать такие конструкции. Например, в языке JavaScript при проверке кода линтер сразу начинает ругаться, когда видит использование инкремента и декремента. + +Мы советуем пользоваться этими конструкциями так: + +* В рамках одного выражения никогда не смешивайте функции без побочных эффектов с функциями с побочными эффектами (то же самое касается операций) +* Используйте инкремент и декремент только там, где нет разницы между префиксным и постфиксным вариантом: отдельно от всего, на своей собственной строчке кода diff --git a/modules/50-loops/50-mutators/ru/data.yml b/modules/50-loops/50-mutators/ru/data.yml new file mode 100644 index 00000000..6ae2d724 --- /dev/null +++ b/modules/50-loops/50-mutators/ru/data.yml @@ -0,0 +1,2 @@ +name: Инкремент и декремент +tips: [] diff --git a/modules/50-loops/55-return-from-loop/en/EXERCISE.md b/modules/50-loops/55-return-from-loop/en/EXERCISE.md new file mode 100644 index 00000000..0ead009f --- /dev/null +++ b/modules/50-loops/55-return-from-loop/en/EXERCISE.md @@ -0,0 +1,16 @@ + +Implement a function called `hasChar()`, which checks if a string contains a letter in the specified case. The function takes two parameters: + +* A string +* A letter to be found + +Call example: + +```php + El ciclo con el índice `$i` se repite mientras se cumpla la condición `$i < strlen($str)`, y después de cada paso, `$i` se incrementa en 1. + +Veamos qué se encuentra entre paréntesis: + +1. Valor inicial del contador: este código se ejecuta exactamente una vez antes de la primera iteración. +2. Predicado (condición de repetición del ciclo): se ejecuta en cada iteración, al igual que en el `while`. +3. Descripción del cambio del contador: este código se ejecuta al final de cada iteración. + +Por lo demás, el funcionamiento es exactamente igual al del ciclo `while`. diff --git a/modules/50-loops/70-for/es/data.yml b/modules/50-loops/70-for/es/data.yml new file mode 100644 index 00000000..b0dffac4 --- /dev/null +++ b/modules/50-loops/70-for/es/data.yml @@ -0,0 +1,2 @@ +name: Ciclo For +tips: [] diff --git a/modules/50-loops/70-for/ru/EXERCISE.md b/modules/50-loops/70-for/ru/EXERCISE.md new file mode 100644 index 00000000..36ffaad0 --- /dev/null +++ b/modules/50-loops/70-for/ru/EXERCISE.md @@ -0,0 +1,20 @@ + +Реализуйте функцию `sumOfSeries()`, которая считает сумму [ряда целых чисел](https://ru.wikipedia.org/wiki/Числовой_ряд). Ряд задаётся двумя числами — начальным и конечным. + +Функция принимает два аргумента-числа и возвращает сумму ряда. Например, для аргументов `4` и `7` сумма будет `4 + 5 + 6 + 7 = 22`. + +```php + Цикл с индексом `$i` повторяется, пока соблюдается условие `$i < strlen($str)`, и после каждого шага `$i` увеличивается на 1 + +Посмотрим, что находится в круглых скобках: + +1. Начальное значение счетчика — этот код выполняется ровно один раз перед первой итерацией +2. Предикат (условие повторения циклов) — выполняется на каждой итерации, как и в `while` +3. Описание изменения счетчика — этот код выполняется в конце каждой итерации + +В остальном принцип работы точно такой же, как у цикла `while`. diff --git a/modules/50-loops/70-for/ru/data.yml b/modules/50-loops/70-for/ru/data.yml new file mode 100644 index 00000000..3debe3c2 --- /dev/null +++ b/modules/50-loops/70-for/ru/data.yml @@ -0,0 +1,2 @@ +name: Цикл For +tips: [] diff --git a/modules/60-deep-into-strings/10-unicode/en/EXERCISE.md b/modules/60-deep-into-strings/10-unicode/en/EXERCISE.md new file mode 100644 index 00000000..984787e9 --- /dev/null +++ b/modules/60-deep-into-strings/10-unicode/en/EXERCISE.md @@ -0,0 +1,9 @@ + +Write a version of `invertCase()` that inverts the case of each character in the string you pass. + +```php + 13 +``` + +https://replit.com/@hexlet/php-basics-strings-deeper-strlen + +Languages are divided into two camps. Some have built support into existing functions, and the switch to UTF-8 had no effect on programming. Among them are Java, Ruby, and JavaScript. But PHP went its own special way. In order to work with multibyte encodings, a separate [extension for working with multibyte strings](https://www.php.net/manual/en/book.mbstring.php), was added to the language, which for the most part adds many functions for working with strings, with the only difference that each function of them has the prefix `mb_` (multibyte). + +```php + 7 +``` + +https://replit.com/@hexlet/php-strings-deeper-mbstrlen + +But there's no decent alternative to taking a specific character in the string by index. This task should be performed using `mb_substr()`. + +```php + Øèðîêàÿ ýëåêòðèôèêàöèÿ þæíûõ ãóáåðíèé äàñò ìîùíûé òîë÷îê ïîäú¸ìó ñåëüñêîãî õîçÿéñòâà + +Estos caracteres aparecen porque el mismo código en diferentes codificaciones corresponde a caracteres completamente diferentes, excepto los primeros 128. Por lo tanto, el texto que utiliza letras en inglés siempre se lee correctamente, pero en otros casos, depende de la suerte. La situación se complicaba aún más porque incluso dentro de un solo alfabeto se creaban múltiples codificaciones diferentes, como Windows-1252, KOI8-R, CP 866, ISO 8859-5. + +En ese momento, en los lenguajes de programación, todas las funciones para trabajar con cadenas de texto se creaban asumiendo que un carácter era igual a un byte. Al menos, esta propiedad era común a todas las codificaciones. + +Las diferentes codificaciones se convirtieron en la causa de problemas constantes en la interacción entre personas y programas. Esta problemática se agravó especialmente con el desarrollo de Internet. Esta situación no podía continuar indefinidamente, y finalmente se creó el estándar **Unicode**. + +Actualmente, Unicode contiene más de 100,000 caracteres y abarca todos los idiomas existentes, incluso los muertos. El estándar Unicode no es una codificación y no dice nada sobre cómo se deben almacenar los caracteres en la memoria, solo establece la relación entre un carácter y un número. + +La forma específica de codificar Unicode se determina mediante las codificaciones correspondientes, entre las que se encuentran UTF-8, UTF-16 y algunas otras. En estas codificaciones, un solo byte ya no es suficiente para almacenar un carácter, se necesitan más bytes. UTF-8 se comporta de manera más inteligente: utiliza un byte para los caracteres del alfabeto inglés y algunos otros, y dos bytes para otros alfabetos. + +Después de muchos años de popularización de Unicode, ocurrió un milagro y ahora la gran mayoría del software utiliza UTF-8. Este proceso fue doloroso y tuvo diferentes efectos en los lenguajes de programación. Por ejemplo, en PHP, las funciones estándar no admiten codificaciones multibyte: + +```php + 6 +``` + +https://replit.com/@hexlet/php-basics-strings-deeper-strlen + +Los lenguajes se dividieron en dos campos. Algunos lenguajes incorporaron soporte para codificaciones multibyte en las funciones existentes, por lo que el cambio a UTF-8 no afectó el proceso de programación. Entre estos lenguajes se encuentran Java, Ruby, JavaScript. + +Sin embargo, PHP siguió su propio camino. Para trabajar con codificaciones multibyte, se agregó una [extensión separada para trabajar con cadenas multibyte](https://php.net/manual/es/book.mbstring.php) al lenguaje. En su mayoría, esta extensión agrega muchas funciones para trabajar con cadenas, con la única diferencia de que cada función tiene el prefijo `mb_` (_multibyte_): + +```php + 6 +``` + +https://replit.com/@hexlet/php-strings-deeper-mbstrlen + +Sin embargo, no existe una alternativa adecuada para obtener un carácter específico en una cadena por su índice. Esta tarea se debe realizar utilizando la función `mb_substr()`: + +```php + Øèðîêàÿ ýëåêòðèôèêàöèÿ þæíûõ ãóáåðíèé äàñò ìîùíûé òîë÷îê ïîäú¸ìó ñåëüñêîãî õîçÿéñòâà + +Возникают они потому, что один и тот же код в разных кодировках соответствует совершенно разным символам, за исключением первых 128. Поэтому текст, использующий английские буквы всегда читался, а в остальном — как повезет. Ситуация усугублялась тем, что даже в рамках одного алфавита создавалось множество разных кодировок, например: Windows-1252, KOI8-R, CP 866, ISO 8859-5. + +В языках программирования на тот момент все функции для работы со строками создавались из расчета, что один символ — это один байт. По крайней мере, это свойство было общим для всех кодировок. + +Разные кодировки стали причиной постоянных проблем при взаимодействии людей и программ. Особенно остро эта проблема проявилась с развитием интернета. Такая ситуация не могла продолжаться бесконечно, и в конце концов был создан стандарт **Юникод** (_Unicode_). + +Сейчас он содержит более 100 тысяч символов и включает в себя все существующие языки, даже мертвые. Стандарт Юникод не является кодировкой и ничего не говорит о том, как должны храниться символы в памяти, он лишь определяет связь между символом и некоторым числом. + +Конкретный способ кодирования Юникода определяется соответствующими кодировками, среди которых есть UTF-8, UTF-16 и некоторые другие. В этих кодировках для хранения одного символа уже недостаточно одного байта, они используют больше. UTF-8 ведет себя хитрее: для символов английского алфавита и некоторых других используется один байт, для других алфавитов — два байта. + +После многих лет популяризации Юникода свершилось чудо, и сейчас подавляющее большинство программного обеспечения использует UTF-8. Этот процесс был болезненный и по-разному отразился на языках программирования. Например, в PHP стандартные функции не поддерживают многобайтовые кодировки: + +```php + 13 +``` + +https://replit.com/@hexlet/php-basics-strings-deeper-strlen + +Языки разделились на два лагеря. Одни языки встроили поддержку в уже существующие функции — в итоге переход на UTF-8 никак не отразился на процессе программирования. Среди таких языков есть Java, Ruby, JavaScript. + +А вот PHP пошел своим путем. Для работы с многобайтовыми кодировками в язык добавили отдельное [расширение по работе с многобайтовыми строками](https://php.net/manual/ru/book.mbstring.php). По большей части оно добавляет множество функций для работы со строками, с той лишь разницей, что каждая функция из них имеет префикс `mb_` (_multibyte_): + +```php + 7 +``` + +https://replit.com/@hexlet/php-strings-deeper-mbstrlen + +А вот достойной альтернативы взятию конкретного символа в строке по индексу не существует. Такую задачу нужно выполнять с помощью функции `mb_substr()`: + +```php + 1.234 +setlocale(LC_NUMERIC, 'ru_RU'); +print_r(1.234); // => 1,234 +``` + +If you pass `0` as second argument instead of the locale: `setlocale(LC_ALL, 0)`, the function will return the currently set locale for the category. diff --git a/modules/60-deep-into-strings/30-locales/en/data.yml b/modules/60-deep-into-strings/30-locales/en/data.yml new file mode 100644 index 00000000..ef247bef --- /dev/null +++ b/modules/60-deep-into-strings/30-locales/en/data.yml @@ -0,0 +1 @@ +name: Localization diff --git a/modules/60-deep-into-strings/30-locales/es/EXERCISE.md b/modules/60-deep-into-strings/30-locales/es/EXERCISE.md new file mode 100644 index 00000000..3a8251d8 --- /dev/null +++ b/modules/60-deep-into-strings/30-locales/es/EXERCISE.md @@ -0,0 +1 @@ +Muestra en pantalla la localización actual para la categoría `LC_CTYPE`. diff --git a/modules/60-deep-into-strings/30-locales/es/README.md b/modules/60-deep-into-strings/30-locales/es/README.md new file mode 100644 index 00000000..19685b9c --- /dev/null +++ b/modules/60-deep-into-strings/30-locales/es/README.md @@ -0,0 +1,36 @@ +La globalización se manifiesta en muchos aspectos, incluyendo un sistema de medidas unificado: tiempo, tamaños y distancias, temperaturas, fechas y mucho más. + +Por supuesto, hay países que se desvían de la corriente general. Por ejemplo, Estados Unidos es prácticamente el único país en el que se mantiene y prevalece el [sistema de medidas inglés](https://es.wikipedia.org/wiki/Sistema_imperial_de_medidas). Estados Unidos utiliza millas en lugar de kilómetros y libras en lugar de kilogramos. En muchos países orientales, los calendarios están organizados de manera diferente, y en algún lugar se encuentra el año cuatro mil. Pero en general, todo está estandarizado. + +A pesar de esta estandarización, cada país tiene sus propias particularidades en cuanto a la forma de escribir, comparar y otros aspectos. Por ejemplo, en Estados Unidos es común colocar el mes primero y luego el día en las fechas. En algunos países, se utiliza el punto para representar números decimales, mientras que en otros se utiliza la coma: `1,234`. + +Estas particularidades no necesariamente están vinculadas a un país en su totalidad. Dentro de un mismo país puede haber múltiples divisiones adicionales. Cada conjunto de estas particularidades se llama **localización**, y el proceso de adaptación a las particularidades de una localización específica se llama **localización**. + +La localización es importante en el software. Los usuarios siempre esperan que cualquier software o sitio web funcione de manera predecible. Esto incluye la localización. Es comprensible que resolver esta tarea por sí mismo sea demasiado costoso. Afortunadamente, no es necesario hacerlo. La localización generalmente está incorporada en el propio lenguaje o en bibliotecas especiales. + +En PHP, la función [setlocale()](https://secure.php.net/manual/es/function.setlocale.php) se utiliza para gestionar la localización. Esta función configura la localización de forma global. Su llamada afecta a todas las funciones posteriores que dependen de la localización: + +```php +setlocale(int $category, string $locales, string ...$rest): string|false +``` + +El primer parámetro de esta función es el nombre de la categoría (como una constante) a la que se debe aplicar la localización, que se pasa como argumento en los parámetros siguientes: + +* LC_ALL — todo lo siguiente +* LC_COLLATE — funciones de comparación de cadenas `strcoll()` +* LC_CTYPE — funciones de conversión y clasificación de cadenas, como `strtoupper()` +* LC_MONETARY — para la función `localeconv()` +* LC_NUMERIC — establece el símbolo de separación decimal `localeconv()` +* LC_TIME — formato de fecha y hora con la función `strftime()` + +Veamos un ejemplo de cómo la localización establecida afecta la visualización de los datos: + +```php + 1.234 +setlocale(LC_NUMERIC, 'ru_RU'); +print_r(1.234); // => 1,234 +``` + +Intentemos pasar `0` como segundo argumento en lugar de una localización: `setlocale(LC_ALL, 0)`. En este caso, la función devolverá la localización actual establecida para la categoría. diff --git a/modules/60-deep-into-strings/30-locales/es/data.yml b/modules/60-deep-into-strings/30-locales/es/data.yml new file mode 100644 index 00000000..9d85e2d7 --- /dev/null +++ b/modules/60-deep-into-strings/30-locales/es/data.yml @@ -0,0 +1,3 @@ +name: Localización +tips: [] +definitions: [] diff --git a/modules/60-deep-into-strings/30-locales/ru/EXERCISE.md b/modules/60-deep-into-strings/30-locales/ru/EXERCISE.md new file mode 100644 index 00000000..0b91a83a --- /dev/null +++ b/modules/60-deep-into-strings/30-locales/ru/EXERCISE.md @@ -0,0 +1 @@ +Выведите на экран текущую локаль для категории `LC_CTYPE`. diff --git a/modules/60-deep-into-strings/30-locales/ru/README.md b/modules/60-deep-into-strings/30-locales/ru/README.md new file mode 100644 index 00000000..67dd2331 --- /dev/null +++ b/modules/60-deep-into-strings/30-locales/ru/README.md @@ -0,0 +1,36 @@ +Глобализация проявляется во многих аспектах, в том числе в единой системе мер: время, размеры и расстояния, температуры, даты и многое другое. + +Конечно, есть страны, которые выпадают из общего потока. Например, США — это чуть ли не единственная страна, в которой сохраняется и превалирует [английская система мер](https://ru.wikipedia.org/wiki/Английская_система_мер). США использует мили вместо километров и фунты вместо килограммов. Во многих восточных странах по-другому устроены календари, и где-то сейчас идет четырехтысячный год. Но в целом все унифицировано. + +Несмотря на эту унификацию, в каждой стране есть свои особенности по способу записи, сравнению и другим аспектам. Например, в США принято в датах первым ставить месяц, а вторым — день. В некоторых странах для вывода вещественных чисел используют точку, а в некоторых — запятую: `1,234`. + +Эти особенности необязательно привязаны к целой стране. Внутри одной страны может быть множество дополнительных разделений. Каждый такой набор особенностей называют **локалью**, а процесс адаптации к особенностям конкретной локали — **локализацией**. + +Локализация важна в программном обеспечении. Пользователь всегда ожидает, что любой софт или сайт будет работать предсказуемо. В это понятие включается и локализация. Понятно, что самостоятельное решение этой задачи слишком затратно. К счастью, этого делать не нужно. Локализация обычно встроена в сам язык или в специальные библиотеки. + +В PHP для управления локалью используется функция [setlocale()](https://secure.php.net/manual/ru/function.setlocale.php). Эта функция настраивает локаль глобально. Ее вызов влияет на все последующие функции, опирающиеся на локализацию: + +```php +setlocale(int $category, string $locales, string ...$rest): string|false +``` + +Первым параметром эта функция принимает название категории (как константу), к которой нужно применить локаль, передающуюся в параметрах дальше: + +* LC_ALL — все нижеперечисленное +* LC_COLLATE — функции сравнения строк `strcoll()` +* LC_CTYPE — функции преобразования и классификации строк, например, `strtoupper()` +* LC_MONETARY — для функции `localeconv()` +* LC_NUMERIC — задает символ десятичного разделения `localeconv()` +* LC_TIME — форматирование даты и времени функцией `strftime()` + +Изучим на примере, как установленная локаль влияет на отображение данных: + +```php + 1.234 +setlocale(LC_NUMERIC, 'ru_RU'); +print_r(1.234); // => 1,234 +``` + +Попробуем вторым аргументом передать `0` вместо локали: `setlocale(LC_ALL, 0)`. В таком случае функция будет возвращать текущую установленную локаль для категории. diff --git a/modules/60-deep-into-strings/30-locales/ru/data.yml b/modules/60-deep-into-strings/30-locales/ru/data.yml new file mode 100644 index 00000000..147287bc --- /dev/null +++ b/modules/60-deep-into-strings/30-locales/ru/data.yml @@ -0,0 +1,3 @@ +name: Локализация +tips: [] +definitions: [] diff --git a/modules/60-deep-into-strings/40-startwith/en/EXERCISE.md b/modules/60-deep-into-strings/40-startwith/en/EXERCISE.md new file mode 100644 index 00000000..04e6bb89 --- /dev/null +++ b/modules/60-deep-into-strings/40-startwith/en/EXERCISE.md @@ -0,0 +1,9 @@ + +Complete the implementation of `startsWith()`, which determines whether a string starts with a given substring. + +```php + 00:00:00 UTC 1 de enero de 1970 (jueves) + +El tiempo desde este momento se llama "época de Unix" (_Unix Epoch_). El tiempo Unix se representa como un número entero que aumenta con cada segundo transcurrido, sin necesidad de cálculos para determinar el año, mes, día, hora o minuto. + +Una fecha específica en formato Unix Time se llama **timestamp** - sello de tiempo. Por ejemplo, para obtener el _timestamp_ actual en PHP, se utiliza la función `time()`: + +```php + 00:00:00 UTC 1 января 1970 года (четверг) + +Время с этого момента называют «эрой Unix» (_Unix Epoch_). Unix-время представлено целым числом, которое увеличивается с каждой прошедшей секундой без необходимости вычислений для определения года, месяца, дня, часа или минуты. + +Конкретная дата в формате Unix Time называется **timestamp** — временной штамп. Например, для получения текущего _timestamp_ в PHP используется функция `time()`: + +```php + + [Examples of date + formats](https://www.php.net/manual/en/datetime.format.php) diff --git a/modules/70-dates/20-date/es/EXERCISE.md b/modules/70-dates/20-date/es/EXERCISE.md new file mode 100644 index 00000000..c0a40093 --- /dev/null +++ b/modules/70-dates/20-date/es/EXERCISE.md @@ -0,0 +1,11 @@ +Complete la implementación de la función `getCustomDate()`, que devuelve una fecha en el formato `15/03/1985` basada en el _timestamp_ proporcionado. + +Ejemplos de uso: + +```php + + [Ejemplos de formatos de + fecha](https://www.php.net/manual/ru/datetime.format.php) +definitions: [] diff --git a/modules/70-dates/20-date/ru/EXERCISE.md b/modules/70-dates/20-date/ru/EXERCISE.md new file mode 100644 index 00000000..12587259 --- /dev/null +++ b/modules/70-dates/20-date/ru/EXERCISE.md @@ -0,0 +1,11 @@ +Допишите реализацию функции `getCustomDate()`, которая возвращает дату в формате `15/03/1985` на основе переданного timestamp. + +Примеры вызова: + +```php + + [List of supported time zones in + PHP](https://www.php.net/manual/en/timezones.php) diff --git a/modules/70-dates/40-timezone/es/EXERCISE.md b/modules/70-dates/40-timezone/es/EXERCISE.md new file mode 100644 index 00000000..8ada5e26 --- /dev/null +++ b/modules/70-dates/40-timezone/es/EXERCISE.md @@ -0,0 +1,2 @@ + +Muestre en pantalla la zona horaria actual. diff --git a/modules/70-dates/40-timezone/es/README.md b/modules/70-dates/40-timezone/es/README.md new file mode 100644 index 00000000..03407e19 --- /dev/null +++ b/modules/70-dates/40-timezone/es/README.md @@ -0,0 +1,9 @@ +Una de las partes más complicadas al trabajar con fechas son las zonas horarias (_time zones_). + +La Tierra se divide en 24 zonas horarias, por lo que en zonas adyacentes, la hora suele diferir en una hora. El tiempo universal coordinado (UTC) se considera el tiempo cero. Las zonas horarias alrededor del mundo se expresan como un desplazamiento positivo o negativo con respecto al UTC. Por ejemplo, en Moscú, la zona horaria es +3. + +Un detalle interesante de este mecanismo es el cambio de horario de verano e invierno. Mientras que las zonas horarias son fijas, el cambio de horario de verano e invierno es una prerrogativa de los países que periódicamente lo implementan o lo cancelan. El tiempo UTC nunca se cambia, los desplazamientos ocurren en relación a él. Además, hay mil y un problema más. + +La regla principal al trabajar con fechas es almacenar y comparar en formato UTC. Sin embargo, es mejor mostrar las fechas en la zona horaria del usuario. + +Si necesita verificar la zona horaria actual, puede utilizar la función `date_default_timezone_get()`. Para establecer la zona, utilice la función `date_default_timezone_set()`. diff --git a/modules/70-dates/40-timezone/es/data.yml b/modules/70-dates/40-timezone/es/data.yml new file mode 100644 index 00000000..3782fedf --- /dev/null +++ b/modules/70-dates/40-timezone/es/data.yml @@ -0,0 +1,6 @@ +name: Zonas horarias +tips: + - > + [Lista de zonas horarias admitidas en + PHP](https://php.net/manual/es/timezones.php) +definitions: [] diff --git a/modules/70-dates/40-timezone/ru/EXERCISE.md b/modules/70-dates/40-timezone/ru/EXERCISE.md new file mode 100644 index 00000000..d2bcdf6f --- /dev/null +++ b/modules/70-dates/40-timezone/ru/EXERCISE.md @@ -0,0 +1,2 @@ + +Выведите на экран текущий часовой пояс. diff --git a/modules/70-dates/40-timezone/ru/README.md b/modules/70-dates/40-timezone/ru/README.md new file mode 100644 index 00000000..3d94f22d --- /dev/null +++ b/modules/70-dates/40-timezone/ru/README.md @@ -0,0 +1,9 @@ +Одна из самых сложных деталей при работе с датами — часовые пояса (_time zones_). + +Вся Земля делится на 24 часовых пояса, так что в соседних поясах время чаще всего отличается на час. Нулевым временем считается [всемирное координированное время](https://ru.wikipedia.org/wiki/Всемирное_координированное_время) (UTC). Часовые пояса вокруг земного шара выражаются, как положительное или отрицательное смещение от UTC. Например, в Москве часовой пояс +3. + +Изюминку в этот механизм добавляет переход на летнее и зимнее время. Причем если пояса строго фиксированы, то переход на зимнее и летнее время — прерогатива конкретных государств, которые периодически его вводят или отменяют. Время UTC никогда не переводят, смещения происходят относительно него. Кроме этого есть еще тысяча и одна проблема. + +Главное правило при работе с датами — хранение и сравнение должно производиться в UTC формате. А вот выводить даты лучше в той зоне, в которой живет пользователь. + +Если вам нужно проверить текущую таймзону, можно воспользоваться функцией `date_default_timezone_get()`. Установить зону функцией `date_default_timezone_set()`. diff --git a/modules/70-dates/40-timezone/ru/data.yml b/modules/70-dates/40-timezone/ru/data.yml new file mode 100644 index 00000000..372d176a --- /dev/null +++ b/modules/70-dates/40-timezone/ru/data.yml @@ -0,0 +1,6 @@ +name: Часовые пояса (тайм зоны) +tips: + - > + [Список поддерживаемых временных зон в + PHP](https://php.net/manual/ru/timezones.php) +definitions: []