Skip to content

Homework#113

Open
kaplya-sys wants to merge 4 commits intolearnpythonru:masterfrom
kaplya-sys:homework
Open

Homework#113
kaplya-sys wants to merge 4 commits intolearnpythonru:masterfrom
kaplya-sys:homework

Conversation

@kaplya-sys
Copy link
Copy Markdown

No description provided.

Comment thread 2_if2.py Outdated
"""

def check_string(first_string, second_string):
if type(first_string) and type(second_string) != str:
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Тут ты тип first_string не проверяешь, ты по сути проверяешь True оно или False)

Comment thread 2_if2.py Outdated
if second_string == 'learn':
return 3
elif len(first_string) > len(second_string):
return 2
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

а зачем тут дополнительная вложенность? все будет прекрасно работать с одной вложенностью)

Comment thread 3_for.py Outdated
def get_total_sold(items_sold):
summ = 0
for item in items_sold:
summ += item
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() тут)

Comment thread 3_for.py Outdated
def get_average_sold(items_sold):
summ = 0
for item in items_sold:
summ += item
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

и тут

Comment thread 3_for.py Outdated
def total_sold_all_item(products):
all_summ = 0
for product in products:
all_summ += get_total_sold(product['items_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.

а тут попробуй использовать генератор списков в связке с функцией sum . Это не обязательно, задание со звездочкой

Comment thread 3_for.py Outdated
def average_sold_all_item(products):
all_summ = 0
for product in products:
all_summ += get_average_sold(product['items_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.

чтобы получить среднее по всем средним недостаточно просто их сложить)

Comment thread 3_for.py Outdated
def average_sold_all_item(products):
all_summ = 0
for product in products:
all_summ += get_average_sold(product['items_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.

чтобы получить среднее по всем средним недостаточно просто их сложить)

Comment thread 5_while2.py Outdated
while True:
question = input('Введите вопрос: ')
answer = questions_and_answers.get(question)
if answer:
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

get по дефолту возвращает None. None принято проверять как is None или is not None

Comment thread 7_exception2.py
else:
return price - (price * discount / 100)
except (ValueError, TypeError):
print('Ошибка, переданы не верные данные!')
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

  1. строки с 24 по 30 не могут вызвать ни ValueError ни TypeError, не смысла их запихивать в try except. Туда нужно класть только те строки, в которых ты ожидаешь увидеть ошибку
  2. Тут ты отлавливаешь две ошибки разом с одним сообщением, чаще всего это не очень удобно, потому что будет сложно понять где именно произошла ошибка и что это была за ошибка

Comment thread 8_ephem_bot.py Outdated
text_message = update.message.text.split()
date_today = date.today().strftime("%Y/%m/%d")

fn = getattr(ephem, text_message[1])
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

а что если нужно планеты не будет? Спойлер: у getattr есть третий аргумент, на основе которого можно будет обработать этот кейс

Comment thread 1_if1.py Outdated
"""
def distribute_career(age):
if age < 1.5:
return print('Ты совсем еще маленький')
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Нет никакого смысла возвращать возвращаемое значение принта (там None кажется). Или вернуть строку или вызвать print.

Comment thread 1_if1.py Outdated
elif 7 < age <= 18:
return print('Учиться в школе')
elif 18 < age <= 23:
return print('Учиться в ВУЗе')
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Два пробела перед принтом🙈

Comment thread 2_if2.py Outdated

def check_string(first_string, second_string):
if type(first_string) and type(second_string) != str:
if isinstance(first_string, str) and isinstance(second_string, str) is not True:
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 not isinstance(first_string, str) or not isinstance(second_string, str) :

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

Comment thread 3_for.py
item_summ_sold = get_total_sold(product['items_sold'])
items_summ.append({product['product']: item_summ_sold})
return items_summ
return [{product['product']: sum(product['items_sold'])} for product in products]
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Лайк!

Comment thread 5_while2.py Outdated
question = input('Введите вопрос: ')
answer = questions_and_answers.get(question)
if answer:
if not answer is None:
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 not answer is not None: . Да, иногда путаешься во всех этих not is и т.д, со временем привыкнешь)

Comment thread 7_exception2.py Outdated
except TypeError:
return print('Ошибка, передан не верный тип!')
except ValueError:
return print('Ошибка, переданы не верные данные!')
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

print() не нужно возвращать:

  1. print - это функция, которая что-то делает внутри и возвращает None
  2. Она возвращает None потому что любая функция всегда что-то должна возвращать и если внутри функции не указать return, то по дефолту будет возвращаться None
  3. Итого тут есть два варианта: ты либо печатаешь сначала и потом явно возвращаешь None (сели написать просто return без ничего, то функция вернет None тоже), либо возвращаешь строку и принтишь ее вне функции

Comment thread 8_ephem_bot.py

if fn == 'err':
return update.message.reply_text('Допущена ошибка вводе планеты.')

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Я бы рекомендовал третьим аргументом передвать None тут) семантически None - это ничего, как раз подходит сюда

И обрати внимание на название переменных, из них не очень понятно что хранится внутри

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants