While 循环与用户输入和命令一起运行

While loop functioning with user input and commands

我需要制作一个程序来存储联系人(姓名和 phone 号码)。第一步是使程序 运行 除非输入是 'exit'。该程序应提供一组选项。我的问题是,当我输入一个选项时,它会再次提供选项集,我必须再次输入该选项才能 运行.

我有点理解为什么程序会那样做,所以我尝试了一段时间 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:

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

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)

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

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

那是因为 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)