Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
iteration stops
#1
quick question:

the following loop
list_nums= [i for i in range(15)]

    for i in range(len(list_nums)):
        if list_nums[i]<9:
            print(list_nums[i])
works as it should since all the numbers from 0 to 8 are printed,
but if I place the same loop into a function:
list_nums= [i for i in range(15)]
def fn():
    for i in range(len(list_nums)):
        if list_nums[i]<9:
            return(list_nums[i])
print(fn())
Only the first number is printed.
As far as I am understanding, the 'return' command interrupts the loop.

How do I make this function work the same way as the loop in the first code?
I am trying not to use any 'print' command inside the function.
Reply


Messages In This Thread
iteration stops - by d8a988 - Aug-31-2020, 12:12 PM
RE: iteration stops - by perfringo - Aug-31-2020, 03:48 PM
RE: iteration stops - by d8a988 - Aug-31-2020, 04:13 PM
RE: iteration stops - by jefsummers - Sep-01-2020, 09:11 PM
RE: iteration stops - by perfringo - Sep-01-2020, 10:38 PM

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020