In a user interactive program there are times that a program might need to ask the user to proceed or exit to determine whether the program needs to continue or not.
For this a prompt is necessary, and ask a user to decide and press some keys and depending on the user input, it will determine whether the code or program will continue running or not.
Below is a simple Python code that will ask a user to press y or n.
The code only shows how to detect the key that was pressed, of course the logic or the code can be inserted to other existing Python codes.
Python code snippet, works in Python 3:
Try this code, and see what's the difference. Code below will only accept Y,y, N or n.
Romans 12:12 ~ Rejoice in hope, be patient in tribulation, be constant in prayer.
All things passes away, be gentle and be patient in whatever situation you are in. Have faith, be strong.
For this a prompt is necessary, and ask a user to decide and press some keys and depending on the user input, it will determine whether the code or program will continue running or not.
Below is a simple Python code that will ask a user to press y or n.
The code only shows how to detect the key that was pressed, of course the logic or the code can be inserted to other existing Python codes.
Python code snippet, works in Python 3:
import sys
print("Make a choice press [y] to continue else [n] to exit")
proceed_or_exit = input()
if proceed_or_exit == 'y' or proceed_or_exit == 'Y':
print("Y was pressed")
#put some code here
pass
elif proceed_or_exit == 'n' or proceed_or_exit == 'N':
print("N was pressed")
#put some code here if necessary
sys.exit()
Try this code, and see what's the difference. Code below will only accept Y,y, N or n.
import sys
while True:
print("Make a choice press [y] to continue else [n] to exit")
proceed_or_exit = input()
if proceed_or_exit == 'y' or proceed_or_exit == 'Y':
print("Y was pressed")
#put some code here if necessary
pass
elif proceed_or_exit == 'n' or proceed_or_exit == 'N':
print("N was pressed")
#put some code here if necessary
sys.exit()
else:
print("Invalid input. Please enter 'y' or 'n'.")
Romans 12:12 ~ Rejoice in hope, be patient in tribulation, be constant in prayer.
All things passes away, be gentle and be patient in whatever situation you are in. Have faith, be strong.
Comments
Post a Comment