-
Notifications
You must be signed in to change notification settings - Fork 446
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
My-homework #128
base: master
Are you sure you want to change the base?
My-homework #128
Changes from all commits
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -5,22 +5,41 @@ | |
Условный оператор: Сравнение строк | ||
|
||
* Написать функцию, которая принимает на вход две строки | ||
* Проверить, является ли то, что передано функции, строками. | ||
* Проверить, является ли то, что передано функции, строками. | ||
Если нет - вернуть 0 | ||
* Если строки одинаковые, вернуть 1 | ||
* Если строки разные и первая длиннее, вернуть 2 | ||
* Если строки разные и вторая строка 'learn', возвращает 3 | ||
* Вызвать функцию несколько раз, передавая ей разные праметры | ||
* Вызвать функцию несколько раз, передавая ей разные праметры | ||
и выводя на экран результаты | ||
|
||
""" | ||
|
||
def main(): | ||
|
||
def main(str_one, str_two): | ||
""" | ||
Эта функция вызывается автоматически при запуске скрипта в консоли | ||
В ней надо заменить pass на ваш код | ||
""" | ||
pass | ||
|
||
|
||
if type(str_one) != str and type(str_two) != str: | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. лучше тип проверять через isinstance |
||
print(0) | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Надо возвращать значения, а не печатать их |
||
elif str_one == str_two: | ||
print(1) | ||
elif str_one != str_two and len(str_one) > len(str_two): | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. а тут разве нужна первая чать условия? |
||
print(2) | ||
elif str_one != str_two and str_two == "learn": | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. и вот тут тоже? |
||
print(3) | ||
|
||
|
||
if __name__ == "__main__": | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Обычно это блок один и уже внутри можно вызвать функцию main столько сколько нужно |
||
main(1, 2) | ||
|
||
if __name__ == "__main__": | ||
main("python", "python") | ||
|
||
if __name__ == "__main__": | ||
main("learn_python", "python") | ||
|
||
if __name__ == "__main__": | ||
main() | ||
main("py", "learn") |
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -6,7 +6,7 @@ | |
|
||
* Дан список словарей с данными по колличеству проданных телефонов | ||
[ | ||
{'product': 'iPhone 12', 'items_sold': [363, 500, 224, 358, 480, 476, 470, 216, 270, 388, 312, 186]}, | ||
{'product': 'iPhone 12', 'items_sold': [363, 500, 224, 358, 480, 476, 470, 216, 270, 388, 312, 186]}, | ||
{'product': 'Xiaomi Mi11', 'items_sold': [317, 267, 290, 431, 211, 354, 276, 526, 141, 453, 510, 316]}, | ||
{'product': 'Samsung Galaxy 21', 'items_sold': [343, 390, 238, 437, 214, 494, 441, 518, 212, 288, 272, 247]}, | ||
] | ||
|
@@ -16,12 +16,36 @@ | |
* Посчитать и вывести среднее количество продаж всех товаров | ||
""" | ||
|
||
def main(): | ||
""" | ||
Эта функция вызывается автоматически при запуске скрипта в консоли | ||
В ней надо заменить pass на ваш код | ||
""" | ||
pass | ||
|
||
if __name__ == "__main__": | ||
main() | ||
phones = [ | ||
{'product': 'iPhone 12', 'items_sold': [363, 500, 224, 358, 480, 476, 470, 216, 270, 388, 312, 186]}, | ||
{'product': 'Xiaomi Mi11', 'items_sold': [317, 267, 290, 431, 211, 354, 276, 526, 141, 453, 510, 316]}, | ||
{'product': 'Samsung Galaxy 21', 'items_sold': [343, 390, 238, 437, 214, 494, 441, 518, 212, 288, 272, 247]}, | ||
] | ||
|
||
|
||
def main(phone_sold): | ||
scores_sum = 0 | ||
for score in phone_sold: | ||
scores_sum += score | ||
scores_avg = scores_sum / len(phone_sold) | ||
print(f"Суммарно {one_mark['product']} проданно {scores_sum}") | ||
return scores_avg | ||
|
||
|
||
for one_mark in phones: | ||
mark_score_avg = main(one_mark['items_sold']) | ||
print(f"Средние продажи на марку телефона {one_mark['product']}: {mark_score_avg}.") | ||
|
||
avg_scores_sum = 0 | ||
|
||
for one_mark in phones: | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. а зачем во втором цикле заново проходить, если можно сразу и посчиать |
||
avg_scores_sum += main(one_mark["items_sold"]) | ||
|
||
mark_avg = avg_scores_sum / len(phones) | ||
print(f"В среднем по каждой марке {mark_avg}. В среднем продано всего {avg_scores_sum}") | ||
|
||
try: | ||
if __name__ == "__main__": | ||
main() | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. main надо же с аргументом вызывать Надо вспомогательную функцию на 26 строке назвать по-другому, а остальной код положить в main |
||
except TypeError: | ||
print("Подсчет закончен") |
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -4,18 +4,25 @@ | |
|
||
Цикл while: hello_user | ||
|
||
* Напишите функцию hello_user(), которая с помощью функции input() спрашивает | ||
* Напишите функцию hello_user(), которая с помощью функции input() спрашивает | ||
пользователя “Как дела?”, пока он не ответит “Хорошо” | ||
|
||
""" | ||
|
||
|
||
def hello_user(): | ||
""" | ||
Замените pass на ваш код | ||
""" | ||
pass | ||
user_say = input("Как дела?: ") | ||
while True: | ||
if user_say.capitalize() == "Хорошо": | ||
print("Вот и хорошо") | ||
break | ||
else: | ||
print("Ну скажи 'Хорошо'?") | ||
return hello_user() | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. а без рекурсии как сделать? |
||
|
||
|
||
|
||
if __name__ == "__main__": | ||
hello_user() |
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -10,15 +10,25 @@ | |
* Первые два нужно приводить к вещественному числу при помощи float(), | ||
а третий - к целому при помощи int() и перехватывать исключения | ||
ValueError и TypeError, если приведение типов не сработало. | ||
|
||
""" | ||
|
||
def discounted(price, discount, max_discount=20) | ||
""" | ||
Замените pass на ваш код | ||
""" | ||
pass | ||
|
||
|
||
def discounted(price, discount, max_discount=20): | ||
try: | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. в блок try лучше оборачивать те строки где ожидается ошибка, а не весь код |
||
price = float(price) | ||
discount = float(discount) | ||
max_discount = int(max_discount) | ||
if max_discount >= 100: | ||
raise ValueError("Слишком большая скидка") | ||
if discount >= max_discount: | ||
return price | ||
else: | ||
return price - (price * discount / 100) | ||
except (ValueError, TypeError): | ||
print("Неверное значение") | ||
|
||
|
||
if __name__ == "__main__": | ||
print(discounted(100, 2)) | ||
print(discounted(100, "3")) | ||
|
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
вот эту строчку оборачивать в try не нужно