尝试根据用户输入从列表列表中返回相关信息

时间:2018-06-12 00:41:48

标签: python python-3.x

我是Python的新手,我还不能掌握功能。我有一份列表,其中包含3种产品,其库存和价格。

products = [['milk', 'eggs','bread'], [10,15,20], [3.50, 2.00, 2.50]]

我想创建一个功能,以便用户输入可以选择他们想要了解哪些产品的信息,以及他们是否需要库存编号,价格或两者。

def return_information():

这需要大量的嵌套if语句,还是我以这种方式过度思考? 我的用户输入语句是应该在第一个函数中发生还是属于我执行整个程序的主函数?

1 个答案:

答案 0 :(得分:0)

试试这个:

products = [['milk', 'eggs','bread'], [10,15,20], [3.5, 2.00, 2.5]]
total_number_items = sum(products[1])
min_num = min(products[1])
max_num = max(products[1])
average_price = sum(products[2]) / len(products[2])


def generate_overall_stats():
    return total_number_items
    return max_num
    return min_num


def return_information():  
    inquiry = input('Which product would you like information about?')
    if inquiry in products[0]:
        inquiry_2 = input('Would you like quantity, price, or both?')
        if inquiry_2 == 'both':
            print([i[products[0].index(inquiry)] for i in products[1:]])
        if inquiry_2 == 'price':
            print([i[products[0].index(inquiry)] for i in products[1]])
        if inquiry_2 == 'quantity':
            print([i[products[0].index(inquiry)] for i in products[2]])
        if inquiry_2 not in ['both','price','quantity']:
            print('Info does not exist')
    else:
        print('product does not exist')



def main():
    run = True
    while run:
        print('1.Generate overall statistics')
        print('''2.Retrieve information (quantity or price) for a given 
product')''')
        UserOp = int(input('Select an operation by entering its number: '))
        if UserOp == 1:
            print(generate_overall_stats())
        if UserOp == 2: 
            return_information()    
        runCheck = input('Do you want to run another operation? ')
        if runCheck.lower() == 'no':
            run = False
            print('Goodbye')
main()