[英]“None” as return from while loop
我有以下功能:
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'对象不可下标。 如何解决这个问题?
编辑:首先,感谢括号中的提及,我在编写自己的代码时忘记了几次,现在的代码是我实际上正在尝试的代码。
我想将Drafts带来的文本字符串放入此函数中,if / elif会将1-2-3字符串转换为我需要的4位数字以及我想要的方式。 例如,字符串“ 1”将变为“ 0100”。 但是你知道的。 如果用户以某种方式搞砸了,我会在一段时间内使用它。 是的,我应该以其他方式重新组织它,例如在实际尝试编辑字符串之前,使用int(f[:2]) <= 23 and int(f[2:]) <= 59
。
回到正轨,如果用户搞砸了,输入将使他有机会插入正确的字符串,该字符串会经过一会儿。 问题是,当用户输入正确的值时,这是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)
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('')
您需要初始化f才能说""
。 在while True
的第一个迭代中while True
f为None
,因此在if
条件下,它正在测试None[:2]
和None[2:]
,这显然会引发错误。
编辑:好吧,我想知道为什么你不明白
object of type 'NoneType' has no len()
错误第一...
在方法顶部,添加以下内容:
def AdjustTime(f):
if not f:
return
如果传递了“ falsey”值,这将阻止该方法执行。
为了做到这一点,您需要更改逻辑,以在该函数的调用raw_input
包含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循环将失败。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.