如何在无限循环中尝试多个输入而无需从循环开始重新启动?

时间:2017-08-09 19:56:48

标签: python loops

如果出现值错误,我希望此语句返回当前问题,而不必在第一个问题上重新开始。我需要制作3个独立的循环吗?解决这个问题的最佳方法是什么?因为如果我有100多个输入,它可能会变得混乱!

while True:
    try:
        num_of_ppl = int(input("How many people? "))
        num_of_pizza = int(input("How many pizza's? "))
        num_of_slices_per_pizza = int(input("How many slice's per pizza? "))

    except ValueError:
        print("You must enter a whole number.\n")
        continue
    break

2 个答案:

答案 0 :(得分:3)

也许有比我更多经验的人可以说为什么我的做法是错的,但我会这样做:

def take_input(msg):
  try:
    return int(input(msg))
  except:
    return take_input(msg)


pizzas = take_input("how many pizzas?")
num_of_ppl = take_input("How many people?")

当然,由于您可以继续提供无效答案,因此可能会超出递归深度。还有其他我忽视的事情吗?

答案 1 :(得分:0)

好吧,我的朋友,不必经常重写代码,完全是功能。尝试这样的事情怎么样:

protected String doInBackground(String... connUrl){
    HttpURLConnection conn = null;
    BufferedReader reader;
    StringBuilder sb;

    try{
        final URL url = new URL(connUrl[0]);
        conn = (HttpURLConnection) url.openConnection();
        conn.addRequestProperty("Content-Type", "application/json; 
charset=utf-8");
        conn.setRequestMethod("GET");
        int result = conn.getResponseCode();
        if(result == 200){

            InputStream in = new BufferedInputStream(conn.getInputStream());
            reader = new BufferedReader(new InputStreamReader(in));
            sb = new StringBuilder();
            String line = null;

            while ((line = reader.readLine()) != null){
                sb.append(line);
            }

        }

    }catch(Exception ex){

    }
    return sb.toString();
    }
    protected void onPostExecute(String result){
       super.onPostExecute(result);
       System.out.println(result);
    }

然后你只需要用instring调用那个方法作为那些问题。你甚至可以有一个清单:

def get_answer(instring):
    while True:
        try:
            ret = int(input(instring))      

        except ValueError:
            print("You must enter a whole number.\n")
            continue
        break
    return ret

然后可以使用这样的循环:

qlist = ["How many people? ", "How many pizza's? ","How many slice's per pizza? "]