-1

Im trying to display some values from another program using this one but also calculating the average the numerical values of the program, however, I did not get to the point of figuring out how to calculate the average because I keep getting a value error that says could not convert string to float ''.

def main():
    friends_file = open('friends.txt', 'r')
    name = friends_file.readline()
    while name != '':
        age = float(friends_file.readline())
        name = name.rstrip('\n')
        print(f'My friend {name} is {age:.0f}')
        print()
        name = friends_file.readline()
    friends_file.close()

    
main()

This is the code I used

confused
  • 19
  • 2
  • 1
    The type of your variable, `name` is a `str`. In your `while` loop you are comparing it to a value of type `int` (0). These will never be equal. Note, however, that this isn't an idiomatic way of looping through the lines of a file. See https://stackoverflow.com/a/48124263/442945 – Nathaniel Ford Mar 27 '23 at 22:20
  • I changed the zero but it still repeats – confused Mar 27 '23 at 22:23
  • What did you change it to? `"0"` and `''` are unlikely to work for the same reason you need to, two lines later, strip out a newline character. One way you can debug is to print out `name` immediately after the while loops so you can see what it is trying to compare. But, a better way is to use `for line in ...`, which will iterate over each line one time. – Nathaniel Ford Mar 27 '23 at 22:36
  • Also, as a suggestion, you should include sample contents for `friends.txt` - a good answer will be able to take that sample input and show you how the suggested fix operates over it. Right now we are guessing what `name` actually is. – Nathaniel Ford Mar 27 '23 at 22:37

2 Answers2

0

With this input file friends.txt:

abby
21
bianca
28
claire
52
diane
11

And this code:

def main():
  with open("friends.txt", "r") as f:
     lines = [l.rstrip('\n') for l in f.readlines()]
     friends = {lines[(idx*2)]: lines[(idx * 2) + 1] for idx in range(len(lines) // 2)}

  for name, age in friends.items():
     print(f"My friend {name} is {age}")

main()

You get a result close to what you want. This is not the most efficient approach (you end up looping over all the values two and a half times), but it is a cleaner way of managing the various things you're attempting - taking, for instance, every other line as the age. I'm omitting casting it to a value, but this is a trivial step. It is generally good to break up your data ingestion and display this way as well - it makes things like taking averages a lot simpler.

Nathaniel Ford
  • 20,545
  • 20
  • 91
  • 102
-1

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).