Python语法错误:'return'在函数外及referer_list函数代码解析求助
Hey there! Let's tackle your problems one by one:
1. Resolving the SyntaxError: 'return' outside function
This error pops up when you have a return statement that's not tucked inside any function definition (either def or lambda). The referer_list function you shared doesn't include a return, so you’ll need to scan your entire codebase for any stray return lines that aren’t wrapped within a function block. That’s the immediate fix for this syntax error.
2. Issues in Your referer_list Function
Looking at the code you provided, there are several problems with the URLs and invalid snippets that need addressing:
def referer_list(): global headers_referers headers_referers.append('http://www.google.com/?q=') headers_referers.append('http://yandex.ru/yandsearch?text=%D1%%D2%?=g.sql()81%..') headers_referers.append('http://vk.com/profile.php?redirect=') headers_referers.append('http://www.usatoday.com/search/results?q=') headers_referers.append('http://engadget.search.aol.com/search?q=query?=query=..') headers_referers.append('https://www.google.ru/#hl=ru&newwindow=1?&saf..,or.r_gc.r_pw=?.r_cp.r_qf...')
Key Problems to Fix:
Missing initialization for
headers_referers: Before using this global list, you need to define it outside the function first, like:headers_referers = []Without this, you’ll get a
NameErrorwhen trying to callappend().Invalid URL formatting & broken snippets:
- The Yandex URL (
http://yandex.ru/yandsearch?text=%D1%%D2%?=g.sql()81%..) has:- Incomplete URL encoding (
%D1%%D2%is invalid—URL encoded characters are always%XXwhere XX is a hexadecimal pair) - A misplaced SQL-like snippet
g.sql()that doesn’t belong in a referer URL, plus invalid parameter syntax (?=instead of a validkey=valuepair)
- Incomplete URL encoding (
- The AOL search URL (
http://engadget.search.aol.com/search?q=query?=query=..) has two?characters—URLs only use one?to separate the path from parameters; additional parameters should use&. Thequery?=querypart is also invalid parameter syntax. - The Google.ru URL is incomplete (ends with
...) and uses HTML entities (&) instead of raw&characters for parameters, plus an extra?that breaks the URL structure.
- The Yandex URL (
Cleaned-Up Example
Here’s a revised version of your function with valid URLs and proper setup:
headers_referers = [] # Initialize the global list first def referer_list(): global headers_referers headers_referers.append('http://www.google.com/?q=') headers_referers.append('http://yandex.ru/yandsearch?text=') headers_referers.append('http://vk.com/profile.php?redirect=') headers_referers.append('http://www.usatoday.com/search/results?q=') headers_referers.append('http://engadget.search.aol.com/search?q=') headers_referers.append('https://www.google.ru/?hl=ru&newwindow=1')
This removes invalid snippets, fixes URL structure, and ensures the global list is properly initialized.
内容的提问来源于stack exchange,提问作者Ahmed Shady Elsadany

