简体   繁体   English

使用无功能返回

[英]Using function returns with None

Write a function file_in_english(filename, character_limit) that takes a filename (as a str) and a character_limit (as an int). 编写一个函数file_in_english(filename,character_limit),该函数采用文件名(作为str)和character_limit(作为int)。 The filename is the name of the file to convert from Cat Latin to English and the character limit is the maximum number of characters that can be converted. 文件名是要从Cat Latin转换为英语的文件的名称,字符数限制是可以转换的最大字符数。 The limit is on the total number of characters in the output (including newline characters). 限制是输出中的字符总数(包括换行符)。

The function should return a string that contains all the converted lines in the same order as the file - remember the newline character at the end of each line (that is make sure you include a newline character at the end of each converted line so that it is included in the line's length). 该函数应返回一个字符串,该字符串包含与文件顺序相同的所有转换后的行-请记住每行末尾的换行符(请确保在每行转换后的末尾都包含一个换行符,以便它包含在行的长度中)。

If the limit is exceeded (ie, a converted sentence would take the output over the limit) then the sentence that takes the character count over the limit shouldn't be added to the output. 如果超出了限制(即,转换后的句子将使输出超出限制),则字符数超过限制的句子不应添加到输出中。 A line with "<>" should be added at the end of the output instead. 应该在输出末尾添加带有“ <>”的行。 The processing of lines should then stop. 然后,行的处理应停止。

The lines in the file will each be a sentence in Weird Latin and your program should print out the English version of each sentence 文件中的每一行将是一个古怪的拉丁文句子,您的程序应打印出每个句子的英文版本

The function should keep adding sentences until it runs out of input from the file or the total number of characters printed (including spaces) exceeds the limit. 该功能应继续添加句子,直到用尽文件输入或打印的字符总数(包括空格)超过限制为止。

The answer must include your definition of english_sentence and its helper(s) functions - that I should have called english_word or similar. 答案必须包括您对english_sentence及其辅助功能的定义-我应该将其称为english_word或类似名称。

You MUST use while in your file_in_english function. 您必须在file_in_english函数中使用。

You can only use one return statement per function. 每个函数只能使用一个return语句。

The test file used in the examples (test1.txt) has the following data: 示例中使用的测试文件(test1.txt)具有以下数据:

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

I program works fine except that sometimes it returns None. 我的程序工作正常,但有时它返回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)

Output is: 输出为:

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

But I must use only one return statement in each function. 但是我必须在每个函数中仅使用一个return语句。 How can I do that for the second function and avoid the "None" in output? 如何为第二个功能做到这一点,并避免输出“ None”?

You're doing the same thing as: 您正在执行以下操作:

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

So basically narrows down to: 因此基本上可以缩小为:

print(print('hello world'))

Also btw: 顺便说一句:

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

To solve your code do: 要解决您的代码,请执行以下操作:

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)

You have to make sure, that any function that should return something, does this for ALL ways that your function can end. 您必须确保任何应返回内容的函数都以函数可以结束的所有方式执行此操作。

Your function file_in_english only returns something for the case if characters > character_limit: if characters > character_limit:函数file_in_english仅返回某些情况if characters > character_limit:

If charachter == or charachter < character_limit this is not the case, the function returns nothing explicitly. 如果charachter ==charachter < character_limit 不是这种情况,则该函数明确返回任何内容。

Any function that does not return something from it on end, implicitly returns None when it returns to its caller. 任何最终不从其返回任何东西的函数,在返回到其调用方时都隐式返回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

You can find this fact fe in the python tutorial: 您可以在python教程中找到以下事实:

Coming from other languages, you might object that fib is not a function but a procedure since it doesn't return a value. 来自其他语言,您可能会反对fib不是函数而是过程,因为它不返回值。 In fact, even functions without a return statement do return a value, albeit a rather boring one. 实际上,即使没有return语句的函数也确实会返回一个值,尽管这很无聊。 This value is called None (it's a built-in name). 此值称为“无”(这是一个内置名称)。 Writing the value None is normally suppressed by the interpreter if it would be the only value written. 如果写入值None是唯一写入的值,则通常会被解释器抑制。 You can see it if you really want to using print(): 如果您确实要使用print(),则可以看到它:

Source: https://docs.python.org/3.7/tutorial/controlflow.html#defining-functions - just short after the 2nd green example box 来源: https : //docs.python.org/3.7/tutorial/controlflow.html#defining-functions-在第二个绿色示例框后不久

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM