从while循环返回“None”

2024-09-30 06:18:31 发布

您现在位置:Python中文网/ 问答频道 /正文

我有以下功能:

def AdjustTime(f):
    if len(f) == 1:
        return '0' + f + '00'
    elif len(f) == 2:
        return f + '00'
    elif len(f) == 3:
        return '0' + f
    elif len(f) == 4:
        return f
    else:
        while True:
            if len(f) > 0 and len(f) <= 4 and int(f[:2]) <= 23 and int(f[2:]) <= 59:
                return f
                break
            else:
                clear()
                print f,'Get this date right'
                f = raw_input('')

直到我得到一个正确的数字,这会导致一个TypeError:'NoneType'对象不可订阅。怎么解决这个问题?在

编辑:首先,感谢括号中提到的,我在自己编写代码时忘记了几次,现在代码就是我正在尝试的代码。在

我想把草稿中的一个文本字符串放入这个函数中,if/elif将把一个1-2-3的字符串转换成我需要的4位数,以及我想要它的方式。例如,字符串“1”将变为“0100”。但你知道的。如果用户搞砸了,我就用它。是的,我应该用其他方法重新组织它,比如在实际编辑字符串之前使用int(f[:2]) <= 23 and int(f[2:]) <= 59。在

回到正轨上,如果用户搞砸了,输入将给他插入一个正确字符串的机会,该字符串将通过while传递。问题是,当用户输入正确的值时,这就是print f所显示的值,该值为1234:

^{pr2}$

现在,我还能帮你什么忙吗?在

编辑2:既然每个人都要求完整的代码,你是来帮我的,我只是觉得没必要。为此道歉(:

from urllib import quote
import time
from webbrowser import open
from console import clear

rgv = ['a path', 'This is an awesome reminder\nWith\nMultiple\nLines.\nThe last line will be the time\n23455']

a = rgv[1].split('\n')

reminder = quote('\n'.join(a[:(len(a)-1)]))

t = a[len(a)-1]

def AdjustTime(f):
    if len(f) == 1:
    return '0' + f + '00'
    elif len(f) == 2:
        return f + '00'
    elif len(f) == 3:
        return '0' + f
    elif len(f) == 4:
        return f
    else:
        while True:
            if len(f) > 0 and len(f) <= 4 and int(f[:2]) <= 23 and int(f[2:]) <= 59:
                return f
                break
            else:
                clear()
                print 'Get this date right'
                f = raw_input('')

mins = int(AdjustTime(t)[:2])*60 + int(AdjustTime(t)[2:])

local = (time.localtime().tm_hour*60+time.localtime().tm_min)

def findTime():
    if local < mins:
        return mins - local
    else: 
        return mins - local + 1440

due = 'due://x-callback-url/add?title=' + reminder + '&minslater=' + str(findTime()) + '&x-source=Drafts&x-success=drafts://'

open(due)

Tags: and字符串代码importlenreturniftime
3条回答

在方法的顶部,添加以下内容:

def AdjustTime(f):
   if not f:
      return

如果传递了"falsey" value,这将阻止该方法执行。在

但是,为了做到这一点,您需要更改您的逻辑,使raw_input行出现在该函数的调用方中;因为上面的方法将返回并且永远不会显示提示:

^{2}$

@gnibbler在评论中说:

def AdjustTime(f):
   f = f or ""

如果传入的值是falsey,这将把f的值设置为空字符串。此方法的好处是if循环仍将运行(因为空字符串有长度),但while循环将失败。在

您需要初始化f来表示,""。在while Truef的第一次生成是None,所以在if条件下测试{}和{},这显然会引起误差。在

编辑:我想知道你为什么不

object of type 'NoneType' has no len()

先出错。。。。在

def AdjustTime(f):
    f = f or ""   # in case None was passed in
    while True:
        f = f.zfill(4)
        if f.isdigit() and len(f) == 4 and int(f[:2]) <= 23 and int(f[2:]) <= 59:
            return f
        clear()
        print f, 'Get this date right'
        f = raw_input('')

相关问题 更多 >

    热门问题