-3

I have python code as below

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

input1

How to call 'input1' action only. I want after call it, the input1 action will start for inputting data on the screen.

But on above code... when I run, it show warning 'input1 not defined'

Thanks you!

trunghai
  • 3
  • 4
  • Given this code, you can’t “call input1” from outside `input`. – deceze Mar 07 '20 at 10:03
  • Rename your `input()` function something else and call it with that new name. – martineau Mar 07 '20 at 10:33
  • @martineau how to do? Could you pls send me a example ? – trunghai Mar 07 '20 at 14:53
  • 1
    Change `def input():` to `def something_else():`. – martineau Mar 07 '20 at 17:09
  • @martineau not correct . I have changed and call 'input1' but could not. – trunghai Mar 09 '20 at 01:20
  • You have to call it using its new name — but leave the calls to `input()` _inside_ it alone. – martineau Mar 09 '20 at 01:28
  • @martineau pls check a post as above, I have modified. – trunghai Mar 09 '20 at 01:41
  • You're getting the `input1 not defined` error because you are trying to access a variable that is local to the `call()` function. See [Access a function variable outside the function without using “global”](https://stackoverflow.com/questions/19326004/access-a-function-variable-outside-the-function-without-using-global). – martineau Mar 09 '20 at 01:58
  • @martineau sorry but I don't understand because i'm new with python. Could you pls suggest me example how to call sub action inside function from outside ?? – trunghai Mar 09 '20 at 02:34
  • I suppose you could add an argument to the `call()` function that told it which "action" to perform — but that alone won't allow you to access its `input1` local variable from outside the function. **Note** `input1` is a local _variable_, not an "action". – martineau Mar 09 '20 at 02:40

1 Answers1

0

You can't access the local variables of a function from outside of it. One way to workaround that limitation would be to do something like this:

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)
martineau
  • 119,623
  • 25
  • 170
  • 301