Skip to content
Open
13 changes: 12 additions & 1 deletion 1_if1.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,12 +14,23 @@

"""


def main():
"""
Эта функция вызывается автоматически при запуске скрипта в консоли
В ней надо заменить pass на ваш код
"""
pass
def activity_by_age(age):
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Лучше объявить функцию activity_by_age не внутри функции main а перед ней. Тогда она будет доступна для вызова из любой части кода, а не только из функции main. В данном случае это мало на что влияет, но важно обратить внимание

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

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

a6e9a6a Исправил

if 0 <= age <= 7:
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Нужно ли тут сравнение с 0 или оно избыточно? (и далее вопрос про сравнение с 7)

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

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

Думаю, что 0 избыточен. 7 скорее всего тоже, но как будто так код удобнее читается. Подскажи как лучше плиз

return 'Вы в детском садике'
elif 7 < age <= 17:
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Можно ли заменить elif на if? А почему?

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

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

Думаю, что можно. Если выполнится условие, то мы выйдем из функции и программа не будет проходить по следующим проверкам. Возможно код с elif все же будет более читабельным. Больше не знаю что добавить)

return 'Вы учитесь в школе'
else:
return 'Вы в ВУЗе или работаете'

age = abs(int(input('Введите ваш возраст: ')))
print(activity_by_age(age))

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

при желании можно избавиться от функции main и перенести этот код в if name но тут на твое усмотрение уже

Copy link
Copy Markdown
Author

@Maksimous777 Maksimous777 Jun 2, 2023

Choose a reason for hiding this comment

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

вынес) a1c78dc


if __name__ == "__main__":
main()
23 changes: 21 additions & 2 deletions 2_if2.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,12 +15,31 @@

"""


def main():
"""
Эта функция вызывается автоматически при запуске скрипта в консоли
В ней надо заменить pass на ваш код
"""
pass

def check_strings(str1, str2):
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Аналогично про расположение функции

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

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

4d6f8c8 забыл для исправления свой коммит написать

if not isinstance(str1, str) or not isinstance(str2, str):
return 0

str1 = str1.strip().lower()
str2 = str2.strip().lower()

if str1 == str2:
return 1
elif str2 == 'learn':
return 3
elif len(str1) > len(str2):
return 2

print(check_strings('hello', 777)) # 0
print(check_strings('hello', 'hello')) # 1
print(check_strings('hello', 'hell')) # 2
print(check_strings('hi', 'learn')) # 3
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

А можешь придумать тест из 2 строк, в котором выведется на экран что-то кроме 0-1-2-3
Это очень полезное упражнение :)

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

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

4d6f8c8 Приделал, сразу потребовался else :)



if __name__ == "__main__":
main()
33 changes: 31 additions & 2 deletions 3_for.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,12 +16,41 @@
* Посчитать и вывести среднее количество продаж всех товаров
"""


def main():
"""
Эта функция вызывается автоматически при запуске скрипта в консоли
В ней надо заменить pass на ваш код
"""
pass


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 count_sum(items_list):
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

здорово что написал сам! Дальше можно использовать встроенную функцию sum

items_sum = 0
for item in items_list:
items_sum += item
return items_sum

phones_sum = 0
for phone in phones:
phone['sum_sold'] = count_sum(phone['items_sold'])
phone_sold_avg = int(phone['sum_sold'] / len(phone['items_sold']))
phones_sum += phone['sum_sold']
print(
f"Суммарное количество продаж {phone['product']}: {phone['sum_sold']}")
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Маленькая придирка. Наверно, не количество, а объем продаж

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

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

79209f9 Исправил

print(
f"Среднее количество продаж {phone['product']}: {phone_sold_avg}", end='\n\n')
print(f"Всего телефонов продано: {phones_sum}")
phones_avg = int(phones_sum / len(phones))
print(f"В среднем телефонов продано: {phones_avg}")


if __name__ == "__main__":
main()
6 changes: 4 additions & 2 deletions 4_while1.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,8 +14,10 @@ def hello_user():
"""
Замените pass на ваш код
"""
pass
while True:
if input('Как дела? \n') == 'Хорошо':
break

Copy link
Copy Markdown

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()
13 changes: 11 additions & 2 deletions 5_while2.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,13 +15,22 @@

"""

questions_and_answers = {}
questions_and_answers = {
'Как дела': 'Хорошо!',
'Что делаешь': 'Программирую',
'И все?': 'Ну, почти',
'Ну и лошара': 'Да пошел ты'
}

def ask_user(answers_dict):
"""
Замените pass на ваш код
"""
pass
print('Введите вопрос: ')
while True:
question = input('Пользователь: ')
if answers_dict.get(question):
print(f"Программа: {answers_dict.get(question, '')}", end='\n\n')
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

👍 Отлично! Не придраться


if __name__ == "__main__":
ask_user(questions_and_answers)