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

2024-09-30 12:12:56 发布

您现在位置: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()

Tags: the用户nameadddatagetstringdef
1条回答
网友
1楼 · 发布于 2024-09-30 12:12:56

你有点不对劲,我在我改的台词上做了笔记。 我希望这有帮助。你知道吗

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()

相关问题 更多 >

    热门问题