Python Forum

Full Version: Print the longest str from user input
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Essentially, the user inputs random strings and i am trying to reprint the longest string that the user input (so far it only prints the first non-capital letter). A bit lost on how to fix this.

loopEnd = ""

n = (input("Input: "))
longString = max(n)

while n != loopEnd:
    n = str(input("Input: "))
    if n == loopEnd:
        print("Longest input was", "'",longString,"'")
you only need one input statement.

In your while loop, append each input to a string
include a keyword to terminate input , like 'quit'
after exiting the input loop, check for and print longest entry in list
Sorry i am very new and very confused. What would that actually look like in my script?
Some observations about your code:

- input is string, so no need to use str() for converting
- no need to define n before while loop. Use instead 'while True' and break
- use Larz60+ advice - append user answers to list and print out longest

As this is homework I provide 3.8-only compatible solution which probably will not pass automagic check but gives general idea:

values = []                                             # list to collect user entered strings
while (answer := input('Enter input: ')) != '':         # while loop which assigns user input to answer and checks equality to ''
    values.append(answer)                               # appends answers to values list

print(f'Longest input was {max(values, key=len)}')      # prints out longest element in values list
Thanks a bunch. I'm assuming that i need an initial input to declare answer? (my IDE otherwise states its undeclared. Furthermore apparently line 2 a : is expected even though its present?
As stated - this is only Python 3.8 compatible code (using walrus operator).

Task can be described: 'collect user input until break and find longest input'

So


# assign empty list to a name where user input will be collected

# while True loop - executes until 'break' encountered in the body of loop
# assign name to user input
# check if user input is break symbol or word, if so - break loop
# append answer to list of collected inputs

# print max value by length in list