简体   繁体   中英

Using variable inside the def function globaly

Here is my code

@bot.message_handler(content_types=['text'])
def welcome(message):
    bot.send_message(message.chat.id,"Hello, <b>{0.first_name}</b>!".format(message.from_user, bot.get_me()), parse_mode='html')
    sent = bot.send_message(message.chat.id,"Enter your name".format(message.from_user, bot.get_me()), parse_mode='html')
    bot.register_next_step_handler(sent, hello)

def hello(message):
    text = message.text
    print(text)
print(text)


bot.polling(none_stop=True, timeout=123)

Here I use librarie telebot. So When I attempt to use variable text globaly I always fail.

I have an error: NameError: name 'text' is not defined

I have already attempted to use global parameter in a def but it wasn't succesfull.

You should use the global keyword and call the function hello() before print text :

def hello(message):
    global text
    text = message.text
    print(text)
# call hello() in here
print(text)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM