Skip to content

Домашнее задание к 1-ой лекции#72

Open
KudryavtsevaMariya wants to merge 4 commits into
mainfrom
mkudryavceva
Open

Домашнее задание к 1-ой лекции#72
KudryavtsevaMariya wants to merge 4 commits into
mainfrom
mkudryavceva

Conversation

@KudryavtsevaMariya
Copy link
Copy Markdown
Collaborator

No description provided.

Copy link
Copy Markdown
Owner

@IlyaOrlov IlyaOrlov left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Всё хорошо! Хотя есть некоторые замечания.
И ещё такой момент... Чтоб Гитхаб не рисовал "кирпичи" в конце файлов, рекомендуется оставлять в файле одну последнюю строку пустой. Это нужно, чтоб код можно было без проблем открыть даже в старых текстовых редакторах, которые пропускают строки, не оканчивающиеся символом переноса строки (это как раз последняя строка). Подробнее об этом рассказывается в 4-й лекции где-то с отметки 1ч14мин.

end = input("Топлива осталось: ")
distance = input("Расстояние: ")
diff = int(start) - int(end)
result = int(diff) / int(distance)
Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

diff - и так число, потому что определён как разность двух чисел (в стр.4). Поэтому в int здесь его можно не оборачивать.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Поняла.

import hashlib
import ast
import argparse
# Возможно, здесь знак умножения нужно заменить на time.
Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Кстати, хорошее предложение. Тем более функция time, которую Вы, по факту, предлагаете импортировать из модуля time (from time import time), как раз используется в стр.46
Только "знак умножения" лучше назвать "звёздочкой", т.к. в этом контексте он точно не обозначает умножение.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Поняла.


def rename(self, dirname, output):
mp3s = []
# Я пока не поняла саму суть этого года, но в конце строки должно быть либо "os.walk()", либо "os.path.dirname()".
Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Нет, в этом ошибки нет. Здесь имеется в виду переменная dirname, переданная сюда в стр.15.
os.walk(dirname) - это обход всех файлов и папок, лежащих в папке dirname.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Поняла.

for root, directories, files in os.walk(dirname):
for file in files:
if file[-3:] == '.mp3':
# Не совсем поняла какой элемент списка mp3s будет добавляться в конец, если элементов в списке пока нет.
Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Здесь в список mp3s добавляется ещё один список (да, так тоже можно) из пары значений root и file.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Поняла.

if file[-3:] == '.mp3':
# Не совсем поняла какой элемент списка mp3s будет добавляться в конец, если элементов в списке пока нет.
mp3s.append([root, file])
# В самом верху кода не указано "from pathlib import Path".
Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Path и path - это разные, с точки зрения Python, слова. Для него регистр буквы имеет значение. В любом случае path здесь - это просто переменная. Как можно понять из предыдущего замечания, mp3s будет состоять из пар root (путь к текущему файлу) и file (имя файла). И здесь мы эти пары последовательно извлекаем из mp3s, так что path указывает на root, а mp3 - на file.
Мы это еще будем разбирать детально, когда пройдем функции и списки.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Поняла.

rename_parser = subparsers.add_parser('rename', help='rename help')
rename_parser.add_argument('dirname')
rename_parser.add_argument('-o', '--output', help='path to a file where restore map is stored')
# В коде используются либо одинарные, либо двойные скобки. Если их и смешивают, то для цитирования '"Какой-то фразы"'.
Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Хороший комментарий! Первый раз вижу, чтоб на это обратили внимание! Но да, всё по делу.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Вы же про это говорили)
P.S. пыталась найти хоть какие-то ошибки, которые я понимаю что это ошибки.

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Да. Тут и требовалось найти ВСЕ ошибки. Только те, которые понятны.

return args

# Если это продолжение рабочего кода, то зачем здесь разделение в две строки?
def main():
Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Функция верхнего уровня (т.е. не вложенная ни в класс, ни в другую функцию) должна обособляться двумя пустыми строками (PEP8) А чем эта функция хуже других?

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

О! Это интересно. Спасибо за разъяснение!

else:
sys.exit()

# Функция main() используется для разделения блоков кода в программе. Какой смысл от неё в конце кода?
Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Почему она используется для разделения блоков в программе?
Это обычная функция) В стр.65-76 она определяется (описывается, как она должна работать). А здесь она вызывается. По сути, это единственная строчка основного кода в этом файле.


long = input("Введите длинну: ")
width = input("Введите ширину: ")
sguare = (int(long) + int(width)) * 2
Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Название переменной sguare вводит в заблуждение) Мы же всё-таки периметр рассчитываем, а не площадь.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Когда делала задание, думала о периметре, а написала площадь facepalm.
Буду более внимательней.

time = input("Введите время: ")
distance = input("Введите расстояние: ")
average_speed = int(distance) / int(time)
print("Средняя скорость автомобиля: ", int(average_speed), "км/ч.") No newline at end of file
Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Можно уже попробовать форматную строку применить;)

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Что за форматная версия приложения?

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

"форматная версия приложения"???
Нет, всего лишь форматная строка:

print(f"Средняя скорость автомобиля: {int(average_speed)}км/ч.")

# Написать программу, заменяющую все буквы “А” в слове, введённом пользователем, на символ “*”.

s = input('Напишите слово, начинающееся на букву "А": ')
print(s.replace("А", "*", 1))
Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

А почему только одну букву А заменяем? Надо же ВСЕ.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

То, что две подряд АА программа не заменяет, я сейчас вижу. Исправлю.
А программа должна заменять "А" в верхнем и нижнем регистре?

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

В задании речь только о большой букве "А"

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants