[英]How can I create a list user inputs while using a loop?
我正在创建一个 function 询问用户他们想要报告多少天的睡眠,然后根据它应该询问一周中的哪一天和睡眠时间的答案。 function 必须返回包含星期几和用户报告睡眠时间的列表列表。 这是我想要从 python 获得的愿望 output 的图片。
到目前为止,我创建了一个基本代码来询问用户问题的要求,但我似乎无法适应一个 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)
,然后将结果存储在列表列表中并从 function 中返回。
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
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())
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.