If i code:
a = [56, 2, 5, 2, 5, 2, 6, 2, 6, 2, 56, 2, 6, 2, 52, 5, 2]
def func1(a3):
for i in range(len(a)-1):
if a[i] a[i 1] == 58:
print(a[i])
func1(a)
I get in output: 56 2 56
But if i code return a[i] instead of print(a[i]) i get only first suitable number How can i fix it?
CodePudding user response:
Your code exits out of the function when it encounters a return statement. So the following iterations dont happen. If you need a list of values that you were going to print, take a empty array and then append to it whenever you want to print and then return that list when the for loop is over
a = [56, 2, 5, 2, 5, 2, 6, 2, 6, 2, 56, 2, 6, 2, 52, 5, 2]
def func1(a3):
ans = []
for i in range(len(a)-1):
if a[i] a[i 1] == 58:
ans.append(a[i])
return ans
func1(a)
CodePudding user response:
The return
function causes your function to "stop running", returning the value passed in parameter. If you want to return more than the first element, you might want to create a list in which you append the desired elements.
a = [56, 2, 5, 2, 5, 2, 6, 2, 6, 2, 56, 2, 6, 2, 52, 5, 2]
def func1(a3):
result = []
for i in range(len(a)-1):
if a[i] a[i 1] == 58:
result = [a[i]]
func1(a)