Ad

How To Access A Variable From Inside A Function

- 1 answer

File structure:

def mainStuff():
  for a in aa:
    aName = aa[a].split('')[-1].split('-')[5]

   # Do other important stuff so I can't return early

def replaceOne():
  if aName.split('_')[1] == "android":
    aName = aName.replace('_android','Android')

  return aName

def replaceTwo():
  if aName.split('_')[4:7] == "abc":
    aName = aName.replace('abc','Tom')

  return aName

I want the two if statement blocks to run consecutively, so I have decided to put them in separate functions. However, as aName is generated when the loop runs, my functions are unable to get the variable. I cannot use return as the function has to run to its completion for my output to work.

I have tried using yield but the function just ends prematurely.

How do I get aName and pass it through my other functions?

Ad

Answer

You need to pass aName to your functions a parameter. See the parameters section in this tutorial. In your case, try adjusting your code as follows:

def mainStuff():
    for a in aa:
        aName = aa[a].split('')[-1].split('-')[5]
        aName = replaceOne(aName)
        aName = replaceTwo(aName)

def replaceOne(aName: str) -> str:
    if aName.split('_')[1] == "android":
        aName = aName.replace('_android','Android')
    return aName

def replaceTwo(aName: str) -> str:
    if aName.split('_')[4:7] == "abc":
        aName = aName.replace('abc','Tom')
    return aName
Ad
source: stackoverflow.com
Ad