S
S
swww2020-07-14 21:46:20
Python
swww, 2020-07-14 21:46:20

How to make a function return all elements?

How to make a function return all elements?

a = [1,2,3,4,5,6,7]

def get(a):
    for i in a:
        return i

def main():
    s = get(a)
    print(s+1)

main()

Answer the question

In order to leave comments, you need to log in

2 answer(s)
D
Deleting Account, 2020-07-14
@swww

What is it all about. What is the purpose of this program. I would write like this:

numbers = [number for number in range(1, 7)]

def main():
      for number in numbers:
            print(number)

if __name__ == "__main__":
      main()

How to make a function return all elements?

If you want to create a generator, then read about it here https://docs.python.org/3/tutorial/classes.html#ge...
numbers = [number for number in range(1, 7)]

def numbers_generator(numbers):
      for number in numbers:
            yield number

def main():
     for number in numbers_generator(numbers):
          print(number + 1)

if  __name__ == "__main__":
    main()

Although this code, as for me, does not make any sense.

S
Sergey Pankov, 2020-07-14
@trapwalker

Because the exit from the function occurs at the first returned return with the value that first got there.
Learn materiel. Read carefully.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question