简体   繁体   English

如何重复获取用户的输入并跟踪它?

[英]How to repeat getting user's input and keep track of it?

I have a question about input loops and keeping track of it.我有一个关于输入循环和跟踪它的问题。

I need to make a program that will keep track of all the grades of a class.我需要制作一个程序来跟踪班级的所有成绩。 The thing is that the class size varies every semester, so there is no fixed number assigned to the number of students.问题是每个学期的班级规模都不一样,所以学生人数没有固定的数字。

The program will stop taking input when a student enters a grade of -1.当学生的成绩为 -1 时,该程序将停止输入。

while True:
    grade = int(input("Test: "))
    if grade < 0:
        break

How can I make it so that it keeps track of every single input?我怎样才能让它跟踪每一个输入?

You could use a list comp with iter and get the user to enter -1 to end the loop:您可以使用带有 iter 的列表 comp 并让用户输入 -1 以结束循环:

grades = [int(grade) for grade in iter(lambda:input("Enter grade or -1 to exit: "), "-1")]

iter takes a sentinel that will break the loop when entered, so as soon as the user enters -1 the loop will end. iter需要一个哨兵,当输入时会中断循环,所以一旦用户输入 -1,循环就会结束。

When taking input and casting you should really use a try/except to validate what the users inputs:在接受输入和强制转换时,您应该真正使用 try/except 来验证用户输入的内容:

grades = []
while True:
    try:
        grade = int(input(""Enter grade or -1 to exit: ""))
    except ValueError:
        # user entered bad input 
        # so print message and ask again
        print("Not a valid grade")
        continue
    if grade == -1:
        break
    grades.append(grade) # input was valid and not -1 so append it
grades = [] # initialize an empty list
while True:
    grade = int(input("Test: "))
    if grade < 0:
        break
    else:
        grades.append(grade) # add valid values to the list

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM