Python 为什么没有定义目标
我正在用discord.py编写discord economy机器人程序,但我的共享命令不起作用:Python 为什么没有定义目标,python,discord.py,Python,Discord.py,我正在用discord.py编写discord economy机器人程序,但我的共享命令不起作用: if message.content.startswith('bott share'): try: target, amount = message.content.split(' ')[1:] amount = int(amount) except ValueError: await mess
if message.content.startswith('bott share'):
try:
target, amount = message.content.split(' ')[1:]
amount = int(amount)
except ValueError:
await message.channel.send('Invalid Arguments')
target = target[2:-1]
if target[0] == '!':
target = target[1:]
target = int(target)
if amount > getcoins(user):
await message.channel.send('ARE YOU TRYING TO HJACK THE SYSTEM?')
elif amount < 0:
await message.channel.send('ARE YOU TRYING TO HJACK THE SYSTEM?')
setcoins(user, getcoins(user)-amount)
setcoins(target, getcoins(target)+amount)
await message.channel.send(f'You gave {target} {amount}, and now you have {getcoins(user)}.')
当你跑的时候
target, amount = message.content.split(' ')[1:]
然后会有错误,它不会创建变量target,amount,但在捕获此错误后,您运行target[2:-1],然后它会尝试从不存在的变量中获取值
你可以把所有的东西都放进去试试看
if message.content.startswith('bott share'):
try:
target, amount = message.content.split(' ')[1:]
amount = int(amount)
target = target[2:-1]
if target[0] == '!':
target = target[1:]
target = int(target)
if amount > getcoins(user):
await message.channel.send('ARE YOU TRYING TO HJACK THE SYSTEM?')
elif amount < 0:
await message.channel.send('ARE YOU TRYING TO HJACK THE SYSTEM?')
setcoins(user, getcoins(user)-amount)
setcoins(target, getcoins(target)+amount)
await message.channel.send(f'You gave {target} {amount}, and now you have {getcoins(user)}.')
except ValueError:
await message.channel.send('Invalid Arguments')
或者最终-但如果目标为空字符串或金额为0,则if将给出False
若在函数中运行此代码,那个么可以使用return to finish函数
try:
target, amount = message.content.split(' ')[1:]
amount = int(amount)
except ValueError:
await message.channel.send('Invalid Arguments')
return # finish function
我会尝试打印目标,看看它是否包含您认为它所包含的内容。@Chris它不起作用,但感谢这应该是您的第一个错误指示。如果try块的第一行失败,则不会为target或amount分配任何值。您需要:A为这些变量预先赋值,B在except子句中为它们赋值,或C让except子句完全退出函数,这样您就不会在这些变量没有值的情况下继续操作。target,amount=message.content.split'[1:]当且仅当message.content.split'[1:]长度为2,但可能不是。如果/当失败时,您的目标不会被分配。
target = None
amount = None
try:
target, amount = message.content.split(' ')[1:]
amount = int(amount)
except ValueError:
await message.channel.send('Invalid Arguments')
if target is not None and amount is not None:
target = target[2:-1]
# ... rest ...
if target and amount:
target = target[2:-1]
# ... rest ...
try:
target, amount = message.content.split(' ')[1:]
amount = int(amount)
except ValueError:
await message.channel.send('Invalid Arguments')
return # finish function