You need to enable JavaScript to run this app.
最新活动
大模型
产品
解决方案
定价
生态与合作
支持与服务
开发者
了解我们

Python代码报错:'return' outside function 寻求排查解决

Fixing the "return outside function" Syntax Error in Your Python Code

Hey there, let's get this syntax error sorted out for you. The error message you're seeing is crystal clear:

File "tvlattest.py", line 84 return self._key, self._textin SyntaxError: 'return' outside function

As you suspected, this is almost certainly an indentation issue—Python uses indentation to define code block boundaries, so if your return statement isn't properly indented under the newPair function, Python thinks it's sitting outside the function entirely.

Looking at your code, the return self._key, self._textin line is not indented to match the rest of the code inside the newPair function. Here's the corrected version of your code with proper indentation:

def newPair(self):
    rand = random.random()
    num_tot = self.num_group1 + self.num_group2
    if num_tot == 0:
        group1 = (rand < 0.5)
    else:
        cutoff = float(self.num_group1) / num_tot
        group1 = (rand < cutoff)
    if group1:
        self._textin = self._textin1
        if AES is not None:
            cipher = AES.new(str(self._key), AES.MODE_ECB)
            self._textin1 = bytearray(cipher.encrypt(str(self._textin1)))
        else:
            self._textin1 = bytearray(16)
            for i in range(0, 16):
                self._textin1[i] = random.randint(0, 255)
        if self.num_group1 > 0:
            self.num_group1 -= 1
    else:
        self._textin = self._interleavedPlaintext
        if self.num_group2 > 0:
            self.num_group2 -= 1
    # Check key works with target
    self.validateKey()
    # Properly indented return statement inside the function
    return self._key, self._textin

Key Fixes:

  • The return line is now indented to the same level as self.validateKey() and other top-level statements inside the newPair function, ensuring it's part of the function's code block.
  • I also double-checked all nested if/else and for loop blocks to make sure their inner statements are correctly indented—this helps prevent similar scope-related errors in the future.

Remember, in Python, consistent indentation (usually 4 spaces per level) isn't just a style choice—it's how the interpreter knows which code belongs to which function or block. Always double-check your indentation when you get scope-related syntax errors!

内容的提问来源于stack exchange,提问作者Konstantinos Papa

火山引擎 最新活动