Python 函数在连续运行时返回 'None'

Python function returning 'None' on consecutive runs

当我第一次收到时就正确了 'mwindow'。但是,如果我错了一次或多次,我总是得到 'none',即使我最后做对了。

def windows():
    print('\n---Maintenence Window Config---\n')
    mwdate = input('Enter the date for the maintenance window (3 letters, Mon, Tue, Wed, etc.) : ')
    if len(mwdate) > 3 or len(mwdate) < 3:
        print('Error, date must be 3 characters in length.')
        windows()
    else:
        mwstart = input('Enter the time in 24h format for the beginning of the maintenance window (e.x. 04:00): ')
        mwend = input('Enter the ending time of the maintenance window in 24h format (e.x. 04:30): ')
        if int((mwstart and mwend).replace(':','')) < 1000 and (mwstart and mwend).startswith('0'):
            mwindow = mwdate.capitalize()+mwstart+'-'+mwdate.capitalize()+mwend
            return mwindow
        else:
            print('Error, be sure you prefix your window times with a 0 if they are earlier than 10:00.')
            windows()

print(windows())

我不认为这是重复的,因为所有其他问题都存在忘记将测试值传回函数的问题,但在我的情况下这不是 ap

您忽略了递归调用的 return 值,因此您的函数刚刚结束并且 return None。您可以改用 return windows() 来更正您的 windows() 调用。

更好的是,不要使用递归。当给出正确的输入时,只需使用循环和 return:

def windows():
    while True:
        print('\n---Maintenence Window Config---\n')
        mwdate = input('Enter the date for the maintenance window (3 letters, Mon, Tue, Wed, etc.) : ')
        if len(mwdate) > 3 or len(mwdate) < 3:
            print('Error, date must be 3 characters in length.')
            continue

        mwstart = input('Enter the time in 24h format for the beginning of the maintenance window (e.x. 04:00): ')
        mwend = input('Enter the ending time of the maintenance window in 24h format (e.x. 04:30): ')
        if int((mwstart and mwend).replace(':','')) < 1000 and (mwstart and mwend).startswith('0'):
            mwindow = mwdate.capitalize()+mwstart+'-'+mwdate.capitalize()+mwend
            return mwindow

        print('Error, be sure you prefix your window times with a 0 if they are earlier than 10:00.')

另见 Asking the user for input until they give a valid response