Xin chào! Em mới học python gần đây, e có viết 1 chương trình nhỏ, e muốn hỏi là có cách nào để mà lặp lại chương trình đó theo kiểu: cho chạy hết chương trình, ấn Enter để chạy lại từ đầu, còn ấn Esc để thoát chương trình không ạ?
Cần hướng dẫn cách lặp lại chương trình trong python
Bạn thử cách này xem sao.
You can use Keyboard module to detect keys pressed. It can be installed by using
pip
. You can find the documentation here. Keyboard API docspip install keyboard
check the below code to understand how it can be done.
import sys import keyboard a=[1,2,3,4] print("Press Enter to continue or press Esc to exit: ") while True: try: if keyboard.is_pressed('ENTER'): print("you pressed Enter, so printing the list..") print(a) break if keyboard.is_pressed('Esc'): print("\nyou pressed Esc, so exiting...") sys.exit(0) except: break
3 Likes
Mình cảm ơn bạn nhiều ^^
1 Like