【发布时间】:2019-10-28 18:36:54
【问题描述】:
有一个代码用于网络抓取并查找有关 python 的文章并显示它们的名称和链接。
问题是if / else,如果使用制表符和分号分隔,那么一切正常。但是如果你在一行中写了if / else,而'continue'操作符将是else的主体,那么它就不起作用了,指的是语法错误。
SyntaxError: 无效语法
def habr_python_articles():
pageid = 1
headline_link_dict = {
}
for pageid in range(1, 10):
url = 'https://habr.com/en/all/page%d/' % pageid
response = requests.get(url)
soup = BeautifulSoup(response.text, 'html.parser')
for headline_tag in soup.findAll('a', {'class': 'post__title_link'}):
result = str(headline_tag.contents).lower().find('python')
# TODO if else continue one line statement
#print(str(headline_tag.contents) + '\n\t' + headline_tag['href']) if result > 0 else continue
if result > 0:
headline_link_dict[str(headline_tag.contents)] = headline_tag['href']
else:
continue
return headline_link_dict
虽然,如果不是继续写其他东西,例如,打印一些东西或数学动作,那么一切正常。有什么我错过了,还是我需要记住并离开?
【问题讨论】:
-
因为
continue是一个语句,而不是一个表达式。 -
在循环结束时不需要
continue。无论有没有它,都会发生完全相同的事情。您的目标是在一行中获得if语句吗? -
A if C else B是一个返回值的表达式。它不等同于多行流控制结构if C:\ndoA()\nelse: doB()。除了换行符,请注意冒号的存在。
标签: python if-statement continue