Harry Tong
Harry Tong

Reputation: 259

How to get multiline input with empty lines - Python

I can get Multiline input with this loop but it stops as soon there is an empty line

    lines = []
    line = input()
    while True:
        if line:
            line = input()
            lines.append(line)

        else:
            return lines
            break

For example how could i get an input of

1 cup butter, melted
3 cups white sugar
1 tablespoon vanilla extract
4 eggs


1 1/2 cups all-purpose flour
1 cup unsweetened cocoa powder
1 teaspoon salt
1 cup semisweet chocolate chips 

Upvotes: 2

Views: 1354

Answers (2)

Jayme Tosi Neto
Jayme Tosi Neto

Reputation: 1239

You need to use something to mark the end of the input. Right now your code stops on empty lines. Because line is going to get the blank value '' that evaluates to False. So your iteration breaks. You could use a mark. For example, end_of_list;:

lines = []
line = input()
while True:
    if line != 'end_of_list;': 
        line = input()
        lines.append(line)

    else:
        return lines
        break

You could also add some more condition to avoid appending blank values. It depends of your goals.

Upvotes: 4

Wonka
Wonka

Reputation: 1886

This happens because if line = "" (Empty text)

your IF LINE: assert it to False and you return lines and break

So try to change you if

if line or line == "":

Upvotes: 1

Related Questions