【问题标题】:"None" as return from while loop“无”作为 while 循环的返回
【发布时间】:2013-09-03 13:06:14
【问题描述】:

我有以下功能:

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' object is not subscriptable。如何解决这个问题?

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

我想把从 Drafts 带来的一串文本放到这个函数中,if/elif 会将一个 1-2-3 字符串转换成我需要的 4 位数字以及我想要的方式。例如,字符串“1”将变为“0100”。但你知道的。如果用户以某种方式搞砸了,我正在使用那段时间。是的,我应该以其他方式重新组织它,例如在实际尝试编辑字符串之前使用int(f[:2]) &lt;= 23 and int(f[2:]) &lt;= 59

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

1234
None

现在,我还能做些什么来帮助你?

EDIT2:由于每个人都在要求完整的代码,所以你是来帮助我的,我只是认为没有必要。对此表示歉意(:

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)

【问题讨论】:

  • return 声明之后不需要break。您应该显示示例输入/输出
  • f 是一个非常糟糕的变量名。请阅读 pep8 标准。
  • if 语句中的最后一个int() 缺少)
  • 您在if len(f) &gt; 0 ... 行中缺少)。所以很明显我们不是在看你实际运行的代码
  • len(f) &gt; 0 and len(f) &lt;= 4 最好写成0 &lt; len(f) &lt;=4

标签: python


【解决方案1】:
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('')

【讨论】:

  • 我喜欢这种方法,但 OP 可能不知道 zfill 做了什么。
  • 谢谢。我快速查看了文档以了解 zfill 的作用。
  • 我也完全忘记了 isdigit()。再次感谢(:
【解决方案2】:

你需要初始化 f 说,""。在while True 的第一次迭代中,f 是None,所以在if 条件下,它正在测试None[:2]None[2:],这显然会引发错误。

编辑:嗯,我想知道你为什么不明白

object of type 'NoneType' has no len()

先出错....

【讨论】:

    【解决方案3】:

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

    def AdjustTime(f):
       if not f:
          return
    

    如果您已将 "falsey" value 传递给该方法,这将阻止该方法执行。

    然而,为了做到这一点,你需要改变你的逻辑,在这个函数的调用者中有raw_input 行;因为上面的方法会返回,提示永远不会显示:

    def AdjustTime(f):
        if not f:
           return
        if len(f) == 1:
            return '0' + f + '00'
        if len(f) == 2:
            return f + '00'
        if len(f) == 3:
            return '0' + f
        if len(f) == 4:
            return f
        if 0 > len(f) <= 4 and int(f[:2]) <= 23 and int(f[2:] <= 59:
            return f
    
    def get_input():
        f = raw_input('')
        result = AdjustTime(f)
        while not result:
            print('{} get this date right'.format(f))
            f = raw_input('')
            result = AdjustTime(f)
    

    @gnibbler 在评论中有一个很好的建议:

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

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

    【讨论】:

    • 如果是这种情况,object of type 'NoneType' has no len() 不应该是错误吗?
    • 不,因为我不检查长度;而是对象的真值(请参阅我的答案中的链接)。
    • f = f or "" 更好,所以你会进入while循环
    • 我的意思是这似乎不是错误的原因。否则 len() 会在索引之前出错。
    • @0xc0de,请参阅我对这个问题的评论。该错误是由与问题中的代码不同的代码产生的。
    猜你喜欢
    • 2015-11-17
    • 2017-11-09
    • 1970-01-01
    • 1970-01-01
    • 2016-05-29
    • 1970-01-01
    • 2016-11-30
    • 2019-05-08
    相关资源
    最近更新 更多