Home > OS >  input function inside a nested function in python
input function inside a nested function in python

Time:08-31

This is strange. I have searched this problem, but I didn't find any similar question. The following code in Python 3.X is the simplest model that I can explain.

def is_correct(function,wait_sec=0.5):
    while True:
        output = function
        is_correct = input('Is the input correct(y(Enter)/n)?')
        time.sleep(1)
        if is_correct.lower() in ['','y','yes']:
            clear_output()
            time.sleep(wait_sec)
            return output
        clear_output()
        time.sleep(wait_sec)

def whileloop(fun):
    while True:
        fun
def INPUT():
    result=input('...')

def hello_world():
    print('hello world')

def forloop(fun):
    for i in range(3):
        fun

Thus, when I run forloop(INPUT()), it only let me input two times. when I run whileloop(INPUT()), I got one input and then an infinite loop. Most strangely, when I run is_correct(hello_world), it only print 'hello world' once.

Any idea?

CodePudding user response:

You are missing () when using argument fun or function inside functions,
And when you call the functions, you should pass the argument without () like forloop(INPUT) and whileloop(INPUT)

def is_correct(function,wait_sec=0.5):
    while True:
        output = function()
        is_correct = input('Is the input correct(y(Enter)/n)?')
        #time.sleep(1)
        if is_correct.lower() in ['','y','yes']:
            #clear_output()
            #time.sleep(wait_sec)
            return output
        #clear_output()
        #time.sleep(wait_sec)

def whileloop(fun):
    while True:
        fun()
def INPUT():
    result=input('...')

def hello_world():
    print('hello world')

def forloop(fun):
    for i in range(3):
        fun()

forloop(INPUT)
  • Related