+ 2

What is the reason for the last output being wrong?

Firstly let me say this is just code i was playing around with while trying to figure out the soloution (I know it's most likely very wrong) That being said it seems to output everything exactly how it should..right until the last one. I'm not looking for other ways/ the actual way to complete the challenge. If possible, I would love just the reason why the last one in my output fails while all of the others are correct. Thankyou :) My output - H12 T16 P19 G17 Expected output: H12 T16 P19 G18 My code: file = open("/usercode/files/books.txt", "r") i = 4 while i > 0: first_letter = (file.readline(1)) length = len(file.readline()) code = str(first_letter) + str(length) print(code) i = i - 1 file.close() Full problem: You have been asked to make a special book categorization program, which assigns each book a special code based on its title. The code is equal to the first letter of the book, followed by the number of characters in the title. For example, for the book "Harry Potter", the code would be: H12, as it contains 12 characters (including the space). You are provided a books.txt file, which includes the book titles, each one written on a separate line. Read the title one by one and output the code for each book on a separate line.

1st Feb 2022, 3:45 PM
Braiden Parsons
Braiden Parsons - avatar
3 odpowiedzi
+ 3
All line includes a \n character at end except for last line, use single readline and dont count '\n' to len(line) or subtract one expect for last one.
1st Feb 2022, 4:08 PM
Jayakrishna 🇮🇳
+ 5
Elliot , your last code is running perfectly in the code coach. may be you try it again? happy coding!
1st Feb 2022, 8:28 PM
Lothar
Lothar - avatar
+ 2
Thanks for the reply, I ended up confusing myself so started fresh and completed it with this code file = open("/usercode/files/books.txt", "r") for i in file: i = i.strip('\n') length = len(i) first_letter = i[0] print(str(first_letter) + str(length)) file.close() I appreciate you taking the time to help :)
1st Feb 2022, 5:11 PM
Braiden Parsons
Braiden Parsons - avatar