而循环计数器不会停止

时间:2017-05-23 15:24:17

标签: python while-loop counter python-2.x

def individual_question_scores_pretest():
    question_number = 1
    for name in students:
    print("Now we will input the scores for %s: " % name) 

    while question_number <= number_of_questions:
       questionScore = float(raw_input("Score for question # %d: " % 
           question_number))
       question_scores_preTest[name] = questionScore
       question_number = question_number + 1
    return question_scores_pretest

我试图让这个while循环遍历由number_of_questions定义的一组有限的问题编号。目前number_of_questions设置为10.所以我想输入问题#1,问题#2等的分数一直到10但是,它一直输入11,12,13,14 ...作为无限环。我的缩进是错误的还是我对流程的命令? 谢谢!

1 个答案:

答案 0 :(得分:1)

由于您正在递增价值,&#34;无限循环&#34;只会发生:

  • 如果number_of_questions非常高
  • 如果您正在使用python 2,并且number_of_questions通过raw_input 将其转换为intraw_input返回一个字符串,无论价值是多少)

demo(python 2):

>>> 12 < "10"
True

请注意,在python 3中,您会得到一个&#34;不可共享的类型:int()&lt; STR()&#34;相反的例外(它是最好的,这将有助于找到你的错误)

所以从你上次的评论来看,quickfix是:

number_of_questions = int(raw_input("Please input the number of questions on the assessment: "))