Reputation: 81
I am starting to learn python and gotten this far to code a program to allow user input a series of lines of text to then output the longest line's number of characters. Could you please tell me what I need to add to display the longest text itself with the number of characters? thank you.
print('Please enter lines of text.')
print('Finish with a blank line.')
maxi = 0
text = '.'
while len(text) > 0:
text = input()
if len(text) > maxi:
maxi = len(text)
if maxi == 0:
print('No text entered.')
else:
print('The longest line of text was ' + str(maxi) + ' characters long.')
Upvotes: 2
Views: 1141
Reputation: 3570
You can do it by either introducing another variable to store the text of the longest line found, or replace the length in the maxi
variable with the text of the line and use len(maxi)
to compare lengths. While this choice may seem irrelevant in this scope, you can keep this in mind for larger-scale problems in the future, where the re-calculated function is more complex than len()
.
New variable:
This saves a little bit of processing by storing the length of the current longest line in a separate variable. However, you manually have to keep them both in sync.
print('Please enter lines of text.')
print('Finish with a blank line.')
maxi = 0
text = '.'
maxline = ""
while len(text) > 0:
text = input()
if len(text) > maxi:
maxi = len(text)
maxline = text
if maxi == 0:
print('No text entered.')
else:
print('The longest line of text was ' + str(maxi) + ' characters long.')
print(maxline)
Only storing the text of the longest line:
This way you always have to recalculate the current length of the longest line, but you are sure to always get the correct length.
print('Please enter lines of text.')
print('Finish with a blank line.')
maxi = ""
text = '.'
while len(text) > 0:
text = input()
if len(text) > len(maxi):
maxi = text
if maxi == "":
print('No text entered.')
else:
print('The longest line of text was ' + str(len(maxi)) + ' characters long.')
print(maxi)
Upvotes: 1
Reputation: 64
You have to save the maximum length text like this:
print('Please enter lines of text.')
print('Finish with a blank line.')
maxi = 0
maxiText = ''
text = '.'
while len(text) > 0:
text = input()
if len(text) > maxi:
maxi = len(text)
maxiText = text
if maxi == 0:
print('No text entered.')
else:
print('The longest line of text was ' + str(maxi) + ' characters long. The text is ' + maxiText)
Upvotes: 2
Reputation: 344
You have to save the test when he is higher than your previous maxText. And at the end you can now print it.
Upvotes: 0