[英]Python: Why if-else oneline statement does not work with continue in else?
There is a code which web scraping and finds articles about python and displays their names and links.有一个代码,web 抓取并找到关于 python 的文章并显示其名称和链接。
The problem is if / else, if using tabs and a semicolon to separate, then everything works.问题是如果/否则,如果使用制表符和分号分隔,那么一切正常。 But if you write if / else in one line, and the 'continue' operator will be the body for else, then it will not work, referring to a syntax error.但是如果你在一行中写了 if / else ,而 'continue' 运算符将是 else 的主体,那么它就不起作用了,指的是语法错误。
SyntaxError: invalid syntax 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
Although, if instead of continue write something else, for example, print something or mathematical action, then everything works.虽然,如果不是继续写其他东西,例如,打印一些东西或数学动作,那么一切正常。 Is there something that I am missing out on, or is it something I need to remember and leave?有什么我错过了,还是我需要记住并离开?
Because continue
is a statement, not an expression.因为continue
是一个语句,而不是一个表达式。
x = foo if bar else baz
is meant to produce a value and then bind x
to that value.旨在产生一个值,然后将x
绑定到该值。 For that to be possible, foo
, bar
and baz
need to be things that can be evaluated (expressions).为此, foo
、 bar
和baz
需要是可以评估的东西(表达式)。
What should x
become in the case of在以下情况下x
应该变成什么
x = foo if False else continue
? x = foo if False else continue
?
Right...正确的...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.