Мой первый коммит
This commit is contained in:
commit
810e42437e
1
.gitignore
vendored
Normal file
1
.gitignore
vendored
Normal file
@ -0,0 +1 @@
|
||||
.env
|
||||
3
1_2.py
Normal file
3
1_2.py
Normal file
@ -0,0 +1,3 @@
|
||||
rus_publish_year='2014'
|
||||
var1 = rus_publish_year
|
||||
print(var1)
|
||||
8
1_3.py
Normal file
8
1_3.py
Normal file
@ -0,0 +1,8 @@
|
||||
# Какой тип данных содержат переменные book_title и rus_publish_year?
|
||||
# Проверьте свое предположение, используя функцию `type()` и
|
||||
# выведите типы переменных на экран с помощью функции print().
|
||||
|
||||
rus_publish_year = 2014
|
||||
print(type(rus_publish_year))
|
||||
book_title = "Щегол"
|
||||
print(type(book_title))
|
||||
6
1_4.py
Normal file
6
1_4.py
Normal file
@ -0,0 +1,6 @@
|
||||
# Преобразуйте тип переменной `book_price` в целое число,
|
||||
# используя функцию `int()` и выведите на экран значение и тип
|
||||
# преобразованной переменной.
|
||||
|
||||
book_price = int(25)
|
||||
print(book_price)
|
||||
17
2_1.py
Normal file
17
2_1.py
Normal file
@ -0,0 +1,17 @@
|
||||
# Посчитайте разницу стоимости книги на ozon
|
||||
# (`ozon_price`) и wildberries (`wb_price`).
|
||||
# Результат сохраните в переменной `delta_price`.
|
||||
# Выведите на экран её значение.
|
||||
|
||||
ozon_price = 1058.2
|
||||
wb_price = 956
|
||||
|
||||
delta_price = ozon_price - wb_price
|
||||
print(delta_price)
|
||||
|
||||
|
||||
#далее -- округлите результат вычислений `delta_price`
|
||||
# до первого знака после запятой,
|
||||
# используя функцию `round()` и другие известные вам
|
||||
# способы. Выведите результат на экран. Сравните разные способы
|
||||
# округления
|
||||
23
2_2.py
Normal file
23
2_2.py
Normal file
@ -0,0 +1,23 @@
|
||||
# Перед вами загадка сфинкса из турнира Кубок Огня:
|
||||
|
||||
# Мой первый слог проворней всех слывёт по праву
|
||||
# Он очень быстр на руку, ногу и расправу;
|
||||
# Второй мой слог есть плод окружности решений
|
||||
# Её с диаметром законных отношений.
|
||||
# Мой третий слог — абстрактно названный мужчина
|
||||
# Ни цвета кожи, ни фамилии, ни чина.
|
||||
# Сложив их вместе, существо ты образуешь,
|
||||
# Какое ты скорей умрёшь, чем поцелуешь.
|
||||
|
||||
# Сохраните ее в переменной `sphinx_riddle` в виде многострочной строки.
|
||||
# Выведите содержимое переменной на экран.
|
||||
# Сохраните ее в переменной `` в виде многострочной строки.
|
||||
sphinx_riddle = """" Мой первый слог проворней всех слывёт по праву
|
||||
# Он очень быстр на руку, ногу и расправу;
|
||||
# Второй мой слог есть плод окружности решений
|
||||
# Её с диаметром законных отношений.
|
||||
# Мой третий слог — абстрактно названный мужчина
|
||||
# Ни цвета кожи, ни фамилии, ни чина.
|
||||
# Сложив их вместе, существо ты образуешь,
|
||||
# Какое ты скорей умрёшь, чем поцелуешь. """
|
||||
print(sphinx_riddle)
|
||||
17
calc_test.py
Normal file
17
calc_test.py
Normal file
@ -0,0 +1,17 @@
|
||||
print("Доступныен действия в калькуляторе:*(умножение),-(минус),+(плюс)")
|
||||
print("Обратите внимание,что наш калькулятор обращает внимание только на знаки + - и * , так что писать все остальное бесполезно")
|
||||
|
||||
user_input1 = int(input("Введите сюда нужное кол-во символов для использования: "))
|
||||
|
||||
user_num_array = []
|
||||
|
||||
for i in range(user_input1):
|
||||
num = float(input())
|
||||
user_num_array.append(num)
|
||||
|
||||
print("Результат(числа):")
|
||||
for num in user_num_array:
|
||||
print(num)
|
||||
|
||||
|
||||
|
||||
8
eval_test.py
Normal file
8
eval_test.py
Normal file
@ -0,0 +1,8 @@
|
||||
expression = ""
|
||||
|
||||
try:
|
||||
result = eval(expression)
|
||||
print(result)
|
||||
except:
|
||||
print("Случилась ошибка")
|
||||
|
||||
45
functions.py
Normal file
45
functions.py
Normal file
@ -0,0 +1,45 @@
|
||||
user_input1 = int(input("Введите сюда нужное кол-во символов для использования: "))
|
||||
print("Доступныен действия в калькуляторе:*(умножение),-(минус),+(плюс)")
|
||||
print("Обратите внимание,что наш калькулятор обращает внимание только на знаки + - и * , так что писать все остальное бесполезно")
|
||||
|
||||
nums = []
|
||||
|
||||
for i in range(user_input1):
|
||||
user_input2 = int(input("Введи сюда число: "))
|
||||
nums.append(user_input2)
|
||||
|
||||
print(nums)
|
||||
|
||||
# print(my_function(42, 42))
|
||||
|
||||
def Vitya(nums):
|
||||
num = nums[0]
|
||||
for num in nums:
|
||||
num = num - num
|
||||
return num
|
||||
|
||||
# print(my_friends(98, 1000))
|
||||
|
||||
def my_cat(nums):
|
||||
num = 1
|
||||
for i in range(len(nums) ):
|
||||
num *= nums[i]
|
||||
return num
|
||||
# print(my_cat(10, 9))
|
||||
|
||||
|
||||
user_input0 = input("Введите операцию: ")
|
||||
|
||||
|
||||
|
||||
if user_input0 == "*":
|
||||
print(my_cat(nums))
|
||||
|
||||
elif user_input0 == "-":
|
||||
print(Vitya(nums))
|
||||
|
||||
elif user_input0 == "+":
|
||||
print(sum(nums))
|
||||
else:
|
||||
print("Вы ввели либо ничего,либо какую то ересь ненужную,не пытайтесь выставить нас дураками" )
|
||||
|
||||
135
Бот.py
Normal file
135
Бот.py
Normal file
@ -0,0 +1,135 @@
|
||||
from dotenv import load_dotenv
|
||||
import os
|
||||
|
||||
load_dotenv() # take environment variables
|
||||
|
||||
# Code of your application, which uses environment variables (e.g. from `os.environ` or
|
||||
# `os.getenv`) as if they came from the actual environment.
|
||||
# Code of your application, which uses environment variables (e.g. from `os.environ` or
|
||||
# `os.getenv`) as if they came from the actual environment.
|
||||
|
||||
|
||||
|
||||
#!/usr/bin/env python
|
||||
# pylint: disable=unused-argument
|
||||
# This program is dedicated to the public domain under the CC0 license.
|
||||
|
||||
"""
|
||||
Simple Bot to reply to Telegram messages.
|
||||
|
||||
First, a few handler functions are defined. Then, those functions are passed to
|
||||
the Application and registered at their respective places.
|
||||
Then, the bot is started and runs until we press Ctrl-C on the command line.
|
||||
|
||||
Usage:
|
||||
Basic Echobot example, repeats messages.
|
||||
Press Ctrl-C on the command line or send a signal to the process to stop the
|
||||
bot.
|
||||
"""
|
||||
|
||||
import logging
|
||||
|
||||
from telegram import ForceReply, InlineKeyboardButton, InlineKeyboardMarkup, Update
|
||||
from telegram.ext import Application, CommandHandler, ContextTypes, MessageHandler, filters, CallbackQueryHandler
|
||||
|
||||
# Enable logging
|
||||
logging.basicConfig(
|
||||
format="%(asctime)s - %(name)s - %(levelname)s - %(message)s", level=logging.INFO
|
||||
)
|
||||
# set higher logging level for httpx to avoid all GET and POST requests being logged
|
||||
logging.getLogger("httpx").setLevel(logging.WARNING)
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
keyboard = [
|
||||
[InlineKeyboardButton(text ="9", callback_data = "9"), InlineKeyboardButton(text = "8", callback_data="8"), InlineKeyboardButton(text ="7", callback_data="7"),InlineKeyboardButton(text ="-", callback_data="-")],
|
||||
[InlineKeyboardButton(text ="6", callback_data ="6"), InlineKeyboardButton(text = "5", callback_data="5"), InlineKeyboardButton(text ="4", callback_data="4"),InlineKeyboardButton(text ="+", callback_data="+")],
|
||||
[InlineKeyboardButton(text ="3", callback_data="3"), InlineKeyboardButton(text ="2", callback_data ="2"), InlineKeyboardButton(text = "1", callback_data="1"),InlineKeyboardButton(text ="c", callback_data="c")],
|
||||
[InlineKeyboardButton(text ="0", callback_data="0"),InlineKeyboardButton(text ="=", callback_data="=")],
|
||||
[InlineKeyboardButton(text ="/", callback_data="/"),InlineKeyboardButton(text ="*", callback_data="*"),InlineKeyboardButton(text =".", callback_data=".")],
|
||||
]
|
||||
|
||||
# Define a few command handlers. These usually take the two arguments update and
|
||||
# context.
|
||||
async def start(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
|
||||
"""Send a message when the command /start is issued."""
|
||||
await update.message.reply_text(
|
||||
rf"Здраствуйте, {update.effective_user.full_name}!, начните считать: ", reply_markup=InlineKeyboardMarkup(keyboard))
|
||||
|
||||
|
||||
# keyboard = InlineKeyboardMarkup(keyboard)
|
||||
|
||||
async def help_command(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
|
||||
"""Send a message when the command /help is issued."""
|
||||
await update.message.reply_text("Все команды:/start - перезапуск/запуск системы,/help - помощь в командах.")
|
||||
|
||||
async def calc(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
|
||||
query = update.callback_query
|
||||
await query.answer()
|
||||
|
||||
expression = context.user_data.get("expression", "")
|
||||
|
||||
data = query.data
|
||||
|
||||
if data == "c":
|
||||
expression = ""
|
||||
elif data == "=":
|
||||
try:
|
||||
expression = str(eval(expression ))
|
||||
except Exception:
|
||||
expression = ""
|
||||
else:
|
||||
expression += data
|
||||
|
||||
|
||||
context.user_data["expression"] = expression
|
||||
|
||||
await query.edit_message_text(f"Выражение: {expression}", reply_markup=InlineKeyboardMarkup(keyboard))
|
||||
|
||||
|
||||
|
||||
|
||||
# async def calc(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
|
||||
# await update.message.reply_text("Введите выражение:", reply_markup=InlineKeyboardMarkup(keyboard))
|
||||
# await update.callback_query
|
||||
# print(update.callback_query)
|
||||
# context.chat_data["выражение"] = "0"
|
||||
# query = update.callback_query
|
||||
# await query.answer()
|
||||
|
||||
# data = query.data
|
||||
# print(data)
|
||||
# # try:
|
||||
# # result = eval(context.chat_data["выражение"])
|
||||
# # print(result)
|
||||
# # except:
|
||||
# # print("Случилась ошибка")
|
||||
# # print(context.chat_data)
|
||||
|
||||
# if data == "C":
|
||||
# Exception = ""
|
||||
# elif data == "=":
|
||||
# try
|
||||
# except
|
||||
|
||||
|
||||
def main() -> None:
|
||||
"""Start the bot."""
|
||||
# Create the Application and pass it your bot's token.
|
||||
application = Application.builder().token(os.getenv("TOKEN")).build()
|
||||
|
||||
# on different commands - answer in Telegram
|
||||
application.add_handler(CommandHandler("start", start))
|
||||
# application.add_handler(CommandHandler("calc", calc))
|
||||
application.add_handler(CommandHandler("help", help_command))
|
||||
|
||||
# on non command i.e message - echo the message on Telegram
|
||||
# application.add_handler(MessageHandler(filters.TEXT & ~filters.COMMAND, echo))
|
||||
application.add_handler(CallbackQueryHandler(calc))
|
||||
|
||||
# Run the bot until the user presses Ctrl-C
|
||||
application.run_polling(allowed_updates=Update.ALL_TYPES)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Loading…
x
Reference in New Issue
Block a user