-3

I am trying to understand why the second function with the return inside the conditionals, will only loop once. l = [1,2,3,45,6,7] First working example with print:

def xyz(l):
    for i in l:
        if i==7:
            print('7 found')
        else:
            print('7 not found')

xyz(l)

Output:

7 not found
7 not found
7 not found
7 not found
7 not found
7 found

Now the function with return statement:

def xyz(l):
    for i in l:
        if i==7:
            return '7 found'
        else:
            return '7 not found'

Result:

'7 not found'

The loop runs only once for the first element and returns the else value. Please don`t downvote this, this is a thing I need to understand before continuing to learn python. Does the return statement exit the loop?

Thanks in advance

DeepSpace
  • 78,697
  • 11
  • 109
  • 154
Mortada
  • 35
  • 4
  • 2
    Because this is what `return` is doing. It **returns** from the function, which will stop any loop. What did you expect it to do? – DeepSpace Nov 12 '18 at 11:33
  • 6
    Possible duplicate of [What is the purpose of the return statement?](https://stackoverflow.com/questions/7129285/what-is-the-purpose-of-the-return-statement) – DeepSpace Nov 12 '18 at 11:34
  • 1
    @DeepSpace I expected it to loop through all the elements first before quitting – Mortada Nov 13 '18 at 14:11

1 Answers1

0

'return' word ends the execution of the function, 'return something' means the value the function is trying to achieve is: something; it can be visualized as the answer of the function.

'print' word only displays a certain string (text) on the console.