Python打印具有无限用户输入的2D列表

时间:2017-02-02 23:23:26

标签: python

我正在尝试完成此代码,它会询问用户输入他们的名字是什么以及他们最喜欢的食物是什么,它会不断询问用户是否要添加更多数据。在用户输入“N”的时候,我需要使用完整的表格将所有输入打印在一起,任何人都知道如何做到这一点而不是一个接一个?

def get_string_inputs (p) :
    ''' requests the string data and returns it'''
    strData=input("Please enter {0} : ".format(p))
    return strData

def add_data_rows () :
    ''' adds data to the row array'''
    meal_details = [ ]
    #the helper function is used here
    name = get_string_inputs("your name ").capitalize()
    meal_details.append(name)
    favourite_meal = get_string_inputs("your favourite food").capitalize()
    meal_details.append(favourite_meal)
    return meal_details

def main() :
    '''runs all functions'''
    favMeal = []
    header=['Name','Favourite Meal']
    favMeal.append(header)

    meal_details = add_data_rows()
    favMeal.append(meal_details)
    for a,b in favMeal:
        print('{0:16}{1:<16}'.format(a,b))
    while True:    
        valid_option = ['Y','N']
        question = input("Would you like to add more data? (Y/N): ").upper()
        if question in valid_option:
            if question == 'Y' :
                main()
            if question == 'N' :
                ??????
        break
    else:
        print("That is not a valid choice, Please enter Y or N")
main()

1 个答案:

答案 0 :(得分:0)

你有几件事不合适,我在我改变的台词上做了笔记。 我希望这有帮助。

def get_string_inputs (p) :
    ''' requests the string data and returns it'''
    strData=input("Please enter {0} : ".format(p))
    return strData

def add_data_rows () :
    ''' adds data to the row array'''
    meal_details = [ ]
    #the helper function is used here
    name = get_string_inputs("your name ").capitalize()
    meal_details.append(name)
    favourite_meal = get_string_inputs("your favourite food").capitalize()
    meal_details.append(favourite_meal)
    return meal_details

def main() :
    '''runs all functions'''
    favMeal = []
    header=['Name','Favourite Meal']  # Add the header row
    favMeal.append(header)
    meal_details = add_data_rows()  # Now add the first row
    favMeal.append(meal_details)
    valid_option = ['Y', 'N']  # Just do this once, not every time the loop happens
    while True:  # Now add rows until they say N
        question = input("Would you like to add more data? (Y/N): ").upper()
        if question in valid_option:
            if question == 'Y' :
                favMeal.append(add_data_rows())  # Here we just call the function that adds a row, and append the results that it returns
            if question == 'N' :
                break # Break the while loop if they answer N
        else:
            print("That is not a valid choice, Please enter Y or N")
    for a,b in favMeal: # Now print everything
        print('{0:16}{1:<16}'.format(a,b))
main()