Input Error Checking Python
Contents |
here for a quick overview of the site Help Center Detailed answers to any questions you might have Meta Discuss the workings and policies of this site About Us Learn more about Stack Overflow the company Business Learn more about hiring developers or posting ads with python error types us Stack Overflow Questions Jobs Documentation Tags Users Badges Ask Question x Dismiss Join the Stack python exception message Overflow Community Stack Overflow is a community of 4.7 million programmers, just like you, helping each other. Join them; it only takes a minute: Sign up
Python Raise Custom Exception
Python User Input Error Handling up vote 0 down vote favorite I don't know why I never thought of this before... but I'm wondering if there's a neater/shorter/more efficient manner of error handling a user input. For example, if I ask
Syntax For Generic Except Clause In Python
the user to enter either "hello" or "goodbye", and they type something else, I need it to tell the user it's wrong and ask again. For all of coding I've ever done, this is how I've done it (typically the question is better): choice = raw_input("hello, goodbye, hey, or laters? ") while choice not in ("hello","goodbye","hey","laters"): print "You typed something wrong!" choice = raw_input("hello,goodbye,hey,or laters? ") Is there a smarter way of doing this? Or should I just stick with how I've had it? python print exception This is the method I use for all languages I've written in. Thanks, Sean python user-input share|improve this question asked Oct 16 '13 at 15:54 user2869231 434519 add a comment| 4 Answers 4 active oldest votes up vote 4 down vote accepted For a simple script, the way you have it is fine. For a more complex system, you're effectivey writing your own parser. def get_choice(choices): choice = "" while choice not in choices: choice = raw_input("Choose one of [%s]:" % ", ".join(choices)) return choice choice = get_choice(["hello", "goodbye", "hey", "laters"]) share|improve this answer edited Oct 16 '13 at 16:18 answered Oct 16 '13 at 16:04 Christian Ternus 6,6611337 I like this because it is general, and the prompt is auto generated based on the choices. My only criticism would be I would do ",".join(choices) instead of " ".join(choices). And I would also do while choice not in choices: –SethMMorton Oct 16 '13 at 16:13 Hmm. I can see creating a method being cleaner, but I feel like the only way I'd prefer it is if I passed a function to it so I could use the method for every question I asked. That would definitely be convenient, just... it might take me a little while to figure out and replace lol –user2869231 Oct 16 '13 at 16:15 As in, I have a lot of user inputs, so I'd rather not have a new method for each one –user2869231 Oct 16 '13 at 16:16
you have probably seen some. There are (at least) two distinguishable kinds of errors: syntax errors and exceptions. 8.1. Syntax
Python Try Except Else
Errors¶ Syntax errors, also known as parsing errors, are perhaps the is nested try block possible in python most common kind of complaint you get while you are still learning Python: >>> while True print name of errors in python 'Hello world' File "
and VariablesOperatorsinput and raw_input via the keyboardConditional StatementsWhile LoopsFor LoopsFormatted outputOutput with PrintSequential Data TypesDictionariesSets and Frozen SetsShallow and Deep CopyFunctionsRecursion and http://www.python-course.eu/exception_handling.php Recursive FunctionsTests, DocTests, UnitTestsMemoization with DecoratorsPassing ArgumentsNamespacesGlobal vs. Local http://www.pythonforbeginners.com/error-handling/exception-handling-in-python VariablesFile ManagementModular Programming and ModulesIntroduction in Regular ExpressionsRegular Expressions, AdvancedLambda Operator, Filter, Reduce and MapList ComprehensionGeneratorsException HandlingObject Oriented ProgrammingInheritance ExampleSlotsClasses and Class CreationRoad to MetaclassesMetaclassesMetaclass Example: Count Function Calls Exception from the Rule "There are two great in python rules of life, the one general and the other particular. The first is that everyone can in the end, get what he wants, if he only tries. That is the general rule. The particular rule is that every individual is, more or less, an exception to input error checking the rule." Samuel Butler Delicate Handling "The finest qualities of our nature, like the bloom on fruits, can be preserved only by the most delicate handling. Yet we do not treat ourselves nor one another thus tenderly." Henry David Thoreau Supported by: Python Training Courses in Canada This topic in German / Deutsche Übersetzung: AusnahmebehandlungPython 2.7This tutorial deals with Python Version 2.7This chapter from our course is available in a version for Python3: Exception HandlingClassroom Training Courses This website contains a free and extensive online tutorial by Bernd Klein. If you are interested in an instructor-led classroom training in Canada or the US, you may have a look at the Python courses by Bernd Klein at Bodenseo © kabliczech - Fotolia.com Overview of Python courses by Bernd Klein. The Truth in Errors "The first step toward
with exceptions. What is an Exception? An exception is an error that happens during execution of a program. When that error occurs, Python generate an exception that can be handled, which avoids your program to crash. Why use Exceptions? Exceptions are convenient in many ways for handling errors and special conditions in a program. When you think that you have a code which can produce an error then you can use exception handling. Raising an Exception You can raise an exception in your own program by using the raise exception statement. Raising an exception breaks current code execution and returns the exception back until it is handled. Exception Errors Below is some common exceptions errors in Python: IOError If the file cannot be opened. ImportError If python cannot find the module ValueError Raised when a built-in operation or function receives an argument that has the right type but an inappropriate value KeyboardInterrupt Raised when the user hits the interrupt key (normally Control-C or Delete) EOFError Raised when one of the built-in functions (input() or raw_input()) hits an end-of-file condition (EOF) without reading any data Exception Errors Examples Now, when we know what some of the exception errors means, let's see some examples: except IOError: print('An error occurred trying to read the file.') except ValueError: print('Non-numeric data found in the file.') except ImportError: print "NO module found" except EOFError: print('Why did you do an EOF on me?') except KeyboardInterrupt: print('You cancelled the operation.') except: print('An error occurred.') Try to use as few try blocks as possible and try to distinguish the failure conditions by the kinds of exceptions they throw. Set up exception handling blocks To use exception handling in Python, you first need to have a catch-all except clause. The words "try" and "except" are Python keywords and are used to catch exceptions. try-except [exception-name] (see above for examples) blocks The code within the try clause will be executed statement by statement. If an exception occurs, the