我必须使用追加方法从用户那里获取信息,但是我只想从用户那里获取 10 行,而不是询问他们是否有另一组信息要输入。谁能告诉我如何停止 list_append 而不要求用户停止它?
以下是我的Python代码。
#set limit
num_grades = 10
def main():
#making of the list
grades = [0] * num_grades
#hold the index
index = 0
#ask the user for the info
print('Please enter the final grades for 10 students: ')
#put the info into the list with a loop
while index < num_grades:
grade = input('Enter a grade: ')
grades.append(grade)
main()
最佳答案
您给定的代码只缺少一件事:您忘记在每次循环时增加索引。
使用 for 循环可以更好地做到这一点:
for index in range(num_grades):
grade = input('Enter a grade: ')
grades.append(grade)
关于Python 追加列表并停止它,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43262179/