Python throws error, ‘return’ outside function, if you use return statement without defining a function. return statement can only be used within function definition and not outside it.

Consider this code example –

SuperHeroList = ['Captain America', 'Ironman', 'Hulk', 'Thor']
i = 0
while len(SuperHeroList) > i:
    return SuperHeroList[i]
    i = i+1

# Error: 'return' outside function

This code will throw error, return outside function because we have used return in while loop without defining any function.

The correct way of doing this is –

def returnSuperHero(ind = 0):
    return SuperHeroList[ind]

SuperHeroList = ['Captain America', 'Ironman', 'Hulk', 'Thor']
i = 0
while len(SuperHeroList) > i:
    print(returnSuperHero(i))
    i = i+1

    Tweet this to help others

Live Demo

Demo might not work in private window (incognito)

Comments

About the Author

akamit

I am Akash Mittal, an overall computer scientist. If you want to guest post, need help in your projects, want to advertise, Feel free to contact me at [email protected]

View All Articles