Reputation: 43
Hi there I have a program that I have been using for about a year now with no issues however now I want to make some changes. There is some code that I would like to remove from main function and rather put it in its own function however i am not sure on the correct way to return 2 of the variables and use them in other functions I have tried a few ways already and this is the last resort. The variables i need to return are listads_buy_str and listads_sell_str. The point of this is to continuously re-read the google sheet instead of rerunning the program every time
while i4a <= 2:
adlink = spreadsheet.cell(line1, 1).value
if adlink != '':
listads_buy.append(adlink)
line1 = line1 + 1
i4a +=1
listads_buy_str = listads_buy[0]
for ad in listads_buy[1:]:
if ad is not None:
listads_buy_str = listads_buy_str + ',' + str(ad)
i4a = 0
line1 = 18
listads_sell = []
while i4a <= 4:
adlink = spreadsheet.cell(line1, 1).value
if adlink != '':
listads_sell.append(adlink)
line1 = line1 + 1
i4a +=1
listads_sell_str = listads_sell[0]
for ad in listads_sell[1:]:
listads_sell_str = str(listads_sell_str) + ',' + str(ad)
Upvotes: 0
Views: 51
Reputation: 523
To return two values (or more) from a function, you can use encapsulation. It would look like this -
def fun():
return "hello", "world"
word1, word2 = fun()
print(word1, word2)
output:
"hello world"
I do not know what part of your code you'd like to put in a new function, but you'd return the two values you need to return like this and save them in the main function (or whatever function you are calling your new function from).
If all of this code is supposed to be in the function, it would look like this -
def you_function():
while i4a <= 2:
adlink = spreadsheet.cell(line1, 1).value
if adlink != '':
listads_buy.append(adlink)
line1 = line1 + 1
i4a += 1
listads_buy_str = listads_buy[0]
for ad in listads_buy[1:]:
if ad is not None:
listads_buy_str = listads_buy_str + ',' + str(ad)
i4a = 0
line1 = 18
listads_sell = []
while i4a <= 4:
adlink = spreadsheet.cell(line1, 1).value
if adlink != '':
listads_sell.append(adlink)
line1 = line1 + 1
i4a += 1
listads_sell_str = listads_sell[0]
for ad in listads_sell[1:]:
listads_sell_str = str(listads_sell_str) + ',' + str(ad)
return listads_buy_str, listads_sell_str
Please note that some of the variables you are addressing in the function are out of scope, so you'd have to send them to the function or something like that (depends on where in your code they are defined).
Upvotes: 2
Reputation: 1314
When you want to throw the output of a function inside another use * to unwrapp all returns. For example:
def foo():
return "hello", "world"
def bar(arg1, arg2):
print(arg1, arg2)
bar(*foo())
The result:
>>> hello world
Upvotes: 0