1

Let's say we have a function like this

def function():
    while True:
        user_input = input("enter a number: ")
        if user_input == "0":
            print("finish")
            break
        print("the number is " + user_input)

And in the main() we call the function

function()

Then it will ask for user input until it gets a "0". What I want to do is like have something can store all the input, and automatically give it to the console. So, I don't need to manually type them in the console.

Please note that I'd like to have the function not accepting arguments and use something_taken_as_input without passing it as an argument.

something_taken_as_input = ["1","2","3","0"]
function()
# enter a number: 1
# enter a number: 2
# enter a number: 3
# enter a number: 0
# finish
# all done by the program, no manually typing!
thushv89
  • 10,865
  • 1
  • 26
  • 39
lyy
  • 11
  • 2
  • 2
    get inputs from file `python script.py < user_inputs.txt`. You can even save results in file `python script.py < user_inputs.txt > result.text` so you can compare this file with file which has expected results. – furas Nov 30 '19 at 06:03
  • https://stackoverflow.com/questions/31239002/enter-to-raw-input-automatically – αԋɱҽԃ αмєяιcαη Nov 30 '19 at 06:03
  • it is good when function get value as arguments and other function only get value from user and run first function with this value. This way you can test first function with data from list, file, sys.args, or database - and you don't have to do it manually. – furas Nov 30 '19 at 06:08

1 Answers1

0

A fun way to do this would be to pass the input method to the function.

This way, you can do this:

def function(inp_method):
while True:
    user_input = inp_method("enter a number: ")
    if user_input == "0":
        print("finish")
        break
    print("the number is " + user_input)

if you want to take input from the user, call it like this:

function(input)

otherwise, define a class with the data you want to input:

    class input_data:
        def __init__(data):
            self.data = data
            self.count = 0

        def get(self, str = ""):
            if(self.count == len(self.data)):
            return 0
        else:
            count+=1
            x = self.data[count-1]

and call function using:

d = input_data(["1", "2", "3", "0"])
function(d.get)

Fundamentally, you are just passing the method through the parameters of the function.

Ananay Gupta
  • 355
  • 3
  • 14