George
George

Reputation: 13

While Loop Counter Does Not Stop

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

I'm trying to have this while loop go through a limited set of question numbers defined by number_of_questions. Currently number_of_questions is set to 10. So I would like to input the score for question #1, question #2 etc. all the way to 10. However, it keeps going to 11, 12, 13, 14... as an infinite loop. Is my indentation wrong or is it the order I have for the flow? Thanks!

Upvotes: 0

Views: 81

Answers (1)

Jean-Fran&#231;ois Fabre
Jean-Fran&#231;ois Fabre

Reputation: 140168

Since you're incrementing your value, "infinite loop" can only occur:

  • if number_of_questions is very high
  • if you're using python 2, and you got number_of_questions through raw_input without converting it to int (raw_input returns a string whatever the value is)

demo (python 2):

>>> 12 < "10"
True

note that in python 3 you get an "unorderable types: int() < str()" exception instead (it's for the best, that would have helped to find your error)

So from your last comment, the quickfix is:

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

Upvotes: 1

Related Questions