1

I don't know how but it seems that my ages keep getting mixed up within the while loop. It also doesn't include one of the names. The loop works within the IDE but I can't get it to write correctly into the text file.

def main():
friendsfile = open('friends.txt', 'w')
name = str(input('Enter first name of friend or Enter to quit : '))

while name != '':
    age = int(input('Enter age of this friend : '))
    name = str(input('Enter first name of friend or Enter to quit : '))
    friendsfile.write(name + '\n')
    friendsfile.write(str(age) + '\n')

friendsfile.close()

print('File was created')

main()

When I enter the names Justin with age 13, Scott with age 20, and Lucy with age 14 I get this written to the file.

Scott 13 Lucy 20

14

  • Welcome to Stack Overflow! Please tag your question with the appropriate programming language, not just tags like `loops`, `file` and `text-files`, those are too generic. – Étienne Laneville Oct 18 '19 at 16:57

1 Answers1

0

The problem is that the name variable gets updated before you print it. This should work:

while name != '':
    age = int(input('Enter age of this friend : '))
    friendsfile.write(name + '\n')
    friendsfile.write(str(age) + '\n') 
    name = str(input('Enter first name of friend or Enter to quit : '))
Étienne Laneville
  • 4,697
  • 5
  • 13
  • 29