generated from hexlet-basics/exercises-template
-
Notifications
You must be signed in to change notification settings - Fork 3
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
12 changed files
with
197 additions
and
2 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,6 @@ | ||
*.ru | ||
__pycache__ | ||
.mypy_cache | ||
.DS_Store | ||
.ropeproject | ||
text_length.txt |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -28,4 +28,4 @@ compose-code-lint: | |
docker compose run exercises make code-lint | ||
|
||
code-lint: | ||
flake8 modules | ||
flake8 modules |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,2 @@ | ||
test: | ||
@ test.sh |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,85 @@ | ||
--- | ||
|
||
name: Цикл for и функция range | ||
theory: | | ||
Представьте, что у нас есть ряд чисел от 0 до 9. Мы хотим сложить эти числа. Мы могли бы сделать это так: | ||
```python | ||
sum = 0 | ||
i = 0 | ||
while i < 10: | ||
sum += i | ||
i += 1 | ||
print(sum) # => 45 | ||
``` | ||
Сначала мы устанавливаем начальную сумму 0. Далее запускается цикл, в котором переменная `i` начинает принимать значения начиная с 0 и доходя до 10. На каждом шаге мы прибавляем значение `i` к нашей сумме и увеличиваем `i` на 1. Как только `i` становится равным 10, цикл заканчивается и программа выдаёт нам сумму всех чисел от 0 до 9 равную 45. | ||
Такой код мы можем переписать на цикл `for` | ||
```python | ||
sum = 0 | ||
for i in range(10): | ||
sum += i | ||
print(sum) # => 45 | ||
``` | ||
Первый пример использует `while`, который продолжает работать пока `i < 10`. Второй использует `for` и выполняет итерацию от 0 до 9 с помощью функции `range()`. Оба выполняют одно и то же: складывают числа от 0 до 9 в переменную `sum`, но используют разные способы выполнения итераций. | ||
## Функция `range()` | ||
Функция range в Python является встроенной функцией, которая создает последовательность чисел внутри определенного диапазона. Ее можно использовать в цикле for для контроля количества итераций. | ||
У `range()` есть несколько вариантов использования: | ||
* `range(stop)` создает последовательность от 0 до `stop - 1` | ||
* `range(start, stop)` создает последовательность от start до `stop - 1` | ||
* `range(start, stop, step)` создает последовательность из чисел от start до `stop - 1`, с шагом `step` | ||
Пример с одним конечным значением мы рассмотрели выше. Рассмотрим другой - распечатаем на экран числа от 1 до 3: | ||
```python | ||
for i in range(1, 4): | ||
print(i) | ||
# => 1 | ||
# => 2 | ||
# => 3 | ||
``` | ||
Теперь попробуем вывести числа в обратном порядке | ||
```python | ||
for i in range(3, 0, -1): | ||
print(i) | ||
# => 3 | ||
# => 2 | ||
# => 1 | ||
``` | ||
На примерах выше мы видим, что итерация завершается до конечного значения | ||
instructions: | | ||
Реализуйте функцию `print_table_of_squares(from, to)`, которая считает квадраты чисел от `from` до `to` и печатает на экран строки `square of <число> is <результат>` | ||
Примеры вызова: | ||
```python | ||
print_table_of_squares(1, 3) | ||
# => square of 1 is 1 | ||
# => square of 2 is 4 | ||
# => square of 3 is 9 | ||
``` | ||
tips: [] | ||
|
||
definitions: [] |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,4 @@ | ||
def print_table_of_squares(first, last): | ||
for i in range(first, last + 1): | ||
square = i * i | ||
print(f"square of {i} is {square}") |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,11 @@ | ||
|
||
Реализуйте функцию `print_table_of_squares(from, to)`, которая печатает на экран квадраты чисел. Она первое `from` и последнее `to` число печатает строку `square of <число> is <результат>` | ||
|
||
Примеры вызова: | ||
|
||
```python | ||
print_table_of_squares(1, 3) | ||
# => square of 1 is 1 | ||
# => square of 2 is 4 | ||
# => square of 3 is 9 | ||
``` |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,64 @@ | ||
|
||
Представьте, что у нас есть ряд чисел от 0 до 9. Мы хотим сложить эти числа. Мы могли бы сделать это так: | ||
|
||
```python | ||
sum = 0 | ||
i = 0 | ||
|
||
while i < 10: | ||
sum += i | ||
i += 1 | ||
|
||
print(sum) # => 45 | ||
``` | ||
|
||
Сначала мы устанавливаем начальную сумму 0. Далее запускается цикл, в котором переменная `i` начинает принимать значения начиная с 0 и доходя до 10. На каждом шаге мы прибавляем значение `i` к нашей сумме и увеличиваем `i` на 1. Как только `i` становится равным 10, цикл заканчивается и программа выдаёт нам сумму всех чисел от 0 до 9 равную 45. | ||
|
||
Такой код мы можем переписать на цикл `for` | ||
|
||
```python | ||
sum = 0 | ||
|
||
for i in range(10): | ||
sum += i | ||
|
||
print(sum) # => 45 | ||
``` | ||
|
||
Первый пример использует `while`, который продолжает работать пока `i < 10`. Второй использует `for` и выполняет итерацию от 0 до 9 с помощью функции `range()`. Оба выполняют одно и то же: складывают числа от 0 до 9 в переменную `sum`, но используют разные способы выполнения итераций. | ||
|
||
|
||
## Функция `range()` | ||
|
||
Функция range в Python является встроенной функцией, которая создает последовательность чисел внутри определенного диапазона. Ее можно использовать в цикле for для контроля количества итераций. | ||
|
||
У `range()` есть несколько вариантов использования: | ||
|
||
* `range(stop)` создает последовательность от 0 до `stop - 1` | ||
* `range(start, stop)` создает последовательность от start до `stop - 1` | ||
* `range(start, stop, step)` создает последовательность из чисел от start до `stop - 1`, с шагом `step` | ||
|
||
Пример с одним конечным значением мы рассмотрели выше. Рассмотрим другой - распечатаем на экран числа от 1 до 3: | ||
|
||
```python | ||
|
||
for i in range(1, 4): | ||
print(i) | ||
|
||
# => 1 | ||
# => 2 | ||
# => 3 | ||
``` | ||
|
||
Теперь попробуем вывести числа в обратном порядке | ||
|
||
```python | ||
for i in range(3, 0, -1): | ||
print(i) | ||
|
||
# => 3 | ||
# => 2 | ||
# => 1 | ||
``` | ||
|
||
На примерах выше мы видим, что итерация завершается до конечного значения |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,3 @@ | ||
name: Цикл for и функция range | ||
tips: [] | ||
definitions: [] |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,18 @@ | ||
from index import print_table_of_squares | ||
from hexlet.test import expect_output | ||
|
||
|
||
def test(capsys): | ||
expected = '''square of 1 is 1 | ||
square of 2 is 4 | ||
square of 3 is 9 | ||
square of 4 is 16 | ||
square of 5 is 25 | ||
square of 6 is 36 | ||
square of 7 is 49 | ||
square of 8 is 64 | ||
square of 9 is 81 | ||
square of 10 is 100''' | ||
|
||
print_table_of_squares(1, 10) | ||
expect_output(capsys, expected) |