My function gets input from user. I want to call it in a way that it gets input from list - without changing function. I am using Jupyter notebook - Python
def example_function() :
a = input()
b = input()
print (a b)
c = input()
d = input()
print (c d)
return
I want to call example_function
and pass a list to it as input values (a, b, c and d). It is not possible to change example_function
itself.
CodePudding user response:
You can do it by temporarily changing stdin
which is where the input()
function gets its data:
from contextlib import contextmanager
from io import StringIO
import sys
@contextmanager
def redirect_stdin(source):
save_stdin = sys.stdin
sys.stdin = StringIO('\n'.join(source) '\n')
yield
sys.stdin = save_stdin
def example_function():
a = input()
b = input()
print(a b)
c = input()
d = input()
print(c d)
return
inp = ['a', 'b', 'c', 'd']
with redirect_stdin(inp):
example_function()
Output:
ab
cd
CodePudding user response:
Try this:
def get_inputs():
a = input()
b = input()
c = input()
d = input()
return (a, b, c, d)
def example_function(a, b, c, d):
print(a b)
print(c d)
return
example_function(*get_inputs())
Or more literally what you asked for, passing a list:
def get_inputs():
a = input()
b = input()
c = input()
d = input()
return [a, b, c, d]
def example_function(inputs):
a = inputs[0]
b = inputs[1]
c = inputs[2]
d = inputs[3]
print(a b)
print(c d)
return
example_function(get_inputs())
CodePudding user response:
I guess it's necessary to change the function here because it doesn't have any arguments currently. Here's one way to do the function so it works like you described.
def example_function(list):
counter = 0
for i in list:
counter = counter 1
if (counter == 1 or counter == 3):
print(list[i] list[i -1])
CodePudding user response:
With absolutely no changes to your example_function
function, the only way I'd know is to change the global input
. You should also reset it after so that the rest of your script works. this can be done by creating another method.
def example_function():
a = input()
b = input()
print (a b)
c = input()
d = input()
print (c d)
return
def call_example_function(list):
global input
_input = input
index = 0
def input(*args, **kwargs):
nonlocal index
ret = list[index]
index = 1
return str(ret) # the normal input will always return a string
example_function()
input = _input
if __name__ == "__main__":
name = input("What's your name?")
print(name)
call_example_function(["aa", "bb", "cc", "dd"])
pet = input("What pet do you have") # input works as normal outside
print(pet)
Output:
aabb
ccdd