<bdo id='BvLYW'></bdo><ul id='BvLYW'></ul>
      <tfoot id='BvLYW'></tfoot>
      <i id='BvLYW'><tr id='BvLYW'><dt id='BvLYW'><q id='BvLYW'><span id='BvLYW'><b id='BvLYW'><form id='BvLYW'><ins id='BvLYW'></ins><ul id='BvLYW'></ul><sub id='BvLYW'></sub></form><legend id='BvLYW'></legend><bdo id='BvLYW'><pre id='BvLYW'><center id='BvLYW'></center></pre></bdo></b><th id='BvLYW'></th></span></q></dt></tr></i><div id='BvLYW'><tfoot id='BvLYW'></tfoot><dl id='BvLYW'><fieldset id='BvLYW'></fieldset></dl></div>
    1. <legend id='BvLYW'><style id='BvLYW'><dir id='BvLYW'><q id='BvLYW'></q></dir></style></legend>
    2. <small id='BvLYW'></small><noframes id='BvLYW'>

    3. 要求用户输入,直到他们给出有效的响应

      Asking the user for input until they give a valid response(要求用户输入,直到他们给出有效的响应)

          <tfoot id='nHpv3'></tfoot>
          <legend id='nHpv3'><style id='nHpv3'><dir id='nHpv3'><q id='nHpv3'></q></dir></style></legend>
          • <bdo id='nHpv3'></bdo><ul id='nHpv3'></ul>
            <i id='nHpv3'><tr id='nHpv3'><dt id='nHpv3'><q id='nHpv3'><span id='nHpv3'><b id='nHpv3'><form id='nHpv3'><ins id='nHpv3'></ins><ul id='nHpv3'></ul><sub id='nHpv3'></sub></form><legend id='nHpv3'></legend><bdo id='nHpv3'><pre id='nHpv3'><center id='nHpv3'></center></pre></bdo></b><th id='nHpv3'></th></span></q></dt></tr></i><div id='nHpv3'><tfoot id='nHpv3'></tfoot><dl id='nHpv3'><fieldset id='nHpv3'></fieldset></dl></div>

                <small id='nHpv3'></small><noframes id='nHpv3'>

                  <tbody id='nHpv3'></tbody>

                本文介绍了要求用户输入,直到他们给出有效的响应的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

                问题描述

                I am writing a program that accepts an input from the user.

                #note: Python 2.7 users should use `raw_input`, the equivalent of 3.X's `input`
                age = int(input("Please enter your age: "))
                if age >= 18: 
                    print("You are able to vote in the United States!")
                else:
                    print("You are not able to vote in the United States.")
                

                The program works as expected as long as the the user enters meaningful data.

                C:PythonProjects> canyouvote.py
                Please enter your age: 23
                You are able to vote in the United States!
                

                But it fails if the user enters invalid data:

                C:PythonProjects> canyouvote.py
                Please enter your age: dickety six
                Traceback (most recent call last):
                  File "canyouvote.py", line 1, in <module>
                    age = int(input("Please enter your age: "))
                ValueError: invalid literal for int() with base 10: 'dickety six'
                

                Instead of crashing, I would like the program to ask for the input again. Like this:

                C:PythonProjects> canyouvote.py
                Please enter your age: dickety six
                Sorry, I didn't understand that.
                Please enter your age: 26
                You are able to vote in the United States!
                

                How can I make the program ask for valid inputs instead of crashing when non-sensical data is entered?

                How can I reject values like -1, which is a valid int, but nonsensical in this context?

                解决方案

                The simplest way to accomplish this is to put the input method in a while loop. Use continue when you get bad input, and break out of the loop when you're satisfied.

                When Your Input Might Raise an Exception

                Use try and except to detect when the user enters data that can't be parsed.

                while True:
                    try:
                        # Note: Python 2.x users should use raw_input, the equivalent of 3.x's input
                        age = int(input("Please enter your age: "))
                    except ValueError:
                        print("Sorry, I didn't understand that.")
                        #better try again... Return to the start of the loop
                        continue
                    else:
                        #age was successfully parsed!
                        #we're ready to exit the loop.
                        break
                if age >= 18: 
                    print("You are able to vote in the United States!")
                else:
                    print("You are not able to vote in the United States.")
                

                Implementing Your Own Validation Rules

                If you want to reject values that Python can successfully parse, you can add your own validation logic.

                while True:
                    data = input("Please enter a loud message (must be all caps): ")
                    if not data.isupper():
                        print("Sorry, your response was not loud enough.")
                        continue
                    else:
                        #we're happy with the value given.
                        #we're ready to exit the loop.
                        break
                
                while True:
                    data = input("Pick an answer from A to D:")
                    if data.lower() not in ('a', 'b', 'c', 'd'):
                        print("Not an appropriate choice.")
                    else:
                        break
                

                Combining Exception Handling and Custom Validation

                Both of the above techniques can be combined into one loop.

                while True:
                    try:
                        age = int(input("Please enter your age: "))
                    except ValueError:
                        print("Sorry, I didn't understand that.")
                        continue
                
                    if age < 0:
                        print("Sorry, your response must not be negative.")
                        continue
                    else:
                        #age was successfully parsed, and we're happy with its value.
                        #we're ready to exit the loop.
                        break
                if age >= 18: 
                    print("You are able to vote in the United States!")
                else:
                    print("You are not able to vote in the United States.")
                

                Encapsulating it All in a Function

                If you need to ask your user for a lot of different values, it might be useful to put this code in a function, so you don't have to retype it every time.

                def get_non_negative_int(prompt):
                    while True:
                        try:
                            value = int(input(prompt))
                        except ValueError:
                            print("Sorry, I didn't understand that.")
                            continue
                
                        if value < 0:
                            print("Sorry, your response must not be negative.")
                            continue
                        else:
                            break
                    return value
                
                age = get_non_negative_int("Please enter your age: ")
                kids = get_non_negative_int("Please enter the number of children you have: ")
                salary = get_non_negative_int("Please enter your yearly earnings, in dollars: ")
                

                Putting It All Together

                You can extend this idea to make a very generic input function:

                def sanitised_input(prompt, type_=None, min_=None, max_=None, range_=None):
                    if min_ is not None and max_ is not None and max_ < min_:
                        raise ValueError("min_ must be less than or equal to max_.")
                    while True:
                        ui = input(prompt)
                        if type_ is not None:
                            try:
                                ui = type_(ui)
                            except ValueError:
                                print("Input type must be {0}.".format(type_.__name__))
                                continue
                        if max_ is not None and ui > max_:
                            print("Input must be less than or equal to {0}.".format(max_))
                        elif min_ is not None and ui < min_:
                            print("Input must be greater than or equal to {0}.".format(min_))
                        elif range_ is not None and ui not in range_:
                            if isinstance(range_, range):
                                template = "Input must be between {0.start} and {0.stop}."
                                print(template.format(range_))
                            else:
                                template = "Input must be {0}."
                                if len(range_) == 1:
                                    print(template.format(*range_))
                                else:
                                    expected = " or ".join((
                                        ", ".join(str(x) for x in range_[:-1]),
                                        str(range_[-1])
                                    ))
                                    print(template.format(expected))
                        else:
                            return ui
                

                With usage such as:

                age = sanitised_input("Enter your age: ", int, 1, 101)
                answer = sanitised_input("Enter your answer: ", str.lower, range_=('a', 'b', 'c', 'd'))
                

                Common Pitfalls, and Why you Should Avoid Them

                The Redundant Use of Redundant input Statements

                This method works but is generally considered poor style:

                data = input("Please enter a loud message (must be all caps): ")
                while not data.isupper():
                    print("Sorry, your response was not loud enough.")
                    data = input("Please enter a loud message (must be all caps): ")
                

                It might look attractive initially because it's shorter than the while True method, but it violates the Don't Repeat Yourself principle of software development. This increases the likelihood of bugs in your system. What if you want to backport to 2.7 by changing input to raw_input, but accidentally change only the first input above? It's a SyntaxError just waiting to happen.

                Recursion Will Blow Your Stack

                If you've just learned about recursion, you might be tempted to use it in get_non_negative_int so you can dispose of the while loop.

                def get_non_negative_int(prompt):
                    try:
                        value = int(input(prompt))
                    except ValueError:
                        print("Sorry, I didn't understand that.")
                        return get_non_negative_int(prompt)
                
                    if value < 0:
                        print("Sorry, your response must not be negative.")
                        return get_non_negative_int(prompt)
                    else:
                        return value
                

                This appears to work fine most of the time, but if the user enters invalid data enough times, the script will terminate with a RuntimeError: maximum recursion depth exceeded. You may think "no fool would make 1000 mistakes in a row", but you're underestimating the ingenuity of fools!

                这篇关于要求用户输入,直到他们给出有效的响应的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

                本站部分内容来源互联网,如果有图片或者内容侵犯了您的权益,请联系我们,我们会在确认后第一时间进行删除!

                相关文档推荐

                Split a Pandas column of lists into multiple columns(将 Pandas 的列表列拆分为多列)
                How does the @property decorator work in Python?(@property 装饰器在 Python 中是如何工作的?)
                What is the difference between old style and new style classes in Python?(Python中的旧样式类和新样式类有什么区别?)
                How to break out of multiple loops?(如何打破多个循环?)
                How to put the legend out of the plot(如何将传说从情节中剔除)
                Why is the output of my function printing out quot;Nonequot;?(为什么我的函数输出打印出“无?)
                • <bdo id='YjlRa'></bdo><ul id='YjlRa'></ul>
                    <legend id='YjlRa'><style id='YjlRa'><dir id='YjlRa'><q id='YjlRa'></q></dir></style></legend>

                      <tbody id='YjlRa'></tbody>

                    <small id='YjlRa'></small><noframes id='YjlRa'>

                    • <tfoot id='YjlRa'></tfoot>

                          <i id='YjlRa'><tr id='YjlRa'><dt id='YjlRa'><q id='YjlRa'><span id='YjlRa'><b id='YjlRa'><form id='YjlRa'><ins id='YjlRa'></ins><ul id='YjlRa'></ul><sub id='YjlRa'></sub></form><legend id='YjlRa'></legend><bdo id='YjlRa'><pre id='YjlRa'><center id='YjlRa'></center></pre></bdo></b><th id='YjlRa'></th></span></q></dt></tr></i><div id='YjlRa'><tfoot id='YjlRa'></tfoot><dl id='YjlRa'><fieldset id='YjlRa'></fieldset></dl></div>