0

NORMAL CODE:

s = list(range(1))

for i in s:
    print(i)

RESULT: (Vertical Display)

0
1
2
3
4

I want the same result using a function which i can assign to a variable and use inside a string literal.

def results():
    for i in s:
        print(i)

numbers = results()
report = f"Here is the list on numbers: {numbers}"

RESULT: None

When i use 'return' inside function, i get just one value.

Any better way to do this???

4
  • 2
    Read about Python generator functions. Commented Jul 21, 2020 at 16:00
  • Did you mean: print(s)? Commented Jul 21, 2020 at 16:00
  • Generators functions are what you're looking for. Commented Jul 21, 2020 at 16:00
  • Actually, a generator won't do what you want, since you'll need to call your function in a loop. Commented Jul 21, 2020 at 16:00

3 Answers 3

1

The function needs to collect all the results into a list instead of printing them. You can use a list comprehension for this.

def results():
    return [i for i in s]
Sign up to request clarification or add additional context in comments.

Comments

1

When you return within a function in python in a for loop, it will return the singular value and cease function execution. In this particular case, this should work if your desire is only string formatting:

def results():
    ret = "\n"
    for i in s:
        ret += str(i) + "\n"
    return ret

s = [1,2,3,4]

numbers = results()
print(f"Here you go: {numbers}")

3 Comments

This would be better is s was a parameter of results().
@quamrana I was just trying to match the structure of his existing code
Ok, I see. I normally like to make another small improvement in my answers. But also: As a programmer you should try very, very, very hard not to use globals.
0
def results():
    s = list(range(10))
    for i in s:
        print(i)
    return s

numbers = results()
report = f"Here is the list on numbers: {numbers}"

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.