2

I need your help. Why I get this error? title is assigned as global variable, so I should get 'None' printed out, right?

def get_history_events(requests, BeautifulSoup):
    global title, facts
    title = facts = None

    url = 'https://cs.wikipedia.org/wiki/Hlavn%C3%AD_strana'
    header = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:88.0) Gecko/20100101 Firefox/88.0'}

    r = requests.get(url, headers=header).text
    soup = BeautifulSoup(r, 'lxml')

    table = soup.find('div', class_ = 'mainpage-block calendar-container')
    title = table.find('div', class_ = 'mainpage-headline').text
    facts = table.find('ul').text

print(title)
# NameError: name 'title' is not defined
Konrad Rudolph
  • 530,221
  • 131
  • 937
  • 1,214
ton1czech
  • 41
  • 4

3 Answers3

1

You need to either declare the variable in global scope first

eg:

title = None
def get_history_events(requests, BeautifulSoup):
    global title, facts
    title = facts = None

    url = 'https://cs.wikipedia.org/wiki/Hlavn%C3%AD_strana'
    header = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:88.0) Gecko/20100101 Firefox/88.0'}

    r = requests.get(url, headers=header).text
    soup = BeautifulSoup(r, 'lxml')

    table = soup.find('div', class_ = 'mainpage-block calendar-container')
    title = table.find('div', class_ = 'mainpage-headline').text
    facts = table.find('ul').text

print(title)

or execute your funtion before calling print on it: eg.:

def get_history_events(requests, BeautifulSoup):
    global title, facts
    title = facts = None

    url = 'https://cs.wikipedia.org/wiki/Hlavn%C3%AD_strana'
    header = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:88.0) Gecko/20100101 Firefox/88.0'}

    r = requests.get(url, headers=header).text
    soup = BeautifulSoup(r, 'lxml')

    table = soup.find('div', class_ = 'mainpage-block calendar-container')
    title = table.find('div', class_ = 'mainpage-headline').text
    facts = table.find('ul').text

get_history_events(<imagine your args here>)
print(title)

1

You haven't run your function yet - so your global statement has never been seen by running code.

To make your code work, call your function first:

get_history_events(...)
print(title)

Here is an excellent set of examples for global use: https://www.programiz.com/python-programming/global-keyword

KateYoak
  • 1,591
  • 3
  • 18
  • 34
-1

Thanks to everyone. Fixed. Working properly.

ton1czech
  • 41
  • 4