-
Notifications
You must be signed in to change notification settings - Fork 469
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
base: master
Are you sure you want to change the base?
Shestakas DZ 1 #151
Changes from all commits
c1c78f3
24d573d
2871e31
95ce02c
2832226
bffb0aa
7bb6aff
04b0f82
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,3 +1,4 @@ | ||
settings.py | ||
# Byte-compiled / optimized / DLL files | ||
__pycache__/ | ||
*.py[cod] | ||
|
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -13,13 +13,33 @@ | |
* Вывести содержимое переменной на экран | ||
|
||
""" | ||
def prof_by_age(age): | ||
if age <= 6: | ||
return 'учиться в детском саду' | ||
elif age < 18: | ||
return 'учится в школе' | ||
else: | ||
return 'учиться в ВУЗе или работать' | ||
|
||
def main(): | ||
""" | ||
Эта функция вызывается автоматически при запуске скрипта в консоли | ||
В ней надо заменить pass на ваш код | ||
""" | ||
pass | ||
while True: | ||
try: | ||
age = int(input('----Для выхода введите 0 ----\nВведите ваш возраст: ')) | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Здорово что прикрутил обработку исключений, но в таком случае внутри try блока надо оставить только ту строчку в которой у тебя это исключение может возникнуть. (age = int(input()). |
||
if age == 0: | ||
break | ||
else: | ||
prof = prof_by_age(age) | ||
print(f"По возрасту вам положено {prof}") | ||
except ValueError: | ||
print('Введите ваш возраст цифрами!') | ||
continue | ||
|
||
|
||
""" | ||
Эта функция вызывается автоматически при запуске скрипта в консоли | ||
В ней надо заменить pass на ваш код | ||
""" | ||
#pass | ||
|
||
if __name__ == "__main__": | ||
main() |
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -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: | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe 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() |
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -11,10 +11,17 @@ | |
|
||
|
||
def hello_user(): | ||
""" | ||
Замените pass на ваш код | ||
""" | ||
pass | ||
while True: | ||
try: | ||
whatsup = input('Как дела?:') | ||
if whatsup.lower() == 'хорошо': | ||
break | ||
else: | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Здесь тоже блок else никак не влияет на выполнение кода |
||
continue | ||
except KeyboardInterrupt: | ||
break | ||
|
||
|
||
|
||
|
||
if __name__ == "__main__": | ||
|
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,3 +1,4 @@ | ||
import urllib.request | ||
""" | ||
|
||
Домашнее задание №1 | ||
|
@@ -14,14 +15,27 @@ | |
Программа: Программирую | ||
|
||
""" | ||
|
||
questions_and_answers = {} | ||
def external_ip(): | ||
external_ip = str(urllib.request.urlopen('https://ident.me').read().decode('utf8')) #Обработать try/except | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Сложный путь сделать запрос 🙂 |
||
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()) | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Если используешь f-строку то и запятую сразу в нее перенести стоит. |
||
|
||
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) |
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -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') | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe 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")) | ||
|
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -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' | ||
|
@@ -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': | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe 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() | ||
|
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Это такой пограничный случай. Если бы веток было бы больше, я бы однозначно рекомендовал использовать один return на функцию.
Есть два метода этого достичь: