代码之家  ›  专栏  ›  技术社区  ›  Sonia Acosta

如何在python for while循环中获取下一个用户输入?[副本]

  •  0
  • Sonia Acosta  · 技术社区  · 1 年前

    我目前在学校参加这个实验室的python课程,它要求我创建一个循环,将用户输入输出到一个句子中,直到用户输入quit

    例如:如果输入为:

    apples 5
    shoes 2
    quit 0
    

    输出为:

    Eating 5 apples a day keeps the doctor away.
    Eating 2 shoes a day keeps the doctor away.
    

    我的代码是:

    your_input = input() #input string and int 
    string_value = your_input.split()
    str_value = string_value[0]
    int_value = string_value[1]
    
    while 'quit' not in your_input:
        print("Eating {} {} a day keeps the doctor away.".format(int_value,str_value))
        your_input = input()
        break
    

    输出:

    Eating 5 apples a day keeps the doctor away.
    

    何时应该:

    每天吃5个苹果可以远离医生。
    每天吃两双鞋可以远离医生。
    

    使用输入:

    苹果5
    鞋2
    退出0
    
    1 回复  |  直到 1 年前
        1
  •  1
  •   Rishabh_KT    1 年前

    试试这样的东西,

    your_input = input() #input string and int 
    string_value = your_input.split() 
    str_value = string_value[0] 
    int_value = string_value[1]
    
    while 'quit' not in your_input:
        print("Eating {} {} a day keeps the doctor away.".format(int_value,str_value))
        your_input = input()
        string_value = your_input.split() 
        str_value = string_value[0] 
        int_value = string_value[1]
    

    当前代码的问题是,您不需要中断,因为while语句中已经有一个终止条件,那么您需要在循环的每次迭代中拆分输入