While 循环计数器不停止
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
我试图让这个 while 循环遍历 number_of_questions 定义的一组有限的问题编号。目前 number_of_questions 设置为 10。所以我想输入第 1 题、第 2 题等的分数,一直到 10。但是,它会一直到 11、12、13、14.. . 作为一个无限循环。我的缩进是错误的还是我对流程的顺序?
谢谢!
由于您要增加您的价值,"infinite loop" 只能发生:
- 如果
number_of_questions
非常高
- 如果您使用的是 python 2,并且您通过
raw_input
得到了 number_of_questions
而没有 将其转换为 int
(raw_input
returns 一个字符串,无论值是什么)
演示 (python 2):
>>> 12 < "10"
True
请注意,在 python 3 中你会得到一个 "unorderable types: int() < str()" 异常(这是最好的,这将有助于找到你的错误)
所以根据你最后的评论,快速修复是:
number_of_questions = int(raw_input("Please input the number of questions on the assessment: "))
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.. . 作为一个无限循环。我的缩进是错误的还是我对流程的顺序? 谢谢!
由于您要增加您的价值,"infinite loop" 只能发生:
- 如果
number_of_questions
非常高 - 如果您使用的是 python 2,并且您通过
raw_input
得到了number_of_questions
而没有 将其转换为int
(raw_input
returns 一个字符串,无论值是什么)
演示 (python 2):
>>> 12 < "10"
True
请注意,在 python 3 中你会得到一个 "unorderable types: int() < str()" 异常(这是最好的,这将有助于找到你的错误)
所以根据你最后的评论,快速修复是:
number_of_questions = int(raw_input("Please input the number of questions on the assessment: "))