-
Notifications
You must be signed in to change notification settings - Fork 446
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
Homework_1_Glazunova #173
base: master
Are you sure you want to change the base?
Homework_1_Glazunova #173
Changes from 3 commits
9d3f5d5
4385309
71d8d59
8b6721f
f4bdc48
4de17a5
4cc817c
e8dc5bc
51535d8
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 |
---|---|---|
|
@@ -14,12 +14,28 @@ | |
|
||
""" | ||
|
||
def main(): | ||
""" | ||
def main(age): | ||
if age >= 2 and age < 7: | ||
return "Детский сад" | ||
elif age >= 7 and age < 18: | ||
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. Можно ли тут безболезненно заменить
на
Почему? 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. Проверила, можем) 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. А если age = 1? :) 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. Здесь затупила. Нет, получается, не можем. Работать будет, но криво. Условия проверяются последовательно. 1>=2 - не верно, поэтому в садик не попадаем, зато однозначно <18, поэтому школа как раз подходит)) исправила, как было. |
||
return "Школа" | ||
elif age >= 18 and age < 23: | ||
return "вуз" | ||
elif age >= 23 and age < 60: | ||
return "Работа" | ||
else: | ||
return "Старый или малый)" | ||
|
||
age_in = input("Введите ваш возраст: ") | ||
age = int(age_in) | ||
activity = main(age) | ||
print(f"Ваше занятие по возрасту {activity}") | ||
input () | ||
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. 👍 |
||
""" | ||
Эта функция вызывается автоматически при запуске скрипта в консоли | ||
В ней надо заменить pass на ваш код | ||
""" | ||
pass | ||
# pass | ||
|
||
if __name__ == "__main__": | ||
main() | ||
#if __name__ == "__main__": | ||
# main() |
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -15,12 +15,28 @@ | |
|
||
""" | ||
|
||
def main(): | ||
""" | ||
Эта функция вызывается автоматически при запуске скрипта в консоли | ||
В ней надо заменить pass на ваш код | ||
""" | ||
pass | ||
def main(str1,str2): | ||
if not isinstance(str1, str) or not isinstance(str2, str): | ||
return 0 | ||
if str1 == str2: | ||
return 1 | ||
if len(str1) > len(str2): | ||
return 2 | ||
if str1 != str2 and str2 == "learn": | ||
return 3 | ||
|
||
print(main ("text","123")) | ||
print(main("text","text")) | ||
print(main("texttexttext", "text")) | ||
print(main("text","learn")) | ||
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. 👍 отлично! |
||
|
||
input() | ||
|
||
# """ | ||
# Эта функция вызывается автоматически при запуске скрипта в консоли | ||
# В ней надо заменить pass на ваш код | ||
# """ | ||
# pass | ||
|
||
if __name__ == "__main__": | ||
main() | ||
#if __name__ == "__main__": | ||
# main() |
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -5,7 +5,7 @@ | |
Цикл for: Продажи товаров | ||
|
||
* Дан список словарей с данными по колличеству проданных телефонов | ||
[ | ||
[ | ||
{'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]}, | ||
|
@@ -15,13 +15,37 @@ | |
* Посчитать и вывести суммарное количество продаж всех товаров | ||
* Посчитать и вывести среднее количество продаж всех товаров | ||
""" | ||
data = [ | ||
{'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(data): | ||
all_sales = 0 | ||
all_products = len(data) | ||
for phone in data: | ||
product = phone['product'] | ||
sales = phone['items_sold'] | ||
total_sales = sum(sales) | ||
avg_sales = round(total_sales / len(sales), 2) | ||
|
||
print(f'телефон: {product} суммарное колиичество продаж: {total_sales}, среднее количество продаж: {avg_sales}') | ||
|
||
all_sales += total_sales | ||
|
||
avg_all_sales = round(all_sales / all_products, 2) | ||
print(f'суммарное количество продаж {all_sales}') | ||
print(f'среднее количество продаж {avg_all_sales}') | ||
|
||
main(data) | ||
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. Супер! Аккуратное выполнение |
||
|
||
def main(): | ||
""" | ||
Эта функция вызывается автоматически при запуске скрипта в консоли | ||
В ней надо заменить pass на ваш код | ||
""" | ||
pass | ||
input() | ||
|
||
#""" | ||
#Эта функция вызывается автоматически при запуске скрипта в консоли | ||
#В ней надо заменить pass на ваш код | ||
#""" | ||
#pass | ||
|
||
if __name__ == "__main__": | ||
main() | ||
#if __name__ == "__main__": | ||
#main() |
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -11,11 +11,17 @@ | |
|
||
|
||
def hello_user(): | ||
""" | ||
Замените pass на ваш код | ||
""" | ||
pass | ||
# """ | ||
# Замените pass на ваш код | ||
# """ | ||
while True: | ||
ask = input('Как дела? ') | ||
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. Кажется имя переменной ask не отражает то что в ней лежит. Как ты можешь описать что в этой переменной лежит(можно сначала на русском ответить)) |
||
if ask == ('хорошо'): | ||
break | ||
else: | ||
print('Как дела? ') | ||
hello_user() | ||
|
||
if __name__ == "__main__": | ||
hello_user() | ||
input() | ||
#if __name__ == "__main__": | ||
# hello_user() |
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -15,13 +15,31 @@ | |
|
||
""" | ||
|
||
questions_and_answers = {} | ||
questions_and_answers = { | ||
"как дела?": "хорошо", | ||
"Чем занимаешься?": "Программирую", | ||
"Как тебя зовут?": "Оля", | ||
"Сколько тебе лет?": "38", | ||
"Ты умеешь программировать?": "нет, но хочу научиться", | ||
"какой язык ты изучаешь?": "python" | ||
} | ||
|
||
def ask_user(answers_dict): | ||
def ask_user(): | ||
""" | ||
Замените pass на ваш код | ||
""" | ||
pass | ||
|
||
if __name__ == "__main__": | ||
ask_user(questions_and_answers) | ||
question = input('Введите вопрос: ') | ||
answer = questions_and_answers.get(question) | ||
if question in questions_and_answers: | ||
print(answer) | ||
else: | ||
print("я не знаю") | ||
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. Да, это рабочий вариант. Давай для тренировки избавимся от if-else и попробуем переписать через .get(...) |
||
|
||
ask_user() | ||
|
||
input() | ||
|
||
|
||
#if __name__ == "__main__": | ||
# ask_user(questions_and_answers) |
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -11,10 +11,23 @@ | |
""" | ||
|
||
def hello_user(): | ||
""" | ||
Замените pass на ваш код | ||
""" | ||
pass | ||
# """ | ||
# Замените pass на ваш код | ||
# """ | ||
try: | ||
while True: | ||
ask = input('Как дела? ') | ||
if ask == ('хорошо'): | ||
break | ||
else: | ||
print('Как дела? ') | ||
except KeyboardInterrupt: | ||
print('Пока!') | ||
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. 👍 |
||
|
||
|
||
if __name__ == "__main__": | ||
hello_user() | ||
hello_user() | ||
|
||
input() | ||
|
||
#if __name__ == "__main__": | ||
# hello_user() |
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -13,16 +13,33 @@ | |
|
||
""" | ||
|
||
def discounted(price, discount, max_discount=20) | ||
def discounted(price, discount, max_discount=20): | ||
""" | ||
Замените pass на ваш код | ||
""" | ||
pass | ||
|
||
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")) | ||
try: | ||
price = abs(price) | ||
price = float(price) | ||
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. Можно такие действия объединять |
||
discount = abs(discount) | ||
discount = float(discount) | ||
max_discount = abs(max_discount) | ||
max_discount = int(max_discount) | ||
if max_discount >= 100: | ||
raise ValueError("Максимальная скидка не должна быть больше 100") | ||
if discount >= max_discount: | ||
price_with_discount = price | ||
else: | ||
price_with_discount = price - (price * discount / 100) | ||
return price_with_discount | ||
except(ValueError, 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 слишком низко. Попробуй переместить аккуратно и проверить что приведение типов обрабатывается корректно и max_discount >=100 выдавал свою ошибку |
||
print("Не сработало приведение типов") | ||
|
||
input() | ||
|
||
#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")) |
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,57 +1,74 @@ | ||
""" | ||
Домашнее задание №1 | ||
|
||
Использование библиотек: ephem | ||
|
||
* Установите модуль ephem | ||
* Добавьте в бота команду /planet, которая будет принимать на вход | ||
название планеты на английском, например /planet Mars | ||
* В функции-обработчике команды из update.message.text получите | ||
название планеты (подсказка: используйте .split()) | ||
* При помощи условного оператора if и ephem.constellation научите | ||
бота отвечать, в каком созвездии сегодня находится планета. | ||
|
||
""" | ||
import logging | ||
|
||
from telegram.ext import Updater, CommandHandler, MessageHandler, Filters | ||
|
||
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' | ||
} | ||
} | ||
|
||
|
||
def greet_user(update, context): | ||
text = 'Вызван /start' | ||
print(text) | ||
update.message.reply_text(text) | ||
|
||
|
||
def talk_to_me(update, context): | ||
user_text = update.message.text | ||
print(user_text) | ||
update.message.reply_text(text) | ||
print("Вызван /start") | ||
update.message.reply_text("Привет!") | ||
|
||
#def talk_to_me(update, context): | ||
# text = update.message.text | ||
# print(text) | ||
# update.message.reply_text(text) | ||
|
||
def planets(update, context): | ||
import ephem | ||
print("Вызвана функция planets") | ||
|
||
# planet = update.message.text | ||
# planet = ephem.Mars('2024/11/29') | ||
# update.message.reply_text("Планета {planet}") | ||
# print(planet) | ||
# const = ephem.constellation(planet) | ||
# print(const) | ||
# update.message.reply_text(const) | ||
try: | ||
# planet = ephem.Mars('2024/11/29') | ||
planet = update.message.text | ||
planet_name = planet.split() | ||
print(planet_name) | ||
name = planet_name[1] | ||
Mars = ephem.Mars("2024/11/30") | ||
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. А давай заменим "2024/11/30" на переменную отвечающую за текущую дату |
||
# Earth = ephem.Earth("2024/11/30") | ||
Uranus = ephem.Uranus("2024/11/30") | ||
Jupiter = ephem.Jupiter("2024/11/30") | ||
Neptune = ephem.Neptune("2024/11/30") | ||
Venus = ephem.Venus("2024/11/30") | ||
Pluto = ephem.Pluto("2024/11/30") | ||
Mercury = ephem.Mercury("2024/11/30") | ||
if name == "Mars": | ||
const = ephem.constellation(Mars) | ||
elif name == "Jupiter": | ||
const = ephem.constellation(Jupiter) | ||
elif name == "Uranus": | ||
const = ephem.constellation(Uranus) | ||
elif name == "Neptune": | ||
const = ephem.constellation(Neptune) | ||
elif name == "Venus": | ||
const = ephem.constellation(Venus) | ||
elif name == "Pluto": | ||
const = ephem.constellation(Pluto) | ||
elif name == "Mercury": | ||
const = ephem.constellation(Mercury) | ||
else: | ||
# const = ephem.constellation(Earth) | ||
print("Не знаю такую планету") | ||
print(const) | ||
update.message.reply_text(const) | ||
except Exception as e: | ||
print(e) | ||
|
||
|
||
def main(): | ||
mybot = Updater("КЛЮЧ, КОТОРЫЙ НАМ ВЫДАЛ BotFather", request_kwargs=PROXY, use_context=True) | ||
|
||
mybot = Updater("7834567751:AAGfqPXRFL3-GDBOH0IcORp7DSIzyJ_W-Jw", use_context = True) | ||
|
||
dp = mybot.dispatcher | ||
dp.add_handler(CommandHandler("start", greet_user)) | ||
dp.add_handler(MessageHandler(Filters.text, talk_to_me)) | ||
|
||
dp.add_handler(CommandHandler("planet", planets)) | ||
# dp.add_handler(MessageHandler(Filters.text, talk_to_me)) | ||
dp.add_handler(MessageHandler(Filters.text, planets)) | ||
mybot.start_polling() | ||
mybot.idle() | ||
|
||
main() | ||
|
||
if __name__ == "__main__": | ||
main() | ||
input() |
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.
Давай переназовем функцию для понятности что она делает