Get the App
SLTechnology News&Howtos  ›  Development  › 

How to prompt the user to exit the program

Shulou Source: shulou.com Published: 2022-06-03 01:51:07 10月03日 Update

This article mainly explains "how to prompt the user to exit the program". The content of the explanation in the article is simple and clear, and it is easy to learn and understand. let's study and learn how to prompt the user to exit the program.

Bronze grade

# Bronze import sys user_input = input ("enter Q, exit the program") if user_input = 'qbronze: sys.exit ()

It should be the most low way to use input to judge user input, right? Not only need to enter, but also need the user to hit enter in order to complete the parameter acquisition. It is suitable for the young contestant who starts the Python for a week.

Silver grade

# Silver import msvcrt user_input = msvcrt.getche () if user_input.decode () = = 'Qothers: exit ()

The msvcrt module allows you to access many functions in the Microsoft Visual C / C + + runtime library (MSVCRT), which dynamically listens to a single char character and then returns byte bytes. So when your exit is not a single character, but a string, it needs to be further encapsulated.

The rank of king

# import msvcrt quit_command of Kings = 'quit' listening_str =' 'while True: user_input = msvcrt.getche () if isinstance (user_input, bytes): user_input = user_input.decode () if user_input = ='\ baked: listening_str = listening_str [:-1] elif user_input in ['\ n' '\ r']: listening_str =''else: listening_str + = user_input print (' listening_str now is:% s'% listening_str) if listening_str = = quit_command: exit ()

We monitor the user's input in real time through a while loop and empty the string cache when the user returns. And the user's delete and backspace operation is supported. The function is improved compared with the first two which only support a single decision. Take a look at the test example in the following figure:

Thank you for your reading, the above is the content of "how to prompt the user to exit the program". After the study of this article, I believe you have a deeper understanding of how to prompt the user to exit the program. The specific use of the situation also needs to be verified in practice. Here is, the editor will push for you more related knowledge points of the article, welcome to follow!

Tags: User program prompt character input level learning content single string king bronze silver support following figure function function dynamic parameter byte Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Xiaomi MySQL Shulou Tech Info OPPO Reno Shulou Information