【问题标题】:'return' outside function [closed]“返回”外部函数[关闭]
【发布时间】:2012-11-13 11:21:32
【问题描述】:

为什么这给了我错误'return' outside function

Result = ""
char = ""

    # Let char loop over each character in the input string

a = list(s)
for i in range (0, len(s)):

        # If this char is a letter:

    if (type(a[i])=='str'):

            # Set char_low to be char converted to lower case

        char_low = a.lower()
        print a

            # Note: the next 5 lines do not need to be changed -
            #  they will modify the character as necessary
    if char_low <= 'm':
        dist = 13
    else:
         dist = -13
    char = chr(ord(char) + dist)
        # Push char onto the end of the result

    result = result + char

    # Return the encrypted text

return result

【问题讨论】:

  • 请确保您发布的代码具有正确的缩进(这对 Python 尤其重要...)。代码块必须缩进另外四个空格才能在 Markdown 中呈现为预格式化块,您可以通过选择它然后使用 {} 按钮来适当地缩进整个块。

标签: python python-2.7


【解决方案1】:

好吧,因为返回在函数之外。

【讨论】:

  • 这是 OP 应得的答案,但不是他现在需要的答案……
【解决方案2】:

return 语句只能在函数定义中使用,例如:

def myfunc():
    result = 1
    return result

如果结果是退出代码,您可能想要使用sys.exit(result),或者更有可能将结果打印到控制台,在这种情况下只需使用print(result)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-08-19
    • 1970-01-01
    • 2012-12-11
    • 1970-01-01
    • 2015-11-21
    • 2019-11-25
    相关资源
    最近更新 更多