Python 追加列表并停止它

标签 python list append

我必须使用追加方法从用户那里获取信息,但是我只想从用户那里获取 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/

相关文章:

list - 在 Haskell 中将元素插入列表中给定的索引

python - 按最大重叠百分比和值过滤整数范围列表

python - numpy插入一个元素,保留数组维数

python - pyodbc autocommit 似乎不适用于 sybase 和 sqlalchemy

python - 将背景图像或颜色矩形设置为 GridLayout 中的小部件

java - 获取 Struts 2 中的列表映射

ios - 在 Swift 中一致地 append 值

javascript - 如何在不使用库的情况下在 JavaScript 中的另一个元素之后插入一个元素?

javascript - Flask - 我想要一种基于数据库数据显示任务流程图的方法

python - 检查多行 pandas 中标志列的有效性