web scraping – Variable is not assigned a value within a function but assigned outside of a function

I am writing web scraping code and it works well when each line is written in a separate cell but doesn’t work when put inside of a function.

NameError name ‘soup’ is not defined with this code:

def get_data(url):
    r=requests.get(url)
    soup=bs4.BeautifulSoup(r.text,"lxml")
    return soup

Works fine when separately:

r = requests.get(url)

soup = bs4.BeautifulSoup(r.text,"lxml")

The same exact problem with other functions. Really can’t figure out why.