首页 > 解决方案 > Python:通过调用其中的函数退出while循环

问题描述

Python

def insert_tuple2(word_list2):                                   
    while True:                                                     
        word_tuple = input("Write the word")
        if (word_tuple,) in word_list2:
            print("The word is alredy in the list!")
            menu_tuple(word_list2)

        else:
            description_tuple = input("Write its description")
            elsetuple = (word_tuple, description_tuple)
            word_list2 = word_list2 + [elsetuple]
            menu_tuple(word_list2)

该函数的目的是询问word_tuple是否word_tuple已经在列表中声明:"The word is already in the list."应该打印并且应该要求用户在菜单功能中输入。

或者word_tupledescription_tuple应该保存在word_list2菜单中,然后用户回到菜单中,其中的选项根据用户输入(整数)调用各种功能。

  1. 对于 insert_tuple(word_list2)
  2. 对于 search_tuple(word_list2)
  3. 对于 exit_tuple(word_list2)

问题是用户被无限地询问单词和描述输入。

标签: python-3.x

解决方案


它要求input无限,因为您使用while true:

我假设您可以为用户实现一个菜单驱动程序。

所以下面的代码可以帮助你:

def insert_tuple2(word_list2):                                   
    word_tuple = input("Write the word")
    if (word_tuple,) in word_list2:
        print("The word is alredy in the list!")           
    else:
        description_tuple = input("Write its description")
        elsetuple = (word_tuple, description_tuple)
        word_list2 = word_list2 + [elsetuple]
    menu_tuple(word_list2)

推荐阅读