Skip to content
Advertisement

Putting else statement in a loop [closed]

All I want to do is add an else statement at the end e.g else: print(‘Incorrect’) but I keep getting an error saying unexpected indent. Any help would be greatly appreciated.

people = [('John', 36, 'M'), ('Rachel', 24, 'F'), ('Deardrie', 78, 'F'), 
              ('Ahmed', 17, 'M'), ('Sienna', 14, 'F')]
    
def average_age(members,gender):
    ages = []
    for g in members:
        if g[2] == gender:
            ages.append(g[1])
    return sum(ages) / len(ages)
        else:
            print('No matches found.')
    
average_age(people, 'M')
 File "<ipython-input-95-47432c006dc9>", line 7
    else:
    ^
IndentationError: unexpected indent

Advertisement

Answer

(You cant use else without an if) and there cant be anyting after a return

You can check the length of ages before returning

if something is in there return

else you can print something

def average_age(members,gender):
    ages = []
    for g in members:
        if g[2] == gender:
            ages.append(g[1])
    if len(ages) > 0:
        return sum(ages) / len(ages)
    else:
        print('No matches found.')

average_age(people, 'M')
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement