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