Python:如何不断重复程序直到获得特定输入?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20337489/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 20:14:19  来源:igfitidea点击:

Python: How to keep repeating a program until a specific input is obtained?

pythonloopsfor-loopwhile-loop

提问by user3033494

I have a function that evaluates input, and I need to keep asking for their input and evaluating it until they enter a blank line. How can I set that up?

我有一个评估输入的函数,我需要不断询问他们的输入并评估它,直到他们输入一个空行。我该如何设置?

while input != '':
    evaluate input

I thought of using something like that, but it didn't exactly work. Any help?

我想使用类似的东西,但它并没有完全奏效。有什么帮助吗?

采纳答案by user3033494

There are two ways to do this. First is like this:

有两种方法可以做到这一点。首先是这样的:

while True:             # Loop continuously
    inp = raw_input()   # Get the input
    if inp == "":       # If it is a blank line...
        break           # ...break the loop

The second is like this:

第二个是这样的:

inp = raw_input()       # Get the input
while inp != "":        # Loop until it is a blank line
    inp = raw_input()   # Get the input again

Note that if you are on Python 3.x, you will need to replace raw_inputwith input.

请注意,如果您使用的是 Python 3.x,则需要替换raw_inputinput.

回答by theodox

you probably want to use a separate value that tracks if the input is valid:

您可能想要使用一个单独的值来跟踪输入是否有效:

good_input = None
while not good_input:
     user_input = raw_input("enter the right letter : ")
     if user_input in list_of_good_values: 
        good_input = user_input

回答by Shahid Ghafoor

This is a small program that will keep asking an input until required input is given.

这是一个小程序,它将不断询问输入,直到给出所需的输入。

required_number = 18

while True:
    number = input("Enter the number\n")
    if number == required_number:
        print "GOT IT"
    else:
        print ("Wrong number try again")

回答by Adriano Araujo Valumin

Easier way:

更简单的方法:

#required_number = 18

required_number=input("Insert a number: ")
while required_number != 18
    print("Oops! Something is wrong")
    required_number=input("Try again: ")
if required_number == '18'
    print("That's right!")

#continue the code