lundi 28 octobre 2019

Python: Why if-else oneline statement does not work with continue in else?

There is a code which web scrapping and finds articles about python and displays their names and links.

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.

SyntaxError: invalid syntax

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?

Aucun commentaire:

Enregistrer un commentaire