Python Forum
Print the longest str from user input - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: Homework (https://python-forum.io/forum-9.html)
+--- Thread: Print the longest str from user input (/thread-22218.html)



Print the longest str from user input - edwdas - Nov-04-2019

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,"'")



RE: Print the longest str from user input - Larz60+ - Nov-04-2019

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


RE: Print the longest str from user input - edwdas - Nov-04-2019

Sorry i am very new and very confused. What would that actually look like in my script?


RE: Print the longest str from user input - perfringo - Nov-04-2019

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



RE: Print the longest str from user input - edwdas - Nov-04-2019

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?


RE: Print the longest str from user input - perfringo - Nov-04-2019

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