如何在使用循环时创建用户输入列表?

How can I create a list user inputs while using a loop?

我正在创建一个函数,询问用户他们想要报告多少天的睡眠,然后根据答案询问星期几和睡眠时间。该函数必须 return 一个包含星期几和用户报告的睡眠小时数的列表列表。这是我想要从 python.

获得的期望输出的图片

到目前为止,我创建了一个基本代码来询问用户问题的内容,但我似乎无法适应 while 循环以根据用户想要报告的问题数量不断询问用户问题。以下是我到目前为止创建的代码。

def healthy():
    days=int(input("How many days do you want to report?:"))
    day=input("Day of the week:")
    hours=int(input("Hours Slept:"))
    print([day,hours])
healthy()

您可以遍历 range(days),然后将结果存储在列表的列表中,然后 return 从函数中存储结果。

def healthy():
    days = int(input("How many days do you want to report?:"))
    output = []
    for i in range(days):
        day = input("Day of the week:")
        hours = int(input("Hours Slept:"))
        output.append([day, hours])
    return output

输出

result = healthy()
How many days do you want to report?:2
Day of the week:Mon
Hours Slept:8
Day of the week:Tue
Hours Slept:4

print(result)
#[['Mon', 8], ['Tue', 4]]

这就是我的方法。你也不需要 while 循环,你可以使用 range(loops:int).

def healthy():
    info = []
    for i in range(int(input("How many days do you want to report?:"))):
        info.append([input("Day of the week:"),int(input("Hours Slept:"))])
    return info
print(healthy())