【问题标题】:While loop functioning with user input and commandsWhile 循环使用用户输入和命令运行
【发布时间】:2020-02-12 08:24:56
【问题描述】:

我需要编写一个程序来存储联系人(姓名和电话号码)。第一步是让程序运行,除非输入是“退出”。该程序应提供一组选项。我的问题是,当我输入一个选项时,它会再次提供一组选项,我必须再次输入该选项才能运行。

我有点理解程序为什么会这样,所以我尝试了一段时间 True,但没有成功。

def main():
    options = input( "Select an option [add, query, list, exit]:" ) 
    while options != "exit" : 
        options = input( "Select an option [add, query, list, exit]:" )
        # Offrir un choix de commandes
        if options == "add":
            add_contact(name_to_phone)
        if options == "query":
            query_contact(name_to_phone)
        if options == "list":
            list_contacts(name_to_phone)

Select an option [add, query, list, exit]:add
Select an option [add, query, list, exit]:add
Enter the name of a new contact:

【问题讨论】:

  • 您可以在循环之前执行options = 'anything else than exit'循环之前无需询问用户。
  • 只需将第一行从您的while 块移动到块的末尾。注意你调用了一次,输入while然后再调用一次。

标签: python input while-loop exit


【解决方案1】:

这是由于您的第一个选择,请改为这样做:

def main():
    options = None
    while options != "exit" : 
        options = input( "Select an option [add, query, list, exit]:" )
        # Offrir un choix de commandes
        if options == "add":
            add_contact(name_to_phone)
        if options == "query":
            query_contact(name_to_phone)
        if options == "list":
            list_contacts(name_to_phone)

【讨论】:

  • 完美运行!谢谢你的回答!
【解决方案2】:

在进入循环之前,您不需要为 'option' 设置任何值。您可以使用无限循环(当 True 时)检查循环内“选项”的值并采取相应的措施。如果用户输入“退出”,您可以跳出循环。试试这个:

def main():
    #options = input( "Select an option [add, query, list, exit]:" ) 
    while True : 
        options = input( "Select an option [add, query, list, exit]:" )
        # Offrir un choix de commandes
        if options == "add":
            add_contact(name_to_phone)
        if options == "query":
            query_contact(name_to_phone)
        if options == "list":
            list_contacts(name_to_phone)
        if options == "exit":
            break

【讨论】:

    【解决方案3】:

    那是因为你在 while 循环中的第一行也在询问选项。

    您可以在 while 循环之前删除行 options = input( "Select an option [add, query, list, exit]:" 并在开始时设置选项 = ''。

    def main():
    options = '' 
    while options != "exit" : 
        options = input( "Select an option [add, query, list, exit]:" )
        # Offrir un choix de commandes
        if options == "add":
            add_contact(name_to_phone)
        if options == "query":
            query_contact(name_to_phone)
        if options == "list":
            list_contacts(name_to_phone)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-11-16
      • 2020-02-15
      • 1970-01-01
      • 2018-03-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-03-08
      相关资源
      最近更新 更多