Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 12 additions & 8 deletions modules/40-define-functions/400-packages/en/EXERCISE.md
Original file line number Diff line number Diff line change
@@ -1,14 +1,18 @@
Implement the function `generate_pin()`. It returns a random four-digit PIN code as a string.
A message can contain the characters `<`, `>` and `&`. When displayed on an HTML page, a browser can interpret them as markup. The standard-library package `html` replaces these characters with special sequences to preserve the message text.

Check notice on line 1 in modules/40-define-functions/400-packages/en/EXERCISE.md

View workflow job for this annotation

GitHub Actions / LanguageTool

[LanguageTool] modules/40-define-functions/400-packages/en/EXERCISE.md#L1

File types are normally capitalized. (FILE_EXTENSIONS_CASE[1]) Suggestions: `HTML` URL: https://languagetool.org/insights/post/spelling-capital-letters/ Rule: https://community.languagetool.org/rule/show/FILE_EXTENSIONS_CASE?lang=en-US&subId=1 Category: CASING
Raw output
modules/40-define-functions/400-packages/en/EXERCISE.md:1:157: File types are normally capitalized. (FILE_EXTENSIONS_CASE[1])
 Suggestions: `HTML`
 URL: https://languagetool.org/insights/post/spelling-capital-letters/ 
 Rule: https://community.languagetool.org/rule/show/FILE_EXTENSIONS_CASE?lang=en-US&subId=1
 Category: CASING

Each digit of the PIN is an independent random integer from 0 to 9.
## Task

Implement the function `escape_html(text)`. It takes a string and returns the result of the `escape()` function from the `html` package with its default arguments. Single and double quotes are also replaced.

Check notice on line 5 in modules/40-define-functions/400-packages/en/EXERCISE.md

View workflow job for this annotation

GitHub Actions / LanguageTool

[LanguageTool] modules/40-define-functions/400-packages/en/EXERCISE.md#L5

File types are normally capitalized. (FILE_EXTENSIONS_CASE[1]) Suggestions: `HTML` URL: https://languagetool.org/insights/post/spelling-capital-letters/ Rule: https://community.languagetool.org/rule/show/FILE_EXTENSIONS_CASE?lang=en-US&subId=1 Category: CASING
Raw output
modules/40-define-functions/400-packages/en/EXERCISE.md:5:122: File types are normally capitalized. (FILE_EXTENSIONS_CASE[1])
 Suggestions: `HTML`
 URL: https://languagetool.org/insights/post/spelling-capital-letters/ 
 Rule: https://community.languagetool.org/rule/show/FILE_EXTENSIONS_CASE?lang=en-US&subId=1
 Category: CASING

```python
print(generate_pin()) # => e.g. "4823" or "0571"
print(generate_pin()) # => e.g. "1942" or "0037"
print(escape_html("<b>A & B</b>")) # => &lt;b&gt;A &amp; B&lt;/b&gt;
print(escape_html('"Hello"')) # => &quot;Hello&quot;

Check notice on line 9 in modules/40-define-functions/400-packages/en/EXERCISE.md

View workflow job for this annotation

GitHub Actions / LanguageTool

[LanguageTool] modules/40-define-functions/400-packages/en/EXERCISE.md#L9

Unpaired symbol: ‘"’ seems to be missing (EN_UNPAIRED_QUOTES) URL: https://languagetool.org/insights/post/punctuation-guide/#what-are-parentheses Rule: https://community.languagetool.org/rule/show/EN_UNPAIRED_QUOTES?lang=en-US Category: PUNCTUATION
Raw output
modules/40-define-functions/400-packages/en/EXERCISE.md:9:19: Unpaired symbol: ‘"’ seems to be missing (EN_UNPAIRED_QUOTES)
 URL: https://languagetool.org/insights/post/punctuation-guide/#what-are-parentheses 
 Rule: https://community.languagetool.org/rule/show/EN_UNPAIRED_QUOTES?lang=en-US
 Category: PUNCTUATION

Check notice on line 9 in modules/40-define-functions/400-packages/en/EXERCISE.md

View workflow job for this annotation

GitHub Actions / LanguageTool

[LanguageTool] modules/40-define-functions/400-packages/en/EXERCISE.md#L9

Unpaired symbol: ‘"’ seems to be missing (EN_UNPAIRED_QUOTES) URL: https://languagetool.org/insights/post/punctuation-guide/#what-are-parentheses Rule: https://community.languagetool.org/rule/show/EN_UNPAIRED_QUOTES?lang=en-US Category: PUNCTUATION
Raw output
modules/40-define-functions/400-packages/en/EXERCISE.md:9:25: Unpaired symbol: ‘"’ seems to be missing (EN_UNPAIRED_QUOTES)
 URL: https://languagetool.org/insights/post/punctuation-guide/#what-are-parentheses 
 Rule: https://community.languagetool.org/rule/show/EN_UNPAIRED_QUOTES?lang=en-US
 Category: PUNCTUATION
print(escape_html("It's ok")) # => It&#x27;s ok
print(escape_html("Hello")) # => Hello
```

Add a return type annotation.

## Hint
## Hints

Generate each of the four digits with `random.randint(0, 9)` and combine them into a string using an f-string.
- `html` is a regular package in the standard library. Its _\_\_init\_\_.py_ file provides the `escape()` function

Check notice on line 16 in modules/40-define-functions/400-packages/en/EXERCISE.md

View workflow job for this annotation

GitHub Actions / LanguageTool

[LanguageTool] modules/40-define-functions/400-packages/en/EXERCISE.md#L16

File types are normally capitalized. (FILE_EXTENSIONS_CASE[1]) Suggestions: `HTML` URL: https://languagetool.org/insights/post/spelling-capital-letters/ Rule: https://community.languagetool.org/rule/show/FILE_EXTENSIONS_CASE?lang=en-US&subId=1 Category: CASING
Raw output
modules/40-define-functions/400-packages/en/EXERCISE.md:16:3: File types are normally capitalized. (FILE_EXTENSIONS_CASE[1])
 Suggestions: `HTML`
 URL: https://languagetool.org/insights/post/spelling-capital-letters/ 
 Rule: https://community.languagetool.org/rule/show/FILE_EXTENSIONS_CASE?lang=en-US&subId=1
 Category: CASING
- Import the package with `import html` or the function with `from html import escape`

Check notice on line 17 in modules/40-define-functions/400-packages/en/EXERCISE.md

View workflow job for this annotation

GitHub Actions / LanguageTool

[LanguageTool] modules/40-define-functions/400-packages/en/EXERCISE.md#L17

