The loop won't end because the condition in the while statement is checking if name is not equal to the integer 0, which is not the same as checking if name is an empty string. In Python, an empty string is represented as '', not 0.
To fix this, you can change the while loop condition to check if name is not an empty string, like this:
while name != '':
Alternatively, you can use the not keyword to check if name is a "truthy" value (i.e. not empty, not None, not False, etc.), like this:
while not name:
Either of these options should cause the loop to terminate once there are no more lines to read from the file.
Once you've fixed the loop condition, you can calculate the average age by keeping a running total of the ages and a count of the number of friends, like this:
def main():
friends_file = open('friends.txt', 'r')
name = friends_file.readline()
total_age = 0
friend_count = 0
while name != '':
try:
age = float(friends_file.readline())
name = name.rstrip('\n')
print(f'My friend {name} is {age:.0f}')
total_age += age
friend_count += 1
except:
print()
name = friends_file.readline()
friends_file.close()
if friend_count > 0:
avg_age = total_age / friend_count
print(f'The average age of my friends is {avg_age:.1f}')
main()
This code should print out the names and ages of each friend in the file, as well as the average age of all the friends (if there are any).