Answer the question
In order to leave comments, you need to log in
How to make the code work until the error is fixed?
You need to handle a number input error, that is, if the user enters a number with letters or letters, the number will not pass and will throw a ValueError. I did it, but I want to be able to immediately enter the number again after the error message, until there is no error.
The code:
@bot.message_handler(commands=["put"])
def get_put(message):
sent_put = bot.send_message(message.chat.id, "Сколько денег(в рублях) ты хочешь положить в копилку?")
bot.register_next_step_handler(sent_put, put)
def put(message):
global get_put, balance
get_put = message.text
try:
balance += int(get_put)
spent_message = "Ты положил " + str(get_put) + "₽" + "\n" + "Теперь в копилке " + str(balance) + "₽"
bot.send_message(message.chat.id, spent_message, parse_mode="html")
except ValueError:
bot.send_message(message.chat.id, "Ошибка! Попробуй написать только число(без букв и символов)")
Answer the question
In order to leave comments, you need to log in
Using isdigit(), as mentioned before, you write a condition, if an error occurs, then return to the same position:
balance = 0
@bot.message_handler(commands=["put"])
def get_put(message):
sent_put = bot.send_message(message.chat.id, "Сколько денег(в рублях) ты хочешь положить в копилку?")
bot.register_next_step_handler(sent_put, put)
def put(message):
global get_put
get_put = message.text
if (message.text).isdigit() == False:
error_message = bot.send_message(message.chat.id, "Ошибка! Попробуй написать только число(без букв и символов)")
bot.register_next_step_handler(error_message, put)
else:
balance += int(get_put)
spent_message = "Ты положил " + str(get_put) + "₽" + "\n" + "Теперь в копилке " + str(balance) + "₽"
bot.send_message(message.chat.id, spent_message, parse_mode="html")
That's not how you should do it. Input Validation:
$ python3
Python 3.10.2 (main, Mar 8 2022, 23:56:15) [GCC 10.2.1 20210110] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> '123'.isdigit()
True
>>> '123+'.isdigit()
False
>>> '123a'.isdigit()
False
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question