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

Sam*_*ide 0 python return function python-3.x nonetype

当我第一次收到'mwindow'时,我做对了.但是,如果我错了一次或多次,即使我最终得到它也总是得到"无".

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())
Run Code Online (Sandbox Code Playgroud)

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

Mar*_*ers 5

您忽略了递归调用的返回值,因此您的函数刚刚结束并返回None.你可以改用你的windows()电话来改正你的电话return windows().

更好的是,不要使用递归.只需使用循环并在给出正确输入时返回:

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.')
Run Code Online (Sandbox Code Playgroud)

另请参阅询问用户输入,直到他们给出有效的响应