Как «перезапустить» цикл, чтобы оба списка Python были полными до завершения программы? - PullRequest
0 голосов
/ 12 ноября 2018

Я пытаюсь создать программу, в которой пользователь вносит 3 фрукта и 3 фрукта в два разных списка.

Пользователь сначала выбирает первый список, печатая "фрукты" или "не фрукты". Затем пользователь вводит каждый соответствующий элемент до тех пор, пока не заполнится первый список.

Моя проблема в том, что, как только первый выбранный список заполнен, программа завершается. Я хочу, чтобы пользователю предлагалось ввести данные в другой список, пока он также не будет заполнен.

Я думал, что добавление «while len (фрукты) <3 и len (notfruits) <3:» сработает, но, похоже, это не имеет значения. </p>

Как я могу это сделать?

fruits = []
notfruits = []
print(fruits)
print(notfruits)
print("Please enter fruits or notfruits:")
y = str(input(": "))
while len(fruits) < 3 and len(notfruits) < 3:
    if y == "fruits":
        while len(fruits) < 3:
            x = str(input(": "))
            x = x.strip()
            if x in notfruits:
                print(x + " is not a fruit!")
            elif x in fruits:
                print(x + " is already in the list!")
            else:
                fruits.append(x)
                print(fruits)
    elif y == "notfruits":
         while len(notfruits) < 3:
            x = str(input(": "))
            x = x.strip()
            if x in fruits:
                print(x + " is a fruit!")
            elif x in notfruits:
                print(x + " is already in the list!")
            else:
                notfruits.append(x)
                print(notfruits)
    else:
        print("Not a valid option!")

1 Ответ

0 голосов
/ 12 ноября 2018
  1. Попробуйте использовать or вместо and
  2. Переместите входную часть внутри цикла, иначе y никогда не изменится

Вот что я имею в виду:

fruits = []
notfruits = []
print(fruits)
print(notfruits)

while len(fruits) < 3 or len(notfruits) < 3:   # replaced `and` with `or`
    print("Please enter fruits or notfruits:") #
    y = str(input(": "))                       # moved the input here
    if y == "fruits":
        while len(fruits) < 3:
            x = str(input(": "))
            x = x.strip()
            if x in notfruits:
                print(x + " is not a fruit!")
            elif x in fruits:
                print(x + " is already in the list!")
            else:
                fruits.append(x)
                print(fruits)
    elif y == "notfruits":
         while len(notfruits) < 3:
            x = str(input(": "))
            x = x.strip()
            if x in fruits:
                print(x + " is a fruit!")
            elif x in notfruits:
                print(x + " is already in the list!")
            else:
                notfruits.append(x)
                print(notfruits)
    else:
        print("Not a valid option!")
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...