Ad
How To Access A Variable From Inside A Function
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
Related Questions
- → What are the pluses/minuses of different ways to configure GPIOs on the Beaglebone Black?
- → Django, code inside <script> tag doesn't work in a template
- → React - Django webpack config with dynamic 'output'
- → GAE Python app - Does URL matter for SEO?
- → Put a Rendered Django Template in Json along with some other items
- → session disappears when request is sent from fetch
- → Python Shopify API output formatted datetime string in django template
- → Can't turn off Javascript using Selenium
- → WebDriver click() vs JavaScript click()
- → Shopify app: adding a new shipping address via webhook
- → Shopify + Python library: how to create new shipping address
- → shopify python api: how do add new assets to published theme?
- → Access 'HTTP_X_SHOPIFY_SHOP_API_CALL_LIMIT' with Python Shopify Module
Ad