Skip to content
Open
3 changes: 3 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -121,3 +121,6 @@ dmypy.json

# Pyre type checker
.pyre/

# Settings
settings.py
18 changes: 13 additions & 5 deletions 1_if1.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,12 +14,20 @@

"""


def activity_by_age(age):
if 0 <= age <= 7:
return 'Вы в детском садике'
elif 7 < age <= 17:
return 'Вы учитесь в школе'
else:
return 'Вы в ВУЗе или работаете'


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

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

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

Copy link
Copy Markdown
Author

@Maksimous777 Maksimous777 Jun 2, 2023

Choose a reason for hiding this comment

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

вынес) a1c78dc


if __name__ == "__main__":
main()
28 changes: 26 additions & 2 deletions 2_if2.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,12 +15,36 @@

"""


def check_strings(str1, str2):
if not isinstance(str1, str) or not isinstance(str2, str):
return 0

str1 = str1.strip().lower()
str2 = str2.strip().lower()

if str1 == str2:
return 1
elif str2 == 'learn':
return 3
elif len(str1) > len(str2):
return 2
else:
return 'Вот это поворот'


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


print(check_strings('hello', 777)) # 0
print(check_strings('hello', 'hello')) # 1
print(check_strings('hello', 'hell')) # 2
print(check_strings('hi', 'learn')) # 3
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

А можешь придумать тест из 2 строк, в котором выведется на экран что-то кроме 0-1-2-3
Это очень полезное упражнение :)

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

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

4d6f8c8 Приделал, сразу потребовался else :)

print(check_strings('hi', 'learning'))


if __name__ == "__main__":
main()
33 changes: 31 additions & 2 deletions 3_for.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,12 +16,41 @@
* Посчитать и вывести среднее количество продаж всех товаров
"""


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


phones = [
{'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 count_sum(items_list):
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

items_sum = 0
for item in items_list:
items_sum += item
return items_sum

phones_sum = 0
for phone in phones:
phone['sum_sold'] = count_sum(phone['items_sold'])
phone_sold_avg = int(phone['sum_sold'] / len(phone['items_sold']))
phones_sum += phone['sum_sold']
print(
f"Суммарный объем продаж {phone['product']}: {phone['sum_sold']}")
print(
f"Средний объем продаж {phone['product']}: {phone_sold_avg}", end='\n\n')
print(f"Всего телефонов продано: {phones_sum}")
phones_avg = int(phones_sum / len(phones))
print(f"В среднем телефонов продано: {phones_avg}")


if __name__ == "__main__":
main()
6 changes: 4 additions & 2 deletions 4_while1.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,8 +14,10 @@ def hello_user():
"""
Замените pass на ваш код
"""
pass
while True:
if input('Как дела? \n') == 'Хорошо':
break

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 __name__ == "__main__":
hello_user()
13 changes: 11 additions & 2 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 = {
'Как дела': 'Хорошо!',
'Что делаешь': 'Программирую',
'И все?': 'Ну, почти',
'Ну и лошара': 'Да пошел ты'
}

def ask_user(answers_dict):
"""
Замените pass на ваш код
"""
pass
print('Введите вопрос: ')
while True:
question = input('Пользователь: ')
if answers_dict.get(question):
print(f"Программа: {answers_dict.get(question, '')}", end='\n\n')
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 __name__ == "__main__":
ask_user(questions_and_answers)
7 changes: 6 additions & 1 deletion 6_exception1.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,12 @@ def hello_user():
"""
Замените pass на ваш код
"""
pass
try:
while True:
if input('Как дела? \n') == 'Хорошо':
break
except KeyboardInterrupt:
print('Пока')

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

"""

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

try:
price = abs(float(price))
except (ValueError, TypeError):
return 'Цена должна быть числом'
try:
discount = abs(float(discount))
except (ValueError, TypeError):
return 'Размер скидки должен быть числом'
try:
max_discount = abs(int(max_discount))
except (ValueError, TypeError):
return 'Максимальная скидка должна быть числом'

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"))
print(discounted("five", 5))
print(discounted("сто", "десять"))
print(discounted(100.0, 5, "10"))
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"))
50 changes: 41 additions & 9 deletions 8_ephem_bot.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,20 +14,22 @@
"""
import logging

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

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


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


def greet_user(update, context):
Expand All @@ -39,14 +41,44 @@ 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 get_constellation(update, context):
user_input = context.args[0].capitalize()
planet_name = {
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

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

Copy link
Copy Markdown
Author

@Maksimous777 Maksimous777 Jun 2, 2023

Choose a reason for hiding this comment

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

исправил 6b30a1d

'Mercury': ephem.Mercury(),
'Venus': ephem.Venus(),
'Mars': ephem.Mars(),
'Jupiter': ephem.Jupiter(),
'Saturn': ephem.Saturn(),
'Uranus': ephem.Uranus(),
'Neptune': ephem.Neptune(),
'Pluto': ephem.Pluto()
}

try:
planet_name[user_input]
except KeyError:
if user_input == 'Earth':
update.message.reply_text('Earth is not in any constellation')
else:
update.message.reply_text(f'{user_input} is not a planet of solar system')

planet_name[user_input].compute()
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

А ты тестировал свою программу с неправильными планетами? Мне кажется что надо проверить ;)

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

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

Да, все работает)
image

constellation_name = ephem.constellation(planet_name[user_input])[1]
# print(constellation_name, constellation_name[1])
# constellation_name = update.message.text.split()
print(f'{planet_name[user_input].name} is currently in the constellation of {constellation_name}')
update.message.reply_text(f'{planet_name[user_input].name} is currently in the constellation of {constellation_name}')



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", get_constellation))
dp.add_handler(MessageHandler(Filters.text, talk_to_me))

mybot.start_polling()
Expand Down