‘return’ outside function – Python Error

Total
0
Shares

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)

Sign Up for Our Newsletters

Get only the best articles delivered to your mail

You May Also Like