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

learn-homework-1(R) #127

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
21 changes: 14 additions & 7 deletions 1_if1.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,12 +14,19 @@

"""

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

if 3 <= age < 7:
return 'Вы должны быть в детском саду'
elif 7 <= age < 18:
return 'Вы должны быть в школе'
elif 18 <= age < 60:
return 'Вы должны быть на работе'
else:
return 'Отдыхайте!'
Copy link

Choose a reason for hiding this comment

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

в целом все хорошо, но хороший программист всегда немного параноик, а может ли возраст быть отрицательным, а может ли он быть больше скажем 150, может ли пользователь вести не число, что будет тогда? если есть желание, то можно подумать и поправить программу учитывая эти вопросы


result = main('age')
Copy link

Choose a reason for hiding this comment

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


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

"""

def main():
"""
Эта функция вызывается автоматически при запуске скрипта в консоли
В ней надо заменить pass на ваш код
"""
pass
def main(str1, str2):
value1 = (isinstance(str1, str))
value2 = (isinstance(str2, str))
if value1 != True and value2 != True:
Copy link

Choose a reason for hiding this comment

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

if isinstance(str1, str) and isinstance(str2, str):
в таком виде тоже будет работать

return '0'
elif str1 == str2:
return '1'
elif str1 != str2 and len(str1) > len(str2):
return '2'
elif str1 != str2 and str2 == 'python':
return '3'


print(main(1, 2))
Copy link

Choose a reason for hiding this comment

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

все вызовы функций должны быть под if

print(main('London', 'London'))
print(main('Winter is coming', 'Hear me roar!'))
print(main('poo', 'python'))


if __name__ == "__main__":
main()

39 changes: 34 additions & 5 deletions 3_for.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,12 +16,41 @@
* Посчитать и вывести среднее количество продаж всех товаров
"""

stock = [
Copy link

Choose a reason for hiding this comment

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

в таком виде код файла 3_for.py не работает, нужно поправить

Copy link

Choose a reason for hiding this comment

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

в целом я понял, что ты имел ввиду, если сделать пару исправлений, то +- работает
нужно внести несколько исправлений

  1. ты проходишь по словарю 3 раза (у тебя 3 цикла for), давай сделаем 1 проход и один цикл
  2. очень хорошо, что ты используешь функции, но вызывать все функции нужно под if, дававай это тоже исправим
  3. если все поправить и запустить код, появится несколько цифр, которые на первый взгляд ничего не скажут, нужно смотреть код, добавь f строки, чтобы улучшить читаемость

{'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():
"""
Эта функция вызывается автоматически при запуске скрипта в консоли
В ней надо заменить pass на ваш код
"""
pass
def item_sum(quantity):
Copy link

Choose a reason for hiding this comment

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

поправить отступы

sold_sum = 0
for item in quantity:
sold_sum += item
return sold_sum

all_prod_sum = 0
for one_product in stock:
product_sum = product_sum(one_product['items_sold'])
Copy link

Choose a reason for hiding this comment

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

вместо product_sum item_sum

print(product_sum)
all_prod_sum += product_sum
print(all_prod_sum)


def item_avg(quantity):
sell_sum = 0
for item in quantity:
sell_sum += item
avg_prod = sell_sum / len(quantity)
return avg_prod

all_prod_avg = 0
for one_product in stock:
product_avg = item_avg(one_product['items_sold'])
print(product_avg)

all_prod_avg = product_avg / len(stock)
print(all_prod_avg)

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


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

Choose a reason for hiding this comment

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

тут функция вызывается в нужном месте (с заданием все ок)

user_word = input('What does the fox say?')
if user_word == 'furfur':
print('oooooooh, so sweet!')
break
else:
print('Am I a joke to you?')


if __name__ == "__main__":
Expand Down
21 changes: 15 additions & 6 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 = {
'How are you?': 'How are you',
'How old are you?': 'Next question :)',
'Do you like cats?': 'Im obsessed with this sweet fury creatures'
}


def ask_user(questions_and_answers):
while True:
start = input('Ask a question: ')
answer = questions_and_answers.get(start, "wtf")
print(answer)


ask_user(questions_and_answers)
Copy link

Choose a reason for hiding this comment

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

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


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

if __name__ == "__main__":
ask_user(questions_and_answers)
16 changes: 11 additions & 5 deletions 6_exception1.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,10 +11,16 @@
"""

def hello_user():
"""
Замените pass на ваш код
"""
pass
while True:
try:
user_word = input('What does the fox say?')
if user_word == 'furfur':
print('oooooooh, so sweet!')
else:
print('Am I a joke to you?')
except KeyboardInterrupt:
print('Bye!')
break

if __name__ == "__main__":
hello_user()
hello_user()
19 changes: 13 additions & 6 deletions 7_exception2.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,14 +12,21 @@
ValueError и TypeError, если приведение типов не сработало.

"""

def discounted(price, discount, max_discount=20)
"""
Замените pass на ваш код
"""
pass
def discounted(price, discount, max_discount=20):
try:
price = abs(float(price))
discount = abs(float(discount))
max_discount = abs(int(max_discount))
except(ValueError, TypeError):
Copy link

Choose a reason for hiding this comment

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

все ты верно вставил

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

if __name__ == "__main__":

print(discounted(100, 2))
print(discounted(100, "3"))
print(discounted("100", "4.5"))
Expand Down
12 changes: 3 additions & 9 deletions 8_ephem_bot.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,13 +21,7 @@
filename='bot.log')


PROXY = {
'proxy_url': 'socks5://t1.learn.python.ru:1080',
'urllib3_proxy_kwargs': {
'username': 'learn',
'password': 'python'
}
}



def greet_user(update, context):
Expand All @@ -43,7 +37,7 @@ def talk_to_me(update, context):


def main():
mybot = Updater("КЛЮЧ, КОТОРЫЙ НАМ ВЫДАЛ BotFather", request_kwargs=PROXY, use_context=True)
mybot = Updater("КЛЮЧ, КОТОРЫЙ НАМ ВЫДАЛ BotFather", use_context=True)

dp = mybot.dispatcher
dp.add_handler(CommandHandler("start", greet_user))
Expand All @@ -54,4 +48,4 @@ def main():


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