howtothings.co.uk
Prompting users for input, then verifying what they've inputted - Printable Version

+- howtothings.co.uk (https://www.howtothings.co.uk)
+-- Forum: Computing (https://www.howtothings.co.uk/forumdisplay.php?fid=4)
+--- Forum: Programming Support, Graphic Design and Tutorials (https://www.howtothings.co.uk/forumdisplay.php?fid=14)
+--- Thread: Prompting users for input, then verifying what they've inputted (/showthread.php?tid=253)



Prompting users for input, then verifying what they've inputted - Mark - 13-07-2010

Here's how to make two simple scripts that'll check if the user has inputted correctly.

Input a number

Prompting the user to input a number, if they don't enter a number then it'll re-prompt them.

[code=python]
def number():
input_number = raw_input("Please input a number: ")
if not input_number.isdigit():
print "Error: That is not a number. Input a number"
number()
if input_number.isdigit():
print "That is a number! Thank you. \n"
raw_input("Press enter to exit..")
number()
[/code]


Input a word

Prompting the user to enter a word, if they don't enter a single word it re-prompts.

This is essentially the same as the above script, except instead of "isdigit" we'll be using "isalpha".

[code=python]
def start():
letter_input = raw_input("Please input a letter: ")
if not letter_input.isalpha():
print "Error: That is not a letter. Please input a letter"
start()
if letter_input.isalpha():
print "That is a letter! Thank you. \n"
raw_input("Press enter to exit..")
start()
[/code]


Simple yet effective. :yep