【问题标题】:How can a parameter of a function be made global?How can a parameter of a function be made global?
【发布时间】:2022-12-01 23:08:54
【问题描述】:

Is it possible to make the script work without having to declare the variables outside the function?

import telepot

myId = '000000000'

def bot1(msg):
    global bot1msg1, bot1msg2, bot1msg3
    tokenbot1 = '000000000:AAH6AAH6AAH6AAH6AAH6'
    bot1 = telepot.Bot(tokenbot1)
    bot1msg1 = 'Msg 1'
    bot1msg2 = 'Msg 2'
    bot1msg3 = 'Msg 3'
    bot1.sendMessage(myId, msg)

bot1(bot1msg3)

NameError: name 'bot1msg3' is not defined

Make the script work with the variable outside the function

【问题讨论】:

  • When you call bot1(bot1msg3), the variable hasn't been created yet because the function hasn't ran yet. It is unclear what you are trying to do.
  • You're passing bot1msg3 to the function bot1 before you define it. That's the problem.

标签: python python-3.x


【解决方案1】:

(With all code parts that are no used commented), you should, at least, define the returnValue

#import telepot

myId = '000000000'
botAnswer = ''

def bot1(msg):
    #global bot1msg1, bot1msg2, bot1msg3
    tokenbot1 = '000000000:AAH6AAH6AAH6AAH6AAH6'
    #bot1 = telepot.Bot(tokenbot1)
    bot1msg1 = 'Msg 1'
    bot1msg2 = 'Msg 2'
    bot1msg3 = 'Msg 3'
    #bot1.sendMessage(myId, msg)
    return bot1msg3

botAnswer = bot1('Hi')
print(botAnswer)

【讨论】:

    猜你喜欢
    • 2022-12-02
    • 2022-12-02
    • 2022-12-01
    • 2022-12-02
    • 2022-12-01
    • 2022-12-02
    • 2022-12-28
    • 2022-12-01
    • 2021-07-18
    相关资源
    最近更新 更多