Python函数返回'无'连续运行

时间:2015-06-30 14:14:15

标签: python function python-3.x return 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())

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

1 个答案:

答案 0 :(得分: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.')

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