尝试将变量附加到while循环中列表而不附加结束while循环的变量

时间:2016-02-23 03:52:58

标签: python python-3.x

我遇到了问题。代码有效,但我希望它能在不附加用户最终输入的情况下工作。 不知道如何结束循环而不在末尾将不正确的变量放在列表中。     测验= []

#Create variable to start the counter in the while loop
QuizNumber = 1

#Create variable to start while loop
QuizValue = 0

#Create while loop that ends if the user types anything outside of 0 and 15
while int(QuizValue) >= 0 and int(QuizValue) <= 15:

    #Get user input for quiz values
    QuizValue = input("Quiz " +str(QuizNumber) + ":")



    #Make if statement to end while loop if user types anything not integer
    if int(QuizValue) >= 0 or int(QuizValue) <= 15:
        QuizValue = QuizValue

        #Append to list
        Quizzes.append(QuizValue)

    else:
        QuizValue = 999


    #Counter for quiz number
    QuizNumber = QuizNumber + 1

4 个答案:

答案 0 :(得分:0)

循环后尝试Quizzes = Quizzes[:-1]

这会拼接列表并为您提供一个新列表,其中包含除最后一项之外的所有项

答案 1 :(得分:0)

常见的Python习惯用法是使用while 1:开始“无限”循环,但是当满足某个条件时,在循环中间有一个break语句。这取代了在其他语言中找到的do ... until表单。所以:

while 1:  # an "infinite" loop
    QuizValue = input("Quiz " +str(QuizNumber) + ":")
    # Do something if QuizValue is between 0 and 15
    if 0 <= int(QuizValue) <= 15:
        Quizzes.append(QuizValue)
    else:
        break

顺便说一下,在你的代码中,这个:

if int(QuizValue) >= 0 or int(QuizValue) <= 15:

......永远都是真的。每个数字都大于零或小于15。

答案 2 :(得分:0)

弹出

您可以使用pop删除最后一项:

QuizNumber = 1
QuizValue = 0
while 0 <= int(QuizValue) <= 15:
    QuizValue = input("Quiz " +str(QuizNumber) + ":")
    Quizzes.append(QuizValue)
    QuizNumber = QuizNumber + 1
Quizzes.pop()

这样你根本不需要if声明。

另请注意,我将0 <= x and x <= 15条件重写为0 <= x <= 15,这与Python中的内容相同。

无限循环

如果您想要if语句,则可以使用while True无限循环,然后使用break。这样您就不需要两次编写相同的条件检查:

QuizNumber = 1
QuizValue = 0
while True:
    QuizValue = input("Quiz " +str(QuizNumber) + ":")
    if not (0 <= int(QuizValue) <= 15):
        break
    Quizzes.append(QuizValue)
    QuizNumber = QuizNumber + 1

再次注意x < 0 or x > 15not (0 <= x <= 15)

相同

一些不相关的代码建议

您可能想尝试在字符串上使用format方法而不是使用字符串连接。这将允许您转向:

    quiz_value = input("Quiz " +str(quiz_number) + ":")

分为:

    quiz_value = input("Quiz {n}:".format(n=quiz_number))

您也可能希望在变量名中使用underscore_case而不是CamelCase(下划线的情况在Python中更为惯用)。

quiz_number = 1
quiz_value = 0
while 0 <= int(quiz_value) <= 15:
    quiz_value = input("Quiz {n}:".format(n=quiz_number))
    quizzes.append(quiz_value)
    quiz_number = quiz_number + 1
quizzes.pop()

答案 3 :(得分:0)

在处理来自用户的意外输入时,始终使用try,except子句。 以下代码使用布尔标志来断开while循环并避免其他条件。

QuizNumber = 1
QuizValue = 0
Quizzes = []
flag = True

while flag:
    try:
        QuizValue = input("Quiz " +str(QuizNumber) + ":")
        flag = False
        if str(QuizValue).isdigit():
            if int(QuizValue) >= 0 and int(QuizValue) <= 15:
                Quizzes.append(QuizValue)
                QuizNumber = QuizNumber + 1
                flag = True
    except Exception as e:
        flag = False