Terminating while loops at anypoint within the loop by user input, using python

381 views Asked by At

I want the user to be able to terminate a nested loop by entering stop or some other keyboard input. The user is asked to enter an option a to g, followed by 8 if statements, Here is the code I wrote for the first if statement...

if option == "a":
    while True:
        try:
            name = input('\nEnter the students name: ')
            cm = input('Coursework mark: ')
            em = input('Exam mark: ')
            student = (name,cm,em)
            database.append(student)
        except :
            break

I had the idea of using try and except functions but I'm not sure how or if that would work, please help!

2

There are 2 answers

0
wpercy On

You can check the value entered each time and if it matches your keyword (or is in a list of keywords) you break.

if option == "a":
    while True:
        name = input('\nEnter the students name: ')
        if name == 'stop':
            break
        cm = input('Coursework mark: ')
        if cm == 'stop':
            break
        em = input('Exam mark: ')
        if em == 'stop':
            break
        student = (name,cm,em)
        database.append(student)

For checking against a list of stop keywords, you could do something like

stop_kws = ['stop', 'exit', 'quit']

...

if name in stop_kws:
    break

... 
0
Douglas On

If you are concerned about keyboard interrupts (such as Ctr + c or Delete), you can use the built-in Exception KeyboardIntertupt. This will allow you to fail gracefully:

if option == "a":
    try:
        name = input('\nEnter the students name: ')
        cm = input('Coursework mark: ')
        em = input('Exam mark: ')
        student = (name,cm,em)
        database.append(student)
    except KeyboardInterrupt as e:
        #
        # do something 
        #
        break

This would prevent your loop from crashing from interrupt requests.