Nilotpal Choudhury
Nilotpal Choudhury

Reputation: 135

In Python, can a loop be used within a function?

I am just learning python and was trying to define a function using a for loop. The code is as follows -

def chk(hilist):
``` The function returns the output of the enumerate function as (x1,y1) (x2,y2)...
```
    for item in enumerate(hilist):
        return item

I ran the above function for the input 'string' as below -

abc = chk('string')
abc

The output came out as (0,s).

If I ran the regular for function and the output will be as follows - (0, 's') (1, 't') (2, 'r') (3, 'i') (4, 'n') (5, 'g')

Can someone please help me understand what I am doing wrong ? Thanks in advance.

Upvotes: 1

Views: 508

Answers (3)

xoxoxoxoxoxo
xoxoxoxoxoxo

Reputation: 40

I think the simplest solution would be to use print(item) if you wanna get all the enumerated values from 'string':

def chk(hilist):
    for item in enumerate(hilist):
         print(item)

This worked smoothly for me.

Upvotes: 0

silver
silver

Reputation: 126

Return will break the function immediately. So, you have to save the result in a list and return it:

def chk(hilist):
    """ The function returns the output of the enumerate function as (x1,y1) (x2,y2)...
    """
    ret_list=list()

    for item in enumerate(hilist):
        ret_list.append(item)
    return ret_list

Upvotes: 1

Amin Guermazi
Amin Guermazi

Reputation: 1742

in Python (and in all programming languages), using the return keyword will get you out of the function, so I propose two solutions:

  • solution 1: store your tuples in a list and then return the list itself
  • solution 2: replace return with yield (but if you want to print returned items convert it to a list ex: list(abc(some_arguments)))

Upvotes: 1

Related Questions