Question

When using programs like PySripter the following code doesn't except correctly...

Basically, the input value has to be either 1, 2, 3, 4 or 10 if it's not any of these numbers then it will make them try again.

If they chose a number what is in the list then it will continue on to the next part of the script.

In PySripter when I run this it pops up a box for me to input the value but if I press cancel or the red cross it sends the "KeyboardInterrupt" exception but I can't exit the script/stop the script from running..

dvalues = [1, 2, 3, 4, 10]
d1 = None

while d1 is None:
    try:
        d1= int(input("First Value "))
        if not d1 in dvalues:
            d1= None
            print("Can't do this")
    except KeyboardInterrupt:
        print('Canceled')
        continue
    else:
         pass

Anyone know what I'm doing wrong?

EDIT

New error, is it should exit the whole script if exited on the first, second or whatever input instead of continuing...

tot = int(15)
dvalues = [1, 2, 3, 4, 5, 10]

while tot > int(0):

    d1 = None
    while d1 is None:
        try:
            d1 = int(input("First Value"))
            if not d1 in dvalues:
                d1 = None
            else:
                print("Fail")
        except KeyboardInterrupt:
            break

    d2 = None
    while d2 is None:
        try:
            d2 = int(input("Second Value"))
            if not d2 in dvalues:
                d2 = None
            else:
                print("Fail")
        except KeyboardInterrupt:
            break

    total = d1+d2
Was it helpful?

Solution

Instead of continue, try using break. It will end the loop instead of continuing its execution. Also, the else: pass part is redundant.

OTHER TIPS

You probably discovered this by now, but you can...

import sys
sys.exit(1)

...to exit your script early.
exit() accepts an error code, with 0 meaning "no error"

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top