【问题标题】:Python function returning 'None' on consecutive runs [duplicate]Python函数在连续运行时返回“无”[重复]
【发布时间】:2015-09-17 09:29:52
【问题描述】:

当我第一次收到“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())

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

【问题讨论】:

    标签: python function python-3.x return nonetype


    【解决方案1】:

    您忽略了递归调用的返回值,因此您的函数刚刚结束并返回None。您可以改用return windows() 来更正您的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

    【讨论】:

    • 哦!我认为当您发出“return”声明时,它会完全破坏该功能。谢谢!时间一到,我会标记为答案:)
    猜你喜欢
    • 2020-08-24
    • 2021-08-02
    • 1970-01-01
    • 2018-06-09
    • 2021-08-15
    • 2023-01-12
    • 1970-01-01
    • 1970-01-01
    • 2022-12-25
    相关资源
    最近更新 更多