Siva Reddy
Siva Reddy

Reputation: 73

How to Return the values one by one from function in python

for example

def ex(n):
    for i in range(n):
        return i
n = int(input("enter : " ))
x = ex(n)
print(x)

i'm trying to print values from 0 to 10 one by one. But, it just returning only 0 with this method.

Upvotes: 0

Views: 662

Answers (2)

ppwater
ppwater

Reputation: 2277

That's because return gets out of the function (stops the function) and returns one value

you can try this:

def ex(n):
    for i in range(n+1):
        print(i)
n = int(input("enter : " ))
x = ex(n)
print(x)

or this if you need a returning value

def ex(n):
    nlist = []
    for i in range(n+1):
        nlist.append(i)
    return nlist
n = int(input("enter : " ))
x = ex(n)
for i in range(len(x)):
    print(x[i])

or just use yield:

def ex(n):
    for i in range(n+1):
        yield i
n = int(input("enter : " ))
x = ex(n)
for i in x:
    print(i)

Upvotes: 3

Carbon
Carbon

Reputation: 3943

So, there's a couple ways of playing this, and it depends on your intent. If you want ex to return a string of the numbers 0 to 10, given 10, you can just do:

def ex(n):
    return " ".join([str(x) for x in range(n+1)])

If you want to return a generator, a thing that returns an iterable, you can do:

def ex(n):
    for i in range(n+1):
        yield i
n = int(input("enter : " ))

for x in ex(n):
    print(x)

Upvotes: 1

Related Questions