【问题标题】:While Loop Counter Does Not StopWhile 循环计数器不停止
【发布时间】:2017-05-23 15:24:17
【问题描述】:
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... 作为无限环形。我的缩进是错误的还是我的流程顺序? 谢谢!

【问题讨论】:

  • number_of_questions 在哪里定义?它是什么类型的?
  • btw question_scores_preTest 命名不一致
  • number_of_questions 在此之前定义为全局变量:
  • number_of_questions = raw_input("请输入测评题数:")
  • @George 您似乎正在将数字与字符串进行比较。我不记得这会在 Python 中导致什么,但可能没什么好处。不过我预计会出错。

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


【解决方案1】:

由于您正在增加您的价值,“无限循环”只能发生:

  • 如果number_of_questions 很高
  • 如果你使用的是 python 2,并且你得到了 number_of_questionsraw_input 没有将它转换为 intraw_input 返回一个字符串,无论值是什么)

演示(python 2):

>>> 12 < "10"
True

请注意,在 python 3 中,您会得到一个“不可排序的类型:int()

所以从你上一条评论来看,快速修复是:

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

【讨论】:

  • 谢谢!我忘记将其转换为整数 - 我在错误的地方寻找问题。再次感谢!
  • 我会修正不一致的错字:)
  • @George:不客气,如果它适合你,请接受答案 (stackoverflow.com/help/someone-answers)
猜你喜欢
  • 1970-01-01
  • 2017-10-29
  • 2015-12-30
  • 2021-08-18
  • 2012-04-28
  • 1970-01-01
  • 2019-06-25
  • 2010-09-26
  • 2013-09-11
相关资源
最近更新 更多