Skip to content

Shestakas DZ 1 #151

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

Open
wants to merge 8 commits 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
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
settings.py
# Byte-compiled / optimized / DLL files
__pycache__/
*.py[cod]
Expand Down
30 changes: 25 additions & 5 deletions 1_if1.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,13 +13,33 @@
* Вывести содержимое переменной на экран

"""
def prof_by_age(age):
if age <= 6:
return 'учиться в детском саду'
Copy link

Choose a reason for hiding this comment

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

Это такой пограничный случай. Если бы веток было бы больше, я бы однозначно рекомендовал использовать один return на функцию.
Есть два метода этого достичь:

  1. Либо в функции объявляешь переменную rv (сокращенно от return_value) и присваиваешь ей значение в ветках, а в конце просто return rv.
  2. Либо можно использовать табличную функцию: положить возвращаемые значения в словарь и по ключу доставать. Но тут сложно будет с ключом рабоатать, лучше первый вариант взять.

elif age < 18:
return 'учится в школе'
else:
return 'учиться в ВУЗе или работать'

def main():
"""
Эта функция вызывается автоматически при запуске скрипта в консоли
В ней надо заменить pass на ваш код
"""
pass
while True:
try:
age = int(input('----Для выхода введите 0 ----\nВведите ваш возраст: '))
Copy link

Choose a reason for hiding this comment

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

Здорово что прикрутил обработку исключений, но в таком случае внутри try блока надо оставить только ту строчку в которой у тебя это исключение может возникнуть. (age = int(input()).
Остальное вынести после except.

if age == 0:
break
else:
prof = prof_by_age(age)
print(f"По возрасту вам положено {prof}")
except ValueError:
print('Введите ваш возраст цифрами!')
continue


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

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 @@ -14,13 +14,34 @@
и выводя на экран результаты

"""
def two_strings(one, two):
a = isinstance(one, str)
b = isinstance(two, str)
if a and b:
if one == two:
return 1
elif two == 'learn':
return 3
elif len(one) > len(two):
return 2
else:
Copy link

Choose a reason for hiding this comment

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

else: pass не несет никакого смысла тут, можно убрать и код не изменится (только станет проще)

pass
else:
return 0


def main():
print(two_strings('hfp','hfp'))
print(two_strings('hfpsdf','hfp'))
print(two_strings('lkj',1))
print(two_strings(4,4))
print(two_strings('sdfsfds','learn'))

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

if __name__ == "__main__":
main()
35 changes: 33 additions & 2 deletions 3_for.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,23 +5,54 @@
Цикл for: Продажи товаров

