How can I get a user to break out of a loop via text input?

Viewed 82

Lets say a teacher wants to add n number of students to a database.

n = 1000
students = dict(input("enter students name and grade. Example 'Student C: '").split()
    for _ in range(n))
print(students)

This is fine if we have 1000 students, but what if the teacher wants to finish after 10 students? Is there a way we can input "quit" to break the loop?

4 Answers

Rather than embed a generator expression in a single call to dict, build your dict as you process in the input.

n = 1000
students = {}
for _ in range(n):
    x = input("enter students name and grade. Example 'Student C: '")
    if x == "quit":
        break
    # You might want to do more error checking here.
    student, grade = x.split()
    students[student] = grade

A little more advanced, you can make use of the two-argument form of iter (see below) to terminate the loop if quit is entered, and use itertools.islice to limit the loop to n entries.

from itertools import islice


n = 1000
students = {}
for x in islice(iter(lambda: input("..."), "quit"), n):
    student, grade = x.split()
    students[student] = grade

As you might notice, this allows you (ignoring any error checking while splitting the line of input) to go back to your original idea of a generator in a call to dict:

from itertools import islice


n = 1000
students = dict(x.split() for x in islice(iter(lambda: input("..."), "quit"), n))

Finally, if you were only using n as a way to avoid reading input forever, you can omit it, as the user can now enter quit any time they like:

students = dict(x.split() for x in iter(lambda: input("..."), "quit"))

Also, another way to create a zero-argument callable to use as the first argument to iter is to use functools.partial:

from functools import partial


students = dict(x.split() for x in iter(partial(input, "..."), "quit"))

What does iter(x, y) do?

(The two-argument form of iter takes a function to call repeatedly, and produces the return value of that function until the function returns the second argument. iter(lambda: input("..."), n) is equivalent to

def iter(f, stop):
    while True:
        x = f()
        if x == stop:
            break
        yield x

)

What does islice(x, y) do?

This produces a new iterator that returns only the first y elements of x, if it has more than y elements. It is roughly equivalent to

def islice(x, y):
    while y:
        yield next(x)
        y -= 1

Yes there is a way. If you are using python 3 use input() function which will capture the entered Stdin text into a string. Match that string with the word "quit" and a conditional if statement. i.e. if string == "quit" then exit() or something similar.

A better way I think would be to ask how many entries are required in the beginning no? rather than constantly entering input in a while loop. Just my 0.2 cents.

Store the input from user to a variable and check if it is the value is quit or not if it is use break statement to exit the loop or add the input to dictionary.

m = {}
while True:
    grade = input("enter students name and grade. Example 'Student C: '").split()
    if grade[0] == 'quit':
       break
    else:
        m[grade[0]] = grade[1]


print(m)
Related