如何从def函数调用操作-Python

问题描述 投票:-3回答:1

我有如下的python代码

def call():
 input1 = input('Bot1:')
 input2 = input('Bot2:')
call()

input1

仅如何调用“ input1”操作。我想要在调用它之后,input1操作将开始在屏幕上输入数据。

但是在上面的代码...当我运行时,它显示警告'未定义input1'

谢谢!

python
1个回答
0
投票

您无法从函数外部访问函数的局部变量。解决该限制的一种方法是执行以下操作:

ACTION1, ACTION2 = 1, 2

def get_input(action):
    if action == ACTION1:
        return input('Bot1:')
    elif action == ACTION2:
        return input('Bot2:')
    else:
        raise RuntimeError('Unknown action')

input1 = get_input(ACTION1)
© www.soinside.com 2019 - 2024. All rights reserved.