* Дан список словарей с данными по колличеству проданных телефонов
[
"""
lst_phone = [
{'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 sum_list_prod(lst):
for product in lst:
print('Cуммарное количество продаж ',product['product'],'- ',sum(product['items_sold']))

def average_lst(lst):
for product in lst:
avrge_lst = round((sum(product['items_sold'])/len(product['items_sold'])),2)
print('Cреднее количество продаж ', product['product'],'- ',avrge_lst)

def sum_sold(lst):
s = 0
for product in lst:
a = sum(product['items_sold'])
s += a
print('Cуммарное количество продаж всех товаров ', s)

def avrge_sold(lst):
count = 0
a = 0
for i in lst:
avrge = round((sum(i['items_sold'])/len(i['items_sold'])),2)
a += avrge
count += 1
print('Cреднее количество продаж всех товаров ', a/count)

def main():
sum_list_prod(lst_phone)
average_lst(lst_phone)
sum_sold(lst_phone)
avrge_sold(lst_phone)

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

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


def hello_user():
"""
Замените pass на ваш код
"""
pass
while True:
try:
whatsup = input('Как дела?:')
if whatsup.lower() == 'хорошо':
break
else:
Copy link

Choose a reason for hiding this comment

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

Здесь тоже блок else никак не влияет на выполнение кода

continue
except KeyboardInterrupt:
break




if __name__ == "__main__":
Expand Down
26 changes: 20 additions & 6 deletions 5_while2.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import urllib.request
"""

Домашнее задание №1
Expand All @@ -14,14 +15,27 @@
Программа: Программирую

"""

questions_and_answers = {}
def external_ip():
external_ip = str(urllib.request.urlopen('https://ident.me').read().decode('utf8')) #Обработать try/except
Copy link

Choose a reason for hiding this comment

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

Сложный путь сделать запрос 🙂
import requests
requests.get('https://ident.me').text

return external_ip
ext_ip = external_ip()
questions_and_answers = {"Как дела?": "Хорошо!", "Что делаешь?": "Программирую", "Какой у тебя ip?": f'{ext_ip}'}
quest = ''.join(f'{k}'+',' for k in questions_and_answers.keys())
Copy link

Choose a reason for hiding this comment

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

Если используешь f-строку то и запятую сразу в нее перенести стоит.
А вообще тут даже так можно:
','.join(questions_and_answers.keys())


def ask_user(answers_dict):
"""
Замените pass на ваш код
"""
pass
q = f'Возможные вопросы:\n{quest}'
print(q)
while True:
try:
questions = (input('Введите вопрос:')).lower()
a = questions_and_answers.get(questions.capitalize())
if a:
print(a)
else:
print(f'----Введите вопрос из списка!----\n{q}\nЧтобы выйти, нажмите Ctrl+C')
continue
except KeyboardInterrupt:
break

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

def hello_user():
"""
Замените pass на ваш код
"""
pass
while True:
try:
whatsup = input('Как дела?:')
if whatsup.lower() == 'хорошо':
break
else:
continue
except KeyboardInterrupt:
print('\nПока!')
break


if __name__ == "__main__":
hello_user()
21 changes: 15 additions & 6 deletions 7_exception2.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,16 +13,25 @@

"""

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

def discounted(price, discount, max_discount=20):
try:
price_float = float(price)
discount_float = float(discount)
max_discount_int = int(max_discount)
return (price_float, discount_float, max_discount_int)
except TypeError:
return ('TypeError')
Copy link

Choose a reason for hiding this comment

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

Скобки лишние, это просто строка. (Если хочешь тупл из одного элемента, надо запятую добавить перед закрывающей скобкой)

except ValueError:
return ('ValueError')



if __name__ == "__main__":
print(discounted(100, 2))
print(discounted(100, "3"))
print(discounted("100", "4.5"))
print(discounted("five", 5))
print(discounted("сто", "десять"))
print(discounted(100.0, 5, "10"))
print(discounted([100.0,], 5, "10"))

40 changes: 33 additions & 7 deletions 8_ephem_bot.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,22 +13,23 @@

"""
import logging

import ephem
from telegram.ext import Updater, CommandHandler, MessageHandler, Filters
import settings
from datetime import date

logging.basicConfig(format='%(name)s - %(levelname)s - %(message)s',
level=logging.INFO,
filename='bot.log')


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

} """

def greet_user(update, context):
text = 'Вызван /start'
Expand All @@ -39,15 +40,40 @@ def greet_user(update, context):
def talk_to_me(update, context):
user_text = update.message.text
print(user_text)
update.message.reply_text(text)

update.message.reply_text(user_text)

def planet(update, context):
dt_now = date.today()
b = update.message.text #(update['message'])['text']
d = ((b.split())[1]).lower()
if d == 'mars':
Copy link

Choose a reason for hiding this comment

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

Я бы предложил это все сложить в словарь и вытаскивать из словаря. Тогда когда откроют новую планету не придется менять логику кода, а просто добавить еще один объект в словарь.

m = ephem.Mars(dt_now.year)
elif d == 'mercury':
m = ephem.Mercury(dt_now.year)
elif d == 'venus':
m = ephem.Venus(dt_now.year)
elif d == 'jupiter':
m = ephem.Jupiter(dt_now.year)
elif d == 'saturn':
m = ephem.Saturn(dt_now.year)
elif d == 'uranus':
m = ephem.Uranus(dt_now.year)
elif d == 'neptune':
m = ephem.Neptune(dt_now.year)
elif d == 'pluto':
m = ephem.Pluto(dt_now.year)
else:
update.message.reply_text('Не знаю такую планету')
update.message.reply_text(ephem.constellation(m))

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

dp = mybot.dispatcher
dp.add_handler(CommandHandler("start", greet_user))
dp.add_handler(CommandHandler("planet", planet))
dp.add_handler(MessageHandler(Filters.text, talk_to_me))


mybot.start_polling()
mybot.idle()
Expand Down