繁体   English   中英

While 循环使用用户输入和命令运行

[英]While loop functioning with user input and commands

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

我有点理解程序为什么这样做,所以我尝试了一段时间 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 时)检查循环内“选项”的值并采取相应的措施。 如果用户输入“退出”,您可以跳出循环。 尝试这个:

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]:"并在开始时设置 option = ''。

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)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM