Skip to content
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
17 changes: 13 additions & 4 deletions 1_if1.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,11 +4,11 @@

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

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

Expand All @@ -19,7 +19,16 @@ def main():
Эта функция вызывается автоматически при запуске скрипта в консоли
В ней надо заменить pass на ваш код
"""
pass
age = int(input('Введите ваш возраст: '))
if 0 <= age < 7:
Copy link

Choose a reason for hiding this comment

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

Вынеси if-ы в отдельную функцию, так что бы она принимала int на вход и ВСЕГДА возвращала строку.

print('Детский сад')
elif 7 <= age < 18:
print('Школа')
elif 18 <= age < 22:
print('ВУЗ')
else:
print('Работать')


if __name__ == "__main__":
main()
18 changes: 14 additions & 4 deletions 2_if2.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,12 +5,12 @@
Условный оператор: Сравнение строк

* Написать функцию, которая принимает на вход две строки
* Проверить, является ли то, что передано функции, строками.
* Проверить, является ли то, что передано функции, строками.
Если нет - вернуть 0
* Если строки одинаковые, вернуть 1
* Если строки разные и первая длиннее, вернуть 2
* Если строки разные и вторая строка 'learn', возвращает 3
* Вызвать функцию несколько раз, передавая ей разные праметры
* Вызвать функцию несколько раз, передавая ей разные праметры
и выводя на экран результаты

"""
Expand All @@ -20,7 +20,17 @@ def main():
Эта функция вызывается автоматически при запуске скрипта в консоли
В ней надо заменить pass на ваш код
"""
pass

string_1, string_2 = input('Введите данные:'), input('Введите данные:')
Copy link

Choose a reason for hiding this comment

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

функция должна принимать два объекта как аргументы.
Объяви функцию (перед main) и вызывай ее в main()

if not string_1.isalpha() and not string_2.isalpha():
Copy link

Choose a reason for hiding this comment

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

Этот код поломается как только будет передана не строка.
Тут надо было проверять с isinstance(string_1, str)

return 0
elif string_1 == string_2:
return 1
elif string_1 == string_2 and len(string_1) > len(string_2):
return 2
elif string_1 != string_2 and string_2 == 'learn':
return 3
else:
return 'Неизвестные данные'

if __name__ == "__main__":
main()
25 changes: 22 additions & 3 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 @@ -21,7 +21,26 @@ def main():
Эта функция вызывается автоматически при запуске скрипта в консоли
В ней надо заменить pass на ваш код
"""
pass

phones_sales = [
{'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]},
]
sum_price_sold = 0
sum_item_sold = 0

for phone in phones_sales:
sum_price_sold += sum(items_sold(phone))
sum_item_sold += len(items_sold(phone))
print(len(items_sold(phone)))
print(round(sum(items_sold(phone)) / len(items_sold(phone)), 0))

print(round(sum_price_sold / sum_item_sold), 0)


def items_sold(phone):
return phone['items_sold']


if __name__ == "__main__":
main()
10 changes: 6 additions & 4 deletions 4_while1.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,18 +4,20 @@

Цикл while: hello_user

* Напишите функцию hello_user(), которая с помощью функции input() спрашивает
* Напишите функцию hello_user(), которая с помощью функции input() спрашивает
пользователя “Как дела?”, пока он не ответит “Хорошо”

"""


def hello_user():
"""
Замените pass на ваш код
"""
pass
insert_word = input('Как дела? ')
while insert_word.strip().capitalize() != 'Хорошо':
insert_word = input('Как дела? ')



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

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

"""

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

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

text = input("Введите вопрос: ").strip().capitalize()
while text not in questions_and_answers:
text = input("Введите вопрос: ").strip().capitalize()
else:
print(questions_and_answers[text])

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

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

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

"""

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

try:
text = input('Как дела?: ')
except KeyboardInterrupt:
return
while text.strip().capitalize() != 'Хорошо':
try:
text = input('Как дела?: ')

except KeyboardInterrupt:
print('Пока!')
break

if __name__ == "__main__":
hello_user()
33 changes: 29 additions & 4 deletions 7_exception2.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,15 +10,40 @@
* Первые два нужно приводить к вещественному числу при помощи float(),
а третий - к целому при помощи int() и перехватывать исключения
ValueError и TypeError, если приведение типов не сработало.
"""

def discounted(price, discount, max_discount=20)
def discounted(price, discount, max_discount=20):
"""
Замените pass на ваш код
"""
pass

try:
price = float(price)
except (ValueError, TypeError):
return 'eRRor'
try:
discount = float(discount)
except (ValueError, TypeError):
return 'eRRor'
try:
max_discount = int(max_discount)
except (ValueError, TypeError):
return 'eRRor'
try:
price = abs(price)
except:
Copy link

Choose a reason for hiding this comment

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

обязательно указываем что именно мы хотим перехватить
без указания мы пытаемся перехватить вообще все (даже KeyboardInterrupt)

discount = abs(discount)
try:
max_discount = abs(max_discount)
Copy link

Choose a reason for hiding this comment

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

Слишком длинный блок try, желательно что бы в try была одна строчка. Тут исключение может быть или в abs, или там где мы сами его бросаем. Поменяй raise на return строки просто.

if max_discount >= 100:
raise ValueError('Слишком большая максимальная скидка')
if discount >= max_discount:
return price
else:
return price - (price * discount / 100)
except (ValueError, TypeError):
return 'eRRor'

if __name__ == "__main__":
print(discounted(100, 2))
print(discounted(100, "3"))
Expand Down