Skip to content
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

Open
wants to merge 9 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 3 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
26 changes: 21 additions & 5 deletions 1_if1.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,12 +14,28 @@

"""

def main():
"""
def main(age):

Choose a reason for hiding this comment

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

Давай переназовем функцию для понятности что она делает

if age >= 2 and age < 7:
return "Детский сад"
elif age >= 7 and age < 18:

Choose a reason for hiding this comment

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

Можно ли тут безболезненно заменить

elif age >= 7 and age < 18:

на

elif age < 18:

Почему?

Copy link
Author

@Olga888-56 Olga888-56 Dec 1, 2024

Choose a reason for hiding this comment

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

Проверила, можем)

Choose a reason for hiding this comment

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

А если age = 1? :)

Copy link
Author

Choose a reason for hiding this comment

The 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 ()

Choose a reason for hiding this comment

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

👍

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

if __name__ == "__main__":
main()
#if __name__ == "__main__":
# main()
32 changes: 24 additions & 8 deletions 2_if2.py
Original file line number Diff line number Diff line change
Expand Up @@ -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"))

Choose a reason for hiding this comment

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

👍 отлично!


input()

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

if __name__ == "__main__":
main()
#if __name__ == "__main__":
# main()
42 changes: 33 additions & 9 deletions 3_for.py
Original file line number Diff line number Diff line change
Expand Up @@ -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]},
Expand All @@ -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)

Choose a reason for hiding this comment

The 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()
20 changes: 13 additions & 7 deletions 4_while1.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,11 +11,17 @@


def hello_user():
"""
Замените pass на ваш код
"""
pass
# """
# Замените pass на ваш код
# """
while True:
ask = input('Как дела? ')

Choose a reason for hiding this comment

The 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()
28 changes: 23 additions & 5 deletions 5_while2.py
Original file line number Diff line number Diff line change
Expand Up @@ -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("я не знаю")

Choose a reason for hiding this comment

The 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)
25 changes: 19 additions & 6 deletions 6_exception1.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,10 +11,23 @@
"""

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

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()
hello_user()

input()

#if __name__ == "__main__":
# hello_user()
37 changes: 27 additions & 10 deletions 7_exception2.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)

Choose a reason for hiding this comment

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

Можно такие действия объединять
price = float(abs(price))
Или же надо давать разные имена на разных шагах. На самом деле мы стараемся не экономить на именах иначе создается ситуация в которой в разных местах программы под одним именем разные по логике вещи и
raw_price = abs(price)
price = float(raw_price)

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):

Choose a reason for hiding this comment

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

Сейчас у тебя блок except слишком низко.
В итоге сообщение "Максимальная скидка не должна быть больше 100" ты никогда не увидишь так как его сама же перехватишь и заменишь на "Не сработало приведение типов"

Попробуй переместить аккуратно и проверить что приведение типов обрабатывается корректно и 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"))
105 changes: 61 additions & 44 deletions 8_ephem_bot.py
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")

Choose a reason for hiding this comment

The 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()