Skip to content
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

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
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
29 changes: 23 additions & 6 deletions 1_if1.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,22 +4,39 @@

Условный оператор: Возраст

* Попросить пользователя ввести возраст при помощи input и положить
* Попросить пользователя ввести возраст при помощи input и положить
результат в переменную
* Написать функцию, которая по возрасту определит, чем должен заниматься пользователь:
* Написать функцию, которая по возрасту определит, чем должен заниматься пользователь:
учиться в детском саду, школе, ВУЗе или работать
* Вызвать функцию, передав ей возраст пользователя и положить результат
* Вызвать функцию, передав ей возраст пользователя и положить результат
работы функции в переменную
* Вывести содержимое переменной на экран

"""


def main():
"""
Эта функция вызывается автоматически при запуске скрипта в консоли
В ней надо заменить pass на ваш код
"""
pass
age = input("Здравствуйте! Сколько вам лет? ")
person_age = int(age)

if person_age < 7:
print("Вам нужно в садик")
elif person_age < 18:
print("Вам нужно в школу")
elif person_age < 22:
print("Пора в ВУЗ")
elif person_age >= 77:
print("Вам уже никуда не нужно")
else:
print("Теперь можно и на работу!")


if __name__ == "__main__":
main()
try:
if __name__ == "__main__":

Choose a reason for hiding this comment

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

вот эту строчку оборачивать в try не нужно

main()
except ValueError:
print("Напишите пожалуйста цифрами")
31 changes: 25 additions & 6 deletions 2_if2.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:

Choose a reason for hiding this comment

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

лучше тип проверять через isinstance

print(0)

Choose a reason for hiding this comment

The 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):

Choose a reason for hiding this comment

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

а тут разве нужна первая чать условия?

print(2)
elif str_one != str_two and str_two == "learn":

Choose a reason for hiding this comment

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

и вот тут тоже?

print(3)


if __name__ == "__main__":

Choose a reason for hiding this comment

The 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")
44 changes: 34 additions & 10 deletions 3_for.py
Original file line number Diff line number Diff line change
Expand Up @@ -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]},
]
Expand All @@ -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:

Choose a reason for hiding this comment

The 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()

Choose a reason for hiding this comment

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

main надо же с аргументом вызывать

Надо вспомогательную функцию на 26 строке назвать по-другому, а остальной код положить в main

except TypeError:
print("Подсчет закончен")
15 changes: 11 additions & 4 deletions 4_while1.py
Original file line number Diff line number Diff line change
Expand Up @@ -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()

Choose a reason for hiding this comment

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

а без рекурсии как сделать?




if __name__ == "__main__":
hello_user()
23 changes: 14 additions & 9 deletions 5_while2.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,16 +12,21 @@

Пользователь: Что делаешь?
Программа: Программирую

"""

questions_and_answers = {}
questions_and_answers = {"Как дела?": "Хорошо!", "Что делаешь?": "Программирую"}


def ask_user():
while True:
user_say = input("Привет спроси у меня 'Как дела?' или 'Что делаешь?': ")
if user_say.capitalize() in questions_and_answers:
print(f"Ответ: {questions_and_answers[user_say.capitalize()]}")
else:
user_say


def ask_user(answers_dict):
"""
Замените pass на ваш код
"""
pass

if __name__ == "__main__":
ask_user(questions_and_answers)
question = ask_user()
print(question)
27 changes: 19 additions & 8 deletions 6_exception1.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,17 +4,28 @@

Исключения: KeyboardInterrupt

* Перепишите функцию hello_user() из задания while1, чтобы она
перехватывала KeyboardInterrupt, писала пользователю "Пока!"
* Перепишите функцию hello_user() из задания while1, чтобы она
перехватывала KeyboardInterrupt, писала пользователю "Пока!"
и завершала работу при помощи оператора break

"""


def hello_user():
"""
Замените pass на ваш код
"""
pass

user_say = input("Как дела?: ")
while True:
try:
if user_say.capitalize() == "Хорошо":
print("Вот и хорошо")
break
else:
print("Ну скажи 'Хорошо'?")
return hello_user()
except KeyboardInterrupt:
print("Пока")
break


if __name__ == "__main__":
hello_user()

24 changes: 17 additions & 7 deletions 7_exception2.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:

Choose a reason for hiding this comment

The 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"))
Expand Down