我正在聊天机器人中创建一个功能,该功能会更改机器人代理名称。我在顶部声明了该机器人的名称。
bot = "Bot"
然后我创建一个函数,该函数接收用户的输入并更改bot的名称
elif "c-a" in inp:
settt = True
print(f"Choose agent(1-7):", end=' ')
while settt:
s_c = input()
try:
s = int(s_c)
except ValueError:
s = str(s_c)
sv = type(s)
if sv is int:
if s == 1:
bot = "Bhaskar"
return bot
elif s == 2:
bot = "Divya"
return bot
elif s == 3:
bot = "Nayan"
return bot
elif s == 4:
bot = "Sruti"
return bot
elif s == 5:
bot = "Gagan"
return bot
elif s == 6:
bot = "Ruchi"
return bot
elif s == 7:
bot = "Abhishek"
return bot
else:
a()
print("I didn't get it. Chose between 1 to 7 or type /h for help & /q for discard")
q()
else:
if s == "/h":
bot_list()
elif s == "/q":
settt = False
else:
a()
print("I didn't get it. Chose between 1 to 7 or type /h for help & /q for discard")
q()
但是机器人的价值保持不变。它不会改变。
答案 0 :(得分:1)
这是因为变量bot
是全局变量。
在if else
语句之前的函数内部添加此行
global bot
所以代码看起来像这样:
bot = "bot"
def name():
global bot
#if else statements begin here
答案 1 :(得分:0)
您应该在函数中添加global bot
行。但是我建议避免使用全局变量。我认为您应该将其作为参数并返回更改后的变量。
def your_function(param=None):
... Some code (Here you can use the value of bot variable which name is param inside this function.) ...
return param
bot = your_function(param=bot)
这意味着您用函数的返回值覆盖了bot
变量。
一个例子:
bot = 5
print("Before function: %s" % bot)
def your_function(param=None):
param = param*2
return param
bot = your_function(param=bot)
print("After function: %s" % bot)
输出:
python test.py
Before function: 5
After function: 10