-1

how to break loop with keypress ("Y"):

I want to stop function by pressing key "Y", not CTRL+C.

Here's my code:

def main():
    while True:
        try:
            num = int(input("Enter a number: "))
            if (num % 2) == 0:
                print("Even number")
            elif (num % 2) != 0:
                print("Odd number")
        except (ValueError, Exception):
            print("Inappropriate number")


if __name__ == "__main__":
    main()
0

1 Answer 1

0

You can read the input in a variable, check if it's Y and then convert it to an int

def main():
    while True:
        try:
            val = input("Enter a number: ")
            if val == 'Y':
              break

            num = int(val)
            if (num % 2) == 0:
                print("Even number")
            elif (num % 2) != 0:
                print("Odd number")
        except (ValueError, Exception):
            print("Inappropriate number")


if __name__ == "__main__":
    main()
Sign up to request clarification or add additional context in comments.

2 Comments

One could also use a signal handler for this purpose, namely a user-defined signal like SIGUSR1, where you would set a variable in the handler and check it later in the while loop.
@kali Signals have nothing to do with this problem.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.