diff --git a/modules/10-basics/10-hello-world/en/README.md b/modules/10-basics/10-hello-world/en/README.md index ee457502..1521bedc 100644 --- a/modules/10-basics/10-hello-world/en/README.md +++ b/modules/10-basics/10-hello-world/en/README.md @@ -12,12 +12,14 @@ print("Hello, World!") The way `print()` works: you put the text you want to display inside the parentheses. To let Python know it's text and not something else, wrap it in quotes. Both single and double quotes work — just make sure the opening and closing quote match: -```python -print("Hello, World!") + + +```text +print('Hello, World!') print("Hello, World!") ``` -According to the Python style guide (PEP 8), single quotes are preferred for strings when there's no apostrophe inside. +The Python style guide (PEP 8) prefers neither single nor double quotes: pick one style and stick to it. This course uses double quotes. PEP 8 does advise picking the other kind when the string itself contains a quote — the apostrophe in `it's` breaks a single-quoted string, so that one needs double quotes. ```text Code Interpreter Screen diff --git a/modules/10-basics/10-hello-world/es/README.md b/modules/10-basics/10-hello-world/es/README.md index 55585cea..8536a9d1 100644 --- a/modules/10-basics/10-hello-world/es/README.md +++ b/modules/10-basics/10-hello-world/es/README.md @@ -20,11 +20,13 @@ print("Hexlet - escuela de programación") El comando sigue siendo el mismo, solo cambia el contenido de los paréntesis. Para que el programa entienda que se trata precisamente de texto, este se encierra entre comillas. Se pueden usar comillas simples `'...'` o dobles `"..."`, pero la comilla de apertura y la de cierre deben coincidir. -```python -print("Hexlet - escuela de programación") + + +```text +print('Hexlet - escuela de programación') ``` -Según el estándar de estilo de código aceptado en Python (PEP 8), se recomienda usar comillas simples para las cadenas. Si dentro de la cadena hay un apóstrofo, las comillas simples romperán la sintaxis, por lo que en esos casos se usan las dobles. +El estándar de estilo de código PEP 8 no prefiere las comillas simples ni las dobles: lo importante es elegir un estilo y mantenerlo. En este curso usamos las dobles. PEP 8 aconseja que, si dentro de la cadena hay un apóstrofo o una comilla, se usen las del otro tipo para no escapar nada. Por ejemplo, el apóstrofo de `it's` rompe una cadena entre comillas simples, así que aquí hacen falta las dobles. ```python print("it's a Python") # apóstrofo dentro, por eso comillas dobles diff --git a/modules/10-basics/10-hello-world/ru/README.md b/modules/10-basics/10-hello-world/ru/README.md index b4dbf9e6..7d006991 100644 --- a/modules/10-basics/10-hello-world/ru/README.md +++ b/modules/10-basics/10-hello-world/ru/README.md @@ -20,11 +20,13 @@ print("Хекслет - школа программирования") Команда остается той же, меняется только содержимое скобок. Чтобы программа понимала, что это именно текст, он заключается в кавычки. Можно использовать одинарные `'...'` или двойные `"..."`, но открывающая и закрывающая кавычки должны совпадать. -```python -print("Хекслет - школа программирования") + + +```text +print('Хекслет - школа программирования') ``` -По принятому в Python стандарту оформления кода (PEP 8) рекомендуется использовать одинарные кавычки для строк. Если внутри строки есть апостроф, одинарные кавычки сломают синтаксис, поэтому в таких случаях используют двойные. +Стандарт оформления кода PEP 8 не отдает предпочтения одинарным или двойным кавычкам: важно выбрать один стиль и придерживаться его. В этом курсе мы используем двойные. PEP 8 советует: если внутри строки есть апостроф или кавычка, взять другие кавычки, чтобы не экранировать. Например, апостроф в `it's` сломает строку в одинарных кавычках, поэтому здесь нужны двойные. ```python print("it's a Python") # апостроф внутри, поэтому двойные кавычки diff --git a/modules/10-basics/50-syntax-errors/en/README.md b/modules/10-basics/50-syntax-errors/en/README.md index 947d7b07..02339b81 100644 --- a/modules/10-basics/50-syntax-errors/en/README.md +++ b/modules/10-basics/50-syntax-errors/en/README.md @@ -20,12 +20,12 @@ print('Hodor) The closing quote is missing. Running this produces: -```bash +```console $ python index.py -File "index.py", line 1 - print('Hodor) - ^ -SyntaxError: EOL while scanning string literal + File "index.py", line 2 + print('Hodor) + ^ +SyntaxError: unterminated string literal (detected at line 2) ``` The error message may look unfamiliar at first, but that's fine — the more you encounter these messages, the faster you'll understand them at a glance. diff --git a/modules/10-basics/50-syntax-errors/es/README.md b/modules/10-basics/50-syntax-errors/es/README.md index 044460cb..c382e834 100644 --- a/modules/10-basics/50-syntax-errors/es/README.md +++ b/modules/10-basics/50-syntax-errors/es/README.md @@ -29,12 +29,12 @@ print('Hodor) En este código no se cerró la comilla, lo que hace que el programa sea incorrecto desde el punto de vista de la sintaxis. Intentemos ejecutar el programa y el intérprete dará un error: -```bash -python index.py -File "index.py", line 1 - print('Hodor) - ^ -SyntaxError: EOL while scanning string literal +```console +$ python index.py + File "index.py", line 2 + print('Hodor) + ^ +SyntaxError: unterminated string literal (detected at line 2) ``` El texto, por falta de costumbre, puede resultar incomprensible, pero eso es normal: cuanto más te encuentres con esos errores, más entenderás a primera vista qué ocurrió. diff --git a/modules/10-basics/50-syntax-errors/ru/README.md b/modules/10-basics/50-syntax-errors/ru/README.md index e8573c53..18926e69 100644 --- a/modules/10-basics/50-syntax-errors/ru/README.md +++ b/modules/10-basics/50-syntax-errors/ru/README.md @@ -29,12 +29,12 @@ print('Hodor) В этом коде не закрыта кавычка, что делает программу некорректной с точки зрения синтаксиса. Попробуем запустить программу, и интерпретатор выдаст ошибку: -```bash -python index.py -File "index.py", line 1 - print('Hodor) - ^ -SyntaxError: EOL while scanning string literal +```console +$ python index.py + File "index.py", line 2 + print('Hodor) + ^ +SyntaxError: unterminated string literal (detected at line 2) ``` Текст с непривычки может быть непонятен, но это нормально, чем больше вы будете сталкиваться с такими ошибками, тем больше вы с первого взгляда будете понимать, что произошло. diff --git a/modules/20-arithmetics/20-basic/es/README.md b/modules/20-arithmetics/20-basic/es/README.md index 91511a08..117c54af 100644 --- a/modules/20-arithmetics/20-basic/es/README.md +++ b/modules/20-arithmetics/20-basic/es/README.md @@ -129,10 +129,12 @@ Desde el punto de vista de Python, entre `3+4` y `3 + 4` no hay diferencia. El i La variante sin espacios también funciona: -```python -3 + 4 -8 / 2 -7 % 3 + + +```text +3+4 +8/2 +7%3 ``` Pero ese código se ve menos cuidado y cuesta más percibirlo rápido. Por eso conviene acostumbrarse desde el principio a escribir con espacios alrededor de los operadores. diff --git a/modules/20-arithmetics/20-basic/ru/README.md b/modules/20-arithmetics/20-basic/ru/README.md index 10dc60db..8ebcd987 100644 --- a/modules/20-arithmetics/20-basic/ru/README.md +++ b/modules/20-arithmetics/20-basic/ru/README.md @@ -129,10 +129,12 @@ print(15 % 5) # => 0 (делится без остатка) Вариант без пробелов тоже работает: -```python -3 + 4 -8 / 2 -7 % 3 + + +```text +3+4 +8/2 +7%3 ``` Но такой код выглядит менее аккуратно и его сложнее быстро воспринимать. Поэтому лучше сразу привыкать писать с пробелами вокруг операторов. diff --git a/modules/25-strings/10-quotes/en/README.md b/modules/25-strings/10-quotes/en/README.md index 8084e14d..89ed47b8 100644 --- a/modules/25-strings/10-quotes/en/README.md +++ b/modules/25-strings/10-quotes/en/README.md @@ -14,23 +14,25 @@ The definition of a string is quite simple; it's a set of characters. Let us ima Which of these are strings? In fact, all five of them are: -- With `'Hello'` and `'Goodbye'` everything is obvious, we've already worked with similar constructions and called them strings -- `'G'` and `' '` — are also strings, but they only have one character each -- `''` — is an empty string, so it has zero characters +- With `"Hello"` and `"Goodbye"` everything is obvious, we've already worked with similar constructions and called them strings +- `"G"` and `" "` — are also strings, but they only have one character each +- `""` — is an empty string, so it has zero characters We consider anything inside quotation marks a string; even if it's just a space, a single character, or no characters at all. -Above we wrote the strings in single quotes, but this is not the only way. You can also use double quotes: +Above we wrote the strings in double quotes, but this is not the only way. You can also use single quotes: -```python -print("Dracarys!") + + +```text +print('Dracarys!') ``` Now imagine you want to type the string _Dragon's mother_. The apostrophe before the letter **s** — is the same symbol as the single quote. Let's print it: ```python print('Dragon's mother') -# SyntaxError: invalid syntax +# SyntaxError: unterminated string literal (detected at line 1) ``` This program won't work. From Python's point of view, the line started with a single quote and then ended after the word **dragon**. Next were the characters `s mother` without quotation marks, so it's not a string. And then there was a one line-opening quotation mark that was never closed: ``)`. This code contains a syntax error – you can even tell by the way the code is highlighted. @@ -47,7 +49,7 @@ It works the other way too. If you want to use double quotes inside a string, yo Now imagine we want to create this string: -```python +```text Dragon's mother said "No" ``` @@ -55,10 +57,12 @@ It has both single and double quotes. We need to somehow tell the interpreter th The **escape character** is used for this: `\` — a backslash. If we put `\` in front of a quotation mark (single or double), the interpreter will recognize the quotation mark as an ordinary character inside the string, not the beginning or the end of the string: -```python + + +```text # We escape the quotation marks around No so that the interpreter # can recognize them as part of the string -print('Dragon\'s mother said "No"') +print("Dragon's mother said \"No\"") # => Dragon's mother said "No" ``` diff --git a/modules/25-strings/10-quotes/es/README.md b/modules/25-strings/10-quotes/es/README.md index 42769aba..b8e65a15 100644 --- a/modules/25-strings/10-quotes/es/README.md +++ b/modules/25-strings/10-quotes/es/README.md @@ -13,13 +13,13 @@ Desde el punto de vista de Python, una cadena es simplemente un conjunto de cara Todas esas variantes son cadenas. -- `'Hello'`, `'Goodbye'` y `'G'` son cadenas de varios caracteres o de uno solo. -- `' '` es una cadena formada por un solo espacio. -- `''` es una cadena vacía, en ella no hay ni un carácter. Cumple el mismo papel que el 0 en matemáticas. +- `"Hello"`, `"Goodbye"` y `"G"` son cadenas de varios caracteres o de uno solo. +- `" "` es una cadena formada por un solo espacio. +- `""` es una cadena vacía, en ella no hay ni un carácter. Cumple el mismo papel que el 0 en matemáticas. Es decir, todo lo que está dentro de las comillas se considera una cadena, aunque solo haya un espacio o no haya absolutamente nada. -Si se muestran las cadenas en la pantalla, `'Hello'` y `'Goodbye'` se verán con claridad. Pero `' '` y `''` pueden despistar, porque la salida de una cadena vacía parece una ausencia total, mientras que una cadena con un espacio muestra un «espacio vacío» que visualmente es difícil de distinguir. Sin embargo, Python las diferencia con claridad. Una cadena vacía significa la ausencia de caracteres, mientras que una cadena con un espacio contiene un carácter de espacio concreto. +Si se muestran las cadenas en la pantalla, `"Hello"` y `"Goodbye"` se verán con claridad. Pero `" "` y `""` pueden despistar, porque la salida de una cadena vacía parece una ausencia total, mientras que una cadena con un espacio muestra un «espacio vacío» que visualmente es difícil de distinguir. Sin embargo, Python las diferencia con claridad. Una cadena vacía significa la ausencia de caracteres, mientras que una cadena con un espacio contiene un carácter de espacio concreto. Pregunta de control. ¿Son estas cadenas iguales o no? @@ -33,7 +33,7 @@ Pregunta de control. ¿Son estas cadenas iguales o no? En programación hay una trampa terminológica. -- Una cadena (string) es un tipo de dato (el que analizamos arriba), por ejemplo 'hello'. +- Una cadena (string) es un tipo de dato (el que analizamos arriba), por ejemplo `"hello"`. - Una línea (line) es una fila de texto en un archivo o en el código. Por ejemplo, en el código de abajo hay una línea, pero no una cadena. @@ -51,12 +51,14 @@ Para evitar la confusión, en este curso usaremos estas formulaciones. En Python las cadenas se pueden escribir tanto entre comillas simples como entre dobles. -```python -print("Hello") + + +```text +print('Hello') print("Hello") ``` -Por defecto se acostumbra a usar comillas simples `'`, si dentro de la cadena no se necesitan dobles. Ese estilo lo sigue el estándar oficial de formato de código _PEP8_. +El estándar oficial de formato de código _PEP8_ no prefiere las comillas simples ni las dobles: lo importante es elegir un estilo y mantenerlo. En este curso usamos las dobles, y las simples cuando dentro de la cadena hay comillas dobles. ## El problema de las comillas dentro de la cadena @@ -64,7 +66,7 @@ Imagina que quieres imprimir la cadena _Dragon's mother_. En ella hay un apóstr ```python print('Dragon's mother') -# SyntaxError: invalid syntax +# SyntaxError: unterminated string literal (detected at line 1) ``` Python decidirá que la cadena termina después de la palabra 'Dragon', y el resto no lo reconocerá como código válido, lo que provocará un error de sintaxis. Para evitarlo, envolvemos la cadena en comillas dobles. @@ -83,14 +85,16 @@ print('He said "No"') A veces en la cadena aparecen los dos tipos de comillas. -```python +```text Dragon's mother said "No" ``` En ese caso, para que Python no confunda las comillas de dentro de la cadena con las exteriores, se usa el carácter de escape, la barra invertida `\`. Le dice al intérprete que el carácter que la sigue es parte de la cadena y no un carácter de control. -```python -print('Dragon\'s mother said "No"') + + +```text +print("Dragon's mother said \"No\"") # => Dragon's mother said "No" ``` diff --git a/modules/25-strings/10-quotes/ru/README.md b/modules/25-strings/10-quotes/ru/README.md index c9af7b2b..76341a7f 100644 --- a/modules/25-strings/10-quotes/ru/README.md +++ b/modules/25-strings/10-quotes/ru/README.md @@ -15,13 +15,13 @@ Все эти варианты являются строками. -- `'Hello'`, `'Goodbye'` и `'G'` представляют собой строки из нескольких или одного символа. -- `' '` является строкой, состоящей из одного пробела. -- `''` является пустой строкой, в ней нет ни одного символа. Играет такую же роль, как 0 в математике. +- `"Hello"`, `"Goodbye"` и `"G"` представляют собой строки из нескольких или одного символа. +- `" "` является строкой, состоящей из одного пробела. +- `""` является пустой строкой, в ней нет ни одного символа. Играет такую же роль, как 0 в математике. То есть все, что находится внутри кавычек, считается строкой, даже если там только пробел или вообще ничего нет. -Если вывести строки на экран, то `'Hello'` и `'Goodbye'` будут хорошо заметны. Но `' '` и `''` могут сбивать с толку, потому что вывод пустой строки выглядит как полное отсутствие, а строка с пробелом покажет "пустое место", которое визуально сложно отличить. При этом Python четко различает их. Пустая строка означает отсутствие символов, тогда как строка с пробелом содержит конкретный символ пробела. +Если вывести строки на экран, то `"Hello"` и `"Goodbye"` будут хорошо заметны. Но `" "` и `""` могут сбивать с толку, потому что вывод пустой строки выглядит как полное отсутствие, а строка с пробелом покажет "пустое место", которое визуально сложно отличить. При этом Python четко различает их. Пустая строка означает отсутствие символов, тогда как строка с пробелом содержит конкретный символ пробела. Контрольный вопрос. Это одинаковые строки или нет? @@ -35,7 +35,7 @@ В программировании есть терминологическая ловушка. -- Строка (string) является типом данных (то что разбирали выше), например 'hello'. +- Строка (string) является типом данных (то что разбирали выше), например `"hello"`. - Строчка (line) является строкой текста в файле или в коде. Например, в коде ниже есть строчка, но не строка. @@ -53,12 +53,14 @@ print(5) В Python строки можно записывать как в одинарных, так и в двойных кавычках. -```python -print("Hello") + + +```text +print('Hello') print("Hello") ``` -По умолчанию принято использовать одинарные кавычки `'`, если внутри строки не требуется двойных. Этого стиля придерживается официальный стандарт оформления кода _PEP8_. +Официальный стандарт оформления кода _PEP8_ не отдает предпочтения одинарным или двойным кавычкам: важно выбрать один стиль и придерживаться его. В этом курсе мы используем двойные, а одинарные берем тогда, когда внутри строки есть двойные кавычки. ## Проблема с кавычками внутри строки @@ -66,7 +68,7 @@ print("Hello") ```python print('Dragon's mother') -# SyntaxError: invalid syntax +# SyntaxError: unterminated string literal (detected at line 1) ``` Python решит, что строка заканчивается после слова 'Dragon', а остальное не распознает как валидный код, что вызовет синтаксическую ошибку. Чтобы избежать этого, обернем строку в двойные кавычки. @@ -85,14 +87,16 @@ print('He said "No"') Иногда в строке встречаются оба типа кавычек. -```python +```text Dragon's mother said "No" ``` В этом случае чтобы Python не спутал кавычки внутри строки с внешними, используют символ экранирования, обратный слэш `\`. Он говорит интерпретатору, что следующий за ним символ является частью строки, а не управляющим символом. -```python -print('Dragon\'s mother said "No"') + + +```text +print("Dragon's mother said \"No\"") # => Dragon's mother said "No" ``` diff --git a/modules/25-strings/15-escape-characters/es/README.md b/modules/25-strings/15-escape-characters/es/README.md index 629a71df..455b95c4 100644 --- a/modules/25-strings/15-escape-characters/es/README.md +++ b/modules/25-strings/15-escape-characters/es/README.md @@ -59,7 +59,7 @@ print("Hello\nWorld") print("Hello \nWorld") # Hello -# World (al final de la primera línea hay un espacio) +# World (el espacio anterior a \n queda al final de la primera línea) print("Hello\n World") # Hello diff --git a/modules/25-strings/15-escape-characters/ru/README.md b/modules/25-strings/15-escape-characters/ru/README.md index 45716de5..784d9ae3 100644 --- a/modules/25-strings/15-escape-characters/ru/README.md +++ b/modules/25-strings/15-escape-characters/ru/README.md @@ -59,7 +59,7 @@ print("Hello\nWorld") print("Hello \nWorld") # Hello -# World (в конце первой строки есть пробел) +# World (пробел перед \n остался в конце первой строки) print("Hello\n World") # Hello diff --git a/modules/25-strings/20-string-concatenation/en/README.md b/modules/25-strings/20-string-concatenation/en/README.md index a595e0ba..97f43999 100644 --- a/modules/25-strings/20-string-concatenation/en/README.md +++ b/modules/25-strings/20-string-concatenation/en/README.md @@ -11,10 +11,12 @@ print("Dragon" + "stone") # => Dragonstone Strings are always concatenated in the order in which the operands are written. The left operand becomes the left part of the string, and the right one becomes the right part. Here are a few more examples: -```python + + +```text print("Kings" + "wood") # => Kingswood print("Kings" + "road") # => Kingsroad -print("King's" + "Landing") # => King'sLanding +print("King's" + 'Landing') # => King'sLanding ``` As you can see, strings can be concatenated even if they're written with different quotes. diff --git a/modules/25-strings/20-string-concatenation/es/README.md b/modules/25-strings/20-string-concatenation/es/README.md index 3a9a622c..be7b87db 100644 --- a/modules/25-strings/20-string-concatenation/es/README.md +++ b/modules/25-strings/20-string-concatenation/es/README.md @@ -20,21 +20,23 @@ print("Hello" + ", " + "World!") La ejecución: ```text -'Hello' + ', ' + 'World!' +"Hello" + ", " + "World!" └──┬──┘ └┬┘ └──┬───┘ └────┬───┘ │ - 'Hello, ' + 'World!' + "Hello, " + "World!" └──────┬───────┘ - 'Hello, World!' + "Hello, World!" ``` Ejemplos. -```python + + +```text print("Kings" + "wood") # => Kingswood print("Kings" + "road") # => Kingsroad # Aquí por fuera hay comillas dobles, porque dentro hay una simple -print("King's" + "Landing") # => King'sLanding +print("King's" + 'Landing') # => King'sLanding ``` Python permite unir cadenas incluso si están escritas con comillas distintas. Lo importante es que las dos partes sean cadenas. diff --git a/modules/25-strings/20-string-concatenation/ru/README.md b/modules/25-strings/20-string-concatenation/ru/README.md index 8a14faa3..148d51a8 100644 --- a/modules/25-strings/20-string-concatenation/ru/README.md +++ b/modules/25-strings/20-string-concatenation/ru/README.md @@ -20,21 +20,23 @@ print("Hello" + ", " + "World!") Выполнение: ```text -'Hello' + ', ' + 'World!' +"Hello" + ", " + "World!" └──┬──┘ └┬┘ └──┬───┘ └────┬───┘ │ - 'Hello, ' + 'World!' + "Hello, " + "World!" └──────┬───────┘ - 'Hello, World!' + "Hello, World!" ``` Примеры. -```python + + +```text print("Kings" + "wood") # => Kingswood print("Kings" + "road") # => Kingsroad # Здесь снаружи двойные кавычки, потому что внутри есть одиночная -print("King's" + "Landing") # => King'sLanding +print("King's" + 'Landing') # => King'sLanding ``` Python позволяет объединять строки, даже если они записаны в разных кавычках. Главное, чтобы обе части были строками. diff --git a/modules/30-variables/10-definition/en/README.md b/modules/30-variables/10-definition/en/README.md index 105c61cc..3e68b67d 100644 --- a/modules/30-variables/10-definition/en/README.md +++ b/modules/30-variables/10-definition/en/README.md @@ -19,7 +19,7 @@ print(greeting) # => Father! ``` -In the line `greeting = 'Father!'` we take a variable named `greeting` and assign it the value `'Father!'` The variable points to the data that was written to it. In this way, the data can be used repeatedly and not be duplicated constantly. +In the line `greeting = "Father!"` we take a variable named `greeting` and assign it the value `"Father!"` The variable points to the data that was written to it. In this way, the data can be used repeatedly and not be duplicated constantly. Once you've created the variable, you can use it. You put it in the places where we originally had our phrase written out in full. When the code runs, the interpreter reaches the line `print(greeting)`, substitutes the contents of the variable, and then executes the code. diff --git a/modules/30-variables/10-definition/es/README.md b/modules/30-variables/10-definition/es/README.md index a6e528df..44b30888 100644 --- a/modules/30-variables/10-definition/es/README.md +++ b/modules/30-variables/10-definition/es/README.md @@ -27,26 +27,26 @@ Father! Father! ``` -Una **variable** es un nombre detrás del cual se guarda un valor. En nuestro ejemplo creamos una variable con el nombre `greeting` y escribimos en ella la cadena `'Father!'`. +Una **variable** es un nombre detrás del cual se guarda un valor. En nuestro ejemplo creamos una variable con el nombre `greeting` y escribimos en ella la cadena `"Father!"`. ```text -greeting = 'Father!' +greeting = "Father!" Variable Valor ┌──────────┐ ┌──────────┐ -│ greeting │ ──→ │ 'Father!'│ +│ greeting │ ──→ │ "Father!"│ └──────────┘ └──────────┘ ``` -La línea `greeting = 'Father!'` se lee así: «toma el valor `'Father!'` y asígnalo a la variable con el nombre `greeting`». El signo `=` aquí es el operador de asignación, no una indicación de igualdad como en matemáticas. Pone el valor dentro de la variable. +La línea `greeting = "Father!"` se lee así: «toma el valor `"Father!"` y asígnalo a la variable con el nombre `greeting`». El signo `=` aquí es el operador de asignación, no una indicación de igualdad como en matemáticas. Pone el valor dentro de la variable. -Cuando escribimos `print(greeting)`, el intérprete sustituye el nombre `greeting` por el valor que está guardado en ella. Como resultado, en la pantalla se muestra la cadena `'Father!'`. +Cuando escribimos `print(greeting)`, el intérprete sustituye el nombre `greeting` por el valor que está guardado en ella. Como resultado, en la pantalla se muestra la cadena `"Father!"`. ```text print(greeting) | v -print('Father!') +print("Father!") ``` ## Nombres de las variables @@ -69,9 +69,9 @@ print(greeting) # => Mother! print("greeting") # => greeting ``` -En el primer caso se usa la **variable** `greeting`, y el programa sustituye su valor. En el segundo caso `'greeting'` está entre comillas, por eso es un **literal de cadena**, es decir, un valor listo escrito directamente en el código. A pesar de que vemos la palabra `greeting` en los dos casos, desde el punto de vista del intérprete son cosas absolutamente distintas. +En el primer caso se usa la **variable** `greeting`, y el programa sustituye su valor. En el segundo caso `"greeting"` está entre comillas, por eso es un **literal de cadena**, es decir, un valor listo escrito directamente en el código. A pesar de que vemos la palabra `greeting` en los dos casos, desde el punto de vista del intérprete son cosas absolutamente distintas. -Los literales son datos escritos de forma explícita (por ejemplo, `'Hello'`, `42`, `3.14`). Los identificadores son nombres de variables y funciones (por ejemplo, `greeting`, `print`), que apuntan a valores o comandos ya existentes. +Los literales son datos escritos de forma explícita (por ejemplo, `"Hello"`, `42`, `3.14`). Los identificadores son nombres de variables y funciones (por ejemplo, `greeting`, `print`), que apuntan a valores o comandos ya existentes. ## El orden de uso diff --git a/modules/30-variables/10-definition/ru/README.md b/modules/30-variables/10-definition/ru/README.md index 021aa12d..6eb5bac0 100644 --- a/modules/30-variables/10-definition/ru/README.md +++ b/modules/30-variables/10-definition/ru/README.md @@ -29,26 +29,26 @@ Father! ![Определение переменной](./assets/variable-definition.png) -**Переменная** представляет собой имя, за которым хранится значение. В нашем примере мы создали переменную с именем `greeting` и записали в нее строку `'Father!'`. +**Переменная** представляет собой имя, за которым хранится значение. В нашем примере мы создали переменную с именем `greeting` и записали в нее строку `"Father!"`. ```text -greeting = 'Father!' +greeting = "Father!" Переменная Значение ┌──────────┐ ┌──────────┐ -│ greeting │ ──→ │ 'Father!'│ +│ greeting │ ──→ │ "Father!"│ └──────────┘ └──────────┘ ``` -Строчка `greeting = 'Father!'` читается так: "возьми значение `'Father!'` и присвой его переменной с именем `greeting`". Знак `=` здесь является оператором присваивания, а не обозначением равенства как в математике. Он кладет значение в переменную. +Строчка `greeting = "Father!"` читается так: "возьми значение `"Father!"` и присвой его переменной с именем `greeting`". Знак `=` здесь является оператором присваивания, а не обозначением равенства как в математике. Он кладет значение в переменную. -Когда мы пишем `print(greeting)`, интерпретатор подставляет вместо имени `greeting` то значение, которое в ней хранится. В результате на экран выводится строка `'Father!'`. +Когда мы пишем `print(greeting)`, интерпретатор подставляет вместо имени `greeting` то значение, которое в ней хранится. В результате на экран выводится строка `"Father!"`. ```text print(greeting) | v -print('Father!') +print("Father!") ``` ## Имена переменных @@ -71,9 +71,9 @@ print(greeting) # => Mother! print("greeting") # => greeting ``` -В первом случае используется **переменная** `greeting`, и программа подставляет ее значение. Во втором случае `'greeting'` заключено в кавычки, поэтому это **строковый литерал**, то есть готовое значение, написанное прямо в коде. Несмотря на то, что мы видим слово `greeting` в обоих случаях, с точки зрения интерпретатора это абсолютно разные вещи. +В первом случае используется **переменная** `greeting`, и программа подставляет ее значение. Во втором случае `"greeting"` заключено в кавычки, поэтому это **строковый литерал**, то есть готовое значение, написанное прямо в коде. Несмотря на то, что мы видим слово `greeting` в обоих случаях, с точки зрения интерпретатора это абсолютно разные вещи. -Литералы представляют собой данные, записанные явно (например, `'Hello'`, `42`, `3.14`). Идентификаторы являются именами переменных и функций (например, `greeting`, `print`), которые указывают на уже существующие значения или команды. +Литералы представляют собой данные, записанные явно (например, `"Hello"`, `42`, `3.14`). Идентификаторы являются именами переменных и функций (например, `greeting`, `print`), которые указывают на уже существующие значения или команды. ## Порядок использования diff --git a/modules/30-variables/12-change/es/README.md b/modules/30-variables/12-change/es/README.md index de2241e4..fe55165b 100644 --- a/modules/30-variables/12-change/es/README.md +++ b/modules/30-variables/12-change/es/README.md @@ -14,9 +14,9 @@ print(greeting) # => Mother! Aquí primero escribimos en la variable una cadena (_Father!_), después otra (_Mother!_). El nombre de la variable no cambió, pero el valor de dentro pasó a ser otro. ```text -Antes: greeting ──→ 'Father!' +Antes: greeting ──→ "Father!" ╳ -Después: greeting ──→ 'Mother!' +Después: greeting ──→ "Mother!" ``` ## ¿Para qué cambiar el valor? diff --git a/modules/30-variables/12-change/ru/README.md b/modules/30-variables/12-change/ru/README.md index 2af3b98a..f14af2fe 100644 --- a/modules/30-variables/12-change/ru/README.md +++ b/modules/30-variables/12-change/ru/README.md @@ -14,9 +14,9 @@ print(greeting) # => Mother! Здесь мы сначала записали в переменную одну строку (_Father!_), потом другую (_Mother!_). Имя переменной не изменилось, но значение внутри стало другим. ```text -До: greeting ──→ 'Father!' +До: greeting ──→ "Father!" ╳ -После: greeting ──→ 'Mother!' +После: greeting ──→ "Mother!" ``` ## Зачем вообще менять значение? diff --git a/modules/30-variables/18-variable-concatenation/es/README.md b/modules/30-variables/18-variable-concatenation/es/README.md index 36d26afd..c4e2481b 100644 --- a/modules/30-variables/18-variable-concatenation/es/README.md +++ b/modules/30-variables/18-variable-concatenation/es/README.md @@ -40,14 +40,14 @@ print(full) # => Kings road ``` ```text -what = 'Kings' +what = "Kings" who = 'road' what + ' ' + who └─┬──┘ └──┬─┘ -'Kings' + ' ' + 'road' +"Kings" + " " + "road" └────────┬─────────┘ - 'Kings road' + "Kings road" ``` ## ¿Y qué pasa si la variable contiene un número? diff --git a/modules/30-variables/18-variable-concatenation/ru/README.md b/modules/30-variables/18-variable-concatenation/ru/README.md index 4728b6f4..9c0ba12d 100644 --- a/modules/30-variables/18-variable-concatenation/ru/README.md +++ b/modules/30-variables/18-variable-concatenation/ru/README.md @@ -40,14 +40,14 @@ print(full) # => Kings road ``` ```text -what = 'Kings' +what = "Kings" who = 'road' what + ' ' + who └─┬──┘ └──┬─┘ -'Kings' + ' ' + 'road' +"Kings" + " " + "road" └────────┬─────────┘ - 'Kings road' + "Kings road" ``` ## А что если переменная содержит число? diff --git a/modules/31-advanced-strings/70-slices/es/README.md b/modules/31-advanced-strings/70-slices/es/README.md index b18c8afd..04f955a8 100644 --- a/modules/31-advanced-strings/70-slices/es/README.md +++ b/modules/31-advanced-strings/70-slices/es/README.md @@ -56,7 +56,7 @@ part = value[3:7] # => 12-9 print(part[0:2]) # => 12 ``` -Primero obtuvimos la subcadena `'12-9'`, y después hicimos de ella un nuevo corte, `'12'`. +Primero obtuvimos la subcadena `"12-9"`, y después hicimos de ella un nuevo corte, `"12"`. ## Corte hasta el final o desde el principio diff --git a/modules/31-advanced-strings/70-slices/ru/README.md b/modules/31-advanced-strings/70-slices/ru/README.md index 128a78dc..a952a9a9 100644 --- a/modules/31-advanced-strings/70-slices/ru/README.md +++ b/modules/31-advanced-strings/70-slices/ru/README.md @@ -56,7 +56,7 @@ part = value[3:7] # => 12-9 print(part[0:2]) # => 12 ``` -Сначала мы получили подстроку `'12-9'`, а потом сделали из нее новый срез `'12'`. +Сначала мы получили подстроку `"12-9"`, а потом сделали из нее новый срез `"12"`. ## Срез до конца или с начала diff --git a/modules/31-advanced-strings/90-multiline-strings/en/README.md b/modules/31-advanced-strings/90-multiline-strings/en/README.md index 97c48feb..cbde7344 100644 --- a/modules/31-advanced-strings/90-multiline-strings/en/README.md +++ b/modules/31-advanced-strings/90-multiline-strings/en/README.md @@ -45,7 +45,7 @@ several lines Because of the triple quotes, multi-line strings allow you not to escape quotes within a string: ```bash -There is no need to escape the 'single' and 'double' quotes +There is no need to escape the 'single' and "double" quotes ``` Even multi-line strings can become f-string for interpolation: diff --git a/modules/31-advanced-strings/90-multiline-strings/es/README.md b/modules/31-advanced-strings/90-multiline-strings/es/README.md index 355b17f6..4fdb1804 100644 --- a/modules/31-advanced-strings/90-multiline-strings/es/README.md +++ b/modules/31-advanced-strings/90-multiline-strings/es/README.md @@ -84,7 +84,9 @@ varias líneas - Comodidad al editar: es fácil añadir, borrar y cambiar líneas. - No hace falta escapar las comillas: -```python + + +```text quote = '''Aquí no hay que escapar ni las comillas 'simples' ni las "dobles"''' ``` diff --git a/modules/31-advanced-strings/90-multiline-strings/ru/README.md b/modules/31-advanced-strings/90-multiline-strings/ru/README.md index e7f21ac4..92807a84 100644 --- a/modules/31-advanced-strings/90-multiline-strings/ru/README.md +++ b/modules/31-advanced-strings/90-multiline-strings/ru/README.md @@ -84,8 +84,10 @@ text = """Пример текста, - Удобство при редактировании: легко добавлять, удалять и менять строки. - Не нужно экранировать кавычки: -```python -quote = """Здесь не нужно экранировать 'одинарные' и "двойные" кавычки""" + + +```text +quote = '''Здесь не нужно экранировать 'одинарные' и "двойные" кавычки''' ``` ## Интерполяция внутри многострочной строки diff --git a/modules/50-loops/90-debug/en/README.md b/modules/50-loops/90-debug/en/README.md index dc652be6..98451c9c 100644 --- a/modules/50-loops/90-debug/en/README.md +++ b/modules/50-loops/90-debug/en/README.md @@ -12,7 +12,7 @@ Step 1. Study the **traceback** — a list of all function calls from when the p Imagine you wrote code in a file `users.py` and called the function `main()` on line 4. The traceback entry would look like this: -```bash +```text File "users.py", line 4, in main() ``` @@ -21,7 +21,7 @@ As you can see, it shows not just the file and line number, but also the module Step 2. When the traceback reaches the problematic location, it will show an **error message**. For example: -```bash +```text NameError: name 'create' is not defined ``` @@ -29,7 +29,7 @@ The message says: "The name `create` is not defined." This error usually happens Now let's look at how the traceback and error message appear together: -```bash +```text Traceback (most recent call last): File "users.py", line 4, in main() @@ -48,12 +48,11 @@ The simplest errors are **syntax errors**. They are purely about incorrectly for The output of such errors always contains `SyntaxError:`. To debug code in this case, you need to carefully look at the location of the error. Here a syntax error occurred because `'` was used instead of `"`: -```bash -Traceback (most recent call last): +```text File "users.py", line 2 print("Hello" + "world') - ^ -SyntaxError: EOL while scanning string literal + ^ +SyntaxError: unterminated string literal (detected at line 2) ``` The second major group is **programming errors**. For example: diff --git a/modules/50-loops/90-debug/es/README.md b/modules/50-loops/90-debug/es/README.md index c914bb9f..6c85779b 100644 --- a/modules/50-loops/90-debug/es/README.md +++ b/modules/50-loops/90-debug/es/README.md @@ -10,7 +10,7 @@ Lo primero es estudiar el **traceback**. El traceback contiene la lista de todas Imaginemos que escribiste código en el archivo `users.py` y llamaste a la función `main()` en la cuarta línea. El registro en el traceback se verá así: -```bash +```text File "users.py", line 4, in main() ``` @@ -19,7 +19,7 @@ Aquí se ve no solo el archivo y la línea, sino también el nombre del módulo. Cuando el traceback llega al lugar problemático, muestra un **mensaje de error**. Por ejemplo: -```bash +```text NameError: name 'create' is not defined ``` @@ -27,7 +27,7 @@ El mensaje dice que el nombre `create` no está definido. Ese error significa, l Juntos, el traceback y el mensaje de error se ven así: -```bash +```text Traceback (most recent call last): File "users.py", line 4, in main() @@ -44,12 +44,11 @@ Los errores más comprensibles en Python se llaman **sintácticos**. Surgen cuan Miremos un ejemplo. Aquí hay un error sintáctico debido a que la comilla de apertura `"` no coincide con la de cierre `'`: -```bash -Traceback (most recent call last): +```text File "users.py", line 2 print("Hello" + "world') - ^ -SyntaxError: EOL while scanning string literal + ^ +SyntaxError: unterminated string literal (detected at line 2) ``` Lo más difícil de corregir son los **errores de programación**. Aquí entran la llamada a una función que no existe, el uso de una variable no declarada y el paso de argumentos de tipo incorrecto. Normalmente surgen no en el lugar donde está la causa real, lo que complica el diagnóstico. diff --git a/modules/50-loops/90-debug/ru/README.md b/modules/50-loops/90-debug/ru/README.md index db008bb8..ed34ec75 100644 --- a/modules/50-loops/90-debug/ru/README.md +++ b/modules/50-loops/90-debug/ru/README.md @@ -10,7 +10,7 @@ Представим, что вы написали код в файле `users.py` и вызвали функцию `main()` на четвертой строчке. Запись в трейсбеке будет выглядеть так: -```bash +```text File "users.py", line 4, in main() ``` @@ -19,7 +19,7 @@ File "users.py", line 4, in Когда трейсбек доходит до проблемного места, он выдает **сообщение об ошибке**. Например: -```bash +```text NameError: name 'create' is not defined ``` @@ -27,7 +27,7 @@ NameError: name 'create' is not defined Вместе трейсбек и сообщение об ошибке выглядят так: -```bash +```text Traceback (most recent call last): File "users.py", line 4, in main() @@ -44,12 +44,11 @@ NameError: name 'create' is not defined Посмотрим на пример. Здесь синтаксическая ошибка из-за того, что открывающая кавычка `"` не совпадает с закрывающей `'`: -```bash -Traceback (most recent call last): +```text File "users.py", line 2 print("Hello" + "world') - ^ -SyntaxError: EOL while scanning string literal + ^ +SyntaxError: unterminated string literal (detected at line 2) ``` Труднее всего исправлять **ошибки программирования**. Сюда входят вызов несуществующей функции, использование необъявленной переменной, передача аргументов неверного типа. Обычно они возникают не в том месте, где настоящая причина, что и усложняет диагностику.