•
•
•
•
What is DaniWeb IT Discussion Community?
You're currently browsing the Python section within the Software Development category of DaniWeb, a massive community of 391,703 software developers, web developers, Internet marketers, and tech gurus who are all enthusiastic about making contacts, networking, and learning from each other. In fact, there are 3,196 IT professionals currently interacting right now! Registration is free, only takes a minute and lets you enjoy all of the interactive features of the site.
Please support our Python advertiser:
Views: 1428 | Replies: 6
![]() |
I have searched google, but found nothing, I'm not even sure if this is what you call it. But in my program I am writing, if someone hits enter by mistake without entering anything, it errors, is there a way to avoid that?
Another error that happens is if the program is expecting a number and gets a letter.
Another error that happens is if the program is expecting a number and gets a letter.
•
•
Join Date: Dec 2006
Posts: 384
Reputation:
Rep Power: 2
Solved Threads: 52
•
•
•
•
Another error that happens is if the program is expecting a number and gets a letter.
if input_string.isdigit(): do_something() else : print "Enter a number"
•
•
•
•
if someone hits enter by mistake without entering anything, it errors, is there a way to avoid that?
if (input_string) and len(input_string) > 0 : ## -----or try : input_str = raw_input( "Enter a Number --> " ) except : print "No number entered" ## -----or the old stand by input_str = "" while (len(input_str) < 1 ) or (not input_str.isdigit() ): input_str = raw_input( "Enter a Number --> " )
•
•
Join Date: Jul 2006
Posts: 562
Reputation:
Rep Power: 4
Solved Threads: 72
Well, in general, you should validate your input. What that means is making mathematically sure that the user enters a correct something, or else the program prints an error and continues on with life. That's what the first code snippet above does: if the user didn't type a (non-negative!) integer, he gets an error.
A more general way of validating the input is to let Python do it for you! If you try to convert a non-integer to an integer, you get a ValueError exception thrown. The second snippet of code above shows how to catch the exception and avoid having your program break.
Jeff
A more general way of validating the input is to let Python do it for you! If you try to convert a non-integer to an integer, you get a ValueError exception thrown. The second snippet of code above shows how to catch the exception and avoid having your program break.
Jeff
•
•
Join Date: Jul 2006
Posts: 562
Reputation:
Rep Power: 4
Solved Threads: 72
Here's my stab at a quick tutorial:
Validating Input
Any time your program receives input from a device, it needs to check whether the input is valid. By far, the two most common points for input are
(1) When the user types something at the keyboard, and
(2) When data is read from a file.
If your program fails to check the input for validity, then your program runs the risk of crashing, which can lead to the user being frustrated at his hard work going down the tubes and can even become an entry point for hackers (not so much in Python I think, but very true in C).
Here's an example:
How do you validate input?
First, Decide what the input should be. There are two things to consider: type and range. If your program is expecting a certain data type -- say, an integer -- then nothing else should be allowed. If the integer must be non-negative, then negatives should be verboten.
Second, at the point of input, verify that the input has the right type and range. This can happen either by using a try-except clause, or by manual checking, or both together
Two things are important features in the code above. First, the user is always given feedback if his input is invalid. This frees him from the tyranny of the blank screen. Second, when the input is invalid, the value of number is set to a default. The default value should be one that is compatible with the rest of your code.
Alternatively, if no default value is suitable, you can enclose your validation in a while loop:
Here, if the number is an integer and in range, the break statement will get the user out of the loop. Else, he will be forced to try again.
To sum up: always check input from keyboard and disk to make sure it is valid. Use try-except and conditionals to perform the checks, and use default values and while loops to recover from input errors. And always, always give the user feedback when an error occurs.
Hope it helps,
Jeff
Validating Input
Any time your program receives input from a device, it needs to check whether the input is valid. By far, the two most common points for input are
(1) When the user types something at the keyboard, and
(2) When data is read from a file.
If your program fails to check the input for validity, then your program runs the risk of crashing, which can lead to the user being frustrated at his hard work going down the tubes and can even become an entry point for hackers (not so much in Python I think, but very true in C).
Here's an example:
python Syntax (Toggle Plain Text)
(after two hours of game play ... ) What is your name? King Arthur of Camelot What is your quest? To seek the Holy Grail What is your favorite number? Three Traceback (most recent call last): File "<pyshell#0>", line 1, in -toplevel- a = int(raw_input("What is your favorite number? ")) ValueError: invalid literal for int(): Three >>> @$#@$#$#%^%
How do you validate input?
First, Decide what the input should be. There are two things to consider: type and range. If your program is expecting a certain data type -- say, an integer -- then nothing else should be allowed. If the integer must be non-negative, then negatives should be verboten.
Second, at the point of input, verify that the input has the right type and range. This can happen either by using a try-except clause, or by manual checking, or both together
python Syntax (Toggle Plain Text)
try: number = int(raw_input("Enter an integer between 0 and 8: ")) except: print "Invalid input!" number = 0 if not 0 <= number <= 8: print "Your number is out of range!" number = 0
Two things are important features in the code above. First, the user is always given feedback if his input is invalid. This frees him from the tyranny of the blank screen. Second, when the input is invalid, the value of number is set to a default. The default value should be one that is compatible with the rest of your code.
Alternatively, if no default value is suitable, you can enclose your validation in a while loop:
python Syntax (Toggle Plain Text)
while True: try: number = int(raw_input("Enter an integer between 0 and 8: ")) except: print "Invalid input!" if not 0 <= number <= 8: print "Your number is out of range!" else: break
Here, if the number is an integer and in range, the break statement will get the user out of the loop. Else, he will be forced to try again.
To sum up: always check input from keyboard and disk to make sure it is valid. Use try-except and conditionals to perform the checks, and use default values and while loops to recover from input errors. And always, always give the user feedback when an error occurs.
Hope it helps,
Jeff
Pack it into a function then you can use it again and again:
[php]def get_integer():
'''loops until integer value is entered, then returns it'''
while True:
try:
num = int(raw_input("Enter integer number: "))
return num
except ValueError:
print "Please, enter integer number!"
# get integer value from the user
val = get_integer()
print val
[/php]
[php]def get_integer():
'''loops until integer value is entered, then returns it'''
while True:
try:
num = int(raw_input("Enter integer number: "))
return num
except ValueError:
print "Please, enter integer number!"
# get integer value from the user
val = get_integer()
print val
[/php]
![]() |
•
•
•
•
Currently Active Users Viewing This Thread: 1 (0 members and 1 guests)
•
•
•
•
•
•
•
•
DaniWeb Python Marketplace
- code error (ColdFusion)
- Exception handling statement. (JavaScript / DHTML / AJAX)
- purpose of exception handling 'finally' clause (Java)
- Arithmetic Exceptions and exception-handling statements (Java)
Other Threads in the Python Forum
- Previous Thread: Help Please!
- Next Thread: Setting directory for opening files


Linear Mode