【问题标题】:How do you let user pick the range for for loop?你如何让用户选择for循环的范围?
【发布时间】:2017-11-12 18:23:52
【问题描述】:

我必须制作这个程序:

编写一个程序,允许教师输入他/她的班级中有多少学生,然后允许他们使用 for 循环输入班级中每个学生的姓名和标记。请注意,您不需要记录所有名称以供以后使用,这超出了课程的范围 * 所以只需询问他们每个名称,让它将名称彼此重叠保存在一个名称变量中。

即)

循环内部

name = input (“Please enter student name: “)

计算整个班级的平均分——这需要您使用总计。 在程序结束时输出班级平均分,并询问他们是否愿意为其他班级输入分数。如果他们说是,则重新循环程序,如果不是,则将程序停在那里。

于是我开始编写程序,它看起来像这样

studentamount = int(input("Please enter how many students are in your class: "))

for count in range():

    name = input ("Please enter student name: ")
    mark = int(input("Please enter the student's mark"))

我遇到了以下问题:如何让 for 循环下的代码集为每个学生循环?我在想我可以只输入 studentamount 变量作为范围,但我不能,因为 python 不允许你输入变量作为范围。

如何让 for 循环循环显示输入的学生数量?例如如果输入了 20 个学生的学生数量,我希望 for 循环循环 20 次。非常感谢您的帮助和知识。

【问题讨论】:

标签: python loops for-loop


【解决方案1】:

读取用户输入,将其转换为int,并将其作为参数传递给range:

studentamount = input("Please enter how many students ...: ")  # this is a str
studentamount = int(studentamount)  # cast to int ...

for count in range(studentamount):  # ... because that's what range expects
    # ...

【讨论】:

    【解决方案2】:

    Python 不允许您将变量作为范围输入。

    Python 确实 允许您将变量作为范围输入,但它们必须是数字。 Input () 将输入读取为字符串,因此您需要对其进行强制转换。

    所以,这是正确的:

    ```Python studentamount = int(input("请输入您的班级有多少学生:"))

    对于范围内的计数(学生数量):

    name = input ("Please enter student name: ")
    mark = int(input("Please enter the student's mark)
    

    ```

    P.S 一个 try - except 子句在这里可以用来捕获在 [TypeError] 中输入非整数数据的人

    P.S.P.S @schwobaseggl 的例子也很好,使用嵌套函数 studentamount = int(input("Text") 可能比 studentamount = input("Text") studentamount = int(studentamount)

    【讨论】:

      【解决方案3】:

      您可以将每个学生的姓名和标记存储在字典或元组中,并将每个字典(或元组)存储到列表中,参见代码示例(最后输入“no”退出或任何其他值重新循环程序):

      response = None
      while response != 'no':
      
              student_count = int(input('Please enter the number of students: '))
              students = []
              mark_sum = 0
              print('There are {} student(s).'.format(student_count))
              for student_index in range(student_count):
                  student_order = student_index + 1
                  student_name = input('Please enter the name of student number {}: '.format(student_order))
                  student_mark = float(input('Please enter the mark of student number {}: '.format(student_order)))
                  students.append({'name': student_name, 'mark': student_mark})
                  mark_sum += student_mark
      
              print('The average mark for {} student(s) is: {}'.format(student_count, mark_sum / student_count))
      
              response = input('Do you want to enter marks for another class [yes][no]: ')
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-05-13
        • 2011-09-07
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多