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

commit with homework #170

Open
wants to merge 5 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 1 commit
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
15 changes: 14 additions & 1 deletion 1_if1.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,20 @@ def main():
Эта функция вызывается автоматически при запуске скрипта в консоли
В ней надо заменить pass на ваш код
"""
pass
age = int(input('Please enter your age:'))

def detect(age):
if 3 <= age <= 6:
return 'You should be in kindergarden'
elif 7 <= age <=18:
return 'You should be in school boy'
elif 18 <= age <= 23:
return 'You should be in University dude'
else:
return 'You should probably work man'

result = detect (age)
aka-nomad marked this conversation as resolved.
Show resolved Hide resolved
print(result)

if __name__ == "__main__":
main()
23 changes: 22 additions & 1 deletion 2_if2.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,28 @@ def main():
Эта функция вызывается автоматически при запуске скрипта в консоли
В ней надо заменить pass на ваш код
"""
pass
def comapre_str(string1, string2):
if type(string1) is str and type(string2) is str:
len1 = len(string1)
len2 = len(string2)

if len1 == len2:
return 1
elif len1 > len2 and string2 != 'learn':
aka-nomad marked this conversation as resolved.
Show resolved Hide resolved
return 2
elif string2 == 'learn':
aka-nomad marked this conversation as resolved.
Show resolved Hide resolved
return 3
else:
return 'No rule for such combinations'
else:
return 0

for i in range(0, 4):
x = {0:1, 1:'Python',2:'hello', 3:'python3'}
y = {0:'Python', 1:'learn',2:'hello', 3:'PYTHON'}
result = comapre_str(x[i], y[i])
print(result)
#print(x[i], y[i])
aka-nomad marked this conversation as resolved.
Show resolved Hide resolved

if __name__ == "__main__":
main()
19 changes: 18 additions & 1 deletion 3_for.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,24 @@ def main():
Эта функция вызывается автоматически при запуске скрипта в консоли
В ней надо заменить pass на ваш код
"""
pass
product_sell = [
{'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]},
]
total_sale = 0

for i in range(len(product_sell)):
item = product_sell[i].get('product', 'no item')
sale = product_sell[i].get('items_sold', 0)

sum_of_sale = sum(sale)
average_sale = sum(sale) // len(sale)
aka-nomad marked this conversation as resolved.
Show resolved Hide resolved
total_sale += sum_of_sale

print(f"{item}, Total amount of sale: {sum_of_sale}, Average number of sale:{average_sale}")

print(f"All items total sales: {total_sale}, All items average sales: {total_sale // len(product_sell)}")

Choose a reason for hiding this comment

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

Вот тут - неправильный расчет общего среднего.... Посмотри и прикинь, почему оно в 12 раз больше, чем нужно

Copy link
Author

Choose a reason for hiding this comment

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

а т.е. сначала посчитать среднее всех продаж по каждому товару и потом сложить

Copy link
Author

Choose a reason for hiding this comment

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

поправил и пушнул

Copy link
Author

Choose a reason for hiding this comment

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

верно сделал?


if __name__ == "__main__":
main()
8 changes: 6 additions & 2 deletions 4_while1.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,8 +14,12 @@ def hello_user():
"""
Замените pass на ваш код
"""
pass

answer = ''

while True:
answer = input('How are you?')
if answer in ('Good', 'good'):
break
aka-nomad marked this conversation as resolved.
Show resolved Hide resolved

if __name__ == "__main__":
hello_user()
12 changes: 11 additions & 1 deletion 5_while2.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,17 @@ def ask_user(answers_dict):
"""
Замените pass на ваш код
"""
pass
dicts = {
"Как дела": "Хорошо!", "Что делаешь?": "Программирую", "Сколько тебе лет":"У меня нет возраста", "Любишь Питон":"Да"
}

while True:
answer = input("Задай свой вопрос:")

Choose a reason for hiding this comment

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

Тут некорректно выбрано имя переменной. Переменная - anwser - что переводится как ответ, а по факту в ней вопрос. Ее нужно было назвать "question"

Copy link
Author

Choose a reason for hiding this comment

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

тут я немного сам уже не понимаю. В переменной ответ от пользователя или я не прав?

if answer in ("Пока", "пока"):
print("Пока!")
break
else:
print(f"Пользователь: {answer}{'\n'}Программа:{dicts.get(answer, 'У меня нет ответа на данный вопрос')}")
aka-nomad marked this conversation as resolved.
Show resolved Hide resolved

if __name__ == "__main__":
ask_user(questions_and_answers)
12 changes: 11 additions & 1 deletion 6_exception1.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,17 @@ def hello_user():
"""
Замените pass на ваш код
"""
pass
answer = ''

while True:
try:
answer = input('How are you?')
if answer in ('Good', 'good'):
break
except KeyboardInterrupt:
print('\n', 'Good-bye!!!')
break

aka-nomad marked this conversation as resolved.
Show resolved Hide resolved

if __name__ == "__main__":
hello_user()
10 changes: 8 additions & 2 deletions 7_exception2.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,11 +13,17 @@

"""

def discounted(price, discount, max_discount=20)
def discounted(price, discount, max_discount=20):
"""
Замените pass на ваш код
"""
pass
try:
price, discount, max_discount = float(price), float(discount), int(max_discount)
if max_discount >= 100:
raise ValueError('Слишком большая максимальная скидка')
return price - (price * discount / 100)
except (ValueError, TypeError):
print('Переданы некорректные аргументы или не сработало приведение типов данных!')

Choose a reason for hiding this comment

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

Код работает, но есть некоторая неопределенность. Непонятно где проблема преобразования. Лучше сделать обработчики на каждом преобразовании и написать какой именно параметр некорректный

Copy link
Author

Choose a reason for hiding this comment

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

разделил, но все равно остались вопросы


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