我明白下面的函数的作用,但我不太清楚返回True
和False
之间的重要性(或差异)。函数中的正确和错误def
这两个子句都使程序退出;即在输入正面或负面响应时,Python提示符会返回,那么内部实际上会发生什么变化?
而且,如果我设计这样的功能我自己,我应该用True
或False
,如果我只是想程序的提示还给我没有实际做什么?
def ask(prompt, retries = 4, reminder = 'Please try again!'):
while True:
response = input(prompt)
if response in ('y', 'yes'):
print('Got y or yes!')
return True
if response in ('n', 'no', 'nope'):
print('Got n or no or nope!')
return False
retries = retries - 1
if retries < 0:
raise ValueError('Invalid user response!')
print(reminder)
ask('Do you wanna quit?')
它取决于你的应用程序,如果你需要将函数的返回传递给其他地方,那么它会有所作为,否则你可能只是使用return。 – Alessandro
如果你没有使用返回的值,你可能只使用return(没有True或False) – 2016-06-10 11:55:25
如果你想向用户询问其他类似的东西,我会说它有不同的返回值:“你真的想要买这个吗? “那么你可以做一个'如果问('你真的想买这个?')'例如 – KRONWALLED