Сложно: Как получить то, что пользователь вводит в список для печати, чтобы не пропустить ни одного элемента? - PullRequest
0 голосов
/ 10 октября 2019

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


Вот как должен выглядеть экран вывода: (текст, набираемый в [] рядом с ==> - это то, что печатает пользователь)

  • Вводсписки, точно использующие этот формат ["блюдо"]

Lists should have at least 1 dish and not more than 10 dishes 

Lists with prices correspond exactly to lists with dishes 

Execute with new lists (n) or original lists (o)? ==> n 

List of Vietnamese dishes ==> ["water", "rice", "pancake", "steamed sticky rice"] 
List of Vietnamese dishes prices ==> [7.5, 6.75, 5.15, 8.25] 
List of Italian dishes ==> ["pizza", "meatball spaghetti", "pasta"] 
List of Italian dishes prices ==> [7.15, 6.25, 5.0] 
*** TRACE Vietnamese  ['Pho', 'Fried rice', 'Pancake', 'Steamed sticky rice'] [7.5, 6.75, 5.15, 8.25] 
*** TRACE Italian  ['Pizza', 'Meatball spaghetti', 'Pasta'] [7.15, 6.25, 5.0] 


Order a dish? y/n ==> (y) 
All the available dishes are 
============================ 
v1 ‐ Pho 
v2 ‐ Fried rice 
v3 ‐ Pancake 
v4 ‐ Steamed sticky rice 
============================ 
i1 ‐ Pizza 
i2 ‐ Meatball spaghetti 
i3 ‐ Pasta 
============================ 

отображает это:

==================================
v1  - cat

==================================

i1  - cadt
v2  - doh

==================================

i2  - dosh
v3  - dfd

==================================

, когда я использую следующий код

if (1 < a < 10 and 1 < b <10):
        for i in range(1,a+1) and range(1,b+1):
            print("v"+str(i)," -", vietnamese_dishes[i-1])
            print("\n==================================\n")
            print("i"+str(i)," -", italian_dishes[i-1])
        print("\n\nPlease choose another dish by indicating the code that we provide")
        print("\nYou may order the same dish as before, if you want")
        print("\nIf you do not choose an existing dish we will choose one for you")
        return

Ответы [ 3 ]

0 голосов
/ 10 октября 2019
# enter vietnames names dishes names here
vietnamese_dishes  = [input('enter the dish name: ') for i in range(int(input('how many dishes you want to put in vietnamese_dishes: ')))]

# enter the prices for corresponding vietnames dishes here 
vietnamese_dish_prices  = [int(input('enter the price for '+dish+ ': '))  for dish in vietnamese_dishes]

print(vietnamese_dishes)
print(vietnamese_dish_prices)

vietnames = [vietnamese_dishes, vietnamese_dish_prices]
print(vietnames)

этот код может помочь решить вашу проблему, сначала попробуйте попробовать запустить его в новом файле python

enter image description here

0 голосов
/ 10 октября 2019
def user_input(user_list):
    print("Enter the dish that you want to order")
    user_value = input()
    user_list.append(user_value)
    print(user_list)
    print("Do u want to add more dishes: ")
    answer = input()
    if answer == "Yes":
        user_input(user_list)
        return user_list
    else:
        return user_list
#### Start
codes_setup()
dish_codeslist()
user_list=[]
modified_list = user_input(user_list)
print("The modified new list is :")
print(modified_list)

Добавьте этот фрагмент кода в свой код и попробуйте запустить его, чтобы увидеть, соответствует ли он вашим требованиям. Обработка пользовательских вводов, независимо от того, вводят ли они блюдо из какой-либо категории, добавляется в новый список в этом фрагменте кода.

0 голосов
/ 10 октября 2019

Измените второй оператор if в dish_codeslist на этот:

if (1 < a < 10):
        for i in range(1,a+1):
            print("v"+str(i)," -", vietnamese_dishes[i-1])
        print("\n\nPlease choose another dish by indicating the code that we provide")
        print("\nYou may order the same dish as before, if you want")
        print("\nIf you do not choose an existing dish we will choose one for you")
        return

РЕДАКТИРОВАТЬ:

    if (1 < a < 10):
        for i in range(1,a+1):
            print("v"+str(i)," -", vietnamese_dishes[i-1])
    print("\n==================================")
    if (1 < b < 10):
        for i in range(1,b+1):
            print("i"+str(i)," -", italian_dishes[i-1])
        print("\n\nPlease choose another dish by indicating the code that we provide")
        print("\nYou may order the same dish as before, if you want")
        print("\nIf you do not choose an existing dish we will choose one for you")

РЕДАКТИРОВАТЬ 2:

if (1 < a < 10 and 1 < b <10):
        for i in range(1,a+1):
            print("v"+str(i)," -", vietnamese_dishes[i-1])
        print("\n==================================\n")
        for i in range(1,b+1):
            print("i"+str(i)," -", italian_dishes[i-1])
        print("\n==================================\n")
        print("\n\nPlease choose another dish by indicating the code that we provide")
        print("\nYou may order the same dish as before, if you want")
        print("\nIf you do not choose an existing dish we will choose one for you")
        return

РЕДАКТИРОВАТЬ3:

def dish_codeslist():
    a = len(vietnamese_dishes)
    b = len(italian_dishes)
    dish_dict = {}
    print("\n\nAll the available dishes are")
    print("\n==================================")
    if (a == 1):
        print("v"+str(a)," -", vietnamese_dishes[0])
        print("\n\nPlease choose another dish by indicating the code that we provide")
        print("\nYou may order the same dish as before, if you want")
        print("\nIf you do not choose an existing dish we will choose one for you")
        return
    if (1 < a < 10 and 1 < b <10):
        for i in range(1,a+1):
            print("v"+str(i)," -", vietnamese_dishes[i-1])
            dish_dict["v"+str(i)] = (vietnamese_dishes[i-1],vietnamese_dish_prices[i-1])
        print("\n==================================\n")
        for i in range(1,b+1):
            print("i"+str(i)," -", italian_dishes[i-1])
            dish_dict["i"+str(i)] = (italian_dishes[i-1],italian_dish_prices[i-1])
        print("\n==================================\n")
        return dish_dict
def choose_dish(dish_dict):
    print("\n\nPlease choose another dish by indicating the code that we provide")
    print("\nYou may order the same dish as before, if you want")
    print("\nIf you do not choose an existing dish we will choose one for you")
    choice = input("Provide the dish code here (MUST BE a letter and a number) ==> ")
    if choice in dish_dict.keys():
        print(f"*** TRACE: dish {dish_dict[choice][0]} price {dish_dict[choice][1]} ")
    else:
        print("You did not enter a valid choice, we will suggest a dish for you")
        import random
        dish = random.choice([*dish_dict.values()])
        print("*** TRACE: dish {dish[0]} price {dish[1]} ")
#### Start
codes_setup()
dish_dict = dish_codeslist()
choose_dish(dish_dict)
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...