2

Recently I started diving into python a bit, unfortunately I am struggling in the very beginning. What is the best and the most elegant way to abort user input after an empty string is entered?

The approach I tried wont break the input no matter what I enter.

    def populate_list():
    list=[]
    while True:
        try:
            list.append(input("Enter values: "))
        except EOFError:
            break;
    return list
unknown
  • 461
  • 9
  • 23

2 Answers2

5

You're passing the result of input() directly into append(), with no intermediate step to check if it's empty.

You need to save the input in a separate variable and check if it's empty before appending it to your list.

Try this:

while True:
    answer = input("Enter values: ")
    if not answer:
        break
    lista.append(answer)
return lista
John Gordon
  • 29,573
  • 7
  • 33
  • 58
  • OP is using while loop there for `continue;` is better. – Kalana Jan 10 '20 at 17:00
  • @Kalana If I use `continue`, this loop will never exit... – John Gordon Jan 10 '20 at 17:01
  • What if the input is `False`? It will break anyway. What if `False` is a valid input? This will not work. – Raphael Jan 10 '20 at 17:01
  • @Raphael `input()` returns a string, so the value cannot be some other type such as a boolean. It could certainly be the literal strings `"True"` or `"False"`, but the OP did not say those needed special handling. – John Gordon Jan 10 '20 at 17:03
  • I think it is better to mention `continue` as well while keeping `break;` – Kalana Jan 10 '20 at 17:04
  • I tried here in the console and it breaks if the input is `False`. I know the input is a string, but this happens, crazy. Python 2.7 btw since the TAG is `python` and not `python3-x`. – Raphael Jan 10 '20 at 17:05
  • @Raphael are you using Python 2? The correct function for accepting keyboard user input in Python 2 is `raw_input()`, not plain `input()`. This is 2020, Python 2 is history. `python` tag should assume Python 3. – John Gordon Jan 10 '20 at 17:07
  • I don't use python 2, I tested by mistake and obtained this result. I typed `python` (Python 2.7.5 (default, Aug 4 2017, 00:39:18)) on my console instead of `python3` – Raphael Jan 10 '20 at 17:07
0
def populate_list():
    lista=[]
    while True:
        try:
            s_input = raw_input("Enter values: ")
            if not s_input:
                print("INVALID INPUT")
                break
            lista.append(s)
        except EOFError:
            break;
    return list
Wonka
  • 1,548
  • 1
  • 13
  • 20