File types are normally capitalized. (FILE_EXTENSIONS_CASE[1]) Suggestions: `HTML` URL: https://languagetool.org/insights/post/spelling-capital-letters/ Rule: https://community.languagetool.org/rule/show/FILE_EXTENSIONS_CASE?lang=en-US&subId=1 Category: CASING
Raw output
modules/40-define-functions/400-packages/en/EXERCISE.md:17:34: File types are normally capitalized. (FILE_EXTENSIONS_CASE[1])
 Suggestions: `HTML`
 URL: https://languagetool.org/insights/post/spelling-capital-letters/ 
 Rule: https://community.languagetool.org/rule/show/FILE_EXTENSIONS_CASE?lang=en-US&subId=1
 Category: CASING

Check notice on line 17 in modules/40-define-functions/400-packages/en/EXERCISE.md

View workflow job for this annotation

GitHub Actions / LanguageTool

[LanguageTool] modules/40-define-functions/400-packages/en/EXERCISE.md#L17

File types are normally capitalized. (FILE_EXTENSIONS_CASE[1]) Suggestions: `HTML` URL: https://languagetool.org/insights/post/spelling-capital-letters/ Rule: https://community.languagetool.org/rule/show/FILE_EXTENSIONS_CASE?lang=en-US&subId=1 Category: CASING
Raw output
modules/40-define-functions/400-packages/en/EXERCISE.md:17:67: File types are normally capitalized. (FILE_EXTENSIONS_CASE[1])
 Suggestions: `HTML`
 URL: https://languagetool.org/insights/post/spelling-capital-letters/ 
 Rule: https://community.languagetool.org/rule/show/FILE_EXTENSIONS_CASE?lang=en-US&subId=1
 Category: CASING
