Python – Case where Print works but Return doesn't in a basic function

Question:

So as the title suggests, I made a simple function like this:

import sys

string = sys.argv[1]
def position():
        for index in range(len(string)):
                if string[index] == 'A':
                        print(int(index+1))

position()

Which, when used with a test string like "AABABC", will return the position of each "A" as a number.

Here I increment the index with 1 because I noticed the range is starting at 0. While I can pass 1 or any number I want to it to make it start to that, it will remove/not print everything I want. So I found that this worked best in this case.

Everything works here. What doesn’t is when I replace the print in the function, with a return statement:

import sys

string = sys.argv[1]
def position():
        for index in range(len(string)):
                if string[index] == 'A':
                        return int(index+1)

print(position())

Here I only show this edit to the code, but I did try a couple of different things, all with a similar results (in that it doesn’t work):

  • not using int() and instead incrementing the index with += -> doesn’t work in this specific case?
  • using another variable (a naive test which obviously didn’t work)

Compared to the other "questions" that might be seen as duplicate/similar ones to mine, I’m using print() on the function outside of it in the last example. So the problem is likely not coming from there.

I don’t think my indentation is wrong here either.

To give even more details on "what doesn’t work", when I use return instead of print here and using a test string like "ABABACD", it would output the correct "136" as a result. But when using return along with the other failed attempt I listed earlier, it would only output "1" instead….

Asked By: Nordine Lotfi

||

Answers:

Return ends the run of the function whether or not there are more "loops" left. If you want to have it return all of the positions there is an "A" in your string you can try something like this:

def position():
    return [i+1 for i, j in enumerate(string) if j == "A"]

same as

def position():
    pos = []
    for i, j in enumerate(string):
        if j == "A":
            pos.append(i+1)
    return pos

It can also be done using regular expressions:

import re

[i.start()+1 for i in re.finditer("A", string)]
Answered By: goalie1998
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.