【问题标题】:Using function returns with None使用函数返回 None
【发布时间】:2018-09-09 04:48:05
【问题描述】:

编写一个函数 file_in_english(filename, character_limit),它接受一个文件名(作为 str)和一个 character_limit(作为 int)。文件名是要从 Cat Latin 转换为英语的文件的名称,字符限制是可以转换的最大字符数。限制是输出中的字符总数(包括换行符)。

该函数应该返回一个字符串,其中包含所有转换后的行,其顺序与文件相同 - 记住每行末尾的换行符(即确保在每个转换行的末尾包含一个换行符以便它包含在行的长度中)。

如果超出限制(即转换后的句子会使输出超过限制),则不应将字符数超过限制的句子添加到输出中。应该在输出的末尾添加一个带有“”的行。然后应该停止对行的处理。

文件中的每一行都是一个奇怪的拉丁语句子,你的程序应该打印出每个句子的英文版本

函数应该不断添加句子,直到文件输入用完或打印的字符总数(包括空格)超过限制。

答案必须包括您对english_sentence 及其辅助函数的定义——我应该称之为english_word 或类似函数。

您必须在 file_in_english 函数中使用 while。

每个函数只能使用一个返回语句。

示例中使用的测试文件(test1.txt)有以下数据:

impleseeoow estteeoow aseceeoow
impleseeoow estteeoow aseceeoow ineleeoow 2meeoow
impleseeoow estteeoow aseceeoow ineleeoow 3meeoow
impleseeoow estteeoow aseceeoow ineleeoow 4meeoow

我的程序工作正常,只是有时它返回 None。

def english_sentence(sentence):
"""Reverse Translation"""
consonants = 'bcdfghjklmnpqrstvwxyzBCDFGHJKLMNPQRSTVWXYZ'
eng_sentence = [] 
for coded_word in sentence.split():
    if coded_word.endswith("eeoow") and (coded_word[-6] in consonants):
        english_word = coded_word[-6] + coded_word[:-6]
        if (coded_word[-6] == 'm') and (coded_word[0] not in consonants):
            english_word = '(' + english_word + ' or ' + coded_word[:-6] + ')'
    eng_sentence.append(english_word)
return " ".join(eng_sentence)


def file_in_english(filename, character_limit):
"""English File"""
newone = open(filename)
nowline = newone.readline()  
characters = 0
while characters < character_limit and nowline != "":
    process = nowline[0:-1]
    print(english_sentence(process))
    characters += len(nowline)
    nowline = newone.readline()
if characters > character_limit:
    return("<<Output limit exceeded>>")



ans = file_in_english('test1.txt', 20)
print(ans)

输出是:

simple test case
simple test case line (m2 or 2)
simple test case line (m3 or 3)
simple test case line (m4 or 4)
None

但我必须在每个函数中只使用一个 return 语句。我怎样才能为第二个功能做到这一点并避免输出中的“无”?

【问题讨论】:

  • 您必须确保,任何应该返回某些内容的函数都适用于所有情况。您的函数file_in_english 仅针对if characters &gt; character_limit: 的情况返回一些内容 - 如果不是不是 的情况,则该函数不返回任何内容。 任何函数如果最终不从它返回任何东西,当它返回给它的调用者时会隐式返回None

标签: python python-3.x


【解决方案1】:

你正在做同样的事情:

def f():
    print('hello')
print(f())

所以基本上缩小到:

print(print('hello world'))

顺便说一句:

>>> type(print('hello'))
hello
<class 'NoneType'>
>>> 

要解决您的代码,请执行以下操作:

def file_in_english(filename, character_limit):
    s=""
    """English File"""
    newone = open(filename)
    nowline = newone.readline()  
    characters = 0
    while characters < character_limit and nowline != "":
        process = nowline[0:-1]
        s+=english_sentence(process)+'\n'
        characters += len(nowline)
        nowline = newone.readline()
    if characters > character_limit:
        s+="<<Output limit exceeded>>"

    return s


ans = file_in_english('test1.txt', 20)
print(ans)

【讨论】:

  • 它似乎有效。谢谢。虽然我仍然不清楚我在哪里搞砸了。
  • @JD1978 因为有一个打印,外面也是一个打印,我知道你需要打印,因为多个returns不起作用
【解决方案2】:

您必须确保,任何应该返回某些内容的函数都以您的函数可以结束的所有方式执行此操作。

您的函数file_in_english 仅返回针对情况if characters &gt; character_limit: 的内容

如果charachter ==charachter &lt; character_limit不是的情况,该函数不会显式返回任何内容。

任何函数最终不从它返回任何东西,当它返回给它的调用者时隐式返回None

def something(boolean):
    """Function that only returns something meaninfull if boolean is True."""
    if boolean:
        return "Wow" 

print(something(True))  # returns Wow
print(something(False)) # implicitly returns/prints None

你可以找到这个事实 f.e.在python教程中:

来自其他语言,您可能会反对 fib 不是 函数而是一个过程,因为它不返回值。实际上, 即使没有 return 语句的函数也会返回一个值,尽管是 相当无聊的一个。这个值称为 None (它是一个内置名称)。 写入值 None 通常会被解释器抑制,如果它 将是唯一写入的值。如果你真的想看,你可以看到它 使用打印():

来源:https://docs.python.org/3.7/tutorial/controlflow.html#defining-functions - 就在第二个绿色示例框之后

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-10-26
    • 1970-01-01
    • 2016-06-09
    • 2014-12-06
    • 2023-01-12
    • 2013-02-17
    • 2018-03-08
    相关资源
    最近更新 更多