- [html.escape documentation](https://docs.python.org/3/library/html.html#html.escape)
25 changes: 20 additions & 5 deletions modules/40-define-functions/400-packages/en/README.md
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
Python programs almost always use code written by others. Reinventing mathematical functions, date handling, or network requests makes no sense — all of this is already available. Python uses packages to share and reuse code.

A package is a directory of Python files organized by topic. The Python standard library contains dozens of such packages, covering everything from mathematics to filesystem access.
A regular package is a directory containing an _\_\_init\_\_.py_ file and Python modules organized by topic. The _\_\_init\_\_.py_ file can be empty. A directory can hold any files; this file identifies it as a regular Python package. The standard library provides both individual modules and packages.

## Importing a Package
## Importing Modules and Packages

To use code from a package, import it with the `import` keyword. Let's look at the `math` package:
To use code from a package, import it with the `import` keyword. Let's look at the `math` module:

```python
import math
Expand All @@ -13,7 +13,7 @@
print(math.pi) # => 3.141592653589793
```

After `import math`, everything in the package is available through dot notation: `math.sqrt`, `math.floor`, `math.pi`.
After `import math`, its names are available through dot notation: `math.sqrt`, `math.floor`, `math.pi`.

## Importing Specific Names

Expand Down Expand Up @@ -42,7 +42,7 @@

## Standard Library

Python ships with a rich set of built-in packages. A few commonly used ones:
Python ships with a rich set of modules and packages. A few commonly used modules:

- `math` — mathematical functions: `sqrt`, `hypot`, `floor`, `ceil`, `pi`
- `random` — random numbers: `randint`, `choice`, `shuffle`
Expand All @@ -55,6 +55,21 @@
print(random.choice(["rock", "paper", "scissors"])) # => random element
```

## Creating a Regular Package

A package groups related modules under one import path. A project with payment modules can have this structure.

```text
payments/
├── __init__.py
├── stripe.py

Check notice on line 65 in modules/40-define-functions/400-packages/en/README.md

View workflow job for this annotation

GitHub Actions / LanguageTool

[LanguageTool] modules/40-define-functions/400-packages/en/README.md#L65

The official name of this payment provider is spelled with two capital “P”. (PAYPAL[1]) Suggestions: `PayPal` URL: https://en.wikipedia.org/wiki/PayPal Rule: https://community.languagetool.org/rule/show/PAYPAL?lang=en-US&subId=1 Category: CASING
Raw output
modules/40-define-functions/400-packages/en/README.md:65:2: The official name of this payment provider is spelled with two capital “P”. (PAYPAL[1])
 Suggestions: `PayPal`
 URL: https://en.wikipedia.org/wiki/PayPal 
 Rule: https://community.languagetool.org/rule/show/PAYPAL?lang=en-US&subId=1
 Category: CASING
└── paypal.py
```

The _\_\_init\_\_.py_ file belongs to the package, while _stripe.py_ and _paypal.py_ are its modules. Importing `payments.stripe` gives access through `payments.stripe`; `from payments import stripe` binds the same module to the shorter name `stripe`. Importing `payments` executes _\_\_init\_\_.py_, which may define names available through the package. This file stays empty when no initialization code is needed.

Check notice on line 69 in modules/40-define-functions/400-packages/en/README.md

View workflow job for this annotation

GitHub Actions / LanguageTool

[LanguageTool] modules/40-define-functions/400-packages/en/README.md#L69

The official name of this payment provider is spelled with two capital “P”. (PAYPAL[1]) Suggestions: `PayPal` URL: https://en.wikipedia.org/wiki/PayPal Rule: https://community.languagetool.org/rule/show/PAYPAL?lang=en-US&subId=1 Category: CASING
Raw output
modules/40-define-functions/400-packages/en/README.md:69:46: The official name of this payment provider is spelled with two capital “P”. (PAYPAL[1])
 Suggestions: `PayPal`
 URL: https://en.wikipedia.org/wiki/PayPal 
 Rule: https://community.languagetool.org/rule/show/PAYPAL?lang=en-US&subId=1
 Category: CASING

Python also supports namespace packages, which can combine portions from several directories without _\_\_init\_\_.py_. The packages created in this lesson are regular packages and include that file in every package directory.

## Third-Party Packages

Beyond the standard library, thousands of packages are created by developers around the world. Install them with `pip`, Python's package manager:
Expand Down
20 changes: 12 additions & 8 deletions modules/40-define-functions/400-packages/es/EXERCISE.md
Original file line number Diff line number Diff line change
@@ -1,14 +1,18 @@
Implementa la función `generate_pin()`. Devuelve un código PIN de cuatro dígitos aleatorio como cadena de texto.
Un mensaje puede contener los caracteres `<`, `>` y `&`. Al mostrarlo en una página HTML, el navegador puede interpretarlos como parte del marcado. El paquete `html` de la biblioteca estándar los sustituye por secuencias especiales para conservar el texto del mensaje.

Check notice on line 1 in modules/40-define-functions/400-packages/es/EXERCISE.md

View workflow job for this annotation

GitHub Actions / LanguageTool

[LanguageTool] modules/40-define-functions/400-packages/es/EXERCISE.md#L1

File types are normally capitalized. (FILE_EXTENSIONS_CASE[1]) Suggestions: `HTML` URL: https://languagetool.org/insights/post/spelling-capital-letters/ Rule: https://community.languagetool.org/rule/show/FILE_EXTENSIONS_CASE?lang=en-US&subId=1 Category: CASING
Raw output
modules/40-define-functions/400-packages/es/EXERCISE.md:1:160: File types are normally capitalized. (FILE_EXTENSIONS_CASE[1])
 Suggestions: `HTML`
 URL: https://languagetool.org/insights/post/spelling-capital-letters/ 
 Rule: https://community.languagetool.org/rule/show/FILE_EXTENSIONS_CASE?lang=en-US&subId=1
 Category: CASING

Cada dígito del PIN es un entero aleatorio independiente del 0 al 9.
## Tarea

Implementa la función `escape_html(text)`. Recibe una cadena y devuelve el resultado de `escape()` del paquete `html` con sus parámetros por defecto. También se sustituyen las comillas simples y dobles.

Check notice on line 5 in modules/40-define-functions/400-packages/es/EXERCISE.md

View workflow job for this annotation

GitHub Actions / LanguageTool

[LanguageTool] modules/40-define-functions/400-packages/es/EXERCISE.md#L5

File types are normally capitalized. (FILE_EXTENSIONS_CASE[1]) Suggestions: `HTML` URL: https://languagetool.org/insights/post/spelling-capital-letters/ Rule: https://community.languagetool.org/rule/show/FILE_EXTENSIONS_CASE?lang=en-US&subId=1 Category: CASING
Raw output
modules/40-define-functions/400-packages/es/EXERCISE.md:5:110: File types are normally capitalized. (FILE_EXTENSIONS_CASE[1])
 Suggestions: `HTML`
 URL: https://languagetool.org/insights/post/spelling-capital-letters/ 
 Rule: https://community.languagetool.org/rule/show/FILE_EXTENSIONS_CASE?lang=en-US&subId=1
 Category: CASING

```python
print(generate_pin()) # => por ejemplo, "4823" o "0571"
print(generate_pin()) # => por ejemplo, "1942" o "0037"
print(escape_html("<b>A & B</b>")) # => &lt;b&gt;A &amp; B&lt;/b&gt;
print(escape_html('"Hello"')) # => &quot;Hello&quot;

Check notice on line 9 in modules/40-define-functions/400-packages/es/EXERCISE.md

View workflow job for this annotation

GitHub Actions / LanguageTool

[LanguageTool] modules/40-define-functions/400-packages/es/EXERCISE.md#L9

Unpaired symbol: ‘"’ seems to be missing (EN_UNPAIRED_QUOTES) URL: https://languagetool.org/insights/post/punctuation-guide/#what-are-parentheses Rule: https://community.languagetool.org/rule/show/EN_UNPAIRED_QUOTES?lang=en-US Category: PUNCTUATION
Raw output
modules/40-define-functions/400-packages/es/EXERCISE.md:9:14: Unpaired symbol: ‘"’ seems to be missing (EN_UNPAIRED_QUOTES)
 URL: https://languagetool.org/insights/post/punctuation-guide/#what-are-parentheses 
 Rule: https://community.languagetool.org/rule/show/EN_UNPAIRED_QUOTES?lang=en-US
 Category: PUNCTUATION

Check notice on line 9 in modules/40-define-functions/400-packages/es/EXERCISE.md

View workflow job for this annotation

GitHub Actions / LanguageTool

[LanguageTool] modules/40-define-functions/400-packages/es/EXERCISE.md#L9

Unpaired symbol: ‘"’ seems to be missing (EN_UNPAIRED_QUOTES) URL: https://languagetool.org/insights/post/punctuation-guide/#what-are-parentheses Rule: https://community.languagetool.org/rule/show/EN_UNPAIRED_QUOTES?lang=en-US Category: PUNCTUATION
Raw output
modules/40-define-functions/400-packages/es/EXERCISE.md:9:20: Unpaired symbol: ‘"’ seems to be missing (EN_UNPAIRED_QUOTES)
 URL: https://languagetool.org/insights/post/punctuation-guide/#what-are-parentheses 
 Rule: https://community.languagetool.org/rule/show/EN_UNPAIRED_QUOTES?lang=en-US
 Category: PUNCTUATION
print(escape_html("It's ok")) # => It&#x27;s ok
print(escape_html("Hello")) # => Hello
```

Añade la anotación de tipo del valor de retorno.

## Pista
## Pistas

Check notice on line 14 in modules/40-define-functions/400-packages/es/EXERCISE.md

View workflow job for this annotation

GitHub Actions / LanguageTool

[LanguageTool] modules/40-define-functions/400-packages/es/EXERCISE.md#L14

File types are normally capitalized. (FILE_EXTENSIONS_CASE[1]) Suggestions: `HTML` URL: https://languagetool.org/insights/post/spelling-capital-letters/ Rule: https://community.languagetool.org/rule/show/FILE_EXTENSIONS_CASE?lang=en-US&subId=1 Category: CASING
Raw output
modules/40-define-functions/400-packages/es/EXERCISE.md:14:9: File types are normally capitalized. (FILE_EXTENSIONS_CASE[1])
 Suggestions: `HTML`
 URL: https://languagetool.org/insights/post/spelling-capital-letters/ 
 Rule: https://community.languagetool.org/rule/show/FILE_EXTENSIONS_CASE?lang=en-US&subId=1
 Category: CASING

Genera cada uno de los cuatro dígitos con `random.randint(0, 9)` y combínalos en una cadena usando un f-string.
- `html` es un paquete regular de la biblioteca estándar. Su archivo _\_\_init\_\_.py_ proporciona la función `escape()`
- Puedes importar el paquete mediante `import html` o la función mediante `from html import escape`

Check notice on line 17 in modules/40-define-functions/400-packages/es/EXERCISE.md

View workflow job for this annotation

GitHub Actions / LanguageTool

[LanguageTool] modules/40-define-functions/400-packages/es/EXERCISE.md#L17

File types are normally capitalized. (FILE_EXTENSIONS_CASE[1]) Suggestions: `HTML` URL: https://languagetool.org/insights/post/spelling-capital-letters/ Rule: https://community.languagetool.org/rule/show/FILE_EXTENSIONS_CASE?lang=en-US&subId=1 Category: CASING
Raw output
modules/40-define-functions/400-packages/es/EXERCISE.md:17:39: File types are normally capitalized. (FILE_EXTENSIONS_CASE[1])
 Suggestions: `HTML`
 URL: https://languagetool.org/insights/post/spelling-capital-letters/ 
 Rule: https://community.languagetool.org/rule/show/FILE_EXTENSIONS_CASE?lang=en-US&subId=1
 Category: CASING

Check notice on line 17 in modules/40-define-functions/400-packages/es/EXERCISE.md

View workflow job for this annotation

GitHub Actions / LanguageTool

[LanguageTool] modules/40-define-functions/400-packages/es/EXERCISE.md#L17

File types are normally capitalized. (FILE_EXTENSIONS_CASE[1]) Suggestions: `HTML` URL: https://languagetool.org/insights/post/spelling-capital-letters/ Rule: https://community.languagetool.org/rule/show/FILE_EXTENSIONS_CASE?lang=en-US&subId=1 Category: CASING
Raw output
modules/40-define-functions/400-packages/es/EXERCISE.md:17:73: File types are normally capitalized. (FILE_EXTENSIONS_CASE[1])
 Suggestions: `HTML`
 URL: https://languagetool.org/insights/post/spelling-capital-letters/ 
 Rule: https://community.languagetool.org/rule/show/FILE_EXTENSIONS_CASE?lang=en-US&subId=1
 Category: CASING
- [Documentación de html.escape](https://docs.python.org/3/library/html.html#html.escape)

Check notice on line 18 in modules/40-define-functions/400-packages/es/EXERCISE.md

View workflow job for this annotation

GitHub Actions / LanguageTool

[LanguageTool] modules/40-define-functions/400-packages/es/EXERCISE.md#L18

If a new sentence starts here, add a space and start with an uppercase letter. (LC_AFTER_PERIOD[1]) Suggestions: ` Escape`, ` escape` Rule: https://community.languagetool.org/rule/show/LC_AFTER_PERIOD?lang=en-US&subId=1 Category: CASING
Raw output
modules/40-define-functions/400-packages/es/EXERCISE.md:18:17: If a new sentence starts here, add a space and start with an uppercase letter. (LC_AFTER_PERIOD[1])
 Suggestions: ` Escape`, ` escape`
 Rule: https://community.languagetool.org/rule/show/LC_AFTER_PERIOD?lang=en-US&subId=1
 Category: CASING
21 changes: 14 additions & 7 deletions modules/40-define-functions/400-packages/es/README.md
Original file line number Diff line number Diff line change
@@ -1,16 +1,18 @@
A medida que el programa crece aumenta no solo la cantidad de líneas de código, sino también la cantidad de módulos. En proyectos pequeños, decenas de archivos todavía se pueden mantener en un solo directorio, pero en aplicaciones reales los archivos pueden ser cientos y miles.

Para organizar los módulos en grupos lógicos más grandes, en Python se usan los paquetes. Un paquete es un directorio con archivos de Python.
Para organizar los módulos en grupos lógicos más grandes, en Python se usan los paquetes. En esta lección trabajamos con paquetes regulares. Un paquete regular es un directorio con un archivo _\_\_init\_\_.py_ y módulos de Python. El archivo _\_\_init\_\_.py_ puede estar vacío.

Por ejemplo, la estructura de un proyecto puede verse así:

```text
project/
├── main.py
├── payments/
│ ├── __init__.py

Check notice on line 11 in modules/40-define-functions/400-packages/es/README.md

View workflow job for this annotation

GitHub Actions / LanguageTool

[LanguageTool] modules/40-define-functions/400-packages/es/README.md#L11

The official name of this payment provider is spelled with two capital “P”. (PAYPAL[1]) Suggestions: `PayPal` URL: https://en.wikipedia.org/wiki/PayPal Rule: https://community.languagetool.org/rule/show/PAYPAL?lang=en-US&subId=1 Category: CASING
Raw output
modules/40-define-functions/400-packages/es/README.md:11:21: The official name of this payment provider is spelled with two capital “P”. (PAYPAL[1])
 Suggestions: `PayPal`
 URL: https://en.wikipedia.org/wiki/PayPal 
 Rule: https://community.languagetool.org/rule/show/PAYPAL?lang=en-US&subId=1
 Category: CASING
│ ├── stripe.py
│ └── paypal.py
└── users/
├── __init__.py
├── auth.py
└── profile.py
```
Expand Down Expand Up @@ -39,15 +41,15 @@

## Importación de un módulo concreto

A menudo no se importa todo el camino, sino un módulo concreto:
Las dos formas importan el módulo `payments.stripe`. La forma `from payments import stripe` lo asocia al nombre corto `stripe` en el archivo actual.

```python
from payments import stripe

stripe.create_payment()
```

Esa forma acorta la escritura y hace el código más compacto.
Lo que se acorta es la llamada, `stripe.create_payment()` en lugar de `payments.stripe.create_payment()`. La instrucción de importación puede ser más larga.

## Paquetes anidados

Expand All @@ -56,8 +58,11 @@
```text
project/
└── app/
├── __init__.py
└── payments/
├── __init__.py

Check notice on line 63 in modules/40-define-functions/400-packages/es/README.md

View workflow job for this annotation

GitHub Actions / LanguageTool

[LanguageTool] modules/40-define-functions/400-packages/es/README.md#L63

The official name of this payment provider is spelled with two capital “P”. (PAYPAL[1]) Suggestions: `PayPal` URL: https://en.wikipedia.org/wiki/PayPal Rule: https://community.languagetool.org/rule/show/PAYPAL?lang=en-US&subId=1 Category: CASING
Raw output
modules/40-define-functions/400-packages/es/README.md:63:23: The official name of this payment provider is spelled with two capital “P”. (PAYPAL[1])
 Suggestions: `PayPal`
 URL: https://en.wikipedia.org/wiki/PayPal 
 Rule: https://community.languagetool.org/rule/show/PAYPAL?lang=en-US&subId=1
 Category: CASING
├── stripe/
│ ├── __init__.py
│ ├── client.py
│ └── api.py
└── paypal.py
Expand All @@ -80,8 +85,10 @@
```text
project/
├── admin/
│ ├── __init__.py
│ └── config.py
└── user/
├── __init__.py
└── config.py
```

Expand All @@ -96,9 +103,9 @@

Sin los paquetes, esos nombres entrarían en conflicto entre sí.

## El archivo \_\_init\_\_.py
## El archivo de inicialización del paquete

Check notice on line 106 in modules/40-define-functions/400-packages/es/README.md

View workflow job for this annotation

GitHub Actions / LanguageTool

[LanguageTool] modules/40-define-functions/400-packages/es/README.md#L106

The official name of this payment provider is spelled with two capital “P”. (PAYPAL[1]) Suggestions: `PayPal` URL: https://en.wikipedia.org/wiki/PayPal Rule: https://community.languagetool.org/rule/show/PAYPAL?lang=en-US&subId=1 Category: CASING
Raw output
modules/40-define-functions/400-packages/es/README.md:106:45: The official name of this payment provider is spelled with two capital “P”. (PAYPAL[1])
 Suggestions: `PayPal`
 URL: https://en.wikipedia.org/wiki/PayPal 
 Rule: https://community.languagetool.org/rule/show/PAYPAL?lang=en-US&subId=1
 Category: CASING

Antes, para crear un paquete, dentro del directorio se colocaba obligatoriamente el archivo `__init__.py`:
El archivo _\_\_init\_\_.py_ identifica un paquete regular. También se crea cuando el paquete no necesita código común. En ese caso se deja vacío.

```text
payments/
Expand All @@ -107,6 +114,6 @@
└── paypal.py
```

Ese archivo informaba a Python de que el directorio había que tratarlo como un paquete.
Un directorio puede contener cualquier tipo de archivo. Con _\_\_init\_\_.py_, `payments` es un paquete regular cuyos módulos se importan como `payments.stripe` y `payments.paypal`. Al importar `payments`, Python ejecuta el código de _\_\_init\_\_.py_. Allí se pueden definir los nombres accesibles mediante el paquete.

En las versiones modernas de Python los paquetes pueden funcionar también sin `__init__.py`. No obstante, ese archivo se sigue usando a menudo. Normalmente en él se coloca código común y la configuración del paquete.
Python también tiene paquetes de espacio de nombres. Permiten reunir partes de un paquete desde varios directorios y no llevan _\_\_init\_\_.py_. Son otra forma de organizar paquetes. Los ejemplos de esta lección usan paquetes regulares y cada directorio de paquete, incluidos los anidados, contiene ese archivo.
20 changes: 12 additions & 8 deletions modules/40-define-functions/400-packages/ru/EXERCISE.md
Original file line number Diff line number Diff line change
@@ -1,14 +1,18 @@
Реализуйте функцию `generate_pin()`. Она возвращает случайный четырёхзначный PIN-код в виде строки.
Текст сообщения может содержать символы `<`, `>` и `&`. При выводе на HTML-странице браузер воспринимает их как часть разметки. Пакет стандартной библиотеки `html` заменяет такие символы специальными последовательностями и сохраняет текст сообщения.

Check notice on line 1 in modules/40-define-functions/400-packages/ru/EXERCISE.md

View workflow job for this annotation

GitHub Actions / LanguageTool

[LanguageTool] modules/40-define-functions/400-packages/ru/EXERCISE.md#L1

File types are normally capitalized. (FILE_EXTENSIONS_CASE[1]) Suggestions: `HTML` URL: https://languagetool.org/insights/post/spelling-capital-letters/ Rule: https://community.languagetool.org/rule/show/FILE_EXTENSIONS_CASE?lang=en-US&subId=1 Category: CASING
Raw output
modules/40-define-functions/400-packages/ru/EXERCISE.md:1:158: File types are normally capitalized. (FILE_EXTENSIONS_CASE[1])
 Suggestions: `HTML`
 URL: https://languagetool.org/insights/post/spelling-capital-letters/ 
 Rule: https://community.languagetool.org/rule/show/FILE_EXTENSIONS_CASE?lang=en-US&subId=1
 Category: CASING

Check notice on line 1 in modules/40-define-functions/400-packages/ru/EXERCISE.md

View workflow job for this annotation

GitHub Actions / LanguageTool

[LanguageTool] modules/40-define-functions/400-packages/ru/EXERCISE.md#L1

File types are normally capitalized. (FILE_EXTENSIONS_CASE[1]) Suggestions: `HTML` URL: https://languagetool.org/insights/post/spelling-capital-letters/ Rule: https://community.languagetool.org/rule/show/FILE_EXTENSIONS_CASE?lang=en-US&subId=1 Category: CASING
Raw output
modules/40-define-functions/400-packages/ru/EXERCISE.md:1:377: File types are normally capitalized. (FILE_EXTENSIONS_CASE[1])
 Suggestions: `HTML`
 URL: https://languagetool.org/insights/post/spelling-capital-letters/ 
 Rule: https://community.languagetool.org/rule/show/FILE_EXTENSIONS_CASE?lang=en-US&subId=1
 Category: CASING

Каждый разряд PIN-кода — независимое случайное целое число от 0 до 9.
## Задание

Реализуйте функцию `escape_html(text)`. Она принимает строку и возвращает результат функции `escape()` из пакета `html` с параметрами по умолчанию. При этом также заменяются одинарные и двойные кавычки.

Check notice on line 5 in modules/40-define-functions/400-packages/ru/EXERCISE.md

View workflow job for this annotation

GitHub Actions / LanguageTool

[LanguageTool] modules/40-define-functions/400-packages/ru/EXERCISE.md#L5

Unpaired symbol: ‘"’ seems to be missing (EN_UNPAIRED_QUOTES) URL: https://languagetool.org/insights/post/punctuation-guide/#what-are-parentheses Rule: https://community.languagetool.org/rule/show/EN_UNPAIRED_QUOTES?lang=en-US Category: PUNCTUATION
Raw output
modules/40-define-functions/400-packages/ru/EXERCISE.md:5:102: Unpaired symbol: ‘"’ seems to be missing (EN_UNPAIRED_QUOTES)
 URL: https://languagetool.org/insights/post/punctuation-guide/#what-are-parentheses 
 Rule: https://community.languagetool.org/rule/show/EN_UNPAIRED_QUOTES?lang=en-US
 Category: PUNCTUATION

Check notice on line 5 in modules/40-define-functions/400-packages/ru/EXERCISE.md

View workflow job for this annotation

GitHub Actions / LanguageTool

[LanguageTool] modules/40-define-functions/400-packages/ru/EXERCISE.md#L5

Unpaired symbol: ‘"’ seems to be missing (EN_UNPAIRED_QUOTES) URL: https://languagetool.org/insights/post/punctuation-guide/#what-are-parentheses Rule: https://community.languagetool.org/rule/show/EN_UNPAIRED_QUOTES?lang=en-US Category: PUNCTUATION
Raw output
modules/40-define-functions/400-packages/ru/EXERCISE.md:5:108: Unpaired symbol: ‘"’ seems to be missing (EN_UNPAIRED_QUOTES)
 URL: https://languagetool.org/insights/post/punctuation-guide/#what-are-parentheses 
 Rule: https://community.languagetool.org/rule/show/EN_UNPAIRED_QUOTES?lang=en-US
 Category: PUNCTUATION

Check notice on line 5 in modules/40-define-functions/400-packages/ru/EXERCISE.md

View workflow job for this annotation

GitHub Actions / LanguageTool

[LanguageTool] modules/40-define-functions/400-packages/ru/EXERCISE.md#L5

File types are normally capitalized. (FILE_EXTENSIONS_CASE[1]) Suggestions: `HTML` URL: https://languagetool.org/insights/post/spelling-capital-letters/ Rule: https://community.languagetool.org/rule/show/FILE_EXTENSIONS_CASE?lang=en-US&subId=1 Category: CASING
Raw output
modules/40-define-functions/400-packages/ru/EXERCISE.md:5:248: File types are normally capitalized. (FILE_EXTENSIONS_CASE[1])
 Suggestions: `HTML`
 URL: https://languagetool.org/insights/post/spelling-capital-letters/ 
 Rule: https://community.languagetool.org/rule/show/FILE_EXTENSIONS_CASE?lang=en-US&subId=1
 Category: CASING

```python
print(generate_pin()) # => например, "4823" или "0571"
print(generate_pin()) # => например, "1942" или "0037"
print(escape_html("<b>A & B</b>")) # => &lt;b&gt;A &amp; B&lt;/b&gt;

Check notice on line 8 in modules/40-define-functions/400-packages/ru/EXERCISE.md

View workflow job for this annotation

GitHub Actions / LanguageTool

[LanguageTool] modules/40-define-functions/400-packages/ru/EXERCISE.md#L8

File types are normally capitalized. (FILE_EXTENSIONS_CASE[1]) Suggestions: `HTML` URL: https://languagetool.org/insights/post/spelling-capital-letters/ Rule: https://community.languagetool.org/rule/show/FILE_EXTENSIONS_CASE?lang=en-US&subId=1 Category: CASING
Raw output
modules/40-define-functions/400-packages/ru/EXERCISE.md:8:52: File types are normally capitalized. (FILE_EXTENSIONS_CASE[1])
 Suggestions: `HTML`
 URL: https://languagetool.org/insights/post/spelling-capital-letters/ 
 Rule: https://community.languagetool.org/rule/show/FILE_EXTENSIONS_CASE?lang=en-US&subId=1
 Category: CASING
print(escape_html('"Hello"')) # => &quot;Hello&quot;

Check notice on line 9 in modules/40-define-functions/400-packages/ru/EXERCISE.md

View workflow job for this annotation

GitHub Actions / LanguageTool

[LanguageTool] modules/40-define-functions/400-packages/ru/EXERCISE.md#L9

File types are normally capitalized. (FILE_EXTENSIONS_CASE[1]) Suggestions: `HTML` URL: https://languagetool.org/insights/post/spelling-capital-letters/ Rule: https://community.languagetool.org/rule/show/FILE_EXTENSIONS_CASE?lang=en-US&subId=1 Category: CASING
Raw output
modules/40-define-functions/400-packages/ru/EXERCISE.md:9:17: File types are normally capitalized. (FILE_EXTENSIONS_CASE[1])
 Suggestions: `HTML`
 URL: https://languagetool.org/insights/post/spelling-capital-letters/ 
 Rule: https://community.languagetool.org/rule/show/FILE_EXTENSIONS_CASE?lang=en-US&subId=1
 Category: CASING
print(escape_html("It's ok")) # => It&#x27;s ok

Check notice on line 10 in modules/40-define-functions/400-packages/ru/EXERCISE.md

View workflow job for this annotation

GitHub Actions / LanguageTool

[LanguageTool] modules/40-define-functions/400-packages/ru/EXERCISE.md#L10

If a new sentence starts here, add a space and start with an uppercase letter. (LC_AFTER_PERIOD[1]) Suggestions: ` Escape`, ` escape` Rule: https://community.languagetool.org/rule/show/LC_AFTER_PERIOD?lang=en-US&subId=1 Category: CASING
Raw output
modules/40-define-functions/400-packages/ru/EXERCISE.md:10:4: If a new sentence starts here, add a space and start with an uppercase letter. (LC_AFTER_PERIOD[1])
 Suggestions: ` Escape`, ` escape`
 Rule: https://community.languagetool.org/rule/show/LC_AFTER_PERIOD?lang=en-US&subId=1
 Category: CASING
print(escape_html("Hello")) # => Hello
```

Укажите аннотацию типа возвращаемого значения.

## Подсказка
## Подсказки

Сгенерируйте каждую из четырёх цифр через `random.randint(0, 9)` и соберите строку через f-строку. Модуль `random` подключается в начале файла инструкцией `import random`, и после неё функция вызывается через имя модуля, `random.randint()`.
- `html` является обычным пакетом стандартной библиотеки. Его файл _\_\_init\_\_.py_ предоставляет функцию `escape()`
- Можно импортировать пакет через `import html` или саму функцию через `from html import escape`
- [Документация html.escape](https://docs.python.org/3/library/html.html#html.escape)
21 changes: 14 additions & 7 deletions modules/40-define-functions/400-packages/ru/README.md
Original file line number Diff line number Diff line change
@@ -1,16 +1,18 @@
По мере роста программы увеличивается не только количество строк кода, но и количество модулей. В небольших проектах десятки файлов еще можно держать в одной директории, но в реальных приложениях файлов могут быть сотни и тысячи.

Чтобы организовывать модули в более крупные логические группы, в Python используют пакеты. Пакет представляет собой директорию с Python-файлами.
Чтобы организовывать модули в более крупные логические группы, в Python используют пакеты. В этом уроке мы работаем с обычными пакетами. Обычный пакет представляет собой директорию с файлом _\_\_init\_\_.py_ и модулями Python. Файл _\_\_init\_\_.py_ может быть пустым.

Check notice on line 3 in modules/40-define-functions/400-packages/ru/README.md

View workflow job for this annotation

GitHub Actions / LanguageTool

[LanguageTool] modules/40-define-functions/400-packages/ru/README.md#L3

The official name of this payment provider is spelled with two capital “P”. (PAYPAL[1]) Suggestions: `PayPal` URL: https://en.wikipedia.org/wiki/PayPal Rule: https://community.languagetool.org/rule/show/PAYPAL?lang=en-US&subId=1 Category: CASING
Raw output
modules/40-define-functions/400-packages/ru/README.md:3:218: The official name of this payment provider is spelled with two capital “P”. (PAYPAL[1])
 Suggestions: `PayPal`
 URL: https://en.wikipedia.org/wiki/PayPal 
 Rule: https://community.languagetool.org/rule/show/PAYPAL?lang=en-US&subId=1
 Category: CASING

Check notice on line 3 in modules/40-define-functions/400-packages/ru/README.md

View workflow job for this annotation

GitHub Actions / LanguageTool

[LanguageTool] modules/40-define-functions/400-packages/ru/README.md#L3

The official name of this payment provider is spelled with two capital “P”. (PAYPAL[1]) Suggestions: `PayPal` URL: https://en.wikipedia.org/wiki/PayPal Rule: https://community.languagetool.org/rule/show/PAYPAL?lang=en-US&subId=1 Category: CASING
Raw output
modules/40-define-functions/400-packages/ru/README.md:3:370: The official name of this payment provider is spelled with two capital “P”. (PAYPAL[1])
 Suggestions: `PayPal`
 URL: https://en.wikipedia.org/wiki/PayPal 
 Rule: https://community.languagetool.org/rule/show/PAYPAL?lang=en-US&subId=1
 Category: CASING

Например, структура проекта может выглядеть так:

```text
project/
├── main.py
├── payments/
│ ├── __init__.py
│ ├── stripe.py
│ └── paypal.py
└── users/
├── __init__.py
├── auth.py
└── profile.py
```
Expand Down Expand Up @@ -39,15 +41,15 @@

## Импорт конкретного модуля

Часто импортируют не весь путь, а конкретный модуль:
Обе формы импорта загружают модуль `payments.stripe`. Форма `from payments import stripe` связывает его с коротким именем `stripe` в текущем файле.

```python
from payments import stripe

stripe.create_payment()
```

Такой способ сокращает запись и делает код компактнее.
Сокращается обращение к функции, `stripe.create_payment()` вместо `payments.stripe.create_payment()`. Сам импорт при этом может занимать больше символов.

## Вложенные пакеты

Expand All @@ -56,8 +58,11 @@
```text
project/
└── app/
├── __init__.py
└── payments/
├── __init__.py

Check notice on line 63 in modules/40-define-functions/400-packages/ru/README.md

View workflow job for this annotation

GitHub Actions / LanguageTool

[LanguageTool] modules/40-define-functions/400-packages/ru/README.md#L63

The official name of this payment provider is spelled with two capital “P”. (PAYPAL[1]) Suggestions: `PayPal` URL: https://en.wikipedia.org/wiki/PayPal Rule: https://community.languagetool.org/rule/show/PAYPAL?lang=en-US&subId=1 Category: CASING
Raw output
modules/40-define-functions/400-packages/ru/README.md:63:3: The official name of this payment provider is spelled with two capital “P”. (PAYPAL[1])
 Suggestions: `PayPal`
 URL: https://en.wikipedia.org/wiki/PayPal 
 Rule: https://community.languagetool.org/rule/show/PAYPAL?lang=en-US&subId=1
 Category: CASING
├── stripe/
│ ├── __init__.py
│ ├── client.py
│ └── api.py
└── paypal.py
Expand All @@ -80,8 +85,10 @@
```text
project/
├── admin/
│ ├── __init__.py
│ └── config.py
└── user/
├── __init__.py
└── config.py
```

Expand All @@ -96,9 +103,9 @@

Без пакетов такие имена конфликтовали бы между собой.

## Файл \_\_init\_\_.py
## Файл инициализации пакета

Раньше для создания пакета внутри директории обязательно размещали файл `__init__.py`:
Файл _\_\_init\_\_.py_ обозначает обычный пакет. Он нужен и тогда, когда внутри нет общего кода. В этом случае файл оставляют пустым.

Check notice on line 108 in modules/40-define-functions/400-packages/ru/README.md

View workflow job for this annotation

GitHub Actions / LanguageTool

[LanguageTool] modules/40-define-functions/400-packages/ru/README.md#L108

The official name of this payment provider is spelled with two capital “P”. (PAYPAL[1]) Suggestions: `PayPal` URL: https://en.wikipedia.org/wiki/PayPal Rule: https://community.languagetool.org/rule/show/PAYPAL?lang=en-US&subId=1 Category: CASING
Raw output
modules/40-define-functions/400-packages/ru/README.md:108:71: The official name of this payment provider is spelled with two capital “P”. (PAYPAL[1])
 Suggestions: `PayPal`
 URL: https://en.wikipedia.org/wiki/PayPal 
 Rule: https://community.languagetool.org/rule/show/PAYPAL?lang=en-US&subId=1
 Category: CASING

Check notice on line 108 in modules/40-define-functions/400-packages/ru/README.md

View workflow job for this annotation

GitHub Actions / LanguageTool

[LanguageTool] modules/40-define-functions/400-packages/ru/README.md#L108

The official name of this payment provider is spelled with two capital “P”. (PAYPAL[1]) Suggestions: `PayPal` URL: https://en.wikipedia.org/wiki/PayPal Rule: https://community.languagetool.org/rule/show/PAYPAL?lang=en-US&subId=1 Category: CASING
Raw output
modules/40-define-functions/400-packages/ru/README.md:108:110: The official name of this payment provider is spelled with two capital “P”. (PAYPAL[1])
 Suggestions: `PayPal`
 URL: https://en.wikipedia.org/wiki/PayPal 
 Rule: https://community.languagetool.org/rule/show/PAYPAL?lang=en-US&subId=1
 Category: CASING

Check notice on line 108 in modules/40-define-functions/400-packages/ru/README.md

View workflow job for this annotation

GitHub Actions / LanguageTool

[LanguageTool] modules/40-define-functions/400-packages/ru/README.md#L108

If a new sentence starts here, add a space and start with an uppercase letter. (LC_AFTER_PERIOD[1]) Suggestions: ` Stripe`, ` stripe` Rule: https://community.languagetool.org/rule/show/LC_AFTER_PERIOD?lang=en-US&subId=1 Category: CASING
Raw output
modules/40-define-functions/400-packages/ru/README.md:108:139: If a new sentence starts here, add a space and start with an uppercase letter. (LC_AFTER_PERIOD[1])
 Suggestions: ` Stripe`, ` stripe`
 Rule: https://community.languagetool.org/rule/show/LC_AFTER_PERIOD?lang=en-US&subId=1
 Category: CASING

```text
payments/
Expand All @@ -107,9 +114,9 @@
└── paypal.py
```

Этот файл сообщал Python, что директорию нужно воспринимать как пакет.
Каталог может хранить любые файлы. Наличие _\_\_init\_\_.py_ делает `payments` обычным пакетом, к модулям которого обращаются по именам `payments.stripe` и `payments.paypal`. При импорте `payments` Python выполняет код из _\_\_init\_\_.py_. В нём можно определить имена, доступные через пакет.

Check notice on line 117 in modules/40-define-functions/400-packages/ru/README.md

View workflow job for this annotation

GitHub Actions / LanguageTool

[LanguageTool] modules/40-define-functions/400-packages/ru/README.md#L117

The official name of this payment provider is spelled with two capital “P”. (PAYPAL[1]) Suggestions: `PayPal` URL: https://en.wikipedia.org/wiki/PayPal Rule: https://community.languagetool.org/rule/show/PAYPAL?lang=en-US&subId=1 Category: CASING
Raw output
modules/40-define-functions/400-packages/ru/README.md:117:78: The official name of this payment provider is spelled with two capital “P”. (PAYPAL[1])
 Suggestions: `PayPal`
 URL: https://en.wikipedia.org/wiki/PayPal 
 Rule: https://community.languagetool.org/rule/show/PAYPAL?lang=en-US&subId=1
 Category: CASING

Check notice on line 117 in modules/40-define-functions/400-packages/ru/README.md

View workflow job for this annotation

GitHub Actions / LanguageTool

[LanguageTool] modules/40-define-functions/400-packages/ru/README.md#L117

The official name of this payment provider is spelled with two capital “P”. (PAYPAL[1]) Suggestions: `PayPal` URL: https://en.wikipedia.org/wiki/PayPal Rule: https://community.languagetool.org/rule/show/PAYPAL?lang=en-US&subId=1 Category: CASING
Raw output
modules/40-define-functions/400-packages/ru/README.md:117:105: The official name of this payment provider is spelled with two capital “P”. (PAYPAL[1])
 Suggestions: `PayPal`
 URL: https://en.wikipedia.org/wiki/PayPal 
 Rule: https://community.languagetool.org/rule/show/PAYPAL?lang=en-US&subId=1
 Category: CASING

Check notice on line 117 in modules/40-define-functions/400-packages/ru/README.md

View workflow job for this annotation

GitHub Actions / LanguageTool

[LanguageTool] modules/40-define-functions/400-packages/ru/README.md#L117

The official name of this payment provider is spelled with two capital “P”. (PAYPAL[1]) Suggestions: `PayPal` URL: https://en.wikipedia.org/wiki/PayPal Rule: https://community.languagetool.org/rule/show/PAYPAL?lang=en-US&subId=1 Category: CASING
Raw output
modules/40-define-functions/400-packages/ru/README.md:117:304: The official name of this payment provider is spelled with two capital “P”. (PAYPAL[1])
 Suggestions: `PayPal`
 URL: https://en.wikipedia.org/wiki/PayPal 
 Rule: https://community.languagetool.org/rule/show/PAYPAL?lang=en-US&subId=1
 Category: CASING

Check notice on line 117 in modules/40-define-functions/400-packages/ru/README.md

View workflow job for this annotation

GitHub Actions / LanguageTool

[LanguageTool] modules/40-define-functions/400-packages/ru/README.md#L117

The official name of this payment provider is spelled with two capital “P”. (PAYPAL[1]) Suggestions: `PayPal` URL: https://en.wikipedia.org/wiki/PayPal Rule: https://community.languagetool.org/rule/show/PAYPAL?lang=en-US&subId=1 Category: CASING
Raw output
modules/40-define-functions/400-packages/ru/README.md:117:328: The official name of this payment provider is spelled with two capital “P”. (PAYPAL[1])
 Suggestions: `PayPal`
 URL: https://en.wikipedia.org/wiki/PayPal 
 Rule: https://community.languagetool.org/rule/show/PAYPAL?lang=en-US&subId=1
 Category: CASING

В современных версиях Python пакеты могут работать и без `__init__.py`. Тем не менее этот файл до сих пор часто используется. Обычно в нем размещают общий код и настройки пакета.
У Python также есть namespace-пакеты. Они позволяют объединять части одного пакета из нескольких каталогов и обходятся без _\_\_init\_\_.py_. Это отдельный способ организации пакетов. Для обычных пакетов из примеров этого урока файл создаётся в каждом каталоге пакета, в том числе во вложенных.

## Имена пакета в \_\_init\_\_.py

Expand Down
10 changes: 3 additions & 7 deletions modules/40-define-functions/400-packages/solution.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,5 @@
import random
import html


def generate_pin() -> str:
d1 = random.randint(0, 9)
d2 = random.randint(0, 9)
d3 = random.randint(0, 9)
d4 = random.randint(0, 9)
return f"{d1}{d2}{d3}{d4}"
def escape_html(text):
return html.escape(text)
44 changes: 31 additions & 13 deletions modules/40-define-functions/400-packages/test_solution.py
Original file line number Diff line number Diff line change
@@ -1,18 +1,36 @@
import random
import importlib
from unittest.mock import patch

import solution


def test():
annotations = solution.generate_pin.__annotations__
assert 'return' in annotations, "You should add a return type annotation"
assert callable(getattr(solution, "escape_html", None)), (
"Define the escape_html(text) function"
)
cases = [
("", ""),
("Hello", "Hello"),
("<b>A & B</b>", "&lt;b&gt;A &amp; B&lt;/b&gt;"),
('"Hello"', "&quot;Hello&quot;"),
("It's ok", "It&#x27;s ok"),
("&lt;", "&amp;lt;"),
("Привет, мир!", "Привет, мир!"),
]
for text, expected in cases:
assert solution.escape_html(text) == expected, (
"escape_html must return the escaped string",
text,
)

for seed in [1, 7, 42]:
random.seed(seed)
result = solution.generate_pin()
random.seed(seed)
d1 = random.randint(0, 9)
d2 = random.randint(0, 9)
d3 = random.randint(0, 9)
d4 = random.randint(0, 9)
assert result == f"{d1}{d2}{d3}{d4}"
assert len(result) == 4
with patch("html.escape", return_value="escaped-by-html") as escape:
importlib.reload(solution)
assert solution.escape_html("source") == "escaped-by-html", (
"Use the escape function from the html package"
)
assert escape.call_count == 1, "Use the escape function from the html package"
args, kwargs = escape.call_args
assert (args[0] if args else kwargs.get("s")) == "source", (
"Use the escape function from the html package"
)
importlib.reload(solution)
Loading